link to assignment**
This is what I have so far but I cant figure out the rest. I am having a hard time solving the rest of the problem. Like calling sum variables from other functions. If anyone could lend a hand I would appreciate it, thank you.
#hello function
def hello():
print("***************************************")
print("*** WELCOME TO THE MAGIC PROGRAM *****")
print("***************************************")
#get_highest function
def get_highest():
first_num = int(input("\nEnter first number: "))
second_num = int(input("Enter second number: "))
largest_num = 0
if first_num > 0 and second_num > 0 and first_num >= second_num:
print("\nThe largest number is: ", first_num)
first_num = largest_num
elif second_num > 0 and first_num > 0 and second_num >= first_num:
print("\nThe largest number is:", second_num)
second_num = largest_num
else:
print("\nERROR: Both numbers must be greater than 0!")
print("Try again.")
get_highest()
return largest_num
#odd_or_even function
def odd_or_even(largest_num):
largest_num = get_highest()
if (largest_num % 2 == 0):
print(largest_num, " is an EVEN NUMBER!!")
else:
print(largest_num, " is an ODD NUMBER!!")
#print_magic function
def print_magic(largest_num):
largest_num = get_highest()
total = 0
for x in range(1, largest_num):
total = total + x
hello()
get_highest()
odd_or_even()
Related
The counters in functions "getWeight" and "getPrice" do not go up as I planned. It always reverts back to the original integer, which applies to whatever value you input in the console. How can I fix this error?
import math
class ShippingCharges:
def __init__(self, userInput=None, packNum= None, packPrice = None):
self.userInput = userInput
self.packNum = packNum
self.packPrice = packPrice
def getPrice (self):
if (self.userInput <= 2):
print("Package", self.packNum," will cost $1.10 per pound\n")
elif(6 >= self.userInput and 2 < self.userInput):
print("Package", self.packNum, " will cost $2.20 per pound\n")
elif(10 >= self.userInput and 6 < self.userInput):
print("Package", self.packNum, "will cost 3.70 per pound\n")
elif(self.userInput > 10):
print("Package ", self.packNum, "will cost $3.80 per pound\n")
def getWeight(self):
return self.userInput + self.userInput
def getPrice(self):
if (self.userInput <= 2):
return self.pacPrice + 1.10
elif(6 >= self.userInput and 2 < self.userInput):
return self.packPrice+ 2.20
elif(10 >= self.userInput and 6 < self.userInput):
return self.packPrice + 3.70
elif(self.userInput > 10):
return self.packPrice + 3.80
def displayInfo(self):
print("The total price is: %.2f" % self.getPrice())
print("The total weight of packages is: %.2f" % self.getWeight())
def main():
x = 0
userResponse = "y"
packNum = 1
packPrice = 0
while(x != 1):
userInput = eval(input("Enter the weight of package in pounds: "))
if(userInput >0):
package = ShippingCharges(userInput, packNum, packPrice)
packNum = packNum + 1
userResponse = input("Would you like to send another package? y/n \n")
if(userResponse == "n"):
break
elif(userInput <= 0):
print("Package must be greater than 0")
package.displayInfo()
main()
If I type "5" 5 times as the userInput, why is the output:
The total charge for all packages is: 2.2
The total weight of all packages is: 10.00
Why is it not?
The total charge for all packages is: 11.00
The total weight of all packages is: 25.00
I am trying to list down all the prime numbers up till a specific number e.g. 1000. The code gets slower as the number increase. I am pretty sure it is because of the for loop where (number -1) is checked by all the prime_factors. Need some advise how I can decrease the processing time of the code for larger numbers. Thanks
import time
t0 = time.time()
prime_list = [2]
number = 0
is_not_prime = 0
count = 0
while number < 1000:
print(number)
for i in range (2,number):
count = 0
if (number%i) == 0:
is_not_prime = 1
if is_not_prime == 1:
for j in range (0,len(prime_list)):
if(number-1)%prime_list[j] != 0:
count += 1
if count == len(prime_list):
prime_list.append(number-1)
is_not_prime = 0
count = 0
break
number += 1
print(prime_list)
t1 = time.time()
total = t1-t0
print(total)
Your solution, on top of being confusing, is very inefficient - O(n^3). Please, use the Sieve of Eratosthenes. Also, learn how to use booleans.
Something like this (not optimal, just a mock-up). Essentially, you start with a list of all numbers, 1-1000. Then, you remove ones that are the multiple of something.
amount = 1000
numbers = range(1, amount)
i = 1
while i < len(numbers):
n = i + 1
while n < len(numbers):
if numbers[n] % numbers[i] == 0:
numbers.pop(n)
else:
n += 1
i += 1
print(numbers)
Finally, I was able to answer because your question isn't language-specific, but please tag the question with the language you're using in the example.
I'm getting an error on line 3 "TypeError: 'int' object is not iterable," and its been bothering me. Any advice/fixes appreciated.
Example test: collatz_counts(4) → 3 # 4 -> 2 -> 1 (3 steps)
Code I have:
def collatz_counts(x):
num = 0
for i in (x):
if i == 1:
num += 1
return num
elif i % 2 == 0:
num(i) / 2
num += 1
num.append(i)
else:
num = (i*2) + 3
num += 1
num.append(i)
return num
This can be solved recursively:
def collatz_length(n):
if n == 1:
return 1
return 1 + collatz_length(3*n+1 if n%2 else n//2)
Which lends itself to be memoized if you are going to be calling for a range of numbers, e.g. in Py3
import functools as ft
#ft.lru_cache(maxsize=None)
def collatz_length(n):
if n == 1:
return 1
return 1 + collatz_length(3*n+1 if n%2 else n//2)
Which will run through the first million collatz sequences in about 2.31s vs about 28.6s for the iterative solution.
Use a while loop. Just modify x in place until you get to 1 and keep track of the number of steps each time you run a cycle.
def collatz_counts(x):
steps = 0
while x != 1:
if x % 2:
x = x * 3 + 1
else:
x = x // 2
steps += 1
return steps
Ok so I'm trying to make a working napier numeral calculator. I have gone through most of the steps I need to make it work. I need 2 more steps the function and converting it back to napier numbers. Currently I'm stuck on getting the functions to work. It just seems to skip that step. From what I can tell it should work and not be skipped. Could anyone tell me if I missed a step in the process of making the function.
def main():
response = 'y'
while response == 'y' or response == 'Y':
nap1 = getNapier()
num1 = napToInt(nap1)
print(num1)
nap2 = getNapier()
num2 = napToInt(nap2)
print(num1, num2)
operator = getOperator
result = doMath(num1, num2, operator)
response = input("Try another[y/n]")
def doMath(num1, num2, operator):
if operator == "+":
answer = num1 + num2
elif operator == "-":
answer = num1 - num2
elif operator == "*":
answer = num1 * num2
else:
if operator == "/":
answer = num1 / num2
return doMath
def getOperator():
op = input("Enter operator: ")
while op not in "+-*/":
op = input("Error!!!! Enter operator: ")
return op
def napToInt(n):
result = 0
for ch in n:
result += 2 ** (ord(ch) - ord('a'))
return result
def getNapier():
nap = input("Enter Napier number: ")
while not nap.isalpha():
nap = input("Error!!! Enter Napier number: ")
return nap
main()
this is the result I get as you can see it gets the napier numbers and just stops
Enter Napier number: asdf
262185
Enter Napier number: adsf
262185 262185
Try another[y/n]
your line operator = getOperator should be operator = getOperator()
I am new to this, and I am looking for help. I currently am stuck in a program I'm trying to complete. Here it is:
def printStock(stockList, stockPrice, p):
for i in range(len(stockPrice)):
if stockPrice[i] > p:
p = stockList[i]
print("The stocks with a higher value are:", p)
def searchStock(stockList, stockPrice, s):
for i in range(len(stockList)):
if s == stockList[i]:
s = stockPrice[i]
elif s != stockList[i]:
s = -1
return s
def mainFun():
stockList= []
stockPrice = []
l = 1
while l > 0:
stocks = str(input("Enter the name of the stock:"))
stockList += [stocks]
if stocks == "done"or stocks == 'done':
l = l * -1
stockList.remove("done")
else:
price = int(input("Enter the price of the stock:"))
stockPrice += [price]
l = l + 1
print(stockList)
print(stockPrice)
s = input("Enter the name of the stock you're looking for:")
searchStock(stockList, stockPrice, s)
p = s
printStock(stockList, stockPrice, p)
Every time I run the program to the end, it never returns the variable s for some reason. If i replace return with print, it always prints -1 instead of the stockPrice if its on the list. I also get an error saying "unorderable types int() > str()" regarding line 3. Basically the function printStock takes the three parameters and once the function is done it should print the names of the stocks higher than the value 'p'. The value of 'p' is the same as the value I get after calling searchStock function, but I cant seem to get it to work. Can someone please help me?
s is being returned from the function, but the return value is not being assigned to any variable on the outer scope.
Just replace
searchStock(stockList, stockPrice, s)
with
s=searchStock(stockList, stockPrice, s)
And everything should work as expected