Guess the result

Weiwei QI

2022/11/27

run python in RStudio

package required:

reticulate

# reticulate::py_config()
reticulate::py_config()$version_string
## [1] "3.8.8 (default, Apr 13 2021, 15:08:03) [MSC v.1916 64 bit (AMD64)]"

QuiiiiiizZ Time!

fun # 1: zero

number = "zero"

for number in range(10):
    number *= 2
    print(number)
  • A: zero
  • B: 9
  • C: 18
  • D: zerozero

fun # 2: animals

animals = ["Python", "Viper", "Cobra"]

def add_snake(snake_type):
    animals.extend(snake_type)
    print(animals)
    
item = ("Boa")
add_snake(item)
  • A: [“Python”, “Viper”, “Cobra”, “Boa”]
  • B: [“Boa]
  • C: [“Python”, “Viper”, “Cobra”, “B”, “o”, “a”]
  • D: Error

fun # 3: arguments

def func(*args):
    for arg in args:
        print(arg)

func(name="Alice", age = 25)

## hint: **args, then A

# func() got an unexpected keyword argument 'name'
  • A: name age
  • B: Alice 25
  • C: name Alice age 25
  • D: Error

fun # 4: list & dict

a = [(1,0), [2,3,1], {1:"x", 2:"y"}]

lst = list()

for n in a:
    lst.extend(n) # careful with the diff between extend and append
    
print(len(lst))
  • A: 3
  • B: 6
  • C: 7
  • D: 9
  • E: Error

fun # 5 parallel list comp

result_list = [x + y for x in ['A','B'] for y in ['C', 'D']]

print(result_list)
  • A: [‘AD’, ‘BC’]
  • B: [‘AC’, ‘BD’]
  • C: [‘AC’, ‘BC’, ‘AD’, ‘BD’]
  • D: [‘AC’, ‘AD’, ‘BC’, ‘BD’]
  • E: [‘AD’, ‘BC’, ‘AC’, ‘BD’]

fun # 6 “mirror” append

a = list()
a.append(a)
print(a)
  • A: [[]]
  • B: [[[]]]
  • C: [[…]]
  • D: Error

fun # 7 adding tuples

a = (1, 2)
b = (3, 4)
c = a+b
print(c)
  • A: (4,6)
  • B: (1,2,3,4)
  • C: None
  • D: Error

fun # 7.1

a = [1, 2]
b = [3, 4]
c = a+b
print(c)

fun # 7.2

a = [[1, 2]]
b = [[3, 4]]
c = a+b
print(c)

fun # 7.3

now, what if I want to have element-wise operations?

  • numpy built-in vector manipulation
import numpy as np

x = np.array([1,2,3])
y = np.array([2,3,4])
print(x+y)
  • Lambda
list1=[1, 2, 3]
list2=[4, 5, 6]
print(map(lambda x,y:x+y, list1, list2))

list(map(lambda x,y:x+y, list1, list2))
  • zip and list comprehension
list1=[1, 2, 3]
list2=[4, 5, 6]
print([x + y for x, y in zip(list1, list2)])