Write a program that prints the numbers in the given range. But for multiples of three print "Fizz" instead of the number and for the multiples of five print "Buzz".For numbers which are multiples of both three and five print "FizzBuzz". Print a new line after each string or number.
Input Format:- First line will be the number of testcase, T. Next line will have T integers, denoted by N.
Out Format:- For each testcase, print the number from 1 to N. But follow the rules given in the problem statement.
SAMPLE INPUT 1
2
3 15
This is my code:-
n_input = int(input())
x, y = map(int, input().split(" "))
for i in range(1, x + 1):
if i % 3 == 0 and i % 5 == 0:
print("FizzBuzz", sep="\n")
elif i % 3 == 0:
print("Fizz", sep="\n")
elif i % 5 == 0:
print("Buzz", sep="\n")
else:
print(i, sep="\n")
for i in range(1, y+1):
if i % 3 == 0 and i % 5 == 0:
print("FizzBuzz", sep="\n")
elif i % 3 == 0:
print("Fizz", sep="\n")
elif i % 5 == 0:
print("Buzz", sep="\n")
else:
print(i, sep="\n")
I know my mistake that i have to print according to initial input but i don't know how to fix it.
Thank you
k = int(input()) # useless given what we're doing below
cases = [int(i) for i in input().split()]
for case in cases:
for k in range(1, case + 1):
out = ""
if (k % 3) == 0:
out += "fizz"
if (k % 5) == 0:
out += "buzz"
if out != "":
print(out)
else:
print(k)
The second line is shorthand for
cases = []
for i in input().split():
cases.append(int(i))
Run my Colab notebook
Answer in C#:
A first line is a number of case.
The second line is a value.
Example :
Line1: 3
Line2: 10,55,20
Example 2:
Line1: 4
Line2: 10,55,20, 44
Code:
using System;
class sasikumarv{
public static void Main()
{
var read = Console.ReadLine();
int T= Convert.ToInt32(read);
var line = Console.ReadLine();
var numbers = line.Split(' ');
if(first>=1 && first<=10)
{
for(int cnt=0;cnt<T;cnt++)
{
for(int i = 1; i <= Convert.ToInt32(numbers[cnt]); i++)
{
if (i % 15 == 0)
Console.WriteLine("FizzBuzz" + " ");
else if (i % 3 == 0)
Console.WriteLine("Fizz" + " ");
else if (i % 5 == 0)
Console.WriteLine("Buzz" + " ");
else
Console.WriteLine(i + " ");
}
}
}
}
}
Related
I want to inset new key,value pair into a variable that was not previously defined
Here is what i want to do:
def drawboard(nextmove):
result = nextmove
pos = 1
print result
for i in range(7):
for j in range(7):
if (j == 0 or i % 2 == 0 or j % 2 == 0):
print '*',
if (i % 2 != 0 and j % 2 != 0):
print pos,
pos += 1
if (j == 6):
print '\n'
move = raw_input("Input you move(i.e. x,3[position, your symbol]: ")
if move == 'q':
exit()
calcres(move)
def calcres(move):
nextmove = dict([move.split(',')])
drawboard(nextmove)
drawboard({0: 0})
Inside drawboard function i want to concatenate nextmove with result, and save all the moves inside the result finally. I tried initializing result = {} but as expected that removes all items from result and re-initializes it resulting only one item inside that dictionary.
Use setdefault to initialize the result dictionary value to an empty list whenever the key is not present
def drawboard(nextmove):
result.setdefault(nextmove[0],[]).append(nextmove[1])
pos = 1
#print result
for i in range(7):
for j in range(7):
if (j == 0 or i % 2 == 0 or j % 2 == 0):
print '*',
if (i % 2 != 0 and j % 2 != 0):
print pos,
pos += 1
if (j == 6):
print '\n'
move = raw_input("Input you move(i.e. x,3[position, your symbol]: ")
if move == 'q':
exit()
calcres(move)
def calcres(move):
nextmove = move.split(',')
drawboard(nextmove)
result = {}
drawboard([0,0])
I dont know why the error is coming up. Its a program to show the numbers that include a 7 and are a multiple of 7.
import sys
Numbers = raw_input()
Answer = 0
NumbersList = Numbers.split()
Length = len(NumbersList)
for num in range(0, Length):
N = NumbersList [num-1]
ListNumber = list(str(N))
if (N == 0):
print(Answer)
elif (num == Length):
print(Answer)
elif (N % 7 == 0):
Answer = Answer + 1
elif 7 in ListNumber:
Answer = Answer + 1
sys.stdout.flush()
New Question. My elif statement at the bottom doesnt seem to work.
The input is a list of numbers from 0-100. Stop at a 0. Answer = Numbers with %7 = 0 or with a 7 in it
import sys
Numbers = raw_input()
Answer = 0
NumbersList = Numbers.split()
Length = len(NumbersList)
for num in range(0, Length):
N = NumbersList [num]
ListNumber = list(str(N))
if (int(N) == 0):
print(Answer)
break
elif (num == Length):
if (int(N) % 7 == 0):
Answer = Answer + 1
elif 7 in ListNumber:
Answer = Answer + 1
print(Answer)
elif (int(N) % 7 == 0):
Answer = Answer + 1
elif 7 in ListNumber:
Answer = Answer + 1
sys.stdout.flush()
Stealing #PeterWood's comment, you need to convert the input to an integer first.
N = int( NumbersList [num-1] )
You may also want to consider using for num in NumberList and reading https://www.python.org/dev/peps/pep-0008/ for a guide to good practice.
This works for me (or doesn't error):
import sys
Numbers = raw_input()
Answer = 0
NumbersList = Numbers.split()
Length = len(NumbersList)
for num in range(0, Length):
N = int( NumbersList [num-1])
ListNumber = list(str(N))
if (N == 0):
print(Answer)
elif (num == Length):
print(Answer)
elif (N % 7 == 0):
Answer = Answer + 1
elif 7 in ListNumber:
Answer = Answer + 1
print Answer
sys.stdout.flush()
how can i make my code to ask user if wants to input another number? I could barely make my code run without errors, i am a toddler at python. I struggled a lot to write the code below. I know that stackoverflow is not a code writing service. But my little brain hurts now and i can't continue without help. I want to say simply "Do you want to convert another number?"
import math
# Global definition
#Base = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F]
Base = [str (x) for x in range (10)] + [chr (x) for x in range (ord ('A'), ord ('A') +6)]
h=[str(i) for i in range(10)]+["A","B","C","D","E","F"]
def BIN2DEC (string_num):
num = string_num
if num == 0:
return '0'
bin_str = ''
while num > 0:
bin_str = str(num % 2) + bin_str
num = num / 2
return bin_str
def HEX2DEC (string_num):
return str (int (string_num.upper (), 16))
# Dec2bin
# Decimal to binary
def dec2bin (string_num):
num = int (string_num)
mid = []
while True:
if num == 0: break
num, rem = divmod (num, 2)
mid.append (Base [rem])
return''. join ([str (x) for x in mid [:: -1]])
# Dec2hex
# Decimal to hexadecimal
def DEC2HEX (number):
n = long(number ,16)
if (n < 0):
print(0)
elif (n<=1):
print n,
else:
DEC2HEX( n / 16 )
x =(n%16)
if (x < 10):
print(x),
if (x == 10):
print("A"),
if (x == 11):
print("B"),
if (x == 12):
print("C"),
if (x == 13):
print("D"),
if (x == 14):
print("E"),
if (x == 15):
print ("F"),
# Hex2tobin
#The hexadecimal to bry
def HEX2BIN (hex_string):
s = int(hex_string, 16)
num_digits = int(math.ceil(math.log(s) / math.log(2)))
digit_lst = ['0'] * num_digits
idx = num_digits
while s > 0:
idx -= 1
if s % 2 == 1: digit_lst[idx] = '1'
s = s / 2
return ''.join(digit_lst)
# Bin2hex
# Binary to hexadecimal
def BIN2HEX (string_num):
return DEC2HEX (BIN2DEC (string_num))
my_num = 0
my_num = raw_input("Insert binary,decimal or hexadecimal:")
while(my_num != 0):
if my_num[0:2] == "0x" or my_num[0] == "x":
print HEX2BIN(my_num)
print HEX2DEC(my_num)
break
elif my_num[0:2] == "0b" or my_num[0] == "b" and all(x in "01" for x in my_num):
print""
print BIN2HEX(my_num)
print BIN2DEC(my_num)
break
else:
print dec2bin(my_num)
print HEX2BIN(my_num)
print long(my_num)
break
my_num = 0
my_num = raw_input(":")
print list(iter(lambda:raw_input("Enter Value, or 'q' to quit:"),"q"))
is my personal favorite way
iter makes an iterator (you need to look it up)
it takes an optional no-argument function that it will continually call until it receives the second argument
I have a program that is supposed to ask how many primes to calculate then write them all to a text file. However, it creates the file then dosen't run.
def constantcall():
j = 2
chk = 1
f = open("primes.txt", "w")
primes = []
notprimes = []
ask = input("how many primes? ")
while len(primes) < int(ask):
k = 2
while not(k==j) and not(j%k==0):
k = k + 1
if k == j:
primes.append(j)
f.write(str(j)+"\n")
else:
notprimes.append(j)
if len(primes) >= 1000*chk:
chk = chk + 1
print("There have been " + str(len(primes)) + " primes counted so far")
j = j + 1
print("Primes written to file 'primes.txt', " + str(len(primes)) + " written")
f.close
return(" ")
if __name__ == '__main__':
while(True):
constantcall()
Your problem is the code:
while len(primes) < int(ask):
k = 2
at this point len(primes) is less than int(ask), and there is nothing that add items to primes, so infinite loop.
Your code must be (in order to avoid infinite loop):
def constantcall():
j = 2
chk = 1
f = open("primes.txt", "w")
primes = []
notprimes = []
ask = input("how many primes? ")
while len(primes) < int(ask):
k = 2
while not(k==j) and not(j%k==0):
k = k + 1
if k == j:
primes.append(j)
f.write(str(j)+"\n")
else:
notprimes.append(j)
if len(primes) >= 1000*chk:
chk = chk + 1
print("There have been " + str(len(primes)) + " primes counted so far")
j = j + 1
print("Primes written to file 'primes.txt', " + str(len(primes)) + " written")
f.close
return(" ")
if __name__ == '__main__':
constantcall()
Using Sieve of Eratosthenes algorithm
You could use the algorithm Sieve of Eratosthenes:
def primes(count):
"""
Returns a list with the first `count` prime numbers.
An advice: If you will be using this functiona a lot it's better
for performance if you precalculate cribe.
"""
# Calculate primes up to 50, you can change this to your preference.
MAX = 50
sieve = [1] * MAX
for i in range(2, int(MAX ** 0.5) + 2 ):
for j in range(i + i, MAX, i):
sieve[j] = 0
# Finally primes are indexes in the list that still has 0.
result = []
for index, elem in enumerate(sieve):
if elem == 1: result.append(index)
return result[1:count + 1]
Your code can then be rewrited as:
def constantcall():
f = open("primes.txt", "w")
ask = int(input("how many primes? "))
prime_numbers = primes(ask)
f.writelines(map(lambda x: "{0}\n".format(x), prime_numbers))
if __name__ == '__main__':
constantcall()
Your code does nothing.
while len(primes) < int(ask):
k = 2
Is useless.
while not(k==j) and not(j%k==0):
k = k + 1
Is useless as j is always 2.
if k == j:
primes.append(j)
f.write(str(j)+"\n")
else:
notprimes.append(j)
Here you append 2 to primes once.
if len(primes) >= 1000*chk:
chk = chk + 1
print("There have been " + str(len(primes)) + " primes counted so far")
j = j + 1
print("Primes written to file 'primes.txt', " + str(len(primes)) + " written")
f.close()
return
So len(primes) is always 1.
Here is a solution. Sorry for C language, but you could easily pythonize it.
#include <stdio.h>
typedef unsigned long long ull;
int main(){
ull numb=10000,stop=20000;
ull i,c;
int cnt;
printf("Here are the primes between %lld and %lld :\n\n",numb,stop);
while(numb<=stop){
for(i=1;i<=numb;++i){
if(!(numb%i)) ++cnt;
}
if ((cnt==2) || (i==1)) printf("%lld; ",numb);
cnt=0;
++numb;
}
printf("\n\nThat's all\n");
}
MyFunctions file file -
def factList(p,n1):
counter = 1
while counter <= n1:
if n1 % counter == 0:
p.append(counter)
counter = counter + 1
def isPrime(lst1,nbr):
factList(lst1, nbr)
if len(lst1) == 2:
return True
else:
return False
def nextPrime(nbr1):
cnt1 = 1
while cnt1 == 1:
nbr1 == nbr1 + 1
if isPrime(lst2,nbr1):
cnt1 = 0
Filetester file -
nbr1 = 13
nextPrime(nbr1)
print nbr1
My isPrime function already works I'm tring to use my isPrime function for my nextPrime function, when I run this I get
">>>
13
" (when using 13)
">>> " (When using 14)
I am supposed to get 17 not 13. And if I change it to a composite number in function tester it gets back in a infinite loop. Please only use simple functions (the ones I have used in my code).
This is NOT the right way to do this, but this is the closest adaptation of your code that I could do:
def list_factors_pythonic(number):
"""For a given number, return a list of factors."""
factors = []
for x in range(1, number + 1):
if number % x == 0:
factors.append(x)
return factors
def list_factors(number):
"""Alternate list_factors implementation."""
factors = []
counter = 1
while counter <= number:
if number % counter == 0:
factors.append(counter)
return factors
def is_prime(number):
"""Return true if the number is a prime, else false."""
return len(list_factors(number)) == 2
def next_prime(number):
"""Return the next prime."""
next_number = number + 1
while not is_prime(next_number):
next_number += 1
return next_number
This would be helpful:
def nextPrime(number):
for i in range(2,number):
if number%i == 0:
return False
sqr=i*i
if sqr>number:
break
return True
number = int(input("Enter the num: ")) + 1
while(True):
res=nextPrime(number)
if res:
print("The next number number is: ",number)
break
number += 1
I don't know python but if it's anything like C then you are not assigning anything to your variables, merely testing for equality.
while cnt1 == 1:
nbr1 == nbr1 + 1
if isPrime(lst2,nbr1):
cnt1 == cnt1 + 1
Should become
while cnt1 == 1:
nbr1 = nbr1 + 1 << changed here
if isPrime(lst2,nbr1):
cnt1 = cnt1 + 1 << and here
Well this code help you
n=int(input())
p=n+1
while(p>n):
c=0
for i in range(2,p):
if(p%i==0):
break
else:c+=1
if(c>=p-2):
print(p)
break
p+=1
this code optimized for finding sudden next prime number of a given number.it takes about 6.750761032104492 seconds
def k(x):
return pow(2,x-1,x)==1
n=int(input())+1
while(1):
if k(n)==True:
print(n)
break
n=n+1