How can I fix this index error? - python-3.x

Well this is the code I have written so far
import csv
file = open("gardeningJobs.txt", "r")
read= csv.reader(file)
ls=list(read)
file.close()
print(ls)
total=0
status = " A"
for line in ls:
if (int(line[3] - int(line[4]) = 0):
total += int(line[4])
print(total)
The error occures in this line of code if (int(line[3] - int(line[4]) = 0):
1234, 27/02/2016, A56, 125, Q, 0
1235, 27/02/2016, A26, 250, A, 125
1236, 27/02/2016, A36, 300, N, 0
1237, 27/02/2016, A55, 170, Q, 0
1238, 28/02/2016, A59, 90, A, 90
1240, 28/02/2016, A60, 260, A, 120
This is the 2D array that goes with it in a file
Please any kind of help is appreciated

Your code should be this:
if int(line[3]) - int(line[4]) == 0:
== instead of = and int(line[3]).

Related

how do I convert following python code to recursion

I wish to generate a sequence of numbers such that I get:
(n - 10)^2, (n - 9)^2, ... n^2, ... (n + 9)^2, (n + 10)^2
I have the following code that does that via a loop:
def a_func(number):
start = -10
result = []
while start <= 10:
result.append((number + start) ** 2)
start += 1
return result
How would I go about doing the same with recursion?
The tricky part (in my mind) is determining how to "start" and "stop" based on your range between -10 and 10. Let's look at how we might do that with a closure.
Conceptually we are going to:
def func_a(n):
## ---------------
## Do "something" based on "n" and the current value of "i"
## ---------------
def func_b(n,i):
## ---------------
## i is larger than our stopping point to stop
## ---------------
if i > from_to[1]:
return []
## ---------------
## ---------------
## i is within range so calculate "this" value
## and append all the additional values
## ---------------
return [(n + i)**2] + func_b(n, i+1)
## ---------------
## ---------------
## ---------------
## This variable hidden inside the closure will allow
## us to specify where to start and stop our recursion
## ---------------
from_to = (-10, 10)
## ---------------
return func_b(n, from_to[0])
print(func_a(10))
Now let's clean it up a bit with a lambda:
def func_a(n):
from_to = (-10, 10)
func_b = lambda n, i: [(n + i)**2] + func_b(n, i+1) if i <= from_to[1] else []
return func_b(n, from_to[0])
print(func_a(10))
This prints:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400]
Technically, from_to is not needed if you are happy hard coding those values. In that case you might do simply:
def func_a(n):
func_b = lambda n, i: [(n + i)**2] + func_b(n, i+1) if i <= 10 else []
return func_b(n, -10)
print(func_a(10))

Adding items to a deque() via a generator

I have a prime number generator. The yielded items are cast into a list. I can reference any item in the list.
def primes(limit):
yield 2
if limit < 3:
return
lmtbf = (limit - 3) // 2
buf = [True] * (lmtbf + 1)
for i in range((int(limit ** 0.5) - 3) // 2 + 1):
if buf[i]:
p = i + i + 3
s = p * (i + 1) + i
buf[s::p] = [False] * ((lmtbf - s) // p + 1)
for i in range(lmtbf + 1):
if buf[i]:
yield i + i + 3
x = list(primes(100))
print(x)
print(len(x), '\n')
Output:
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
25
The problem is if I use x = list(primes(num)) with a very large number then the resultant list becomes
extremely large.
All I want are the last n (the largest) items in the list, but I would to be able to vary n.
I thought a deque() would be perfect for this. I was looking through documentation and I found: Appending to a deque that is full (len(d) == d.maxlen) discards items from the other end.
This, combined with the ability to specify a maxlen=n at queue creation is exactly what I want.
With that in mind, I tried this:
from collections import deque
def primes(limit):
yield 2
if limit < 3:
return
lmtbf = (limit - 3) // 2
buf = [True] * (lmtbf + 1)
for i in range((int(limit ** 0.5) - 3) // 2 + 1):
if buf[i]:
p = i + i + 3
s = p * (i + 1) + i
buf[s::p] = [False] * ((lmtbf - s) // p + 1)
for i in range(lmtbf + 1):
if buf[i]:
yield i + i + 3
x = deque([primes(100)], maxlen=10)
# x = list(primes(100))
print(x)
print(len(x), '\n')
But what I get is this:
deque([<generator object primes at 0x0000025ED8449C80>], maxlen=10)
1
I also tried:
for i in x:
print(x)
But that also does not work.
How can I use deque() as I described above to get my desired result?
I need to be able to print out the contents of the deque, which should be the last n items from the generator.
Figured it out: x = deque([x for x in primes(100)], maxlen=10)
deque([53, 59, 61, 67, 71, 73, 79, 83, 89, 97], maxlen=10)
10
x = deque([x for x in primes(1000)], maxlen=10)
deque([937, 941, 947, 953, 967, 971, 977, 983, 991, 997], maxlen=10)
10

Rainbow Animated Text

Im trying to make an animated rainbow text (left to right) so far everything was working until it reached the final of the colors list (c list) and when I try to rollback (if x == 18: ; x = 0) it dosent work
Please help
import os
import time
from sty import fg, bg, ef, rs, RgbFg
c = [196, 202, 208, 214, 220, 226, 190, 118, 121, 122, 123, 75, 33, 21, 93, 171, 201, 199]
w = "ElapsedTime"
#fg(c[0]) + w[0] + fg(c[0]) + w[1] + fg(c[0]) + w[2] + fg(c[0]) + w[3] + fg(c[0]) + w[4]
final = []
n = 0
def clear():
time.sleep(.01)
os.system("clear")
def d001(x):
y = 0
while True:
f101 = fg(c[x]) + w[y]
final.append(f101)
x = x+1
if x == 18:
x = 0
if y == 10:
break
y = y+1
print("".join(final))
final.clear()
while True:
d001(n)
print(n)
n = n+1
if n == 20:
break
X and Y both will increase by 1 and y == 10 become true before x == 18 and break the loop

How do i call out variable from a function in another function?-Python3

def run():
rundecision=input("What do you want to do? calculate distance(d),pace(p) time(t):")
if rundecision in ['distance', 'd']:
pace()
time()
distance=calculator(distance=None,pace=pacetotal,time=timetotal)
return str(distance) + paceunit
print (run())
my pace() is below where pace total is defined and called out above.
def pace():
while True:
pacemin=input("Enter what pace you want to run/ you ran in :00(min):")#user pace in min
pacesec=input("Enter what pace you want to run/ you ran in :00(secs):")#user pace in sec
try:
pacemin=int(pacemin)
pacesec=int(pacesec)
if 0 <= pacemin <= 59 and 0 <= pacesec <=59:
pacetotal=(to_seconds(pacemin,'min')) + (to_seconds(pacesec,'s'))
pacetotal=int(pacetotal)
return pacetotal
break
)
This is my error:
Traceback (most recent call last): File "minicapstonev2.py", line
188, in
print (run()) File "minicapstonev2.py", line 185, in run
distance=calculator(distance=None,pace=pacetotal,time=timetotal)
NameError: name 'pacetotal' is not defined
You have to assign the return values of your functions to a variable that u can use:
if rundecision in ['distance', 'd']:
pacetotal = pace() # pace returns the seconds
timetotal = time() # this should also return the value for your next computation
distance=calculator(distance=None,pace=pacetotal,time=timetotal)
return str(distance) + paceunit
You did not supply the time() function, but if it is similar to pace this should work.
Edit due to question in comments:
Some variations on how to approach returnvalues and your program:
# Different ways to return something from a function
def ModifyGivenDict(di , li):
# do some calculations
di["milesPerHour"] = 42
li.append(999)
def ReturnAValue(x):
return x ** x
def ReturnMultipleValues(x):
return [x * u for u in range(20)]
def ReturnTuple(x,y):
return (x,y,x * y,x ** y,y ** x,"someValue")
d = {"Round1": 496 }
l = [2,3,4,5,"Hurray"]
a = ModifyGivenDict(d,l)
print(d)
k = ReturnAValue(22)
print(k)
i = ReturnMultipleValues(22)
print(i)
h = ReturnTuple(4,7)
print(h)
# OOP aproach
class Timings:
#staticmethod
def toSeconds(text):
"""Understands up to '12:18:24.3545' - returns a floatvalue of seconds"""
t = [0,0] + text.split(":") # prefix with 2 * 0 if only "22" or "1:22" is given
t[-1] = float(t[-1]) # make last elements to float
t[-2] = int(t[-2]) * 60 # make integer minutes into seconds
t[-3] = int(t[-3]) * 60 * 60 # make integer hours into seconds
return sum(t)
#staticmethod
def toMeters(distance):
"""Understands '255.23 meters'"""
converterDict = {'mile':1609.34, 'mi':1609.34, 'km':1000, 'kilometer':1000,
'y':0.9144, 'yard':0.9144, 'meter':1, 'm':1}
dist,unit = distance.split(" ")
dist = float(dist)
unit = unit.rstrip("s").strip().lower()
return dist * converterDict[unit]
def __init__(self, name):
self.name = name
self.laps = {}
self.lap = 0
def addLap(self, minutesColonSeconds, distance):
t = self.toSeconds(minutesColonSeconds)
m = self.toMeters(distance)
self.laps[self.lap] = {"time":t, "distance":m}
self.lap += 1
def printLaps(self):
print("Results for " + self.name,sep="\t")
print("{:<14} {:<14} {:<14} {:<14} {:<14} {:<14} {:<14}".format(
"lap","m","s","m/s", "total time", "total dist","speed"))
tm = 0
tt = 0
# you could also use an orderedDict from collections
for k in sorted(self.laps.keys()):
m = self.laps[k]["distance"]
t = self.laps[k]["time"]
tm +=m
tt += t
print("{:<14} {:<14} {:<14} {:<14} {:<14} {:<14} {:<14}".format(
k,m,t,round(m / t,2), tt,tm,round(tm/tt,2)))
def inputTime(text):
while True:
i = input(text)
try:
t = [0,0] + i.split(":")
sec = float(t[-1])
min = int(t[-2])
hou = int(t[-3])
if sec+min*60+hou*60*60 <= 0:
raise ValueError
return i
except (ValueError,EOFError):
print("Wrong input! Use '1:12:23.99' for hour:minute:second.partials")
def inputDistance(text):
while True:
t = input(text)
try:
dis,un = t.split()
dis = float(dis)
return t
except:
print("Wrong input. Use: '23 km' - or: meter, mile(s), yard(s), m, mi, y")
print("\nClassaproach\n\n")
timing = Timings("Just Me")
while True:
dis = inputDistance("What distance did you cover?")
tim = inputTime("In what time?")
timing.addLap(tim,dis)
timing.printLaps()
Output (edited to better fit here):
{'Round1': 496, 'milesPerHour': 42}
341427877364219557396646723584
[0, 22, 44, 66, 88, 110, 132, 154, 176, 198, 220, 242, 264, 286,
308, 330, 352, 374, 396, 418]
(4, 7, 28, 16384, 2401, 'someValue')
Classaproach
What distance did you cover?100 m
In what time?12.02
Results for Just Me
lap m s m/s total time total dist speed
0 100.0 12.02 8.32 12.02 100.0 8.32
What distance did you cover?20 km
In what time?2:0:01
Results for Just Me
lap m s m/s total time total dist speed
0 100.0 12.02 8.32 12.02 100.0 8.32
1 20000.0 7201.0 2.78 7213.02 20100.0 2.79
What distance did you cover?5 mi
In what time?1:1:1
Results for Just Me
lap m s m/s total time total dist speed
0 100.0 12.02 8.32 12.02 100.0 8.32
1 20000.0 7201.0 2.78 7213.02 20100.0 2.79
2 8046.7 3661.0 2.2 10874.02 28146.7 2.59
What distance did you cover?120 km
In what time?1:02:00
Results for Just Me
lap m s m/s total time total dist speed
0 100.0 12.02 8.32 12.02 100.0 8.32
1 20000.0 7201.0 2.78 7213.02 20100.0 2.79
2 8046.7 3661.0 2.2 10874.02 28146.7 2.59
3 120000.0 3720.0 32.26 14594.02 148146.7 10.15
What distance did you cover?
...

Lane Departure Warning System for Autonomous Driving- TypeError: expected non-empty vector for x

I'm using this program from github https://github.com/JunshengFu/driving-lane-departure-warning . I am trying to run a video file and i get below errors
File "/home/ramakrishna/PycharmProjects/Lanedect/driving-lane-departure-warning-master/lane.py", line 602, in process_frame
detector(binary_sub, ploty, visualization)
File "/home/ramakrishna/PycharmProjects/Lanedect/driving-lane-departure-warning-master/lane.py", line 554, in detector
left_fit, right_fit = full_search(binary_sub, visualization=visualization)
Code:
def detector(binary_sub, ploty, visualization=False):
left_fit, right_fit = full_search(binary_sub, visualization=visualization)
left_fitx = left_fit[0] * ploty**2 + left_fit[1] * ploty + left_fit[2]
right_fitx = right_fit[0] * ploty**2 + right_fit[1] * ploty + right_fit[2]
std_value = np.std(right_fitx - left_fitx)
File "/home/ramakrishna/PycharmProjects/Lanedect/driving-lane-departure-warning-master/lane.py", line 294, in full_search
right_fit = np.polyfit(righty, rightx, 2)
Code :
# Fit a second order polynomial to each
left_fit = np.polyfit(lefty, leftx, 2)
right_fit = np.polyfit(righty, rightx, 2)
File "/usr/local/lib/python3.4/dist-packages/numpy/lib/polynomial.py", line 555, in polyfit
raise TypeError("expected non-empty vector for x")
Code :
if x.size == 0:
raise TypeError("expected non-empty vector for x")
if y.ndim < 1 or y.ndim > 2:
raise TypeError("expected 1D or 2D array for y")
TypeError: expected non-empty vector for x

Resources