how to make a delay and print it? - python

anyone can help me. I am working on the traffic light and I want to make a delay for green and red lights and print so I tried this code:
import time
t=10
while True:
time.sleep(1)
print(t)
t = t - 1
if(t==0):
break
but it repeated twice:
10
9
8
7
6
5
4
3
2
1
10
9
8
7
6
5
4
3
2
1
i expected :
10
9
8
7
6
5
4
3
2
1
0

This worked for me:
import time
t = 10
while (t >= 0):
time.sleep(1)
print(t)
t -= 1

change if(t ==0): to if(t<0):
if t==0, it will print upto 1(ie from 10-1),it stops when t=0.
if want to include 0, then change the to t<0.so it prints upto 0(from 10-0), it stops when t value is less than 0.
check out this code:
code:
import time
t=10
while True:
time.sleep(1)
print(t)
t = t - 1
if(t < 0):
break
output:
10
9
8
7
6
5
4
3
2
1
0

Related

Python Welsh-Powell graph coloring

I have implemented algorithm for Welsh-Powell graph coloring.
Task is that you have txt document with lines of 2 numbers, in which the first one represent vertex and the second one represent its neighbor.
Looks like this:
1 2
1 4
1 5
1 8
1 9
1 11
2 3
2 4
2 5
2 6
2 7
2 8
2 10
2 11
2 12
3 4
3 5
3 6
3 7
3 8
3 9
3 11
4 6
4 9
4 10
4 11
4 12
5 6
5 7
5 10
5 11
5 12
6 7
6 10
6 11
6 12
7 8
7 10
7 11
7 12
8 10
8 11
8 12
9 10
9 12
10 12
Output should be also txt document with two numbers in line, where the first one is vertex and the second one is number of color like this:
1 2
2 1
3 2
4 3
5 3
6 4
7 5
8 3
9 1
10 2
11 6
12 6
The number of used colors is not important, as it shouldnt be more than all vertexes.
This is graphColoring.py
def file_to_graph(filename):
file1 = open(filename, 'r')
lines = file1.readlines()
graph = [[], []]
for line in lines:
if line == '':
continue
row = line.split(' ')
from_vertex = int(row[0])
to_vertex = int(row[1])
found_from_vertex = -1
found_to_vertex = -1
for i in range(len(graph[0])):
if graph[0][i][0] == from_vertex:
graph[0][i][1] += 1
found_from_vertex = i
if graph[0][i][0] == to_vertex:
graph[0][i][1] += 1
found_to_vertex = i
if found_from_vertex == -1:
graph[0].append([from_vertex, 1])
if found_to_vertex == -1:
graph[0].append([to_vertex, 1])
graph[1].append((from_vertex, to_vertex))
return graph
def get_color(colored_vertexes, vertex):
for colored_vertex in colored_vertexes:
if colored_vertex[0] == vertex:
return colored_vertex[1]
return -1
def color_graph(graph, max_colors=-1):
sorted_vertexes = sorted(graph[0], key=lambda x: x[1])
colored_vertexes = []
for vertex_with_edges in reversed(sorted_vertexes):
colored_vertexes.append([vertex_with_edges[0], 0])
actual_color = 1
while True:
for vertex_with_edge_count in reversed(sorted_vertexes):
color = 0
colored_vertex_index = -1
vertex_name = vertex_with_edge_count[0]
for i in range(len(colored_vertexes)):
if colored_vertexes[i][0] == vertex_name:
color = colored_vertexes[i][1]
colored_vertex_index = i
break
if color != 0:
continue
color_of_neighbours = []
for (from_vertex, to_vertex) in graph[1]:
if from_vertex == vertex_name:
color_of_neighbours.append(get_color(colored_vertexes, to_vertex))
if to_vertex == vertex_name:
color_of_neighbours.append(get_color(colored_vertexes, from_vertex))
if actual_color not in color_of_neighbours:
colored_vertexes[colored_vertex_index][1] = actual_color
actual_color += 1
is_colored = True
for colored_vertex in colored_vertexes:
if colored_vertex[1] == 0:
is_colored = False
break
if is_colored:
break
return colored_vertexes
And this is main.py
from graphColoring import file_to_graph, color_graph
import sys
if __name__ == '__main__':
graph = file_to_graph(sys.argv[1])
colored_vertexes = color_graph(graph)
for colored_vertex in sorted(colored_vertexes, key=lambda x: x[0]):
print(str(colored_vertex[0]) + " " + str(colored_vertex[1]))
EDIT//: I received a solution for problem with input, but I dont have expected output. Instead of expected output above, i received this:
1 2
2 1
3 2
4 4
5 6
6 5
7 4
8 5
9 1
10 3
11 3
12 2
//
I should use "python main.py ./input.txt" to input txt document, but after running the program it says:
line 7, in <module>
graph = file_to_graph(sys.argv[1])
~~~~~~~~^^^
IndexError: list index out of range
I˙m not so good at programming and all of this is really hard for me to understand so I really appreciate some help to make this functional.
For me it is working. And it also gives your desired output
1 1
2 2
3 1
4 2
I think it is about how you run the script. Because when I run
python .\main.py I also get
Traceback (most recent call last):
File "C:\Users\fhdwnig\Desktop\main.py", line 5, in <module>
graph = file_to_graph(sys.argv[1])
~~~~~~~~^^^
you have to run it like this:
python .\main.py .\input.txt
(on windows)
The script is missing the input file.
change this line
sorted_vertexes = sorted(graph[0], key=lambda x: x[1])
to this one
sorted_vertexes = sorted(sorted(graph[0][::-1],key=lambda x:x[0], reverse=True), key=lambda x: x[1])

