Skip to content

Instantly share code, notes, and snippets.

@wb213
Created September 21, 2016 14:07
Show Gist options
  • Select an option

  • Save wb213/d50d02c6aa6aae1fefc6c26a1038de61 to your computer and use it in GitHub Desktop.

Select an option

Save wb213/d50d02c6aa6aae1fefc6c26a1038de61 to your computer and use it in GitHub Desktop.
Stock Price Question
#!/bin/env python
import sys
import random
global arr_len
global run_times
global ran_max
arr_len = 20 # Max length of the Array
run_times = 1 # How many times this program will run
ran_max = 10 # Max int random number will generate
def main_func():
list1 = [random.randint(1,ran_max) for x in range(arr_len)]
list2 = list()
out_diff = 0
for x in range(len(list1)-1):
val_min = list1[x]
val_max = max(list1[x+1:])
val_diff = val_max - val_min
pos_min = list1.index(val_min)
pos_max = list1[x+1:].index(val_max)+x+1
if pos_min > pos_max:
continue
if val_diff <= out_diff:
continue
elif val_diff > out_diff:
out_diff = val_diff
out_result = (pos_min,pos_max)
print "Input Stock Price:"
for x in range(arr_len):
print "Day %d, Price %d"%(x+1,list1[x]),
if x == out_result[0]:
print " <--- Buy"
elif x == out_result[1]:
print " ---> Sell"
else:
print "\n",
return
if __name__ == "__main__":
if len(sys.argv) >= 2:
arr_len = int(sys.argv[1])
if len(sys.argv) >= 3:
run_times = int(sys.argv[2])
for y in range(run_times):
print "Case # %d ==========================="%(y+1)
main_func()
@wb213
Copy link
Author

wb213 commented Sep 21, 2016

Sample Result

Case # 1 ===========================
Input Stock Price:
Day 1, Price 9
Day 2, Price 5
Day 3, Price 7
Day 4, Price 1    <--- Buy
Day 5, Price 7
Day 6, Price 9
Day 7, Price 8
Day 8, Price 10    ---> Sell
Day 9, Price 5
Day 10, Price 8
Case # 2 ===========================
Input Stock Price:
Day 1, Price 3
Day 2, Price 6
Day 3, Price 2
Day 4, Price 9
Day 5, Price 1    <--- Buy
Day 6, Price 6
Day 7, Price 9    ---> Sell
Day 8, Price 8
Day 9, Price 7
Day 10, Price 4
Case # 3 ===========================
Input Stock Price:
Day 1, Price 9
Day 2, Price 10
Day 3, Price 1    <--- Buy
Day 4, Price 5
Day 5, Price 7
Day 6, Price 9    ---> Sell
Day 7, Price 7
Day 8, Price 8
Day 9, Price 7
Day 10, Price 4
Case # 4 ===========================
Input Stock Price:
Day 1, Price 6
Day 2, Price 5
Day 3, Price 3    <--- Buy
Day 4, Price 3
Day 5, Price 10    ---> Sell
Day 6, Price 2
Day 7, Price 7
Day 8, Price 2
Day 9, Price 3
Day 10, Price 2
Case # 5 ===========================
Input Stock Price:
Day 1, Price 1    <--- Buy
Day 2, Price 3
Day 3, Price 3
Day 4, Price 1
Day 5, Price 5
Day 6, Price 1
Day 7, Price 4
Day 8, Price 3
Day 9, Price 10    ---> Sell
Day 10, Price 10

@wb213
Copy link
Author

wb213 commented Sep 21, 2016

运行命令实例python stock.py 10 3
运行时有2个参数,第一个参数是数组的长度,第二个参数是运行多少次
这里我偷懒就没有做一些边缘条件的检查了,数组的长度不能太短,运行次数也必须要大于1
还有一个随机数生成的上限我就没有做成参数,需要在代码里面改ran_max

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment