Omit last line in nested for loop - python-3.x

I have a nested for loop:
for i in range(0,6):
for j in range(0,10):
print(j, end="")
print("\n",0)
Which results in the following:
0123456789
0
0123456789
0
0123456789
0
0123456789
0
0123456789
0
0123456789
0
How do I omit the last 0 from the result?

you can simply add an if as follows:
for i in range(0, 6):
for j in range(0, 10):
print(j, end="")
if i != 5:
print("\n", 0)

You can keep a variable to see if the process is complete and there is no need for more zeroes.
done = False
for i in range(0,6):
for j in range(0,10):
print(j, end="")
if i == 5 and j == 9:
done = True
if not done:
print("\n",0)
# You can also use this variable to break the loop
# after the process is complete.

Related

What is the point of including print() at the end of a Python function?

def display_list(self):
if self.start is None:
print("List is empty!")
print("List is: ")
p = self.start
while p is not None:
print(p.info, " ", end=" ")
p = p.next
print()
This code simply prints the list's contents. As you can see, there is a print() function at the end of the function with no arguments. What is the point of including that, and is it actually needed?
To make the next print statement after the function starts from the next line. Compare these codes:
def fn():
i = 0
while i < 10:
print(i, end=' ')
i += 1
fn()
print('hello world')
output:
0 1 2 3 4 5 6 7 8 9 hello world
and this:
def fn():
i = 0
while i < 10:
print(i, end=' ')
i += 1
print()
fn()
print('hello world')
output:
0 1 2 3 4 5 6 7 8 9
hello world
x = 5
print(x,end="\n",sep=" ")
The end attribute of print functions which is by default set to newline is responsible for adding new line after print statement is over.You can change this to achieve any other functionality.
print("a",end="<=>",sep=" ")//outputs a<=>

Incrementing the for loop in python given a certain condition

The i+=1 isn't working, it should have increased the i value but it isn't
n = int(input())
for j in range(n):
a = input()
pair = 0
for i in range(len(a)-1):
print(i)
if a[i] == "x" and a[i+1] == "y":
pair += 1
print("*")
elif a[i] == "y" and a[i+1] =="x":
pair += 1
print('**')
else:
continue
i+=1
print(pair)
print("****")
print(pair)strong text
```
You are trying to modify a parameter that is implicitly set by the for loop.
This isn't C-Code, increasing the counter variable will not skip the next iteration.
The reason for that is quite simple: for itself does not increase i in every iteration, it just steps through the given iteratable. In this case the iteratable is a range, which behaves like for would increase i every iteration, but it really just takes the next value from the range.
So i+=1 doesn't have an effect on the next iteration, as it doesn't modify the next value in the range.
Your for-loop already increments i on every iteration. But if you want to increment by more than 1 when certain condition is satisfied, then you can use while loop as follows:
n = int(input())
for j in range(n):
a = input()
pair = 0
i = 0
while i < len(a)-1:
print(i)
if a[i] == "x" and a[i+1] == "y":
pair += 1
print("*")
elif a[i] == "y" and a[i+1] =="x":
pair += 1
print('**')
else:
i += 1
continue
i+=2
print(pair)
print("****")
print(pair)strong text
You could explicitely skip the next iteration when a pair is found.
Here is your code with the changes pointed at by # <---.
n = int(input())
for j in range(n):
a = input()
pair = 0
skip_next = False # <---
for i in range(len(a)-1):
if skip_next is True: # <---
skip_next = False # <---
continue # <---
print(i)
if a[i] == "x" and a[i+1] == "y":
pair += 1
print("*")
skip_next = True # <---
elif a[i] == "y" and a[i+1] =="x":
pair += 1
print('**')
skip_next = True # <---
else:
continue
print(pair)
print("****")
print(pair)

What am I doing wrong with this code for hackerrank?

I have been coding this problem for HackerRank and I ran into so many problems. The problem is called "Plus Minus" and I am doing it in Python 3. The directions are on https://www.hackerrank.com/challenges/plus-minus/problem. I tried so many things and it says that "there is no response on stdout". I guess a none-type is being returned. Here is the code.:
def plusMinus(arr):
p = 0
neg = 0
z = arr.count(0)
no = 0
for num in range(n):
if arr[num] < 0:
neg+=1
if arr[num] > 0:
p+=1
else:
no += 1
continue
return p/n
The following are the issues:
1) variable n, which represents length of the array, needs to be passed to the function plusMinus
2) No need to maintain the extra variable no, as you have already calculated the zero count. Therefore, we can eliminate the extra else condition.
3) No need to use continue statement, as there is no code after the statement.
4) The function needs to print the values instead of returning.
Have a look at the following code with proper naming of variables for easy understanding:
def plusMinus(arr, n):
positive_count = 0
negative_count = 0
zero_count = arr.count(0)
for num in range(n):
if arr[num] < 0:
negative_count += 1
if arr[num] > 0:
positive_count += 1
print(positive_count/n)
print(negative_count/n)
print(zero_count/n)
if __name__ == '__main__':
n = int(input())
arr = list(map(int, input().rstrip().split()))
plusMinus(arr, n)
The 6 decimals at the end are needed too :
Positive_Values = 0
Zeros = 0
Negative_Values = 0
n = int(input())
array = list(map(int,input().split()))
if len(array) != n:
print(f"Error, the list only has {len(array)} numbers out of {n}")
else:
for i in range(0,n):
if array[i] == 0:
Zeros +=1
elif array[i] > 0:
Positive_Values += 1
else:
Negative_Values += 1
Proportion_Positive_Values = Positive_Values / n
Proportion_Of_Zeros = Zeros / n
Proportion_Negative_Values = Negative_Values / n
print('{:.6f}'.format(Proportion_Positive_Values))
print('{:.6f}'.format(Proportion_Negative_Values))
print('{:.6f}'.format(Proportion_Of_Zeros))

Not Able To use for-loop

** I want to use two for-loops instead of two while-loops **
i = 7
while i >= 1:
j = i
while j <= 7:
print(j, end =" ")
J += 1
i -= 1
print()
The following is the for-loop equivalent:
for i in range(7, 0, -1):
j = i
for j in range(i, 8):
print(j, end=" ")
print()
The key is the correct use of range(start, stop, step). See also this.

A function to manipulate strings ad numbers

I need the solution for a function that prints numbers from 1 to 100. For multiples of three print “Foo”
instead of the number and for the multiples of five print “Bar”. For numbers which are multiples of both three and five print “FooBar”. For the remaining numbers just print this number.
i = 0
while I < 100:
i += 1
print(i)
if i == 3:
print("Foo")
You will have to use mod (%) to check the remainder of a division.
See if i % 3 is equal to 0. If this is true, then print FOO.
If i % 5 equal 0, print Bar; and so on.
I would recommend using an if else statement in your while loop after the index counter. Something like...
i = 0
while i <= 100:
i += 1
if i % 15 == 0:
print("foobar")
elif i % 3 == 0;
print("foo")
elif i % 5 == 0:
print("bar")
else:
print(i)
Using % returns the remainder and if that returns a remainder of 0 then you know that it is evenly divisible by that number.
i = 0
while i < 100:
i += 1
if i%15 == 0:
print('FooBar')
elif i%3 == 0:
print('Foo')
elif i%5 == 0:
print('Bar')
else:
print(i)
Apply if and else statement to decide which is the situation during the while loop.
Also, % could return the remainder. 3 and 5 both are prime numbers, so a number which % (3*5) == 0 indicates itself is a multiples of 3 and 5.

Resources