Python redundancy [closed] - python

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.

Related

What am I Doing wrong. Google kickstart 2020 [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
this the question.
Ron read a book about boring numbers. According to the book, a positive number is called boring if all of the digits at even positions in the number are even and all of the digits at odd positions are odd. The digits are enumerated from left to right starting from 1. For example, the number 1478 is boring as the odd positions include the digits {1, 7} which are odd and even positions include the digits {4, 8} which are even.
Given two numbers L and R, Ron wants to count how many numbers in the range [L, R] (L and R inclusive) are boring. Ron is unable to solve the problem, hence he needs your help.
Input
The first line of the input gives the number of test cases, T. T test cases follow. Each test case consists of a single line with two numbers L and R.
Output
For each test case, output one line containing Case #x: y, where x is the test case number (starting from 1) and y is the count of boring numbers.
Sample
3
5 15 Case #1: 6
120 125 Case #2: 3
779 783 Case #3: 2
And this is the result which I have written.
t = int(input())
for case in range(1, t+1):
total_number = 0
numbers = []
l, r = map(int, input().split())
for number in range(l, r+1):
answer = False
for x in range(len(str(number))):
position = x+1
pos_num = int(str(number)[x])
if ((position%2 == 0) and (pos_num%2 == 0)) or ((position%2 ==1) and (position%2 == 1)):
answer = True
else:
answer = False
if answer == True:
numbers.append(number)
total_number += 1
print(f"Case #{case}: {total_number}")
I am running this and getting the wrong results. Where am I doing wrong?
Sorry guys, I got the answer. This is the answer but if anyone can suggest a more efficient answer then, you are most welcome!
t = int(input())
for case in range(1, t + 1):
total_number = 0
numbers = []
l, r = map(int, input().split())
for number in range(l, r + 1):
answer = []
lst_number = list(str(number))
for x in range(len(lst_number)):
position = x + 1
pos_num = int(lst_number[x])
if ((position % 2 == 0) and (pos_num % 2 == 0)) or ((position % 2 == 1) and (pos_num % 2 == 1)):
answer.append(1)
else:
answer.append(0)
if 0 not in answer:
numbers.append(number)
total_number += 1
print(f"Case #{case}: {total_number}")

Python programming and the use of for loops [closed]

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

If N is positive then output all values from N down to and excluding 0. If N is negative, then output every value from N up to and excluding 0 [closed]

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 5 years ago.
Improve this question
As I said before I'm a beginner trying to learn Python in a college course, but what they teach us, doesn't always apply to the real world, and when I try to research a solution, there's nothing to be found. Anyway my latest problem is:
This is a tricky challenge for you.
We will pass in a value N. N can be positive or negative.
If N is positive then output all values from N down to and excluding 0.
If N is negative, then output every value from N up to and excluding 0.
and the starting code is:
# Get N from the command line
import sys
N = int(sys.argv[1])
# Your code goes here
counter = 0
while counter <= N:
print(counter)
counter = counter + 1
elif counter >= N:
print(N+counter)
counter = counter - 1
My solution produced an error:
SyntaxError: unexpected EOF while parsing
There is an error is your program.
And I honestly don't know where to start, as our textbook doesn't cover these challenges. Thanks in advance for any assistance rendered in this matter. BTW my code is inputted in Codio, and must pass in Codio's IDE.
# Get N from the command line
import sys
N = int(sys.argv[1])
# Your code goes here
if N > 0:
for x in range(N, 0, -1):
print x
if N < 0:
for x in range(N, 0):
print x
While Loops Version
# Your code goes here
if N > 0:
while N > 0:
print N
N -= 1
if N < 0:
while N < 0:
print N
N += 1
The main problem here is that you have a while and an elif. Elif is used with other if statements.
For example:
if condition:
do something
elif condtion:
do something else
else:
do something as a "last resort"
I think you are trying to do this:
#Checks To See if N is Positive
if N > 0:
#Sets counter to 1
counter = 1
#Iterates Thru Each Num from 1 To N-1
while counter < N:
print counter
#Increments Counter
counter += 1
#Checks To See If N Is Negative
elif N < 0:
#Sets Counter to -1
counter = -1
#Iterates Thru Each Num From -1 To N-1
while counter > N:
print counter
#Decrements Counter
counter -= 1
A couple final things:
If you want to learn what you consider "real world" programming, then I suggest that you look at some online resources such as https://www.codecademy.com/ or looking through the docs.
When posting on Stack Overflow, please explain your question/problem thoroughly
When inputting your code on Stack Overflow, make sure that it is properly formatted (e.g. indentations), as they make decoding larger programs much easier.
Stack Overflow is not a "do my homework for me" site

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.

Categories

Resources