From random to XPath - python

I have 3 random generated numbers with random function
random = random.sample(range(1, 10), 3)
print (random)
Result is: [1, 6, 8]
and have XPath where need to change result for each number from result
For 1st number:
'//*[#id="app"]/div/div[3]/div/div[1]/div[1]/div'
For 2nd number:
'//*[#id="app"]/div/div[3]/div/div[1]/div[6]/div'
For 3rd number:
'//*[#id="app"]/div/div[3]/div/div[1]/div[8]/div'
Tried with for loop but not working
for i in random:
'//*[#id="app"]/div/div[3]/div/div[1]/div['+ i[0] +']/div'

In this case, your loop
for i in random
iterates for each element in the random list. If you were to print out i in the loop, you'll find it is an element of the list rather than a list itself. So it doesn't make sense to index it like you have done: i[0].
However, if you remove the indexing and just use i, you will still encounter a new error - since i is an integer and not a string - you can't concatenate an integer with strings. So, to correct this, you should cast it like this: str(i) and then it should work.
So the final solution would be:
xpath = '//*[#id="app"]/div/div[3]/div/div[1]/div['+ str(i) +']/div'
Alternative:
You can use Python 3's f-strings to avoid the string concatenation and type conversion:
xpath = f'//*[#id="app"]/div/div[3]/div/div[1]/div[{i}]/div'

Related

List updation statement showing index out of range

List=eval(input('enter list of numbers and string :'))
for x in range(1,len(List)+1,2):
List[x]=List[x]*2
print(List)
i want to update value at odd index but, why i don't know the statement 3 is generating error**List[x]=List[x]2 showing me error -index out of range**
There's three issues with your code:
eval() on user input is risky business. Use ast.literal_eval() instead.
Your for loop has an off-by-one error. Remember that array indices start at zero in Python.
List is not a good variable name, as it conflicts with List from the typing module. Use something like lst instead.
import ast
lst = ast.literal_eval(input('enter list of numbers and string :'))
for x in range(0, len(lst), 2):
lst[x] = lst[x] * 2
print(lst)

Display only 1 element when it's a repetition

