0% found this document useful (0 votes)
2 views10 pages

PhysComp1 Lect10

The document provides examples of Python code demonstrating list comprehensions, including creating lists of squares and combinations, as well as converting input strings to integer lists. It also includes a brief section on calculating scalar and vector triple products. References to Python's official documentation for lists and tuples are provided.

Uploaded by

kfce1951
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views10 pages

PhysComp1 Lect10

The document provides examples of Python code demonstrating list comprehensions, including creating lists of squares and combinations, as well as converting input strings to integer lists. It also includes a brief section on calculating scalar and vector triple products. References to Python's official documentation for lists and tuples are provided.

Uploaded by

kfce1951
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Physics and

Computers

1
References

https://docs.python.org/3/library/stdtypes.html#lists

https://docs.python.org/3/library/stdtypes.html#tuples

2
listComprehension.py
squares = []
for x in range(1,11):
squares.append(x**2)
print('squares ',squares)

3
listComprehension.py
squares = []
for x in range(1,11):
squares.append(x**2)
print('squares ',squares)

squares2 = [x**2 for x in range(1,11)]


print('squares2',squares2)

4
listComprehension.py
squares = []
for x in range(1,11):
if x > 5:
squares.append(x**2)
print('squares ',squares)

squares2 = [x**2 for x in range(1,11) if x > 5]


print('squares2',squares2)

5
listComprehension.py
combs = []
for x in [1,2,3]:
for y in [3,1,4]:
if x != y:
combs.append((x, y))
print('combs ',combs)

combs1 = [(x, y) for x in [1,2,3] for y in [3,1,4] if x !=


y]
print('combs1',combs1)

6
listComprehension.py
inputs = input('Enter numbers\n')
mylist = inputs.split()
print('string list: ', mylist)

# convert each item to int type


for i,x in enumerate(mylist):
mylist[i] = int(x)

print('number list: ', mylist)

7
listComprehension.py
mylist = input('Enter numbers\n').split()
print('string list: ', mylist)

# convert each item to int type


mylist = [int(x) for x in mylist]
print('number list: ', mylist)

8
listComprehension.py
# in one line
mylist = [int(x) for x in input('Enter numbers\n').split()]
print('number list: ', mylist)

9
quiz.py
# use for-loops for scalar products
# vector triple product use a×(b×c) = (a·c)b - (a·b)c
Enter 3d vector a: 1 2 3
Enter 3d vector b: 1 5 7
Enter 3d vector c: 2 3 1
the a·(b×c) = -11
the a×(b×c) = (-53,−41,45)

10

You might also like