When I run this, the Progress % is backwards, does anyone know how to make it 0% at the beginning and 100% when it completes?
import time
x = 25
y = x
t = 0
downloading = True
while downloading:
time.sleep(1)
t += 1
x -= 1
f = ((x/y) * 100)
print('Time:', str(t) + ',', 'Progress: ', '{0:.2}'.format(str(f)) + '%,', 'Remaining: ' + str(x), 'MB', end="\r")
if(x == 0):
print('\nComplete!')
break
Just use (1-x/y) instead of x/y in f.
import time
x = 25
y = x
t = 0
downloading = True
while downloading:
time.sleep(0.01)
t += 1
x -= 1
f = ((1-x/y) * 100)
print('Time:', str(t) + ',', 'Progress: ', '{0:.3}'.format(str(f)) + '%,', 'Remaining: ' + str(x), 'MB', end="\r")
if(x == 0):
print('\nComplete!')
break
Also note that you should use '{0:.3}'.format(str(f)) so that 100% can be displayed correctly.
Related
I'm currently working on trying to build a scheduler that will assign parts to specific time slots. This is what I've come up with currently, but I'm curious to know if there is a better way to do this. I'm fairly new to coding in python, so really have just working with while/for loops and if/else statements. I'm sure there is a way, so hopefully someone out there can show me the light.
import pandas as pd
from datetime import datetime, timedelta
day_start = str('2021-07-28 06:30')
break_1_start = str('2021-07-28 08:50')
lunch_start = str('2021-07-28 12:00')
break_2_start = str('2021-07-28 14:50')
day_end = str('2021-07-28 17:40')
day_start = datetime.strptime(day_start, "%Y-%m-%d %H:%M")
break_1_start = datetime.strptime(break_1_start, "%Y-%m-%d %H:%M")
break_1_end = break_1_start + timedelta(minutes=20)
lunch_start = datetime.strptime(lunch_start, "%Y-%m-%d %H:%M")
lunch_end = lunch_start + timedelta(minutes=30)
break_2_start = datetime.strptime(break_2_start, "%Y-%m-%d %H:%M")
break_2_end = break_2_start + timedelta(minutes=20)
day_end = datetime.strptime(day_end, "%Y-%m-%d %H:%M")
sched_df = pd.DataFrame({"Time": [day_start, break_1_start, break_1_end, lunch_start, lunch_end,
break_2_start, break_2_end, day_end]})
print(sched_df)
demand_df = pd.DataFrame({"PartNo": ['Part1', 'Part2', 'Part3', 'Part4', 'Part5'],
"TTJ": [75, 100, 180, 30, 60]})
demand_df = demand_df.astype({'TTJ': float})
print(demand_df)
a = 0
b = 1
c = 2
x = sched_df.iloc[a]['Time']
y = sched_df.iloc[0]['Time']
z = 0
for n in range(0, len(demand_df)):
while y < sched_df.iloc[1]['Time']:
y = x + timedelta(minutes=demand_df.iloc[a]['TTJ'])
if y > sched_df.iloc[1]['Time']:
end = sched_df.iloc[1]['Time']
print(demand_df.iloc[a]['PartNo'], 'time from : ', x.time(), ' to ', end.time())
start = sched_df.iloc[1]['Time']
end = sched_df.iloc[2]['Time']
print('Break time from : ', start.time(), ' to ', end.time())
xyz = sched_df.iloc[1]['Time'] - x
delta = xyz.total_seconds()
minutes = float(delta // 60)
z = demand_df.iloc[a]['TTJ'] - minutes
x = end + timedelta(minutes=z)
counter = a
else:
print(demand_df.iloc[a]['PartNo'], 'time from : ', x.time(), ' to ', y.time())
x = y
a = a+1
if x > sched_df.iloc[3]['Time']:
start = sched_df.iloc[2]['Time']
end = sched_df.iloc[3]['Time']
print(demand_df.iloc[a]['PartNo'], 'time from : ', start.time(), ' to ', end.time())
xyz = x-end
delta = xyz.total_seconds()
minutes = float(delta // 60)
z = minutes
start = sched_df.iloc[3]['Time']
end = sched_df.iloc[4]['Time']
print('Lunch time from : ', start.time(), ' to ', end.time())
start = sched_df.iloc[4]['Time']
x = start + timedelta(minutes=z)
print(demand_df.iloc[a]['PartNo'], 'time from : ', start.time(), ' to ', x.time())
z = 0
a = a + 1
else:
start = sched_df.iloc[2]['Time']
print(demand_df.iloc[a]['PartNo'], 'time from : ', start.time(), ' to ', x.time())
z = 0
a = a + 1
y = x
for n in range(0, len(demand_df)):
while y < sched_df.iloc[3]['Time']:
y = x + timedelta(minutes=demand_df.iloc[a]['TTJ'])
if y > sched_df.iloc[3]['Time']:
end = sched_df.iloc[3]['Time']
print(demand_df.iloc[a]['PartNo'], 'time from : ', x.time(), ' to ', end.time())
start = sched_df.iloc[3]['Time']
end = sched_df.iloc[4]['Time']
print('Lunch time from : ', start.time(), ' to ', end.time())
xyz = sched_df.iloc[3]['Time'] - x
delta = xyz.total_seconds()
minutes = float(delta // 60)
z = demand_df.iloc[a]['TTJ'] - minutes
start = sched_df.iloc[4]['Time']
x = start + timedelta(minutes=z)
print(demand_df.iloc[a]['PartNo'], 'time from : ', start.time(), ' to ', x.time())
z = 0
a = a + 1
else:
print(demand_df.iloc[a]['PartNo'], 'time from : ', x.time(), ' to ', y.time())
x = y
a = a + 1
Any help will be appreciated.
I'm not sure what exactly your problem is, but if you say you are new to python programming you could read through some comparable projects.
A project that comes to my mind would be pyschedule for example. The solution approaches should be similar to those to your problem.
Decided to make a simple mp3 player for terminal. But while I was doing animation I had a problem - it blinks when the frame changes. Heres a video of it: https://youtu.be/in4VLPOfzHw. And the code:
import time, os, glob, eyed3, math, sys
from colorama import init
from mutagen.mp3 import MP3
mpts = glob.glob('*.mp3')
dark_grey = '\033[1;30;40m'
light_grey = '\033[0;37;40m'
white = '\033[1;37;40m'
lime = '\033[1;32;40m'
red = '\033[0;31;40m'
i = 0
song_list = []
for mpt in mpts:
song = MP3(mpt)
duration = math.ceil(song.info.length)
m_duration = duration // 60
s_duration = duration % 60
song = eyed3.load(mpt)
name = song.tag.title
song_list.append([name, [m_duration, s_duration]])
init()
# draw
while True:
# cassette
res = ''
i += 1
res += light_grey + ' ■̅̅̅̅̅̅̅̅̅̅̅̅■ \n'
res += dark_grey + ' |'
res += light_grey + '|############|'
res += dark_grey + '| \n'
res += dark_grey + ' |'
res += light_grey + '|'
if i % 4 == 0:
res += white + ' (/)====(/) '
elif i % 4 == 1:
res += white + ' (-)====(-) '
elif i % 4 == 2:
res += white + ' (\\)====(\\) '
elif i % 4 == 3:
res += white + ' (|)====(|) '
res += light_grey + '|'
res += dark_grey + '| \n'
res += dark_grey + ' |'
res += light_grey + '|############|'
res += dark_grey + '|\n'
res += light_grey + ' ■____________■ \n'
# green line
res += lime + ' ___________________________________\n\n'
# song list
res += red + ' # NAME TIME\n'
for i1 in range(len(song_list)):
res += dark_grey + ' ' + str(i1+1) + '.'
res += white + ' ' + song_list[i1][0] + ' '*(28 - len(song_list[i1][0])) + f'{song_list[i1][1][0]}:{song_list[i1][1][1]}\n'
os.system('cls')
sys.stdout.write(res)
sys.stdout.flush()
time.sleep(0.4)
Can it be fixed or sould I try to make in some other language instead of python?
It's the shelling out to cls that's doing it. Since you're already using ANSI codes for other stuff, try something like:
clear = '\033c'
...
while True:
...
print(clear)
Note that you'll never be able to completely get rid of the screen flicker using the "clear the screen then redraw it" technique, but this will shave several milliseconds from every loop and should decrease the flickering.
The idea is to avoid cleaning the whole screen (os.system('cls')). We could simply move the cursor to top and reprint everything. However moving cursor to top is almost impossible. One workaround I found is to print a lot of special characters that move cursor up one line until all the way to the top.
Reference:
cmd console game; reduction of blinking
The first solution of using \b does not work for me on a windows machine. So I go for the ender_scythe's solution. You have to print an empty line on first run to avoid the issue he/she mentioned. Here is the sample code that does not blink at all:
import time
import os
i = 0
dark_grey = '\033[1;30;40m'
light_grey = '\033[0;37;40m'
white = '\033[1;37;40m'
lime = '\033[1;32;40m'
red = '\033[0;31;40m'
def my_cls(nrow = 0):
if nrow == 0:
os.system('cls')
else:
print('\033[F'*nrow)
def my_display(chars):
print(''.join(chars))
return len(chars)
nrow = 0
while True:
my_cls(nrow)
# cassette
res = []
i+=1
if i == 1:
res.append('\n')
res.append(light_grey + ' ■̅̅̅̅̅̅̅̅̅̅̅̅■ \n')
res.append(dark_grey + ' |')
res.append(light_grey + '|###########|')
res.append(dark_grey + '| \n')
res.append(dark_grey + ' |')
res.append(light_grey + '|')
if i % 4 == 0:
res.append(white + ' (/)====(/) ')
elif i % 4 == 1:
res.append(white + ' (-)====(-) ')
elif i % 4 == 2:
res.append(white + ' (\\)====(\\) ')
elif i % 4 == 3:
res.append(white + ' (|)====(|) ')
res.append(light_grey + '|')
res.append(dark_grey + '| \n')
res.append(dark_grey + ' |')
res.append(light_grey + '|############|')
res.append(dark_grey + '|\n')
res.append(light_grey + ' ■____________■ \n')
# green line
res.append(lime + ' ___________________________________\n\n')
# song list
res.append(red + ' # NAME TIME\n')
nrow = my_display(res)
time.sleep(0.4)
How can I make the program print the CTRL+C to go BACK once down?[Look pictures][Picture][1]
while h < math.inf:
time2 = time.strftime("[%H" + ":%M" + ":%S]")
console = colorama.Fore.WHITE + time2 + '' + defaultname
file = open("Accounts/Failed.txt", "a+")
file2 = open("Accounts/Success.txt", "a+")
x = random.randrange(0, 100)
f = generator()
if x <= 97:
print(console + colorama.Fore.RED + "[FAILED] " + "0x" + f + ' ETH Wallet' + colorama.Fore.WHITE + ' CTRL+C to go BACK')
file.write(str(j) + ":0x" + f + "\n")
time.sleep(0.15)
j += 1
file.close()
elif x >= 97:
print(console + colorama.Fore.GREEN + "[SUCCESS] " + "0x" + f + ' ETH Wallet' + colorama.Fore.WHITE + ' CTRL+C to go BACK')
file2.write(str(h) + ":0x" + f + "\n")
time.sleep(0.15)
h += 1
file2.close()```
[1]: https://i.stack.imgur.com/Qa7Bw.png
So to print CTRL+C to go BACK only on the last loop iteration, you have too check if h + 1 is going to break the loop condition. To do so, you could check the condition h + 1 >= math.inf.
if h + 1 >= math.inf:
print("CTRL+C to go BACK")
This way you'll have to remove the CTRL+C to go BACK in your infos print functions
The function does what I want it to, but when it's done it just sits there rather than continuing from where I called it and I can't figure out why. The code is:
x = 9
y = 9
n = 10
ty = 1
tx = 1
while ty <= y:
while tx <= x:
vars()["p" + str(ty) + str(tx)] = 0
tx += 1
ty += 1
tx = 1
tn = 1
while tn <= n:
vars()["m" + str(tn)] = tn
tn += 1
t = x * y
tm = n
def recursion(z):
global tm
if z < n:
for x in range(n):
recursion(z + 1)
else:
if tm > 0:
tv = "m" + str(tm)
otm = eval(tv)
while eval(tv) < t - n + tm:
vars()[tv] = eval(tv) + 1
print(tv + " = " + str(eval(tv)))
vars()[tv] = otm + 1
print(tv + " = " + str(eval(tv)))
if tm > 1:
vars()["m" + str(tm - 1)] = eval("m" + str(tm - 1)) + 1
print(str("m" + str(tm - 1) + " = " + str(eval("m" + str(tm -1)))))
tm -= 1
recursion(1)
print("done")
I've put the return in where I would expect it to end but as far as I know it shouldn't actually need it.
Can anyone see what I've done to cause it to get stuck?
Thanks
Note for people not going through the change history: This is based on the comments on other answers. UPDATE: Better version.
import itertools
def permutations(on, total):
all_indices = range(total)
for indices in itertools.combinations(all_indices, on):
board = ['0'] * total
for index in indices:
board[index] = '1'
yield ''.join(board)
If anyone is interested in what the original code did, I rearranged the conditionals to prune the tree of function calls:
x = 9
y = 9
n = 10
ty = 1
tx = 1
while ty <= y:
while tx <= x:
vars()["p" + str(ty) + str(tx)] = 0
tx += 1
ty += 1
tx = 1
tn = 1
while tn <= n:
vars()["m" + str(tn)] = tn
tn += 1
t = x * y
tm = n
def recursion(z):
global tm
if tm > 0:
if z < n:
for x in range(n):
recursion(z + 1)
else:
tv = "m" + str(tm)
otm = eval(tv)
while eval(tv) < t - n + tm:
vars()[tv] = eval(tv) + 1
print(tv + " = " + str(eval(tv)))
vars()[tv] = otm + 1
print(tv + " = " + str(eval(tv)))
if tm > 1:
vars()["m" + str(tm - 1)] = eval("m" + str(tm - 1)) + 1
print(str("m" + str(tm - 1) + " = " + str(eval("m" + str(tm -1)))))
tm -= 1
recursion(1)
print("done")
This could be made much clearer through the use of lists and range objects, but that takes effort.
I wasn't able to work out what was happening (turns out if I left it for a few minutes it would actually finish though), instead, I realised that I didn't need to use recursion to achieve what I wanted (and I also realised the function didn't actually do what I want to do).
For anyone interested, I simplified and rewrote it to be a few while loops instead:
x = 9
y = 9
t = x * y
n = 10
tt = 1
while tt <= t:
vars()["p" + str(tt)] = 0
tt += 1
tn = 1
while tn <= n:
vars()["m" + str(tn)] = tn
vars()["p" + str(tn)] = 1
tn += 1
def cl():
w = ""
tt = 1
while tt <= t:
w = w + str(eval("p" + str(tt)))
tt += 1
p.append(w)
tm = n
tv = "m" + str(tm)
p = []
while m1 < t - n + tm - 1:
cl()
while tm == n and eval(tv) < t - n + tm:
vars()["p" + str(eval(tv))] = 0
vars()[tv] = eval(tv) + 1
vars()["p" + str(eval(tv))] = 1
cl()
tm -= 1
tv = "m" + str(tm)
while tm < n and tm > 0:
if eval(tv) < t - n + tm:
vars()["p" + str(eval(tv))] = 0
vars()[tv] = eval(tv) + 1
vars()["p" + str(eval(tv))] = 1
while tm < n:
tm += 1
ptv = tv
tv = "m" + str(tm)
vars()["p" + str(eval(tv))] = 0
vars()[tv] = eval(ptv) + 1
vars()["p" + str(eval(tv))] = 1
else:
tm -= 1
tv = "m" + str(tm)
while solving the same problem in python 3x on my machine, getting the correct output whereas during submission to hackerearth getting RunTimeError
for t in range(int(raw_input())):
i = list(map(int, raw_input().split()))
zom = []
vam = []
zc = 0
vc = 0
for x in i:
if x%2 == 0:
zom.append(x)
zc += x
else:
vam.append(x)
vc += x
zom.sort()
vam.sort()
zom.append(zc)
vam.append(vc)
print ' '.join(map(str, zom))+' '+' '.join(map(str, vam))
I don't know what is hackerearth but try this one.
for t in range(int(raw_input())):
i = list(map(int, raw_input().split()))
zom = []
vam = []
zc = 0
vc = 0
for x in i:
if x % 2 == 0:
zom.append(x)
zc += x
else:
vam.append(x)
vc += x
zom.sort()
vam.sort()
zom.append(zc)
vam.append(vc)
print ' '.join(map(str, zom)) + ' ' + ' '.join(map(str, vam))
x=input()
i = map(int, raw_input().split())
zom = []
vam = []
zc = 0
vc = 0
for x in i:
if x%2 == 0:
zom.append(x)
zc += x
else:
vam.append(x)
vc += x
zom.sort()
vam.sort()
zom.append(zc)
vam.append(vc)
print ' '.join(map(str,zom))+' '+' '.join(map(str, vam))
You acutally dont need a loop.