List prints letters and not strings? - python

I'm having a hard time getting the following to print correctly:
core = 1, 2, 3, 4, 5
glutes = 6, 7, 8, 9, 10
upper = 11, 12, 13, 14, 15
lower = 16, 17, 18, 19, 20
conditioning = 21, 22, 23, 24, 25
core_ability = int(input("Core: "))
glute_ability = int(input("Glutes: "))
if core_ability > 4:
upper_ability = int(input("Upper body: "))
else:
""
lower_ability = int(input("Lower body: "))
conditioning_ability = int(input("\nConditioning ability level:"))
newcore = core[0:core_ability]
newglutes = glutes[0:glute_ability]
if core_ability > 4:
newupper = upper[0:upper_ability]
newlower = lower[0:lower_ability]
newconditioning = conditioning[0:conditioning_ability]
if core_ability > 4:
movement_bank = str(newcore) + str(newglutes) + str(newupper) + str(newlower) + str(conditioning_ability)
else:
movement_bank = str(newcore) + str(newglutes) + str(newlower) + str(conditioning_ability)
sections = int(input("\nNumber of GPP sections in the session: "))
print("\nSPECIFY THE NUMBER OF MOVEMENTS PER SECTION")
if sections == 1:
section1_num = int(input("Section 1:"))
print(random.sample(movement_bank[0:], k=section1_num))
I get an output the looks like:
' ', ' ', 'r'
when I'd like to get something like:
'1', '16', '8'
I added "str()" to each list in the "movement_bank" list because without it I got an error of: TypeError: can only concatenate list (not "int") to list.
All help is greatly appreciated.

It seems, you have different lists, and want to combine them all into one list.
Use extend:
core = 1, 2, 3, 4, 5
glutes = 6, 7, 8, 9, 10
upper = 11, 12, 13, 14, 15
lower = 16, 17, 18, 19, 20
conditioning = 21, 22, 23, 24, 25
movement_bank = []
core_ability = int(input("Core: "))
movement_bank.extend(core[:core_ability])
glute_ability = int(input("Glutes: "))
movement_bank.extend(glutes[:glute_ability])
if core_ability > 4:
upper_ability = int(input("Upper body: "))
movement_bank.extend(upper[:upper_ability])
lower_ability = int(input("Lower body: "))
movement_bank.extend(lower[:lower_ability])
conditioning_ability = int(input("\nConditioning ability level:"))
movement_bank.extend(conditioning[:conditioning_ability])
sections = int(input("\nNumber of GPP sections in the session: "))
print("\nSPECIFY THE NUMBER OF MOVEMENTS PER SECTION")
if sections == 1:
section1_num = int(input("Section 1:"))
print(random.sample(movement_bank, k=section1_num))

Related

Is there any way to combine time and date in python using pandas?

I have 2 functions which gives output as date and time
def jdtodatestd (jdate):
if len(jdate) == 5:
fmt = '%y%j'
datestd = datetime.datetime.strptime(jdate, fmt).date()
return(datestd)
elif len(jdate) == 6:
yr = jdate[0:2]
day = jdate[2:len(jdate)]
day = day.lstrip('0')
jdate = yr+day
fmt = '%y%j'
datestd = datetime.datetime.strptime(jdate, fmt).date()
return(datestd)
elif len(jdate) == 7:
fmt = '%Y%j'
datestd = datetime.datetime.strptime(jdate, fmt).date()
return(datestd)
jdtodatestd('120365')
Output: datetime.date(2012, 12, 30)
def jdtotimestd (jtime):
if len(jtime) == 5:
jtime = '0' + jtime
elif len(jtime) == 6:
jtime = jtime
else:
jtime = '000000'
stdtime = jtime[0:2] + ':' + jtime[2:4] + ':' + jtime[4:6]
return stdtime
jdtotimestd('140932')
Output: '14:09:32'
I would like to combine both such as '2012, 12, 30 14:09:32
How can I do?
Modify your function jdtotimestd:
def jdtotimestd(jtime):
"""Returns a dt.time object from string."""
jtime = jtime.zfill(6)
return datetime.time(int(jtime[:2]), int(jtime[2:4]), int(jtime[4:]))
d = jdtodatestd('120365')
t = jdtotimestd('140932')
dt = datetime.datetime.combine(d, t)
Output:
>>> dt
datetime.datetime(2012, 12, 30, 14, 9, 32)
You can use strftime and strptime:
output1 = jdtodatestd('120365')
output2 = jdtotimestd('140932')
>>> datetime.datetime.strptime(datetime.datetime.strftime(output1, "%Y-%m-%d")+output2, "%Y-%m-%d%H:%M:%S")
datetime.datetime(2012, 12, 30, 14, 9, 32)

