设为首页收藏本站

Crossin的编程教室

 找回密码
 立即加入
楼主: manhong2112
打印 上一主题 下一主题

新人報到

[复制链接]

1

主题

0

好友

207

积分

中级会员

Rank: 3Rank: 3

21#
发表于 2016-1-17 15:08:52 |只看该作者
【每周一坑】3道题
  1. def ex1(text):
  2.     i = {}
  3.     for j in text:
  4.         if j in i:
  5.             i[j] += 1
  6.         else:
  7.             i[j] = 1
  8.     return sorted(i.items(), key=lambda i: i[1], reverse=True)


  9. print(ex1("History is his story."))
复制代码
  1. def ex2():
  2.     from random import randint
  3.     from sys import exit

  4.     class Game:
  5.         thrownNumber = 0
  6.         gameRound = 0

  7.         def start_game(self):
  8.             self.gameRound += 1
  9.             print("New Game start, Round", self.gameRound)
  10.             self.thrownNumber = randint(3, 18)

  11.         def end_game(self, *players):
  12.             for i in players:
  13.                 player_score = 0
  14.                 player_score += i.bet.get("big", 0) * 2 if self.thrownNumber >= 11 else 0
  15.                 player_score += i.bet.get("small", 0) * 2 if self.thrownNumber < 11 else 0
  16.                 player_score += i.bet.get(str(self.thrownNumber), 0) * 10
  17.                 i.score += player_score
  18.                 i.bet = {}

  19.     class Player:
  20.         def __init__(self, player_id, score=100):
  21.             self.player_id = player_id
  22.             self.score = score
  23.             self.bet = {}

  24.         def add_bet(self, bet_type, bet_score):
  25.             if self.score - bet_score < 0:
  26.                 raise ValueError()
  27.             self.bet[bet_type] = self.bet.get(bet_type, 0) + bet_score
  28.             self.score -= bet_score

  29.     class Computer(Player):
  30.         def __init__(self, player_id, score=100):
  31.             super().__init__(player_id, score)

  32.         def add_bet(self):
  33.             for i in range(randint(1, 5)):
  34.                 try:
  35.                     bet_score = randint(1, int(self.score / randint(1, 5)) + 1)
  36.                     if randint(0, 1):
  37.                         super().add_bet("big" if randint(0, 1) else "small", bet_score)
  38.                     else:
  39.                         super().add_bet(str(randint(3, 18)), bet_score)
  40.                     pass
  41.                 except ValueError:
  42.                     break

  43.     comp = Computer("Computer")
  44.     player = Player(input("Input Your Name: \n> "))
  45.     game = Game()

  46.     # game main body
  47.     while True:
  48.         game.start_game()
  49.         # print(game.thrownNumber)

  50.         # read input
  51.         print("Input 'quit' to end game, input 'end' or leave blank to end input, input as '<type/number> <bet>' to bet")
  52.         while True:
  53.             tmp = input("> ")
  54.             if tmp == "end" or tmp == "": break
  55.             if tmp == "quit": exit(0)
  56.             tmp = tmp.split(" ")
  57.             try:
  58.                 player.add_bet(tmp[0], int(tmp[1]))
  59.             except ValueError:
  60.                 print("Over your existing score")
  61.             except IndexError:
  62.                 print("Wrong input, try again")

  63.         comp.add_bet()
  64.         print(comp.player_id, " bet ", comp.bet, sep="")
  65.         print(player.player_id, " bet ", player.bet, sep="")

  66.         game.end_game(player, comp)
  67.         print("Number is", game.thrownNumber)

  68.         print(comp.player_id, "'s score: ", comp.score, sep="")
  69.         print(player.player_id, "'s score: ", player.score, sep="")

  70.         print("=" * 24, sep="")


  71. ex2()
复制代码
回复

使用道具 举报

1

主题

0

好友

207

积分

中级会员

Rank: 3Rank: 3

