I have a for loop with a 100 iterations and I would like to change the value of a variable for every 10 iterations. One way of doing this would be:
for i in range(100):
if i < 10:
var = 1
elif i < 20 :
var = 1.5
...
But I don't want to have 10 if statements. Is there a better way of doing it? In this case, the variable changes by the same amount for every 10 iterations.
You're looking for the modulo (%) operator. From the docs:
The % (modulo) operator yields the remainder from the division of the first argument by the second.
Indeed, 11 = 10 * 1 + 1 hence 11 % 10 = 1, but 30 = 10*3 + 0 hence 30 % 10 = 0! And you're looking for all those that are a factor of ten:
increment = 0.5
for i in range(100):
if i % 10 == 0:
var += increment
There is this modulo operator %
for i in range(100):
if 0 == i % 10:
var = var + 0.5
or if you want to change var on other than the first iteration:
for i in range(100):
if i and 0 == i % 10:
var = var + 0.5
Related
I am trying to add elements of two lists together e.g. listing all integers below 10 that are multiples of 3 or 5. The sum of these multiples should be 23 (3+5+6+9) but I keep getting 18. I have only just starting programming and learning python. Here's my code:
for i in range (1,10):
if i % 3 == 0:
print(i)
for x in range (1,10):
if x % 5 ==0:
print(x)
sum_multiples=i+x
print(sum_multiples)
What you are trying to do:
3 + 6 + 9 + 5 = 23
What you are doing:
9 + 9 = 18
This is what you want:
l1 = [x for x in range(1, 10) if x % 3 == 0]
l2 = [x for x in range(1, 10) if x % 5 == 0]
print(sum(l1) + sum(l2))
First off, let me address your problem. When you add variable i and variable x, they are both value of 9. This is because after the loop their value is 9, and because you are adding the values after the loop, you are adding 9 + 9.
You can fix this by making a variable outside the loop and adding the number to the variable. My code would be:
total = 0
for i in range (1,10):
if i % 3 == 0:
print(i)
total = total + i
for x in range (1,10):
if x % 5 ==0:
print(x)
total = total + x
print(total)
(this is just based off what you were doing, I would probably condense it into one loop)
You could so something like this:
sum_multiples = 0
for i in range(1, 10):
if i % 3 == 0 or i % 5 == 0:
sum_multiples += i
print(sum_multiples)
If you prefer a one line solution:
print(sum(i for i in range(1, 10) if i % 3 == 0 or i % 5 == 0))
hint:pi can be computed by 4*(1-1/3+1/5-1/7+1/9- ...).
I have idea to solve this question by using while loop, but I'm confused that, in while loop, how can I save my variable every time when i use if conditional.
Here is my code.
def piA(num):
i = 1
pi = 4
while i <= num:
s = 0
float(s)
if i % 2 == 1:
s = s + (1/(2*i-1))
print(s)
elif i % 2 == 0:
s = s - (1/(2*i-1))
print(s)
i += 1
print(s)
return pi*s
print(piA(2))
The result shows:
1.0
1.0
-0.3333333333333333
-0.3333333333333333
-1.3333333333333333
You don't have to save the previous variable, just use builtin method sum():
def pi(num):
return 4*sum((1 if i % 2 else -1)*(1 / (2*i - 1)) for i in range(1, num+1))
print(pi(10000))
Prints:
3.1414926535900345
If i have a number 101, i want to multiply all the digits of the number (1*0*1) but this result will become Zero. Instead how to split the number into 10 and 1 and multiply(10*1).
Similar examples,
3003033 -> 300*30*3*3 or
2020049 -> 20*200*4*9
You could use a negative look behind to check its not the start of the list and a positive look ahead for nums that are not 0 as your split point.
REGEX: Essentially this says split where the next num is not a 0 and it not the start of the line
/
(?<!^)(?=[^0])
/
gm
Negative Lookbehind (?<!^)
Assert that the Regex below does not match
^ asserts position at start of a line
Positive Lookahead (?=[^0])
Assert that the Regex below matches
Match a single character not present in the list below [^0]
0 matches the character 0 literally (case sensitive)
CODE
import re
from functools import reduce
def sum_split_nums(num):
nums = re.split(r'(?<!^)(?=[^0])', str(num))
total = reduce((lambda x, y: int(x) * int(y)), nums)
return " * ".join(nums), total
nums = [3003033, 2020049, 101, 4040]
for num in nums:
expression, total = sum_split_nums(num)
print(f"{expression} = {total}")
OUTPUT
300 * 30 * 3 * 3 = 81000
20 * 200 * 4 * 9 = 144000
10 * 1 = 10
40 * 40 = 1600
Let a and b be two integer numbers. Let c be a new number made by putting n zeros in the right side of b. Then multiplying a and c is equal to multiplying a and b and 10^n.
Now you can simplify what you want to do to the following: Multiply digits of your number to each other with the agreement that instead of 0, you will put 10. So actually you don't need to split your number.
Here I defined two functions. In both of them the idea is to convert your number to a string, run a for-loop on its digits and by an if condition in the case
1) multiply the previous result to the new digit if it is not 0, otherwise multiply to 10.
def multio1(x):
s = str(x)
ans = 1
for i in range(len(s)):
if s[i] != '0':
ans *= int(s[i])
else:
ans *= 10
return(ans)
2) multiply the previous result to the new digit if it is not 0, otherwise add one unit to the number of zeros. Then at the end put as many as number of zeros, zeros at the right side of your final result.
def multio2(x):
s = str(x)
ans = 1
number_of_zeros = 0
for i in range(len(s)):
if s[i] != '0':
ans *= int(s[i])
else:
number_of_zeros += 1
if number_of_zeros != 0:
ans = str(ans)
for i in range(number_of_zeros):
ans += '0'
ans = int(ans)
return(ans)
Now the multio1(x) and multio2(x) for x=101,3003033,2020049, both gives equal results shown in below.
10,81000,144000
That's kind of odd, but this code will work:
a = '3003033'
num = ''
last_itr = 0
tot=1
for i in range(len(a)-1):
if a[i]=='0' and a[i+1]<='9' and a[i+1]>'0':
tot*=int(a[last_itr:i+1])
last_itr=i+1
elif a[i]>'0' and a[i]<='9' and a[i+1]<='9' and a[i+1]>'0':
tot*=int(a[i])
last_itr=i+1
tot*=int(a[last_itr:len(a)])
print(tot)
Just put your number at a
I am a beginner trying to learn python through MIT OpenCourseware. This problem is from part B of problem set 1. I understand the mathematical expression but I do not know how to write it out in code.
This is the problem:
Determine how long it will take to save enough
money to make the down payment for a house given the following assumptions:
portion_down payment = 0.25 (25%)
You start with a current savings of $0
Assume that you invest your current savings wisely, with an annual return of r = 0.04 (4%)
Your salary increases by a certain percentage every 6 months (semi-annual rise)
Here is a test case:
Enter your starting annual salary: 120000
Enter the percent of your salary to save, as a decimal: .05
Enter the cost of your dream home: 500000
Enter the semiannual raise, as a decimal: .03
Number of months: 142
Here is my code:
annual_salary = float(input('Annual Salary: '))
portion_saved = float(input('Portion saved (decimal): '))
total_cost = float(input('Total Cost of House: '))
semi_annual_rise = float(input('Semi-annual salary rise (decimal): '))
downp = float(0.25*total_cost)
current_savings = 0
monthly_savings = float(portion_saved*annual_salary/12)
ret = 1 + .04/12
rise = 1 + semi_annual_rise
n = 0
while current_savings < downp:
for n in range(0,300,6):
monthly_savings = monthly_savings*(rise)
current_savings = (current_savings + monthly_savings)*(ret)
n += 1
print ('Number of months: ' + str(n))
Under the while loop, I am trying to increase the salary after 6, 12, 18 etc... months. But I dont know how to insert such a conditionI know it's wrong but I do not know how to correct it. Please help me!!
Just make the raise when n%6 == 0 ...
...
n = 0
while current_savings < downp:
n += 1
if n % 6 == 0: #every six months
monthly_savings = monthly_savings*(rise)
current_savings = (current_savings + monthly_savings)*(ret)
...
while True:
try:
number = input('Enter') #Asks user to input 7 digit number
if len(str(number)) != 7:
print('Incorrect')
if len(str(number)) == 7:
print('Okay')
multiplier = [3,1]
times = ''
total = 0
for index, digit in enumerate(list(str(number))):
total = total + int(digit)*multiplier[index%2]
times = times+str(int(digit)*multiplier[index%2])+', '
mof10 = total + (10 - total%10)
checkdigit = mof10 - total
final = str(number) + str(checkdigit)
print (times[:-1])
print(total)
print(mof10)
print(checkdigit)
print(final)
break
except ValueError:
print('Not a number')
My task is to 'Calculate the GTIN-8 product code from a seven digit number'
I need a line by line explanation of the code above, please.
Some info on enumerate by typing help(enumerate)
enumerate(iterable[, start]) -> iterator for index, value of iterable
Return an enumerate object. iterable must be another object that supports iteration. The enumerate object yields pairs containing a count (from start, which defaults to zero) and a value yielded by the iterable argument. enumerate is useful for obtaining an indexed list:
The % operator returns the remainder of x / y eg
10 / 5 = 2 r 0 | 10 % 5 = 0
7 / 2 = 3 r 1 | 7 % 2 = 1
Here is the code explained with comments
while True: # Loop will continue until break is called
try:
number = input('Enter') #Asks user to input 7 digit number
# Checks if the length of the input
# If not 7 characters long
# Will then ask for input again due to while loop
if len(str(number)) != 7:
print('Incorrect')
# If is 7 chacters long
if len(str(number)) == 7:
print('Okay')
multiplier = [3,1]
times = ''
total = 0
# example input for number '1234567'
# list(str(number))
# '1234567' -> ['1', '2', '3', '4', '5', '6', '7']
for index, digit in enumerate(list(str(number))):
# index%2 returns either 0 or 1
# this is used to get 3 or 1 from multiplier
# depending on if the index is odd or even
# for first index and digit from example
# index = 0, digit = '1'
# total = total + 1 * 3
total = total + int(digit)*multiplier[index%2]
# adds the multiplier value from digit * multiplier[index%2]
# to times as a string. First value is
# times = times + str(1 * 3) which is 3
times = times+str(int(digit)*multiplier[index%2])+', '
# essentially rounds up to nearest 10
mof10 = total + (10 - total%10)
# gets the number it was rounded up by
checkdigit = mof10 - total
final = str(number) + str(checkdigit)
print(times[:-1]) # slice the string to return everything except the last value
print(total)
print(mof10)
print(checkdigit)
print(final)
break # exit while loop
# If the convertion from string to int returns an error
# meaning a non-number was entered into input eg. !##$
# print the following, while loop will continue and prompt again
except ValueError:
print('Not a number')