Home  >  Article  >  Backend Development  >  3 interesting Python questions that are very suitable for newbies to practice

3 interesting Python questions that are very suitable for newbies to practice

little bottle
little bottleOriginal
2019-04-04 11:09:483534browse

Friends who know Python know that although Python is easy to get started, it involves a lot of knowledge and is very skillful! These skills are like chains. It takes some practice to become proficient and master the knowledge points firmly! Today, the editor has selected 3 interesting Python questions for you. Let’s move your fingers and practice together!

3 interesting Python questions that are very suitable for newbies to practice

The editor below will show you how rookies and experts deal with the problem respectively:

NO.1 Character replacement in strings

Strings are the most basic and important knowledge point in Python. The following question is about string replacement.

Create a function that can process the input string and return a string with certain characters replaced. The rules are as follows

· If a letter is an uppercase consonant, please Replace this character with "Iron".

· If a letter is a lowercase consonant or a non-alphabetic character, do nothing with the character

· If a letter is an uppercase vowel, replace the character with " Iron Yard".

· If a letter is a lowercase vowel, replace the character with "Yard".

Test case

Input: "Hello WORLD!"

Output: "IronYardllYard IronIron YardIronIronIron!"

Novice solution:

def replace_str(string):
	res = ""
	vowel = 'aeiou'
	for i in string:
		if i in vowel:
			res += 'Yard'
		elif i in vowel.upper():
			res += 'Iron Yard'
		elif i.isupper():
			res +='Iron'
		else:
			res += i
	return res

print(replace_str('Hello WORLD!'))

Master's solution:

def tiy_fizz_buzz(s):
   return "".join(("Iron "*c.isupper() + "Yard"*(c.lower() in "aeiou")).strip() or c for c in s)

Comments:

The most clever solution for experts is not to use a method like pushing to a list to loop through strings, but also to use "Iron"*True or " Iron"*False, if the former is the string itself, and the latter is empty"". Then use to synthesize the two strings, and then use or to classify! It perfectly integrates the above if-elif-elif-else into one line of code, which is really good!

NO.2 Interesting weight ranking

3 interesting Python questions that are very suitable for newbies to practice

Xiaoli is in a "weight loss club". At the end of each month, Xiaoli is very worried because every A list of members' weights is released every month, and every month she is last on the list, meaning she is the heaviest. So she suggested that the president modify the rules. For example, the new rules are as follows:

The new sorting rules will be sorted according to "weight". If the weights are the same, they will be sorted according to the weight string. (Calculation rule of weight: the sum of the numbers in different digits of the weight number)

Given the weight strings of the members of a certain normal order club, how to sort them according to the new rules? Test case: Input: "99 189 86 75" Output: "75 86 189 99"

Novice's solution:

def order_weight(string):
    weight_list = string.split(' ')
    def helper(x):
        if not x:
            return x
            y = int(x)
            z = 0
            while y:
                z += y % 10
                Y = int(y / 10)
            return (z,x)
 
    weight_list.sort.sort(key = helper)
    return " ".join(weight_list)

Master's solution:

def order_weight(_str):
    return' '.join(sortsd(_str.split(' '),key = lambda x: sum(int(c) for c in x)))

Comments:

The expert's solution is also relatively simple! Most of us use for c in x and end it at this level. In fact, we can also perform further operations on c and then sum it up. This example can draw inferences! A lot of advanced uses of sorted are gathered together at once, concisely and effectively!

3. Dice throwing game

A dice game played with five six-sided dice. Each time the dice is thrown, an array of 5 numbers will appear (numbers: 1-6). Count the number of times each number appears in the array, split the number of times each number appears into a combination of 3 times and 1 time, and then count according to the following rules. Note: If the number of occurrences is greater than or equal to 3 times, then at least one of them must be calculated as 3 times, and not all of them can be calculated as 1 time

3 times 1 = = 1000 points 3 times 6 = = 600 points

3 times 5 = = 500 points 3 times 4 = = 400 points

3 times 3 = = 300 points 3 times 2 = = 200 points

1 time 1 => 100 points 1 time 5 => 50 points

1 time 2 => 0 points 1 time 3 => 0 points

1 time 4 => 0 points 1 time 6 => 0 points

For example, if 5 appears 5 times, then it should be calculated as 3 5s, 1 5 and 1 5; if 5 appears 6 times, then it should be calculated as 3 A 5 or 3 5s are used to calculate the score, and the same applies to other numbers.

Test case:

Throw the dice and calculate the score

5 1 3 4 1 50 2 * 100 = 250

1 1 1 3 1 1000 100 = 1100

2 4 4 5 4 400 50 = 450

Rookie’s solution:

from collections import Counter
def score(dice):
    num_dict = dict(Counter(dice))
    res = 0
    for i in num_dict:
        if i == 1:
            res +=1000 * (int(num_dict[i] / 3)) + 100 * (num_dict[i] % 3)
            elif i == 5:
                res +=500 * (int(num_dict[i])) + 50 * (num_dict[i] % 3)
            else:
                res += 100 * (i * int(num_dict[i] / 3))
    return res

Master’s solution:

def score(dice):
        sum = 0 
        counter = [0,0,0,0,0,0]
        points = [1000, 200, 300, 400, 500, 600]
        extra = [100,0,0,0,50,0]
        for die in dice:
            counter[die-1] += 1
        for (i, count) in enumerate(counter):
            sum += (points[i] if count >= 3 else 0) + extra[i] * (count%3)
        return sum

Comments:

The master’s solution is that the designed data structure is very clever. Several containers are designed in advance according to the meaning of the question, and then the counter list cleverly associates (1-6) with the number of occurrences of (1-6). The points and extra lists cleverly associate the number of times a number appears (3 times and 1 time) with the score, reducing the chance of accidentally entering scores and improving code reuse. The whole solution is very clever!

The above questions seem very simple and easy to understand, but the solutions are not as concise and ingenious as others! Just like a cooking competition, a seemingly simple egg fried rice is actually a test of your skills! Programming itself contains the fusion of algorithms and data structures. If you have time, you can learn more about excellent codes, which will be of great benefit to your own learning and improvement!

[Recommended course: Python column video tutorial]


The above is the detailed content of 3 interesting Python questions that are very suitable for newbies to practice. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn