python problem : print the frequencies of each number - python

I have to solve this problem like below manner only,
As you see in output, The only wrong thing in output I get is, 4 and 5 are count two times,
How I can get rid of this, please improvise below code only. do not change the code completely.
n=[1,2,3,4,4,5,5]
i=0
a=0
count=0
while i<len(n):
a=0
count=0
while a<len(n):
if n[i]==n[a]:
count=count+1
a=a+1
print(n[i],"present",count,"times")
i=i+1
output:
1 present 1 times
2 present 1 times
3 present 1 times
4 present 2 times
4 present 2 times
5 present 2 times
5 present 2 times

you can use a Counter to do this efficiently https://docs.python.org/3/library/collections.html#collections.Counter
from collections import Counter
n = [1,2,3,4,4,5,5]
c = Counter(n)
for val, count in c.items():
print(f"{val} present {count} times")
prints:
1 present 1 times
2 present 1 times
3 present 1 times
4 present 2 times
5 present 2 times

I purpose to use set to do so. Does it suit your needs?
n_list = [1,2,3,4,4,5,5]
n_set = set(n_list)
for i in n_set:
print(i, " present ", n_list.count(i), "times")

Sticking to your original code and not the other many ways to solve this using libraries and dictionaries and whatnot.
You can check to see if you the item you are counting has already occurred in the list and skip processing it.
n=[1,2,3,4,4,5,5]
i=0
a=0
count=0
while i<len(n):
a=0
count=0
#check if this value has already been encountered in the list
if n[i] not in n[:i]:
while a<len(n):
if n[i]==n[a]:
count=count+1
a=a+1
print(n[i],"present",count,"times")
i=i+1
If that's too advanced (in the event this is homework). You could create a second list to keep track of the values you've already checked:
n=[1,2,3,4,4,5,5]
i=0
a=0
count=0
n2=[]
while i<len(n):
a=0
count=0
if n[i] not in n2:
while a<len(n):
if n[i]==n[a]:
count=count+1
a=a+1
print(n[i],"present",count,"times")
n2.append(n[i])
i=i+1

in general we should use a for loop if we iterate over a sequence because it's length is known. doing so avoids the need of helper variables. the code for this approach looks more clean and readable (2)
to get rid of the problem of duplicating outputs, we can use a list like seen (1). if a number is not in seen (3), we can print it out. to get the total number of occurrences of the number, we use nums.count(nums) (4). in the step after this, we add the current number used to the list 'seen' (5).
if the number is already in the list 'seen', the loop will take the next number from the input list.
nums = [1,2,3,4,4,5,5]
seen = [] # (1)
for num in nums: # (2)
if num not in seen: # (3)
print(num,"present",nums.count(num),"times") # (4)
seen.append(num) # (5)

Related

Codechef practice problem - Chef and demonetisation

THE QUESTION IS:
In a country called Chef Land, there was a lot of monetary fraud, so Chefu, the head of the country, decided to choose new denominations of the local currency ― all even-valued coins up to an integer N should exist. After a few days, a citizen complained that there was no way to create an odd value, so Chefu decided that he should also introduce coins with value 1. Formally, you are given an integer N; for v=1 and each even positive integer v≤N, coins with value v exist.
You are also given an integer S. To handle transactions quickly, find the minimum number of coins needed to pay a price S.
Input
The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows.
The first and only line of each test case contains two space-separated integers S and N.
Output
For each test case, print a single line containing one integer ― the minimum number of coins.
Constraints
1≤T≤10,000
1≤S≤109
2≤N≤109
N is even
Subtasks
Subtask #1 (100 points): original constraints
Example Input
4
2 2
1 14
30 10
31 4
Example Output
1
1
3
9
MY SOLUTION IS
n=int(input())
res=[]
for i in range(1,n+1):
S,N = [int(x) for x in input().split()]
rem=S%N
if rem == 0:
res.append(int(S/N))
else:
if rem==1:
res.append(int(S/N+1))
else:
if rem/2 == 0:
res.append(int(S/N+1))
else:
res.append(int(S/N+2))
for j in res:
print(j)
Its showing my answer is wrong. Can anyone help me ?
Actually, I was not considering the case of getting 1 as a remainder i.e. in case of numbers like 31,41,51 etc. Which was causing me trouble. Well, after considering the above condition and some little manipulation it finally worked. Hope you understand it. And thank you for your responses.
n=int(input())
res=[]
for i in range(n):
S,N = [int(x) for x in input().split()]
rem=S%N
if S==1:
res.append(int(1))
elif(rem == 0):
res.append(int(S/N))
else:
if(rem%2==0 or rem==1):
res.append(int(S/N+1))
else:
res.append(int(S/N+2))
for j in res:
print(j)

Creating a program that counts the amount of adding the numbers from 1 to 100 (for example: 1+2+3+4+5....and so on), using the WHILE loop

I have a homework to create a program that counts the amount of adding the numbers from 1 to 100 (1+2+3+4+5.....), using the while loop!
I tried the code provided down below! But the problem with it is that I already know the amount, but I need to make the program calculate it!
Code I tried:
amount = 0
while amount <= 5050:
amount += 1
print("The amount is: " + str(amount))
So what you're doing now is adding 1 until you reach 5050. Instead, you want to add the numbers 1 through 100. The solution, then, is to have two variables - one representing the total sum so far (this can be amount), and another representing the number you're adding. You continue to increase the amount you add, for each iteration, until you've added 100 to your running total.
amount = 0
to_add = 1
while to_add <= 100:
amount += to_add
to_add += 1
A more traditional way to do this would be to use a for loop, which can let you iterate over "the list of numbers from 1 through 100" (which you get by using the built-in range() function):
amount = 0
for i in range(1, 101):
amount += i
i=0
sum=0
while i<=100:
sum+=i
i+=1
print(sum)

