Skip to content

Instantly share code, notes, and snippets.

@wulinlw
Last active February 17, 2020 09:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wulinlw/b7f37207218b2973c0ba01e3f577629a to your computer and use it in GitHub Desktop.
Save wulinlw/b7f37207218b2973c0ba01e3f577629a to your computer and use it in GitHub Desktop.
#题目是给一个方法 foo(),能以各 50%的概率随机返回 0 或者 1。
#问题是基于 foo()方法,实现一个 boo()方法,该方法能以各 10%的概率返回[0-9]中的一个数字。
for i in range(10):
print("{:0>32b}".format(i), i)
import random
def foo():
return random.randint(0,1)
# 0000 0
# 0001 1
# 0010 2
# 0011 3
# 0100 4
# 0101 5
# 0110 6
# 0111 7
# 1000 8
# 1001 9
def bar():
s = []
for _ in range(4):
s.append(foo())
if s[0] and s[1]==0 and s[2]==0:
return 9 if s[3] else 8
if s[0]==0 and s[1]:
if s[2]:
return 7 if s[3] else 6
else:
return 5 if s[3] else 4
if s[0]==0 and s[1]==0 and s[2]:
return 3 if s[3] else 2
elif s[0]==0 and s[1]==0 and s[2] ==0:
return 1 if s[3] else 0
return bar()
# test
count = {}
for i in range(10):
count[i] = 0
for i in range(100000):
t = bar()
count[t] += 1
for i in range(10):
print(i, count[i])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment