Counting numbers in a range [closed] - python

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have to write a Python script that will allow the user to enter a set of positive numbers and then count how many are
equal to 50
greater than 50
less than 50
Use appropriate output to prove that your program is working.

Just for example's sake, let's write a function that counts how many numbers are above 50, then one for equal to 50, then one for less than 50. Disclaimer: this is not the only, or even the BEST way to accomplish what you want to do, this is just the best teaching aid :). Also, some of the nomenclature may change if you're not using Python 3.x.
#this function returns how many values in the list that's passed to it
#are greater than 50
def greaterThanFifty(list_to_compare):
how_many_above_fifty = 0
for value in list_to_compare:
if value > 50:
how_many_above_fifty += 1
return how_many_above_fifty
#this function returns how many values in the list that's passed to it
#are less than 50
def lessThanFifty(list_to_compare):
how_many_under_fifty = 0
for value in list_to_compare:
if value < 50:
how_many_under_fifty += 1
return how_many_under_fifty
#this function returns how many values in the list that's passed to it
#are equal to 50
def equalToFifty(list_to_compare):
how_many_are_fifty = 0
for value in list_to_compare:
if value == 50:
how_many_are_fifty += 1
return how_many_are_fifty
Now we have our functions that will return the values we need. Again, this is not the only or even the best way to do this, but it's the way I'm using because it teaches a lot of basic strategies like writing modular programs (each function is performed by its own bit of code) and using functions rather than straight code to perform your task. Unfortunately, on their own, this code doesn't do anything. It just defines functions that we'll leverage to solve the problem at hand. In essence -- we've made our hammer, nails, and saw, but now we have to cut the lumber to size and nail it up. Let's do that.
def main(): #this is always the name of our function that does the heavy lifting
list_of_numbers = []
user_input = input("List some numbers, comma separated please: ")
for num in user_input.split(","):
#loop through user_input, split by commas
list_of_numbers.append(num.strip())
#add to list_of_numbers each item that we find in user_input,
#stripped of leading and trailing whitespace
#at this point we've looped through all of user_input and added each number
#to list_of_numbers, so we can use our functions, defined earlier, to return
#the requested values. Luckily we set up our functions to accept
#lists!
greater_than_fifty = greaterThanFifty(list_of_numbers)
less_than_fifty = lessThanFifty(list_of_numbers)
equal_to_fifty = equalToFifty(list_of_numbers)
#now just to display the results to the user, and we're done.
print("There are "+str(greater_than_fifty)+" numbers over fifty")
print("There are "+str(less_than_fifty)"+ numbers under fifty")
print("There are "+str(equal_to_fifty)"+ numbers that are fifty")
We still haven't actually DONE anything, though, since all we've done is define functions that do what we want from start to finish. our greaterThanFifty function is our hammer, our lessThanFifty function is our saw, and our equalToFifty function is our nails. Now we've added a main function, which is our handyman. Now we need to tell him to work. Luckily that's easy :)
main()
That's it! We're done!
For comparison purposes, this is how I'd write all that:
input_list = [int(each.strip()) for each in input("Enter a list of numbers, comma-separated: ").split(",")]
print("{} are less than 50, {} are more than 50, {} are 50".format(len([each for each in input_list if each<50]),len([each for each in input_list if each>50]),len([each for each in input_list if each==50])))
You'll get there, young padawan :)

def main():
inp = input('enter number of positive numbers to enter ')
print 'enter the list of positive numbers'
num = []
count_eq = 0
count_gr = 0
count_ls = 0
for elem in range(inp):
num.append(input(''))
for item in num:
if item == 50:
count_eq += 1
if item > 50:
count_gr += 1
if item < 50:
count_ls += 1
print '%d are equal %d are less than and %d are greater than 50' % (count_eq, count_ls, count_gr)
main()
This is a very basic program ! You should start python's beginner tutorial here

Related

