How do I reduce the number of loops or complexity - python

So what I am trying to do is to find count of alternating numbers such that it alternates with -ve and positive sign
for eg: 1 -2 3 -4 would get me 4 3 2 1 as from 1 to -4 including the two numbers there are 4 numbers.
Simillarly for 1 1 -3 2 would get me 1 3 2 1
Now I have the code but I cannot optimise it and it returns me a time limit exceeded error even though it works for moderate input stream.
j=0
count=0
length=(raw_input())
st=map(int,raw_input().split())
while j+1 < len(st):
k=j+1
count=0
temp=j
while k<len(st) and ((st[k]<0 and st[j]>0) or (st[k]>0 and st[j]<0)):
count+=1
k+=1
j+=1
print count+1,
j=temp+1
print 1

Try using for loops instead of while loops as that avoids you some variable assignments:
st = map(int, raw_input().split())
length = len(st)-1
for i in range(length):
count = 1
for j in range(i, length):
if (st[j]<0 and st[j+1]>0) or (st[j+1]<0 and st[j]>0):
count += 1
else:
break
print(count)
print(1)
This will give:
<< 1 -2 3 4
>> 4
>> 3
>> 2
>> 1
<< 1 1 -3 2
>> 1
>> 3
>> 2
>> 1
It may also be a bit faster if you extract the numbers from the list once instead of twice:
st = map(int, raw_input().split())
length = len(st)-1
for i in range(length):
count = 1
for j in range(i, length):
first, second = st[j:j+2]
if (first<0 and second>0) or (first>0 and second<0):
count += 1
else:
break
print(count)
print(1)
The last thing I would try is checking that they sigs are different with a single comparisson but I do not really expect this to be faster:
st = map(int, raw_input().split())
length = len(st)-1
for i in range(length):
count = 1
for j in range(i, length):
product = st[j] * st[j+1]
if product != abs(product):
count += 1
else:
break
print(count)
print(1)

Related

How to receive a num at each step and continue until zero is entered; then this program should print each entered num as its own num

Here I have this code:
N = int(input())
Tmp=n
While tmp>0 :
Print(n)
Tmp-=1
But for ex: when I have:
3
2
1
0
As entered nums, it just prints:
3
3
3
But I need to print:
3
3
3
2
2
1
Here I have this code:
N = int(input())
Tmp=n
While tmp>0 :
Print(n)
Tmp-=1
But there is a problem!bc it just prints
3
3
3
Instead of:
3
3
3
2
2
1
you need to print(tmp) instead of print(n)
this will print 3 2 1.
To get 3 3 3 2 2 1 you need to change your code more:
n = int(input())
tmp=n
while tmp > 0:
for _ in range(tmp)
print(tmp)
tmp -= 1
You need to add if statement when tmp equals 0 then subtract n by 1 and assign tmp back to n:
n = int(input('input : '))
tmp = n
while tmp > 0:
print(n)
tmp -= 1
if tmp == 0:
n -= 1
tmp = n
Output:
# input : 3
# 3
# 3
# 3
# 2
# 2
# 1

How to get the count of lines in a output of a python script

This is my code for getting a 3 digit combination.
a = input("Enter first number: ")
b = input("Enter second number: ")
c = input("Enter third number: ")
d = []
d.append(a)
d.append(b)
d.append(c)
for i in range(0, 4):
for j in range(0, 4):
for k in range(0, 4):
if(i !=j & j!=k & k!=i):
for count, i in enumerate(range(4),1):
print(i,j,k)
Input:
1,2,3
and
Output:
0 1 2
1 1 2
2 1 2
3 1 2
0 2 0
1 2 0
2 2 0
3 2 0 & more....
My question is how can I get the count of how many combinations I have got?
Thank you so much for your attention and participation.
Outside of your loop, create an integer variable and set it equal to 0. Where you print out the combinations (within the loop), add 1 to this integer variable. Finally at the end of your program outside the loop, print the value of the counter variable.
For example:
counter = 0
for i in range(0, 4):
for j in range(0, 4):
for k in range(0, 4):
if (i != j & j != k & k != i):
for count, i in enumerate(range(4), 1):
print(i, j, k)
counter += 1
print(counter)

Find the sum of all the multiples of 3 or 5 below 1000. (idk what is wrong with my code)

