Learn programming with Lao Ma while “leveling up and fighting monsters”!
This aims to provide comprehensive learning materials for children to prepare for the level exam together.
Add the assistant on WeChat and reply with 【GESP Level 1 2023.03_Chicken and Rabbit】 to get the source code for this problem.
GESP Level 1 2023.03_Chicken and Rabbit
Problem Description
Use the <span>input()</span>
statement to input two positive integers sequentially, representing the total number of heads and feet of chickens and rabbits. Each rabbit has four feet, and each chicken has two feet, with only one head each.
Please write Python code to calculate the number of rabbits and chickens, outputting the result in the format “Chicken=15 Rabbit=5”. If there is no solution, output “No solution!”.
Input Description
Input is done in two steps: first input the total number of heads, press enter, then input the total number of feet.
Note: In regular programs, it is good practice to have prompts during input. However, due to system limitations during the exam, all <span>input()</span>
functions cannot have prompt messages.
Output Description
If there is a solution, output the number of chickens and rabbits in the format “Chicken=15 Rabbit=5” with one space before Rabbit, and both C and R should be capitalized.
If there is no solution, output “No solution!” with one space after No and an exclamation mark after solution.
Note: Pay attention to the matching of letter cases, spaces, and exclamation marks.
Sample Input 1
20
50
Sample Output 1
Chicken=15 Rabbit=5
Sample Input 2
20
30
Sample Output 2
No solution!
Reference Program:
Note: For reference only, candidates can design their own solutions as long as the results meet the problem requirements.
Method 1:
head = int(input())
foot = int(input())
i = 0
num = 0
while i <= head:
if i * 2 + (head - i) * 4 == foot:
print("Chicken={} Rabbit={}".format(i, head - i))
num += 1
i += 1
if num == 0:
print("No solution!")
Method 2:
head = int(input())
foot = int(input())
R = (foot - 2 * head) / 2
C = head - R
if R < 0 or int(R) != R:
print('No solution!')
else:
C = int(C)
R = int(R)
print("Chicken={} Rabbit={}".format(C, R))
Youth Programming Competition Communication
The “Youth Programming Competition Communication Group” has been established (suitable for youth aged 6 to 18). Add the assistant on WeChat to invite everyone to join the learning group. After joining, everyone can participate in regularly organized 21-day problem-solving challenges, level exam assessments, guidance for Ministry of Education whitelist competitions, and youth programming team competitions.