I need to build a program that prints all the numbers between 1 to n, if we have a number that is divisible by 7 print "boom!" instead of a number, if the number has the digit 7, print "boom!" instead and if both print boom-boom!. For example, for n=18:
1
2
3
4
5
6
boom-boom!
8
9
10
11
12
13
boom!
15
16
boom!
18
This is what I did so far, I have almost no experience in coding so I must be doing something wrong here:
n=100
intlst=range(n+1)
strlst=str(range(n+1))
for i in intlst:
print(i)
if i % 7 == 0:
print("boom")
if "7" in strlst:
print("boop")
The modulo works but the string check doesn't. I tried to run it without the modulu part and I just get the normal 1 to 100 print.
If you're new to coding, a good idea is to write down your algorithm in a simple, "pseudocode" language. This way you won't get overwhelmed by weird names and functions. So if I understand correctly, you're looking for something like this:
for each *number* in the range [1,100] do:
if *number* is divisible by 7 and contains the number 7 then print "boom-boom!"
else if *number* has digit 7 in it or is divisible by 7, then print "boom!"
else print *number*
Now all you gotta do is translate this algorithm into python, and realli has beaten me to it ;)
Try this:
n = 100
for i in xrange(1, n + 1):
s = str(i)
if "7" in s and i % 7 == 0:
print "boom-boom!"
elif "7" in s or i % 7 == 0:
print "boom!"
else:
print i
Related
I have this super simple code of FizzBuzz on Python 3 that must work but it doesn't. The output looks like
FizzBuzz
1
2
3
4
Buzz
6
7
8
9
Buzz
11
12
13
14
FizzBuzz
Works for the 5 and 15 but not for the 3. I know I could solve this in other ways but I would like to know what I am missing in this bite.
for i in range(100):
output="";
if i % 3 == 0:
output += "Fizz";
if i % 5 == 0:
output += "Buzz";
else:
output = i
print(output)
The else happens when you hit 3. That is your bug.
This is because the else only applies to the second if.
Maybe you can try replacing the else with if not output:.
The else is only referring to the second if statement. You could change the else to be something like:
if not output:
which is the same as:
if output == "":
This effectively is making sure none of the other two ifs have run.
So I am very new to code and have learnt the basics of python. I am testing out my skills on codeforces by first solving some of their easier problems. I am trying to do 158A on codeforces. I think I have got it because it passed a few tests I assigned. So, I tried submitting it and it told me something about a runtime error. I don't really know what it is so I would like it if someone could tell me what it is and how to fix it in my code. Here is the link to the problem: https://codeforces.com/problemset/problem/158/A
n = int(input())
k = int(input())
b = []
for i in range(n):
a = int(input())
b.append(a)
c = 0
for i in b:
if i >= b[k]:
c = c+1
else:
pass
print(c)
The input you are given is "8 5" and "10 9 8 7 7 7 5 5". That doesn't mean you are given "8" and "5" as two different inputs. It means you have a very long string that contains numbers separated by spaces. You should turn these into a list.
a = input()
n = int(a.split(" ")[0])
k = int(a.split(" ")[1])
a should equal "8 5". We then turn the string into a list using a.split(" "). This will produce ["8", "5"].
In the problem 158A the expected input are:
1. Two numbers (int) separated by a single space, where 1 ≤ k ≤ n ≤ 50
2. n space-separated integers, where ai ≥ ai + 1
There is also a condition: Scores MUST be positive (score>0) so you can advance
This is all you need, I tested it and I got the expected output everytime
a = input("Input n and k: ")
n = int(a.split(" ")[0])
k = int(a.split(" ")[1])
b = input("Input n scores: ")
willAdvance = 0
scores = b.split()
print(scores)
for element in scores:
if int(element) >= int(scores[k-1]) and int(scores[k-1]) > 0:
willAdvance += 1
print(willAdvance)
TEST
Input:
8 5
10 9 8 7 7 7 5 5
Output:
6
Input:
4 6
0 0 0 0
Output:
0
Help! I'm a Python beginner given the assignment of displaying the Collatz Sequence from a user-inputted integer, and displaying the contents in columns and rows. As you may know, the results could be 10 numbers, 30, or 100. I'm supposed to use '\t'. I've tried many variations, but at best, only get a single column. e.g.
def sequence(number):
if number % 2 == 0:
return number // 2
else:
result = number * 3 + 1
return result
n = int(input('Enter any positive integer to see Collatz Sequence:\n'))
while sequence != 1:
n = sequence(int(n))
print('%s\t' % n)
if n == 1:
print('\nThank you! The number 1 is the end of the Collatz Sequence')
break
Which yields a single vertical column, rather than the results being displayed horizontally. Ideally, I'd like to display 10 results left to right, and then go to another line. Thanks for any ideas!
Something like this maybe:
def get_collatz(n):
return [n // 2, n * 3 + 1][n % 2]
while True:
user_input = input("Enter a positive integer: ")
try:
n = int(user_input)
assert n > 1
except (ValueError, AssertionError):
continue
else:
break
sequence = [n]
while True:
last_item = sequence[-1]
if last_item == 1:
break
sequence.append(get_collatz(last_item))
print(*sequence, sep="\t")
Output:
Enter a positive integer: 12
12 6 3 10 5 16 8 4 2 1
>>>
EDIT Trying to keep it similar to your code:
I would change your sequence function to something like this:
def get_collatz(n):
if n % 2 == 0:
return n // 2
return n * 3 + 1
I called it get_collatz because I think that is more descriptive than sequence, it's still not a great name though - if you wanted to be super explicit maybe get_collatz_at_n or something.
Notice, I took the else branch out entirely, since it's not required. If n % 2 == 0, then we return from the function, so either you return in the body of the if or you return one line below - no else necessary.
For the rest, maybe:
last_number = int(input("Enter a positive integer: "))
while last_number != 1:
print(last_number, end="\t")
last_number = get_collatz(last_number)
In Python, print has an optional keyword parameter named end, which by default is \n. It signifies which character should be printed at the very end of a print-statement. By simply changing it to \t, you can print all elements of the sequence on one line, separated by tabs (since each number in the sequence invokes a separate print-statement).
With this approach, however, you'll have to make sure to print the trailing 1 after the while loop has ended, since the loop will terminate as soon as last_number becomes 1, which means the loop won't have a chance to print it.
Another way of printing the sequence (with separating tabs), would be to store the sequence in a list, and then use str.join to create a string out of the list, where each element is separated by some string or character. Of course this requires that all elements in the list are strings to begin with - in this case I'm using map to convert the integers to strings:
result = "\t".join(map(str, [12, 6, 3, 10, 5, 16, 8, 4, 2, 1]))
print(result)
Output:
12 6 3 10 5 16 8 4 2 1
>>>
I was wondering how I could change the following lines of codes to use a while loop instead of a for loop.
for num in range(10):
print(num+1)
It currently prints out the following:
1
2
3
4
5
6
7
8
9
10
Thanks!
start = 0
while start != 10:
start = start + 1
print(start)
hope this hepls
number = 1
while (number <=10):
print 'The number is:', number
number = number + 1
The for loop runs over an iterable, while a while loop runs while a condition is true, so you just need to think of the right condition.
Here, something counting up to 10 will work:
>>> number = 0
>>> while number < 10:
... print(number + 1)
... number += 1
...
1
2
3
4
5
6
7
8
9
10
Writing code that has the same output is not the same as rewriting code to do the same thing. Other answers simply do the former, so this solves the latter:
numbers = range(10)
while numbers:
numbers.pop(0) + 1
The original code iterates over a list that does not exist outside of the loop - it could work with a list of something other than range(10), but it's not necessarily just a '+ 1' operation.
The conditional statement for a while loop, however, needs to be true for the loop to begin so the list should already exist. To keep true to the spirit of the original code, we use range() to create the list, and use pop() to iteratively remove the first element from it.
The differences here are that a variable (numbers) gets used, but is empty after the loop, and we don't rely on list comprehension to iterate, but explicitly remove the first element until 'numbers', being empty, results in a false condition.
well..... a while statement operates UNTIL a certain condition is met, as the for operates for a set of given iterations.
in your case you want to print stuff until num reaches 10, so
while num <= 10 :
print num
num = num + 1
would do
I'm a few weeks into learning python and I am trying to write a script that takes an input of any length of numbers and splits them in one-character lengths. like this:
input:
123456
output:
1 2 3 4 5 6
I need to do this without using strings, and preferably using divmod...
something like this:
s = int(input("enter numbers you want to split:"))
while s > 0:
s, remainder = divmod(s, 10)
I'm not sure how to get the spacing right.
Thank you for the help.
As your priority is to use divmod, you can do it like this:
lst=[]
while s>0:
s, remainder = divmod(s, 10)
lst.append(remainder)
for i in reversed(lst):
print i,
Output:
enter numbers you want to split:123456
1 2 3 4 5 6
You can use join() to achieve that. Cast to string if your are using python 2.*
s = input("enter numbers you want to split:")
s= str(s)
digitlist=list(s)
print " ".join(digitlist)
In case, you are in need of integers, just do it.
intDigitlist=map(int,digitlist)
What about the following using the remainder:
s = 123456
output = []
while s > 0:
s, r = divmod(s, 10)
output.append(r)
fmt='{:<12d}'*len(output)
print fmt.format(*output[::-1])
Output:
1 2 3 4 5 6
This also uses some other useful Python stuff: the list of digits can be reversed (output[::-1]) and formatted into 12-character fields, with the digit aligned on the left ({:<12d}).
Try it with mod:
while x > 0:
x = input
y = x % 10
//add y to list of numbers
x = (int) x / 10
e.g. if x is 123:
123 % 10 is 3 -> you save 3.
the Integer value of 123 / 10 is 12.
Then 12 % 10 is 2 -> you save 2
Int of 12 / 10 is 1.
1 % 10 = 1 -> you save 1
Now you have all numbers. You can invert the list after that to have it like you want.
You can iterate over Python string amd use String.join() to get result:
>>>' '.join(str(input("Enter numbers you want to split: ")))
Enter numbers you want to split: 12345
1 2 3 4 5