I managed to sort of complete the first part of this question. But I have no idea on how to finish the second part. I managed to complete the input for x and y.
Exercise 1
The function takes in input a number x and a list of numbers y, and returns a value as
follows:
• If x is odd, fun_exercise_1 subtract 1 from all the elements of y and then returns
its sum.
• If x is even, fun_exercise_1 multiplies each element of y by 2 and then returns its
sum.
• If x is zero, fun_exercise_1 returns the sum of all the elements in y
def fun_exercise_1(x,y):
print ("enter value for x")
x = float (input ("x:"))
y = []
print ("Enter 4 numbers for a list. Use a negative number to finish")
yy = float(input ("Enter Number:"))
while yy >=0.0 :
y.append(yy)
yy = float(input("Next number:"))
This is one way to do it. Although it doesn't validate if the first argument is an integer or if the second argument is a list. It just expects those in order to run correctly.
def test(x, y):
if x == 0:
sum = 0
for i in y:
sum += i + sum
return sum
elif x % 2 == 0:
sum = 0
for i in y:
sum += i * 2
return sum
else:
sum = 0
for i in y:
sum += i - 1
return sum
This would be tested by passing an integer and a list as arguments when calling test().
Here is what you wanna do:
def fun_exercise_1(x, y):
if x ==0:
return sum(y)
elif x % 2 == 0:
y = [(val*2) for val in y]
return sum(y)
else:
y = [(val -1) for val in y]
return sum(y)
print(fun_exercise_1(3,[4,5,6,7]))
Output:
18
Related
Detail: User enters 3 integers as numX >= numY >= numZ. Count how many
integers between the range of numX and numZ that are divisible by
numY (while loop required).
This is a practice question from my course worksheet and here are the codes I wrote for which I can't get the correct answer.
print("Enter 3 integer numbers, where as numX ≥ numY ≥ numZ")
x = int(input("numX: "))
y = int(input("numY: "))
z = int(input("numZ: "))
oldx = x
oldy = y
oldz = z
ctr = 0
while x >= y >= z:
if x % y == 0 or z % y == 0:
ctr = ctr + 1
x = x - 1
z = z + 1
print(f"There are {ctr} numbers in {oldx}...{oldz} that are divisible by {oldy}")
Thank you in advance for any helpful tips.
You were increasing z value and decreasing x value. You shouldn't do that. If you increase z value then it will not execute between the actual range. You don't even need the old variables.
So, I think the following code snippet will work for you.
Code:
print("Enter 3 integer numbers, where as numX ≥ numY ≥ numZ")
x = int(input("numX: "))
y = int(input("numY: "))
z = int(input("numZ: "))
oldx = x
ctr = 0
while x >= y >= z:
if x % y == 0:
ctr += 1
x -= 1
print(f"There are {ctr} numbers in {oldx}...{z} that are divisible by {y}")
Output:
Enter 3 integer numbers, where as numX ≥ numY ≥ numZ
numX: 12
numY: 3
numZ: 0
There are 4 numbers in 12...0 that are divisible by 3
terms = int(input("Enter the terms: "))
x, y = 1, 2
count = 0
sum = 0.0
if terms <= 0:
print("Please enter a positive integer")
elif terms == 1:
print("Fibonacci sequence upto",terms,":")
print(x)
else:
print("Fibonacci sequence:")
while count < terms:
sum = z + x + y
print(x,end=" ")
z = x + y
x = y
y = z
count += 1
print("The sum of Fibonacci sequence:",sum)
'The error is the program cant defined the z and cant display the sum. Is that i put the sum code in wrong place?'
When you call
sum = z + x + y
you have not defined z.
Try this
x, y, z = 1, 2, 0
you are simply using z variable before even initializing it. The program doesn't know z exists and you are trying to use it to calculate sum.
first you need to initialize z and then use it to calculate sum.
You should replace "sum" with another name, try "summation"
Since you didn't defined z in first 14 lines, you can't use it in line 15. You should define z before using it.
Your sum calculation is not correct at all.
I need help for printing the largest number from the multiple outputs. How can I modify this code to do so?
x = int(input("Enter a number : "))
while(x!=1):
if(x%2==0):
x = x/2
print("\n",x)
else:
x = 3*x+1
print("\n",x)
When I typed "20" as the input, I get a list of numbers and I can easily say that 16 is the largest out of the outputs. But it is really hard when the input is big. I need a code to print out the largest number from the outputs
You could create a generator that generates the Collatz sequence and then use the max() function to find the largest number:
def collatz_sequence(x):
yield x
while x > 1:
x = x // 2 if x % 2 == 0 else 3 * x + 1
yield x
print(max(collatz_sequence(5))) # Output: 16
def multiplication_maker(m=1):
n = 1
while n < 11:
print(m,"*",n,"=",m*n)
n += 1
x = input("Enter the multiplication you want =" )
x = int(x)
multiplication_maker(x)
You could check the length by using len() then assigning 1 to it
def multiplication_maker(m=1):
n = 1
while n < 11:
print(m,"*",n,"=",m*n)
n += 1
x = input("Enter the multiplication you want =" )
if len(x) == 0:
x = 1
x = int(x)
multiplication_maker(x)
Solution
You can use the fact that an empty string is evaluated as false and set a condition
x = input("Enter the multiplication you want =")
if not x:
x = "1"
x = int(x)
multiplication_maker(x)
Smart
Using the fact that is a the left operand is false (ie empty string) then the right operand will be evaluated and returned you can do that trick
x = int(input("Enter the multiplication you want =") or "1")
multiplication_maker(x)
def multiplication_maker(m=None):
try:
m = int(m)
except:
m = 1
n = 1
while n < 11:
print(m, "*", n, "=", m * n)
n += 1
x = input("Enter the multiplication you want =")
multiplication_maker(x)
My function for finding LCM does not work. Is there a problem with the while loop?
x = int(input("Enter the first number"))
y = int(input("Enter the second number"))
def calculate_LCM(x,y):
if (x>y):
max=x
else:
max=y
while((max%x==0) and (max%y==0)):
print(max)
max=max+1
print(calculate_LCM(x,y))
Your lcm logic is wrong the condition you used in while loop is wrong.
LCM logic should be like,
def calculate_LCM(x, y):
# choose the greater number
if x > y:
greater = x
else:
greater = y
while(True):
if((greater % x == 0) and (greater % y == 0)):
lcm = greater
break
greater += 1
return lcm
x = int(input("Enter the first number"))
y = int(input("Enter the second number"))
print(calculate_LCM(x,y))
Addition to the above answers, you can find LCM of two numbers using GCD. GCD of two numbers take less time when the two numbers are Co prime.First calculate GCD in this way:
def gcd(a,b):
if b==0:
return a
else:
return gcd(b,a%b)
Then calculate LCM using this formula:
lcm = (a*b)//gcd(a,b)
The smallest change to make your code work is to put a not on the while condition - you want the loop to repeat if both remainders are not 0.
while not ((max%x==0) and (max%y==0)):
Btw, your function doesn't return a value, so it implicitly returns None which is what print() receives. Add it after the while-block:
while not (max % x == 0 and max % y == 0): # remove extra parens and add spaces, PEP8
max += 1 # same as max = max + 1
return max
Side note: since 0 is boolean-Falsey and non-zero integers and floats are boolean Truthy, that while check can be reduced to:
while max % x or max % y:
so if either value (remainders) is non-zero, the loop repeats.
Tip: max() is a Python built-in so don't use that as a variable name.