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
Related
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'm solving this HackerRank challenge:
Alice has a binary string. She thinks a binary string is beautiful if and only if it doesn't contain the substring '010'.
In one step, Alice can change a 0 to a 1 or vice versa. Count and print the minimum number of steps needed to make Alice see the string as beautiful.
So basically count the number of '010' occurrences in the string 'b' passed to the function.
I want to increment i by 2 once the if statement is true so that I don't include overlapping '010' strings in my count.
And I do realize that I can just use the count method but I wanna know why my code isn't working the way I want to it to.
def beautifulBinaryString(b):
count = 0
for i in range(len(b)-2):
if b[i:i+3]=='010':
count+=1
i+=2
return count
Input: 0101010
Expected Output: 2
Output I get w/ this code: 3
You are counting overlapping sequences. For your input 0101010 you find 010 three times, but the middle 010 overlaps with the outer two 010 sequences:
0101010
--- ---
---
You can't increment i in a for loop, because the for loop construct sets i at the top. Giving i a different value inside the loop body doesn't change this.
Don't use a for loop; you could use a while loop:
def beautifulBinaryString(b):
count = 0
i = 0
while i < len(b) - 2:
if b[i:i+3]=='010':
count += 1
i += 2
i += 1
return count
A simpler solution is to just use b.count("010"), as you stated.
If you want to do it using a for loop, you can add a delta variable to keep track of the number of positions that you have to jump over the current i value.
def beautifulBinaryString(b):
count = 0
delta = 0
for i in range(len(b)-2):
try:
if b[i+delta:i+delta+3]=='010':
count+=1
delta=delta+2
except IndexError:
break
return count
You don't need to count the occurrences; as soon as you find one occurrence, the string is "ugly". If you never find one, it's beautiful.
def is_beautiful(b):
for i in range(len(b) - 2):
if b[i:i+3] == '010':
return False
return True
You can also avoid the slicing by simply keeping track of whether you've started to see 010:
seen_0 = False
seen_01 = False
for c in b:
if seen_01 and c == '0':
return False
elif seen_1 and c == '1':
seen_01 = True
elif c == '0':
seen_0 = True
else:
# c == 1, but it doesn't follow a 0
seen_0 = False
seen_01 = False
return True
I'm searching to make a loop to go throw samples till I reach the result. Example:
i=(list(np.random.randint(2, size=5)),list(np.random.randint(2, size=2)),list(np.random.randint(2, size=7)),list(np.random.randint(2, size=7)),list(np.random.randint(2, size=9)),list(np.random.randint(2, size=8)),list(np.random.randint(2, size=7)))
tot=0
for j in range(0,len(anytable)):
if resp(i,(anytable.iloc[j,0:7].tolist())): #this function "resp" gives me True and False and add 1 to variable "tot"
tot=tot+1
Now I want to stop till I have to tot>=100 .
So I have to generate many "i" samples lists till I get to tot>=100.
How can I do this?
Thank you very much
From guessing I would say, this could be your solution.
j, tot = 1, 1
while j<len(anytable) and tot<100 :
tot += int( resp(i,(anytable.iloc[j,0:7].tolist())) )
j += 1
The condition is false if one of the inequations is false. The incementing operator += on tot is adding the integer representation of a boolean True = 1 or False = 0 to the value of tot.
I have a 2-D 6x6 array, A.
I want its values to be input by the user in the following format or example:
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
where the 0's indicate the places where the user would write their values.
This is my code. It returns an error in split().
def arr_input(x):
for i in range(6):
for j in range(6):
n = int(input().split(' '))
if n>=-9 and n<=9:
x[i][j] = n
print "\n"
I don't want input in a single line. Please help!
EDIT 1
The code I needed was already provided :D. Nevertheless, I learned something new and helpful. Here is the existing code to do the task I wanted:
arr = []
for arr_i in xrange(6):
arr_temp = map(int,raw_input().strip().split(' '))
arr.append(arr_temp)
First of all, you are using input() which returns int when you enter numbers in terminal. You should use raw_input() and get it line by line.
Second, you are trying to convert a list to integer, you should loop through the list values, convert and insert on the resulting list.
Fixed code:
def arr_input(x):
for i in range(6):
num_list = raw_input().split(' ')
for j, str_num in enumerate(num_list):
n = int(str_num)
if n >= -9 and n <= 9:
x[i][j] = n
print "\n"
Here, I used enumerate() to loop though the number list by getting its index each iteration.
There's an inconsistency in how you're treating the input. In python 2.7, the input() function is designed to read one, and only one, argument from stdin.
I'm not exactly sure which way you're trying to read the input in. The nested for loop suggests that you're trying to read the values in one by one, but the split suggests that you're doing it line by line. To cover all bases, I'll explain both cases. At least one of them will be relevant.
Case 1:
Let's say you've been inputting the values one by one, i.e.
1
4
9
4
...
In this case, what's happening is that the input() function is automatically parsing the inputs as integers, and when you try running split() on an integer there's a type error. Python is expecting a string and you're providing an int. That's going to break. There's an easy solution--this can be fixed by simply replacing that line with
n = input()
Case 2: Let's say you're inputing the numbers line by line, as strings. By this, I mean something like:
"1 3 4 5 7 9"
"4 1 8 2 5 1"
...
What's occurring here is that int(...) is trying to cast a list of strings into an integer. That will clearly break the code. A possible solution would be to restructure the code by gett rid of the inner for loop. Something like this should work:
def arr_input(arr):
for i in range(6):
s = input()
nums_s = s.split(' ')
nums = [int(x) for x in nums_s]
arr.append(nums)
print "\n"
return arr
# Usage
a = []
print(a)
a = arr_input(a)
print(a)
Give this one-liner a try:
def arr_input(N=6):
print 'Enter %d by %d array, one row per line (elements separated by blanks)' % (N, N)
return [[n if abs(n)<=9 else 0 for n in map(int, raw_input().split())] for i in range(N)]
The following interactive session demonstrates its usage:
>>> A = arr_input(3)
Enter 3 by 3 array, one row per line (elements separated by blanks)
1 2 -3
4 5 -6
8 9 10
>>> A
[[1, 2, -3], [4, 5, -6], [8, 9, 0]]
Please help for task with the list in Python my logic is bad works:( .
This is full text of task: Write a program that takes a list of
numbers on one line and displays the values in a single row, are
repeated in it more than once.
To solve the problem can be useful sort method list.
The procedure for withdrawal of repetitive elements may be arbitrary.
My beginning code is :
st = (int(i) for i in input().split())
ls = []
for k in st:
if k == k + 1 and k > 1:
Task is : if we have replay value in list we must print it. We only can use sort() method and without any modules importing.
Results Examples:
Sample Input 1:
4 8 0 3 4 2 0 3
Sample Output 1:
0 3 4
Sample Input 2:
10
Sample Output 2:
Sample Input 3:
1 1 2 2 3 3
Sample Output 3:
1 2 3
This code isn't run( sort() function doesn't want sort my_list. But I must input values like my_list = (int(k) for k in input().split())
st = list(int(k) for k in input())
st.sort()
for i in range(0,len(st)-1):
if st[i] == st[i+1]:
print(str(st[i]), end=" ")
my_list = (int(k) for k in input().split())
After running this line, my_list is a generator, something that will create a sequence - but hasn't yet done so. You can't sort a generator. You either need to use []:
my_list = [int(k) for k in input().split()]
my_list.sort()
which makes my_list into a list from the start, instead of a generator, or:
my_list = list(int(k) for k in input().split()))
my_list.sort()
gather up the results from the generator using list() and then store it in my_list.
Edit: for single digits all together, e.g. 48304, try [int(k) for k in input()]. You can't usefully do this with split().
Edit: for printing the results too many times: make the top of the loop look backwards a number, like this, so if it gets to the second or third number of a repeating number, it skips over and continues on around the loop and doesn't print anything.
for i in range(0,len(st)-1):
if st[i] == st[i-1]:
continue
if st[i] == st[i+1]:
print...
st = (int(i) for i in input().split())
used = []
ls = []
for k in st:
if k in used: # If the number has shown up before:
if k not in used: ls.append(k) # Add the number to the repeats list if it isn't already there
else:
used.append(k) # Add the number to our used list
print ' '.join(ls)
In summary, this method uses two lists at once. One keeps track of numbers that have already shown up, and one keeps track of second-timers. At the end the program prints out the second-timers.
I'd probably make a set to keep track of what you've seen, and start appending to a list to keep track of the repeats.
lst = [num for num in input("prompt ").split()]
s = set()
repeats = []
for num in lst:
if num in s and num not in repeats:
repeats.append(num)
s.add(num)
print ' '.join(map(str,repeats))
Note that if you don't need to maintain order in your output, this is faster:
lst = [num for num in input("prompt ").split()]
s = set()
repeats = set()
for num in lst:
if num in s:
repeats.add(num)
s.add(num)
print ' '.join(map(str, repeats))
Although if you can use imports, there's a couple cool ways to do it.
# Canonically...
from collections import Counter
' '.join([num for num,count in Counter(input().split()).items() if count>1])
# or...
from itertools import groupby
' '.join([num for num,group in groupby(sorted(input().split())) if len(list(group))>1])
# or even...
from itertools import tee
lst = sorted(input('prompt ').split())
cur, nxt = tee(lst)
next(nxt) # consumes the first element, putting it one ahead.
' '.join({cur for (cur,nxt) in zip(cur,nxt) if cur==nxt})
this gives the answers you're looking for, not sure if it's exactly the intended algorithm:
st = (int(i) for i in input().split())
st = [i for i in st]
st.sort()
previous = None
for current in st:
if ((previous is None and current <= 1)
or (previous is not None and current == previous + 1)):
print(current, end=' ')
previous = current
>>> "4 8 0 3 4 2 0 3"
0 3 4
>>> "10"
>>> "1 1 2 2 3 3"
1 2 3
updated to:
start with st = (int(i) for i in input().split())
use only sort method, no other functions or methods... except print (Python3 syntax)
does that fit the rules?