how can I decrease execution time needed for python code?

#https://www.codechef.com/problems/GRIDGM
from sys import setrecursionlimit
setrecursionlimit(10**6)
def sol(l,lst):
sum=0
for i in range(l[0],l[2]+1):
for j in range(l[1],l[3]+1):
#print(lst[i-1][j-1],end="")
sum += lst[i-1][j-1]
#print('---')
#print("sol below")
return sum
for _ in range(int(input())):
n,m=map(int, input("enter values of n and m").split())
lst=[]
for _ in range(n):
lst.append(list(map(int,input("enter a row").split())))
#print(lst)
#q=int(input())
#dj=[] #it saves x y and a b
for _ in range(int(input("enter no of queries"))):
#v=list(map(int,input().split()))
#print(v)
#print('sol below')
print(sol(list(map(int,input("enter cordinates").split())),lst))
sample input
1
4 4
9 13 5 2
1 11 7 6
3 7 4 1
6 0 7 10
2
2 1 4 2
2 2 4 4
output
28
53
above code took 5.1 sec to execute.
in this question, I have to find sum of elements within given coordinates a,b and x,y
more information about this problem can be found in the link below.
https://www.codechef.com/problems/GRIDGM

Do python recursive calls interfere with each other?

I am trying to set up a recursive game solver (for the cracker-barrel peg game). The recursive function appears to not be operating correctly, and some outputs are created with no trace of how they were created (despite logging all steps). Is it possible that the python recursion steps are overwriting eachother?
I have already tried adding in print statements at all steps of the way. The game rules and algorithms work correctly, but the recursive play algorithm is not operating as expected
def recursive_play(board, moves_list, move_history, id, first_trial, recurse_counter):
# Check how many moves are left
tacks_left = len(char_locations(board, character=tack, grid=True))
log_and_print(f"tacks_left: {tacks_left}")
log_and_print(f"moves_left: {len(moves_list)}")
log_and_print(f"moves_list: {moves_list}")
if (len(moves_list) == 0):
if (tacks_left == 1):
# TODO: Remove final move separator
log_and_print(f"ONE TACK LEFT :)!!!!")
log_and_print(f"move_history to retrun for win: {move_history}")
return move_history
pass
elif (len(moves_list) > 0):
# Scan through all moves and make them recursively
for move in moves_list:
if first_trial:
id += 1
else:
# id += 1
id = id
next_board = make_move(board, move)
next_moves = possible_moves(next_board)
if first_trial:
next_history = "START: " + move
else:
next_history = move_history + round_separator + move
# log_and_print(f"og_board:")
prettify_board(board)
log_and_print(f"move: {move}")
log_and_print(f"next_board:")
prettify_board(next_board)
# log_and_print(f"next_moves: {next_moves}")
log_and_print(f"next_history: {next_history}")
log_and_print(f"id: {id}")
log_and_print(f"recurse_counter: {recurse_counter}")
# NOTE: Would this be cleaner with queues?
recursive_play(next_board, moves_list=next_moves, move_history=next_history, id=id, first_trial=False, recurse_counter=recurse_counter+1)
log_and_print(f"finished scanning all moves for board: {board}")
I expect all steps to be logged, and "START" should only occur on the first trial. However, a mysterious "START" appears in a later step with no trace of how that board was created.
Good Output:
INFO:root:next_history: START: 4 to 2 to 1 , 6 to 5 to 4 , 1 to 3 to 6 , 7 to 4 to 2
INFO:root:id: 1
INFO:root:recurse_counter: 3
INFO:root:tacks_left: 5
INFO:root:moves_left: 2
INFO:root:moves_list: ['9 to 8 to 7', '10 to 6 to 3']
INFO:root:o---
INFO:root:xo--
INFO:root:oox-
INFO:root:xoox
INFO:root:move: 9 to 8 to 7
INFO:root:next_board:
INFO:root:o---
INFO:root:xo--
INFO:root:oox-
INFO:root:xoox
INFO:root:next_history: START: 4 to 2 to 1 , 6 to 5 to 4 , 1 to 3 to 6 , 7 to 4 to 2 , 9 to 8 to 7
INFO:root:id: 1
INFO:root:recurse_counter: 4
INFO:root:tacks_left: 4
INFO:root:moves_left: 1
INFO:root:moves_list: ['10 to 6 to 3']
INFO:root:o---
INFO:root:xx--
INFO:root:ooo-
INFO:root:xooo
INFO:root:move: 10 to 6 to 3
INFO:root:next_board:
INFO:root:o---
INFO:root:xx--
INFO:root:ooo-
INFO:root:xooo
INFO:root:next_history: START: 4 to 2 to 1 , 6 to 5 to 4 , 1 to 3 to 6 , 7 to 4 to 2 , 9 to 8 to 7 , 10 to 6 to 3
Bad Output:
INFO:root:move: 6 to 3 to 1
INFO:root:next_board:
INFO:root:x---
INFO:root:xo--
INFO:root:ooo-
INFO:root:oooo
INFO:root:next_history: START: 6 to 3 to 1
INFO:root:id: 2
INFO:root:recurse_counter: 0
INFO:root:tacks_left: 2
INFO:root:moves_left: 1
INFO:root:moves_list: ['1 to 2 to 4']
INFO:root:o---
INFO:root:oo--
INFO:root:xoo-
INFO:root:oooo
INFO:root:move: 1 to 2 to 4
INFO:root:next_board:
INFO:root:o---
INFO:root:oo--
INFO:root:xoo-
INFO:root:oooo
INFO:root:next_history: START: 6 to 3 to 1 , 1 to 2 to 4
INFO:root:id: 2
INFO:root:recurse_counter: 1
INFO:root:tacks_left: 1
INFO:root:moves_left: 0
INFO:root:moves_list: []
INFO:root:ONE TACK LEFT :)!!!!
INFO:root:move_history to retrun for win: START: 6 to 3 to 1 , 1 to 2 to 4
INFO:root:finished scanning all moves for board: ['o---', 'oo--', 'xoo-', 'oooo']
Any tips anyone can provide would be greatly appreciated.