I'm a beginner and I tried this code to list the sum of all the multiples of 3 or 5 below 100, but it gives a wrong answer and I don't know why.
result = 0
result2 = 0
som = 0
sum2 = 0
below_1000 = True
while below_1000:
result = result+3
if result < 1000:
som += result
else:
below_1000 = False
below_1000 = True
while below_1000:
result2 = result2+5
if result2 < 1000:
sum2 += result2
else:
below_1000 = False
final_result = som+sum2
print(final_result)
Since you first loop over multiples of 3, then again over multiples of 5, you are double-counting a lot of values, specifically values that are multiples of both 3 and 5 (for example 15 or 60).
To write this manually, you can use a for loop over range
total = 0
for i in range(1000):
if i % 3 == 0 or i % 5 == 0:
total += i
>>> total
233168
A more concise way to do this same thing is using a generator expression within the sum function
>>> sum(i for i in range(1000) if i % 3 == 0 or i % 5 == 0)
233168

printing maximum number of consecutive 1's in python

Im trying to print the maximum number of consecutive 1's in python...but im getting stuck here....IDK why im getting a syntax error...strange...can anyone help me out
li2 = []
t = int(input())
for i in range(0, t): //testcases
n = int(input())
for i in range(n): //length of list(binary array)
li = list(map(int, input().strip().split())
count = 0
max_count=0
for i in range(len(li)):
if (li[i] == 0):
count = 0
else:
count += 1
max_count = max(max_count,count)
li2.append(max_count)
for i in range(len(li2)):
print(li2[i])
File "<ipython-input-2-f159cb61e247>", line 7
count = 0
^
SyntaxError: invalid syntax
Corrections:
li2 = []
t = int(input())
for i in range(0, t): #testcases
n = int(input())
li = list(map(int, input().strip().split())) #<--- before that loop is removed.
count = 0
max_count=0
for i in range(len(li)):
if (li[i] != 1): #<------- Here
count = 0
else:
count += 1
max_count = max(max_count,count) #<--- here
li2.append(max_count)
print()
for i in range(len(li2)):
print(li2[i])
3
5
2 1 1 1 1
3
2 3 4
7
1 2 3 1 1 1 1
4
0
4
Improve the above answer using inline function
li2 = []
t = int(input())
for i in range(0, t): #testcases
n = int(input())
li = ''.join(input().split())
li = [n if n == '1' else '0' for n in li] # replace the numbers not '1' to '0'
max_count = max(map(len, ''.join(li).split('0'))) # split by '0' and get max length from each 1's
li2.append(max_count)
print()
for i in range(len(li2)):
print(li2[i])

Splitting a string of integers with spaces without converting to a list in python

Basically, I need a code that takes an integer and then prints out the string of numbers with the certain range.
For example:
n = 11
1 2 2 3 3 3 4 4 4 4
n = 7
1 2 2 3 3 3 4
a = []
n = int(input())
if n == 0:
print(n)
for i in range(int(n) + 1):
a += [i] * i
a = ' '.join(map(str, a))
print(a[:n])
This does the job but it counts spaces as characters, so I tried to convert it to an int
n = int(n)
print(' '.join(a[:n]))
But when the n >= 47, it starts to print out 10 as 1 0 which is incorrect
I also tried this code
n = int(input())
for i in range(n):
b = (str(i) * i)
print(b, end = ' ')
But I don't understand how to separate the b with spaces without converting the string to a list and printing it in one line either.
I am not sure if it is even possible.
Maybe something like this?
# initialize variables:
number = 11
counter = 0
for i in range(number):
for j in range(i):
# print number:
print('%d ' %i, end='')
# increment counter (tracks how many numbres to print):
counter += 1
# exit inner loop if counter reaches number:
if counter >= number-1: break
# exit outer loop if counter reaches number:
if counter >= number-1: break
Output:
1 2 2 3 3 3 4 4 4 4
Here's a solution using itertools. Generators, chain, repeat and islice are all lazily evaluated, so this uses O(1) space.
>>> n = 7
>>> from itertools import chain, repeat, islice
>>> gen = chain.from_iterable(repeat(i, i) for i in range(1, n+1))
>>> for i in islice(gen, n):
... print(i, end=' ')
...
1 2 2 3 3 3 4
This seems simple. But this does solve the problem?
>>> for i in t:
... if i!=" ": print i
...
1
2
2
3
3
3
4
4
4
4
or even string replace like,
print t.replace(" ","\n")
1
2
2
3
3
3
4
4
4
4

Categories