So I am testing my script in which i am passing two values to compare. It goes through two conditional statements. I have carried out some debugging and it prints out the same expression twice which is "Current value is in range". It first prints it out from the first loop and then from the second loop. I am not sure why my code is doing that. It should only print that out once and get out of the else statement and not go in to the second else statement which it is currently doing. What is that I am doing wrong to stop this.
def compare_sizes(previous_size, current_size):
subtract_f1_f2 = int(current_size - previous_size)
range_num = 0.4
range_previous_day = int(previous_size * range_num)
if subtract_f1_f2 > 0 and range_previous_day > 0 and subtract_f1_f2 >= range_previous_day:
whole_percent = subtract_f1_f2 / previous_size * 100
print (human_bytes(previous_size) +" -> " + human_bytes(current_size) + " " +
"+" + str(whole_percent) + " % bigger" + "\n")
return
else:
print("Current Value Is In Range")
if subtract_f1_f2 <0 and subtract_f1_f2 <= range_previous_day:
whole_percent = abs(subtract_f1_f2 / previous_size * 100)
print (human_bytes(previous_size) + " -> " + human_bytes(current_size) + " " + str(
whole_percent) + " % smaller" + "\n")
else:
print("Current Value Is In Range")
result = compare_sizes(1000,1400)# 40% Bigger
result = compare_sizes(1000,1399)# In Range
# result = compare_sizes(1000,599)
Related
I was trying to bubble sort the temperature array but i am getting this kind of error.. Someone please help me fix this :)
Here's the code :
print("")
print("")
days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thrusday", "Friday", "Saturday"]
temperature = []
highest = float(0.0)
lowest = float(100.0)
total = float(0.0)
for i in range(7):
inp = round(float(input("Please enter the temperature for " + days[i] + " in Celcus: ")),1)
temperature.append(inp)
print("")
print("")
print("You entered these Temperatures in Celsius and Fahrenheit.")
print("")
print("")
for j in range(len(temperature)):
def bubble_sort(tem):
for a in range(len(tem)):
for b in range(len(tem)-1):
if(tem[b]>tem[b+1]):
temp=tem[b]
tem[b]=tem[b+1]
tem[b+1]=temp
return tem
arr = []
arr.append(temperature[j])
Fahrenheit = round(((temperature[j] * 1.8) + 32),1)
total = total + temperature[j]
print(bubble_sort(arr) + " C° is " + str(Fahrenheit) + " F°" )
print("--------------------")
avg = round(total / len(temperature),1)
print("High Temp: " + str(max(temperature)) + "C°, Low Temp: " + str(min(temperature)) + " C° Average Temp: " + str(avg) + " C°")
I am not getting what wrong is with this code ..
The error is pretty explicit: the list is bubble_sort(arr) and the str is " C° is "
You can't concatenate them at bubble_sort(arr) + " C° is ", you'd need to wrap the list into str
The nicest is just to use the fact that print allows multiple values to be given
print(bubble_sort(arr), "C° is", Fahrenheit, "F°")
print("High Temp:", max(temperature), "C°, Low Temp:",
min(temperature), "C° Average Temp:", avg, "C°")
Now, you're not sorting anything as there is only ONE value in arr, just sort once before the loop, then show the Fahrenheit value
arr = bubble_sort(temperature)
for value in arr:
fahrenheit = round(((value * 1.8) + 32), 1)
print(value, "C° is", fahrenheit, "F°")
avg = round(sum(temperature) / len(temperature), 1)
print("High Temp:", max(temperature), "C°, Low Temp:",
min(temperature), "C° Average Temp:", avg, "C°")
the defectiv line is
print(bubble_sort(arr) + " C° is " + str(Fahrenheit) + " F°" )
since you are using the "+" operator on a list and a string
in order to fix it try converting the list (that you get from calling "bubble_sort(arr)" to a string )
like this
print(''.join(str(e) for e in bubble_sort(arr)) + " C° is " + str(Fahrenheit) + " F°")
im rather new to python and found someones lottery simulation in github. After playing around with it for a while i wanted to add a counter, that counts the number of matches of your Number out of the total draws.
I don't know if it is because i did not write the code myself, but i can't seem to make it happen. I've tried some of pythons counter modules bu that did'nt seem to be the right thing.
Heres my code:
import random
import time
### TODO - Refactor GetDrawNumbers (add timers)
### TODO - Refactor CheckNumbers
def GetDrawNumbers():
drawNumbers = []
for i in range(6):
x = None
while (x == None or x in drawNumbers):
x = random.randint(1, 49)
drawNumbers.append(x)
return drawNumbers
def CheckNumbers(myTicket, actualNumbers):
numbersMatched = 0
for number in myTicket:
if number in actualNumbers:
numbersMatched += 1
return numbersMatched
### Script starts here
startTime = time.perf_counter()
myNumbers = [4, 8, 15, 16, 23, 42]
for draw in range(2000):
drawNumber = draw + 1
thisWeeksDraw = GetDrawNumbers()
numbersMatched = CheckNumbers(myNumbers, thisWeeksDraw)
##print("Week " + str(drawNumber) + " numbers : " + str(thisWeeksDraw) + " (" + str(numbersMatched) + " matched)")
if numbersMatched == 4:
print("Week " + str(drawNumber) + " numbers : " + str(thisWeeksDraw) + " (" + str(numbersMatched) + " matched)")
count = numbersMatched
print("Total matches: " + str(count))
endTime = time.perf_counter()
elapsedTime = endTime - startTime
print("Completed in " + str(elapsedTime) + " seconds!")
If anyone knows a way to implement a counter, that counts the number of times this the program gets 3,4,5 or 6 correct matches i would be super relieved! It's not that this project would be super important but solving the problem would be a milestone for me and my learning process!
Thanks in advance and best wishes!
How about this where I have added a check of the numbersMatched value and increment a counter whenever it is 3 or more
import random
import time
### TODO - Refactor GetDrawNumbers (add timers)
### TODO - Refactor CheckNumbers
def GetDrawNumbers():
drawNumbers = []
for i in range(6):
x = None
while (x == None or x in drawNumbers):
x = random.randint(1, 49)
drawNumbers.append(x)
return drawNumbers
def CheckNumbers(myTicket, actualNumbers):
numbersMatched = 0
for number in myTicket:
if number in actualNumbers:
numbersMatched += 1
return numbersMatched
### Script starts here
startTime = time.perf_counter()
myNumbers = [4, 8, 15, 16, 23, 42]
countOfThreeOrMoreMatched = 0
for draw in range(2000):
drawNumber = draw + 1
thisWeeksDraw = GetDrawNumbers()
numbersMatched = CheckNumbers(myNumbers, thisWeeksDraw)
##print("Week " + str(drawNumber) + " numbers : " + str(thisWeeksDraw) + " (" + str(numbersMatched) + " matched)")
if numbersMatched >= 3:
countOfThreeOrMoreMatched += 1
if numbersMatched == 4:
print("Week " + str(drawNumber) + " numbers : " + str(thisWeeksDraw) + " (" + str(numbersMatched) + " matched)")
print(f"Count with 3 or more matches {countOfThreeOrMoreMatched}")
count = numbersMatched
print("Total matches: " + str(count))
endTime = time.perf_counter()
elapsedTime = endTime - startTime
print("Completed in " + str(elapsedTime) + " seconds!")
I'm making a small program that shoots out math problems and requires an answer to pass. It works fine, but all the randint values I generate stay static for as long as the progran is running. I figured if I change:
Tehtävä = random.choice(Laskut)
Into a function it should refresh with the loop. Problem is I can't for the life of me figure out how to do that. Would it even work for what I'm trying? The randint values are determined in a seperate list. Heres the rest of the code:
Peli = 1
while Peli != 2:
pulma = 1
refresh = 1
Tehtävä = random.choice(Laskut)
while pulma == 1:
ratkaisu = float(input(Tehtävä.problem + "\n:"))
if ratkaisu == Tehtävä.answer:
pulma += 1
refresh += 1
print("oikein")
elif ratkaisu == "loppu":
pulma += 1
refresh += 1
Peli += 1
else:
print("väärin")
Here are the values I used:
import random
class Algebra:
def __init__(self, problem, answer):
self.problem = problem
self.answer = answer
#Muuttujat
#erotus ja summa
a = random.randint(1,99)
b = random.randint(1,99)
c = random.randint(1,99)
d = random.randint(1,99)
#jako ja kerto
e = random.randint(1,10)
f = e*random.randint(1,10)
g = random.randint(1,10)
#Kysymykset
Kysymys_M = [str(a) + "+" + str(b) + "-x=" + str(c),
str(a) + "-" + str(b) + "-x=" + str(a),
str(a) + "-" + str(b) + "-" + str(c) + "-x=" + str(d),
str(e) + "*x=" + str(f),
str(f) + ":x=" + str(e),
"x:" + str(e) + "=" + str(g)]
#Vastaukset
Vastaus_M = [a+b-c,
-b,
a-b-c-d,
f/e,
f/e,
e*g]
Laskut = [
Algebra(Kysymys_M[0], Vastaus_M[0]),
Algebra(Kysymys_M[1], Vastaus_M[1]),
Algebra(Kysymys_M[2], Vastaus_M[2]),
Algebra(Kysymys_M[3], Vastaus_M[3]),
Algebra(Kysymys_M[4], Vastaus_M[4]),
Algebra(Kysymys_M[5], Vastaus_M[5]),]
(If I have packed too much information please let me know.)
I'm trying to write a program that prints the values and keys in a dictionary depending of the input the user types. The problem appears when the elif statement on line 11 gets skipped. It doesn't matter if the if statement is false, the elif statement gets skipped. I'm learning so I don't really know where my error is. Thanks for the help!
areaM = {str(1) + " acre" : str(160) + " sq rods"}
linearM = {str(1) + " ft" : str(12) + " in", str(1) + " yd": str(3) + " ft"}
def displayConversion(conv):
for k, v in conv.items():
print(str(v) + " = " + str(k))
while True:
print("Enter a conversion")
if input() == "Area Meassure":
displayConversion(areaM)
elif input() == "Linear Meassure":
displayConversion(linearM)
else:
print("Conversion not available")
Maybe this as the full code (too much inputss):
areaM = {str(1) + " acre" : str(160) + " sq rods"}
linearM = {str(1) + " ft" : str(12) + " in", str(1) + " yd": str(3) + " ft"}
def displayConversion(conv):
for k, v in conv.items():
print(str(v) + " = " + str(k))
while True:
a=input("Enter a conversion\n")
if a == "Area Meassure":
displayConversion(areaM)
break
elif a == "Linear Meassure":
displayConversion(linearM)
break
else:
print("Conversion not available")
I am fairly new to python, I am not sure on how to fix a index string out of range. it happens right after the while loop when I want to send mylist[i][0] to formatting function. Any pointer on my code in general would be awesome!
def formatting(str1):
if str1 == '?':
return True
else:
return False
while(i <= len(mylist)):
val = formatting(mylist[i][0])
if val == True:
str1 = mylist[i]
str2 = mylist[i+1]
i = i + 2
format_set(str1, str2)
else:
if format == True:
if (margin + count + len(mylist[i])) <= width:
if (i == (len(mylist)-1)):
list2.append(mylist[i])
print(" " * margin + " ".join(list2))
break
list2.append(mylist[i])
count += len(mylist[i])
i += 1
else:
print(" " * margin + " ".join(list2))
list2 = []
count = 0
else:
temp_margin = margin
temp_width = width
width = 60
margin = 0
if (margin + count + len(mylist[i])) <= width:
if (i == (len(mylist)-1)):
list2.append(mylist[i])
print(" " * margin + " ".join(list2))
margin = temp_margin
width = temp_width
break
list2.append(mylist[i])
count += len(mylist[i])
i += 1
else:
print(" " * margin + " ".join(list2))
list2 = []
count = 0
change
i <= len(mylist)
to
i < len(mylist)
In the last iteration of the while loop, i is referring to the last value. Hence,
str2 = mylist[i+1]
is trying to reference a string outside the allowed range and you get an error.
EDIT: Also, as Wcrousse mentioned, the while (i <= len(...)) should be changed to i < len(...) because indexes go from 0 - (length-1).