


3 interesting Python questions that are very suitable for newbies to practice
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!
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
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.