how can I plan this sequence-1,2,2,3,4,4,5 [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 2 months ago.
Improve this question
I am fairly new to programming and I try to create the above mentioned sequence.
this problem is about having a strict length of elements which always progresses, this progression is inside the list by moving on the indexes. this strict length shifts from a set of indexes to the next one once all the indexes inside the strict length (not passing it's limits) are finished being scanned, and they are scanned in a format of "one after the other".
after all of that we come to the root of the problem:
once the strict length moves to another set, it starts from the last index that was previously, inside of the strict length but in the previous strict length.
the output of the root problem is the title of this post. I don't know how to solve the root problem.
this problem, involves "k" as an exponent of the strict length.
this is the script:
strarr = ["1","2","3","4","5","6","7","8","9","10"]
k = 2
n = 0
while True:
for i in range(k):
print(strarr[n])
n = n+1
print(strarr[n])
the output I got is:
1,2,3,3,4,5,5,6,7,7,8,9,9,10
and I don't know why I got such output, it doesn't seem logical.
As I can understand what you are looking for is to print the even numbers twice.
You can do the following without using a for loop by this way.
strarr = ["1","2","3","4","5","6","7","8","9","10"]
k = 2
n = 0
while (n<10):
if(int(strarr[n])%2 == 0):
print(strarr[n])
print(strarr[n])
elif(int(strarr[n])%2 != 0):
print(strarr[n])
n = n+1
The reason why your code gives that output is because,
for the 1st iteration it would print 1, 2, 3
2nd iteration it would print out 3 again as there is another print(stararr[n]) outside the for loop. That's the reason why you are getting the output you are getting.
strarr = ["1","2","3","4","5","6","7","8","9","10"]
k = 2
n = 0
while True:
for i in range(k):
print(strarr[n])
n = n+1
print(strarr[n])
The error that I think you're seeing has to do with the order that you print your output and update the index n. In the current, buggy code, you're printing first, then updating the value. This means that the second print outside of the inner loop prints using the next value of n, not the one you just used in the inner loop. The same index gets used a second time in the first pass of the inner loop the next time, but that's not the value you wanted to see repeated.
The solution to this issue is pretty simple. Rather than updating after you print, update before. You'll need to adjust the starting value of n, but that's no problem:
strarr = ["1","2","3","4","5","6","7","8","9","10"]
k = 2
n = -1 # change starting index
while True:
for i in range(k):
n = n+1 # and reorder the lines in the inner loop
print(strarr[n])
print(strarr[n])
That said, the two loop thing is a lot more awkward than anything I'd really recommend. If you just want to repeat the odd-indexed values in the loop, you can do that much more simply:
for index in range(len(strarr)):
print(strarr[index])
if index % 2 == 1:
print(strarr[index])
Or you can avoid directly needing to index at all, using enumerate to get the index and value of each element in the for statement itself. This is probably a more "Pythonic" way to solve the problem.
for index, value in enumerate(strarr):
print(value)
if index % 2 == 1:
print(value)

Order of appearance for if/else in list comprehension based on for loop [duplicate]

This question already has answers here:
Is it possible to use 'else' in a list comprehension? [duplicate]
(6 answers)
Closed 2 years ago.
Learning list comprehensions and discovered that if/if-else statement can be placed in different order of apperance in expression.
In example, starting understanding list comprehension construction from for loop schema:
positive = []
for number in numbers:
if int(number) >= 0:
positive.append(int(number))
else:
positive.append(0 - int(number))
can be evaluated to:
positive = [int(number) if int(number) >= 0 else 0 - int(number) for number in numbers]
But
positive = []
for number in number:
if int(number) >= 0:
positive.append(int(number))
goes to:
positive = [int(number) for number in numbers if int(number) >= 0]
I know that one of useful technique for creating list comprehension is to read for loop from top to down and put them in one line (a little shortcut of course).
But why those 2 examples put if / if-else statement once in front and secondly in the end of construction?
In the first case, you're choosing between two options; but in either choice, you're adding to the list. Whatever comes before the for is added to the list.
In the second case, you're only adding to the result list in one option. Whatever comes after the for construct on the right decides if something is added at all.
If you want to pick what's added between (usually two) options, use the first. If you what to pick if something is added at all, use the second.

Why is this code not valid for all the cases? [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 3 years ago.
Improve this question
I am trying to solve this problem on hacker rank:
Here is my code:
L = []
check = True
num_cases = int(input())
for i in range(num_cases):
num_cubes = int(input())
inp = input()
L = inp.split(" ")
for m in range(0, len(L)):
L[m] = int(L[m])
while len(L) != 1:
x = max(L)
if L.count(x) <= 2:
if x == L[0] or x == L[-1]:
while x in L:
L.remove(x)
else:
check = False
break
else:
check = False
break
if check == False:
print("No")
else:
print("Yes")
L = []
check = True
Here I check if the maximum values of the list lie on either end of the list.
This code is working for all the cases that I have given it but works for none of the cases that the website gives it.
Test case 1: Here
Expected solution to test case 1: Here
PS. please inform me if I need to edit my question in any way.
the L.count(x) <= 2 is not correct, as long as it's at either end repeated number are fine e.g. 1 1 1 1 1 1 should be Yes
the while x in L bit is also incorrect, on two fronts
given 2 1 2 1 2 you're going to remove the 2 from the middle of the sequence, which should not be the case
not that this matters because you're also misunderstanding the behaviour of while... else, so this is never going to work either
finally the way you're going at it is extremely inefficient as you're traversing the entire sequence (looking for the max) on every iteration, with a double-ended queue (collections.deque) this can be solved in O(n):
define a "tip of stack" larger than anything possible (e.g. 231 or 232)
check which is the largest of the first or last of the row
if that is larger than your tip of stack, the row is not stackable
otherwise pop it (popleft/pop) and set it as the new tip of stack
then loop around to (2)
alternatively you can first pop the larger end of the row, then check against the current tip, then set as the new tip, same difference:
def solve(cubes):
"""
:param list(int) cubes: cube edge length
:rtype: bool
:returns: whether the input cubes can be stacked
"""
current = 2**32
cubes = collections.deque(cubes)
while cubes:
# pick largest value from either end
if cubes[0] > cubes[-1]:
val = cubes.popleft()
else:
val = cubes.pop()
# found a cube that's larger than the current top of the
# stack, can't solve
if val > current:
return False
current = val
return True
Also note that for this sort of things you might be well-served by:
separating the "parsing" step from the "resolution" step, this lets you more easily feed values and check results
learn about property-testing tools like hypothesis which can automatically generate and reduce test cases as long as you can define a property which should always hold (that's the hardest part)
You should remove if L.count(x) <= 2: , that is one error in your code's logic.

The proper way of using "yield" in this example

I'm trying to demonstrate how yield in Python is used. I want to demonstrate that through an example.
The example will ask the user to enter yes or no, and increase the counter n by 1 every time yes is entered.
The part I want to show how yield works is when the user calls the function again, and getting an updated value of the number of times. For instance, if return was used, and the user runs the script again, it will start from scratch and the number of times would be 1. Rather, I want the user to get 1,2,3,...etc, that is the number of times yes was entered.
The issue here is how to use yield to demonstrate such example. In the code I wrote below, I always get a generator object returned rather than the value of n. How can I get the integer value n returned instead?
def yes_times(answer):
n = 0
if answer == 'yes':
n = n + 1
yield n
answer = raw_input('"yes" or "no": ')
times = yes_times(answer)
print 'You answered yes ' + str(times) + ' times'
Thanks.
I'm trying to demonstrate how yield in Python is used.
... example problem ...
The issue here is how to use yield to demonstrate such example.
You're doing this backwards.
Don't demonstrate how yield is used by picking some arbitrary example, which is unrelated to generator behaviour, and try implementing it using yield.
Instead, choose something that yield is good at, and implement that - ideally with a comparable non-yield implementation so you can show the benefits.
Simple example: toy implementation of range
def naive_range(begin, end):
i = begin
result = []
while i < end:
result.append(i)
i = i + 1
return result
def generate_range(begin, end):
i = begin
while i < end:
yield i
i = i + 1
Now, can you name the drawbacks of the naive implementation? When will it be significantly worse than the generator, and why?
For your example, you can try:
def yes_times(answer = None):
count = 0
while True:
if answer=="yes":
count += 1
answer = yield count
else:
answer = yield count
gen = yes_times()
gen.next()
while True:
answer = raw_input('"yes" or "no": ')
print 'You answered yes ' + str(gen.send(answer)) + ' times'
The problem is that you're trying to use the generator as if it were a function. I strongly recommend that you go through a tutorial on line until you grasp the difference -- after all, that's how I quit making exactly this mistake. :-)
Your statement
times = yes_times(answer)
instantiates the generator, which is what you get when you print. Instead, you need to either use the next function ...
times = next(yes_times(answer))
... or properly employ a generator that does what you need. The general use of a generator is to recognize it as a stream of data, something like
for times in yes_times(answer):
However, this requires that you update your generator to get the input itself.
Is that enough to get you moving?

Project Euler #4 with python. What;s wrong with my code?

I am trying to do project euler problem 4 using python. The problem statement goes like this:
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
I wrote down a solution for it:
s=0
x=100
y=100
list=[]
z=x*y
def palindrome():
while z>=1:
s=s*10+z%10
z=z/10
if z==s:
list.append(z)
while x<=999:
while y<=999:
palindrome()
y=y+1
x=x+1
y=100
print list
It ended up giving an error along the lines of 'z referenced beyond assignment'.
I searched for a solution to this error before finally deciding to use the syntax 'global' to bypass this error.
s=0
x=100
y=100
list=[]
z=x*y
def palindrome():
global z
global s
global x
global y
global list
while z>=1:
s=s*10+z%10
z=z/10
if z==s:
list.append(z)
while x<=999:
while y<=999:
palindrome()
y=y+1
x=x+1
y=100
print list
Now it doesn't give an error, but it gives an empty list as output. I tried to debug the code by inserting print statements in between. The loops appear to work fine, as 'x' and 'y' print all the values they are supposed to. However, I get an empty list as an output to the print list command and 'z' does not apparently change values and is stuck at 100000 despite me using while loops to change the values of x and y.
I am at a loss on how to proceed from here.
The error you got was probably:
UnboundLocalError: local variable 'z' referenced before assignment
This means that z was not defined, at least not within the palindrome() function. Your solution of adding the global keyword is technically correct. However, as others have pointed out already, use of globals makes the code hard to follow.
It's not clear to me what palindrome() is supposed to do. Is it supposed to check if a number is a palindrome? Generate palindrome numbers? To fix this problem, you should think about structuring your code. There are many ways to do this, of course, and with time you will find your own style.
My advice, then, is to think about how you would solve this in general. If you don't know the solution, coding won't help you. Sometimes, when solving problems like this one, I write functions without declaring their bodies. You can do this top-down or bottom-up, both work. For example:
def is_palindrome(n):
""" Check if n is a palindrome number. """
pass
def multiples_of_3_digits():
""" Return all numbers that are the product of two 3-digit numbers ."""
pass
def main():
print max(n for n in multiples_of_3_digits() if is_palindrome(n))
This way you can focus on solving the problem, then on the actual coding. Maybe you will add helper functions or realize you can solve the problem in a more efficient way, but it's a start. Good luck!
min=100
max=999
max_palindrome = 0
for a in range(min,max + 1):
for b in range(a + 1, max + 1):
prod = a*b
if prod > max_palindrome and str(prod)==(str(prod)[::-1]):
max_palindrome = prod
print max_palindrome
Here we are only concerned with the maximum palindrome, and so we don’t spend any time storing other palindromes once they are known to be non-maximum. Also, the if statement first checks if the given product is larger than the maximum known palindrome before using the string cast and list slice to check whether or not the number is even a palindrome. This should speed up our code a bit since the greater than comparison will often fail, regardless of whether the product in question is a palindrome. When we run this, we get the following.
906609
Alternate Way:
I would discourage you to use the global variables because of the reasons pointed out by others. I would also like you to refer to Andre's approach as it will teach you to organize yourself. In this approach too I will be using 2 functions is_palindrome(num) [to check if the number is palindrome or not] and find_max_palindrome [to find the largest palindrome]
def is_palindrome(num):
reversed = 0
original = num
if num < 10:
return True
if num % 10 == 0:
return False
while num >= 1:
reversed = (reversed * 10) + (num % 10)
num = num/10
if original == reversed:
return True
else:
return False
def find_max_palindrome():
max_palindrome = 0
a = 999
b = 999
prod = 0
while a > 99:
b = 999
while b >= a:
prod = a*b
if prod > max_palindrome and is_palindrome(prod):
max_palindrome = prod
b = b -1
a = a - 1
return max_palindrome
print find_max_palindrome()

Categories

Resources