While loop ignores conditionals (if, else) and just prints first suggested print option

I am trying to create a program that prints out a list of numbers starting at 0 and leading up to a number the user inputs (represented by the variable "number"). I am required to use "while" loops to solve this problem (I already have a functional "for" loop version of the assignment). The program should mark anything in that list divisible by 3 with the word "Fizz," divisible by 5 with the word "Buzz," and anything divisible by both with "FizzBuzz" while also including unlabeled numbers outside of those specifications.
Every time I run this program, it ignores the conditions and just prints the word "FizzBuzz" however many times is represented by the number inputted. (I typically use 15 because it has at least one example of each condition, so that means I get 15 "FizzBuzz"s in a row).
To find out why it was doing that, I used print(i) instead of the rest of the program under the first conditional and it gave me 15 counts of the number 0, so there is reason to believe the program is completely ignoring the range I gave it and just outputting copies of i based on the user number input.
Any help would be appreciated!
number = int(input("Enter a Number"))
i = 0
while(i < number + 1):
if number % 3 == 0 and number % 5 == 0:
print("Fizzbuzz")
elif number % 5 == 0:
print("Buzz")
elif number % 3 == 0:
print("Fizz")
else:
print(number)
i += 1
print ("Done!")
You meant to check the divisibility of i, which increments every loop, not of number which doesn't change.
You also meant to print(i) in the else clause.

Python: Adding odd numbers together from an input

Have a little problem. I'm writing a simple program that takes an input of numbers (for example, 1567) and it adds the odd numbers together as well as lists them in the output. Here is my code:
import math
def oddsum(n):
y=n%10
if(y==0):
return
if(y%2!=0):
oddsum(int(n/10))
print (str(y),end="")
print (" ",end="")
else:
oddsum(int(n/10))
def main():
n=int(input("Enter a value : "))
print("The odd numbers are ",end="")
oddsum(n)
s = 0
while n!=0:
y=n%10
if(y%2!=0):
s += y
n //= 10
print("The sum would be ",end=' ')
print("=",s)
return
main()
It outputs just fine, in the example it will print 1 5 and 7 as the odd numbers. However, when it calculates the sum, it just says "7" instead of 13 like it should be. I can't really understand the logic behind what I'm doing wrong. If anyone could help me out a bit I'd appreciate it :)
I understand it's an issue with the "s += y" as it's just adding the 7 basically, but I'm not sure how to grab the 3 numbers of the output and add them together.
As #Anthony mentions, your code forever stays at 156 since it is an even num.
I would suggest you directly use the string input and loop through each element.
n = input("Enter a value : ") #'1567'
sum_of_input = sum(int(i) for i in n if int(i)%2) #1+5+7=13
[print(i, end="") for i in n if int(i)%2] #prints '157'
Note that int(i)%2 will return 1 if it is odd.
1567 % 10 will return 7. You might want to add the numbers you printed in oddsum to a list, and use the sum function on that list to return the right answer.
The immediate issue is that n only changes if the remainder is odd. eg 1,567 will correctly grab 7 and then n=156. 156 is even, so s fails to increment and n fails to divide by 10, instead sitting forever at 156.
More broadly, why aren't you taking advantage of your function? You're already looping through to figure out if a number is odd. You could add a global parameter (or just keep passing it down) to increment it.
And on a even more efficient scale, you don't need recursion to do this. You could take advantage of python's abilities to do lists. Convert your number (1567) into a string ('1567') and then loop through the string characters:
total = 0
for c in '1567':
c_int = int(c)
if c_int%2!= 0:
total += c_int
print(c)
print(total)

Why does my code return 1 when the given number has more zeroes?

If you have another method that can help me I will appreciate your help, I tried my best to write a code that calculates the number of zeroes in a given number.
Here's the code I tried:
def zrc(n):
count=0
while n%10==0 and n!=0:
n=n%10
count=count+1
return count
print(zrc(2500))
it just gives 1 as output of the code, while it must print 2, but for numbers like 36, it gives 0 as output, what is the problem? I know there must be a problem with that while...
If n%10 is zero, n is zero in the next step, so the condition is always fulfilled after the first loop. You probably want to use // instead of %:
def zrc(n):
count = 0
while n%10 == 0 and n != 0:
n //= 10
count += 1
return count
while n%10==0 and n!=0:
n=n%10
See the above lines. If the condition in the while loop is true, n=n%10 line will be executed.
This line will make your n=0 no matter what. For example,
2500%10 = 0
25000%10 = 0
250000%10 = 0
So, there is no chance that your loop condition will be True during the second iteration, so no chance of increment count variable more than once.
So, no matter what is your n is, you always get the output 1.
In your code, Change this:
n=n%10
To this:
n=n/10
An alternative way, might help you.
from collections import Counter
def zrc(n):
valDict=Counter(str(n))
return valDict['0']
print(zrc(2500))

Categories

Resources