While Loop Print List formatting - python

I wanted to create a list of factors from any given number only using the formula below. I am not allowed to use list therefore, I have imitate using strings as follows:
for example and lets say we choose num=12:
def factors(num):
i=1
while i <= num :
if num % i == 0:
print i
i = i + 1
this code prints:
1
2
3
4
6
12
Without using lists, for loops, int, function and can only use strings,
how do i format the loop outputs to make it look like this?:
[1, 2, 3, 4 ,6 ,12]
I tried doing this first:
num = 12
i = 1
while i <= num :
if num % i == 0:
a=str("[")+str(i)+", "+str("]")
print a
i = i + 1
This prints:
[1, ]
[2, ]
[3, ]
[4, ]
[6, ]
[12, ]
Can anyone help or suggest where I can put that print state or how do i modify it? Thanks!

def factors(num):
i=1
result="["
while i <= num :
if num % i == 0:
result=result+str(i)+","
i+=i
result=result[:-1]+"]"
print result
factors(12)
Output > [1,2,4]

you can use use a print statement that ends with a comma to not insert a new line when a second print statement is used then you just need to make sure the first time in prints "[" and the last time it prints "]"
for example
print "hello ",
print "world"
would return >>>hello world
the code would look something like this
def factors(num):
i=1
while i <= num :
if i == 1:
if num % i == 0:
print "[",
else:
print "[",
if i == num:
print "%s]"%(i)
elif num % i == 0:
if i == num:
print i,"]"
else:
print "%s,"%(i),
i = i + 1

You can concatenate each str(i) to string a by +=,
def factors(num):
i = 1
a = "["
while i < num :
if num % i == 0:
a+=str(i)+", "
i = i + 1
print(a + str(num) + str("]"))
factors(12)
Output:
[1, 2, 3, 4, 6, 12]

def factors(num):
i = 1
factors = []
while i <= num:
if num % i == 0:
factors.append(i)
i += 1
print factors
factors(12)
This adds all the factors to a table called factors, and then when all the factors are added, the table factors is printed out.

Related

i want to break the loop when there string in the list python

lst1 = [1,2,3,4,5,"hello",6,7,8,9,]
countodd = 0
counteven = 0
for i in range(len(lst1)):
if i%2 != 0:
countodd += 1
else:
counteven += 1
else:
type(lst1) == str:
break
print("this is string!!")
print("this counter of even numbers:",counteven)
print("this counter of odd numbers:",countodd)
Create a python program that will count the number of appearances of odd and even values in a list. In case that the program encounters a string use break statement and return a print that says, “It’s a string!!!” and nullify the values of odd and even numbers counters.
As you said, break the loop once you find a string, and nullify the counters:
for i in range(len(lst1)):
if isinstance(lst1[i], str):
print("It’s a string!!!")
countodd = 0 # or None
counteven = 0 # or None
break
.
.
.
lst1 = [1, 2, 3, 4, 5, "hello", 6, 7, 8, 9, ]
countodd = 0
counteven = 0
# no need to do range(len(lst1)) to iterate
for i in lst1:
if isinstance(i, str):
print("this is string!!")
countodd = 0
counteven = 0
break
if i % 2 != 0:
countodd += 1
else:
counteven += 1
print("this counter of even numbers:", counteven)
print("this counter of odd numbers:", countodd)

Python : Using while loop 1-100 even number and sort 3 number on 1 line

i'm got the code using while loop 1-100 result output is even number and sorting 3 number on 1 line.
My code:
i = 1
a = 100
n = ''
while i <= a :
if i % 2 == 0:
n = n + str(i)
if i < 100 :
n = n + ','
i += 1
print(n)
How to do the result display is
2, 4, 6,
8, 10, 12,
14, 16, 18,
....
98, 100
What you can do is add another condition where you check if i is the last element of your row. If so, append \n which results in a new line
i = 1
a = 100
n = ''
while i <= a:
if i % 2 == 0:
n += str(i)
if i < 100:
n += ','
# needs to be added last
if i % 6 == 0:
n += '\n'
i += 1
print(n)
since you want 6 to be the last index, when i=6,i%6 will result in 0.
The percent symbol works as a Modulo/remainder.
Note: make sure you have the right indentations, it seemed the code inside your while had an extra indent.

Get a list of prime numbers in python 3

