USING PYTHON IDLE 3.4: Need help with this please! PLEASE USE PYTHON IDLE 3.4! D
ID: 3807669 • Letter: U
Question
USING PYTHON IDLE 3.4:
Need help with this please! PLEASE USE PYTHON IDLE 3.4!
Define a function named q4() that accepts a string as a parameter. After verifying that the string includes only includes numeric digits, count the number of even (E) and odd (O) digits. Finally, create a new string made up of these values and their sum. Repeat this process until your end result is a string containing '123'. For example, '15327' contains 1 even digit (E = 1), 4 odd digits (O=4) and the sum of these is 5 (E+O). The new string would be "145'. Repeating the process (E = 1, O = 2, E+O = 3) gives me '123'. The function q4() should return the number of repetitions it takes to create the string 123 Example output of function q4() at the interactive Python prompt: >>> q4 ('123') 0 >>> q4 ('5') 2 >>> q4 ('471') 1 >>> q4 ('1234567890') 3 >>> q4 ('0') 2 Already '123' so takes zero repetitionsExplanation / Answer
Answer:
Here's the python script for the function:
#function which takes a number and returns the number of even digits in it
def num_even_digits(x):
return len([ y for y in str(x) if int(y) % 2 == 0])
#function which takes a number and returns the number of odd digits in it
def num_odd_digits(x):
return len([ y for y in str(x) if int(y) % 2 != 0])
def q4(number):
if number.isdigit():
int_num = int(number)
sum_str = str(int_num)
number_of_reps = 0
while sum_str != '123':
int_num = int(sum_str)
even = num_even_digits(int_num)
odd = num_odd_digits(int_num)
#sum of even and odd digits in the number
sum_e_o = even+odd
#converting the number to a string
sum_str = str(even*100 + odd*10 + sum_e_o)
number_of_reps += 1
return number_of_reps
-------------------------------------------------------------------------------------------------------------------------------------------------------------------
OUTPUT:
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.