blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
55f6250afbc40ef2ff82cc69d7ce136b5e61df6d
ml758392/python_tedu
/python2/Day3_modlue_oop/pycharm/oop_5.py
593
3.625
4
# -*-coding:utf-8-*- class A: def foo(self): print('你好!') class B: def bar(self): print('How are you?') def pstar(self): print('@'*20) class C(A, B): def pstar(self): print('*'*20) if __name__ == '__main__': c = C() # 子类的实例继承了所有父类的方法 c.foo() # 如果多个父类有同名的方法,查找顺序是从上向下,从左到右 c.bar() # 也就是先查子类,再查父类,父类按定义顺序从左到右查找 c.pstar() # 子类和父类有同名的方法先查子类
6e507249b67a8332e0dab307a9f168cb597fbc68
ml758392/python_tedu
/python1/Day2_基础/pycharm/login_2.py
183
3.609375
4
#-*-coding:utf-8-*- user = input("username:") passwd = input("password:") if user == "yy" and passwd == "123456": print("Login successful") else: print("Login inorrect")
6af0400e64f62fd553527c7b57719a03968c7a8e
ml758392/python_tedu
/nsd2018-master/nsd1804/python/day08/count_patt2.py
544
3.546875
4
import re from collections import Counter class CountPatt: def __init__(self, patt): self.cpatt = re.compile(patt) def count_patt(self, fname): result = Counter() with open(fname) as fobj: for line in fobj: m = self.cpatt.search(line) if m: result.update([m.group()]) return result if __name__ == '__main__': count_ip = CountPatt('^(\d+\.){3}\d+') a = count_ip.count_patt('access_log') print(a) print(a.most_common(3))
5f8e4ec42ea9dfd48be6dc1e84a4c9a3d7895cad
ml758392/python_tedu
/python100例/Python100Cases-master/100examples/077.py
90
3.578125
4
l=['moyu','niupi','xuecaibichi','shengfaji','42'] for i in range(len(l)): print(l[i])
38f3d5077db94d81a8e8e7d212237be0521b926e
ml758392/python_tedu
/python2/Tkinter/5.点击按钮输出输入框中的内容.py
425
3.546875
4
# -*-coding:utf-8-*- import tkinter # 创建主窗口 win = tkinter.Tk() # 设置标题 win.title("YY") # 设置大小和位置 长x宽 距离 win.geometry('400x400+200+200') def showinfo(): print(entry.get()) entry = tkinter.Entry(win) entry.pack() button =tkinter.Button(win, text='提交', command=showinfo) button.pack() # 进入消息循环 win.mainloop() if __name__ == '__main__': pass
f1b0fb2020b926fb8e9a9971b3dc0a3a584b4bbe
ml758392/python_tedu
/nsd2018-master/nsd1802/python/day02/while_break.py
482
3.78125
4
# yn = input('Continue(y/n): ') # # while yn not in 'nN': # print('running...') # yn = input('Continue(y/n): ') # python DRY原则: Don't Repeat Yourself while True: yn = input('Continue(y/n): ') if yn in ['n', 'N']: break print('running...') ############################################# sum100 = 0 counter = 0 while counter < 100: counter += 1 # if counter % 2: if counter % 2 == 1: continue sum100 += counter print(sum100)
b49f84b9ae3a5bceb5d069432a33a5200cea8b98
ml758392/python_tedu
/nsd2018-master/nsd1802/python/day04/list_method.py
603
3.765625
4
alist = [1, 2, 3, 'bob', 'alice'] alist[0] = 10 alist[1:3] = [20, 30] alist[2:2] = [22, 24, 26, 28] alist.append(100) alist.remove(24) # 删除第一个24 alist.index('bob') # 返回下标 blist = alist.copy() # 相当于blist = alist[:] alist.insert(1, 15) # 向下标为1的位置插入数字15 alist.pop() # 默认弹出最后一项 alist.pop(2) # 弹出下标为2的项目 alist.pop(alist.index('bob')) alist.sort() alist.reverse() alist.count(20) # 统计20在列表中出现的次数 alist.clear() # 清空 alist.append('new') alist.extend('new') alist.extend(['hello', 'world', 'hehe'])
b286bc4bd3179f174b808381c6f408bd80e2bcfe
ml758392/python_tedu
/python2/Day3_modlue_oop/pycharm/9.重写__repr__与__str__.py
807
4.15625
4
# -*-coding:utf-8-*- """ 重写:可将函数重写定义一遍 __str__() __repr__() """ class Person(object): """ :param :parameter """ def __init__(self, name, age): self.name = name self.age = age def myself(self): print("I'm %s , %s years old " % (self.name, self.age)) # __str__()在调用print打印对象时自动调用,是给用户用的,是一个描述对象的方法 def __str__(self): return 'person' # __repr__():给机器用的,再python解释起里面直接敲对象名在回车后调用的方法 def __repr__(self): return 'ppp' person1 = Person('yy', 18) print(person1.__dict__) print(person1.__class__) print(person1.__doc__) print(person1.__dir__()) print(person1.__repr__()) print(person1)
2c30c0c30b5075e5d27f93544cfadb95467c85fe
ml758392/python_tedu
/python2/Day3_modlue_oop/继承/worker.py
432
3.5625
4
# -*-coding:utf-8-*- from person import Person class Worker(Person): def __init__(self, name, age, money): super(Worker, self).__init__(name, age, money) def work(self): # 继承父类中的私有属性 # print(self.__money) print(A._Person__money) # 私有属性的名仍为父类的名 A = Worker('bob', 30, 10000) A.work() A.get_mon() # 使用方法获取父类的私有属性
e8a13cc7c1079e0ccc88ebfcf3f41acc8638f1ad
ml758392/python_tedu
/nsd2018-master/nsd1804/python/day05/railway.py
209
3.5
4
import time print('#' * 20, end='') counter = 0 while True: print('\r%s@%s' % ('#' * counter, '#' * (19 - counter)), end='') counter +=1 if counter == 20: counter = 0 time.sleep(0.3)
9ba277aca0b2ee7388da28eb1577c477db26efbb
ml758392/python_tedu
/nsd2018-master/nsd1802/python/day06/mygui3.py
525
3.5625
4
import tkinter from functools import partial def hello(word): def welcome(): lb.config(text="Hello %s!" % word) return welcome # hello函数的返回值还是函数 root = tkinter.Tk() lb = tkinter.Label(text="Hello world!", font="Times 26") MyBtn = partial(tkinter.Button, root, fg='white', bg='blue') b1 = MyBtn(text='Button 1', command=hello('China')) b2 = MyBtn(text='Button 2', command=hello('tedu')) b3 = MyBtn(text='quit', command=root.quit) lb.pack() b1.pack() b2.pack() b3.pack() root.mainloop()
dc510858253ff64e6b52fc184714df2a3bbaeb2a
ml758392/python_tedu
/python100例/Python100Cases-master/100examples/006.py
170
3.75
4
def Fib(n): return 1 if n<=2 else Fib(n-1)+Fib(n-2) print(Fib(int(input()))) target=int(input()) res=0 a,b=1,1 for i in range(target-1): a,b=b,a+b print(a)
72dc30fd01b0534b20e07ec811ffc7903f0c265d
ml758392/python_tedu
/nsd2018-master/nsd1803/python/day03/mtable.py
173
3.53125
4
for i in range(1, 10): # 外层循环控制行 for j in range(1, i + 1): # 内层循环控制某一行 print('%sX%s=%s' % (j, i, j * i), end=' ') print()
28d4a6b3e584c628a2be3570b569d97cc58daf83
ml758392/python_tedu
/nsd2018-master/nsd1803/python/day08/mytime.py
740
3.75
4
class Date: def __init__(self, year, month, day): self.year = year self.month = month self.day = day def say_hi(self): # 必须有实例,通过实例调用 print('hello world!') @classmethod # 类方法,没有实例就可以调用 def create_date(cls, str_date): # cls是类本身,即Date y, m, d = map(int, str_date.split('-')) return cls(y, m, d) @staticmethod def is_date_valid(str_date): y, m, d = map(int, str_date.split('-')) return 1 <= d <= 31 and 1 <= m <= 12 and y < 4000 if __name__ == '__main__': d1 = Date(2018, 8, 22) if Date.is_date_valid('2018-02-22'): d2 = Date.create_date('2018-02-22') print(d2)
33e6295afebb628d2a60097724496a36dc66d02f
ml758392/python_tedu
/nsd2018-master/nsd1802/python/day04/str_method.py
783
3.65625
4
py_str = 'hello world!' py_str.capitalize() py_str.title() py_str.center(50) py_str.center(50, '#') py_str.ljust(50, '*') py_str.rjust(50, '*') py_str.count('l') # 统计l出现的次数 py_str.count('lo') py_str.endswith('!') # 以!结尾吗? py_str.endswith('d!') py_str.startswith('a') # 以a开头吗? py_str.islower() # 字母都是小写的?其他字符不考虑 py_str.isupper() # 字母都是大写的?其他字符不考虑 'Hao123'.isdigit() # 所有字符都是数字吗? 'Hao123'.isalnum() # 所有字符都是字母数字? ' hello\t '.strip() # 去除两端空白字符,常用 ' hello\t '.lstrip() ' hello\t '.rstrip() 'how are you?'.split() 'hello.tar.gz'.split('.') '.'.join(['hello', 'tar', 'gz']) '-'.join(['hello', 'tar', 'gz'])
443afc71938eb3f5beacfa7138b884488d1287c9
ml758392/python_tedu
/nsd2018-master/nsd1803/python/day06/mydict.py
916
3.71875
4
# adict = dict(['ab', 'cd', ('name', 'zhangsan')]) # print(adict) bdict = {}.fromkeys(['bob', 'alice', 'tom'], 7) print(bdict) for key in bdict: print('%s: %s' % (key, bdict[key])) print('%(bob)s' % bdict) bdict['tom'] = 8 # tom已经是字典的key,更新值 bdict['john'] = 6 # john没在字典中,新增一项 print(bdict) bdict.pop('alice') 7 in bdict # 返回False 'tom' in bdict # 返回True cdict = bdict.copy() # 将bdict的内容赋值给cdict,cdict使用全新的内存空间 bdict.get('bob') # 返回bob对应的value,如果没有bob,默认返回None bdict.get('jane', 'not found') # 如果没有jane,返回not found bdict.setdefault('bob', 10) # bob已经是字典的key,返回value bdict.setdefault('jane', 10) # jane没在字典中,向字典中写入 list(bdict.keys()) list(bdict.values()) list(bdict.items()) bdict.update({'aaa': 111, 'bbb': 222}) # 合并字典
4d06d510df701a3589334f8849255717f5122e0b
ml758392/python_tedu
/nsd2018-master/nsd1804/python/day06/anon2.py
538
3.546875
4
from random import randint def mydiv(x): return x % 2 def func1(x): return x * 2 + 1 if __name__ == '__main__': alist = [randint(1, 100) for i in range(10)] print(alist) print(list(filter(mydiv, alist))) # alist中的每一项都作为mydiv的参数,如果返回值是True就留下来,否则过滤掉 print(list(filter(lambda x: x % 2, alist))) print(list(map(func1, alist))) # alist中的每每一项都作为func1的参数,处理后把结果返回 print(list(map(lambda x: x * 2 + 1, alist)))
23765e98c4daee3f6dcc2177971dbd538878410c
ml758392/python_tedu
/python100例/Python100Cases-master/100examples/049.py
136
3.734375
4
Max=lambda x,y:x*(x>=y)+y*(y>x) Min=lambda x,y:x*(x<=y)+y*(y<x) a=int(input('1:')) b=int(input('2:')) print(Max(a,b)) print(Min(a,b))
3932d3894497eeea75c745a2468b84a6096252d0
ml758392/python_tedu
/python100例/Python-programming-exercises-master/python100/level2/9.py
519
3.984375
4
""" 编写一个接受行序列作为输入的程序,并在使句子中的所有字符大写后打印行。 假设为程序提供了以下输入: Hello world Practice makes perfect 然后,输出应该是: HELLO WORLD PRACTICE MAKES PERFECT 提示: 如果输入数据被提供给问题,则应该假定它是控制台输入。 """ lines = [] while True: s = input('input:') if s: lines.append(s.upper()) else: break for sentence in lines: print(sentence)
2d1d7d32813d8fb72c7e889ea85b7ee5006f222b
ml758392/python_tedu
/python1/Day3_文件_fun_mod/pycharm/randpass.py
226
3.796875
4
# -*-coding:utf-8-*- from random import choice num = int(input("请输入密码的位数:")) string = "123456absimport!#@%" password = "" for i in range(num): password = password + choice(string) else: print(password)
7e40c4b9259486ee55d80691c66f8a8cc0efb36c
ml758392/python_tedu
/nsd2018-master/nsd1804/python/day01/hello.py
706
4.1875
4
# 如果希望将数据输出在屏幕上,常用的方法是print print('Hello World!') print('Hello' + 'World!') print('Hello', 'World!') # 默认各项之间用空格分隔 print('Hello', 'World!', 'abc', sep='***') # 指定分隔符是*** print('Hello World!', end='####') # print默认在打印结束后加上一个回车,可以使用end=重置结束符 n = input('number: ') # 屏幕提示number: 用户输入的内容赋值给n print(n) # input得到的数据全都是字符类型 # a = n + 10 # 错误,不能把字符和数字进行运算 a = int(n) + 10 # int可以将字符串数值转成相应的整数 print(a) b = n + str(10) # str可以将其他数据转换成字符 print(b)
0030823476eda14a6172efa3228afab8b0f140e9
ml758392/python_tedu
/nsd2018-master/nsd1803/python/day03/mylist.py
240
3.5
4
[10] [3 + 2] [3 + 2 for i in range(10)] # 执行10次3+2 [3 + i for i in range(10)] # 循环控制3+i运行多少次 [3 + i for i in range(10) if i % 2 == 1] # 判断条件作为过滤依据 ['192.168.1.%s' % i for i in range(1, 255)]
b688b8ce2aa2cc925b936c49b5366147f6fb4b03
ml758392/python_tedu
/nsd2018-master/nsd1802/python/day07/books.py
444
3.65625
4
class Book: def __init__(self, title, author, pages): self.title = title self.author = author self.pages = pages def __str__(self): return '《%s》' % self.title def __call__(self): print('《%s》is written by %s' % (self.title, self.author)) if __name__ == '__main__': py_book = Book('Core Python', 'Wysley', 800) print(py_book) # 调用__str__ py_book() # 调用__call__
ff8d1f55ebf3a241031f3c3499e7e4ac6c916d08
ml758392/python_tedu
/devops/Day1_fork_thread/Thread/7.线程通信.py
417
3.640625
4
# -*-coding:utf-8-*- import threading import time def oo(): event = threading.Event() def run(): for i in range(5): # 阻塞, 等待时间的触发 event.wait() # 重置 event.clear() print('sunck is a good man') threading.Thread(target=run).start() return event event =oo() for i in range(5): time.sleep(2) event.set()
4ac57f656e4393651ca3b39b0916918e15bbe8d0
ml758392/python_tedu
/python1/Day2_基础/pycharm/game_2.py
820
4
4
# -*-coding:utf-8-*- import random all_choice = ['剪刀', '石头', '布'] win = [['剪刀', '布'], ['石头', '剪刀'], ['布', '石头']] num_player = 2 num_computer = 2 while num_player > 0 and num_computer > 0: computer = random.choice(all_choice) prompt = ''' (0)剪刀 (1)石头 (2)布 请出拳(0/1/2):''' player = int(input(prompt)) player = all_choice[player] print("You choice:"+player) print("You choice:"+computer) if player == computer: print("平局") # 先写平局的,代码执行效率高 elif [player, computer] in win: print("You win!") num_player -= 1 else: print("You lose") num_computer -= 1 else: if num_player == 0: print("你赢了") else: print("电脑赢了")
e2364c287a56b8c3704ea927c94d1971f7eee6c5
ml758392/python_tedu
/python100例/Python-programming-exercises-master/python100/level2/8.py
368
4.03125
4
""" 题: 编写一个程序,接受逗号分隔的单词序列作为输入,并按字母顺序排序后以逗号分隔的顺序打印单词。 假设为程序提供了以下输入: 不,你好,包,世界 然后,输出应该是: 袋,你好,没有,世界 """ item = [x for x in input('input:').split(',')] item.sort() print(','.join(item))
2729e7bfbd3d0e37b2e3adbfcdc158c32a743184
ml758392/python_tedu
/nsd2018-master/nsd1803/python/day07/parial_func.py
350
3.5625
4
from functools import partial def add(a, b, c, d): return a + b + c + d if __name__ == '__main__': print(add(10, 20, 30, 5)) print(add(10, 20, 30, 15)) print(add(10, 20, 30, 25)) print(add(10, 20, 30, 35)) myadd = partial(add, 10, 20, 30) print(myadd(5)) print(myadd(15)) print(myadd(25)) print(myadd(35))
a75144bd1fa587df3cf16ef5e4eb6e5dc6eb92dc
Rekt77/Algorithm
/boj/2839.py
162
3.59375
4
kg = int(input()) if kg in [1,2,4,7]: print(-1) elif kg%5==1 or kg%5==3: print(kg//5+1) elif kg%5==2 or kg%5==4: print(kg//5+2) else: print(kg//5)
b629e4a4f0a8144c215791d92ebc074422615eaf
Rekt77/Algorithm
/boj/2747_generator.py
385
3.765625
4
# -*- coding: utf-8 -*- """ Created on Mon Mar 25 01:06:23 2019 @author: Rekt77 """ import sys from itertools import islice def Fibonacci_numbers(): prev, curr = 0,1 while True: yield curr prev, curr = curr, prev+curr if __name__ == "__main__": f = Fibonacci_numbers() n = int(sys.stdin.readline().strip()) print(list(islice(f,0,n))[n-1])
3da3ad094575ff79947fd44f3b651e8270dee9ac
Rekt77/Algorithm
/programmers/programmers_removepair.py
255
3.78125
4
string = "abaaba" stack = [] if len(string)%2 != 0: print(0) for each in string: stack.append(each) if len(stack) != 1 and (stack[-1]==stack[-2]): stack.pop() stack.pop() print(stack) if stack: print(0) else: print(1)
b713f81753cf0d6b36d066be7b53a61ea8d1374e
forthing/leetcode-share
/python/123 Best Time to Buy and Sell Stock III.py
1,262
3.75
4
''' Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete at most two transactions. Note: You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again). ''' class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ total_max_profit = 0 n = len(prices) first_profits = [0] * n min_price = float('inf') for i in range(n): min_price = min(min_price, prices[i]) total_max_profit = max(total_max_profit, prices[i] - min_price) first_profits[i] = total_max_profit max_profit = 0 max_price = float('-inf') for i in range(n - 1, 0, -1): max_price = max(max_price, prices[i]) max_profit = max(max_profit, max_price - prices[i]) total_max_profit = max(total_max_profit, max_profit + first_profits[i - 1]) return total_max_profit if __name__ == "__main__": assert Solution().maxProfit([2, 4, 6, 1, 3, 8, 3]) == 11 assert Solution().maxProfit([1, 2]) == 1
bb5892474298adf10e7aa203081f855ecffc5e11
forthing/leetcode-share
/python/060 Permutation Sequence.py
1,097
3.984375
4
''' The set [1,2,3,…,n] contains a total of n! unique permutations. By listing and labeling all of the permutations in order, We get the following sequence (ie, for n = 3): "123" "132" "213" "231" "312" "321" Given n and k, return the kth permutation sequence. Note: Given n will be between 1 and 9 inclusive. ''' class Solution(object): def getPermutation(self, n, k): """ :type n: int :type k: int :rtype: str """ k -= 1 factorial = 1 for i in range(1, n): factorial *= i result = [] array = list(range(1, n + 1)) for i in range(n - 1, 0, -1): index = k // factorial result.append(str(array[index])) array = array[:index] + array[index + 1:] k %= factorial factorial //= i result.append(str(array[0])) return "".join(result) if __name__ == "__main__": assert Solution().getPermutation(3, 3) == "213" assert Solution().getPermutation(9, 324) == "123685974"
7b1c566cc18b4dad37b9a62c20127d808b814d2e
forthing/leetcode-share
/python/030 Substring with Concatenation of All Words.py
1,745
3.84375
4
''' You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s that is a concatenation of each word in words exactly once and without any intervening characters. For example, given: s: "barfoothefoobarman" words: ["foo", "bar"] You should return the indices: [0,9]. (order does not matter). ''' class Solution(object): def findSubstring(self, s, words): """ :type s: str :type words: List[str] :rtype: List[int] """ s_length = len(s) word_num = len(words) word_length = len(words[0]) words_length = word_num * word_length result = [] words_dict = {} for word in words: words_dict[word] = words_dict[word] + 1 if word in words_dict else 1 for i in range(word_length): left = i right = i curr_dict = {} while right + word_length <= s_length: word = s[right:right + word_length] right += word_length if word in words_dict: curr_dict[word] = curr_dict[word] + 1 if word in curr_dict else 1 while curr_dict[word] > words_dict[word]: curr_dict[s[left:left + word_length]] -= 1 left += word_length if right - left == words_length: result.append(left) else: curr_dict.clear() left = right return result if __name__ == "__main__": assert Solution().findSubstring("barfoothefoobarman", ["foo", "bar"]) == [0, 9]
8c326cefac9c979874f8a03334934c685a88c953
forthing/leetcode-share
/python/152 Maximum Product Subarray.py
813
4.21875
4
''' Find the contiguous subarray within an array (containing at least one number) which has the largest product. For example, given the array [2,3,-2,4], the contiguous subarray [2,3] has the largest product = 6. ''' class Solution(object): def maxProduct(self, nums): """ :type nums: List[int] :rtype: int """ positive, negative = nums[0], nums[0] result = nums[0] for num in nums[1:]: positive, negative = max(num, positive * num, negative * num), min(num, positive * num, negative * num) result = max(result, positive) return result if __name__ == "__main__": assert Solution().maxProduct([2, 3, -2, 4]) == 6
b7a2cbc135fc64b983bb4e94dd42001927d870b4
forthing/leetcode-share
/python/051 N-Queens.py
1,541
4.09375
4
''' The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other. Given an integer n, return all distinct solutions to the n-queens puzzle. Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively. For example, There exist two distinct solutions to the 4-queens puzzle: [ [".Q..", // Solution 1 "...Q", "Q...", "..Q."], ["..Q.", // Solution 2 "Q...", "...Q", ".Q.."] ] ''' class Solution(object): def solveNQueens(self, n): """ :type n: int :rtype: List[List[str]] """ self.col = [False] * n self.diag = [False] * (2 * n) self.anti_diag = [False] * (2 * n) self.result = [] self.recursive(0, n, []) return self.result def recursive(self, row, n, column): if row == n: self.result.append(list(map(lambda x: '.' * x + 'Q' + '.' * (n - 1 - x), column))) else: for i in range(n): if not self.col[i] and not self.diag[row + i] and not self.anti_diag[n - i + row]: self.col[i] = self.diag[row + i] = self.anti_diag[n - i + row] = True self.recursive(row + 1, n, column + [i]) self.col[i] = self.diag[row + i] = self.anti_diag[n - i + row] = False if __name__ == "__main__": print(Solution().solveNQueens(5))
5342778e7ce54985e47b35ffb838de3836a97382
forthing/leetcode-share
/python/219 Contains Duplicate II.py
885
3.625
4
''' Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the difference between i and j is at most k. ''' class Solution(object): def containsNearbyDuplicate(self, nums, k): """ :type nums: List[int] :type k: int :rtype: bool """ if not nums: return False m = {} for i in range(len(nums)): if nums[i] in m: if i - m.get(nums[i]) <= k: return True m[nums[i]] = i return False if __name__ == "__main__": assert Solution().containsNearbyDuplicate([1, 2, 3, 4], 1) == False assert Solution().containsNearbyDuplicate([1, 1, 2, 3], 2) == True assert Solution().containsNearbyDuplicate([1, 2, 3, 1], 2) == False
88ddaec1c09a46fac173c4b520c6253b59aad09b
kmair/Graduate-Research
/PYOMO_exercises_w_soln/exercises/Python/fcn_soln.py
1,248
4.40625
4
## Write a function that takes in a list of numbers and *prints* the value of the largest number. Be sure to test your function. def print_max_value(nums): print("The max value is: ") print(max(nums)) ## Write a function that takes a list of numbers and *returns* the largest number def max_value(nums): return max(nums) ## Do so without using any built-in functions def my_max_value(nums): tmp = nums[0] for i in range(1, len(nums)): if nums[i] > tmp: tmp = nums[i] return tmp ## Call both functions on a couple different lists of numbers to verify they return the same value l1 = [1, 3, 0, 5, -2] ans1 = max_value(l1) print(ans1) ans2 = my_max_value(l1) print(ans2) l2 = [12, 0, 11.9] print(max_value(l2)) print(my_max_value(l2)) ## Write a function that takes a list of numbers and returns a dict consisting of the smallest and largest number ## (use keys 'smallest' and 'largest'). Be sure to test your function. def max_and_min(nums): return {'smallest': min(nums), 'largest': max(nums)} ## Write a function that takes in two lists and prints any common elements between them ## hint: check if an item is in a list using: ## if item in list def get_common(l1, l2): for i in l1: if i in l2: print(i)
b29bf7aee53ceeca2952e5f2db345b2ff3fdb8b8
disconnect78/bandcamper
/bandcamper/metadata/track_metadata.py
2,424
3.59375
4
from abc import ABC from abc import abstractmethod from mutagen import File class TrackMetadata(ABC): """Handles the metadata of track files. Parameters ---------- filename : str or path-like object. The filename or file-path of the respective file to read/write metadata. Attributes ---------- file : mutagen.FileType The track file. """ FILE_CLASS = File def __init__(self, filename): self.file = self.FILE_CLASS(filename) def save(self): self.file.save() @property @abstractmethod def title(self): """The title of the track. Returns ------- str or None """ @title.setter @abstractmethod def title(self, val): pass @property @abstractmethod def track_number(self): """The number of the track. Returns ------- int or None """ @track_number.setter @abstractmethod def track_number(self, val): pass @property @abstractmethod def track_total(self): """The total number of tracks in the album. Returns ------- int or None """ @track_total.setter @abstractmethod def track_total(self, val): pass @property @abstractmethod def album(self): """The title of the album. Returns ------- str or None """ @album.setter @abstractmethod def album(self, val): pass @property @abstractmethod def artist(self): """The name of the artist. Returns ------- str or None """ @artist.setter @abstractmethod def artist(self, val): pass @property @abstractmethod def album_artist(self): """The name of the album artist. Returns ------- str or None """ @album_artist.setter @abstractmethod def album_artist(self, val): pass @property @abstractmethod def lyrics(self): """The lyrics of the track. Returns ------- str or None """ @lyrics.setter @abstractmethod def lyrics(self, val): pass @property @abstractmethod def cover_art(self): """The cover art. Returns ------- bytes or None """
89e29e7a555fb0f7d760c8589d30b69642275c94
Danyt13/gitProjects
/calculatrice.py
1,625
3.5625
4
import tkinter as tk racine = tk.Tk() racine.title("Calculatrice") def carre0(): x = 1 y = 0 print("0") #création de widgets bouton_carre0 = tk.Button(racine, text="0", command=carre0) bouton_carre1 = tk.Button(racine, text="1") bouton_carre2 = tk.Button(racine, text="2") bouton_carre3 = tk.Button(racine, text="3") bouton_carre4 = tk.Button(racine, text="4") bouton_carre5 = tk.Button(racine, text="5") bouton_carre6 = tk.Button(racine, text="6") bouton_carre7 = tk.Button(racine, text="7") bouton_carre8 = tk.Button(racine, text="8") bouton_carre9 = tk.Button(racine, text="9") bouton_carre10 = tk.Button(racine, text="+") bouton_carre11 = tk.Button(racine, text="-") bouton_carre12 = tk.Button(racine, text="*") bouton_carre13 = tk.Button(racine, text="/") bouton_carre14 = tk.Button(racine, text="=") bouton_carre15 = tk.Button(racine, text=".") canvas = tk.Canvas(racine, width=250, height=90, bg="black", bd=10, relief="raised") canvas.grid(column=0, row=5, rowspan=4) #placement des widgets bouton_carre0.grid(column=1, row=8) bouton_carre1.grid(column=1, row=7) bouton_carre2.grid(column=2, row=7) bouton_carre3.grid(column=3, row=7) bouton_carre4.grid(column=1, row=6) bouton_carre5.grid(column=2, row=6) bouton_carre6.grid(column=3, row=6) bouton_carre7.grid(column=1, row=5) bouton_carre8.grid(column=2, row=5) bouton_carre9.grid(column=3, row=5) bouton_carre10.grid(column=4, row=8) bouton_carre11.grid(column=4, row=7) bouton_carre12.grid(column=4, row=6) bouton_carre13.grid(column=4, row=5) bouton_carre14.grid(column=3, row=8) bouton_carre15.grid(column=2, row=8) racine.mainloop()
82d3e7c695fbab62b222781240a1865cfe877151
Kaushalendra-the-real-1/Python-assignment
/Q2.py
779
4.125
4
# class Person: # def __init__(self): # print("Hello Reader ... ") # class Male(Person): # def get_gender(self): # print("I am from Male Class") # class Female(Person): # def get_gender(self): # print("I am from Female Class") # Obj = Female() # Obj.get_gender() # ---------------------------------------------------------------------------------------------------------------------- # Bonus Section from abc import ABC, abstractmethod class Person(ABC): @abstractmethod def get_gender(self): return 0 class Male(Person): def get_gender(self): print("I am from Male Class") class Female(Person): def get_gender(self): print("I am from Female Class") unknown = Person() #expecteed to throw an error.
aa235b4ae0089d491d5defeea978a7c8d33b3640
TomCallegari/Python-Challenge
/combined_main.py
7,390
3.828125
4
import pandas as pd print(''' ''') print( '''Please choose a dataset for analysis: -------------------------------------------------- [1] for PyBank 'budget_data.csv' or [2] for PyPoll 'election_data.csv' ''' ) print('-'*50) print(''' ''') first_input = int(input('Selection: ')) if first_input == 1: data = pd.read_csv('budget_data.csv') month = data['Date,Profit/Losses'].str.split('-', n=1, expand=True) data['month'] = month[0] year = month[1].str.split(',', n=1, expand=True) data['year'] = year[0] data['P/L'] = year[1] months = data['month'].count() convert = {'P/L': int} data = data.astype(convert) total = data['P/L'].sum() avg = round(data['P/L'].mean(), 3) max = data.max(axis=0) min = data.min(axis=0) print(''' ''') print('Financial Analysis') print('-'*50) print(f' Total Months: {months}') print(f' Total: ${total}') print(f' Average Change: ${avg}') print(f' Greatest Increase in Profits: {max[1]}' + f' {max[2]}' + f' (${max[3]})') print(f' Greatest Decrease in Profits: {min[1]}' + f' {min[2]}' + f' (${min[3]})') with open('PyBank.txt', 'w') as f: print(' ', file=f) print('Financial Analysis', file=f) print('-'*50, file=f) print(f' Total Months: {months}', file=f) print(f' Total: ${total}', file=f) print(f' Average Change: ${avg}', file=f) print(f' Greatest Increase in Profits: {max[1]}' + f' {max[2]}' + f' (${max[3]})', file=f) print(f' Greatest Decrease in Profits: {min[1]}' + f' {min[2]}' + f' (${min[3]})', file=f) print(''' ''') print('-'*50) print("A 'PyBank.txt' file has been saved to your local directory.") print(' ') elif first_input == 2: data = pd.read_csv('election_data.csv') voters = int(data['Voter ID'].nunique()) data['Votes'] = 1 vote_count = data.groupby('Candidate').agg({'Votes': 'sum'}) vote_count['Percent'] = round((vote_count['Votes'] / voters) * 100, 2) vote_count = vote_count.sort_values(by='Percent', ascending=False) khan = vote_count.loc['Khan'] correy = vote_count.loc['Correy'] li = vote_count.loc['Li'] otooley = vote_count.loc["O'Tooley"] print(''' ''') print(' Election Results') print('-'*25) print(f' Total Votes: {voters}') print('-'*25) print(f' Khan: {khan[1]}% ({khan[0]})') print(f' Correy: {correy[1]}% ({correy[0]})') print(f' Li: {li[1]}% ({li[0]})') print(f" O'Tooley: {otooley[1]}% ({otooley[0]})") print('-'*25) print(' Winner: Khan') print('-'*25) with open('PyPoll.txt', 'w') as f: print(' ', file=f) print(' Election Results', file=f) print('-'*25, file=f) print(f' Total Votes: {voters}', file=f) print('-'*25, file=f) print(f' Khan: {khan[1]}% ({khan[0]})', file=f) print(f' Correy: {correy[1]}% ({correy[0]})', file=f) print(f' Li: {li[1]}% ({li[0]})', file=f) print(f" O'Tooley: {otooley[1]}% ({otooley[0]})", file=f) print('-'*25, file=f) print(' Winner: Khan', file=f) print('-'*25, file=f) print(''' ''') print('-'*50) print("A 'PyPoll.txt' file has been saved to your local directory.") print(' ') else: print(''' ''') print(''' It seems you have not followed the instructions ... buh bye now. ''') print(''' ''') print(' ') print(' ') second_input = input('Would you like the other analysis just because? (Y/N)').lower() if second_input == 'y' and first_input == 1: data = pd.read_csv('election_data.csv') voters = int(data['Voter ID'].nunique()) data['Votes'] = 1 vote_count = data.groupby('Candidate').agg({'Votes': 'sum'}) vote_count['Percent'] = round((vote_count['Votes'] / voters) * 100, 2) vote_count = vote_count.sort_values(by='Percent', ascending=False) khan = vote_count.loc['Khan'] correy = vote_count.loc['Correy'] li = vote_count.loc['Li'] otooley = vote_count.loc["O'Tooley"] print(''' ''') print(' Election Results') print('-'*25) print(f' Total Votes: {voters}') print('-'*25) print(f' Khan: {khan[1]}% ({khan[0]})') print(f' Correy: {correy[1]}% ({correy[0]})') print(f' Li: {li[1]}% ({li[0]})') print(f" O'Tooley: {otooley[1]}% ({otooley[0]})") print('-'*25) print(' Winner: Khan') print('-'*25) with open('PyPoll.txt', 'w') as f: print(' ', file=f) print(' Election Results', file=f) print('-'*25, file=f) print(f' Total Votes: {voters}', file=f) print('-'*25, file=f) print(f' Khan: {khan[1]}% ({khan[0]})', file=f) print(f' Correy: {correy[1]}% ({correy[0]})', file=f) print(f' Li: {li[1]}% ({li[0]})', file=f) print(f" O'Tooley: {otooley[1]}% ({otooley[0]})", file=f) print('-'*25, file=f) print(' Winner: Khan', file=f) print('-'*25, file=f) print(''' ''') print('-'*50) print("A 'PyPoll.txt' file has been saved to your local directory.") print(' ') elif second_input == 'y' and first_input == 2: data = pd.read_csv('budget_data.csv') month = data['Date,Profit/Losses'].str.split('-', n=1, expand=True) data['month'] = month[0] year = month[1].str.split(',', n=1, expand=True) data['year'] = year[0] data['P/L'] = year[1] months = data['month'].count() convert = {'P/L': int} data = data.astype(convert) total = data['P/L'].sum() avg = round(data['P/L'].mean(), 3) max = data.max(axis=0) min = data.min(axis=0) print(''' ''') print('Financial Analysis') print('-'*50) print(f' Total Months: {months}') print(f' Total: ${total}') print(f' Average Change: ${avg}') print(f' Greatest Increase in Profits: {max[1]}' + f' {max[2]}' + f' (${max[3]})') print(f' Greatest Decrease in Profits: {min[1]}' + f' {min[2]}' + f' (${min[3]})') with open('PyBank.txt', 'w') as f: print(' ', file=f) print('Financial Analysis', file=f) print('-'*50, file=f) print(f' Total Months: {months}', file=f) print(f' Total: ${total}', file=f) print(f' Average Change: ${avg}', file=f) print(f' Greatest Increase in Profits: {max[1]}' + f' {max[2]}' + f' (${max[3]})', file=f) print(f' Greatest Decrease in Profits: {min[1]}' + f' {min[2]}' + f' (${min[3]})', file=f) print(''' ''') print('-'*50) print("A 'PyBank.txt' file has been saved to your local directory.") print(' ') elif second_input == 'n': print(''' ''') print('Ok then, buh bye now.') print(''' ''') elif second_input != 'y' or second_input != 'n': print(''' ''') print(''' It seems you have not followed the instructions ... buh bye now. ''') print(''' ''')
7da361d9b21c62037abb965c490ef2b30a266665
xynicole/Python-Course-Work
/Huang_Xinyi_Assignment5/Assignment5EX2/2.py
1,831
4.03125
4
''' Xinyi Huang (Nicole) xhuang78@binghamton.edu B58 Jia Yang Assignment #5(2) ''' ''' RESTATEMENT: this program is based on lucky sevens ask a user to input a money value OURPUT to monitor: rolls number money value INPUT to keyboard: money ''' import random #CONSTANTS SEVEN = 7 FOUR = 4 ONE = 1 # validation loop def invalidMoney(money_str): return money_str.isdigit() and int(money_str) > 0 #put function to excute the game runs def game(money): roll = 0 high_money = 0 high_roll = 0 while money > 0: dice1 = random.randrange(1, SEVEN) dice2 = random.randrange(1, SEVEN) sum_dice = dice1 + dice2 if sum_dice == 7: money = money + FOUR else: money = money - ONE roll += 1 if money > high_money: high_money = money high_roll = roll print(roll, '\t', sum_dice, '\t', money) return roll, high_roll, high_money def main(): print("This is the game of Lucky Sevens.") money_str = input( "Please palce your bet in positive whole dollars OR press <Enter> to quit: ") #check the validate input while money_str: money = money_str while not invalidMoney(money_str): print("Invalid Input: Input whole numvers greater than 0 ONLY") money_str = input( "Please palce your bet in positive whole dollars OR press <Enter> to quit: ") money = money_str break money = int(money_str) # create the table print("Roll",'\t',"Value",'\t',"Dollars") while money_str: roll, high_roll, high_money =game(money) break print("You become broke after: ",roll,"rolls") print("You should have quit after: ", high_roll,"\ rolls when you had $", high_money) money_str = input( "Please palce your bet in positive whole dollars OR press <Enter> to quit: ") money= int(money_str) main()
1b918e5f602dbf6500a09464a1e932bde3a82312
xynicole/Python-Course-Work
/lab/lab1BeforeCoding.py
1,057
3.828125
4
''' Rose Williams rosew@binghamton.edu B5_ Lab #1 ''' ''' ANALYSIS RESTATEMENT: Ask a user how many of each type of coin they have and output the total in dollars OUTPUT to monitor: total_dollars (float) - total amount of change in dollars INPUT from keyboard: quarter_count (int) dime_count (int) nickel_count (int) penny_count (int) GIVENS: QUARTER_VALUE (int) - 25 DIME_VALUE (int) - 10 NICKEL_VALUE (int) - 5 PENNY_VALUE (int) - 1 TO_DOLLAR (int) - 100 ''' # CONSTANTS # This program outputs the total amount of change that a user has in dollars # given the count of each type of coin def main(): # Explain purpose of program to user # Ask user for number of coins they have # Start with quarters, end with pennies # Note constraints: no dollar, half-dollar coins # Convert str data to int # Multiply the value of each type of coin by it's count and sum each result # Convert to dollars (float) # Display labeled and formatted output in dollars main()
dd78a214f6c3323713f6871391f6e0e9fd078cbc
xynicole/Python-Course-Work
/W12/ex5buttonDemo.py
809
3.875
4
from tkinter import * #from tkinter import messagebox ''' Demonstrates Button widget and info dialog box ''' class MyGUI: def __init__(self): # Create main window self.__main_window = Tk() # Create button with 'Click Me!' on face # doSomething method executed when clicked self.__my_button = Button(self.__main_window, \ text='Click Me!', \ command=self.do_something) # Pack the Button self.__my_button.pack() # Start the listener mainloop() # Event handler aka callback function for button def do_something(self): # Display info dialog box messagebox.showinfo('Response', \ 'Thanks for clicking the button.') MyGUI()
a947f1570eadf213201881c0291514173b11e033
xynicole/Python-Course-Work
/W12/kiloConverterGUI2.py
4,519
4.125
4
import tkinter import kiloToMiles ''' Converts kilometers to miles Displays result in Label ''' class KiloConverterGUI: # --------------------------------------------------------------------------- # Constructor def __init__(self): # Create instance of MODe_l self.__kilo_val = kiloToMiles.KiloToMiles() # Create the main window self.__main_window = tkinter.Tk() #-------------------------------------------------------------------------- # Frames and widgets # Create three frames to group widgets self.__top_frame = tkinter.Frame() self.__mid_frame = tkinter.Frame() self.__bottom_frame = tkinter.Frame() # Create top frame widgets self.__kilo_entry_label = tkinter.Label(self.__top_frame, text='Enter distance in kilometers: ') self.__kilo_entry = tkinter.Entry(self.__top_frame, width = 10) # use bind method to connect <Return> event to callback method self.__kilo_entry.bind('<Return>', self.convert_from_entry) # Pack top frame widgets self.__kilo_entry_label.pack(side='left') self.__kilo_entry.pack(side='left') # Create middle frame widgets # Associate StringVar with label for output # Use set method to initialize self.__value1 = tkinter.StringVar() self.__value1.set("%.2f kilometers" % self.__kilo_val.get_kilo()) # Create label and associate with StringVar # Value stored in StringVar will be # automatically displayed in label self.__kilo_label = tkinter.Label(self.__mid_frame, textvariable = self.__value1) self.__middle_label = tkinter.Label(self.__mid_frame, text=' converted to miles = ') # Associate StringVar with label for output # Use set method to initialize self.__value2 = tkinter.StringVar() self.__value2.set("%.2f miles" % self.__kilo_val.to_miles()) # Create label and associate with StringVar # Value stored in StringVar will be # automatically displayed in label self.__miles_label = tkinter.Label(self.__mid_frame, textvariable=self.__value2) # Pack middle frame widgets self.__kilo_label.pack(side='left') self.__middle_label.pack(side='left') self.__miles_label.pack(side='left') # Create bottom frame button widgets self.__convert_button = tkinter.Button(self.__bottom_frame, text='Convert', command=self.convert) self.__quit_button = tkinter.Button(self.__bottom_frame, text='Quit', command=self.__main_window.destroy) # Pack buttons self.__convert_button.pack(side='left') self.__quit_button.pack(side='left') # Pack frames self.__top_frame.pack() self.__mid_frame.pack() self.__bottom_frame.pack() #-------------------------------------------------------------------------- # Enter the tkinter main loop tkinter.mainloop() #---------------------------------------------------------------------------- # Event Handlers # Callback method for entry box # Invokes button callback to do work def convert_from_entry(self, event): self.convert() # Callback method for compute button # Note use of exception handling instead of validation def convert(self): try: # Get value from kilo_entry widget and set mode_l self.__kilo_val.set_kilo(float(self.__kilo_entry.get())) # self.__value1.set("%.2f kilometers" % self.__kilo_val.get_kilo()) # Convert kilometers to miles and # store formatted result in StringVar object # Wll automatically update milesLabel widget self.__value2.set("%.2f miles" % self.__kilo_val.to_miles()) # Entry box input was inappropriate except ValueError as err: tkinter.messagebox.showerror('Kilos to Miles', "Must provide valid input: %s" % err) self.__kilo_val.reset_kilo() self.__value1.set("%.2f kilometers" % self.__kilo_val.get_kilo()) self.__value2.set("%.2f miles" % self.__kilo_val.to_miles()) finally: self.__kilo_entry.delete(0, tkinter.END) # Clear entry box # Create instance of KiloConverterGUI class KiloConverterGUI()
cf70fba4fc95f6f82cdf473c942fac876eb5324a
xynicole/Python-Course-Work
/lab/pi.py
1,123
3.9375
4
import random import math import turtle def main(): tyr = turtle.Turtle() wn = turtle.Screen() wn.setworldcoordinates(-2,-2,2,2) tyr.hideturtle() tyr.penup() tyr.goto(-1,-1) tyr.pendown() tyr.goto(-1,1) tyr.goto(1,1) tyr.goto(1,-1) tyr.goto(-1,-1) tyr.goto(-1,0) tyr.goto(1,0) tyr.penup() tyr.goto(0,1) tyr.pendown() tyr.goto(0,-1) tyr.penup() reddart = 0 print("This program simulates throwing darts at a datboard to simulate pi") print() dart_num = input("Please input the number of darts to be thrown" "in the simulation: ") dart_int = int(dart_num) wn.tracer(1000) for i in range(dart_int): randx = random.random() randy = random.random() x = randx * random.choice([-1,1]) y = randy * random.choice([-1,1]) tyr.goto(x,y) if tyr.distance(0,0) <= 1: tyr.color('red') reddart = reddart + 1 else: tyr.color('blue') tyr.dot() pi = (reddart / dart_int) * 4 print(pi) main()
e33a070506458cacbf4d52304982c491f2c9980d
xynicole/Python-Course-Work
/lab/435/ZeroDivideValue.py
595
4.25
4
def main(): print("This program will divide two numbers of your choosing for as long as you like\n") divisorStr = input("Input a divisor: ") while divisorStr: dividendStr = input("Input a dividend: ") try: divisor = int(divisorStr) dividend = int(dividendStr) print (dividend / divisor) except ZeroDivisionError: print("You cannot divide by zero\n") except ValueError: print("You must input a number\n") except Exception: print("Something happened\n") divisorStr = input("Input a divisor: ") main()
881fc46faa626aaac3317dd9f65d3e8975b3f32e
xynicole/Python-Course-Work
/W12/kiloToMiles.py
1,148
4.25
4
''' Stores value in kilometers Retrieves value in kilometers or miles Displays value in kilometers and miles ''' class KiloToMiles: # Constructor def __init__(self, kilo = 0.0): self.__kilo = float(kilo) self.__KILO_TO_MILES = 0.6214 # Conversion constant # --------------------------------------------------------------------------- # Accessors # return kilometers (float) def get_kilo(self): return self.__kilo # return kilo converted to miles (float) def to_miles(self): return self.__kilo * self.__KILO_TO_MILES # --------------------------------------------------------------------------- # Mutators # param kilo (float) def set_kilo(self, kilo): self.__kilo = kilo # param kilo (float) def reset_kilo(self): self.__kilo = 0.0 # --------------------------------------------------------------------------- # 'toString' def __str__(self): return "\n%.2f kilometers = %.2f miles" % (self.get_kilo(), self.to_miles()) ''' def main(): k = KiloToMiles(10) k2 = KiloToMiles() k2.set_Kilo(20) print(k, k2) main() '''
52c4ef860f81460674b933a964cd84162cb69ab8
xynicole/Python-Course-Work
/W12/ex6quitButton.py
1,194
3.703125
4
import tkinter import tkinter.messagebox ''' Demonstrates Tk class destroy() method when Quit button clicked as well as info dialog box ''' class MyGUI: def __init__(self): # Create main window self.__main_window = tkinter.Tk() # Create button with 'Click Me!' on face # doSomething method executed when clicked self.__my_button = tkinter.Button(self.__main_window, \ text='Click Me!', \ command=self.do_something) # Create Quit button that executes root widget's destroy() method # when clicked self.__quit_button = tkinter.Button(self.__main_window, \ text='Quit', \ command=self.__main_window.destroy) # Pack the Buttons self.__my_button.pack() self.__quit_button.pack() # Start listener tkinter.mainloop() # Event handler aka callback function for button def do_something(self): # Display info dialog box tkinter.messagebox.showinfo('Response', \ 'Thanks for clicking the button.') MyGUI()
66a1cb0c5645c8b254243aac6ff976ed309a7adc
leyosu23/PythonAlgorithmStudy
/1_greedy&Implementation/0_exchange.py
336
3.671875
4
''' You are a clerk. There are 4 kinds of coins at the counter, which are 500,100,50,10. Find the minimum number of coins to be exchanged , assuming the guest is paying N. However, N is always a multiple of 10. ''' # O(n) n = 1260 count = 0 array = [500,100,50,10] for coin in array: count += n // coin n %= coin print(count)
a4db74268b564d6d62a4a20f022357d9e500510a
rbendev/jenkins_1.0
/flotte.py
4,581
3.703125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import random from navire import Navire class Flotte(): taille_grille = 9 nom = "flotte" nb_bateaux = 5 random_positions = [] position_safe = False noms_bateaux = ["porte_avion", "croiseur", "contre torpilleur", "sous-marin", "torpilleur", "cuirassé", "croiseur lourd", "SNLE", "flotille", "frégate"] liste_navires = [] def __init__(self, nom, nombre): #Pour créer une flotte avant une grille il faut déterminer le nombre de cases de la grille #car les instances de navires sont générées dans la flotte, et leurs positions #sont aléatoirement générées dans la grille while self.taille_grille > 20 or self.taille_grille < 10: self.taille_grille = round(int(input("Saisir la Taille de la grille entre 10 et 20"))) self.nom = nom self.nb_bateaux = nombre self.init_positions(self.nb_bateaux) self.init_navires() def init_navires(self): for i in range(self.nb_bateaux): navire = Navire(self.noms_bateaux[i], self.random_positions[i], self.nom) self.liste_navires.append(navire) def init_positions(self, nombre): #initialisation pour démarrer la boucle de vérification avec #deux positions identiques qui permettent de lancer la boucle while(not self.position_safe): self.random_positions = [] #Retourne un dictionnaire de bateaux contenant leurs coordonnées et leur état initial #Les longueurs de bateaux sont prévues jusqu'à un nombre de 10 bateaux longueur_navires = [5, 4, 3, 3, 2, 4, 3, 5, 2, 3] sens_navires = [] position_navire = [0, 0, 0, 0, 0] temp = [] for i in range(nombre): sens_navires.append(random.choice([0, 1])) ligne_depart = random.randint(1, self.taille_grille) colonne_depart = random.randint(1, self.taille_grille) coord_depart = ligne_depart, colonne_depart depart_navire = (coord_depart) navire = {} # if sens ==1 => horizontal if sens_navires[i] == 1: # if longueur navire non collable à gauche, colle on colle à droite if (depart_navire[1] - (int(longueur_navires[i]))) <= 0 or not ( (depart_navire[1] + longueur_navires[i]) > self.taille_grille): for j in range(longueur_navires[i]): coord = (depart_navire[0], depart_navire[1] + j) navire[coord] = True # sinon colle à gauche else: for j in range(longueur_navires[i]): coord = (depart_navire[0], depart_navire[1] - j) navire[coord] = True self.random_positions.append(navire) if sens_navires[i] == 0: # if longueur navire collable en bas colle en bas if (depart_navire[0] - (int(longueur_navires[i]))) <= 0 or not (depart_navire[0] + longueur_navires[i]) > self.taille_grille: for j in range(longueur_navires[i]): coord = (depart_navire[0] + j, depart_navire[1]) navire[coord] = True # sinon colle en hauteur else: for j in range(longueur_navires[i]): coord = (depart_navire[0] - j, depart_navire[1]) navire[coord] = True self.random_positions.append(navire) print(navire) self.test_positions() def test_positions(self): liste_coord = [] somme_len_dict = 0 for navire in self.random_positions : for coord in navire.keys(): liste_coord.append(coord) somme_len_dict += 1 print(liste_coord) print(len(set(liste_coord))) print(somme_len_dict) #on supprime les clés en doublon dans la liste des coordonnées grâce à un set #si la longueur du set est la meme que celle de la liste alors il n'y a pas de doublons if len(set(liste_coord)) == somme_len_dict: self.position_safe = True else : self.position_safe = False print("Changement de la position des bateaux")
7b7a94cb9200528c466d4979c6cfd958a7a1b8f0
RSUBRAMANIAN1/data-structure
/code/linked list/linkedlist.py
1,138
3.921875
4
class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def insertafternode(self, val): temp = self.head while(temp.data != val): temp = temp.next ne=input() tmp1 = Node(ne) tmp1.next = temp.next temp.next = tmp1 def createnode(self, no): if(self.head == None): val = input() self.head = Node(val) if(no > 1): for i in range(no-1): val = input() self.next = Node(val) self = self.next def printnode(self): temp = self.head while(temp): println(temp.data) temp = temp.next if __name__ == "__main__": llist = LinkedList() n = int(input()) llist.createnode(n) # llist.insertafternode("hey") llist.printnode() sn=input() sn.upper() # from collections import defaultdict # f=defaultdict() # f['banana']=1 # f['apple']=31 # for k,v in f.items(): # print(k,v)
6fe33376a1b69a905a4463a1b0795d267894bb1b
jasdeepbhalla/python-algorithms
/LCA.py
627
3.703125
4
class Node: def __init__(self, data): self.data = data self.left = None self.right = None def lca(root, n1, n2): if root is None: return None if n1 < root.data and n2 < root.data: return lca(root.left, n1, n2) if n1 > root.data and n2 > root.data: return lca(root.right, n1, n2) return root def main(): root = Node(20) root.left = Node(8) root.right = Node(22) root.left.left = Node(4) root.left.right = Node(12) root.left.right.left = Node(10) root.left.right.right = Node(14) n1 = 10 n2 = 14 t = lca(root, n1, n2) print "ssd" print "LCA of %d and %d is %d" %(n1, n2, t.data) main()
a62f3f806c8119ce2e13cdcd867ddbea0b04dc34
WilliamBlack99/cs-club-code-off
/alphabet.py
818
4.09375
4
def sort(in_string): # convert to list for ease of swapping characters in_string = list(in_string) # flag variable alphabetized = False while not alphabetized: alphabetized = True # will remain True if no values are swapped for i in range(len(in_string)): if i == 0: continue # check if every character is lower on the alphabet than the previous if ord(in_string[i]) < ord(in_string[i - 1]): # swap the 2 characters placeholder = in_string[i] in_string[i] = in_string[i - 1] in_string[i - 1] = placeholder alphabetized = False # convert back to string in_string = ''.join(in_string) # return result return in_string
d2ee40453faed04f6e08bacf0862fe762daca518
amarnadhreddymuvva/pythoncode
/armstrong.py
199
4.03125
4
num=int(input("eneter a number")) sum=0 temp=num while(temp>0): digit=temp%10 sum=sum+digit**3 temp=temp//10 if (num==sum): print(("armstrong number")) else: print("not")
240868c7fb1cf39a3db78c9c5912d7dc93c79e45
SamuelMontanez/Shopping_List
/shopping_list.py
2,127
4.1875
4
import os shopping_list = [] def clear_screen(): os.system("cls" if os.name == "nt" else "clear") def show_help(): clear_screen() print("What should we pick up at the store?") print(""" Enter 'DONE' to stop adding items. Enter 'HELP' for this help. Enter 'SHOW' to see your current list. Enter 'REMOVE' to delete an item from your list. """) def add_to_list(item): show_list() if len(shopping_list): #If there are items in the shopping list position = input("Where should I add {}?\n" "Press ENTER to add to the end of the list\n" "> ".format(item)) else: position = 0 #This means if this is the first item in the list then the position is 0. try: position = abs(int(position)) #abs stands for absolute, so if a user gives us -5 the abs of that is 5. except ValueError: position = None #If value error occurs, then 'none' means dont put the item in the list. if position is not None: shopping_list.insert(position-1, item) #The reason for the -1 is beacuse the user should input 1 for the first spot or 2 for the second spot so the -1 will put it in the correct spot. else: shopping_list.append(new_item) show_list() def show_list(): clear_screen() print("Here's your list:") index = 1 for item in shopping_list: print("{}. {}".format(index, item)) index += 1 print("-"*10) def remove_from_list(): show_list() what_to_remove = input("What would you like to remove?\n> ") try: shopping_list.remove(what_to_remove) except ValueError: pass show_list() show_help() while True: new_item = input("> ") if new_item.upper() == 'DONE' or new_item.upper() == 'QUIT': break elif new_item.upper() == 'HELP': show_help() continue elif new_item.upper() == 'SHOW': show_list() continue elif new_item.upper() == 'REMOVE': remove_from_list() else: add_to_list(new_item) show_list()
c158bda35f01e5fd9480c9b0519064d309a83047
Vibek/Back-up
/Human_intention/src/Train_model/jacobi_theta.py
565
3.703125
4
import numpy as np from scipy.linalg import solve '''____Define function____''' def jacobi(mu, var, x, k): D = np.diag(mu) R = mu - np.diagflat(D) for i in range(n): x = (var - np.dot(R,x))/ D print str(i).zfill(3), print(x) return x '''___Main function___''' mu = np.array([[4.0, -2.0, 1.0], [1.0, -3.0, 2.0], [-1.0, 2.0, 6.0]]) car = [1.0, 2.0, 3.0] x = [1.0, 1.0, 1.0] k = 25 print("\n\ninit"), print(x) print("") x = jacobi(mu, var, x, k) print("\nSol "), print(x) print("Act "), print solve(A, b) print("\n")
64fa14b4e6adfd945fdd346cc638656ca7b52640
kmorris0123/list_overlap_no_duplicates
/list_overlap_no_duplicate_nums.py
1,181
3.921875
4
import random import os play = True while play == True: list_one_size = random.randint(10,20) list_two_size = random.randint(10,20) list_one = [] list_two = [] common_list = [] x = range(1,list_one_size) for elem in x: num = random.randint(1,20) list_one.append(num) y = range(1,list_two_size) for elem in y: num_2 = random.randint(1,20) list_two.append(num_2) list_one_length = len(list_one) list_two_length = len(list_two) if list_one_length > list_two_length: for item in list_one: if item in list_two and item not in common_list: common_list.append(item) if list_two_length > list_one_length: for item in list_two: if item in list_one and item not in common_list: common_list.append(item) list_one_p = "List 1: "+ str(list_one) list_two_p = "List 2: "+ str(list_two) common_list_p = "Overlapping Numbers: " + str(common_list) print("") print(list_one_p) print("") print(list_two_p) print("") print(common_list_p) print("") play_again = input('Do you want to play again? "Yes" or "No": ') if play_again == "yes": play = True os.system('clear') else: print("Thanks for playing!") play = False
dbdf3bdd97752a32d7eb1eef8b0927a69276327c
gengkeye/orderbot
/apps/orderbot/utils.py
323
3.65625
4
# -*- coding: utf-8 -*- # import re def convert_str_to_list(text, seperator=' '): text_list = text.split(seperator) return list(filter(None, text_list)) def convert_str_to_num_list(text, seperator=' '): text_list = re.sub(r'\D', seperator, text).split(seperator) return list(filter(None, text_list))
c99dcddf225321f2640e21f478676b1e7cb1ee2a
kristy0414/SF_crime_analysis
/SF_Crime_github.py
16,671
3.6875
4
# Databricks notebook source # MAGIC %md # MAGIC ## SF crime data analysis and modeling # COMMAND ---------- # MAGIC %md # MAGIC ##### In this notebook, you can learn how to use Spark SQL for big data analysis on SF crime data. (https://data.sfgov.org/Public-Safety/Police-Department-Incident-Reports-Historical-2003/tmnf-yvry). # COMMAND ---------- # DBTITLE 1,Import package from csv import reader from pyspark.sql import Row from pyspark.sql import SparkSession from pyspark.sql.types import * import pandas as pd import numpy as np import seaborn as sb import matplotlib.pyplot as plt import warnings import os os.environ["PYSPARK_PYTHON"] = "python3" # COMMAND ---------- data_path = "dbfs:/laioffer/spark_hw1/data/sf_03_18.csv" # use this file name later # COMMAND ---------- # DBTITLE 1,Get dataframe and sql from pyspark.sql import SparkSession spark = SparkSession \ .builder \ .appName("crime analysis") \ .config("spark.some.config.option", "some-value") \ .getOrCreate() df_opt1 = spark.read.format("csv").option("header", "true").load(data_path) display(df_opt1) df_opt1.createOrReplaceTempView("sf_crime") # from pyspark.sql.functions import to_date, to_timestamp, hour # df_opt1 = df_opt1.withColumn('Date', to_date(df_opt1.OccurredOn, "MM/dd/yy")) # df_opt1 = df_opt1.withColumn('Time', to_timestamp(df_opt1.OccurredOn, "MM/dd/yy HH:mm")) # df_opt1 = df_opt1.withColumn('Hour', hour(df_opt1['Time'])) # df_opt1 = df_opt1.withColumn("DayOfWeek", date_format(df_opt1.Date, "EEEE")) # COMMAND ---------- # MAGIC %md # MAGIC #### Q1 question (OLAP): # MAGIC #####Write a Spark program that counts the number of crimes for different category. # MAGIC # MAGIC Below are some example codes to demonstrate the way to use Spark RDD, DF, and SQL to work with big data. You can follow this example to finish other questions. # COMMAND ---------- # DBTITLE 1,Spark dataframe based solution for Q1 q1_result = df_opt1.groupBy('category').count().orderBy('count', ascending=False) display(q1_result) # COMMAND ---------- # DBTITLE 1,Spark SQL based solution for Q1 #Spark SQL based #df_update.createOrReplaceTempView("sf_crime"), this view step is important and need to be done before sql queries crimeCategory = spark.sql("SELECT category, COUNT(*) AS Count FROM sf_crime GROUP BY category ORDER BY Count DESC") display(crimeCategory) # COMMAND ---------- # important hints: ## first step: spark df or sql to compute the statisitc result ## second step: export your result to a pandas dataframe. spark_df_q1 = df_opt1.groupBy('category').count().orderBy('count', ascending=False) display(spark_df_q1) # crimes_pd_df = crimeCategory.toPandas() # Spark does not support this function, please refer https://matplotlib.org/ for visuliation. You need to use display to show the figure in the databricks community. # display(crimes_pd_df) # COMMAND ---------- # DBTITLE 1,Visualize your results import seaborn as sns fig_dims = (15,6) fig = plt.subplots(figsize=fig_dims) spark_df_q1_plot = spark_df_q1.toPandas() chart=sns.barplot(x = 'category', y = 'count', palette= 'coolwarm',data = spark_df_q1_plot) chart.set_xticklabels(chart.get_xticklabels(), rotation=45, horizontalalignment='right') # COMMAND ---------- # MAGIC %md # MAGIC #### Q2 question (OLAP) # MAGIC Counts the number of crimes for different district, and visualize your results # COMMAND ---------- spark_sql_q2 = spark.sql("SELECT PdDistrict, COUNT(*) AS Count FROM sf_crime GROUP BY 1 ORDER BY 2 DESC") display(spark_sql_q2) # COMMAND ---------- import matplotlib.pyplot as plt crimes_dis_pd_df = spark_sql_q2.toPandas() plt.figure() ax = crimes_dis_pd_df.plot(kind = 'bar',x='PdDistrict',y = 'Count',logy= True,legend = False, align = 'center') ax.set_ylabel('count',fontsize = 12) ax.set_xlabel('PdDistrict',fontsize = 12) plt.xticks(fontsize=8, rotation=30) plt.title('#2 Number of crimes for different districts') display() # COMMAND ---------- # MAGIC %md # MAGIC #### Q3 question (OLAP) # MAGIC Count the number of crimes each "Sunday" at "SF downtown". # MAGIC hint 1: SF downtown is defiend via the range of spatial location. For example, you can use a rectangle to define the SF downtown, or you can define a cicle with center as well. Thus, you need to write your own UDF function to filter data which are located inside certain spatial range. You can follow the example here: https://changhsinlee.com/pyspark-udf/ # MAGIC # MAGIC hint 2: SF downtown physical location rectangle a < x < b and c < y < d. thus, San Francisco Latitude and longitude coordinates are: 37.773972, -122.431297. X and Y represents each. So we assume SF downtown spacial range: X (-122.4213,-122.4313), Y(37.7540,37.7740). # MAGIC # COMMAND ---------- df_opt2 = df_opt1[['IncidntNum', 'Category', 'Descript', 'DayOfWeek', 'Date', 'Time', 'PdDistrict', 'Resolution', 'Address', 'X', 'Y', 'Location']] display(df_opt2) df_opt2.createOrReplaceTempView("sf_crime") # COMMAND ---------- from pyspark.sql.functions import hour, date_format, to_date, month, year # add new columns to convert Date to date format df_new = df_opt2.withColumn("IncidentDate",to_date(df_opt2.Date, "MM/dd/yyyy")) # extract month and year from incident date df_new = df_new.withColumn('Month',month(df_new['IncidentDate'])) df_new = df_new.withColumn('Year', year(df_new['IncidentDate'])) display(df_new.take(5)) df_new.createOrReplaceTempView("sf_crime1") # COMMAND ---------- # sql way spark_sql_q3 = spark.sql("SELECT IncidentDate, DayOfWeek, COUNT(*) AS Count FROM sf_crime1 WHERE DayOfWeek = 'Sunday' \ AND X > -122.4313 AND X < -122.4213 AND Y > 37.7540 AND Y < 37.7740 \ GROUP BY IncidentDate, DayOfWeek ORDER BY IncidentDate") # COMMAND ---------- display(spark_sql_q3) # COMMAND ---------- # MAGIC %sql select month(IncidentDate), count(*) AS Count from sf_crime1 WHERE DayOfWeek = 'Sunday' # MAGIC AND X > -122.4313 AND X < -122.4213 AND Y > 37.7540 AND Y < 37.7740 # MAGIC GROUP BY month(IncidentDate) ORDER BY month(IncidentDate),Count desc # COMMAND ---------- # MAGIC %md # MAGIC late June: 54+33+31+28= 146 July 4th is Independence Day, people tend to have a vocation around this holiday and trabel to SF city. # MAGIC # MAGIC December10/11 and new year: 35+28+31= 94 Some companies may approve employees's paid time off before Christmas holiday, and the whole December is holiday season. travel to SF is a choice. # MAGIC # MAGIC the whole July: 29+26+26= 81 July 4th is Independence Day, it is time for travel. # MAGIC # MAGIC the whole September: 29+26+26= 81 the first Monday of September is also another holiday called Labor Day. # MAGIC # MAGIC late October: 33+31= 64 the second Monday of October is Columbus Day that is another holiday. # MAGIC # MAGIC why travel cause crime? especially for June, October and Janaury? Cause when you are not at home, it gives crimer a chance to approach you and especially when you have a tight vocation schedule you will lose your awareness to take care all of the stuff. it also reflects that people like to travel from the whole second half of the year. # COMMAND ---------- # MAGIC # MAGIC %sql select year(IncidentDate), month(IncidentDate), count(*) AS Count from sf_crime1 WHERE DayOfWeek = 'Sunday' # MAGIC AND X > -122.4313 AND X < -122.4213 AND Y > 37.7540 AND Y < 37.7740 # MAGIC GROUP BY year(IncidentDate), month(IncidentDate) ORDER BY year(IncidentDate), month(IncidentDate),Count desc # COMMAND ---------- # MAGIC %md # MAGIC 2012, 2013, 2016, 2017 is crazy. what's happened? Oh, it is actually the election year. I still remember when I first land to US and I have no idea about America election. But I do remember lots of students sit in the college plaza to watch for the vote activity. And most of them felt sad when it turns out that the result did not meet their expecatation. # MAGIC I may think it is reasonable to make a hypothesis that a new presidential election is prone to social unrest. Also, see what happened this year, 2020 is also a election year. Do you feel the whole socitey is safe enough? Not, right. # COMMAND ---------- # MAGIC %md # MAGIC #### Q4 question (OLAP) # MAGIC Analysis the number of crime in each month of 2015, 2016, 2017, 2018. Then, give your insights for the output results. What is the business impact for your result? # COMMAND ---------- years = [2015, 2016, 2017, 2018] df_years = df_new[df_new.Year.isin(years)] display(df_years.take(10)) # COMMAND ---------- spark_df_q4 = df_years.groupby(['Year', 'Month']).count().orderBy('Year','Month') display(spark_df_q4) # COMMAND ---------- df_years.createOrReplaceTempView("sf_crime2") fig_dims = (20,6) # COMMAND ---------- # MAGIC %sql select distinct(category) as type, count(*) as Count, year from sf_crime2 where Year in (2015, 2016, 2017, 2018) group by 1,3 order by 2 desc # COMMAND ---------- # MAGIC %sql select count(*) as Count, year, month from sf_crime2 where Year in (2015, 2016, 2017, 2018) and category='LARCENY/THEFT' group by 2,3 order by 2,3 # COMMAND ---------- # MAGIC %md # MAGIC the business impact is the theft contributes to the most crime portion. And the 47th Act signed by the governor in the California take on effect at Nov 2014. After 2015 winter, the crime number is boosting under theft category until Jan 2018.The reason for the decline in crime rate since 2018 may be that the San Francisco Police Department has increased uniformed police patrols. # COMMAND ---------- # MAGIC %md # MAGIC #### Q5 question (OLAP) # MAGIC Analysis the number of crime w.r.t the hour in certian day like 2015/12/15, 2016/12/15, 2017/12/15. Then, give your travel suggestion to visit SF. # COMMAND ---------- from pyspark.sql.functions import to_timestamp # add new columns to convert Time to hour format df_new1 = df_new.withColumn('IncidentTime', to_timestamp(df_new['Time'],'HH:mm')) # extract hour from incident time df_new2 = df_new1.withColumn('Hour',hour(df_new1['IncidentTime'])) display(df_new2.take(5)) # COMMAND ---------- dates = ['12/15/2015','12/15/2016','12/15/2017'] df_days = df_new2[df_new2.Date.isin(dates)] spark_df_q5_1 = df_days.groupby('Hour','Date').count().orderBy('Date','Hour') display(spark_df_q5_1) # COMMAND ---------- # MAGIC %md # MAGIC from the plot we can see that: # MAGIC for 2015, the peak time of crime is 12,14,16,19. it just from noon to the sunset. # MAGIC for 2016, the peak time of crime is 12,18,19. it concentrate on 18, the dinner time. # MAGIC for 2017, the peak time of crime is 0, 8,10,15,16,17,18,19,22,23. the data is more even and the interesting trend is that it seems the crime has more records during the midnight, from 22 to 24. I think at that time there is less police power and the crimers are also easy to steal stuff from the dark enviroment. # COMMAND ---------- # MAGIC %md # MAGIC #### Q6 question (OLAP) # MAGIC (1) Step1: Find out the top-3 danger district # MAGIC (2) Step2: find out the crime event w.r.t category and time (hour) from the result of step 1 # MAGIC (3) give your advice to distribute the police based on your analysis results. # COMMAND ---------- #sql way spark_sql_q6_s1 = spark.sql( """ SELECT PdDistrict, COUNT(*) as Count FROM sf_crime GROUP BY 1 ORDER BY 2 DESC LIMIT 3 """ ) display(spark_sql_q6_s1) # COMMAND ---------- df_new2.createOrReplaceTempView("sf_crime2") display(df_new2.take(5)) # COMMAND ---------- # MAGIC %sql select category, hour, count(*) from sf_crime2 where PdDistrict in ('SOUTHERN','MISSION','NORTHERN') group by category, hour # MAGIC order by category, hour # COMMAND ---------- # MAGIC %md # MAGIC the lunch time and dinner time, espcially the dinner time will have more crime cases. And the most of them are theft and assault. Cause the California law won't arrest the crimer who steal something valued under 900 dollars. people will get off from work and go to grocery store, eat dinner outset or hang out with friends. Southern Area probably has less police power and where people live. The route from office to home can describle like from Mission Area to Southern Area. People need to be careful when they go out of the office, take public traffic, and walk to home with awareness. don't look at cellphone, instead should look around the surroundings. # COMMAND ---------- # MAGIC %md # MAGIC #### Q7 question (OLAP) # MAGIC For different category of crime, find the percentage of resolution. Based on the output, give your hints to adjust the policy. # COMMAND ---------- # MAGIC %md # MAGIC Below is the resolution count for each category. # COMMAND ---------- # MAGIC %sql select category, count(*) from sf_crime2 # MAGIC group by category order by count(*) desc limit 10 # COMMAND ---------- # MAGIC %sql select distinct(resolution) as resolve from sf_crime2 # COMMAND ---------- # MAGIC %md # MAGIC Here, 'None' takes the most portion of the data. I think they are the cases that are not resolved. it is still open in investigation. So we exclude it. usually, to analyze a problem, we need to know 80/20 rule. focus on the 80% of the data and ignore the cases with less data. So I will pick up the top 10 categories and analyze the resolution percentage. The rest of the category will discover in the future if i have more time. # COMMAND ---------- # MAGIC %sql select distinct Category, Resolution, count(*) over (PARTITION BY Category, Resolution) as sum_div from sf_crime2 # MAGIC where Resolution != 'NONE' # MAGIC order by Category, sum_div desc # COMMAND ---------- # MAGIC %sql with cte_1 as # MAGIC (select distinct Category, Resolution, count(*) over (PARTITION BY Category, Resolution) as sum_div, # MAGIC count(*) over (PARTITION BY Category) as cat_div # MAGIC from sf_crime2 # MAGIC where Resolution != 'NONE' # MAGIC order by Category, sum_div desc) # MAGIC select distinct Category, Resolution, round(sum_div/cat_div,4) from cte_1 # MAGIC where Category in (select category from (select category, count(*) from sf_crime2 where Resolution != 'NONE' # MAGIC group by category order by count(*) desc limit 10) as a) # COMMAND ---------- # MAGIC %md # MAGIC the most cases's resolution is arrest, booked. it means it is easy to make a judgement. but missing person and non-criminal has a variance. # MAGIC most missing person's result is located. is it means dead? how to prevent it and how to rescue before we found a dead body? # MAGIC also, for non-criminal, the most cases are psychopathic cases. Do we need to pay attention to people who has mental health problems? Are they tend to attack people? where do they live and how to make residential areas more safe? # MAGIC Besides, we may also think about to adjust the police power to the poor area and protect the people there. # COMMAND ---------- # MAGIC %md # MAGIC ### Conclusion. # MAGIC Use four sentences to summary your work. Like what you have done, how to do it, what the techinical steps, what is your business impact. # MAGIC More details are appreciated. You can think about this a report for your manager. Then, you need to use this experience to prove that you have strong background on big data analysis. # MAGIC Point 1: what is your story ? and why you do this work ? # MAGIC Point 2: how can you do it ? keywords: Spark, Spark SQL, Dataframe, Data clean, Data visulization, Data size, clustering, OLAP, # MAGIC Point 3: what do you learn from the data ? keywords: crime, trend, advising, conclusion, runtime # COMMAND ---------- # MAGIC %md # MAGIC I generated reports from different topics and perspectives. such as time, district, year, resolution type, crime type and so on. I cleaned the data, process data to integret the format, and run sql queries to check the data pattern or trends, then visulize the results. # MAGIC # MAGIC I found several business impact that we may need to have notice: # MAGIC # MAGIC 1 election year will need more polce power to the unrest society. # MAGIC # MAGIC 2 lunch time, dinner time is the best time for crimer to take action. need police power patrol around the restaurant plazas. # MAGIC # MAGIC 3 travel time, holiday season is also a peak time for crimes. # MAGIC # MAGIC the insight is when you want to have a rest and relax, the crime won't let you to take a rest. Just be careful.
8ba4b76757a1073e7249d71a87a555c79dbee829
alcbeatriz/Pesquisa-Operacional
/REVISAO01/questao02.py
485
3.6875
4
listanum = [] maior = 0 menor = 0 media = 0 for c in range(0,10): listanum.append(int(input(f'Digite um valor para a {c} posição: '))) if c== 0: maior = menor = listanum[c] else: if listanum[c] >maior: maior = listanum[c] if listanum[c]<menor: menor = listanum[c] print(f'Você digitou os valores{listanum}') print(f'O maior valor é: {maior}') print(f'O menor valor é: {menor}') print(f'A média é: {sum(listanum)/2}')
1f643c74b3415e023798cc341e33ba98d1b18995
domzhaomathematics/Trees-4
/lca_binary_tree.py
2,059
4.03125
4
#RECURSIVE SOLUTION (post-order pattern) #Time complexity: O(n) #Space complexity: O(h) ''' Propagate from bottom if left is found and right is found (p,q). We have to traverse post-orderly to make sure we don't miss anything. This works because if they are not found in the left and right subtree respectively, it means the common ancestor not this one and is in one of the subtree. Also, only one of them will have true for left and right. left could be p and q , we don't know. ''' class Solution: def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': found=None def helper(root,p,q): nonlocal found if not root or found: return False left=helper(root.left,p,q) right=helper(root.right,p,q) #either left and right or left and present root,right and present root mid= (root==p or root==q) if left+right+mid>=2: found=root return (mid or right or left) helper(root,p,q) return found #ALTERNATIVE SOLUTION (recursive) ''' When p or q it's found, the root that contains it is propagated to the top until one root has left and right, then this one is propagated to the top. On the top level, we return whatever was propagted to there. If the top level is the common ancestor, then left and right were propagated to there. If not, then only one side has propagated something and it's the common ancestor. Only one node will have both left and right (above that, they would be in the same subtree). ''' class Solution: def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': if not root or root==p or root==q: return root left=self.lowestCommonAncestor(root.left,p,q) right=self.lowestCommonAncestor(root.right,p,q) if left and right: return root if left: return left if right: return right
637967ffadaf57dc97cbbcffff80829135e96f2a
mex3/fizmat-v
/helloworld.py
658
3.65625
4
#Решатель Квадратных Уравнений!!! # авторы: Матвеев и Орусов q = input() w = q.find('x^2') a = q[:w] if a == '': a = 1 else: a = int(a) d=max(q.find("2+"), q.find('2-')) z = max(q.find('x+'), q.find('x-')) b = q[d+2:z] if b == '': b = 1 else: b = int(b) e = q.find('=') c = int(q[z+2:e]) if d == q.find("2-"): b = -b if z == q.find('x-'): c = -c D = b**2 - 4 * a * c if D < 0: x = (-b + 1j * D ** 0.5)/(2 * a) y = (-b - 1j * D ** 0.5)/(2 * a) print(x, ';', y) elif D == 0: x = (-b)/(2 * a) print(x) else: x = (-b + D ** 0.5)/(2 * a) y = (-b - D ** 0.5)/(2 * a) print(x, ';', y) # конец кода
060370a41b9b3d0d207002ded9c38cd554cd5a6c
HemanandhiniGanesan/hello-world-eg
/BVRIT_Sample+programs.py
436
3.671875
4
# coding: utf-8 # In[2]: print ("hello world") # In[5]: a="hema" print ("hai",a) # In[6]: a=int(input("enter a number")) b=int(input("enter another number")) c=a+b print("Addition of two numbers:",c) # In[23]: import matplotlib.pyplot as plt var=['a','b','c'] var1=[5.5,6.2,6.3] plt.plot(var,var1) plt.title("Height of students in a class") plt.xlabel("Sections") plt.ylabel("Height") plt.show() plt.savefig('fig.png')
d78d438330027e6b6078543100b5bb462e2e85f2
NazmiDere/11-HAFTA-OOP
/class battleships.py
8,258
3.90625
4
from random import randint,choice from time import sleep class battleships(): def __init__(self): self.table = [["--" for a in range(10)] for b in range(10)] self.all_coor = [[a, b] for a in range(10) for b in range(10)] self.time = False self.play() def horizontal(self, unit): while True: self.ship = [] coor = choice(self.all_coor) if coor[0] > 9 - unit: coor[0] = 9 - unit if coor not in self.ships: #to check whether 'coor' is besides other ship or not if [coor[0] + 1, coor[1]] not in self.ships: if [coor[0] - 1, coor[1]] not in self.ships: if [coor[0], coor[1] + 1] not in self.ships: if [coor[0], coor[1] - 1] not in self.ships: self.ship.append(coor) for i in range(unit-1): coor = [coor[0] + 1] + [coor[1]] if coor not in self.ships: #to check whether 'coor' is besides other ship or not if [coor[0] + 1, coor[1]] not in self.ships: if [coor[0] - 1, coor[1]] not in self.ships: if [coor[0], coor[1] + 1] not in self.ships: if [coor[0], coor[1] - 1] not in self.ships: self.ship.append(coor) if len(self.ship) == unit: self.ships.extend(self.ship) else: continue return self.ships def vertical(self, unit): while True: self.ship = [] coor = choice(self.all_coor) if coor[1] > 9 - unit: coor[1] = 9 - unit if coor not in self.ships: #to check whether 'coor' is besides other ship or not if [coor[0] + 1, coor[1]] not in self.ships: if [coor[0] - 1, coor[1]] not in self.ships: if [coor[0], coor[1] + 1] not in self.ships: if [coor[0], coor[1] - 1] not in self.ships: self.ship.append(coor) for i in range(unit-1): coor = [coor[0]] + [coor[1] + 1] if coor not in self.ships: #to check whether 'coor' is besides other ship or not if [coor[0] + 1, coor[1]] not in self.ships: if [coor[0] - 1, coor[1]] not in self.ships: if [coor[0], coor[1] + 1] not in self.ships: if [coor[0], coor[1] - 1] not in self.ships: self.ship.append(coor) if len(self.ship) == unit: self.ships.extend(self.ship) else: continue return self.ships def deploy(self): #for ships which has 4 units counter = 0 while True: mark = randint(0,1) if counter == 2: break elif mark == 0: self.horizontal(4) elif mark == 1: self.vertical(4) counter += 1 #for ships which has 3 units counter = 0 while True: mark = randint(0,1) if counter == 2: break elif mark == 0: self.horizontal(3) elif mark == 1: self.vertical(3) counter += 1 #for ships which has 2 units counter = 0 while True: mark = randint(0,1) if counter == 2: break elif mark == 0: self.horizontal(2) elif mark == 1: self.vertical(2) counter += 1 #for ships which has 1 unit counter = 0 while True: mark = randint(0,1) if counter == 2: break self.horizontal(1) counter += 1 def all_ships(self): for ship in self.ships: self.table[ship[0]][ship[1]] = "XX" return self.table def print_table(self): for item in self.table: print("\n\t".expandtabs(20),*item) if self.time: sleep(1) def coordinate(self): global y global x while True: y = input("\nPlease choose the y axis:") if y.isdigit() == False: print("Please enter number between 0 - 10.") time = False continue else: y = int(y) y = y - 1 if y > 9 or y < 0: print("Please enter number between 0 - 10.") continue x = input("\nPlease choose the x axis:") if x.isdigit() == False: print("Please enter number between 0 - 10.") time = False continue else: x = int(x) x = x - 1 if x > 9 or x < 0: print("Please enter number between 0 - 10.") continue if self.table[y][x] == " " or self.table[y][x] == "XX": print("You've already fire there.Please try again.") continue else: break def fire(self): global time if [y, x] not in self.ships: self.table[y][x] = " " self.time = True else: self.table[y][x] = "XX" self.time = False for ship in self.ships[0:4]: if [y, x] in self.ships[0:4]: self.table[ship[0]][ship[1]] = "XX" for ship in self.ships[4:8]: if [y, x] in self.ships[4:8]: self.table[ship[0]][ship[1]] = "XX" for ship in self.ships[8:11]: if [y, x] in self.ships[8:11]: self.table[ship[0]][ship[1]] = "XX" for ship in self.ships[11:14]: if [y, x] in self.ships[11:14]: self.table[ship[0]][ship[1]] = "XX" for ship in self.ships[14:16]: if [y, x] in self.ships[14:16]: self.table[ship[0]][ship[1]] = "XX" for ship in self.ships[16:18]: if [y, x] in self.ships[16:18]: self.table[ship[0]][ship[1]] = "XX" for ship in self.ships[18:19]: if [y, x] in self.ships[18:19]: self.table[ship[0]][ship[1]] = "XX" for ship in self.ships[19:20]: if [y, x] in self.ships[19:20]: self.table[ship[0]][ship[1]] = "XX" return self.table def prnt(self): print("*"*15,"BATTLESHIPS","*"*15) print("""\n WELCOME TO BATTLESHIPS\n There are 8 ships.Two of them has 4 unit. Two of them has 3 unit. Two of them has 2 unit. Two of them has 1 unit. Ships are not besides each other. You can shoot them 15 times. You can choose the coordinates to shoot there.""") def play(self): self.prnt() self.turn = 0 self.ships = []#all ships which are deployed self.deploy() try: while True: if self.turn == 15: print("Game over.You lose.") self.all_ships() self.print_table() break self.print_table() self.coordinate() self.fire() self.turn += 1 counter = 0 for items in self.table: for item in items: if item == "XX": counter += 1 if counter == 20: self.print_table() print("\nCongratulations.You've hit the each ships.") break except: print("Something happened wrong, please try again") battle1 = battleships()
ec8887453eaa5f263665f651338a470b4b8c5f7c
lura00/guess_the_number
/main.py
915
4.15625
4
from random import randint from game1 import number_game def show_menu(): print("\n===========================================") print("| Welcome |") print("| Do you want to play a game? |") print("| 1. Enter the number game |") print("| 2. Exit |") print("===========================================") while True: random_value = randint(0,10) show_menu() try: menu_choice = int(input("Make your choice, guess or exit: ")) if menu_choice == 1: number_game(random_value) elif menu_choice == 2: print("Thanks for playing, welcome back! ") break else: print("Thats a strange symbol, I can't seem to understand your input?") except ValueError: print("An error occurred, please try another input!")
4de0548a0dee06fe345de994055c5542903c5a03
cyril-wang/pythongames
/pagman/spritesandsounds2.py
7,460
3.859375
4
# using sounds and images # adding images with sprites # sprites - single two-dimensional image # sprites are drawn on top of the background # sprites are stored in image files on computer # pygame supports bmp, png, jpg, gif for images # and supports MIDI, WAV, MP3 for sound file # similar to collision detection game, except will use sprites # and will play backgorund music and add sound effects import pygame, sys, time, random # import modules from pygame.locals import * # set up pygame pygame.init() # initialize pygame mainClock = pygame.time.Clock() # similar use as time.sleep() # set up the window WINDOWWIDTH = 1200 # width and height of window WINDOWHEIGHT = 675 windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT), 0, 32) # set up window pygame.display.set_caption('Sprites and Sounds') # set up the colors WHITE = (255,255,255) # only need white for the background # set up the block data structure player = pygame.Rect(300,100,40,40) # creates player rectangle playerImage = pygame.image.load('OMEGALUL.png') playerStretchedImage = pygame.transform.scale(playerImage, (40,40)) BackGround = pygame.image.load('FinalDestination.jpg') # stretches the image the more food you eat foodImage = pygame.image.load('khal.png') foods = [] for i in range(20): # creates 20 food squares randomly splaced foods.append(pygame.Rect(random.randint(0, WINDOWWIDTH - 56), random.randint(0, WINDOWHEIGHT - 56), 56, 56)) foodCounter = 0 NEWFOOD = 40 # set up keyboard variables moveLeft = False # keeps track of which arrow key is being pressed moveRight = False # when key is pressed, variable is set to TRUE moveUp = False # i.e. if up arrow is pressed, moveUp = True moveDown = False MOVESPEED = 6 # set up the music pickUpSound = pygame.mixer.Sound('coin.wav') pygame.mixer.music.load('inferno.mp3') # loads the music pygame.mixer.music.set_volume(0.1) pygame.mixer.music.play(-1, 0.0) # plays the music # first paramter is how many times to play it, -1 means play forever # second parameter is the point in the sound file to start playing, 0.0 = beginning musicPlaying = True # Run the game loop while True: # runs until QUIT event type for event in pygame.event.get(): # check each event if event.type == QUIT: # if quit event pygame.quit() # quits pygame sys.exit() # terminates program # handling events - user inputs from mouse and keyboards # pygame.event.get(): # quit, keydown, keyup, mousemotion, mousebuttondown, mousebuttonup if event.type == KEYDOWN: # if keydown event type, or pressing the key # changing the keyboard variables if event.key == K_LEFT or event.key == K_a: # if pressed key is left arrow or a moveRight = False moveLeft = True if event.key == K_RIGHT or event.key == K_d: # if pressed key is right arrow or d moveLeft = False # moveLeft first so that both arent true moveRight = True if event.key == K_UP or event.key == K_w: # if key is up arrow or w moveDown = False moveUp = True if event.key == K_DOWN or event.key == K_s: # if key is down arrow or s moveUp = False moveDown = True if event.type == KEYUP: # if KEYUP event type, or releasing the key if event.key == K_ESCAPE: # if escape key pygame.quit() sys.exit() # terminates the program if event.key == K_LEFT or event.key == K_a: moveLeft = False # if releasing left key, stops moving left if event.key == K_RIGHT or event.key == K_d: moveRight = False # if releasing right, stops moving right if event.key == K_UP or event.key == K_w: moveUp = False # if released up, stops moving up if event.key == K_DOWN or event.key == K_s: moveDown = False # if released down, stops moving down # teleporting the player if event.key == K_x: # if releasing x, teleports player player.top = random.randint(0, WINDOWHEIGHT - player.height) player.left = random.randint(0, WINDOWWIDTH - player.width) # generates random coordinates for the top-left corner # - player.height so that it does not go off the screen if event.key == K_m: # pressing m if musicPlaying: # if music is playing, pygame.mixer.music.stop()# stops the music else: # but if no music pygame.mixer.music.play(-1, 0.0) # plays the music musicPlaying = not musicPlaying # toggles the value in musicPlaying if event.type == MOUSEBUTTONUP: # if clicking the mouse/releases the mouse foods.append(pygame.Rect(event.pos[0], event.pos[1], 28, 28)) # appends more food squares # based on the position of the mouse event, or where mouse is clicked # adding food automatically foodCounter += 1 # foodCounter increases by 1 each iteration if foodCounter >= NEWFOOD: # once foodCounter passes NEWFOOD (i.e. after 40 iterations) # adds new food foodCounter = 0 # resets foodCounter foods.append(pygame.Rect(random.randint(0, WINDOWWIDTH - 56), random.randint(0, WINDOWHEIGHT - 56), 56, 56)) # and adds a new food square, similar to the ones created before # draw the white background onto the surface windowSurface.fill(WHITE) # fills the surface with white, like a reset windowSurface.blit(BackGround, (0,0)) # move the player if moveDown and player.bottom < WINDOWHEIGHT: # if moveDown is True and player's box isn't past the bottom player.top += MOVESPEED # moves player down if moveUp and player.top > 0: # moveUP == True and box isn't past the top player.top -= MOVESPEED # moves player up if moveLeft and player.left > 0: player.left -= MOVESPEED # moves player left if moveRight and player.right < WINDOWWIDTH: player.right += MOVESPEED # moves player right # draw the block onto the surface windowSurface.blit(playerStretchedImage, player) # draws the stretched image where the player's position is # check whether the block has interesected with any food for food in foods[:]: if player.colliderect(food): foods.remove(food) player = pygame.Rect(player.left, player.top, player.width + 2, player.height +2) playerStretchedImage = pygame.transform.scale(playerImage, (player.width, player.height)) if musicPlaying: pickUpSound.play() # draw the food for food in foods: windowSurface.blit(foodImage, food) # draw the window onto the screen pygame.display.update() mainClock.tick(40)
e8e73b3c67b961f756dfe9a7b5423e21ab7fe1ea
tamaramtz/958d7822-da73-4bbc-817f-fa79ac0778bc
/cashflows/main.py
1,059
3.578125
4
import fire import json from util import Cashflow from util import InvestmentProject class Main(object): #def present_value @staticmethod def describe_investment(filepath, hurdle_rate=None): investment_project = InvestmentProject.from_csv(filepath=filepath, hurdle_rate=hurdle_rate) description = investment_project.describe() print(json.dumps(description, indent=4)) @staticmethod def plot_investment(filepath, save="", show=False): invest = InvestmentProject.from_csv(filepath=filepath) fig = invest.plot(show=show) if save: fig.savefig("pic.png") return if __name__ == "__main__": fire.Fire(Main) #What does it means when the internal-rate of return is greater than the hurdle rate? #If the IRR exceeds the hurdle rate, the project would most likely be executed. Because the investment creates value. #Can the net present value be negative? Why? #Yes, because it means that when the value of the outflows is greater than the inflows, the NPV is negative.
278d9043abb7b40908cfe00e137a42ec3b4f5f41
Zojusane/pycharm
/dog.py
444
3.75
4
class Dog: def __init__(self, name, age, weight, length=5): """initialize the profile/attribute """ self.name = name self.age = age self.weight = weight self.length = length def sit(self): print(f"one {self.age} years old and {self.length}m long dog named {self.name:<8} is sitting now") class Cat: def __init__(self, name, kind): self.name = name self.kind = kind
a63b734707614e84d40d69fb1d98b2d97d8aff90
Ibrahim-Sakaama/OpenCV
/opencv/introOpenCV.py
984
3.96875
4
import cv2 #--------IMPORTANT--------------# #---------IF YOU HAVE AN IMAGE YOU'LL TREAT IT AS A MATRIX-------------# #----------THINK OF IT AS A MATRIX-------------------------------------# #imread() ==> pour lire une image A=cv2.imread("lena.jpg") #resize() ===> resize the image #A=cv2.resize(A,(200,200)) #demi image gauche #shape[1] ===> columns demi_gauche = A[:,0:A.shape[1]//2] #demi image droit demi_droite = A[:,A.shape[1]//2:] #demi image dessus #shape[0] ===> ligne demi_dessus = A[:A.shape[0]//2,:] #demi image dessous demi_dessous = A[A.shape[0]//2:,:] #cvtColor() ====> pour transformer une image couleur en gris gray = cv2.cvtColor(A, cv2.COLOR_BGR2GRAY) print(A) print(A.shape) print(gray.shape) #imshow() ==> afficher une image #Ibrahim is the name title #cv2.imshow("Ibrahim",A) cv2.imshow("Gray",gray) cv2.imshow("Demi Gauche", demi_gauche) cv2.imshow("Demi Droite", demi_droite) cv2.imshow("Demi dessus", demi_dessus) cv2.imshow("Demi Dessous",demi_dessous) cv2.waitKey(0)
62f7d5df5a2e39a6df6b1c1e827ef29cd6fb6507
scardona7/nuevasTecnologias
/taller2/3.gradosC-gradosF.py
206
3.765625
4
#Digite los grados a Fahrenheit gradosC = int(input("Digites los Grados Centigrados: ")) formula = gradosC * (9/5) Fahrenheit = formula + 32 print(f"{gradosC} Centigrados son {Fahrenheit} Fahrenheit ")
b5f47944ad935dc8521a83a8563a333ea717e39b
scardona7/nuevasTecnologias
/taller2/4.lustro.py
171
3.71875
4
#Cantidad de segundos que tiene un Lustro segundos = int(input("Digite los Segundos: ")) lustro = (segundos) * 0.1577 print(f"{segundos} segundos son {lustro} Lustros")
13006b2b8a77c97f0f190a3228aa53452bbefc6d
scardona7/nuevasTecnologias
/taller1/ejercicio11.py
665
4.1875
4
""" 11) Algoritmo que nos diga si una persona puede acceder a cursar un ciclo formativo de grado superior o no. Para acceder a un grado superior, si se tiene un titulo de bachiller, en caso de no tenerlo, se puede acceder si hemos superado una prueba de acceso. """ titulo_bach = input("¿Tiene un titulo Bachiller?: (si o no): ") if titulo_bach == "si" or titulo_bach == "Si": print("Puede acceder a un Grado Superior. Bienvenido!") else: prueba_acce=(input("¿Tiene la Prueba de Acceso?")) if prueba_acce == "si" or titulo_bach == "Si": print("Puede cursar el Grado Superior") else: print("No puede ingrsar al Grado Superior")
c3ecdefab05f1ad587b863be8830ee7db9b9763b
Dave-weatherby/All-Projects
/Python-Projects/gradesCSVReader/gradesCSVReader.py
909
3.765625
4
from csv import reader def main(): # open connection to grade.csv file for reading infile = open("grades.csv", "r") # construct a CSVReader object to do the hard work csvReader = reader(infile) # this will be our 2D list! gradeData = [] # building my 2D list for row in csvReader: # print(row) gradeData.append(row) # print report header print("{0:12} {1:15} {2:18} {3:5} {4:5} {5:5} {6:15} {7}".format("ID", "LAST", "FIRST", "P1", "P2", "P3", "CHALLENGES", "FINAL MARK")) # print grade data for grade in gradeData: print("{0:12} {1:15} {2:18} {3:5} {4:5} {5:5} {6:15} {7}%".format(grade[0], grade[1], grade[2], grade[3], grade[4], grade[5], grade[6], grade[7])) infile.close() main()
3f70a5ee9ea439c77de3088b5626938c6f36c057
w78813967/python
/2/2.py
1,114
3.640625
4
# -*- coding: utf-8 -*- """ Created on Tue Jul 10 14:13:04 2018 @author: user """ import mod a = mod.hello() print(a) def mydef(name): print('yo' , name) def mydef2(name): print('hi'+ name) def mydef3(name = 'noname'): print('hi', name) def redef(x): count = x * 10 return count mydef('ho') mydef2('hola') mydef(6) mydef3() mydef3('lul') print(redef(5)) class Data: def __init__ (self,name,age,sex): self.name = name self.age = age self.sex = sex def person(self): print('my name is:',self.name,'and ' +self.sex) print('I am '+ str(self.age) +' years old') p1 = Data('yoto' , 25,'female') p1.person() p1.name = 'idk' p1.person() class Employee: staff_num = 0 pay_raise = 1.4 def __init__(self,name,age,payment): self.name = name self.age = age self.payment = payment self.email = name+'@gmail.com' staff_num +=1 def info(self): print('{} {}'.format(self.name,self.age)) def pay_up(self): self.payment = int(self.payment * Employee.pay_raise)
8664ece33093d53bb4786a91fd25c2031de470aa
dshubham25/Algorithm-practice
/Arrays/ArrayMultiplication.py
724
3.71875
4
#Write a program that takes two arrays representing integers, and retums an integerWrite a program that takes two arrays representing integers, and retums an integer #representing their product def multiply(n1, n2): sign = -1 if (n1[0] < 0) ^ (n2[0] < 0) else 1 n1[0], n2[0] = abs(n1[0]), abs(n2[0]) result = [0] * ((len(n1) + len(n2)) for i in reversed(range(len(n1))): for j in reversed(range(len(n2))): result[i+j+1] += n1[i]*n2[j] result[i+j] += result[i+j+1] // 10 result[i+j+1] %= 10 result = result[next((i for i, x in enumerate(result) if x != 0), len(result)):] or [0] return [sign * result[0]] + result[1:]
bb32fc280e0d7c86de56fd577fdd5f00dd5ab6ba
ico1036/Algorithm
/DataStructure/N01_Linked_list.py
892
4.0625
4
# Linked list # ex 3 nodes: 67 -> 30 -> 59 # Node: data , link(where is next) # -- Contents in Linked list # Head: First node # Tail: Last node # Number of nodes: ex 3 class Node: def __init__(sef,item): self.data = item self.next = None class LinkedList: def __init__(self): self.nodeCount = 0 self.head = None self.tail = None # Possible Operation? # 1. K-th item # 2. Loop # 3. length # 4. Insert # 5. del # 6. Merge two list # We do not use the first index 0 # We use it as index 1 # 특정원소 지칭 def getAt(self,pos): if pos <=0 or pos > self.nodeCount return None else: curr = self.head while i <pos: curr = curr.next i+=1 return curr # 배열# # 저장공간 -연속한위치 # 특정원소 지칭: 매우간편 (O(1)) # 연결 리스트# # 저장공간 -임의의 위치 # 특정원소 지칭: 선형탐색 (O(n))
ec76011c2acc2385357706562219fcdbfb4091e0
GeorgeDonchev/war_card_game
/player.py
571
3.59375
4
class Player(): def __init__(self, name, hand): self.name = name self.hand = hand def play_card(self): drawn_card = self.hand.remove_card() print(f'{self.name} has placed {drawn_card}. ') print() return drawn_card def war(self): if len(self.hand.cards) < 3: return self.hand.cards else: war_deck = [self.hand.remove_card() for _ in range(3)] return war_deck def check_available_cards(self): return len(self.hand.cards)!=0
1adc325ba5f521539cc6f855d03bf7c96f5530b7
jchen49gsu/coding_practice
/leaf_similar_trees.py
661
3.796875
4
class TreeNode(object): def __init__(self,x): self.val = x self.left = None self.right = None class Solution(object): def leaf_similar_trees(self,t1,t2): res1 = [] res2 = [] self.find_leaf(t1,res1) self.find_leaf(t2,res2) return res1 == res2 def find_leaf(self,root,res): if root is None: return if root.left is None and root.right is None: res.append(root.val) return self.find_leaf(root.left,res) self.find_leaf(root.right,res) return s = Solution() t1 = TreeNode(5) t1.left = TreeNode(2) t1.right = TreeNode(3) t2 = TreeNode(1) t2.left = TreeNode(2) t2.right = TreeNode(3) print s.leaf_similar_trees(t1,t2)
748af97e71f5a9de11069e055fde6189bda5898d
jchen49gsu/coding_practice
/429. N-ary Tree Level Order Traversal.py
751
3.71875
4
from collections import deque class TreeNode(object): def __init__(self,x,children): self.val = x self.children = children class Solution(object): """docstring for Solution""" def levelOderTraversal(self,root): queue = deque() res = [] if root is None: return res queue.append(root) while queue: size = len(queue) l = [] for i in xrange(size): node = queue.popleft() l.append(node.val) for child in node.children: if child is not None: queue.append(child) res.append(l) return res children1 = [TreeNode(5,[]),TreeNode(6,[])] children2 = [TreeNode(3,children1),TreeNode(2,[]),TreeNode(4,[])] #要是list root = TreeNode(1,children2) s = Solution() print s.levelOderTraversal(root)
b41a5be37fad94bc8bcab7d9b73bbf5db114b7f6
jchen49gsu/coding_practice
/TT_missing_words.py
326
3.765625
4
class Solution(object): def missingWords(self,s,t): results = [] s = s.split() t = t.split() for i in xrange(len(s)): if s[i] not in t: results.append(s[i]) return results solution = Solution() s = "I am using HackerRank to improve programming" t = "am HackerRank to improve" print solution.missingWords(s,t)
a544b7b70aca23933437350ce1acbe9f42bc048a
anhvu2103/Python
/testcurrency.py
392
3.765625
4
h = open('test.txt', 'r') # Reading from the file content = h.readlines() # Varaible for storing the sum a = 0 # Iterating through the content # Of the file for line in content: for i in line: # Checking for the digit in # the string if i.isdigit() == True: a += int(i) print("The sum is:", a)
3cae92aaff622d16c388d184bc93968ce6773c8a
sainanda59/SID-TASK-2
/main.py
10,474
3.59375
4
from tkinter import * from PIL import ImageTk, Image from random import randint import sys import os global rock1, paper1, scissor1, spock1, lizard1, rock2, paper2, scissor2, spock2, lizard2 window = Tk() window.title("SID-TASK-2") window.config(bg='#3EDBF0') window.geometry('1990x900') welcome = Label(window, text="THE GAME OF CHANCES", bg='#3EDBF0', fg="black", font=("Arial Bold", 36)) welcome.grid(row=1, padx=500, pady=(250, 0)) player_name = Entry(window, width=27, borderwidth=9, bg="#FFA900", justify='center', fg="black", font=("Arial Bold", 16)) player_name.grid(pady=20, ipady=15, padx=500) player_name.insert(0, "ENTER PLAYER NAME") def exit_game(): window.destroy() def restart(): python = sys.executable os.execl(python, python, *sys.argv) def end_win(ans): end_window = Toplevel(window) end_window.title("RESULT WINDOW") end_window.geometry('1990x900') end_window.config(bg='#3EDBF0') msg_label = Label(end_window, text="THE GAME IS OVER", bg='#3EDBF0', fg="black", font=("Arial Bold", 45)) msg_label.grid(row=1, padx=500, pady=(250, 0)) score_label = Label(end_window, text=player_name.get() + "'S SCORE IS:- " + ans, borderwidth=9, bg="#FFA900", fg="black", font=("Arial Bold", 35)) score_label.grid(pady=20, padx=(350, 350)) restart_btn = Button(end_window, text="START NEW GAME", borderwidth=9, bg="black", fg="#FFA900", font=("Arial Bold", 18), command=restart) restart_btn.grid(row=4, pady=(0, 20)) exit_btn = Button(end_window, text="EXIT THE GAME", borderwidth=9, bg="black", fg="#FFA900", font=("Arial Bold", 18), command=exit_game) exit_btn.grid(row=5) def start(): global rock1, paper1, scissor1, spock1, lizard1, rock2, paper2, scissor2, spock2, lizard2 start_window = Toplevel(window) start_window.title("ROCK PAPER SCISSORS SPOCK LIZARD") start_window.geometry('1990x900') start_window.config(bg='#FF6464') rock1 = ImageTk.PhotoImage(Image.open("r1.jpg")) paper1 = ImageTk.PhotoImage(Image.open("h1.jpg")) scissor1 = ImageTk.PhotoImage(Image.open("sc1.jpg")) spock1 = ImageTk.PhotoImage(Image.open("sp1.jpg")) lizard1 = ImageTk.PhotoImage(Image.open("l1.jpg")) rock2 = ImageTk.PhotoImage(Image.open("r2.jpg")) paper2 = ImageTk.PhotoImage(Image.open("h2.jpg")) scissor2 = ImageTk.PhotoImage(Image.open("sc2.jpg")) spock2 = ImageTk.PhotoImage(Image.open("sp2.jpg")) lizard2 = ImageTk.PhotoImage(Image.open("l2.jpg")) def msg_update(msg): message['text'] = msg def computer_update(): final = int(computer_score['text']) final += 1 computer_score['text'] = str(final) if final == 3: ans = player_score['text'] start_window.destroy() end_win(ans) def player_update(): final = int(player_score['text']) final += 1 player_score['text'] = str(final) options = ["rock", "paper", "scissors", "spock", "lizard"] def winner_check(p, c): if p == c: msg_update("IT'S A TIE!!!") elif p == "rock": if c == "lizard": msg_update("PLAYER WINS!!!") player_update() elif c == "scissors": msg_update("PLAYER WINS!!!") player_update() else: msg_update("MACHINE WINS!!!") computer_update() elif p == "paper": if c == "rock": msg_update("PLAYER WINS!!!") player_update() elif c == "spock": msg_update("PLAYER WINS!!!") player_update() else: msg_update("MACHINE WINS!!!") computer_update() elif p == "scissors": if c == "paper": msg_update("PLAYER WINS!!!") player_update() elif c == "lizard": msg_update("PLAYER WINS!!!") player_update() else: msg_update("MACHINE WINS!!!") computer_update() elif p == "spock": if c == "scissors": msg_update("PLAYER WINS!!!") player_update() elif c == "rock": msg_update("PLAYER WINS!!!") player_update() else: msg_update("MACHINE WINS!!!") computer_update() elif p == "lizard": if c == "spock": msg_update("PLAYER WINS!!!") player_update() elif c == "paper": msg_update("PLAYER WINS!!!") player_update() else: msg_update("MACHINE WINS!!!") computer_update() else: pass def update_choice(msg): computer_choice = options[randint(0, 4)] if computer_choice == "rock": computer_label.configure(image=rock2) elif computer_choice == "paper": computer_label.configure(image=paper2) elif computer_choice == "scissors": computer_label.configure(image=scissor2) elif computer_choice == "spock": computer_label.configure(image=spock2) else: computer_label.configure(image=lizard2) if msg == "rock": player_label.configure(image=rock1) elif msg == "paper": player_label.configure(image=paper1) elif msg == "scissors": player_label.configure(image=scissor1) elif msg == "spock": player_label.configure(image=spock1) else: player_label.configure(image=lizard1) winner_check(msg, computer_choice) rock1_btn = Button(start_window, image=rock1, width=125, borderwidth=5, bg='#DA0037', height=125, command=lambda: update_choice("rock")) rock1_btn.grid(row=2, column=0, padx=(70, 0), pady=(50, 0)) rock2_btn = Button(start_window, image=rock2, width=125, borderwidth=5, bg='#150E56', height=125, ) rock2_btn.grid(row=2, column=10, pady=(50, 0)) paper1_btn = Button(start_window, image=paper1, width=125, borderwidth=5, bg='#DA0037', height=125, command=lambda: update_choice("paper")) paper1_btn.grid(row=4, column=0, padx=(70, 0)) paper2_btn = Button(start_window, image=paper2, width=125, borderwidth=5, bg='#150E56', height=125) paper2_btn.grid(row=4, column=10) scissor1_btn = Button(start_window, image=scissor1, width=125, borderwidth=5, bg='#DA0037', height=125, command=lambda: update_choice("scissors")) scissor1_btn.grid(row=6, column=0, padx=(70, 0)) scissor2_btn = Button(start_window, image=scissor2, width=125, borderwidth=5, bg='#150E56', height=125) scissor2_btn.grid(row=6, column=10) spock1_btn = Button(start_window, image=spock1, width=125, borderwidth=5, bg='#DA0037', height=125, command=lambda: update_choice("spock")) spock1_btn.grid(row=8, column=0, padx=(70, 0)) spock2_btn = Button(start_window, image=spock2, width=125, borderwidth=5, bg='#150E56', height=125) spock2_btn.grid(row=8, column=10) lizard1_btn = Button(start_window, image=lizard1, width=125, borderwidth=5, bg='#DA0037', height=125, command=lambda: update_choice("lizard")) lizard1_btn.grid(row=10, column=0, padx=(70, 0)) lizard2_btn = Button(start_window, image=lizard2, width=125, borderwidth=5, bg='#150E56', height=125) lizard2_btn.grid(row=10, column=10) player_label = Label(start_window, image=rock1, borderwidth=15, bg='#DA0037') player_label.grid(row=6, column=2, padx=(20, 200)) computer_label = Label(start_window, image=rock2, borderwidth=15, bg='#150E56') computer_label.grid(row=6, column=8, padx=(200, 20)) player_title = Label(start_window, text="PLAYER", font=("Arial Bold", 30), bg='#DA0037', fg='white', borderwidth=10) player_title.grid(row=2, column=2, padx=(30, 190)) computer_title = Label(start_window, text="MACHINE", font=("Arial Bold", 30), bg='#150E56', fg='white', borderwidth=10) computer_title.grid(row=2, column=8, padx=(150, 30)) player_score = Label(start_window, text="0", font=("Arial Bold", 50), bg='#DA0037', fg='white', borderwidth=10) player_score.grid(row=10, column=2, padx=(30, 190)) computer_score = Label(start_window, text="0", font=("Arial Bold", 50), bg='#150E56', fg='white', borderwidth=10) computer_score.grid(row=10, column=8, padx=(150, 30)) message = Label(start_window, text="RESULT PANEL", width=15, font=("Arial Bold", 25), bg='orange', fg='black', borderwidth=10) message.grid(row=6, column=5) def rules(): rules_window = Toplevel(window) rules_window.title("RULES OF THE GAME") rules_window.geometry('1990x900') rules_window.config(bg='#FFAA64') rules_text = Text(rules_window, height=20, width=50, bg='#FF8264', fg='black', font=("Arial Bold", 18)) rules_text.grid(padx=450, ipady=5, pady=(90, 5)) quote = """ EVALUATION BASIS: *Scissors cuts Paper *Paper covers Rock *Rock crushes Lizard *Lizard poisons Spock *Spock smashes Scissors *Scissors decapitates Lizard *Lizard eats Paper *Paper disproves Spock *Spock vaporizes Rock *Rock crushes Scissors *For each round first the player selects an action by clicking on any one of the Rock, Paper, Scissors, Lizard or Spock Button, after that the computer will randomly select an action and both will be evaluated. The winner gets a point. *The game ends when the player loses three times. """ rules_text.insert(END, quote) rules_text.config(state='disabled') start_btn1 = Button(rules_window, text="START", borderwidth=9, bg="black", font=("Arial Bold", 18), fg="#FFA900", command=start) start_btn1.grid() start_btn = Button(window, text="START", borderwidth=9, bg="black", fg="#FFA900", font=("Arial Bold", 18), command=start) start_btn.grid(row=4, padx=(100, 250)) rules_btn = Button(window, text="RULES", borderwidth=9, bg="black", fg="#FFA900", font=("Arial Bold", 18), command=rules) rules_btn.grid(row=4, padx=(250, 100)) window.mainloop()
42fdd37801f8ff633cf917b1acbb27572e087004
bushschool/IntroCS_MM
/SegregationModel.py
4,040
3.765625
4
import random def createOneRow(width): """ returns one row of zeros of width "width"... You should use this in your createBoard(width, height) function """ row = [] for col in range(width): row += [0] return row def createBoard(width, height): """ returns a 2d array with "height" rows and "width" cols """ A = [] for row in range(height): A += [createOneRow(width)] # What do you need to add a whole row here? return A def copy(A): height = len(A) width = len(A[0]) newA = createBoard(width,height) for col in range (width): for row in range(height): newA[row][col] = A[row][col] return newA def printBoard(A): for row in A: line = '' for col in row: line += str(col) print line def countNeighbors(row,col,A): total_count = 0 like_count = 0 for r in range(row-1,row+2): for c in range(col-1,col+2): if A[row][col] == A[r][c]: like_count += 1 if A[r][c] != ' ': total_count += 1 like_count -= 1 total_count -= 1 return [like_count,total_count] def emptyIndex(A): height = len(A) width = len(A[0]) emptylist = [] for row in range (height): for col in range (width): if A[row][col] == ' ': emptylist.append([row,col]) return emptylist def populateBoard(width,height,percA, percB): A = createBoard(width, height) numCells = width * height numA = int(percA*numCells) numB = int(percB*numCells) numEmpty = numCells -(numA + numB) population = numA*['A']+numB*['B']+numEmpty*[' '] population = random.sample(population,len(population)) i = 0 for row in range(height): for col in range(width): A[row][col]= population[i] i += 1 return A def next_life_generation(A, threshold): newA = copy(A) height = len(A) width = len(A[0]) emptyList = emptyIndex(A) i = 0 for row in range(1,height-1): for col in range(1,width-1): [like, total] = countNeighbors(row,col,A) # I added " and A[row][col] != ' ' " so that we do not move around empty spaces if float(like)/total < threshold and i < len(emptyList) and total > 0 and A[row][col] != ' ': newA[row][col] = ' ' #print "I moved" #print emptyList[i][0], emptyList[i][1] newA[emptyList[i][0]][emptyList[i][1]] = A[row][col] i += 1 static = (newA == A) return [static, A] def Segregation (A, thershold, percA, percB): newA = copy(A) height = len(A) width = len(A[0]) i = 0 <<<<<<< HEAD A = populateBoard(5,5,.4,.4) printBoard(A) for i in range(10): A = next_life_generation(A,0.5) printBoard(A) print " " ======= >>>>>>> origin/master def segregationIndex(A): """ takes in a matrix and returns a segregation index """ segregation = copy(A) segregationList = [] height = len(A) width = len(A[0]) for row in range(1,height-1): for col in range(1,width-1): if A[row][col] != ' ': [sameNeighbors, totalNeighbors] = countNeighbors(row,col,A) segregation[row][col] = float(sameNeighbors)/float(totalNeighbors) # I could make a heat map of segregation # put it into a list so we can easily take the average segregationList.append(segregation[row][col]) # take the average of the segregationIndex for each cell to get a single metric segregationIndex = sum(segregationList)/len(segregationList) return [segregation, segregationIndex] A = populateBoard(10,10,.3,.3) printBoard(A) print " " static = False i = 0 ''' while static == False and i<1000: [static, A] = next_life_generation(A,0.3) #printBoard(A) print " " i += 1 print i ''' [seg, segI] = segregationIndex(A) print segI
9bd4c7a2ad369669220c7f600529857bb8e758d7
weimengpu/LING165_SP16
/ngrams.py
1,470
3.71875
4
import random # (Aux) Pad sentences. -> DONE! # (1) Store n-gram tokens. # (2) Randomly generates a sentence. def pad(n, line): # e.g. # n = 3, the coffee is good # -> <s> <s> the coffee is good </s> out = '<s> ' * (n - 1) out += line.strip() out += ' </s>' return out def update_ngram_dictionary(n, line, d): # Incorporate ngrams from line into d. # 1. Pad the line. line = pad(n, line) # 2. Extract and store n-grams. words = line.split() for i in range(0, len(words) - (n - 1)): ngram = words[i: i + n] prefix = ' '.join(ngram[:-1]) # a string made of first n-1 words word = ngram[-1] # the last word if not prefix in d: d[prefix] = [] d[prefix].append(word) return d def gen(n, d): # Generate a random sentence. sent = [] prefix = '<s> ' * (n - 1) prefix = prefix.strip() last_word = '' while last_word != '</s>': word_list = d[prefix] last_word = random.choice(word_list) sent.append(last_word) ngram = prefix + ' ' + last_word suffix = ngram.split()[1:] prefix = ' '.join(suffix) sent = ' '.join(sent[:-1]) return sent if __name__ == '__main__': n = input('N-gram: ') d = {} f = open('bullshit.txt', 'r') for line in f: d = update_ngram_dictionary(n, line, d) f.close() for i in range(10): print str(i) + ') ' + gen(n, d)
91e4d05598cb27a723b4b4021557d9379d0f66fb
vijayrajanna/MachineLearning
/SVM/svm_author_id.py
1,252
3.578125
4
#!/usr/bin/python """ This is the code to accompany the Lesson 2 (SVM) mini-project. Use a SVM to identify emails from the Enron corpus by their authors: Sara has label 0 Chris has label 1 """ import sys from sklearn.svm import SVC from time import time sys.path.append("../tools/") from email_preprocess import preprocess rightclass = 0 def accuracy_score(listA, listB): global rightclass for index in range(0,len(listA)): if listA[index] == listB[index]: rightclass = rightclass +1 print rightclass print len(listA) return (float(rightclass)/len(listA))*100 ### features_train and features_test are the features for the training ### and testing datasets, respectively ### labels_train and labels_test are the corresponding item labels features_train, features_test, labels_train, labels_test = preprocess() svmClassifier = SVC(kernel="linear") # svmClassifier = SVC(kernel="rbf",C=0.5) svmClassifier.fit(features_train,labels_train) pred = svmClassifier.predict(features_test) acc = accuracy_score(pred, labels_test) print acc ######################################################### ### your code goes here ### #########################################################
e6554cb7da5994038f046920b30f30e59d9ab0f2
loweffortwizard/Python-Activities
/function/PyFunctions.py
311
3.578125
4
''' defining function for importing. allow progs to import the def ''' #def for squaring a number. def squareNumber(num): answer = num * num return answer #def for multiplication of vars (not defined) num1 and num2. def multiply(num1, num2): answer = num1 * num2 return answer
09e30953c7b9fd71d2fd2725b1fd471df4fa47e6
loweffortwizard/Python-Activities
/function/Pyfunctions2importpyf.py
648
4.0625
4
''' from file - PyFunctions.py def squareNumber(num): answer = num * num return answer def multiply(num1, num2): answer = num1 * num2 return answer ''' #importing expernal functions. import PyFunctions #getting first number form user. num1 = int(input("Please enter the number you wish to multiply: ")) #getting second number form user. num2 = int(input("Please enter the value you wish to multily by: ")) #getting result from inputs with use of external functions. answer = PyFunctions.multiply(num1, num2) #printing result of sum. print (str(num1) + " x " + str(num2) + " = " + str(answer) )
fc2aa8a79fe828d4d2c7c46524b194d7a347142c
loweffortwizard/Python-Activities
/exam/exammark.py
2,848
3.984375
4
import time import sys def wait(): time.sleep(1) #def to close prog def CloseProg(txt): txt.lower() if(txt!='y'): sys.exit() #prog to promp decision to end def UsersDecision(): userChoice = str(input("If you wish to use again, press \"Y\": ")) return userChoice def main(): while(True): #getting input examMark = int(input("Please enter your exam mark: ")) wait() #working out grade if (examMark >=0) and (examMark <= 19): #U print("You have earned a grade U") CloseProg(UsersDecision()) wait() #E elif(examMark >= 20) and (examMark <= 29): print("You have earned a grade E") CloseProg(UsersDecision()) wait() #D elif(examMark >= 30) and (examMark <= 46): print("You have earned a grade D") CloseProg(UsersDecision()) wait() #C elif(examMark >= 46) and (examMark <= 60): print("You have earned a grade C") CloseProg(UsersDecision()) wait() #B elif(examMark >= 60) and (examMark <= 76): print("You have earned a grade B") CloseProg(UsersDecision()) wait() #A elif(examMark >= 75) and (examMark <= 90): print("You have earned a grade A") CloseProg(UsersDecision()) wait() #A* elif(examMark > 90): print("You have earned a grade A*") CloseProg(UsersDecision()) wait() else: print("Error, please try again.") CloseProg(UsersDecision()) main() print("End.") ''' import sys def CloseProg(txt): txt.lower() if(txt!='y'): sys.exit() def UsersDecision(): userChoice = str(input("If you wish to use again, press \"Y\": ")) return userChoice while(True): examMark = int(input("Please enter your exam mark: ")) if (examMark >=0) and (examMark <= 19): print("You have earned a grade U") CloseProg(UsersDecision()) elif (examMark >=20) and (examMark <= 29): print("You have earned a grade E") CloseProg(UsersDecision()) elif (examMark >=30) and (examMark <= 45): print("You have earned a grade D") CloseProg(UsersDecision()) elif (examMark >=46) and (examMark <= 59): print("You have earned a grade C") CloseProg(UsersDecision()) elif (examMark >=60) and (examMark <= 75): print("You have earned a grade B") CloseProg(UsersDecision()) elif (examMark >=76) and (examMark <= 89): print("You have earned a grade A") CloseProg(UsersDecision()) elif (examMark >=90) and (examMark <= 100): print("You have earned a grade A*") CloseProg(UsersDecision()) else: print("You did not enter a valid exam mark.") CloseProg(UsersDecision()) '''
0adcd8285858ab6b5a8a22cb8d3de46619856757
eddyperea05/TT2
/punto10.py
262
3.84375
4
curso = {'Matemáticas': 6, 'Física': 4, 'Química': 5} totalcreditos = 0 for asignatura, credito in curso.items(): print(asignatura, 'tiene', credito, 'créditos') totalcreditos += credito print('Número total de créditos del curso: ', totalcreditos)
18a73e6c8cd9289ce5ba0fd1006dc2ce400e375f
LehlohonoloMopeli/level_0_coding_challenge
/task_3.py
350
4.1875
4
def hello(name): """ Description: Accepts the name of an individual and prints "Hello ..." where the ellipsis represents the name of the individual. type(output) : str """ if type(name) == str: result = print("Hello " + name + "!") return result else: return "Invalid input!"
0373aee2574c6a156e4f71e41fc9e070f2ed9261
myusuf3/dom
/domainr/core.py
2,017
3.546875
4
""" Core functionality for Domainr. """ from argparse import ArgumentParser import requests import simplejson as json from termcolor import colored class Domain(object): """Main class for interacting with the domains API.""" def environment(self): """Parse any command line arguments.""" parser = ArgumentParser() parser.add_argument('query', type=str, nargs='+', help="Your domain name query.") parser.add_argument('-i', '--info', action='store_true', help="Get information for a domain name.") args = parser.parse_args() return args def search(self, environment): """Use domainr to get information about domain names.""" if environment.info: url = "http://domai.nr/api/json/info" else: url = "http://domai.nr/api/json/search" query = " ".join(environment.query) json_data = requests.get(url, params={'q': query}) data = self.parse(json_data.content, environment.info) return data def parse(self, content, info): """Parse the relevant data from JSON.""" data = json.loads(content) if not info: # Then we're dealing with a domain name search. output = [] results = data['results'] for domain in results: name = domain['domain'] availability = domain['availability'] if availability == 'available': name = colored(name, 'blue', attrs=['bold']) symbol = colored(u"\u2713", 'green') else: symbol = colored(u"\u2717", 'red') string = "%s %s" % (symbol, name) output.append(string) return '\n'.join(output) # Then the user wants information on a domain name. return data def main(self): args = self.environment() print self.search(args)
302af6b0ab20d40f648327b77c11ee7766972d39
unfo/exercism-python
/word-count/word_count.py
276
3.75
4
def word_count(sentence): import re pat = re.compile('[^a-z0-9]+') words = [word for word in pat.split(sentence.lower()) if len(word) > 0] simple_freq = {} for word in words: simple_freq[word] = simple_freq[word] + 1 if word in simple_freq else 1 return simple_freq
aa013e73b5ad3308447c761634315efc67fe7ad4
unfo/exercism-python
/flatten-array/flatten_array.py
435
3.671875
4
import collections def _flatten(_in, depth): for item in _in: is_iterable = isinstance(item, collections.Iterable) is_string = isinstance(item, str) if is_iterable and not is_string: for _item in _flatten(item, depth+1): yield _item else: if item is not None: yield item def flatten(items): return [item for item in _flatten(items, 1)]
9d07cb1bbb8e780c193dbb19c6c0ef4b83cb7914
unfo/exercism-python
/bob/bob.py
723
4.25
4
def hey(sentence): """ Bob is a lackadaisical teenager. In conversation, his responses are very limited. Bob answers 'Sure.' if you ask him a question. He answers 'Whoa, chill out!' if you yell at him. He says 'Fine. Be that way!' if you address him without actually saying anything. He answers 'Whatever.' to anything else. """ sentence = sentence.strip() response = "Whatever." if len(sentence) == 0: response = "Fine. Be that way!" elif sentence.startswith("Let's"): # This is just silly. If it ends with an ! then it is shouting... response = "Whatever." elif sentence[-1] == "!" or sentence.isupper(): response = "Whoa, chill out!" elif sentence[-1] == "?": response = "Sure." return response
1276cd809f49a8752dd925822b93d94b3ae91362
unfo/exercism-python
/isogram/isogram.py
182
3.796875
4
def is_isogram(word): chars = list(word.lower()) chars.sort() prev = '' for char in chars: if char.isalpha(): if char == prev: return False prev = char return True
be97e8da8f3733fbb6c0a2e8abb0b950a11181c4
fitzcn/oojhs-code
/loops/printingThroughLoops.py
313
4.125
4
""" Below the first 12 numbers in the Fibonacci Sequence are declared in an array list (fibSeq). Part 1, Use a loop to print each of the 12 numbers. Part 2, use a loop to print each of the 12 numbers on the same line. """ fibSeq = ["1","1","2","3","5","8","13","21","34","55","89","144"] #part 1 #part 2
a48d3631cb3c12d91e9ebe2053e7c13fa21e5814
fitzcn/oojhs-code
/functions/functions1.py
310
4
4
def solveHW(r1,r2,dist): totalMPH = r1 + r2 time = dist/float(totalMPH) return time #print solveHW(550,650,2000) #print (solveHW(260,300,140)) def distance(r,t): d = r*t return d print (distance(5,10)) """ create a function called distance give it a rate and time return the distance traveled """
95c746698bc6bbadecdb49b57e7cc3aac5d387d5
fitzcn/oojhs-code
/apisamples/twitter/mytweets.py
3,754
3.59375
4
""" This code is from Thomas Sileo: http://thomassileo.com/blog/2013/01/25/using-twitter-rest-api-v1-dot-1-with-python/ A quick guide on how to retrieve your Twitter data with Python (from scripts/command line, without setting up a web server) and Twitter REST API v1.1. Requirements We will use requests along with requests-oauthlib. If you haven't heard about requests yet, it provides a pythonic way to make complex HTTP requests, and handles difficult tasks like authentication. Accessing Twitter API Here is the code, followed by the explanations: """ # -*- encoding: utf-8 -*- from __future__ import unicode_literals import requests from requests_oauthlib import OAuth1 from urlparse import parse_qs REQUEST_TOKEN_URL = "https://api.twitter.com/oauth/request_token" AUTHORIZE_URL = "https://api.twitter.com/oauth/authorize?oauth_token=" ACCESS_TOKEN_URL = "https://api.twitter.com/oauth/access_token" CONSUMER_KEY = "YOUR_CONSUMER_KEY" CONSUMER_SECRET = "YOUR CONSUMER_SECRET" OAUTH_TOKEN = "" OAUTH_TOKEN_SECRET = "" def setup_oauth(): """Authorize your app via identifier.""" # Request token oauth = OAuth1(CONSUMER_KEY, client_secret=CONSUMER_SECRET) r = requests.post(url=REQUEST_TOKEN_URL, auth=oauth) credentials = parse_qs(r.content) resource_owner_key = credentials.get('oauth_token')[0] resource_owner_secret = credentials.get('oauth_token_secret')[0] # Authorize authorize_url = AUTHORIZE_URL + resource_owner_key print 'Please go here and authorize: ' + authorize_url verifier = raw_input('Please input the verifier: ') oauth = OAuth1(CONSUMER_KEY, client_secret=CONSUMER_SECRET, resource_owner_key=resource_owner_key, resource_owner_secret=resource_owner_secret, verifier=verifier) # Finally, Obtain the Access Token r = requests.post(url=ACCESS_TOKEN_URL, auth=oauth) credentials = parse_qs(r.content) token = credentials.get('oauth_token')[0] secret = credentials.get('oauth_token_secret')[0] return token, secret def get_oauth(): oauth = OAuth1(CONSUMER_KEY, client_secret=CONSUMER_SECRET, resource_owner_key=OAUTH_TOKEN, resource_owner_secret=OAUTH_TOKEN_SECRET) return oauth if __name__ == "__main__": if not OAUTH_TOKEN: token, secret = setup_oauth() print "OAUTH_TOKEN: " + token print "OAUTH_TOKEN_SECRET: " + secret print else: oauth = get_oauth() r = requests.get(url="https://api.twitter.com/1.1/statuses/mentions_timeline.json", auth=oauth) print r.json() """ In order to access your own data, you must create an application, and generate your own access token, more informations on the Twitter API Getting Started. Go to https://dev.twitter.com/ and register a new appp, fill everything but leave the Callback URL empty if you want call the API without setting up a web server. The API will give us an URL to get an identifier, so we don't need callback. Save the consumer key and consumer secret, set the two constants at the top of mytweets.py: CONSUMER_KEY and CONSUMER_SECRET. Next to generate the OAUTH tokens, just run mytweets.py. $ sudo pip install request request_oauthlib $ wget https://gist.github.com/raw/4637864/9ea056ffbe5bb88705e95b786332ae4c0fd7554c/mytweets.py $ python mytweets.py Go to the URL, enter your identifier, set OAUTH_TOKEN and OAUTH_TOKEN_SECRET. Now you can run mytweets.py again. $ python mytweets.py Now, you should see your last mentions ! You can get the official Twitter REST API documentation here. Please don't hesitate to leave feedback, criticism, or to ask whatever questions you have. """
f946610b9b37543341bd0b8d27a809bd6102d383
BockeyE/LeetCodes
/leet/src/Q_1_10/Q7/Q7.py
961
3.609375
4
class Solution(object): def reverse(self, x): """ 执行用时 :20 ms, 在所有 Python 提交中击败了92.39%%的用户 内存消耗 :11.7 MB, 在所有 Python 提交中击败了25.38%的用户 """ if x >= 2147483647 or x <= (-2147483648): return 0 if x < 0: return -self.act(-x) else: return self.act(x) def act(self, x): print(x) ret = 0 while x != 0: pop = int(x % 10) x = int(x / 10) # //python3以后的代码,计算时都是精确计算,包括取余和除法 # 因此需要用到传统舍弃流计算时,需要对结果进行int转换, if ret > 214748364 or ((ret == 214748364) and (pop > 7)): return 0 ret = ret * 10 ret = ret + pop return ret if __name__ == '__main__': print(Solution().reverse(32414))