Chapter 20 Python vs R
Both Python and R are languages popular among biologists. Here we the differences between them based on a number of examples. This may help those, who already know R, t learn Python. Skip this chapter, if you are unfamiliar with R.
20.1 Sum of integers
Question: Computer the sum 1+2+...+10
20.1.1 Python Solution
sum=0
for i in range(1,11):
sum=sum+i
print(sum)
20.1.2 R Solution
(1:10) %>% sum
20.2 More Complex Sum
Question: Computer the sum 1^2 + 2^2 + ... + 10^2
20.2.1 Python Solution
sum=0
for i in range(1,11):
sum=sum+i*i
print(sum)
20.2.2 R Solution
((1:10)^2) %>% sum
20.3 Compute the sum 1*100 + 2*99+ ....+ 100*1
20.3.1 Python Solution
sum=0
for i in range(1,101):
sum=sum+i*(100-i)
print(sum)
20.3.2 R Solution
((1:100)*(100:1)) %>% sum
20.4 How many of (1*100, 2*99, 3*98, ..., 100*1)
are greater than 2000?
20.4.1 Python Solution
count=0
for i in range(1:101):
if(i*(100-i)>2000):
count=count+1
print(count)
Alternate solution using the numpy library -
import numpy
a=numpy.array(range(1,11))
b=numpy.array(range(1,11))
print(sum(a*b))
20.4.2 R Solution
v=(1:100)*(100:1)
(v>2000) %>% sum
20.5 What is the sum of members of (1*100, 2*99, 3*98, ..., 100*1)
greater than 2000?
20.5.1 Python Solution
sum=0
for i in range(1:101):
if(i*(100-i)>2000):
sum=sum+i*(100-i)
print(sum)
20.5.2 R Solution
v=(1:100)*(100:1)
(v*(v>2000)) %>% sum
20.6 Rotate a list of numbers
Question: Rotate a list of numbers so that the number in the first place goes to second, second to third and so on, and finally the last number moves to the first place.
20.6.1 Python Solution
x=[1,2,5,6,7,9]
L=len(x)
save=x[L-1]
for i in range(L-1,0,-1):
x[i]=x[i-1]
x[0]=save
print(x)
20.6.2 R Solution
x=c(1,2,5,6,7,9)
L=length(x)
c(x[2:L],x[1])
20.7 Check Whether a Number is Prime
20.7.1 Python Solution
N=73
prime=0
for i in range(2,73):
if(N%i==0):
prime=1
if(prime==0):
print("Yes, the number is prime")
else:
print("No, the number is not prime")
20.7.2 R Solution
N=73
v=N%%(2:(N-1))
matches=sum(v==0)
matches==0
N=42
v=N%%(2:(N-1))
matches=sum(v==0)
matches==0