How to Find the Index of an Item in a sublist of a list (python)

ExampleList = [['Ck'], ['Kat'], ['Arcadiusz']]
ExampleListFull = [['CK', 21, 'Male'], ['Kat', 19, 'Female'], ['Arcadiusz', 30, 'Male']]
User = str(input())
User = User.capitalise()
if ([User] in ExampleList) == True:
From here we want to find the Index of "User", lets go with Kat, I know it's 1, 0,
However I want the program to be able to tell me for what ever name is
entered, this way I than can print
(User + '\'s', 'age is', (ExampleListFull(variable) (variable)))
ExampleListFull = [['CK', 21, 'Male'], ['Kat', 19, 'Female'], ['Arcadiusz', 30, 'Male']]
User = str(input())
User = User.capitalise()
Here, we create a dummy list with the values of all the names. This should print ['CK', 'Kat', 'Arcadiusz']
names = [value[0] for value in data]
print(names)
The one-line for-loop is the equivalent of doing:
names = []
for value in data:
names.append(value[0])
Then we can print the result
print(names.index(name))
print("Age is", {data[names.index(name)][1]})
This can all be shortened to just a few lines of code like this:
data = [['CK', 21, 'Male'], ['Kat', 19, 'Female'], ['Arcadiusz', 30, 'Male']]
User = str(input())
User = User.capitalise()
age = data[[value[0] for value in data].index(name)][1]
# gender= data[[value[0] for value in data].index(name)][2]
I would recommend you to use a dictionary as you data structure here but is you need a list you could try using the index method as follow:
ExampleList = [['Ck'], ['Kat'], ['Arcadiusz']]
x = ExampleList.index(['Ck'])
print(x)
Output:
0
This returns the position at the first occurrence of the specified value
ExampleList = [['Ck'], ['Kat'], ['Arcadiusz']]
ExampleListFull = [['CK', 21, 'Male'], ['Kat', 19, 'Female'], ['Arcadiusz', 30, 'Male']]
User = str(input())
User = User.capitalize()
for Index,string in enumerate(ExampleList):
if User == ExampleList[Index][0]:
print(User + 's', 'age is ' + str(ExampleListFull[Index][1]))

MyHDL free variables

Whenever I try to call this function in the MyHDL implementation of MD5 I've been working on I get this error:
File "/usr/local/lib/python2.7/dist-packages/myhdl/conversion/_misc.py", line 149, in raiseError
raise ConversionError(kind, msg, info)
myhdl.ConversionError: in file MD5-8, line 85:
Free variable should be a Signal or an int: calculate
Here is the entire script. If anyone has any light to shed on this or anything else that would be extremely helpful.
Thanks so much.
from myhdl import *
def operative(M0,M1,M2,M3,M4,M5,M6,M7,M8,M9,M10,M11,M12,M13,M14,M15,enable,clock):
singletick = 0
def toW32(x):
return(modbv(x, min=0, max=2**32)[32:])
def leftrotate(x, c):
return ((x<<c) | (x>>(32-c)) % (2**32))
def calculate(M, A, B, C, D, count):
KCONTENT = (0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee,0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501, 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821, 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8, 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391)
SCONTENT = (7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21)
F = int(0)
G = int(0)
#get G and F
if(count<=15):
if(count >=0):
F= (B&C)|((~B)&D)
G = int(count)
elif(count<=31):
if(count >= 15):
F = (D&B)|((~D)&C)
G = int(5*count +1) % 16
elif(count<=47):
if(count>=32):
F = (B^C^D)
G = int(3*count+5) % 16
elif(count <= 63):
if(count >= 48):
F = C^(B|(~D))
G = int(7*count) % 16
#swapping A through D and then calling again
temp = D
D = C
C = B
F = toW32(F)
G = toW32(G)
currentM = toW32(int(M[G]))
currentK = toW32(int(KCONTENT[count]))
currentS = toW32(int(SCONTENT[count]))
#B = leftrotate((((A + F) % (2**32) + (M[G]+KCONTENT[count]) % (2**32)) % (2**32)), SCONTENT[count])
A2 = toW32(A)
F2 = toW32(F)
bcomp0 = toW32((A2 + F2) % (2**32))
bcomp1 = toW32((currentM + currentK) % (2**32))
bcomp = toW32((bcomp0 + bcomp1) % (2**32))
bcomp2 = (leftrotate(bcomp, currentS))
B = toW32((B + bcomp2) % (2**32))
A = temp
print(B)
if(count>=63):
outA = (toW32((0x67452301+A) % (2**32)))
outB = (toW32((0xefcdab89+B) % (2**32)))
outC = (toW32((0x98badcfe+C) % (2**32)))
outD = (toW32((0x10325476+D) % (2**32)))
print(hex(concat(outA, outB, outC, outD)))
return(outA, outB, outC, outD)
else:
count = count + 1
calculate(M, A, B, C, D, count)
HALF_PERIOD = delay(10)
#always(HALF_PERIOD)
def clockGen():
clock.next = not clock
M = (M0,M1,M2,M3,M4,M5,M6,M7,M8,M9,M10,M11,M12,M13,M14,M15)
#always(clock.posedge)
def central():
if(enable == 1):
A = toW32(0x67452301)
B = toW32(0xefcdab89)
C = toW32(0x98badcfe)
D = toW32(0x10325476)
count = toW32(0)
final = int(0)
final = calculate(M, A, B, C, D, count)
return clockGen, central

Try every weighted combination of letters from the text result of tesseract

I've been testing text recognition from images using pyocr (tesseract-ocr and libetesseract). I've been applying various PIL.ImageFilters and getting the result of one specific string in the image. It has not been accurate, but I have 14 different results. Between all of them, all of the correct letters of the string in the image are there. So I have enumerated each string and created a dict containing the characters' position as keys that contain a dict of each character that has appeared in that position at keys and the number of occurrences as the value. Here's a shortened example
String In Image:
2HG2
Results:
#Note: this is not the actual order in which the strings are produced
2HC2
2HC2
2HCZ
2HOZ
2HOZ
2HOZ
2HOZ
2HGZ
2HGZ
2HGZ
ZHGZ
ZHGZ
ZH6Z
ZN6z
Dictionary:
{
0: {
u'2': 10,
u'Z': 4
}, 1: {
u'H': 13,
u'N': 1
}, 2: {
u'C': 3,
u'O': 4,
u'G': 5,
u'6': 2
}, 3: {
u'2': 2,
u'Z': 11,
u'z': 1
}
}
I'd like to try each combination of letters in each position until I get 2HG2. Any help would be appreciated.
EDIT:
The goal I'm trying to achieve is to scan a car registration, get text from it, and then populate a form with the data. As a proof of concept, I'm trying to get the VIN number from my person registration. At the moment, I'm (most likely naively) applying a series of PIL.ImageFilters and getting text from each. Below is my script.
import re
from itertools import permutations
from PIL import Image, ImageFilter
import pyocr
from pyocr import builders
vins = []
characters = {}
def validate(vincode):
"""
Validation code from https://en.wikipedia.org/wiki/Vehicle_identification_number
"""
maps = "0123456789X"
weights = [
8, 7, 6, 5, 4, 3, 2, 10, 0, 9, 8, 7, 6, 5, 4, 3, 2
]
table = {
"0": 0, "1": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9,
"A": 1, "B": 2, "C": 3, "D": 4, "E": 5, "F": 6, "G": 7, "H": 8,
"J": 1, "K": 2, "L": 3, "M": 4, "N": 5, "P": 7, "R": 9,
"S": 2, "T": 3, "U": 4, "V": 5, "W": 6, "X": 7, "Y": 8, "Z": 9,
}
if not isinstance(vincode, str) and not isinstance(vincode, unicode):
return False
if len(vincode) != 17:
return False
vincode = vincode.upper()
if "I" in vincode or "O" in vincode or "Q" in vincode:
return False
total = 0
for index, value in enumerate(vincode):
try:
products = table[value] * weights[index]
except KeyError:
break
total += products
index = total % 11
return maps[index] == vincode[8]
def get_text(tools_, img_):
for tool in tools_:
if tool.get_name() == 'Cuneiform (sh)':
continue
# print '=======================\nUsing {}\n======================='.format(tool.get_name())
boxes = tool.image_to_string(img_, lang='eng', builder=builders.WordBoxBuilder())
global vins
pattern = re.compile('[\W_]+')
vins += [pattern.sub('', x.content) for x in boxes if len(pattern.sub('', x.content)) == 17]
# boxes = [x for x in boxes if len(x.content.strip()) != 0]
# print boxes[3].content
# for box in boxes:
# print box.content
def apply_filters_and_get_text(img_, filter_):
for x in range(1, 5):
print 'Applying {} size: {}'.format(str(filter_), x)
try:
img_ = img_.filter(filter_(x))
except ValueError:
print 'error on {} size: {}'.format(str(filter_), x)
continue
img_.save('tmp{}-{}.jpg'.format(str(filter_), x))
get_text(tools, img_)
def count_occurrences(value):
global characters
for index, c in enumerate(value):
if index in characters and c in characters[index]:
characters[index][c] += 1
continue
if index in characters and isinstance(characters[index], dict):
characters[index][c] = 1
continue
characters[index] = {c: 1}
tools = pyocr.get_available_tools()
img = Image.open('images/test18.jpg')
# get_text(tools)
# img = img.filter(ImageFilter.MaxFilter(5))
# img = img.filter(ImageFilter.SHARPEN)
# img = img.filter(ImageFilter.SMOOTH_MORE)
# get_text(tools)
# get_text(tools)
img = img.convert('L')
# get_text(tools)
# img = img.filter(ImageFilter.MaxFilter(5))
# img = img.filter(ImageFilter.SHARPEN)
# img = img.filter(ImageFilter.SMOOTH_MORE)
# get_text(tools)
# get_text(tools)
img = img.point(lambda x: 0 if x < 128 else 255, '1')
apply_filters_and_get_text(img, ImageFilter.MedianFilter)
apply_filters_and_get_text(img, ImageFilter.MinFilter)
apply_filters_and_get_text(img, ImageFilter.MaxFilter)
apply_filters_and_get_text(img, ImageFilter.ModeFilter)
for vin in vins:
count_occurrences(vin)
# print vin
# print validate(vin)
print characters
I was able to figure out a recursive function that tries every combination of the letters with priority to characters with higher weight.
def determine_character(characters_, tried=[]):
next_character = ""
current_rank = 0
for ch in characters_:
if characters_[ch] > current_rank and ch not in tried:
next_character = ch
return next_character
def determine_weight(word):
global characters
weight = 0
for index, ch in enumerate(word):
weight += characters[index][ch]
return weight
def descramble(word="", index=0):
global characters
count = len(characters)
if index == count and validate(word):
global vin_count, valid_vins
vin_count += 1
valid_vins.append({'vin': word, 'weight': determine_weight(word)})
return {'word': word, 'done': True}
if index == count:
return False
tried = []
while len(tried) < len(characters[index]):
ch = determine_character(characters[index], tried)
tried.append(ch)
next_index = index + 1
descramble("{word}{ch}".format(word=word, ch=ch), next_index)

Python multiprocessing , code keep on executing?

from multiprocessing import Process , Queue
from datetime import datetime
c = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27]
out = Queue()
def support(m):
for k in m :
print "%s <-- hi" % k
out.put("done")
all = Queue()
temp = []
total = len(c)
count = 0
for m in c :
count += 1
total = total - 1
temp.append(m)
if count == 5 or total == 0 :
all.put(temp)
count = 0
temp = []
process_count = 3
while all.qsize() != 0 :
process_list = []
try :
for x in range(process_count) :
p = Process(target=support, args=(all.get(),))
process_list.append(p)
for p in process_list :
p.start()
for p in process_list :
p.join()
except Exception as e :
print e
while out.qsize != 0 :
print out.get()
print "all done"
I dont know why it does not end and does not print "all done" , just remain continuously in loop or keep executing .
Will be of great help if you can make this code more efficient but first i want to know why it does not end .
The problem is:
while out.qsize != 0 :
print out.get()
out.qsize is a function, so now you're comparing the function itself (not the return value!) with 0, with is of course always False.
You should use:
while out.qsize() != 0 :
print out.get()

Categories