Print a number table in a simple format

I am stuck trying to print out a table in Python which would look like this (first number stands for amount of numbers, second for amount of columns):
>>> print_table(13,4)
0 1 2 3
4 5 6 7
8 9 10 11
12 13
Does anyone know a way to achieve this?
This is slightly more difficult than it sounds initially.
def numbers(n, r):
print('\n'.join(' '.join(map(str, range(r*i, min(r*(i + 1), n + 1)))) for i in range(n//r + 1)))
numbers(13, 4)
#>>> 0 1 2 3
4 5 6 7
8 9 10 11
12 13
def numbers(a,b):
i=0;
c=0;
while i<=a:
print(i,end="") #prevents printing a new line
c+=1
if c>=b:
print("\n") #prints a new line when the number of columns is reached and then reset the current column number
c=0;
I think it should work
def num2(n=10, r=3):
print('\n'.join(' '.join(tuple(map(str, range(n+1)))[i:i+r]) for i in range(0, n+1, r)))
<<<
0 1 2
3 4 5
6 7 8
9 10

write a program that prints a nested loop in Python

I'm trying to print a nested loops that looks like this:
1 2 3 4
5 6 7 8
9 10 11 12
This is what I have so far:
def main11():
for n in range(1,13)
print(n, end=' ')
however, this prints the numbers in one line: 1 2 3 4 5 6 7 8 9 10 11 12
You can do that using string formatting:
for i in range(1,13):
print '{:2}'.format(i),
if i%4==0: print
[OUTPUT]
1 2 3 4
5 6 7 8
9 10 11 12
Modulus Operator (%)
for n in range(1,13):
print(n, end=' ')
if n%4 == 0:
print
for offset in range(3):
for i in range(1,5):
n = offset*4 + i
print(n, end=' ')
print()
Output:
1 2 3 4
5 6 7 8
9 10 11 12
Or if you want it nicely formatted the way you have in your post:
for offset in range(3):
for i in range(1,5):
n = offset*4 + i
print("% 2s"%n, end=' ')
print()
Output:
1 2 3 4
5 6 7 8
9 10 11 12
Most of the time when you write a for loop, you should check if this is the right implementation.
From the requirements you have, I would write something like this:
NB_NB_INLINE = 4
MAX_NB = 12
start = 1
while start < MAX_NB:
print( ("{: 3d}" * NB_NB_INLINE).format(*tuple( j+start for j in range(NB_NB_INLINE))) )
start += NB_NB_INLINE

Categories

Resources