22#
发表于 2016-1-17 15:10:38 |只看该作者
每周一坑 記帳本
  1. # coding: utf-8
  2. import pickle
  3. from datetime import datetime
  4. from sys import exit

  5. now = datetime.now()


  6. class Account:
  7.     def __init__(self, user_id=""):
  8.         self.account = {}
  9.         self.count = 0
  10.         self.user_id = user_id
  11.         with open('account.db', 'rb') as db:
  12.             try:
  13.                 self.user_id = pickle.load(db)
  14.                 self.account = pickle.load(db)
  15.                 self.count = pickle.load(db)
  16.             except EOFError:
  17.                 pass

  18.     def add_account(self, item, money):
  19.         int(money)
  20.         self.count += 1
  21.         self.account[self.count] = str(now.date()) + "|" + money + "|" + item

  22.     def check_money(self):
  23.         total = 0
  24.         for record_id in range(1, len(self.account) + 1):
  25.             total += int(self.account[record_id].split("|")[1])

  26.         print("== You have", total, "==")

  27.     def list_account(self):
  28.         print("Date\t\t$\t\tItem")
  29.         for record_id in range(1, len(self.account) + 1):
  30.             print(self.account[record_id].replace('|', "\t\t"))

  31.     def close_account(self):
  32.         with open('account.db', 'wb') as db:
  33.             pickle.dump(self.user_id, db)
  34.             pickle.dump(self.account, db)
  35.             pickle.dump(self.count, db)
  36.         print("Good Bye!")
  37.         exit(0)


  38. f = {"0": lambda x: x.close_account(),
  39.      "1": lambda x: x.add_account(input("Item > "), input("Money > ")),
  40.      "2": lambda x: x.check_money(),
  41.      "3": lambda x: x.list_account()}

  42. account = Account()

  43. while True:
  44.     print("What do you want? ")
  45.     print("  Add record to account, input 1")
  46.     print("  Check your money, input 2")
  47.     print("  List the log of your account, input 3")
  48.     print("  If you want to exit, input 0")
  49.     try:
  50.         f[input("> ")](account)
  51.     except KeyError:
  52.         print("Wrong Input")
  53.     except ValueError:
  54.         print("Wrong Value")
复制代码
回复

使用道具 举报

1

主题

0

好友

207

积分

中级会员

Rank: 3Rank: 3

23#
发表于 2016-1-17 15:21:01 |只看该作者
重命名目錄下資料夾外的所有檔案,不包括子目錄
會先重命名為md5 hash碼,若重複直接刪除
再順號碼重命名一次
  1. import os
  2. import hashlib


  3. def md5(file):
  4.     hash = hashlib.md5()
  5.     with open(file, "rb") as f:
  6.         for chunk in iter(lambda: f.read(8192), b""):
  7.             hash.update(chunk)
  8.     return hash.hexdigest()


  9. def rename(old, new, state):
  10.     new += '.' + old.split('.')[-1]
  11.     if not (state or old == new):
  12.         try:
  13.             os.remove(new)
  14.         except WindowsError:
  15.             {}
  16.     os.rename(old, new)


  17. def main():
  18.     for state in [0, 1]:
  19.         i = 1
  20.         for file in os.listdir('.'):
  21.             if file == 'rename.py' or os.path.isdir(file):
  22.                 continue
  23.             rename(file, str(i) if state else md5(file), state)
  24.             i += 1
  25.             # os.remove('rename.py')

  26. main()
复制代码
回复

使用道具 举报

1

主题

0

好友

207

积分

中级会员

Rank: 3Rank: 3

24#
发表于 2016-1-17 19:26:15 |只看该作者
本帖最后由 manhong2112 于 2016-1-23 19:45 编辑

B站視頻解析
把以前用js寫的插件 (雖然並沒有寫完) 功能用Python實現
輸入av號,輸出up主,硬幣數,收藏數,tag,視頻真實地址,彈幕地址等等等等..
  1. import urllib.request as urllib
  2. import json
  3. import html
  4. import sys

  5. api_1 = "http://api.bilibili.com"
  6. api_2 = "http://interface.bilibili.com"
  7. api_3 = "http://comment.bilibili.com"
  8.    
  9. bilibilijj = "http://www.bilibilijj.com"
  10. api_key = "8e9fc618fbd41e28"

  11. def get_json(url):
  12.     return json.loads(urllib.urlopen(url).read().decode("unicode-escape").replace('\r\n', ''))

  13. def printf(str, *obj):
  14.     print(str.format(*obj))

  15. def get_info(aid):
  16.     video_info = [get_json("{0}/view?type=json&appkey={1}&id={2}".format(api_1, api_key, aid))]
  17.     pages_num = video_info[0]['pages']
  18.     if pages_num > 2:
  19.         for i in range(1, a + 1):
  20.             video_info.append(get_json("{0}/view?type=json&appkey={1}&id={2}&page={3}".format(api_1, api_key, aid, i)))
  21.     return video_info

  22.    
  23. def print_info(video_info):
  24.     cid = video_info['cid']
  25.     link_info = get_json('{0}/playurl?type=mp4&otype=json&quality=4&appkey={1}&cid={2}'.format(api_2, api_key, cid))

  26.     try:
  27.         printf(">> cid: {0}", cid)
  28.         printf(">> Title: {0} Author: {1} Upload Time: {2}", html.unescape(video_info['title']), video_info['author'], video_info['created_at'])
  29.         printf(">> Play: {0} Coins: {1} Fav: {2} Pages: {3}", video_info['play'], video_info['coins'], video_info['favorites'], video_info['pages'])
  30.         printf(">> Type: {0} Tag: {1}", video_info['typename'], video_info['tag'].split(','))
  31.         printf(">> Description: {0}", html.unescape(video_info['description']))
  32.         printf(">> Danmu file link at: {0}/{1}.xml", api_3, cid)
  33.         printf(">> Video link at bilibilijj: {0}/freedown/spare/{1}.mp4", bilibilijj, cid)
  34.         try:
  35.             printf(">> Video link at: {0}", link_info['durl'][0]['url'])
  36.         except KeyError:
  37.             printf("E> Failed to get Video Link: {0}", link_info)
  38.             return
  39.     except KeyError:
  40.         print("E> Video not found")
  41.         printf("D> {0}", video_info)
  42.         return

  43. def main():
  44.     aid = input("aid of video \n> av")
  45.     video_info = []

  46.     try:
  47.         int(aid)
  48.     except ValueError:
  49.         print("Value Error")
  50.         return

  51.     try:
  52.         video_info = get_info(aid)
  53.     except KeyError:
  54.         printf("E> Video not found")
  55.         return

  56.     i = 0
  57.     for video_info in video_info:
  58.         i += 1
  59.         printf("\n>> ====== Page {0} ======", i)
  60.         print_info(video_info)

  61. main()
复制代码
EDIT: 新增多P支持...
回复

使用道具 举报

1

主题

0

好友

207

积分

中级会员

Rank: 3Rank: 3

25#
发表于 2016-1-20 20:18:50 |只看该作者
本帖最后由 manhong2112 于 2016-1-20 21:08 编辑

2048 bj4
  1. import random
  2. from copy import deepcopy as copy


  3. def print2048(block):
  4.     for i in range(len(block)):
  5.         print(str(block[i]).replace(", ", "]["))


  6. def get(block, x, y):
  7.     a = copy(block)
  8.     return a[y][x]


  9. def set(block, x, y, value):
  10.     a = copy(block)
  11.     a[y][x] = value
  12.     return a


  13. def add(block, x, y, value):
  14.     a = copy(block)
  15.     a[y][x] += value
  16.     return a


  17. def up(block):
  18.     a = copy(block)
  19.     for i in range(0, 4):
  20.         for x in range(0, 4)[::-1]:
  21.             for y in range(0, 3):
  22.                 if get(a, x, y + 1) == get(a, x, y) or get(a, x, y) == 0:
  23.                     a = add(a, x, y, get(a, x, y + 1))
  24.                     a = set(a, x, y + 1, 0)
  25.     return a


  26. def down(block):
  27.     a = copy(block)
  28.     for i in range(0, 4):
  29.         for x in range(0, 4):
  30.             for y in range(1, 4):
  31.                 if get(a, x, y - 1) == get(a, x, y) or get(a, x, y) == 0:
  32.                     a = add(a, x, y, get(a, x, y - 1))
  33.                     a = set(a, x, y - 1, 0)
  34.     return a


  35. def left(block):
  36.     a = copy(block)
  37.     for i in range(0, 4):
  38.         for x in range(0, 3):
  39.             for y in range(0, 4)[::-1]:
  40.                 if get(a, x + 1, y) == get(a, x, y) or get(a, x, y) == 0:
  41.                     a = add(a, x, y, get(a, x + 1, y))
  42.                     a = set(a, x + 1, y, 0)
  43.     return a


  44. def right(block):
  45.     a = copy(block)
  46.     for i in range(0, 4):
  47.         for x in range(1, 4):
  48.             for y in range(0, 4):
  49.                 if get(a, x - 1, y) == get(a, x, y) or get(a, x, y) == 0:
  50.                     a = add(a, x, y, get(a, x - 1, y))
  51.                     a = set(a, x - 1, y, 0)
  52.     return a


  53. def reset():
  54.     a = ([0, 0, 0, 0],
  55.          [0, 0, 0, 0],
  56.          [0, 0, 0, 0],
  57.          [0, 0, 0, 0])

  58.     return set(a, random.randrange(0,4), random.randrange(0,4), random.choice([2, 4]))


  59. def add_number(block):
  60.     a = copy(block)
  61.     b = []
  62.     for i in range(0, 4):
  63.         for j in range(0, 4):
  64.             if get(a, i, j) == 0:
  65.                 b.append((i, j))
  66.     if (not b) and right(a) == left(a) == up(a) == down(a):
  67.         print2048(a)
  68.         print("You lose")
  69.         exit()
  70.     if (not b) or right(a) == left(a) == up(a) == down(a):
  71.         return a

  72.     c = random.choice(b)
  73.     return set(block, c[0], c[1], random.choice([2, 4]))


  74. f = {"w": up,
  75.      "a": left,
  76.      "s": down,
  77.      "d": right}

  78. block2048 = reset()

  79. while 1:
  80.     block2048 = add_number(block2048)
  81.     print2048(block2048)
  82.     while 1:
  83.         try:
  84.             block2048 = f[input("Choose Direction (w a s d) > ")](block2048)
  85.         except KeyError:
  86.             print("E> Value Error")
  87.             continue
  88.         break
复制代码
回复

使用道具 举报

174

主题

45

好友

10万

积分

管理员

Rank: 9Rank: 9Rank: 9

26#
发表于 2016-1-21 11:20:10 |只看该作者
manhong2112 发表于 2016-1-20 20:18
2048 bj4

有意思。你可以用pygame把它做出来
#==== Crossin的编程教室 ====#
微信ID:crossincode
网站:http://crossincode.com
回复

使用道具 举报

1

主题

0

好友

207

积分

中级会员

Rank: 3Rank: 3

