search
HomeBackend DevelopmentPython Tutorial3 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!

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
How do you append elements to a Python list?How do you append elements to a Python list?May 04, 2025 am 12:17 AM

ToappendelementstoaPythonlist,usetheappend()methodforsingleelements,extend()formultipleelements,andinsert()forspecificpositions.1)Useappend()foraddingoneelementattheend.2)Useextend()toaddmultipleelementsefficiently.3)Useinsert()toaddanelementataspeci

How do you create a Python list? Give an example.How do you create a Python list? Give an example.May 04, 2025 am 12:16 AM

TocreateaPythonlist,usesquarebrackets[]andseparateitemswithcommas.1)Listsaredynamicandcanholdmixeddatatypes.2)Useappend(),remove(),andslicingformanipulation.3)Listcomprehensionsareefficientforcreatinglists.4)Becautiouswithlistreferences;usecopy()orsl

Discuss real-world use cases where efficient storage and processing of numerical data are critical.Discuss real-world use cases where efficient storage and processing of numerical data are critical.May 04, 2025 am 12:11 AM

In the fields of finance, scientific research, medical care and AI, it is crucial to efficiently store and process numerical data. 1) In finance, using memory mapped files and NumPy libraries can significantly improve data processing speed. 2) In the field of scientific research, HDF5 files are optimized for data storage and retrieval. 3) In medical care, database optimization technologies such as indexing and partitioning improve data query performance. 4) In AI, data sharding and distributed training accelerate model training. System performance and scalability can be significantly improved by choosing the right tools and technologies and weighing trade-offs between storage and processing speeds.

How do you create a Python array? Give an example.How do you create a Python array? Give an example.May 04, 2025 am 12:10 AM

Pythonarraysarecreatedusingthearraymodule,notbuilt-inlikelists.1)Importthearraymodule.2)Specifythetypecode,e.g.,'i'forintegers.3)Initializewithvalues.Arraysofferbettermemoryefficiencyforhomogeneousdatabutlessflexibilitythanlists.

What are some alternatives to using a shebang line to specify the Python interpreter?What are some alternatives to using a shebang line to specify the Python interpreter?May 04, 2025 am 12:07 AM

In addition to the shebang line, there are many ways to specify a Python interpreter: 1. Use python commands directly from the command line; 2. Use batch files or shell scripts; 3. Use build tools such as Make or CMake; 4. Use task runners such as Invoke. Each method has its advantages and disadvantages, and it is important to choose the method that suits the needs of the project.

How does the choice between lists and arrays impact the overall performance of a Python application dealing with large datasets?How does the choice between lists and arrays impact the overall performance of a Python application dealing with large datasets?May 03, 2025 am 12:11 AM

ForhandlinglargedatasetsinPython,useNumPyarraysforbetterperformance.1)NumPyarraysarememory-efficientandfasterfornumericaloperations.2)Avoidunnecessarytypeconversions.3)Leveragevectorizationforreducedtimecomplexity.4)Managememoryusagewithefficientdata

Explain how memory is allocated for lists versus arrays in Python.Explain how memory is allocated for lists versus arrays in Python.May 03, 2025 am 12:10 AM

InPython,listsusedynamicmemoryallocationwithover-allocation,whileNumPyarraysallocatefixedmemory.1)Listsallocatemorememorythanneededinitially,resizingwhennecessary.2)NumPyarraysallocateexactmemoryforelements,offeringpredictableusagebutlessflexibility.

How do you specify the data type of elements in a Python array?How do you specify the data type of elements in a Python array?May 03, 2025 am 12:06 AM

InPython, YouCansSpectHedatatYPeyFeLeMeReModelerErnSpAnT.1) UsenPyNeRnRump.1) UsenPyNeRp.DLOATP.PLOATM64, Formor PrecisconTrolatatypes.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.