Python programming and the use of for loops [closed] - python

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
Am new to programming and I just started studying and practicing. I started with python and am at for loops now. I kinda coded something that’s getting confusing for me because I can’t seem to understand how the code arrived at that output. Can someone please explain it to me. Would be very grateful.
Here’s the code I did:
a = range(1,20)
total = 0
for i in a :
if i%3==0 or i%5==0 :
total new = total + i
print (total new)
And the output was 18.

a = range(1,20)
Your program is creating a range of numbers between 1 and 19 (ranges go to one less than the max number you specify) like [1, 2, 3, 4, ..., 19]
total = 0
Your program is initializing the variable total to equal 0
for i in a:
You start looping through the range you made earlier, the first iteration i=1, the next i=2 and so on until i=19
if i % 3 == 0 or i % 5 == 0:
You are selecting only the data where the modulo of 5 or 3 is 0. For example:
3 % 3 == 0 (0 remainder)
4 % 3 == 1 (1 remainder)
Now altering your variable to a reasonable name (without spaces) that will actually utilize the variable we initialized above
total = total + i # alternatively written "total += i"
This says that every time the value i is evenly divisible by 3 or 5 we will add it to our total
print(total)
We show the final result after adding values. You incorrectly scripted your program to do this though so it only showed the largest value that was evenly divisible by 5 or 3 which is 18.
When scripted correctly:
a = range(1, 20)
total = 0
for i in a:
if i % 3 == 0 or i % 5 == 0:
total += i
print(total)
Outputs
78

Related

Code the Hailstone sequence, Print the sequence for a range of any positive whole numbers, or for an input number [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I got this Python skill assessment for my QA automation job interview and was not able to solve it. Can someone help? Thank you
I've tried to create a function
def odd_and_enven_numbers(number):
if number % 2 == 0:
return number / 2
else:
return number * 3 + 1
Hailstone sequence
If the number is even, divide it by 2
If the number is odd, multiply it by 3 and add 1
The sequence continues until it is equal to 1, then stops
e.g.
Sequence for 3 = 3,10,5,16,8,4,2,1
Sequence for 5 = 5,16,8,4,2,1
Sequence for 7 = 7,22,11,34,17,52,26,13,40,20,10,5,16,8,4,2,1
Your problem is, you only apply your function to number once. This can easily be fixed using recursion. We will keep applying the function to the given number until it reaches one. Every time we run the function we append the current value fo number to a list called seq. Once number reaches 1 we can return our sequence.
seq = []
def odd_even(number):
seq.append(number)
#if you remove this if, we will get a RecursionError.
#basically you are calling the function for ever and it will never stop
if number != 1:
if number % 2 == 0:
return odd_even(number / 2)
else:
return odd_even(number * 3 + 1)
return seq
print(odd_even(3))
output
[3, 10, 5.0, 16.0, 8.0, 4.0, 2.0, 1.0]
This can easily be done without recursion like this:
def hailstone(x):
s = []
while x != 1:
s.append(x)
if x % 2 == 0:
x = x//2
else:
x = 3*x+1
s.append(x)
return s
And it works like this:
hailstone(3)
[3, 10, 5, 16, 8, 4, 2, 1]

Project Euler #1 python code not working [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 7 years ago.
Improve this question
For Project Euler, question #1:
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
I am trying to use Python, and I have the following code:
def findNums():
numsToAdd = []
num = 1
while num < 999:
if 3 % num == 0 or 5 % num == 0:
numsToAdd.extend([num])
num +=1
#print(num) optional
for i in numsToAdd:
lastNum = 0
addition = numsToAdd[i] + lastNum
lastNum = numsToAdd[i]
print(lastNum)
findNums()
But I get the following error when I try to run it:
addition = numsToAdd[i] + lastNum
IndexError: list index out of range
Could someone please tell me what this is and how to fix it?
You have a few issues:
if 3 % num == 0 or 5 % num == 0:
Your conditionals are backward. How you have it set up now, you are checking if 3 or 5 is evenly divisible by num, not if num is evenly divisible by 3 or 5.
for i in numsToAdd:
Assume that numsToAdd has the following values when you get to this point: [100, 500].
When you get to addition = numsToAdd[i] + lastNum you are saying the following:
addition = numsToAdd[100] + lastNum
and
addition = numsToAdd[500] + lastNum
There isn't a 100th or 500th element. Instead, you can remove the indexing (to keep your existing format):
addition = i + lastNum
You could also do this to add up all the values in the list in one line:
sum(numsToAdd)
This can replace the entire for loop.
Finally, your first while is wrong:
Find the sum of all the multiples of 3 or 5 below 1000.
You are checking for everything less than 999. Change your while loop:
while num < 1000:
The problem with your code is that your list numsToAdd has just 465 items in it.
Instead of this:
numsToAdd[0]
numsToAdd[1]
numsToAdd[2]
.
.
numsToAdd[462]
numsToAdd[463]
numsToAdd[464]
You are doing this:
numsToAdd[3]
numsToAdd[5]
numsToAdd[6]
.
.
numsToAdd[459]
numsToAdd[460]
numsToAdd[462]
The error occurs because your list index is out of range! There is no numsToAdd[465]!

Python:Project Euler #1 [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last year.
Improve this question
I've tried looking up some questions that were already on StackOverflow for project Euler problem 1 but not much has helped me. This is my code, it runs, but it's not correct. not sure whats wrong?
def sumOfMultiples(number):
sum = 0
for i in range(1,number):
if i % 3 == 0 or i % 5 == 0:
sum += 1
return sum
print (sumOfMultiples(15))
You are not using i at all. When the number meets the condition (divisible by 3 or 5), you want to add it, not 1.
sum += 1
should be
sum += i
The question asks for "the sum of all the multiples of 3 or 5 below 1000". You're adding 1 to the sum instead of adding the multiple of 3 or 5 to the sum.
So sum += 1 should be sum += i.
import time
#Recording start time of the program
start=time.time()
#A variable to store the sum
result=0
#calculating the sum for all the numbers below 1000
for i in range(1,1000):
#Checking the the condition
if i%3==0 or i%5==0:
result=result+i
print("Sum of all numbers that are multiples of 3 or 5 below 1000 is",result)
print("Execution time of program is",time.time()-start)
def sumOfMultiples(number):
sum = 0
for i in range(1,number):
if i % 3 == 0 or i % 5 == 0:
sum += i
return sum
print (sumOfMultiples(15))
In place of sum+=1 write sum+=i.
Here is a single-liner for you to ponder:
print sum([x for x in xrange(1,1000) if x%3==0 or x%5==0])
or you could also do it like this:
print sum([[0,x][x%3==0 or x%5==0] for x in xrange(1,10**3)])
try using this:
def sumOfMultiples(number):
sum = 0
for i in range(1,number):
if i % 3 == 0 or i % 5 == 0:
sum += i ## You needed to add i, not 1. Probably just a type-o as they are similar looking characters.
print(sum)
(sumOfMultiples(1000)) ## Also Euler1 requires this input to be 1000 for correct answer.

How to use an if/while loop together in Python? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
So basically I want to do this generate a random number (this I know how to do) if that number is even (or number%2 == 0) then divide it by 2 then if the resulting number is odd (or number%2 > 0) then multiply by 3 and add 1. If that didn't make much sense here is an exmaple
Pick a number like 26 (this is even so divide by 2)
Resulting number is 13 (this is odd so multiply by 3 add 1)
Resulting number is 40 (this is even so divide by 2)
Continue this process until the number is == 1
I am not sure what loop to use to do this so any help is very appreciated! :)
number = # generate random number
while number != 1:
if number % 2: # if number is odd, multiply by 3, add 1
number *= 3
number += 1
else: # if number is even, divide by 2
number /= 2
You can run a bit of cheeky code to keep track of iterations, if you like:
num_iterations = 0
number = # generate random number
while number != 1:
num_iterations += 1
if number % 2:
number = number * 3 + 1
else:
number /= 2
Since you do not know how many steps would it take to get the number equal to one, i.e. the number of iterations is unknown , use a while loop:
number = # random number
while number != 1:
if number % 2:
number *= 3
number += 1
else:
number /= 2
Or another approach:
number = # random number
while True:
if number == 1:
break
elif number % 2: # odd
number *= 3
number += 1
else: # even
number /= 2

