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:
defcheck_value(my_list):
# if len is less than 2iflen(my_list) < 2:
if my_list and my_list[0] == 1:
returnTrueelse:
returnFalse
base_val = my_list[1] # as per the logic, it should be original number i.e num**1 for p, item inenumerate(my_list):
if item != base_val ** p:
returnFalseelse:
returnTrue
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:
defpowers(n):
for i in itertools.count(0):
yield n**i
defis_powers(li):
if li[0] == 1:
iflen(li) > 1:
returnall(x==y for x,y inzip(li,powers(li[1])))
returnTruereturnFalse
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()?"