I would like print a result without duplicate with my multiplication
Here an example :
5*3*2=30
2*3*5=30
5*2*3=30
3*2*5=30
.....
All these element are from my list that I browse and you can see it's always =30
So I would like display only the first element (5*3*2) and not others because they are the same.
To be more accurate, here an example what I have :
list = ['5*3*2','5*2*3','2*3*5','2*5*3']
for i in list:
if eval(i) == eval(i)+1 ??? (I dont know how to say the next element)
print(eval(i))
Thanks for reading
Something like this with not in will help you.
#python 3.5.2
list = ['5*3*2','5*2*3','6*9','2*3*5','2*5*3','8*3','9*6']
elm = []
for i in list:
elm_value = eval(i)
if elm_value not in elm:
elm.append(elm_value)
print(elm)
DEMO: https://rextester.com/QKV22875
The comparison:
eval(i) == eval(i)+1
Will compare if the the number i is equal to i + 1, which will always return False. I'm sure you mean to use i as an index and simply wanted to compare if the current element is equal to the next element in the list. However, doing this doesn't really keep track of duplicates, since you have to consider everything else in the list.
Its also not a good idea to use list as a variable name, since it shadows the builtin function list. Plenty of other suitable names you can use.
One way is to use a set to keep track of what items you have seen, and only print items that you have seen for the first time:
lst = ["5*3*2","5*2*3","2*3*5","2*5*3"]
seen = set()
for exp in lst:
calc = eval(exp)
if calc not in seen:
print(calc)
seen.add(calc)
If you are always dealing with simple multiplying expressions with the * operator(no brackets), you could also use functools.reduce and operator.mul instead to multiply the numbers instead of eval here. This will first split the numbers by *, map each number string to an integer, then multiply every element with each other.
from operator import mul
from functools import reduce
lst = ["5*3*2","5*2*3","2*3*5","2*5*3"]
seen = set()
for exp in lst:
numbers = map(int, exp.split("*"))
calc = reduce(mul, numbers)
if calc not in seen:
print(calc)
seen.add(calc)
Output:
30
With the following list:
l = ['5*3*2','5*2*3','2*3*5','2*5*3', '2*2']
(Note that list is already something in python so I wouldn't recommend using that as a variable name)
I would first create a list of unique values:
unique_vals = set(map(eval, list))
set([4, 30])
Then for each unique values get the first match in l:
[next(x for x in l if eval(x) == i) for i in unique_vals]
I get:
['2*2', '5*3*2']
Is that what you want?

How to add values into an empty list from a for loop in python?

The given python code is supposed to accept a number and make a list containing
all odd numbers between 0 and that number
n = int(input('Enter number : '))
i = 0
series = []
while (i <= n):
if (i % 2 != 0):
series += [i]
print('The list of odd numbers :\n')
for num in series:
print(num)
So, when dealing with lists or arrays, it's very important to understand the difference between referring to an element of the array and the array itself.
In your current code, series refers to the list. When you attempt to perform series + [i], you are trying to add [i] to the reference to the list. Now, the [] notation is used to access elements in a list, but not place them. Additionally, the notation would be series[i] to access the ith element, but this still wouldn't add your new element.
One of the most critical parts of learning to code is learning exactly what to google. In this case, the terminology you want is "append", which is actually a built in method for lists which can be used as follows:
series.append(i)
Good luck with your learning!
Do a list-comprehension taking values out of range based on condition:
n = int(input('Enter number : '))
print([x for x in range(n) if x % 2])
Sample run:
Enter number : 10
[1, 3, 5, 7, 9]

Trying to add the first & last integer of a list in python

Hi I have just started an online course for python, just for me, and one of the exercises is asking me to add the first and list integer from a list you input, I think I have it, but not too sure as it keeps giving me an error,
ValueError: invalid literal for int() with base 10
my code is
userList = list(map(int, input().split(',')))
intTotal = userList[1] + userList[len userList]
print (intTotal)
now, how I understand it the, [1] would be the first userList value, as it is the first position in the list, and the [len userList] should give me last position as it is giving the length of list as position number.
then it should print the variable intTotal
If you could show me where i am going wrong if it all that would be ace!
Your error is most likely that your input is something like 1, 2, 3, 4, 5,
When you use split(',') on this, you will have an extra empty entry at the end of your list that you must account for. You can check for this in a list comprehension.
To access the last element of the list, you may use arr[len(arr)-1], or in Python which supports negative indexing, arr[-1].
Here is a working version of your code with the above changes made:
userList = [int(x.strip()) for x in input().split(',') if x]
intTotal = userList[0] + userList[-1]
print (intTotal)
Sample run:
>>>1, 2, 3, 4, 5,
6
You could make this even more robust to filter out bad input by using isdigit(), which would allow for the user to enter letters, but it would only add the first and last numbers entered:
userList = [int(x) for x in input().split(',') if x.isdigit()]
Sample run:
>>> 1,2,a,3,4,6,b,4
5

Index error:list assignment index out of range

I want to:
Take two inputs as integers separated by a space (but in string form).
Club them using A + B.
Convert this A + B to integer using int().
Store this integer value in list C.
My code:
C = list()
for a in range(0, 4):
A, B = input().split()
C[a] = int(A + B)
but it shows:
IndexError: list assignment index out of range
I am unable understand this problem. How is a is going out of the range (it must be starting from 0 ending at 3)?
Why it is showing this error?
Why your error is occurring:
You can only reference an index of a list if it already exists. On the last line of every iteration you are referring to an index that is yet to be created, so for example on the first iteration you are trying to change the index 0, which does not exist as the list is empty at that time. The same occurs for every iteration.
The correct way to add an item to a list is this:
C.append(int(A + B))
Or you could solve a hella lot of lines with an ultra-pythonic list comprehension. This is built on the fact you added to the list in a loop, but this simplifies it as you do not need to assign things explicitly:
C = [sum(int(item) for item in input("Enter two space-separated numbers: ").split()) for i in range(4)]
The above would go in place of all of the code that you posted in your question.
The correct way would be to append the element to your list like this:
C.append(int(A+B))
And don't worry about the indices
Here's a far more pythonic way of writing your code:
c = []
for _ in range(4): # defaults to starting at 0
c.append(sum(int(i) for i in input("Enter two space-separated numbers").split()))
Or a nice little one-liner:
c = [sum(int(i) for i in input("Enter two space-separated numbers").split()) for _ in range(4)]

Categories