Python redundancy [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions must demonstrate a minimal understanding of the problem being solved. Tell us what you've tried to do, why it didn't work, and how it should work. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
If I have the code
i = 0
while i < N:
print("Hello")
i += 1
how many times will Hello be printed out? (assume that N is a defined integer)
Answers:
0
N
N-1
N+1
more than N+1
and why? I never get this so I would appreciate of somebody could explain.
The best way to figure it out is to go through it by hand for a few manageable values of N. For instance, if N is 2:
i == 0 and 0 < 2 → print "hello", increment i
i == 1 and 1 < 2 → print "hello", increment i
i == 2 and 2 < 2 → while-loop condition is no longer satisfied → loop ends
So for N = 2, "hello" is printed 2 times. See the pattern?
Hello will be printed out N times.
assume N is 3.
1st iteration
i = 0
i is less than N
print hello
i = i + 1; // i = 1
2nd iteration
i = 1;
i` is less thanN (3)`
print hello
i = i + 1; // i = 2
3rd iteration
i = 2;
i is less than N (3)
print hello
i = i + 1; // i = 3
4th iteration
i = 3;
i is equal to N (3)
break loop
As the other answers described, it would print N times, because it starts at 0 and goes until it is just before N, not equal to N.
In reality, though, this is very redundant in Python. A much easier way to do this, making it a bit more readable (and hopefully easier for you to understand):
N=3
for x in range(0,N):
print "This is loop %d" % (x)
This loop will print from 0 to N, which is really just N amount of times.

Categories

Resources