Python: Is There A Builtin That Works Similar But Opposite To .index()?
Just a forewarning: I just recently started programming and Python is my first language and only language so far. Is there a builtin that works in the opposite way of .index()? I'm
Solution 1:
As an answer to:
Is there a builtin I could use to input the position and return the item in the list?
You just need to access the list
with it's index as:
>>> my_list = [1,2,4,8,16]
>>> my_list[4]
16 # returns element at 4th index
And, this property is independent of language. All the languages supports this.
Based on your edit in the question, you may write your function as:
def check_value(my_list):
# if len is less than 2
if len(my_list) < 2:
if my_list and my_list[0] == 1:
return True
else:
return False
base_val = my_list[1] # as per the logic, it should be original number i.e num**1
for p, item in enumerate(my_list):
if item != base_val ** p:
return False
else:
return True
Sample run:
>>> check_value([1, 2, 4, 8])
True
>>> check_value([1, 2, 4, 9])
False
>>> check_value([1, 5, 25, 75])
False
Solution 2:
def powers(n):
for i in itertools.count(0):
yield n**i
def is_powers(li):
if li[0] == 1:
if len(li) > 1:
return all(x==y for x,y in zip(li,powers(li[1])))
return True
return False
is_powers([1, 2, 4, 8])
is_powers([1, 5, 25, 75])
maybe ... its really not clear what you are asking... this assumes that it always must start with a 1 if it is valid...
Post a Comment for "Python: Is There A Builtin That Works Similar But Opposite To .index()?"