Beginner. I'm trying to return a list that includes all the prime numbers from 0 to num. Could someone please help me find what's wrong with my code? I always get an empty list. Thanks a lot! (I'm using python 3.6)
def task(num):
num = int(num)
lst = []
if num < 3:
return lst
else:
for i in range(3,num):
if not i & 1:
lst = lst
else:
primetest = range(3, int(i ** 0.5) + 1, 2)
for n in primetest:
if i % n != 0:
lst.append(i)
return lst
task(5)
Updates:
Thank you guys for all your comments! Really helpful.
This is what my revised code looks like.
def task(num):
num = int(num)
lst = []
if num < 2:
return lst
if num >= 2:
lst.append(2)
for i in range(3, num + 1):
if i % 2 == 1:
switch = True
for n in range(3, int(i ** 0.5) + 1, 2):
if i % n == 0:
switch = False
break
if switch:
lst.append(i)
return lst
The main problem lies with your inner for loop :
With your code you will append the list with i each time you find a number in the primetestrange that is not a divisor of i.
You might want to use a boolean here to store the fact that you found a divisor of i, then only append it to the list if you didn't.
To answer your question, your list is empty because the primetestrange is always empty in your example :
int(3**0.5) + 1 = 3 and int(5**0.5) + 1 = 3
range(3,3,2) = []
The array is empty because the range function will not include the upper limit, and since the inner loop is not doing what it should be expected to do in your code, the result will be an empty list until the parameter of the task function is superior or equal to 9
Your code gets it wrong on several counts, tell me if you understand why the following works?
def task(num):
num = int(num)
lst = [2]
if num < 3:
return lst
for i in range(3, num + 1):
if i % 2 == 1:
for n in range(3, int(i ** 0.5) + 1, 2):
if i % n == 0:
break
else:
lst.append(i)
return lst
(note: the for else clause is quite natural here, for else clauses are used when you search for something in a loop, you break when you find that something, if not break is encountered and the regular stopIteration is used to exit the loop the else part is performed, I say it is natural here since in pseudo code you would say something like "if my number can be divided by another number less than its square it is not prime, otherwise add it to the list of primes" see http://book.pythontips.com/en/latest/for_-_else.html for more detauls)
Its by no means a fast way to do it but I tried to stay as close to the spirit of your attempt while improving the aesthetics of the code
you can find prime numbers and the most dividable one in a dateset.`
a=[ int(x) for x in input("Enter 10 values: ").split() ]
c=[]
prime=[]
b=max(a)
for num in range(1,b+1):
for i in range(2,num):
if (num%i)==0:
break
else:
prime.append(num)
for i in a:
for j in prime:
if i%j==0:
c.append(i)
from collections import Counter
e=Counter(c)
f=e.most_common(1)
f
def prim(z):
lst = []
for i in range(2, z+1):
for j in range(2,i):
if i % j == 0:
break
else:
lst = lst + [i]
return lst
print(prim(20))
result:
[2, 3, 5, 7, 11, 13, 17, 19]

sum of the product of even positioned digits

I have attempted this problem like this :
a = input("Enter number : ")
s = 3
w = 1
while a>0:
digit=a%10
if n%2 == 0:
p = p*digit
else:
s = s+digit
a=a/10
n=n+1
print "The sum is",s
it works perfectly for even no of digits but for odd no of digits like for 234 it shows the sum as 6 and product 3
No explicit loop:
import operator
from functools import reduce # in Python 3 reduce is part of functools
a = input("Enter number : ")
lst = [int(digit) for digit in a]
add = sum(lst[1::2])
mul = reduce(operator.mul, lst[::2],1)
print("add =",add,"mul =",mul,"result =",add+mul)
Producing:
Enter number : 234
add = 3 mul = 8 result = 11
You have to start with n = 0 for this to work
a = int(input("Enter number"))
s = 0
p = 1
n = 0
while a>0:
digit=a%10
if n%2 == 0:
p *= digit
else:
s += digit
a /= 10
n += 1
print "The sum is",s
print "Product is",p
Easy mistake to make about the numbering. The first item of any string, list or array is always index 0. For example, be careful in future to take away 1 from the value returned from len(list) if you are iterating through a list's items with a for loop e.g.
for x in range(len(list)-1):
#your code using list[x]
Here's the mathematical version:
n = input('Enter a number: ')
digits = []
while n > 0:
digits.append(n%10)
n //= 10
s = 0
p = 1
i = 0
for digit in reversed(digits):
if i%2 == 0:
s += digit
else:
p *= digit
i += 1
print 'Sum of even digits:', s
print 'Product of odd digits:', p
print 'Answer:', s+p
I have tried to make this as simple as possible for you.
Here's a function that does the same thing:
def foo(n):
s = 0
p = 1
for i, digit in enumerate(str(n)):
if i%2 == 0:
s += digit
else:
p *= digit
return s+p
def foo(num):
lst = [int(digit) for digit in str(num)]
mul, add = 1, 0
for idx, val in enumerate(lst):
if not idx % 2:
mul *= val
else:
add += val
return add, mul
And using it:
>>> foo(1234)
(6, 3)
>>> foo(234)
(3, 8)
This function will take an integer or a string representation of an integer and split it into a list of ints. It will then use enumerate to iterate over the list and preform the required operations. It returns a 2 element tuple.

Trying to turn fizzbuzz into a function in python 3

I have only just started to learn python as my first language and whilst i worked out the code for fizzbuzz, i cannot for the life of me get it to do the items below. I also want it to print horizontally instead of vertically. Any help would be great (heads spinning).
Create a function which does this.
For example
fizzbuzz(20)
would print
1,2,fizz,4,buzz,fizz,7,8,fizz,buzz,11,fizz,13,14,fizzbuzz,16,17,fizz,19,buzz
def fizzbuzz(n):
for x in range (101):
if x%3==0 and x%5==0:
print("fizz buzz")
elif x%3==0:
print('fizz')
elif x%5==0:
print('buzz')
else:
print (x)
def main():
print(fizzbuzz(20))
Shorter yet:
for n in range(100):
print("Fizz"*(not n % 3) + "Buzz"*(not n % 5) or n)
Yes, but why?
To understand this, let's look at the parts separately.
"Fizz"*(not n % 3)
In Python, we can "multiply" strings, so "a"*3 would result in "aaa". You can also multiply a string with a boolean: "a" * True is "a", whereas "a" * False is an empty string, "". That's what's happening to our "Fizz" here. When n % 3 == 0 (ie. n is 3, 6, 9, ...), then not n % 3 will be the same as not 0, which is True. Conversely, when n is 1, 2, 4, 5, 7, ... then n % 3 will be either 1 or 2, and not n % 3 will be false. In Other words, whenever n is divisible by 3, the term "Fizz"*(not n % 3) will multiply the string "Fizz" by True, and when it's not, it will multiply by False, resulting in an empty string.
The same logic applies to the next part, "Buzz"*(not n % 5). It'll give us an empty string when n is not divisible by 5, and the string "Buzz" when it is.
Now we're adding those two things together:
"Fizz"*(not n % 3) + "Buzz"*(not n % 5)
When n is neither divisible by 3 nor 5, this will be adding two empty strings together (ie. "" + ""), which will of course give us another empty string. In that case, the whole print statement reads print("" or n). Since an empty string is False-y, it will print our number n. If n is divisible by 3 (but not 5), this would be print("Fizz" or n), and since "Fizz" is Truthy, it will just print that and omit the number.
Bonus points
Or, if you really want to impress your interviewer,
for n in range(100):
print("FizzBuzz"[n%-3&4:12&8-(n%-5&4)] or n)
Collect the items into a list. Then print the list at the end of function. You can join the items together with a comma in between using ', '.join(...).
def fizzbuzz(n):
result = []
for x in range(1, n+1):
if x % 3 == 0 and x % 5 == 0:
result.append("fizz buzz")
elif x % 3 == 0:
result.append('fizz')
elif x % 5 == 0:
result.append('buzz')
else:
result.append(str(x))
return result
def main():
print(', '.join(fizzbuzz(20)))
main()
It's good to also know that print(..., end=', ') would print "horizontally" with a comma and space at the end, and this would almost solve your problem except that the very last item would also have a comma and space at the end, which is not what you desire.
It's usually a good idea to (1) separate printing from computing, (2) make functions reusable. You often want to compute more frequently than print. In the future you may wish to pass the computation on to some other function before you print. So functions that immediate print are not as useful. So I recommend taking the print statements out of fizzbuzz.
You could return the string ', '.join(result), but how useful would that be? The list result might be (in the future) more useful for further processing, so I chose to return result. The printing I left for the main function.
def fizzbuzz(numbers, fizz, buzz):
x = ['Fizzbuzz' if x % fizz == 0 and x % buzz == 0 else 'Fizz' if x % fizz == 0 else 'Buzz' if x % buzz == 0 else x for x in numbers]
return x
Slightly more elegant
def fizzbuzz(n):
for x in range(1,n+1):
if not x % 15:
yield 'fizz buzz'
elif not x % 3:
yield 'fizz'
elif not x % 5:
yield 'buzz'
else:
yield x
if __name__ == "__main__":
print ','.join(fizzbuzz(20))
I'm a novice coder so some of the answers I did not understand or it did not seems to directly apply to my problem. This answer incorporates Fizz_Buzz as a variable and the range of x is determined by the user. I looked at the above solutions and came up with this:
def Fizz_Buzz(x):
for x in range (0,x):
if x % 3 == 0 and x % 5 == 0:
print('FizzBuzz')
elif x % 3 == 0:
print('Fizz')
elif x % 5 == 0:
print ('Buzz')
else:
print (x)
You can add end=', ' to print in order to print on the same line, with whatever character you want separating the values.
class FizzBuzz:
#staticmethod
def fizz_buzz(n):
if n % 15 == 0:
return 'FizzBuzz'
elif n % 3 == 0:
return 'Fizz'
elif n % 5 == 0:
return 'Buzz'
else:
return str(n)
def __str__(self, rng):
[print(self.fizz_buzz(n), end=', ') for n in range(1, rng + 1)]
But it leaves , at the end. Instead:
def __str__(self, rng):
print(', '.join(self.fizz_buzz(n) for n in range(1, rng + 1)))
one more :) just for fun :)
get_index = lambda i: bool(i%3)+2*bool(i%5) if i !=0 else 3
afb = lambda x: ('fizzbuzz','buzz', 'fizz', str(x))[get_index(x)]
fizzbuzz = lambda inpt: print(','.join([ afb(i) for i in inpt ]))
fizzbuzz(range(101))
'0,1,2,fizz,4,buzz,fizz,7,8,fizz,buzz,11,fizz,13,14,fizzbuzz,16,17,fizz,19,buzz,fizz,22,23,fizz,buzz,26,fizz,28,29,fizzbuzz,31,32,fizz,34,buzz,fizz,37,38,fizz,buzz,41,fizz,43,44,fizzbuzz,46,47,fizz,49,buzz,fizz,52,53,fizz,buzz,56,fizz,58,59,fizzbuzz,61,62,fizz,64,buzz,fizz,67,68,fizz,buzz,71,fizz,73,74,fizzbuzz,76,77,fizz,79,buzz,fizz,82,83,fizz,buzz,86,fizz,88,89,fizzbuzz,91,92,fizz,94,buzz,fizz,97,98,fizz,buzz'
i made a fizzbuzz that works for any number and words, so you can do fizzbuzzfuzz if you wanted. i made it in 6 lines (7 if you count the line that runs through the fizzfuzz)
def f(n:int,m:list,w:list):
s=''
for x in m:
if n%x==0: s+=w[m.index(x)]
if s=='': s=n
return s
for i in range(1, 100 +1): print(f(i,[3,5],['Fizz','Buzz']))
def fizzbuzz(num):
if x % 3 == 0 and x % 5 == 0:
return "Fizz Buzz"
elif x % 3 == 0:
return "Fizz"
elif x % 5 == 0:
return "Buzz"
else:
return x
MAXNUM = 100
for x in range (MAXNUM):
print fizzbuzz(x)
I've found the following works well (Python 3):
def fizzbuzz():
for i in range(1,101):
print("Fizz"*(i%3==0)+"Buzz"*(i%5==0) or i)
print (fizzbuzz())
Here's a fun one (obviously not the best for readability, but still kinda fun to think about list comprehensions):
def fizzBuzz():
print(", ".join(["FizzBuzz" if x%15==0 else "Fizz" if x%3 == 0 else "Buzz" if x%5==0 else str(x) for x in range(1,101)]))
Don't forget, 3 and 5 are coprime! So you can check x % 15 instead of (x % 3 and x % 5) for "FizzBuzz".
Yet another one with list comprehension and Python3
def is_mod_zero(num, *div):
return not [d for d in div if num % d is not 0]
def fizz_buzz(num):
if is_mod_zero(num, 3, 5):
return 'FizzBuzz'
if is_mod_zero(num, 3):
return 'Fizz'
if is_mod_zero(num, 5):
return 'Buzz'
return num
if __name__ == "__main__":
for i in range(100):
print(fizz_buzz(i))
def fizzBuzz(n):
for x in range(1, n + 1):
if x % 3 == 0 and x % 5 == 0:
print("fizzbuzz")
elif x % 3 == 0:
print("fizz")
elif x % 5 == 0:
print("buzz")
else:
print(x)
print(fizzBuzz(50))

Categories