27#
发表于 2016-1-29 23:05:44 |只看该作者
2048 again, 讓它更符合2048的規則, 修改了好多就不放一起了
  1. import random
  2. from copy import deepcopy as copy


  3. class Game(object):
  4.     vector = {"w": (0, 1),
  5.               "s": (0, -1),
  6.               "a": (1, 0),
  7.               "d": (-1, 0)}

  8.     def __init__(self):
  9.         self.block = ([0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0])
  10.         self.recently_block = copy(self.block)
  11.         self.block[random.randint(0, 3)][random.randint(0, 3)] = random.choice((2, 4))
  12.         pass

  13.     def next(self):
  14.         loc_list = []
  15.         for x in range(4):
  16.             for y in range(4):
  17.                 if not self.block[x][y]:
  18.                     loc_list.append((x, y))

  19.         if loc_list:
  20.             if self.recently_block == self.block:
  21.                 return
  22.         else:
  23.             return self.movable()

  24.         loc = random.choice(loc_list)
  25.         self.block[loc[0]][loc[1]] = random.choice((2, 4))
  26.         pass

  27.     def end(self):
  28.         self.print()
  29.         print("# END #")
  30.         print("# Your Score is: {0} #".format(self.score()))
  31.         input("Enter to continue...")
  32.         exit()
  33.         pass

  34.     def move(self, direction, is_check=False):
  35.         cache = copy(self.block)
  36.         dx, dy = self.vector[direction]
  37.         i = ()
  38.         while i != cache:
  39.             i = copy(cache)
  40.             for x in (3, 2, 1, 0):
  41.                 for y in (3, 2, 1, 0):
  42.                     _x, _y = x - dx, y - dy
  43.                     if not (0 <= _x < 4 and 0 <= _y < 4):
  44.                         continue
  45.                     if cache[y][x] and (not cache[_y][_x] or cache[y][x] == cache[_y][_x]):
  46.                         cache[_y][_x] += cache[y][x]
  47.                         cache[y][x] = 0
  48.         if is_check:
  49.             return cache != self.block

  50.         self.recently_block = copy(self.block)
  51.         self.block = cache
  52.         pass

  53.     def movable(self):
  54.         for i in ('w', 'a', 's', 'd'):
  55.             if self.move(i, True):
  56.                 return True
  57.         self.end()
  58.         pass

  59.     def print(self):
  60.         for x in range(4):
  61.             for y in range(4):
  62.                 print(self.block[x][y], end=' ')
  63.             print()
  64.         pass

  65.     def score(self):
  66.         def _f(val, score=0):
  67.             for i in val:
  68.                 score += _f(i) if type(i) == list else i
  69.             return score
  70.         return _f(self.block)


  71. def main():
  72.     game = Game()
  73.     while True:
  74.         game.print()
  75.         print(game.score())
  76.         d = input("Choose Direction> ")
  77.         try:
  78.             game.move(d)
  79.         except KeyError:
  80.             continue
  81.         game.next()


  82. if __name__ == "__main__":
  83.     main()
复制代码
回复

使用道具 举报

1

主题

0

好友

207

积分

中级会员

Rank: 3Rank: 3

28#
发表于 2016-1-29 23:10:10 |只看该作者
crossin先生 发表于 2016-1-21 11:20
有意思。你可以用pygame把它做出来

現在我用的版本是Python 3.5 64bit, 但網上好像並沒有這版本
回复

使用道具 举报

174

主题

45

好友

10万

积分

管理员

Rank: 9Rank: 9Rank: 9

29#
发表于 2016-1-30 12:12:45 |只看该作者
manhong2112 发表于 2016-1-29 23:10
現在我用的版本是Python 3.5 64bit, 但網上好像並沒有這版本

这个版本官方好像没有,你搜搜看有没有其他人做的版本。比较常见的是2.7 32位版本
#==== Crossin的编程教室 ====#
微信ID:crossincode
网站:http://crossincode.com
回复

使用道具 举报

2

主题

0

好友

13

积分

新手上路

Rank: 1

30#
发表于 2016-2-19 23:13:07 来自手机 |只看该作者
javascriptnload=alert('123')
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即加入

QQ|手机版|Archiver|Crossin的编程教室 ( 苏ICP备15063769号  

GMT+8, 2024-4-19 10:44 , Processed in 0.028245 second(s), 20 queries .

Powered by Discuz! X2.5

© 2001-2012 Comsenz Inc.

回顶部