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
8b3ad6b46ad1693f72ac7e78e1cc3989889721b1
jan25/code_sorted
/leetcode/weekly163/1_shift_grid.py
568
3.71875
4
''' https://leetcode.com/contest/weekly-contest-163/problems/shift-2d-grid/ ''' class Solution: def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]: n, m = len(grid), len(grid[0]) r = [[] for _ in range(n)] k %= (n * m) # treat grid as a flattened array and figure the k rotated indices for i in range(n * m): j = (n * m + i - k) % (n * m) x, y = j // m, j % m rx = i // m r[rx].append(grid[x][y]) return r
aa3d6c986bdff216acbb1b913f2e35e8c5f21dc5
jan25/code_sorted
/leetcode/weekly168/3_max_occ_of_substrs.py
575
3.515625
4
''' https://leetcode.com/contest/weekly-contest-168/problems/maximum-number-of-occurrences-of-a-substring/ ''' class Solution: def maxFreq(self, s: str, maxLetters: int, minSize: int, maxSize: int) -> int: max_c = 0 c = {} for i in range(0, len(s) - minSize + 1): current_s = s[i:i + minSize] if len(set(current_s)) > maxLetters: continue if current_s not in c: c[current_s] = 0 c[current_s] += 1 max_c = max(max_c, c[current_s]) return max_c
834279e8959ee912ec3d142366c7f3f80f21176d
jan25/code_sorted
/leetcode/weekly163/3_sum_divisible_threes.py
1,210
3.625
4
''' https://leetcode.com/contest/weekly-contest-163/problems/greatest-sum-divisible-by-three/ ''' class Solution: def maxSumDivThree(self, nums: List[int]) -> int: # put nums into sorted remainder buckets b = [[] for _ in range(3)] nums.sort() for n in nums: b[n % 3].append(n) # combine remainder=2's list and remainder=1's list independently def be_smart(a, b): s = 0 while len(a) >= 3: s += sum(a.pop() for _ in range(3)) while len(b) >= 3: s += sum(b.pop() for _ in range(3)) while len(a) > 0 and len(b) > 0: s += a.pop() + b.pop() return s # handle corner case # mix one or two from remainder=2's list with remainder=1's list l1, l2 = b[1], b[2] s1 = 0 if len(l1) > 0 and len(l2) > 0: s1 = l1[-1] + l2[-1] + be_smart(l1[:-1], l2[:-1]) s2 = 0 if len(l1) > 1 and len(l2) > 1: s2 = sum(l1[-2:] + l2[-2:]) + be_smart(l1[:-2], l2[:-2]) maxs = sum(b[0]) maxs += max(s1, s2, be_smart(l1, l2)) return maxs
231ba12d25aa243173c4122fcc9f158f75f9547a
jan25/code_sorted
/leetcode/weekly177/2_validate_binary_tree.py
536
3.546875
4
''' https://leetcode.com/contest/weekly-contest-177/problems/validate-binary-tree-nodes/ ''' class Solution: def validateBinaryTreeNodes(self, n: int, leftChild: List[int], rightChild: List[int]) -> bool: seen = set() edges = 0 for i in range(n): l, r = leftChild[i], rightChild[i] if l in seen or r in seen: return False if l != -1: seen.add(l); edges += 1 if r != -1: seen.add(r); edges += 1 return edges == n - 1
364f8f81f838ccb1995a2908200c18c6da85bcfd
jan25/code_sorted
/leetcode/weekly181/3_grid_roads.py
1,727
3.71875
4
''' https://leetcode.com/contest/weekly-contest-181/problems/check-if-there-is-a-valid-path-in-a-grid/ DFS algorithm with checks of possible previous cells for a currently visiting cell ''' class Solution: def hasValidPath(self, grid: List[List[int]]) -> bool: pre = [None, (0, -1), (-1, 0), (0, -1), (0, 1), (0, -1), (0, 1)] nex = [None, (0, 1), (1, 0), (1, 0), (1, 0), (-1, 0), (-1, 0)] n, m = len(grid), len(grid[0]) seen = set() def invalid_prev(x, y, px, py): c = grid[x][y] xp, yp = x + pre[c][0], y + pre[c][1] valid = xp == px and yp == py if valid: return 1 xp, yp = x + nex[c][0], y + nex[c][1] valid = xp == px and yp == py if valid: return 2 return 0 def get_next(x, y, rev_prev): if rev_prev == 1: return x + nex[grid[x][y]][0], y + nex[grid[x][y]][1] if rev_prev == 2: return x + pre[grid[x][y]][0], y + pre[grid[x][y]][1] def invalid_pos(x, y): return x < 0 or y < 0 or x >= n or y >= m def dfs(x, y, px, py): if invalid_pos(x, y): return False if (x, y) in seen: return False rev_prev = invalid_prev(x, y, px, py) if rev_prev == 0: return False if x == n - 1 and y == m - 1: return True seen.add((x, y)) nx, ny = get_next(x, y, rev_prev) return dfs(nx, ny, x, y) valid = False for d in [(-1, 0), (0, -1), (1, 0), (0, 1)]: seen = set() valid = valid or dfs(0, 0, *d) return valid
f673b24e2d34cb1d5b66db2c69460b4f40c9f470
jan25/code_sorted
/leetcode/weekly173/1_remove_subseq_palins.py
256
3.71875
4
''' https://leetcode.com/contest/weekly-contest-173/problems/remove-palindromic-subsequences/ ''' class Solution: def removePalindromeSub(self, s: str) -> int: if len(s) == 0: return 0 if s == s[::-1]: return 1 return 2
569b78a242c30db15beb7a6d3ab018058091824e
jan25/code_sorted
/leetcode/weekly155/1_abs_diff.py
416
3.765625
4
''' https://leetcode.com/contest/weekly-contest-155/problems/minimum-absolute-difference/ ''' class Solution: def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]: arr.sort() min_diff = 10**7 for i in range(1, len(arr)): min_diff = min(min_diff, arr[i] - arr[i - 1]) sarr = set(arr) return [[a, a + min_diff] for a in arr if a + min_diff in sarr]
d8fbbe107348901260e321b8b3872c4a0a88000f
jan25/code_sorted
/leetcode/weekly175/3_tweets_freq.py
1,642
3.53125
4
''' https://leetcode.com/contest/weekly-contest-175/problems/tweet-counts-per-frequency/ This is still unaccepted. No ideas whats wrong :( ''' from collections import defaultdict class TweetCounts: def __init__(self): self.per_min = {} self.per_sec = {} def recordTweet(self, tweetName: str, time: int) -> None: if tweetName not in self.per_sec: self.per_min[tweetName] = defaultdict(int) self.per_sec[tweetName] = defaultdict(int) self.per_sec[tweetName][time] += 1 for i in range(60): self.per_min[tweetName][time - i] += 1 def get_per_min(self, s, e, t): pm, ps = self.per_min[t], self.per_sec[t] per_min = [] while s + 60 <= e: per_min.append(pm[s]) s += 60 last_min = 0 while s <= e: last_min += ps[s] s += 1 per_min.append(last_min) pm, ps = None, None return [*per_min] def getTweetCountsPerFrequency(self, freq: str, tweetName: str, startTime: int, endTime: int) -> List[int]: print(freq, startTime, endTime) pm = self.get_per_min(startTime, endTime, tweetName) if freq == 'minute': return [*pm] if freq == 'day': return [sum(pm)] # see range of startTime, endTime inputs # handle hour freq return [sum(pm[i:60]) for i in range(0, len(pm), 60)] # Your TweetCounts object will be instantiated and called as such: # obj = TweetCounts() # obj.recordTweet(tweetName,time) # param_2 = obj.getTweetCountsPerFrequency(freq,tweetName,startTime,endTime)
3044dfccbf45b7ec5c743786e7e562e8ce641ae3
jan25/code_sorted
/leetcode/weekly181/3_longest_prefix_suffix.py
661
3.609375
4
''' https://leetcode.com/contest/weekly-contest-181/problems/longest-happy-prefix/ Algorithm: Construct longest prefix length for every possible string s[:i] This same prefix length array is used in KMP algorithm for pattern matching ''' class Solution: def longestPrefix(self, s: str) -> str: pre, j = [0], 0 for i in range(1, len(s)): if s[i] == s[j]: j += 1 pre.append(j) else: while j - 1 >= 0 and s[j] != s[i]: j = pre[j - 1] if s[i] == s[j]: j += 1 pre.append(j) return s[:pre[-1]]
bfcefba16f48ec16e1da8f15169a4e4a7acd374e
7dongyuxiaotang/python_code
/study_7_20.py
1,290
3.921875
4
# 先定义类 驼峰体 class Student: # 1、变量的定义 stu_school = 'PUBG' def __init__(self, name, age, gender, course): self.stu_name = name self.stu_age = age self.stu_gender = gender self.sut_course = course # 2、 功能的定义 def tell_stu_info(self): pass def set_info(self): pass def choose(self, course): self.sut_course = course # print(stu_school) # #1、访问数据属性 # print(Student.stu_school) # #2、访问函数属性 # print(Student.tell_stu_info(11)) # def init(obj, name, age, gender): # obj.stu_name = name # obj.stu_age = age # obj.stu_gender = gender # # # stu1 = Student() # init(stu1, 'egon', 18, 'male') # # print(stu1.__dict__) # stu1 = Student() # stu1.stu_name = '张三' # print(stu1.__dict__) # 解决方案二: obj1 = Student('egon', 18, 'male', '') obj2 = Student('lili', 18, 'female', '') obj3 = Student('dsb', 18, 'male', '') # print(obj1.__dict__) # print(id(obj1.stu_school)) # print(id(obj2.stu_school)) # print(id(obj3.stu_school)) # Student.stu_school = 'white cloud' # obj1.stu_school = 'white cloud' # print(obj1.stu_school) # print(Student.stu_school) # print(obj2.stu_school) obj1.choose('python') print(obj1.__dict__)
ecfec28ffd3b8e077a17af891e74133455c5548a
7dongyuxiaotang/python_code
/study_5_29.py
2,517
3.6875
4
# x = 10 # y = x # z = x # del x # 解除变量名x与值10的绑定关系,10的引用计数变为2 # # print(x) # print(y) # print(z) # # z=1324 再次赋值也可以使得引用计数减少 # 命名风格: # 1. 纯小写加下划线 # age_of_alex = 73 # print(age_of_alex) # # 2. 驼峰体 # AgeOfAlex = 73 # print(AgeOfAlex) # 变量值三个重要特征 # name ='GPNU' # id:反映的是变量值的内存地址,内存地址不同id则不同 # print(id(name)) # type:不同类型的值用来表示不同的状态 # print(type(name)) # value:变量本身 # print(name) # is 与 == # is 比较左右两边变量id是否相等 # x = 'YUE' # y = 'YUE' # print(id(x), id(y)) # print(x == y) # 小整数池:从python解释器启动那一刻开始,就会在内存中事先申请好一系列内存空间存放好常用的整数 # n = 10 # m = 10 # ret = 4+6 # print(id(n)) # print(id(m)) # print(id(ret)) # n = 156398235658 # m = 156398235658 # print(id(n)) # print(id(m)) # 注意:python语法中没有常量的概念,但是在程序的开发过程中会涉及到常量的概念 # AGE_OF_ALEX = 73 小写字母全为大写代表常量,这只是一个约定、规范 # age=18 # print(type(age)) # weight=55.3 # print(type(weight)) # name="赛利亚" # name2='赛利亚' # name3='''赛利亚''' # print(type(name)) # print(type(name2)) # print(type(name3)) # print(name) # print(name2) # print(name3) # 字符串的嵌套,注意:外层用单引号 \ 双引号,内层用双引号 \ 单引号 # print('my name is"sailiya"') # print("my name is'sailiya'") # x = "my name is " # y = "赛利亚" # print(x+y) # print(id(x)) # print(id(y)) # print(id(x+y)) # print('='*20) # print("hallo world") # print('='*20) # 列表:索引对应值,索引从0开始,0代表第一个 # 作用:记录多个值,并且可以按照索引取指定位置的值 # 定义:在[]内用逗号分割开多个任意类型的值,一个值称之为一个元素 # l=[10,3.1,'aaa',["aaa","bbb"],"ccc"] # print(l[3][0]) # print(l[-1]) #字典 # key对应值,其中key通常为字符串类型,所以key对值可以有描述性的功能 # 作用:用来存多个值,每一个值都有唯一一个key与其对应。 # 定义:在{ }内用逗号分开各多个key:value # d={'a':1 , 'b':2,'c':6} # print(d['c']) # student_info=[ # {"name":"张三","age":19,"sex":"男"}, # {"name":"李四","age":20,"sex":"女"}, # {"name":"王五","age":39,"sex":"保密"} # ] # print(student_info[2]["sex"])
9b1c1c56bdd3f47af1d3e818c85ef9601180904a
7dongyuxiaotang/python_code
/study_7_23.py
1,687
4.21875
4
# class Parent1(object): # x = 1111 # # # class Parent2(object): # pass # # # class Sub1(Parent1): # 单继承 # pass # # # class Sub2(Parent1, Parent2): # 多继承 # pass # # # print(Sub1.x) # print(Sub1.__bases__) # print(Sub2.__bases__) # ps:在python2中有经典类与新式类之分 # 新式类:继承了object类的子类,以及该子类的子类 # 经典:没有继承object类的子类,以及该子类的子类 # ps:在python3中没有继承任何类,默认继承object类 # 所以python3中所有类都是新式类 # class School: # school = '广东技术师范大学' # # def __init__(self, name, age, gender): # self.name = name # self.age = age # self.gender = gender # # # class Student(School): # # def choose_course(self): # print('%s 正在选课' % self.name) # # # class Teacher(School): # # def __init__(self, name, age, gender, salary, level): # School.__init__(self, name, age, gender) # self.salary = salary # self.level = level # # def score(self): # print('%s老师 正在给学生打分' % self.name) # class Foo: # # def __f1(self): # print('foo.f1') # # def f2(self): # print('foo.f2') # self.__f1() # # # class Bar(Foo): # # def f1(self): # print('bar.f1') # # # obj = Bar() # # obj.f2() class A: def test(self): print('from A') class B(A): def test(self): print('from B') class C(A): def test(self): print('from C') class D(B, C): pass print(D.mro()) # 类以及该类的对象访问属性都是参照该类的mro列表 # obj = D() # obj.test()
814efde818fa56515e26396b7b9725543c5a2b05
Steven71111/Steven-s-Assignment4
/mapper.py
235
3.921875
4
#!/usr/bin/env python import sys for num in sys.stdin: num = int(num.strip()) if (num % 2) == 0: # num is even print("%s\t%s") % ("even", 1) else: # num is odd print("%s\t%s") % ("odd", 1)
e8ae0804c720e867b918992acf03bb7eafd6946f
falondarville/practicePython
/element.py
552
4.09375
4
# Write a function that takes an ordered list of numbers (a list where the elements are in order from smallest to largest) and another number. The function decides whether or not the given number is inside the list and returns (then prints) an appropriate boolean. items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] def check_items(l, i): if i in l: return True else: return False # returns True print(check_items(items, 3)) # returns Falso print(check_items(items, 20)) # return False because it is also type checking print(check_items(items, "3"))
3a281cfcad8aa72dc92fdec8b84fcd1b553b5f36
falondarville/practicePython
/listComprehension.py
217
3.890625
4
# Write one line of Python that takes this list a and makes a new list that has only the even elements of this list in it. a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] evens = [n for n in a if n % 2 == 0] print(evens)
57813ddd83679b08db0ca6b7d29ad27d25e32252
falondarville/practicePython
/birthday_dictionary/months.py
495
4.5625
5
# In the previous exercise we saved information about famous scientists’ names and birthdays to disk. In this exercise, load that JSON file from disk, extract the months of all the birthdays, and count how many scientists have a birthday in each month. import json from collections import Counter with open("info.json", "r") as f: info = json.load(f) # print the months, which will be added to a list for each in info["birthdays"]: birthday_month = each["month"] print(birthday_month)
9b505fd7c9d15fedb84b90c9c8443e791d8a9e61
falondarville/practicePython
/birthday_dictionary/json_bday.py
696
4.46875
4
# In the previous exercise we created a dictionary of famous scientists’ birthdays. In this exercise, modify your program from Part 1 to load the birthday dictionary from a JSON file on disk, rather than having the dictionary defined in the program. import json with open("info.json", "r") as f: info = json.load(f) print('Welcome to the birthday dictionary. We know the birthdays of:') for each in info["birthdays"]: print(each["name"]) print('Whose birthday do you want to know?') query = str(input()) print(f'You want to know the birthday of {query}.') for i in info["birthdays"]: if i["name"] == query: birthday = i["birthday"] print(f"{query}'s birthday is on {birthday}")
4e0ee7b43407043bf7a5bdb394be9c728833eb63
KrisNguyen135/Project-Euler
/solutions/p527.py
1,595
3.578125
4
from timeit import default_timer as timer from math import log def B(n): def recur_B(n): if n in result: return result[n] temp_result = 1 index1 = (n + 1) // 2 - 1 index2 = n - (n + 1) // 2 temp_result += (index1 * recur_B(index1) + index2 * recur_B(index2)) / n result[n] = temp_result return temp_result result = {0: 0, 1: 1} return recur_B(n) def R(n): '''temp_result = sum(i / (i + 1) / (i + 2) for i in range(1, n)) return 1 + 2 * (n + 1) * temp_result / n''' running_sum = 0 for i in range(1, n): #print(i) running_sum += i / (i + 1) / (i + 2) return 1 + 2 * (n + 1) * running_sum / n def R_v2(n): running_sum = 0 for i in range(3, n + 1): #print(i) running_sum += 1 / i running_sum = 2 / (n + 1) + running_sum - 1 / 2 return 1 + 2 * (n + 1) * running_sum / n def R_v3(n): running_sum = log(n) - 1.5 + 0.5772156649 + 1 / 2 / n return 3 / n + 2 * (n + 1) * running_sum / n if __name__ == '__main__': '''target = 10000000000 print('Computing R...') #r = R(target) r = R_v2(target) print('Computing B...') b = B(target) print('Final result:', r - b) print('Done.')''' '''for i in range(1000, 1010): print(R(i), R_v2(i), R_v3(i))''' '''target = 1000000 start = timer() result = R(target) print(timer() - start) start = timer() result = R_v2(target) print(timer() - start)''' target = 10000000000 r = R_v3(target) b = B(target) print(r - b)
66c5df684ff9f63f89daeb61bc8a84c9dd483cc2
SGNetworksIndia/J.A.R.V.I.S
/software/non_ai/greet_startup.py
566
3.75
4
from datetime import datetime ''' initiate greeting sequence to be played on jarvis startup ''' def greet(): greet_text = "" hour = int(datetime.now().hour) if hour >= 0 and hour < 12: greet_text = "Good Morning Sir. " elif hour >= 12 and hour < 18: greet_text = "Good Afternoon Sir. " else: greet_text = "Good Evening Sir. " if hour > 12: greet_text += "It's " + str(hour - 12) + " " + str(datetime.now().minute) + " PM " + " now." else: greet_text += "It's " + str(hour) + " " + str(datetime.now().minute) + " AM " + " now." return greet_text
c931dd02e26c57930e28b4925088cf7b3a7e301c
deepwzh/leetcode_practice
/8.py
1,017
3.5625
4
""" 思路:总体思路是通过正则匹配把源字符串分为三部分 比如字符串" abc1.23eee" 第一部分是" abc", 第二部分是"1",第三部分是".23eee" 对于第一部分,如果忽略前导空格后仍然包含乱起八糟的字符,则根据题意我们应该返回0 对于第二部分,需要注意的是为空时或者越界时返回0,另外,我们需要结合第一部分判断正负 对于第三部分,直接忽略即可 详细代码如下 """ class Solution: def myAtoi(self, str): """ :type str: str :rtype: int """ a,b,c = re.match("([^0-9]+)?([0-9]+)?([^0-9]+)?", str.lstrip(' ')).groups() if not b: return 0 if not a: b = int(b) elif a == '-': b = -int(b) elif a == '+': b = int(b) else: return 0 if b < -2147483648: return -2147483648 elif b > 2147483647: return 2147483647 return b
31e740f1b79e7be85fc5fb29ec52208cb9ae8bd6
deepwzh/leetcode_practice
/36.py
1,224
3.828125
4
class Solution: def __init__(self): self.board = None def validate_board(self, r, c, w): for i in range(w): u1 = dict() u2 = dict() for j in range(w): if self.board[i][j] == '.' or self.board[i][j] not in u1: u1[self.board[i][j]] = True else: return False if self.board[j][i] == '.' or self.board[j][i] not in u2: u2[self.board[j][i]] = True else: return False for i in range(9): u = dict() c0 = i % 3 * 3 r0 = i // 3 * 3 for j in range(9): r = j //3 + r0 c = j % 3 + c0 if self.board[r][c] == '.' or self.board[r][c] not in u: u[self.board[r][c]] = True else: return False return True def isValidSudoku(self, board): """ :type board: List[List[str]] :rtype: bool """ self.board = board for i in board: print(i) return self.validate_board(0,0,9)
4164b823de5962f4b1e9958aec6908fb537b0e6a
deepwzh/leetcode_practice
/142.py
824
3.703125
4
""" 快慢指针,证明详见百度 """ # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def detectCycle(self, head): """ :type head: ListNode :rtype: ListNode """ high = head low = head p = None while low and high: low = low.next high = high.next if not high: return None high = high.next if high == low: p = low break if not p: return None res = head while p != None: if res == p: return res res = res.next p = p.next return None
4042c26ff9de43ff3eb90f8c3c7fe3bf4e5ab59a
romainjayles/GAC_solver
/parser.py
1,814
3.578125
4
#! /usr/bin/python # -*- coding:utf-8 -*- import vertex class Parser: """ Allow to parse a path file """ def __init__(self, input_file): self.input_file = input_file self.vertex_list = [] self.number_of_verticle = None self.number_of_edge = None self.min_y = 0 self.max_y = 0 self.min_x = 0 self.max_x = 0 def parse(self): in_file = open(self.input_file, "r") first_couple = map(int, in_file.readline().split()) node_dictionnary = {} self.number_of_verticle = first_couple[0] self.number_of_edge = first_couple[1] print "Verticle" for i in range(0, self.number_of_verticle): parsed_line = map(float, in_file.readline().split()) vertex_id = parsed_line[0] vertex_x = parsed_line[1] vertex_y = parsed_line[2] self.max_x = vertex_x if vertex_x > self.max_x else self.max_x self.max_y = vertex_y if vertex_y > self.max_y else self.max_y self.min_x = vertex_x if vertex_x < self.min_x else self.min_x self.min_y = vertex_y if vertex_y < self.min_y else self.min_y vertex_instance = vertex.Vertex(vertex_id, vertex_x, vertex_y) node_dictionnary[vertex_id] = vertex_instance self.vertex_list.append(vertex_instance) print "Edge" for i in range(0, self.number_of_edge): edge = map(int,in_file.readline().split()) node_dictionnary[edge[0]].add_child(node_dictionnary[edge[1]]) return self.vertex_list def clear_list(self, list): return_list = [] for member in list: for sub_member in member: return_list.append(sub_member) return return_list def coordinate_string_to_array(self, coordinate_string): coordinate_string = coordinate_string[1:-1] coordinate_string = coordinate_string.split(',') return_coordinate = [] for item in coordinate_string: return_coordinate.append(int(item)) return return_coordinate
4f24d9446df29b4d6cbdca225764559bb6dfbc29
rymo90/kattis
/mixedfractions.py
314
3.703125
4
while True: numerator, denominator = map(int, input().split()) if numerator == 0 and denominator == 0: break else: holenum= numerator//denominator reminder= numerator%denominator mixFraction= str(reminder) + " / " + str(denominator) print(holenum, mixFraction)
a6208f4a6e4ea3d39dc1736bdf992fe26f309038
rymo90/kattis
/estimatingtheareaofacircle.py
292
3.609375
4
import math stop = False while not stop: r, m, c = map(float, input().split()) if r == 0 and m == 0 and c == 0: stop = True else: areaOne = math.pi * math.pow(r, 2) temp = (c / m) areaTwo = temp * math.pow(2 * r, 2) print(areaOne, areaTwo)
0252fdb9ed126aee248d59471c21f4c92763b6d4
rymo90/kattis
/stopwatch.py
309
3.546875
4
n = int(input()) suma= 0 fore = 0 if (n%2 == 0): i=0 while i < n: temp=int(input()) if i== 0: fore = temp else: suma =abs(fore-temp) fore = suma # print(fore,temp,i) i+=1 print(suma) else: print("still running")
990801ee689ee9f61e310c63be18e2eb57c472b0
rymo90/kattis
/greetings2.py
149
3.5
4
g = input() num = 0 s= "e" for _ in range(len(g)): if g[_] == "e": num += 1 sv = "".join([char*(num*2) for char in s]) print("h"+sv+"y")
aa7ea8fc5291d423e6e13a27a717661ae8d8965e
the-strawman/cspath-datastructures-capstone-project
/Soho-Restaurants-master/script.py
4,457
4.25
4
from trie import Trie from data import * from welcome import * from hashmap import HashMap from linkedlist import LinkedList # Printing the Welcome Message print_welcome() # Entering cuisine data food_types = Trie() eateries = HashMap(len(types)) for food in types: food_types.add(food) eateries.assign(food, LinkedList()) # restaurant data-point key names: eatery_cuisine = "cuisine" eatery_name = "name" eatery_price = "price" eatery_rating = "rating" eatery_address = "address" # Entering restaurant data for restaurant in restaurant_data: current_eateries_for_cuisine = eateries.retrieve(restaurant[0]) current_eatery_data = HashMap(len(restaurant)) current_eatery_data.assign(eatery_cuisine, restaurant[0]) current_eatery_data.assign(eatery_name, restaurant[1]) current_eatery_data.assign(eatery_price, restaurant[2]) current_eatery_data.assign(eatery_rating, restaurant[3]) current_eatery_data.assign(eatery_address, restaurant[4]) if current_eateries_for_cuisine.get_head_node().get_value() is None: current_eateries_for_cuisine.get_head_node().value = current_eatery_data else: current_eateries_for_cuisine.insert_beginning(current_eatery_data) # Begin user interaction logic quit_code = "quit!" def quit_sequence(): print("\nThanks for using SoHo Restaurants!") exit() intro_text = """ What type of food would you like to eat? Type that food type (or the beginning of that food type) and press enter to see if it's here. (Type \"{0}\" at any point to exit.) """.format(quit_code) partial_match_text = """ Type a number to select a corresponding cuisine. Or type the beginning of your preferred cuisine to narrow down the options. """ while True: # What cuisine are we looking for? user_input = str(input(intro_text)).lower() if user_input == quit_code: quit_sequence() # First try a full-text match my_cuisine = food_types.get(user_input) if not my_cuisine: print("Couldn't find \"{0}\".".format(user_input.title())) # if no match on full-text search, try prefix search while not my_cuisine: available_cuisines = food_types.find(user_input) if not available_cuisines: # a prefix search found nothing, so return the whole list of available cuisines available_cuisines = food_types.find("") print("Here is the list of available cuisines:\n") else: print("Here are some matches from the available cuisines:\n") idx = 0 for cuisine in available_cuisines: idx += 1 print("{0} - {1}".format(idx, cuisine.title())) available_cuisines_response = input(partial_match_text) if available_cuisines_response == quit_code: quit_sequence() # the user input could be an int or a str. # try to process an int value, a ValueError exception indicates non-int input try: idx = int(available_cuisines_response) - 1 print("Search for {0} restaurants?".format(available_cuisines[idx].title())) user_response = str(input("(Hit [enter]/[return] for 'yes'; type 'no' to perform a new search.) ")).lower() if user_response == quit_code: quit_sequence() elif user_response in ["", "y", "yes", "[enter]", "[return]", "enter", "return"]: my_cuisine = available_cuisines[idx] else: user_input = None except ValueError: available_cuisines_response = str(available_cuisines_response).lower() my_cuisine = food_types.get(available_cuisines_response) if not my_cuisine: user_input = available_cuisines_response # Now we have a cuisine, let's retrieve the restaurants & present the data my_eateries = eateries.retrieve(my_cuisine) current_node = my_eateries.get_head_node() print("\n{} restauants in SoHo".format(my_cuisine.title())) print("-"*20) while current_node: eatery = current_node.get_value() print('{:<14}{}'.format("Restaurant:", eatery.retrieve(eatery_name))) print("{:<14}{}".format("Price:", "$" * int(eatery.retrieve(eatery_price)))) print("{:<14}{}".format("Rating:", "*" * int(eatery.retrieve(eatery_rating)))) print("{:<14}{}".format("Address:", eatery.retrieve(eatery_address))) print("-"*20) current_node = current_node.get_next_node() user_response = str(input("\nWould you like to look for restaurants matching a different cuisine? ")).lower() if user_response in ["n", "no", "q", "quit", "x", "exit", quit_code]: quit_sequence()
61234f3e7b500aeec9bcca947e9931514b0e793f
UndedInside/CodeExamples
/python/userInput.py
128
4
4
name = input("What is your name? ") if name == "Unded": print("Hello", name) else: print("Nice to meet you", name)
03515f7e841491e5a4679790eca1259a8c9bc083
zzy1120716/cs224n-zzy
/python-review/01-language-basics.py
3,949
3.875
4
def QuickSort(arr): if len(arr) <= 1: return arr pivot = arr[len(arr) // 2] left = [x for x in arr if x < pivot] middle = [x for x in arr if x == pivot] right = [x for x in arr if x > pivot] return QuickSort(left) + middle + QuickSort(right) # Brackets --> Indents def fib(n): # Indent level 1: function body if n <= 1: # Indent level 2: if statement body return 1 else: # Indent level 2: else statement body return fib(n - 1) + fib(n - 2) # Classes class Animal(object): def __init__(self, species, age): # Constructor 'a = Animal('bird', 10)' self.species = species # Refer to instance with 'self' self.age = age # All instance variables are public def isPerson(self): # Invoked with 'a.isPerson()' return self.species == "Homo Sapiens" def ageOneYear(self): self.age += 1 class Dog(Animal): # Inherits Animal's methods def ageOneYear(self): # Override for dog years self.age += 7 if __name__ == '__main__': print(QuickSort([3, 6, 8, 10, 1, 2, 1])) x = 10 # Declaring two integer variables y = 3 # Comments start with the hash symbol print(x + y) # Addition print(x - y) # Subtraction print(x ** y) # Exponentiation print(x // y) # Dividing two integers print(x / float(y)) # Type casting for float division print(str(x) + " + " + str(y)) # Casting and string concatenation print(fib(10)) # List Slicing numbers = [0, 1, 2, 3, 4, 5, 6] print(numbers[0:3]) print(numbers[:3]) print(numbers[5:]) print(numbers[5:7]) print(numbers[:]) print(numbers[-1]) # Negative index wraps around print(numbers[-3:]) print(numbers[3:-2]) # Can mix and match # Collections: Tuple names = ('Zach', 'Jay') # Note the parentheses names[0] == 'Zach' print(len(names) == 2) print(names) # names[0] = 'Richard' # Error empty = tuple() # Empty tuple single = (10,) # Single-element tuple. Comma matters! # Collections: Dictionary phonebook = dict() # Empty dictionary phonebook = {'Zach': '12 - 37'} # Dictionary with one item phonebook['Jay'] = '34 - 23' # Add another item print('Zach' in phonebook) print('Kevin' in phonebook) print(phonebook['Jay']) del phonebook['Zach'] # Delete an item print(phonebook) for name, number in phonebook.items(): print(name, number) # Loops for name in ['Zack', 'Jay', 'Richard']: print('Hi ' + name + '!') while True: print('We\'re stuck in a loop...') break # Break out of the while loop # Loops (cont'd) for i in range(10): # Want an index also? print('Line ' + str(i)) # Look at enumerate()! for idx, ele in enumerate([3, 4, 5]): print(str(idx) + ':' + str(ele)) # Looping over a list, unpacking tuples: for x, y in [(1, 10), (2, 20), (3, 30)]: print(x, y) # Classes a = Animal('bird', 10) print(a.isPerson()) print(a.age) a.ageOneYear() print(a.age) d = Dog('ben', 10) print(d.isPerson()) print(d.age) d.ageOneYear() print(d.age) # Importing Modules # Import 'os' and 'time' modules import os, time # Import under an alias import numpy as np print(np.dot(x, y)) # Access components with pkg.fn # Import specific submodules/functions from numpy import linalg as la, dot as matrix_multiply # Not really recommended b/c namespace collisions... # Iterables (cont'd) names = set(['Zack', 'Jay']) # print(names[0]) # TypeError: 'set' object does not support indexing print(len(names) == 2) print(names) names.add('Jay') print(names) # Ignored duplicate empty = set() # Empty set
5a63f6c803542ae7402e2e73ec4489b81f4a63fc
Tems-git/Python_advanced
/tuples_and_sets/02_students'_grades.py
1,355
3.8125
4
n = int(input()) students = {} for i in range(n): command = tuple(input().split()) name, grade = command grade = grade.format() if name not in students: students[name] = [] students[name].append(float(grade)) for key, value in students.items(): value_as_str = ["{:.2f}".format(x) for x in value] print(f"{key} -> {' '.join(value_as_str)} (avg: {sum(value) / len(value):.2f})") # v.2 import sys from io import StringIO from statistics import mean from time import time test_input1 = '''7 Peter 5.20 Mark 5.50 Peter 3.20 Mark 2.50 Alex 2.00 Mark 3.46 Alex 3.00 ''' test_input2 = '''4 Scott 4.50 Ted 3.00 Scott 5.00 Ted 3.66 ''' test_input3 = '''5 Lee 6.00 Lee 5.50 Lee 6.00 Peter 4.40 Kenny 3.30 ''' sys.stdin = StringIO(test_input1) def avg(values): return sum(values) / len(values) n = int(input()) students_records = {} for _ in range(n): name, grade_string = input().split(' ') grade = float(grade_string) if name not in students_records: students_records[name] = [] students_records[name].append(grade) for name, grades in students_records.items(): average_grade = avg(grades) grades_str = ' '.join(str(f'{x:.2f}') for x in grades) print(f'{name} -> {grades_str} (avg: {average_grade:.2f})')
128469770f49907a7cbb201ac9272c5776973caa
Tems-git/Python_advanced
/lists_as_stacks_and_queues/06e_balanced_parentheses.py
1,276
4
4
# parentheses = input() # stack = [] # # balanced = True # # for paren in parentheses: # if paren in "{[(": # stack.append(paren) # elif paren in "}])": # if stack: # open_paren = stack.pop() # # if paren == "}" and open_paren == "{": # # continue # # elif paren == "]" and open_paren == "{": # # continue # # elif paren == ")" and open_paren == "(": # # continue # # else: # # balanced = False # # break # # if f"{open_paren}{paren}" not in ["{}", "[]", "()"]: # balanced = False # break # else: # balanced = False # break # # if balanced: # print("YES") # else: # print("NO") # v.2 expression = input() stack = [] balanced = True for ch in expression: if ch in "{[(": stack.append(ch) else: if len(stack) == 0: balanced = False break last_opening_bracket = stack.pop() pair = f"{last_opening_bracket}{ch}" if pair not in "()[]{}": balanced = False break if balanced: print("YES") else: print("NO")
fe8c35b13ecc12fd043023795917be731beda765
alexdistasi/palindrome
/palindrome.py
937
4.375
4
#Author: Alex DiStasi #File: palindrome.py #Purpose: returns True if word is a palindrome and False if it is not def checkPalindrome(inputString): backwardsStr ="" #iterate through inputString backwards for i in range(len(inputString)-1,-1,-1): #create a reversed version of inputString backwardsStr+=(inputString[i]).lower() #iterate through inputString and compare to the reverse string. If an element has a different value, it is not a palindrome for i in range(0, len(inputString)): if inputString[i]!=backwardsStr[i]: return False return True #Ask user for a word to check until user writes 'stop': userWord = input("Enter a word to see if it is a palindrome. Type 'stop' to exit: ") while (userWord.lower() != "stop"): print (checkPalindrome(userWord)) userWord = input("Enter a word to see if it is a palindrome. Type 'stop' to exit: ")
811e968599ff959fb84f372837f366e0ec1461a4
baixc1/course
/python/liaoxf/2/19.py
619
3.640625
4
import re def is_valid_email(addr): re_email = re.compile(r'^[a-zA-Z]+[a-zA-Z\.]*@[a-zA-Z\.]+[a-zA-Z]+$') if re.match(re_email, addr): return True else: return False def name_of_email(addr): re_name = re.compile(r'^(<(.*?)>)|((.*?)@).*') groups = re.match(re_name,addr).groups() return groups[1] or groups[3] assert is_valid_email('[email protected]') assert is_valid_email('[email protected]') assert not is_valid_email('bob#example.com') assert not is_valid_email('[email protected]') print('ok') assert name_of_email('<Tom Paris> [email protected]') == 'Tom Paris' assert name_of_email('[email protected]') == 'tom' print('ok')
3b310b45ebd2535f2f70316663fa9bbb904da646
immzz/leetcode_solutions
/next permutation.py
802
3.6875
4
class Solution(object): def nextPermutation(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ l = len(nums) - 2 while l >= 0 and nums[l] >= nums[l+1]: l -= 1 if l == -1: nums[:] = nums[::-1] else: r = len(nums) - 1 while r > l and nums[r] <= nums[l]: r -= 1 self.swap(nums,l,r) h,t = l+1,len(nums)-1 while h<t: self.swap(nums,h,t) h += 1 t -= 1 def swap(self,nums,i,j): temp = nums[i] nums[i] = nums[j] nums[j] = temp sol = Solution() a = [1,2] sol.nextPermutation(a) print a
44f1c70ca31e90e7d3e49fb7b154f509e7c94a07
immzz/leetcode_solutions
/TreeTraversal.py
2,584
3.71875
4
# Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param root, a tree node # @return a list of integers def preorderTraversal(self, root): if root == None: return [] else: return [root.val]+self.preorderTraversal(root.left)+self.preorderTraversal(root.right) def preorderIterativelyTraveral(self,root): result = [] node_stack = [root] counter_stack = [0] while node_stack: counter_stack[-1] = counter_stack[-1] + 1 if node_stack[-1] == None or counter_stack[-1] == 3: node_stack.pop() counter_stack.pop() elif counter_stack[-1] == 1: result = result + [node_stack[-1].val] node_stack.append(node_stack[-1].left) counter_stack.append(0) elif counter_stack[-1] == 2: node_stack.append(node_stack[-1].right) counter_stack.append(0) return result def postorderIterativelyTraveral(self,root): result = [] node_stack = [root] counter_stack = [0] while node_stack: counter_stack[-1] = counter_stack[-1] + 1 if node_stack[-1] == None: node_stack.pop() counter_stack.pop() elif counter_stack[-1] == 3: result = result + [node_stack.pop().val] counter_stack.pop() elif counter_stack[-1] == 1: node_stack.append(node_stack[-1].left) counter_stack.append(0) elif counter_stack[-1] == 2: node_stack.append(node_stack[-1].right) counter_stack.append(0) return result def inorderIterativelyTraveral(self,root): result = [] node_stack = [root] counter_stack = [0] while node_stack: counter_stack[-1] = counter_stack[-1] + 1 if node_stack[-1] == None or counter_stack[-1] == 3: node_stack.pop() counter_stack.pop() elif counter_stack[-1] == 1: node_stack.append(node_stack[-1].left) counter_stack.append(0) elif counter_stack[-1] == 2: result = result + [node_stack[-1].val] node_stack.append(node_stack[-1].right) counter_stack.append(0) return result
00e08a0512e2761c342a27005751a31d2b8aa672
immzz/leetcode_solutions
/LRU Cache.py
5,936
3.6875
4
class ListNode(object): def __init__(self,val,key): self.val = val self.key = key self.next = None self.prev = None class LRUCache(object): def __init__(self, capacity): """ :type capacity: int """ self.head = None self.tail = None self.dic = {} self.capacity = capacity def get(self, key): """ :rtype: int """ if key in self.dic: current_node = self.dic[key] self._remove(self.dic[key]) self._append(current_node) return current_node.val return -1 def set(self, key, value): """ :type key: int :type value: int :rtype: nothing """ if key in self.dic: self._remove(self.dic[key]) self._append(ListNode(value,key)) else: if len(self.dic) == self.capacity: self._remove(self.head) new_node = ListNode(value,key) self._append(new_node) def _append(self,node): if not self.tail: self.tail = self.head = node else: prev = self.tail self.tail.next = node node.prev = self.tail node.next = None self.tail = node self.dic[node.key] = node def _remove(self,current_node): if current_node == self.tail: #print "remove tail" self.tail = current_node.prev if self.tail: self.tail.next = None else: self.head = None current_node.next = current_node.prev = None del self.dic[current_node.key] return if current_node == self.head: self.head = current_node.next if self.head: self.head.prev = None else: self.tail = None current_node.prev = current_node.next = None del self.dic[current_node.key] return current_node.prev.next = current_node.next current_node.next.prev = current_node.prev current_node.prev = current_node.next = None del self.dic[current_node.key] def print_list(head): a = [] while head: print str(head.key)+","+str(head.val), head = head.next print ''' cache = LRUCache(2) cache.set(2,1) print_list(cache.head) cache.set(1,1) print_list(cache.head) cache.set(2,3) print_list(cache.head) cache.set(4,1) print_list(cache.head) cache.get(1) print_list(cache.head) cache.get(2) print_list(cache.head) ''' cache = LRUCache(10) cache.set(10,13) print_list(cache.head) print cache.dic.keys() print '---------' cache.set(3,17) print_list(cache.head) print cache.dic.keys() print '---------' cache.set(6,11) print_list(cache.head) print cache.dic.keys() print '---------' cache.set(10,5) print_list(cache.head) print cache.dic.keys() print '---------' cache.set(9,10) print_list(cache.head) print cache.dic.keys() print '---------' cache.get(13) print_list(cache.head) print cache.dic.keys() print '---------' cache.set(2,19) print_list(cache.head) print cache.dic.keys() print '---------' cache.get(2) cache.get(3) cache.set(5,25) cache.get(8) print_list(cache.head) print cache.dic.keys() print '---------' cache.set(9,22) print_list(cache.head) print cache.dic.keys() print '---------' cache.set(5,5) print_list(cache.head) print cache.dic.keys() print '---------' cache.set(1,30) print_list(cache.head) print cache.dic.keys() print '---------' print cache.tail.key cache.get(11) print_list(cache.head) print cache.dic.keys() print '---------+' print cache.tail.key,cache.tail.prev.key cache.set(9,12) print_list(cache.head) print cache.dic.keys() print '---------' cache.get(7) cache.get(5) cache.get(8) cache.get(9) cache.set(4,30) cache.set(9,3) cache.get(9) cache.get(10) cache.get(10) cache.set(6,14) cache.set(3,1) cache.get(3) cache.set(10,11) cache.get(8) cache.set(2,14) cache.get(1) cache.get(5) cache.get(4) cache.set(11,4) cache.set(12,24) cache.set(5,18) cache.get(13) cache.set(7,23) cache.get(8) cache.get(12) cache.set(3,27) cache.set(2,12) cache.get(5) cache.set(2,9) cache.set(13,4) cache.set(8,18) cache.set(1,7) cache.get(6) cache.set(9,29) cache.set(8,21) cache.get(5) cache.set(6,30) cache.set(1,12) print_list(cache.head) cache.get(10) cache.set(4,15) cache.set(7,22) cache.set(11,26) cache.set(8,17) cache.set(9,29) cache.get(5) cache.set(3,4) cache.set(11,30) cache.get(12) cache.set(4,29) cache.get(3) cache.get(9) cache.get(6) cache.set(3,4) cache.get(1) cache.get(10) cache.set(3,29) cache.set(10,28) cache.set(1,20) cache.set(11,13) cache.get(3) cache.set(3,12) cache.set(3,8) cache.set(10,9) cache.set(3,26) cache.get(8) cache.get(7) cache.get(5) cache.set(13,17) cache.set(2,27) cache.set(11,15) cache.get(12) cache.set(9,19) cache.set(2,15) cache.set(3,16) cache.get(1) cache.set(12,17) cache.set(9,1) print_list(cache.head) print cache.dic.keys() print '---------' cache.set(6,19) cache.get(4) cache.get(5) cache.get(5) cache.set(8,1) cache.set(11,7) cache.set(5,2) cache.set(9,28) print_list(cache.head) cache.get(1)#,set(2,2),set(7,4),set(4,22),set(7,24),set(9,26),set(13,28),set(11,26)]) ''' cache.set(1,1) cache.set(2,2) cache.set(3,3) print_list(cache.head) cache.set(4,4) print_list(cache.head) #print cache.dummy #print cache.dic[3],cache.head,cache.head.next,cache.head.prev cache.get(3) #cache.get(3) #print '-',cache.dummy,cache.tail,cache.dummy.next #print cache.dic[3],cache.head,cache.head.next,cache.head.next.next print_list(cache.head) cache.set(4,4) print_list(cache.head) cache.get(2) print_list(cache.head) print cache.dic.keys() cache.set(4,3) print cache.dic.keys() cache.set(1,1) print cache.dic.keys() print cache.get(2) print cache.dic.keys() cache.set(4,1) print cache.get(1) print cache.dic.keys() '''
1ef57ca29b5604845c3323f087b3da14b000584c
immzz/leetcode_solutions
/surrounded regions.py
1,742
3.734375
4
class Solution(object): def solve(self, board): """ :type board: List[List[str]] :rtype: void Do not return anything, modify board in-place instead. """ if not board: return for i in xrange(len(board)): if board[i][0] == 'O': self.solveDo(board,i,0) if board[i][len(board[0])-1] == 'O': self.solveDo(board,i,len(board[0])-1) for j in xrange(len(board[0])): if board[0][j] == 'O': self.solveDo(board,0,j) if board[len(board)-1][j] == 'O': self.solveDo(board,len(board)-1,j) for i in xrange(len(board)): for j in xrange(len(board[0])): if board[i][j] == 'M': board[i][j] = 'O' else: board[i][j] = 'X' def solveDo(self,board,i,j): from Queue import Queue q = Queue() q.put((i,j)) #print "ENter" while q.qsize(): #print q.qsize() p = q.get() #sprint p i,j = p[0],p[1] #print i,j,board[i][j] if board[i][j] != 'O': continue #print "OK" board[p[0]][p[1]] = 'M' if i > 0 and board[i-1][j] == 'O': q.put((i-1,j)) if j > 0 and board[i][j-1] == 'O': q.put((i,j-1)) if i < len(board)-1 and board[i+1][j] == 'O': q.put((i+1,j)) if j < len(board[0])-1 and board[i][j+1] == 'O': q.put((i,j+1)) sol = Solution() a = [list("OOO"),list("OOO"),list("OOO")] sol.solve(a) print a
4979a47f2a05aee5dc531f8ecfa2415572df91d1
immzz/leetcode_solutions
/merge k sorted lists.py
1,075
3.84375
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param {ListNode[]} lists # @return {ListNode} # corner case: [[],[1]] def mergeKLists(self, lists): if not lists: return None if len(lists) == 1: return lists[0] mid = (len(lists)-1)/2 left = self.mergeKLists(lists[0:mid+1]) right = self.mergeKLists(lists[mid+1:]) return self.merge2Lists(left,right) def merge2Lists(self,list1,list2): dummy = ListNode(None) current = dummy while list1 and list2: if list1.val < list2.val: current.next = list1 list1 = list1.next else: current.next = list2 list2 = list2.next current = current.next current.next = list1 if list1 else list2 return dummy.next
a984cccd6ce2265f0f9e340f390f86c59a15a1db
immzz/leetcode_solutions
/closest binary search tree value II.py
1,396
3.703125
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def closestKValues(self, root, target, k): """ :type root: TreeNode :type target: float :type k: int :rtype: List[int] """ s1 = [] s2 = [] self.traverse(False,root,s1,target) self.traverse(True,root,s2,target) res = [] while k > 0: if not s1: res.append(s2.pop()) elif not s2: res.append(s1.pop()) else: if abs(s1[-1]-target) > abs(s2[-1]-target): res.append(s2.pop()) else: res.append(s1.pop()) k -= 1 return res def traverse(self,reverse,root,s,target): if not root: return if reverse: self.traverse(reverse,root.right,s,target) if root.val <= target: return s.append(root.val) self.traverse(reverse,root.left,s,target) else: self.traverse(reverse,root.left,s,target) if root.val > target: return s.append(root.val) self.traverse(reverse,root.right,s,target)
c1a842fa5839ec84dec4bfb7e496434ffae93b87
viegasdev/pong_game
/pong_game.py
3,871
4.125
4
# The famous and classic pong! # Made by viegasdev # Import modules import turtle import os # Inserting player names player_a = str(input("Insert player A name: ")) player_b = str(input("Insert player B name: ")) # Game window configuration window = turtle.Screen() window.title('Pong Game by viegasdev') window.bgcolor('#264653') window.setup(width=800, height=600) window.tracer(0) # Stops window from always updating, increases the perfomance # Score score_a = 0 score_b = 0 # Paddle A -> Left paddle_a = turtle.Turtle() # Creates a object paddle_a.speed(0) # Animation speed (the fastest possible) paddle_a.shape('square') paddle_a.color('#e76f51') paddle_a.shapesize(stretch_wid=5, stretch_len=1) # Stretches the 20px width five times paddle_a.penup() paddle_a.goto(-350, 0) # Paddle B -> Right paddle_b = turtle.Turtle() # Creates a object paddle_b.speed(0) # Animation speed (the fastest possible) paddle_b.shape('square') paddle_b.color('#e76f51') paddle_b.shapesize(stretch_wid=5, stretch_len=1) # Stretches the 20px width five times paddle_b.penup() paddle_b.goto(350, 0) # Ball ball = turtle.Turtle() # Creates a object ball.speed(1) # Animation speed (the fastest possible) ball.shape('square') ball.color('#e9c46a') ball.penup() ball.goto(0,0) window.delay(30) # Score board pen = turtle.Turtle() pen.speed(0) pen.color('#ffb997') pen.penup() pen.hideturtle() pen.goto(0,260) pen.write("{}: 0 {}: 0".format(player_a, player_b), align = 'center', font=('Courier', 24, 'normal')) # Ball x axis movement ball.dx = 0.35 # Everytime ball moves, it moves 2px in x axis # Ball y axis movement ball.dy = 0.35 # Everytime ball moves, it moves 2px in y axis # Functions to move the paddles def paddle_a_up(): y = paddle_a.ycor() y += 20 paddle_a.sety(y) def paddle_a_down(): y = paddle_a.ycor() y -= 20 paddle_a.sety(y) def paddle_b_up(): y = paddle_b.ycor() y += 20 paddle_b.sety(y) def paddle_b_down(): y = paddle_b.ycor() y -= 20 paddle_b.sety(y) # Keyboard binding window.listen() window.onkeypress(paddle_a_up, 'w') # Calls the function when user press the key window.onkeypress(paddle_a_down, 's') window.onkeypress(paddle_b_up, 'Up') window.onkeypress(paddle_b_down, 'Down') # Main game loop while True: window.update() # Every time the loop runs, it updates the screen # Move the ball ball.setx(ball.xcor() + ball.dx) ball.sety(ball.ycor() + ball.dy) # Border hitting if ball.ycor() > 290: ball.sety(290) ball.dy *= -1 if ball.ycor() < -290: ball.sety(-290) ball.dy *= -1 if ball.xcor() > 390: ball.goto(0,0) ball.dx *= -1 score_a += 1 # When the ball touches the right border, 1 point is added to A's score pen.clear() # Clears the pen value before displaying the new value pen.write("{}: {} {}: {}".format(player_a, score_a, player_b, score_b), align = 'center', font=('Courier', 24, 'normal')) if ball.xcor() < -390: ball.goto(0,0) ball.dx *= -1 score_b += 1 # When the ball touches the left border, 1 point is added to B's score pen.clear() pen.write("{}: {} {}: {}".format(player_a, score_a, player_b, score_b), align = 'center', font=('Courier', 24, 'normal')) # Paddle and ball colisions # Paddle B -> Right if (ball.xcor() > 340 and ball.xcor() < 350 and (ball.ycor() < paddle_b.ycor() + 50 and ball.ycor() > paddle_b.ycor() -50)): ball.setx(340) ball.dx *= -1 # Paddle A -> Left if (ball.xcor() < -340 and ball.xcor() > -350 and (ball.ycor() < paddle_a.ycor() + 50 and ball.ycor() > paddle_a.ycor() -50)): ball.setx(-340) ball.dx *= -1
7c348a55efae221b384611ade24f40141972d6d1
paul-yamaguchi/2021_forStudy
/11_01両端キュー.py
272
3.65625
4
from collections import deque #deque : double-ended que(両端キュー) D = deque() #空のキュー[]を作成 D.append("A") D.append("B") D.append("C") D.pop() #C:右端から削除された要素 D.popleft() #A:左端から削除された要素 print(D) #deque("B")
5efe4bf11b54fe0752c60821f291e4408c606067
paul-yamaguchi/2021_forStudy
/06_01分割統治法フィボナッチ.py
258
3.8125
4
def fib(n): if n < 2: return n else: a = fib(n - 1) #再帰的定義 b = fib(n - 2) c = a + b return c print(fib(5)) #この場合返り値cがあるので、ターミナルに表示するにはprintが必要
5b1f21a6426a4fc8bdbf0c29de9bf4fd2efe3687
paul-yamaguchi/2021_forStudy
/14_02ミニマックス法三目並べ.py
1,552
3.515625
4
def leaf(n): #盤面nで勝敗が決まっているか判定する return((triple(n, "0") and not triple(n, "X")) or (not triple(n, "0") and triple(n, "X") or ("_" not in n[0] + n[1] + n[2]))) def triple(n, p): #盤面nの中でpが縦横斜めに一列に揃っているかどうかを判定 for (a,b,c) in [(0,0,0), (1,1,1),(2,2,2),(0,1,2)]: if(n[a][0] == n[b][1] == n[c][2] == p or n[2][a] == n[1][b] == n[0][c] ==p): return True return False def evaluation(n): #〇が揃ったら100(勝)、×は0(負)、引き分けは50を返す if triple(n, "0"): return 100 elif triple(n, "X"): return 0 else: return 50 def edge(n): #取りうる手を全通り列挙し、次の盤面のリストを返す L = n[0] + n[1] + n[2] Ns = [] player = "0" if L.count("0") > L.count("X"): player = "X" for i in range(len(L)): if L[i] == "_": L2 = L[:] L2[i] = player Ns = Ns + [L2] return [[[a,b,c], [d,e,f], [g,h,i]] for (a,b,c,d,e,f,g,h,i) in Ns] #14_01のコピー def my_turn(n): if leaf(n): return evaluation(n) max = 0 for next in edge(n): temp = your_turn(next) if temp > max: max = temp return max def your_turn(n): if leaf(n): return evaluation(n) min = 100 for next in edge(n): temp = my_turn(next) if temp < min: min = temp return min n = [["0", "_", "_"],["0", "X", "_"], ["X", "0", "X"]] print(my_turn(n))
63cfd662441dee6c851b70171d7248cb227d4f76
jinwoo0710/python
/0528/threeSpuare.py
323
3.578125
4
# -*- coding: utf-8 -*- """ Created on Fri May 28 14:28:50 2021 @author: Mac_1 """ import turtle as t def drawRect(length): for i in range(4): t.forward(length) t.left(90) for i in range(-200,400,200): t.up() t.goto(i,0) t.down() drawRect(100) t.done()
ea55381c9511f905b3216fc225880434796ea0d5
jinwoo0710/python
/0528/nPolyon.py
295
3.921875
4
# -*- coding: utf-8 -*- """ Created on Fri May 28 14:50:54 2021 @author: Mac_1 """ import turtle as t def n_polygon(n, length): for i in range(n): t.forward(length) t.left(360/n) for i in range(20): t.left(20) n_polygon(6, 100) t.done()
bb12347a447c97b331f87b0f5565350ed8262508
Viinu07/Python_Programming
/interiorangle.py
118
3.5625
4
a,b,c = input().split() a = int(a) b = int(b) c = int(c) sum = a+b+c if sum ==180: print("yes") else: print("no")
353b341eb43b497f5e6618cd93a7ac169e03ccb7
JennyCCDD/fighting_for_a_job
/LC 反转字符串.py
1,064
4.125
4
# -*- coding: utf-8 -*- """ @author: Mengxuan Chen @description: 反转字符串 编写一个函数,其作用是将输入的字符串反转过来。输入字符串以字符数组 char[] 的形式给出。 不要给另外的数组分配额外的空间,你必须原地修改输入数组、使用 O(1) 的额外空间解决这一问题。 你可以假设数组中的所有字符都是 ASCII 码表中的可打印字符。 @revise log: 2021.01.11 创建程序 解题思路:双指针 """ class Solution(object): def reverseString(self, s): """ :type s: List[str] :rtype: None Do not return anything, modify s in-place instead. """ slow = 0 fast = len(s)-1 while slow < fast: #################################### s[fast], s[slow] = s[slow], s[fast] #################################### slow +=1 fast -=1 return s solution = Solution() result = solution.reverseString(["h","e","l","l","o"]) print(result)
209962037719fae0422ee5668dc3af4ce8a293cb
JennyCCDD/fighting_for_a_job
/LC 删除排序数组中的重复项.py
660
3.671875
4
# -*- coding: utf-8 -*- """ @author: Mengxuan Chen @description: 删除排序数组中的重复项 https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/x2gy9m/ @revise log: 2021.01.05 创建程序 """ class Solution(object): def removeDuplicates(self, nums): """ :type nums: List[int] :rtype: int """ i = 0 j = 0 while j < len(nums)-1: j += 1 if nums[j] != nums[i]: i += 1 nums[i] = nums[j] return i + 1 solution = Solution()#[0, 1, 2, 3, 4] result = solution.removeDuplicates([0,0,0,1,1,1,2,2,3,3,4]) print(result)
496c08f32796ccaf58688b36bf91548b7e0a4528
JennyCCDD/fighting_for_a_job
/LC 反转链表.py
744
3.796875
4
# -*- coding: utf-8 -*- """ @author: Mengxuan Chen @description: 反转链表 进阶: 你可以迭代或递归地反转链表。你能否用两种方法解决这道题? @revise log: 2021.01.16 创建程序 2021.01.17 解题思路: # """ # Definition for singly-linked list. # class ListNode(object): # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution(object): def reverseList(self, head): """ :type head: ListNode :rtype: ListNode """ prev = None curr = head while (curr != None): Next = curr.next curr.next = prev prev = curr curr = Next return prev
639e5f0f5eef308239f53618d6d663956058799e
JennyCCDD/fighting_for_a_job
/LC 将有序数组转换为二叉搜索树.py
1,591
4.03125
4
# -*- coding: utf-8 -*- """ @author: Mengxuan Chen @description: 将有序数组转化为二叉搜索树 @revise log: 2021.02.09 创建程序 一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。 中序遍历,总是选择中间位置右边的数字作为根节点 """ # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right # class Solution { # public TreeNode sortedArrayToBST(int[] nums) { # return helper(nums, 0, nums.length - 1); # } # # public TreeNode helper(int[] nums, int left, int right) { # if (left > right) { # return null; # } # # // 总是选择中间位置右边的数字作为根节点 # int mid = (left + right + 1) / 2; # # TreeNode root = new TreeNode(nums[mid]); # root.left = helper(nums, left, mid - 1); # root.right = helper(nums, mid + 1, right); # return root; # } # } class Solution(object): def sortedArrayToBST(self, nums): """ :type nums: List[int] :rtype: TreeNode """ def helper(left,right): if left > right: return None mid = (left + right + 1) / 2 root = TreeNode(nums[mid]) root.left = helper(left, mid - 1) root.right = helper(mid + 1, right) return root return helper(0,int(len(nums)-1))
8ebfcdfeba3a5e2a8adc7f70ea6bf85a3e423e68
abrambueno1992/Intro-Python
/src/fileio.py
526
4.40625
4
# Use open to open file "foo.txt" for reading object2 = open('foo.txt', 'r') # Print all the lines in the file # print(object) # Close the file str = object2.read() print(str) object2.close() # Use open to open file "bar.txt" for writing obj_bar = open("bar.txt", 'w') # Use the write() method to write three lines to the file obj_bar.write("Python is a great language.\nYeah its great!!\n New line") # Close the file obj_bar.close() objec_read = open('bar.txt', 'r') str2 = objec_read.read() print(str2) objec_read.close()
4114af720b73a8e32cdf1870413fb4a6cbf2d166
EthanShapiro/PythonForDataScience
/Numpy/NumpyArrays.py
1,122
3.65625
4
import numpy as np my_list = [1,2,3] print(my_list) np_array = np.array(my_list) print(np_array) my_mat = [[1,2,3], [4,5,6], [7,8,9]] np_mat = np.array(my_mat) print(np_mat) print(np.arange(0, 10)) # returns a np array from 0-9 print(np.arange(0, 11, 2)) # returns a np array from 0-10 going by 2's print(np.zeros((2, 5))) # returns a np array of zeros print(np.ones((3, 4))) # returns a column print(np.linspace(0, 5, 10)) # one dimensional vector that gives 10 evenly spaced points from 0 to 5 print(np.eye(4)) # Returns an identity matrix of 4x4 print(np.random.random(5)) # returns 5 random array of numbers between 0-1 print(np.random.random((5, 5))) # returns a 5x5 array of numbers between 0-1 print(np.random.randn(4)) # returns 4 gaussian (-1 to 1) print(np.random.randn(4, 4)) # returns 4x4 gaussian (-1 to 1) print(np.random.randint(1, 100, (4, 4))) arr = np.arange(25) ranarr = np.random.randint(0, 50, 10) print(arr) print(ranarr) arr = arr.reshape(5, 5) print(arr) print(ranarr.max()) print(ranarr.min()) print(ranarr.argmax()) print(ranarr.argmin()) print(arr.shape) print(arr.dtype)
aff920f0a7f70f361bc8104b5f996c7192f8c994
TMor1/Old-Python-Regex-Scripts
/MobileNumber.py
3,779
4.5
4
#! python3 #T.M 11/07/21 import sys, re print('This is a collection of 3 script\'s to verify or find a mobile number.\n\n') #===== Script 1 ===== #Develop a script to find a mobile number with the prefix XXX-XXXXXXX without using Regex #Included comments used to test script below print('Script 1'.center(20, '=')) def isMobile(text): if len(text)!=11: print('This is not the correct length for a mobile number.\nPlease try again.') return False #Not a mobile number for i in range(0, 3): # print(text[i]) #Printing 'text[i]' code used for testing to ensure all characters are being checked. if not text[i].isdecimal(): print('This number is missing the first 3 digits.\nPlease try again.') return False #Missing first 3 digits if text[3] != '-': # print(text[i]) print('This number does not include a dash at the correct place.\nPlease try again.') return False #Missing dash for i in range(4, 11): # print(text[i]) if not text[i].isdecimal(): print('This number is missing the last 7 digits.\nPlease try again.') return False #Missing last 7 digits else: print('Yes that is a mobile number! :)') print('Hello, I can confirm if a number follows the mobile format of \'XXX-XXXXXXX\'. Just enter one below :)') number=input() isMobile(number) #===== Script 2 ===== #Develop a script to find all numbers within a given string below without using Regex text='''Find the 5 numbers matching the correct number prefix within the text below. Only 5/10 numbers are in the correct format. Here are the first 5 :) = 085-1234561, 085-1234562, 85-12534562, 085-2145, 087-5134562 Here are the next 5 :) = 083-3214599, 087-9934332, 05-12524549, 0851352145, 083-613262''' print('\n'+'Script 2'.center(20, '=')) def isMobileEither(text): #Updated from above to prevent spam messages if len(text)!=11: return False #Not a mobile number for i in range(0, 3): if not text[i].isdecimal(): return False #Missing first 3 digits if text[3] != '-': return False #Missing dash for i in range(4, 11): if not text[i].isdecimal(): return False #Missing last 7 digits else: return True isNumber=False for i in range(len(text)): check=text[i:i+11] if isMobileEither(check): print('Phone number found: ' + check) isNumber=True if not isNumber: print('No numbers were found within this text.') #===== Script 3 ===== #Regex Time: Develop two scripts to find a single and multiple numbers (XXX-XXXXXXX) within text using Regex print('\n\n'+'Script 3'.center(20, '=')) numberText='''Find the 5/10 numbers matching the correct number format within the text below. This is altered from the text seen in script 2. Here are the first 5 :) = 085-1234561, 085-1234562, 85-12534562, 085-2145, 087-51a4562 Here are the next 5 :) = 3214599, 087-9934332, 05-12524549, 0851352145, 083-6b13262''' #Regex Script 3a - find a single number mobileRegex=re.compile(r'\d{3}-\d{7}') mo=mobileRegex.search('Find the phone number within this text! 085-1234567 :)') print('The number hidden in the text was: ' + str(mo.group()) +'\n') #Regex Script 3b - find 5 numbers withing a group of text matching XXX-XXXXXXX or XXXXXXX [no areas code or dash] mobileRegexTwo=re.compile(r'(\d{3}-)?(\d{7})') order=['1st', '2nd', '3rd', '4th', '5th'] numbers=mobileRegexTwo.findall(numberText) for i in range (0, 5): print('The %s number hidden in the text is: %s' %(order[i], numbers[i][0]+numbers[i][1])) #===== All Scripts Finished ===== print('\nExiting...') sys.exit()
b10d04f81038c8cbb44659ab948cc506c6a6fae8
DiegoFigueroa98/CursoPython
/HolaMundo.py
162
3.8125
4
a = int(input("Ingrese un número entero: ")) b = int(input("Ingrese un número entero: ")) c = a + b print(f"El resultado de la suma de {a} más {b} es: {c}")
6fe91047964236052658ccf013d70992eff27b65
DiegoFigueroa98/CursoPython
/Minijuego.py
457
3.53125
4
import random from random import randrange def iniciarJuego(): j1 = random.randint(1,6) j2 = random.randint(1,6) print(f"\nEl jugador 1 obtuvo {j1} puntos") print(f"\nEl jugador 2 obtuvo {j2} puntos") if j1>j2: print("\nEl ganador es el jugador 1") elif j1==j2: print("\nHubo un empate") else: print("\nEl ganador es el jugador 2") def main(): iniciarJuego() if __name__ == "__main__": main()
ba8d7a3ed6f25495a3a39622f004f0b4047e7866
mackmillar/static_dynamic_testing
/specs/card_game_tests.py
673
3.65625
4
import unittest from src.card import Card from src.card_game import CardGame class TestCardGame(unittest.TestCase): def setUp(self): self.card1 = Card("Hearts", 10) self.card2 = Card("Spades", 1) self.cardGame = CardGame() self.cards = [self.card1, self.card2] def test_check_for_ace(self): self.assertEqual(True, self.cardGame.check_for_ace(self.card2)) def test_highest_card(self): self.assertEqual(self.card1, self.cardGame.highest_card(self.card1, self.card2)) def test_cards_total(self): self.assertEqual("You have a total of 11", self.cardGame.cards_total(self.cards))
f0342b0265c883d87ea58c750f0ca8c92d2d14b1
alexkursell/alexchat
/TCPSocket.py
3,012
3.796875
4
import socket from time import sleep from MySocket import MySocket class TCPSocket(MySocket): ''' A class that represents a TCP connection with a specified host. Wraps around an actual socket.socket, and implements send and receive methods for easier usage. ''' def __init__(self, ip, port=None): ''' Class constructor. Takes either a socket.socket or an IP address and port number and initializes the TCPSocket. If it receives an IP and port, this method is also where the socket.socket is created and connected. :param ip: If port is specified, ip is an IP address\ if port is not specified, ip is a socket.socket object. :param int port: The port number on the host to be connected to. ''' #Used to prevent socket close with data still to be written. self.dataBeingSent = False if port == None: self.sock = ip else: self.ip = ip self.port = port self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.connect((ip, port)) def send(self, msg): ''' A method that sends a message through the socket. :param str msg: The message to be sent. ''' self.dataBeingSent = True try: #Encode message to be sent as UTF-8 with ASCII EOT terminator. msg = bytearray(msg.encode()) msg.append(ord('\x04')) #ASCII EOT byte msg = bytes(msg) #Send packets until whole message is sent. totalsent = 0 while totalsent < len(msg): try: sent = self.sock.send(msg[totalsent:]) except ConnectionResetError: self.dataBeingSent = False raise if sent == 0: raise RuntimeError("socket connection broken") totalsent = totalsent + sent except: raise RuntimeError("Send message failed.") finally: self.dataBeingSent = False def receive(self): ''' A method that waits until it receives a message and returns that message, along with the IP address of the sender. :rtype: tuple ''' chunks = [] while True: chunk = self.sock.recv(2048) if chunk == b'': raise RuntimeError("socket connection broken") chunks.append(chunk) if chr(chunk[-1]) == '\x04': #ASCII EOT byte break #Returns (message, ip of sender) return (str(b''.join(chunks)[:-1])[2:-1].replace("\\n", "\n").rstrip(), self.sock.getpeername()[0]) if __name__ == "__main__": s = MySocket() s.sock.settimeout(0.25) print(s.try_connect('10.243.67.97', 1298))
e6b95f7637894d491a069276b5bb53ea4be830d5
snktagarwal/TCCodes
/codejam/EuroPython2011/monk.py
938
3.5625
4
def readNextInput(): cases = int(raw_input()) for i in range(cases): node = int(raw_input()) desc = raw_input().strip() [nodes, edges] = constructGraph(desc, node) print "Case #"+str(i+1)+": " for day in range(node): print findConnectedNodes(nodes, edges, day) def constructGraph(desc, node): parts = desc.split() nodes = map(lambda x: int(x)-1, parts) edges = [] for i in range(node): edges.append([int(parts[i])-1, i]) return [nodes, edges] def findConnectedNodes(nodes, edges, start): curr_set = [start] visited = [] while(len(curr_set) != 0): # visit the curr_set v = curr_set.pop() neighbours = [] for n in edges: if n[0] == v: neighbours.append(n[1]) for n in neighbours: if n not in visited and n not in curr_set: curr_set.append(n) visited.append(v) return len(visited) if __name__=='__main__': readNextInput()
8397f17194679522c228d4765f805ec499c110a4
chenyapeng1/4-1
/函数九九乘法表.py
726
3.84375
4
#while语句的九九乘法表 # def chengfabiao(rows): # row=1 # while row<=rows: # col=1 # while col<=row: # print("%d*%d=%d" %(col,row,col*row), end="\t") # col+=1 # print("") # row+=1 # # chengfabiao(9) # chengfabiao(10) #for语句的九九乘法表 def stars(rows): start = 1; for row in range(start, rows): str1 = " " space = " " for col in range(1, row + 1): if (row == 3 and col == 2) or (row == 4 and col == 2): space = " " else: space = " " str1 += (str(row) + "+" + str(col) + "=" + str(row * col) + space) print(str1); stars(9) stars(10)
54760b32ee5aa588d2b0ba5fd626da5308eacff6
jeeves990/tkinterTutorial
/tkinterTutorial/tkinterTutorial_1.py
1,661
3.765625
4
#!/usr/bin/env python3 """ ZetCode Tkinter e-book In this script , we change the default style for the label widget class. Author: Jan Bodnar Last modified: January 2016 Website: www.zetcode.com """ from tkinter import Tk, BOTH from tkinter.ttk import Frame , Label , Style, Entry class Example(Frame): def __init__(self , parent): Frame.__init__(self , parent) self.parent = parent self.initUI() def initUI(self): self.pack(fill=BOTH , expand=True) s = Style() s.configure('TLabel', background='dark sea green', font=('Helvetica', '16')) lbl1 = Label(self , text="zetcode.com") lbl2 = Label(self , text="spoznaj.sk") lbl1.pack() lbl2.pack() self.moreStyles() def moreStyles(self): self.parent.title("Custom styles") self.pack(fill=BOTH , expand=True) from tkinter.ttk import Notebook notebook = Notebook(self) s = Style() s.configure('Tab1.TFrame', background='midnight blue') s.configure('Tab2.TFrame', background='lime green') s.configure('Tab3.TFrame', background='khaki') frame1 = Frame(width=400, height=300, style='Tab1.TFrame') frame2 = Frame(width=400, height=300, style='Tab2.TFrame') frame3 = Frame(width=400, height=300, style='Tab3.TFrame') notebook.add(frame1 , text="Tab 1") notebook.add(frame2 , text="Tab 2") notebook.add(frame3 , text="Tab 3") notebook.pack(pady=5) def main(): root = Tk() ex = Example(root) root.geometry("250x100+300+300") root.mainloop() if __name__ == '__main__': main()
81cb9114c1fdd16e8b12863531fdaf860080943b
udbhavkanth/Algorithms
/Find closest value in bst.py
1,756
4.21875
4
#in this question we have a bst and #a target value and we have to find # which value in the bst is closest #to our target value. #First we will assign a variable closest #give it some big value like infinity #LOGIC: #we will find the absolute value of (target-closest) And # (target - tree value) # if the absoulte value of target-closest is larger than #absolute value of target - tree value than we will update our #closest and #than compare the tree value to target value if tree value is #greater than target then we only have to traverse left side of #tree if its lower than rigt side of tree #RECURSIVE WAY :- def findClosestValueInBst(tree, target): return findClosestValueInBstHelper(tree,target,float("inf")) def findClosestValueInBstHelper(tree,target,closest): if tree is None: return closest if abs(target-closest) > abs(target-tree.value): closest = tree.value if target < tree.value: return findClosestValueInBstHelper(tree.left,target,closest) elif target > tree.value: return findClosestValueInBstHelper(tree.right, target, closest) else: return closest def findClosestValueInBSt_1(tree, target): return findClosestValueInBstHelper1(tree,target,float("inf")) def findClosestValueInBstHelper1(tree,target,closest): currentNode = tree while currentNode is not None: if abs(target-closest) > abs(target-tree.value): closest = currentNode.value if target < currentNode.value: currentNode = currentNode.left elif target > currentNode.value: currentNode = currentNode.right else: break return closest
b3860f1282d9658108ed63e184fa5528945c5d9e
baevres/fizz_buzz_projects
/FizzBuzz.py
1,550
4.0625
4
""" Read README.md for explaining about problems in realisation """ def fizz_buzz(string): """ At first function checks: has a string more than one words or not. Then 'string' will be converted to list which function checks by iterations. """ if ' ' in string: lst = string.lower().split(' ') else: lst = [string.lower()] new_string = '' n = len(lst) for x in range(n): micro_n = len(lst[x]) if (x + 1) % 3 == 0: lst[x] = 'Fizz' new_string += lst[x] new_string += ' ' # for space between words elif micro_n >= 5: new_word = '' for y in range(micro_n): if (y + 1) % 5 == 0: new_word += 'Buzz' continue new_word += lst[x][y] new_string += new_word new_string += ' ' else: new_string += lst[x] new_string += ' ' new_string = new_string[:len(new_string)-1] # delete space in the end of new_string return new_string class FizzBuzzDetector: def __init__(self, string): if isinstance(string, str): if 7 <= len(string) <= 100: self.new_string = fizz_buzz(string) self.countFizz = 0 self.countBuzz = 0 else: raise ValueError('Invalid length of input string. Length must be: 7 <= string <= 100.') else: raise TypeError('Type of input value is not a string.') def getOverlappings(self): pattern1 = 'Fizz' pattern2 = 'Buzz' self.countFizz = self.new_string.count(pattern1) self.countBuzz = self.new_string.count(pattern2) return f'"Fizz" in string - {self.countFizz}, "Buzz" in string - {self.countBuzz}'
238d1756503e704ab2a91b06fe29d2b25ba5a8ea
BurningUnder/Learning-Python
/new_code/day01_to_day15/day05/craps_games.py
919
3.9375
4
""" Craps赌博游戏 游戏规则如下:玩家掷两个骰子,点数为1到6, 如果第一次点数和为7或11,则玩家胜, 如果点数和为2、3或12,则玩家输, 如果和为其它点数,则记录第一次的点数和,然后继续掷骰,直至点数和等于第一次掷出的点数和,则玩家胜, 如果在这之前掷出了点数和为7,则玩家输。 """ from random import randint a = randint(1,6) b = randint(1,6) sum = a + b print('和为%d' % sum) if sum == 7 or sum == 11: print('you win') elif sum == 2 or sum == 3 or sum == 12: print('you lose') else: while True: a = randint(1,6) b = randint(1,6) print('丢出了%d点' % (a+b)) if a + b == 7: print('you lose') break elif a + b == sum: print('you win') break """ 这获胜概率还是挺高的 """
5783c75d4b94b3b0d55a37e28f63ddd1f6daa74f
edgardeng/python-data-science-days
/day06-numpy-array-function/index.py
3,429
3.65625
4
# day 6 Numpy Array Function import numpy as np import time from timeit import timeit np.random.seed(0) def compute_reciprocals(values): output = np.empty(len(values)) for i in range(len(values)): output[i] = 1.0 / values[i] return output # time loop # value1 = np.random.randint(1, 10, size=5) # t1 = timeit('compute_reciprocals(value1)', 'from __main__ import compute_reciprocals, value1', number=1) # print('timeit', t1) # # value2 = np.random.randint(1, 100, size=1000000) # t2 = timeit('compute_reciprocals(value2)', 'from __main__ import compute_reciprocals, value2', number=1) # print('timeit', t2) # # t3 = timeit('1.0 / value2', 'from __main__ import value2', number=1) # print('timeit', t3) def array_arithmetic(): x = np.arange(4) print("x =", x) print("x + 5 =", x + 5) print("x - 5 =", x - 5) print("x * 2 =", x * 2) print("x / 2 =", x / 2) print("x // 2 =", x // 2) print("-x = ", -x) print("x ** 2 = ", x ** 2) print("x % 2 = ", x % 2) print('-(0.5*x + 1) ** 2', -(0.5*x + 1) ** 2) print('add', np.add(x, 2)) x = np.array([-2, -1, 0, 1, 2]) print('x=', x) print('abs(x)=', abs(x)) print('np.absolute(x) = ', np.absolute(x)) print('np.abs(x) = ', np.abs(x)) x = np.array([3 - 4j, 4 - 3j, 2 + 0j, 0 + 1j]) print('x=', x) print('np.abs(x) = ', np.abs(x)) def trigonometric(): theta = np.linspace(0, np.pi, 3) print("theta = ", theta) print("sin(theta) = ", np.sin(theta)) print("cos(theta) = ", np.cos(theta)) print("tan(theta) = ", np.tan(theta)) x = [-1, 0, 1] print("x = ", x) print("arcsin(x) = ", np.arcsin(x)) print("arccos(x) = ", np.arccos(x)) print("arctan(x) = ", np.arctan(x)) def logarithms(): x = [1, 2, 3] print("x =", x) print("e^x =", np.exp(x)) print("2^x =", np.exp2(x)) print("3^x =", np.power(3, x)) x = [1, 2, 4, 10] print("x =", x) print("ln(x) =", np.log(x)) print("log2(x) =", np.log2(x)) print("log10(x) =", np.log10(x)) x = [0, 0.001, 0.01, 0.1] print("exp(x) - 1 =", np.expm1(x)) print("log(1 + x) =", np.log1p(x)) def advanced_feature(): # write computation results directly to the memory location x = np.arange(5) y = np.empty(5) np.multiply(x, 10, out=y) print(y) y = np.zeros(10) np.power(2, x, out=y[::2]) print(y) x = np.arange(1, 6) print('x=', x) sum = np.add.reduce(x) print('sum=', sum) mul = np.multiply.reduce(x) print('multiply reduce=', mul) sum2 = np.add.accumulate(x) mul2 = np.multiply.accumulate(x) out = np.multiply.outer(x, x) print('add.accumulate=', sum2) print('multiply.accumulate=', mul2) print('multiply.outer=', out) from scipy import special def scipy_special(): # Gamma functions x = [1, 5, 10] print("gamma(x) =", special.gamma(x)) print("ln|gamma(x)| =", special.gammaln(x)) print("beta(x, 2) =", special.beta(x, 2)) # Error function (integral of Gaussian) x = np.array([0, 0.3, 0.7, 1.0]) print("erf(x) =", special.erf(x)) print("erfc(x) =", special.erfc(x)) print("erfinv(x) =", special.erfinv(x)) if __name__ == '__main__': print('Numpy Version', np.__version__) array_arithmetic() trigonometric() logarithms() advanced_feature() scipy_special()
8c22861d27a06ebe3270f6f21bf8f63a6947c2f4
ujjwal002/100daysofDSA
/day-1/array/reversal_algorithm.py
428
3.9375
4
def reverse_array(arr, start, end): while start<end: temp = arr[start] arr[start] = arr[end] arr[end] = temp start=start+1 end= end-1 def left_rotated(arr,d,n): if d == 0: return None d = d%n reverse_array(arr,0,d-1) reverse_array(arr,d,n-1) reverse_array(arr,0,n-1) return(arr) arr = [1,3,5,7,9,6] d= 2 n= len(arr) print(left_rotated(arr,d,n))
1846137f7bce8222b34daf7d60a3605f550303b5
daoge1205/python
/studentManage.py
1,582
3.78125
4
#!/usr/bin/python3.5 class studentManage: def __init__(self,student): """ menu为输入菜单选项的变量 并且每个class函数必须有一个self变量 """ if type(student) != type({}): print("构建存储的学生信息的存储结构有误,请使用字典结构") self.menu=-1 self.students=student def menuBook(self): print ("\n") print("***************") print("欢迎使用学生管理系统") print("1.增添学生信息") print("2.查找学生信息") print("3.删除学生信息") print("0.退出") print("***************") print("\n") def select(self): self.menu=input("请输入选型:") def addstudent(self): name=input('请输入学生姓名:') number=input('请输入学生学号:') self.students[number]=name print("插入信息成功!") def findstudent(self): try: name=input("请输入学号:") print('名字为%s' %self.students[name]) except KeyError: print("没有此学号") def deleteStudent(self): try: name=input("请输入学号:") student=self.students.pop(name) print ("学生姓名为:%s,学号为:%s,已经被删除" %(student,name)) except KeyError: print("没有此学号") members={} stu=studentManage(members) stu.menuBook() while stu.menu != '0': stu.select() if stu.menu == '1': stu.addstudent() stu.menuBook() elif stu.menu == '2': stu.findstudent() stu.menuBook() elif stu.menu == '3': stu.deleteStudent() stu.menuBook() else: print("输入非法选项,请重新输入!") stu.menuBook() print("感谢使用")
8de813f519101ad2723d7a51099696b33dcd5632
ammoyer/python-challenge
/PyPoll/Resources/main.py
1,679
3.5625
4
import os import csv electioncsv = os.path.join("PyPoll/Resources/election_data.csv") totalvotes = 0 candidate_votes = {} with open (electioncsv) as electiondata: reader = csv.reader(electiondata) header = next(electiondata) print(header) #The total number of votes cast for row in reader: candidate = row[2] totalvotes = totalvotes + 1 if candidate in candidate_votes.keys(): candidate_votes[candidate] += 1 else: candidate_votes[candidate] = 1 #The winner of the election based on popular vote. for key in candidate_votes.keys(): if candidate_votes[key] == max(candidate_votes.values()): winner = key print("Election Results") print("------------------------") print(f"Total Votes: {totalvotes}") print("--------------------------------") percent = [] for i in candidate_votes.keys(): percent = round(candidate_votes[i]/totalvotes*100, 2) poll_results = f"Percentage of Votes Each Candidate Won: {i}: {percent} %: ({candidate_votes[i]})" print(poll_results) print(f"Candidates Who Received Votes: {candidate_votes}") #print(f"Percentage of Votes Each Candidate Won: {percent}") print(f"The Winner is: {winner}.") filepathtosave = ("analysis.txt") with open(filepathtosave,'w') as text: text.write("-------------------------\n") text.write("Election Results\n") text.write("-------------------------\n") text.write(f"Total Votes: {totalvotes}\n") text.write("-------------------------\n") text.write(f"{poll_results}\n") text.write(f"Candidates Who Received Votes: {candidate_votes}\n") text.write(f"The Winner is: {winner}.\n")
953fd68ee3c3f5be6a8359985cfd77f61019744b
turanoff/MRTI2920
/Lessons/Lesson 09-25/lsp_part_two.py
723
3.890625
4
class Engine: def __init__(self, max_speed): self.max_speed = max_speed def move_vehicle(self): print(f"moving at {self.max_speed} speed") class Vehicle: def __init__(self, name, engine): self.name = name self.engine = engine def move(self): self.engine.move_vehicle() class Car(Vehicle): def __init__(self, name, engine): Vehicle.__init__(self, name, engine) def enable_radio(self): print("radio is on") class Bicycle(Vehicle): def __init__(self, name): Vehicle.__init__(self, name, "") #error anyway on the move() method def Jump(self): pass engine = Engine(100) car = Car("fast_car", engine) car.move()
83ab50397f4bc5fc235735fea69a9781ebd9f1fd
turanoff/MRTI2920
/Lessons/Lesson 09-04/test.py
553
3.671875
4
class Hero: hp = 100 damage = 10 __test = "don't touch me" def get_test(self): return self.__test def __init__(self, name): self.name = name def __str__(self): return f"hero {self.name}" def __repr__(self): return f"hero object {self.name} {self.damage} {self.hp}" def get_name(self): return self.name def set_damage(self, damage): self.damage = damage def damaged(self, damage): self.damage =- damage hero = Hero("Jane") print(hero._Hero__test)
817b478a996ab1437ca35dbaee2a42999fc20593
turanoff/MRTI2920
/Tasks/Task1/furman.py
273
4.03125
4
a = int(input("Введите сумму (рубли): ")) b = int(input("Введите процет дипозита: ")) z = int(input("Введите срок дипозита (годы): ")) before = 100 * a after = int(before * (100 + z*b) / 100) print(after // 100)
5892c7fbaf8a41c575b37345f7ff97c049eabc48
GitaShaviraPratiwi/Pemrograman-Desktop-C
/NO1.py
412
3.609375
4
#Mencari nilai rata-rata dari beberapa data var1 = float(input("Masukkan data yang ke-1 = ")) var2 = float(input("Masukkan data yang ke-2 = ")) var3 = float(input("Masukkan data yang ke-3 = ")) var4 = float(input("Masukkan data yang ke-4 = ")) var5 = float(input("Masukkan data yang ke-5 = ")) n_var = 5 rata_rata=((var1+var2+var3+var4+var5)/n_var) print("Rata-rata dari data tersebut =",rata_rata)
7c0ede8af1b25fd43d39e7e3f36e0a3ab20e52f3
manavmishra96/ANN-on-Schrodinger-eqns
/train_the_nn.py
5,857
3.828125
4
""" Python code to train the Neural Network using numpy package. It is a pure pythonic code using no exclusive third party library functions """ import numpy as np import json import random as ra from matplotlib.pylab import * from load_data import load_data_nn training_data, validation_data = load_data_nn() class Neural_network(object): def __init__(self, sizes): self.num_layers = len(sizes) self.sizes = sizes self.biases = [np.random.randn(y,1) for y in self.sizes[1:]] self.weights = [np.random.randn(y,x) for x,y in zip(self.sizes[:-1], self.sizes[1:])] def feedforward(self, a): a = np.array(a); a = a.reshape((a.shape[0], 1)) for b,w in zip(self.biases[:-1], self.weights[:-1]): a = ReLU(np.dot(w,a) + b) #No activation function in the output layer a = np.dot(self.weights[-1], a) + self.biases[-1] return a def backprop(self, x, y): nabla_b = [np.zeros(b.shape) for b in self.biases] nabla_w = [np.zeros(w.shape) for w in self.weights] #feedforward activation = np.array(x); activation = activation.reshape((activation.shape[0], 1)) activations = [] #list to store all activations layer by layer activations.append(activation) zs = [] #list to store all z vectors layer by layer for b,w in zip(self.biases[:-1], self.weights[:-1]): z = np.dot(w, activation) + b zs.append(z) activation = ReLU(z) activations.append(activation) z = np.dot(self.weights[-1], activation) + self.biases[-1] zs.append(z) activation = z y = np.array(y); y = y.reshape((y.shape[0], 1)) activations.append(activation) #backward pass delta = (activations[-1] - y) * ReLU_prime(zs[-1]) nabla_b[-1] = delta nabla_w[-1] = np.dot(delta, activations[-2].transpose()) for l in range(2, self.num_layers): z = zs[-l] sp = ReLU_prime(z) delta = np.dot(self.weights[-l+1].transpose(), delta) * sp nabla_b[-l] = delta nabla_w[-l] = np.dot(delta, activations[-l-1].transpose()) return (nabla_b, nabla_w) def update_mini_batch(self, mini_batch, eta, lmbda, n): nabla_b = [np.zeros(b.shape) for b in self.biases] nabla_w = [np.zeros(w.shape) for w in self.weights] for x,y in mini_batch: delta_nabla_b, delta_nabla_w = self.backprop(x, y) nabla_b = [nb + dnb for nb, dnb in zip(nabla_b, delta_nabla_b)] nabla_w = [nw + dnw for nw, dnw in zip(nabla_w, delta_nabla_w)] #Update weights and biases self.weights = [(1 - eta*(lmbda/n))*w - (eta/len(mini_batch)*nw) for w, nw in zip(self.weights, nabla_w)] self.biases = [b - (eta/len(mini_batch))*nb for b, nb in zip(self.biases, nabla_b)] def SGD(self, training_data, epochs, mini_batch_size, eta, lmbda=0.0): n_data = len(validation_data) n = len(training_data) validation_cost = []; validation_accuracy = [] training_cost = []; training_accuracy = [] epch = [] for j in range(epochs): ra.shuffle(training_data) mini_batches = [training_data[k:k+mini_batch_size] for k in range(0,n,mini_batch_size)] for mini_batch in mini_batches: self.update_mini_batch(mini_batch, eta, lmbda, len(training_data)) print ("Epoch %s: training complete" % j) epch.append(j) #Print cost on the training_data costs = self.total_cost(training_data, lmbda) training_cost.append(costs) print ("Cost on training data: {}".format(costs)) #Print cost on the validation_data plot(epch, training_cost) show() return validation_cost, validation_accuracy, training_cost, training_accuracy def total_cost(self, data, lmbda): #Returns the total cost of the data set J(theta) cost = 0.0 for x, y in data: x = np.array(x); x = x.reshape((x.shape[0], 1)) y = np.array(y); y = y.reshape((y.shape[0], 1)) a = self.feedforward(x) a = np.array(a) val = cost1(a, y) cost += 1.0 * val / len(data) cost += 0.5*(lmbda/len(data)) * sum(np.linalg.norm(w)**2 for w in self.weights) return cost def save(self, filename): """Save the neural network to the file ``filename``.""" data = {"sizes": self.sizes, "weights": [w.tolist() for w in self.weights], "biases": [b.tolist() for b in self.biases]} f = open(filename, "w") json.dump(data,f) f.close() def load(self, filename): f = open(filename, "r") data = json.load(f) f.close() net = Neural_network(data["sizes"]) net.weights = [np.array(w) for w in data["weights"]] net.biases = [np.array(b) for b in data["biases"]] return net def cost1(a, y): """Return the cost associated with an output ``a`` and desired output``y``""" return 0.5 * np.linalg.norm(a-y) def ReLU(z): """The ReLU function.""" return z * (z > 0) def ReLU_prime(z): """Derivative of the ReLU function.""" return 1. * (z > 0) if __name__ == '__main__': net = Neural_network([127, 200, 200, 127]) #net.SGD(training_data, 1500, 300, 18.0, 0.1) #net.save("matrix.csv") net.load("matrix.csv") i = ra.randint(0, len(training_data)-1) x, y = training_data[i] var = [i+1 for i in range(127)] p = net.feedforward(x) plot(var, x, color = 'm') plot(var, y, color = 'r') plot(var, p, color = 'g') show()
7ad8ffef03a979fb5a983ff577b93209f559c90e
brahmaduttan/ProgrammingLab-Python
/CO1/qn7-list-operations.py
395
3.625
4
lst1 = [6,9,3,5,7] lst2 = [9,6,4,2,0,7,2] print("lst1=",lst1) print("lst2=",lst2) a = len(lst1) b = len(lst2) if a == b: print("SAME LENGTH") else: print("NOT SAME LENGTH") s1 = sum(lst1) s2 = sum(lst2) if s1 == s2: print("SUM IS SAME") else: print("SUM IS NOT SAME") lst1 = set(lst1) lst2 = set(lst2) i = lst1.intersection(lst2) i = list(i) print("Common values:",i)
d87cda127f8f239f689dc4e58a576fd046a2d2ee
brahmaduttan/ProgrammingLab-Python
/CO5/Q1.File_List.py
168
3.53125
4
newFile = open("text.txt","a") newFile.write("Python programming…! \n") newFile.close() readFile = open("text.txt","r") print(readFile.readlines()) readFile.close()
6dd094d3d9abf531dab180e297a75149f2a782b7
efarsarakis/keras-playground
/keras_cnn_example.py
1,809
3.984375
4
## Example from: ## https://elitedatascience.com/keras-tutorial-deep-learning-in-python#step-3 ## More accurate code can be found at : ## https://github.com/fchollet/keras/blob/master/examples/mnist_cnn.py import numpy as np np.random.seed(123) from keras.models import Sequential from keras.layers import Dense, Dropout, Activation, Flatten from keras.layers import Conv2D, MaxPooling2D from keras.utils import np_utils from keras.datasets import mnist from keras import backend as K (X_train, y_train), (X_test, y_test) = mnist.load_data() img_height = 28 img_width = 28 print(X_train.shape) from matplotlib import pyplot as plt #plt.imshow(X_train[0]) #plt.show() X_train = X_train.reshape(X_train.shape[0], 28, 28, 1) X_test = X_test.reshape(X_test.shape[0], 28, 28, 1) input_shape = (img_height, img_width, 1) print(X_train.shape) X_train = X_train.astype('float32') X_test = X_test.astype('float32') X_train /= 255 X_test /= 255 #print(y_train.shape) #print(y_train[:10]) y_train = np_utils.to_categorical(y_train, 10) y_test = np_utils.to_categorical(y_test, 10) #print(y_train[:10]) #print(y_train.shape) print(K.image_data_format() == 'channels_first') model = Sequential() model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=input_shape)) #print(model.output_shape) model.add(Conv2D(32, kernel_size=(3, 3), activation='relu')) model.add(MaxPooling2D(pool_size=(2,2))) model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(128, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(10, activation='softmax')) model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) model.fit(X_train, y_train, batch_size=32, nb_epoch=10, verbose=1) score = model.evaluate(X_test, y_test, verbose=0) print(score)
88d8ea096c76aabe18875a33875c055b22afae3b
RaulVan/JustPythonCode
/day1.py
543
3.765625
4
__author__ = 'ElevenVan' # #if # # x=int(input("Plz enter an integer:")) # if x < 0: # x=0 # print("Negative changed to zero") # elif x==0: # print("zero") # elif x==1: # print("single") # else: # print("more") # # for # # a=['cat','windows','defebestrate'] # for x in a: # print(x,len(x)) # # range() # # for i in range(5): # print(i,end=',') # a=['may', 'had', 'a', 'little', 'lamb'] # for i in range(len(a)): # print(i, a[i]) # print(range(10)) print(range(5)) lists= list(range(5)) print(lists)
b4daa28be288e7ac442f9237663bbf5b831cfb29
omritz/Decision-Tree
/decisionTree.py
9,204
3.671875
4
import pandas as pd import numpy as np import math from scipy.stats import chi2 """ This script build a decision tree from scratch by recursive functions and data frames from pandas, it is take a few seconds to build tree so please be patient """ class TreeNode(object): def __init__(self, attribute='leaf', threshold=0, entropy=1, examples=None, childrenLower=[], childrenHigher=[], label=None): self.examples = examples # data in this node self.entropy = entropy # entropy self.attribute = attribute # which attribute is chosen, it non-leaf self.children_lower = childrenLower # child node that lower then threshold self.children_higher = childrenHigher # child node that higher then threshold self.threshold = threshold # the threshold that set for this attribute self.label = label # if it is a leaf, so what will be the answer (viral/ not viral) def print(self): print('attribute is: ', self.attribute) print('threshold is: ', self.threshold) def makeData(): """ return data frame with 1 or 0 in the target attribute """ data_filename = "OnlineNewsPopularity.data.csv" df = pd.read_csv(data_filename) viral = df.shares >= 2000 notViral = df.shares < 2000 df.loc[viral, 'shares'] = 1 df.loc[notViral, 'shares'] = 0 df = df.drop('timedelta', axis='columns').drop('url', axis='columns') return df def divideData(dataRatio, set): """ split the data set to train set and test set""" msk = np.random.rand(len(set)) < dataRatio train, test = set[msk], set[~msk] return train, test def getThreshold(attribute, examples): """ calculate the threshold by the mean of each attribute""" return examples[attribute].mean() def calcEntropy(attribute, examples, threshold): """ calculate the entropy for given attribute""" n = len(examples) query = examples[attribute] >= threshold higher = examples[query] lower = examples[~query] return len(higher) / n * entropy(higher) + len(lower) / n * entropy(lower) def entropy(targetSet): """ Help func to calculate entropy""" n = len(targetSet) if n == 0: return 0 viral = len(targetSet[targetSet['shares'] == 1]) notViral = len(targetSet[targetSet['shares'] == 0]) if viral == 0 or notViral == 0: return 0 return -(viral / n) * math.log2(viral / n) - (notViral / n) * math.log2(notViral / n) def pluralityValue(examples): """ Checks plurality value - most common value of target in examples""" viral = len(examples[examples['shares'] == 1]) notViral = len(examples[examples['shares'] == 0]) if viral > notViral: return 1 else: return 0 def getRoot(examples): """ Return tree node with the attribute that have the min entropy""" minEntropy = 1 attribute = '' features = list(examples.columns[0:59]) for feature in features: if feature == 'shares': break threshold = getThreshold(feature, examples) entropy = calcEntropy(feature, examples, threshold) if minEntropy > entropy: minEntropy = entropy attribute = feature print('min entropy is ' + attribute + ': ', minEntropy) threshold = getThreshold(attribute, examples) examplesLower = examples[examples[attribute] < threshold].drop(attribute, axis=1) examplesHigher = examples[examples[attribute] >= threshold].drop(attribute, axis=1) examples = examples.drop(attribute, axis=1) return TreeNode(attribute, threshold, minEntropy, examples, childrenLower=examplesLower, childrenHigher=examplesHigher) def viralNotViral(examples): """ Return the number of viral and not viral examples """ viral = len(examples[examples['shares'] == 1]) notViral = len(examples[examples['shares'] == 0]) return viral, notViral def pruneVertices(tree): """ Prune the tree vertices by Chi^2 test""" Kstatisti = 0 if tree.children_higher.attribute == 'leaf' and tree.children_lower.attribute == 'leaf': # if is it leaf higherExamples = tree.children_higher.examples lowerExamples = tree.children_lower.examples vH, nvH = viralNotViral(higherExamples) # num of Viral that higher , num of NotViral that higher vL, nvL = viralNotViral(lowerExamples) # num of Viral that lower , num of NotViral that lower probH = (vH + nvH)/(len(higherExamples)+len(lowerExamples)) # probability higher probL = (vL + nvL)/(len(higherExamples)+len(lowerExamples)) # probability Lower vHN = probH * (vH + vL) vLN = probL * (vH + vL) nvHN = probH * (nvH + nvL) nvLN = probL * (nvH + nvL) if vHN != 0: Kstatisti = Kstatisti + ((vHN - vH)**2)/vHN if nvHN != 0: Kstatisti = Kstatisti + ((nvHN - nvH)**2)/nvHN if vLN != 0: Kstatisti = Kstatisti + ((vLN - vL)**2)/vLN if nvLN != 0: Kstatisti = Kstatisti + ((nvLN - nvL)**2)/nvLN Kcriti = chi2.ppf(0.95, len(higherExamples) + len(lowerExamples) - 1) if Kstatisti < Kcriti: if vH + vL > nvH + nvL: return TreeNode(label=1) else: return TreeNode(label=0) else: return tree # recursive, until we reach a leaf elif tree.children_higher.attribute == 'leaf' and tree.children_lower.attribute != 'leaf': tree.children_lower = pruneVertices(tree.children_lower) elif tree.children_higher.attribute != 'leaf' and tree.children_lower.attribute == 'leaf': tree.children_higher = pruneVertices(tree.children_higher) else: tree.children_higher = pruneVertices(tree.children_higher) tree.children_lower = pruneVertices(tree.children_lower) return tree def decisionTree(examples, parnet_examples): """ Recursive func that building the tree, in addition prune nodes that have less then 300 examples""" if examples.empty: return TreeNode(examples=parnet_examples, label=pluralityValue(parnet_examples)) if len(examples) < 300: return TreeNode(examples=examples, label=pluralityValue(examples)) elif len(examples) == len(examples[examples['shares'] == 0]): return TreeNode(examples=examples, label=0) elif len(examples) == len(examples[examples['shares'] == 1]): return TreeNode(examples=examples, label=1) else: root = getRoot(examples) examplesHigher = root.children_higher examplesLower = root.children_lower root.children_higher = decisionTree(examplesHigher, root.examples) root.children_lower = decisionTree(examplesLower, root.examples) return root def isThisViral(example, tree): """ Recursive func that check if example is viral or not by given tree""" if tree.attribute == 'leaf': return tree.label else: if example[tree.attribute] < tree.threshold: return isThisViral(example, tree.children_lower) else: return isThisViral(example, tree.children_higher) def calcError(tree, testSet): """ Calculate the error of given tree and test set """ answer = 0 for example in testSet.iterrows(): if isThisViral(example[1], tree) == example[1]['shares']: answer += 1 return 1 - answer / len(testSet) def buildTree(ratio): data = makeData() trainSet, testSet = divideData(ratio, data) tree = decisionTree(trainSet, trainSet) tree = pruneVertices(tree) printTree(tree) print('Error: ', calcError(tree, testSet)*100, '%') return tree def printTree(tree, dad=None, underOver=None): """ printing given tree , recursive func """ if tree.attribute == 'leaf': print('Dad: ', dad, ', Answer: ', tree.label, ', Under or Over thershold of the dad: ', underOver) return print('Dad: ', dad, ', Attribute: ', tree.attribute, ', Threshold: ', tree.threshold, ', Under or Over thershold of the dad: ', underOver) printTree(tree.children_lower, tree.attribute, 'Under') printTree(tree.children_higher, tree.attribute, 'Over') def treeError(k): """ calculate tree error by k fold cross validation""" data = makeData() trainSet, testSet = divideData(1/k, data) k_cross_validation(k, trainSet) def k_cross_validation(k, trainSet): dataGroups = np.array_split(trainSet, k) totalError = 0 for i in range(k): testSet = dataGroups[i] helpList = [] for j in range(k): if j != i: helpList.append(dataGroups[j]) trainSet = pd.concat(helpList) tree = decisionTree(trainSet, trainSet) totalError += calcError(tree, testSet) print("Error for k-cross validation: ", (totalError / k)*100, '%') if __name__ == "__main__": print('start') buildTree(0.6) treeError(5)
75f8d90d254d177a3a715e744c72b5422b971740
Nika1411/Laba5
/ind3.py
377
3.703125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Вариант 17 # Дано ошибочно написанное слово алигортм. Путем перемещения его букв получить слово # алгоритм. if __name__ == '__main__': s = 'алигортм' n = s.find('и') s = s[:n] + s[n+1:n+4] + s[n] + s[n+4:] print(s)
1a9052ff14cddd92a70f97d936caf7edf8dbe3bb
tiy-lv-python-2016-02/palindrome
/test_palindrome.py
807
3.703125
4
from unittest import TestCase from palindrome import palindrome class PalindromeTests(TestCase): def test_even(self): self.assertTrue(palindrome("toot")) def test_odd(self): self.assertTrue(palindrome("tot")) def test_simple(self): self.assertTrue(palindrome("stunt nuts")) def test_complete_sentences(self): self.assertTrue(palindrome("Lisa Bonet ate no basil.")) def test_complex_sentences(self): self.assertTrue(palindrome("A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal: Panama!")) def test_multiple_sentences(self): self.assertTrue(palindrome("Doc, note, I dissent. A fast never prevents a fatness. I diet on cod.")) def test_non_palindrome(self): self.assertFalse(palindrome("i am not a palindrome"))
7ae09111a112f74117a7a8326845737b8129e790
shijiezhao/IBD_Biomarker
/Select_sequence.py
1,205
3.578125
4
""" Selecting sequences that begin with certain sequences """ from Bio import SeqIO import argparse, os # Read in arguments for the script def parse_args(): usage = "%prog -i INPUT_FASTA_FILE -s Sequence_to_select -o Output_FASTA" # Parse command line arguments parser = argparse.ArgumentParser() parser.add_argument('-i', '--inputf', help = 'input fasta file', default='', required = True) parser.add_argument('-s', '--seqs', help = 'input starting sequence', default='', required = True) parser.add_argument('-o', '--outputf', help = 'output fasta file', default='', required = True) args = parser.parse_args() return args def selecting_sequence(fasta,sequence,outfile): L = len(sequence) output_handle = open(outfile, "w") for record in SeqIO.parse(fasta, "fasta"): if record.seq[0:L] == sequence: SeqIO.write(record, output_handle, "fasta") output_handle.close() def run(): ## Step 1 args = parse_args() ## Step 2: Make an directory to store the info os.system('mkdir '+args.seqs) ## Step 3: Store info outfile = args.seqs + '/' + args.outputf selecting_sequence(args.inputf, args.seqs, outfile) ### Run it! run()
87a612aaf9e7ff1af6943808c5542097694ed5cf
thomasmorgan/Eden
/eden.py
4,026
3.625
4
"""The Eden app.""" from Tkinter import Frame, Tk from simulation import Simulation from ui import UI import utility from utility import log from operator import attrgetter import settings class EdenApp(): """The EdenApp class is the overall app. When it runs it creates two objects: The simulation, that runs the actual simulation. The ui, that presents visuals of the simulation on the screen. """ def __init__(self, master): """Create the app.""" self.master = master # create the simulation object utility.log_welcome() log("> Creating simulation") self.simulation = Simulation() # create the app log("> Creating UI") master.wm_title("Eden") self.frame = Frame(master) self.frame.grid() # create the ui self.ui = UI(self.master, self, self.frame) self.create_key_bindings() self.running = False self.time = 0 def create_key_bindings(self): """Set up key bindings.""" def leftKey(event): self.rotate_map(-10.0) def rightKey(event): self.rotate_map(10.0) def upKey(event): self.change_time_step(1) def downKey(event): self.change_time_step(-1) def spaceKey(event): self.toggle_running() self.master.bind('<Left>', leftKey) self.master.bind('<Right>', rightKey) self.master.bind('<Up>', upKey) self.master.bind('<Down>', downKey) self.master.bind('<space>', spaceKey) def step(self): """Advance one step in time.""" self.time += settings.time_step_size self.ui.update_time_label(self.time) self.simulation.step() self.ui.paint_tiles() self.master.update() def rotate_map(self, degrees): """Spin the map.""" for c in self.simulation.world.cells: c.longitude += degrees if c.longitude < 0: c.longitude += 360.0 elif c.longitude >= 360.0: c.longitude -= 360.0 self.simulation.world.cells = sorted( self.simulation.world.cells, key=attrgetter("latitude", "longitude")) self.ui.paint_tiles() def change_time_step(self, direction): """Change the time_step_size.""" time_steps = [ 1, 10, 60, 60*10, 60*60, 60*60*6, 60*60*24, 60*60*24*7, 60*60*24*30, 60*60*24*365, 60*60*24*365*10, 60*60*24*365*50, 60*60*24*365*100, 60*60*24*365*500, 60*60*24*365*1000, 60*60*24*365*10000, 60*60*24*365*100000, 60*60*24*365*1000000 ] step_descriptions = [ "1s", "10s", "1 minute", "10 minutes", "1 hour", "6 hours", "1 day", "7 days", "30 days", "1 year", "10 years", "50 years", "100 years", "500 years", "1,000 years", "10,000 years", "100,000 years", "1,000,000 years" ] index = time_steps.index(settings.time_step_size) if direction > 0 and index != len(time_steps) - 1: settings.time_step_size = time_steps[index + 1] settings.time_step_description = step_descriptions[index + 1] elif direction < 0 and index != 0: settings.time_step_size = time_steps[index - 1] settings.time_step_description = step_descriptions[index - 1] self.ui.update_time_label(self.time) def toggle_running(self): """Start/stop the simulation.""" self.running = not self.running while self.running: self.step() root = Tk() eden = EdenApp(master=root) root.mainloop()
3faa3caf5ce4178c897e5fca39866b1360564140
Tatnie/tatni
/les 5/5_5.py
318
3.53125
4
def gemiddelde(): willeukeurigezin=input('doe maar een zin') Allewoorden=willeukeurigezin.strip.()split() aantalwoorden=len(allewoorden) accumulator=0 for woord in allewoorden: accumulator += len(woord) print('De gemiddelde lengte van het aantal woorden in deze zin: {}'.format(gem))
f132e65fb3e884765ab28eded1b9ededdb09a1b1
artalukd/Data_Mining_Lab
/data-pre-processing/first.py
1,964
4.40625
4
#import statement https://pandas.pydata.org/pandas-docs/stable/dsintro.html import pandas as pd #loading dataset, read more at http://pandas.pydata.org/pandas-docs/stable/io.html#io-read-csv-table df = pd.read_csv("iris.data") #by default header is first row #df = pd.read_csv("iris.data", sep=",", names=["petal_length","petal_width","sepal_length", "sepal_width", "category"]) #size of df df.shape() df.head() #df.tail(3) ''' Entire table is a data frame and The basics of indexing are as follows: Operation Syntax Result Select column df[col] Series Select row by label df.loc[label] Series Select row by integer location df.iloc[loc] Series Slice rows df[5:10] DataFrame Select rows by boolean vector df[bool_vec] DataFrame ''' #frame[colname] #df.frame["category"] #Acess particular element :df.loc[row_indexer,column_indexer] #df.loc[123,"petal_length"] #df.loc[123,"petal_length"] = <value of appropriate dtype> #assign always returns a copy of the data, leaving the original DataFrame untouched. #df.assign(sepal_ratio = df['sepal_width'] / df['sepal_length']).head()) ''' Simple python programming constructs: FOR loop: for item in sequence: # commands else: #commands example: word = "Hello" for character in word: print(character) While loop: while (condition): # commands else: # commands example: i = 0 while (i < 3): print("Knock") i += 1 print("Penny!") if-else in python example: option = int(input("")) if (option == 1): result = a + b elif (option == 2): result = a - b elif (option == 3): result = a * b elif (option == 4): result = a / b if option > 0 and option < 5: print("result: %f" % (result)) else: print("Invalid option") print("Thank you for using our calculator.") '''
9e836216cb7a71b753cd1eaafe53a92962f221ae
jshubham2304/c-program
/infix.py
1,105
3.515625
4
values=[] op=[] def opt(a1,a2,opp): if opp=='+': return a1 + a2 if opp=='-': return a1 - a2 if opp=='*': return a1 * a2 if opp=='/': return a1//a2 def check(op): if op in ('+','-'): return 1 elif op in ('*','/'): return 2 else: return 0 braces=['(','{','['] braces1=[']','}',')'] x="10*(2+3)" List=[] i=0 while i < len(x): if x[i] in braces: op.append(x[i]) elif x[i].isdigit(): val=0 while (i<len(x) and x[i].isdigit()): val=val*10+int(x[i]) i+=1 values.append(val) i-=1 elif x[i] in braces1: result=0 while (len(op)!=0 and op[-1] not in braces): a2=values.pop() a1=values.pop() opp=op.pop() result=opt(a1,a2,opp) values.append(result) op.pop() else: result=0 while(len(op)!=0 and check(op[-1])>=check(x[i])): a2=values.pop() a1=values.pop() opp=op.pop() result=opt(a1,a2,opp) values.append(result) op.append(x[i]) i+=1 result=0 while len(op)!=0: a2=values.pop() a1=values.pop() opp=op.pop() result=opt(a1,a2,opp) values.append(result) print(values[-1])
9c11bc4989a14b64d65cb6df51c4b12de337108e
natac13/My-Projects
/GoFish/go_fish.py
8,224
4.125
4
# Project: Go Fish game vs computer. # By: Natac import random import sys import time suits = ['Spade', 'Heart', 'Club', 'Diamond'] values = list(map(str, range(2, 11))) + ['A', 'J', 'Q', 'K'] def make_deck(): '''Generate list of tuples, which are the card of a deck''' deck = [(rank, suit) for rank in values for suit in suits] random.shuffle(deck) # does not return anything.... return deck def draw_card(deck): ''' n: an integer which is how many card to draw from the deck, usually 1 deck: is a non-empty list of tuples when n is 9 return: a list of tuples which are the cards, this coud be one card, will return none is the deck is empty ''' new_cards = [] try: card = deck.pop(0) # no need to del since pop() removes element as well except IndexError: print("No cards, left in deck") return [] else: new_cards.append(card) return new_cards def card_in_hand(v, hand): ''' v is a rank value of a card from the deck, ie 3, or 'A' Hand is a list of tuples returns: true if that card is currently in the given hand ''' if v in 'ajqk': v = v.upper() for card in hand: if card[0] == v: return True return False def transfer_cards(cardvalue, hand): ''' cardvalue is a str representation of the value of the card in question hand will contain at least one card matching the value return: list of card(s)(tuples) which are removed from the hand ''' if cardvalue in 'ajqk': cardvalue = cardvalue.upper() return [card for card in hand if card[0] == cardvalue] def update_hand(cardvalue, hand): ''' cardvalue is a str representation of the value of the card in question hand will contain at least one card matching the value return: list of card(s)(tuples) where transffered card are removed ''' if cardvalue in 'ajqk': cardvalue = cardvalue.upper() return [card for card in hand if card[0] != cardvalue] def computer_ask(comp_hand, user_hand, deck): ''' Take the comp hand and will ask user if they have one of the card value Random for some strategy return: tuple of a new comp hand and new user hand to unpack outside function ''' do_you_have = random.choice(comp_hand) print("COMPUTER TURN...") time.sleep(1) print("Do you have any {0}'s?".format(do_you_have[0])) user_answer = input('Y or N? ') print("Checking.....") time.sleep(2) if card_in_hand(do_you_have[0], user_hand): print("Yep, you do have some {0}'s, so I will transfer those" " for you.".format(do_you_have[0])) xfer_cards = transfer_cards(do_you_have[0], user_hand) user_hand = update_hand(do_you_have[0], user_hand) comp_hand += xfer_cards return(comp_hand, user_hand) else: print('Bad guess by the computer, computer draws a card.') time.sleep(1) comp_hand += draw_card(deck) return(comp_hand, user_hand) def book_keeping(comp_hand, user_hand, comp_bookT, user_bookT): ''' comp_hand, user_hand: are list of tuples. These represent cards. comp_books, user_books: are integers that are a total of how many books each player has returns: a tuple of 4 elements that will be unpacked,(comp_hand, user_hand, comp_books, user_books) then reassign outside function ''' for card in comp_hand: if len(transfer_cards(card[0], comp_hand)) == 4: # by not calling transfer_cards they will simple not appear in the # updated comp_hand print("Computer making a book of {0}'s".format(card[0])) comp_hand = update_hand(card[0], comp_hand) comp_bookT += 1 for card in user_hand: if len(transfer_cards(card[0], user_hand)) == 4: print("You can make a book of {0}'s".format(card[0])) user_hand = update_hand(card[0], user_hand) user_bookT += 1 print("Totals: Comp: {0}, User: {1}.".format(comp_bookT, user_bookT)) return (comp_hand, user_hand, comp_bookT, user_bookT) def playGame(): ''' Control flow of game and set up the compHand and userHand variables, as well as compBookTotal and userBookTotal will end when there are no cards left in the deck or in either hand and all books have been made. Player with more books wins ''' print("Welcome to Natac's Go Fish game!\n To win you need to collect more " "books, full sets then the computer.") print("When prompted, input a card value, that appears in your hand to see " "if you can snatch some from the computer, if not you will draw a card") time.sleep(3) prompt = "TO ASK>>>>> " main_deck = make_deck() compHand, userHand = [], [] for i in range(9): compHand += draw_card(main_deck) userHand += draw_card(main_deck) user_turn = True compBookTotal, userBookTotal = 0, 0 while (compBookTotal+userBookTotal) != 13: while user_turn: if len(userHand) == 0: userHand += draw_card(main_deck) if len(compHand) == 0: compHand += draw_card(main_deck) print("\nUSER HAND: {0}\n".format(userHand)) #print("COMP HAND", compHand) #test###################### to_ask_comp = input(prompt) print("Checking...") time.sleep(2) if not card_in_hand(to_ask_comp, userHand): print("Nice try that card is not even in your hand") user_turn = False print("Drawing a card for user hand.") time.sleep(1) userHand += draw_card(main_deck) break elif card_in_hand(to_ask_comp, compHand) and card_in_hand( to_ask_comp, userHand): print("Looks like the computer has some {0}'s.".format( to_ask_comp)) print("Transferring cards to your hand now") time.sleep(1) userHand += transfer_cards(to_ask_comp, compHand) compHand = update_hand(to_ask_comp, compHand) break else: print("Computer didn't have any {0}'s.".format(to_ask_comp)) print("Drawing a card for user hand.") time.sleep(1) userHand += draw_card(main_deck) print("\nUSER HAND: {0}\n".format(userHand)) user_turn = False while not user_turn: if len(compHand) == 0: compHand += draw_card(main_deck) if len(userHand) == 0: userHand += draw_card(main_deck) temp_hand = userHand[:] #print("COMP HAND", compHand) #test###################### print("\nUSER HAND: {0}\n".format(userHand)) compHand, userHand = computer_ask(compHand, userHand, main_deck) #print("COMP HAND", compHand) #test###################### # If the computer fails to find userHand won't change if len(temp_hand) == len(userHand): user_turn = True break else: print("\nUSER HAND: {0}\n".format(userHand)) break compHand, userHand, compBookTotal, userBookTotal = book_keeping( compHand, userHand, compBookTotal, userBookTotal) print("All books have been completed, let's see who won.") time.sleep(1) if userBookTotal > compBookTotal: print("Congratulation you have won Natac's Go Fish game") else: print("Looks like the computer beat you this time.... wamp wamp") if __name__ == '__main__': playGame()
a11e94ed6d4a744bdba7e74cc02efd2a4205576d
sniperswang/dev
/leetcode/L401/test.py
1,812
4.0625
4
""" A binary watch has 4 LEDs on the top which represent the hours (0-11), and the 6 LEDs on the bottom represent the minutes (0-59). Each LED represents a zero or one, with the least significant bit on the right. 8 4 2 1 32 16 8 4 2 1 For example, the above binary watch reads "3:25". Given a non-negative integer n which represents the number of LEDs that are currently on, return all possible times the watch could represent. Example: Input: n = 1 Return: ["1:00", "2:00", "4:00", "8:00", "0:01", "0:02", "0:04", "0:08", "0:16", "0:32"] Note: The order of output does not matter. The hour must not contain a leading zero, for example "01:00" is not valid, it should be "1:00". The minute must be consist of two digits and may contain a leading zero, for example "10:2" is not valid, it should be "10:02". """ """ class Solution(object): def readBinaryWatch(self, num): output = [] for h in range(12): for m in range(60): if bin(h * 64 + m).count('1') == num: output.append('%d:%02d' % (h, m)) return output """ class Solution(object): def readBinaryWatch(self, n): def dfs(n, hours, mins, idx): if hours >= 12 or mins > 59: return if not n: res.append(str(hours) + ":" + "0" * (mins < 10) + str(mins)) res.append('%d:%02d' %(hours, mins)) return for i in range(idx, 10): if i < 4: print idx,":",1 << i dfs(n - 1, hours | (1 << i), mins, i + 1) else: k = i - 4 dfs(n - 1, hours, mins | (1 << k), i + 1) res = [] dfs(n, 0, 0, 0) return res s = Solution() print s.readBinaryWatch(2)
6019bb30ca868623718771b5ac2e3beeb96c3665
sniperswang/dev
/leetcode/L452/test.py
1,578
4.03125
4
""" There are a number of spherical balloons spread in two-dimensional space. For each balloon, provided input is the start and end coordinates of the horizontal diameter. Since it's horizontal, y-coordinates don't matter and hence the x-coordinates of start and end of the diameter suffice. Start is always smaller than end. There will be at most 104 balloons. An arrow can be shot up exactly vertically from different points along the x-axis. A balloon with xstart and xend bursts by an arrow shot at x if xstart <=x <= xend. There is no limit to the number of arrows that can be shot. An arrow once shot keeps travelling up infinitely. The problem is to find the minimum number of arrows that must be shot to burst all balloons. nput: [[10,16], [2,8], [1,6], [7,12]] Output: 2 Explanation: One way is to shoot one arrow for example at x = 6 (bursting the balloons [2,8] and [1,6]) and another arrow at x = 11 (bursting the other two balloons). """ class Solution(object): def findMinArrowShots(self, points): """ :type points: List[List[int]] :rtype: int """ if (len(points) == 0 or len(points) == 1): return len(points) cnt = 1 points.sort() currP = points[0] for point in points[1:]: if point[0] <= currP[1]: currP[0] = point[0] currP[1] = min(currP[1],point[1]) else: currP = point cnt += 1 return cnt s = Solution() arr = [[10,16], [2,8], [1,6], [7,12]] print s.findMinArrowShots(arr)
b3a6e632568dd13f128eda2cba96293e2bd0d3cd
sniperswang/dev
/leetcode/L265/test.py
1,452
3.640625
4
""" There are a row of n houses, each house can be painted with one of the k colors. The cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color. The cost of painting each house with a certain color is represented by a n x k cost matrix. For example, costs[0][0] is the cost of painting house 0 with color 0; costs[1][2] is the cost of painting house 1 with color 2, and so on... Find the minimum cost to paint all houses. Note: All costs are positive integers. Follow up: Could you solve it in O(nk) runtime? """ class Solution(object): def minCostII(self, costs): """ :type costs: List[List[int]] :rtype: int """ if len(costs) == 0: return 0 m = len(costs) n = len(costs[0]) for i in range (1, m): preMin = {} preMin[0] = min(costs[i-1][1:]) costs[i][0] = costs[i][0] + preMin[0] if ( n > 1): preMin[n-1] = min(costs[i-1][:n-1]) costs[i][n-1] = costs[i][n-1] + preMin[n-1] for j in range (1, n-1): preMin[j] = min( min(costs[i-1][:j]), min(costs[i-1][j+1:]) ) costs[i][j] = costs[i][j] + preMin[j] return min(costs[len(costs)-1]) costa = [1,2,4] costb = [3,1,0] costc = [1,2,1] costs = [] costs.append(costa) costs.append(costb) costs.append(costc) s = Solution() print s.minCostII(costs)
988dab09d39206865788bc0f8d7c3088b551b337
VictoriaEssex/Codio_Assignment_Contact_Book
/part_two.py
2,572
4.46875
4
#Define a main function and introduce the user to the contact book #The function is executed as a statement. def main(): print("Greetings! \nPlease make use of my contact book by completing the following steps: \na) Add three new contacts using the following format: Name : Number \nb) Make sure your contacts have been arranged in alphebetical order.\nc) Delete a contact.\nd) Search for an existing contact.") #Create two variables made up of an array of strings. #The first variable represents the name of an indiviudal and the second is their contact number. Name = ['Victoria', 'Andrew'] print(Name) Number = ['0849993016', '0849879074'] print(Number) #Create a third variable, which is made of an empty array. contacts = [] print(contacts) #Create a loop which will continue to run until it reaches the length of array. #Make use of the append method to add a new contact to the end of the list. for i in range(len(Name)): contacts.append(Name[i] + ' : ' + Number[i]) #concatenation of the two different arrays. #Introduce a while loop to run until the statement is false, where the number of contacts has reached maximum number of 5. while len(contacts) < 5: details = input('Please enter a name and number of an individual to create a new contact.\n') # name : number contacts.append(details) print(contacts) #The sort method is used to arrange all your exisitng contacts into alphabetical order. contacts.sort() print(contacts) #A input is used to inform the user that they can delete a contact by inputting their name. name_to_delete = input('Which contact do you want to delete? ') #Delete a contact based on what it starts with. index_to_delete = 0 for c in range(len(contacts)): contact_name = contacts[c] if contact_name.startswith(name_to_delete): index_to_delete = c #The pop method is used to delete a contact in a specific index position. print('Index to delete: ' + str(index_to_delete)) contacts.pop(index_to_delete) print(contacts) #Search for a contact based on what their name starts with. name_search = input('Search contact: ') for search in range(len(contacts)): contact_name = contacts[search] if contact_name.startswith(name_search): print(contact_name) if __name__ == "__main__": main() #Close main function.
844b799722ef7c3e3ca6c01431c04663aa3f47d7
rkobismarck/dcp
/random/fibonacci.py
263
4.0625
4
""" Please calculate the first n numbers of a fibonacci series. n = 8 0,1,1,2,3,5,8,13 """ def fibonacci(n): if(n == 1): return 1 if(n == 0): return 0 return fibonacci(n-1) + fibonacci(n-2) print(fibonacci(7))
c9679d4d03aaa0520d9d245a9289e4bf3b64b92f
MrMugiwara/RKE
/tools/scripts/manchester-encode.py
414
3.609375
4
#!/usr/bin/env python3 # # Applies manchester encoding to the given bitstream import sys import binascii data = binascii.unhexlify(sys.stdin.read().strip()) output = [] for byte in data: bits = format(byte, '0>8b') for c in bits: if c == '0': output.append('01') elif c == '1': output.append('10') else: assert(False) print(''.join(output))
d6561bfc99721cd864195a426d59584a82f7b1a7
Jasonmes/Single_link_list
/Module_Use.py
1,179
3.609375
4
# def Modele(): # print("欢迎进入模块的世界") zhang = ["张三", 18, "man"] lisi = ["李四", 28, "female"] laowu = ["老五", 34, "gay"] feiwu = ["废物", 189, "freak"] # 全部名片 Lu = [zhang, lisi, laowu, feiwu] # 新建名片 def Creat_NewName(): New_One = [] newname = input("新的名字:") New_One.append(newname) newage = int(input("年龄:")) New_One.append(newage) newsex = input("新的性别:") New_One.append(newsex) Lu.append(New_One) return Lu # 查询名片 def Search_NameCard(): Search_Name = input("请输入要找的的名字:") for i in range(len(Lu)): if Search_Name == Lu[i]: print(Lu[i]) else: print("输入有误") def Enter_System(item): # ONE = Creat_NewName() # TWo = Search_NameCard() dict = {"1": "全部名片", "2": ONE, "3": TWo, "4": "退出系统"} if item == dict.keys(): # dict = {1: Creat_NewName(), 2: Lu, 3: Search_NameCard(), 4: "退出系统"} # 出错,不能把类作为对象储存,只能是对象。 print(dict["1"]) Item = input("输入一个选项:") Enter_System(Item)
90978c6cf43a6a450b95d84a7291e894819e1d78
jqdsouza/algos
/CTCI/python-sols/Chapter2/partition.py
1,272
4.09375
4
""" 2.4 Partition Write code to a parttion a linked list around a value x, such that all nodes less than x come before all nodes greater than or equal to x. If x is contained within the list, the values of x only need to be after the elements less than x. The partition element x can appear anywhere in the "right partition"; it does not need to appear between the left and right partitions. EXAMPLE: input: 3->5->8->5->10->2->1 (partition = 5) output: 3->1->2->10->5->5->8 """ from LinkedList import * def partition(ll, x): current = ll.tail = ll.head print("current: ", current) print("tail: ", ll.tail) print("head: ", ll.head) while current: nextNode = current.next current.next = None if current.value < x: current.next = ll.head ll.head = current print("new head: ", ll.head) else: ll.tail.next = current ll.tail = current print("new tail: ", ll.tail) current = nextNode # Error check in case all nodes are less than x if ll.tail.next is not None: ll.tail.next = None return ll if __name__ == "__main__": ll = LinkedList() ll.generate(3, 0, 99) print(ll) print(partition(ll, ll.head.value))
eefd7782ae06bcc6a738e2cc1a99bd2c199e2da6
RawatMeghna/BestPricedApartment_YouTube
/simple-linear-regression.py
1,889
3.53125
4
import pandas as pd import matplotlib.pyplot as plt import numpy as np df = pd.read_excel('apartment_prices.xlsx') ##df = df.set_index('Property') print(df.head()) price = df['Price'] #Prices of all apartments size = df['m2'] #Sizes of all apartments Property = df['Property'] #List of all properties apartments = [100, 110, 120, 130, 140, 150] #Calculate mean mean_size = round(np.mean(size), 4) mean_price = round(np.mean(price), 4) n = len(price) numerator = 0 denominator = 0 for i in range(n): numerator += (size[i] - mean_size) * (price[i] - mean_price) denominator += (size[i] - mean_size) ** 2 #Simple linear regression coefficients b1 = round(numerator / denominator, 4) b0 = round(mean_price - b1 * mean_size, 4) min_size = np.min(size) max_size = np.max(size) x = np.linspace(min_size, max_size) y = b0 + b1 * x abs_difference = [] rel_difference = [] ss_r = 0 ss_t = 0 for i in range(n): y_pred = b0 + b1 * size[i] ss_r += (price[i] - y_pred) ** 2 ss_t += (price[i] - mean_price) ** 2 abs_difference.append(round(price[i] - y_pred,0)) rel_difference.append(round((price[i] - y_pred) / y_pred,4)) for i in range(n): if rel_difference[i] == np.min(rel_difference): print('The cheapest property is property '+ Property[i]+ ' with a price of ' + str(price[i]) + ' and size of '+ str(size[i]) + ' m2.') r2 = 100 - round((ss_r/ss_t),4) * 100 print('R-squared - Coefficient of determination: ' + str(r2) + '%.') def estimate(size): price = round(b0 + b1 * size,0) return price for i in apartments: print('The apartment has a size of ' + str(i) + ' m2 and it\'s estimated price is ' + str(estimate(i))) plt.scatter(size, price, color = 'red', label = 'Data points') plt.plot(x,y, color = 'blue', label = 'Regression line') plt.xlabel('Size in m2') plt.ylabel('Price in EUR') plt.legend() plt.show()
757b60fbc021114cc77faa07b7e828a12ea00072
aholyoke/language_experiments
/python/Z_combinator.py
1,285
4.28125
4
# ~*~ encoding: utf-8 ~*~ # Implementation of recursive factorial using only lambdas # There are no recursive calls yet we achieve recursion using fixed point combinators # Y combinator # Unfortunately this will not work with applicative order reduction (Python), so we will use Z combinator # Y := λg.(λx.g (x x)) (λx.g (x x)) Y = (lambda g: (lambda x: g(x(x)))(lambda x: g(x(x)))) # Z combinator # Like the Y combinator except it has an extra "thunking" step to prevent infinite reduction # Z = λf.(λx.f (λv.x x v)) (λx.f (λv.x x v)) Z = (lambda f: (lambda x: f(lambda v: x(x)(v)))(lambda x: f(lambda v: x(x)(v)))) # The definition of factorial # Takes a continuation r which will be the recursive definition of factorial # λr. λn.(1, if n = 0; else n × (r (n−1))) G = (lambda r: (lambda n: 1 if n == 0 else n * (r(n - 1)))) # Z(G) = factorial # The definition of factorial G is passed to Z as argument f # Since Z is a fixed point combinator it satisfies Z(G) = G(Z(G)) # G(Z(G)) tells us that parameter r of G is passed the recursive definition of factorial factorial = (lambda f: (lambda x: f(lambda v: x(x)(v)))(lambda x: f(lambda v: x(x)(v))))( lambda r: (lambda n: 1 if n == 0 else n * (r(n - 1)))) # demonstration print(factorial(5)) print(factorial(6))
a579cab53ea98d7711744ff818ed3fd90544268e
shrilakshmishastry/NN-Practice-models
/kannada_phonetically_similar_words.py
10,368
3.734375
4
#program to generate phonetically similar words of a given kannada word # input_word = input() # word = list(input_word) word_set = [] with open("converted_word.txt","r") as cv_file: # print(cv_file) stripped = (line for line in cv_file) # t = stripped.split(",") # print(t) for k in stripped: # print(k.strip("\n")) word_set.append(k.strip("\n")) # print(type(word)) # print() # word_set.append(word) # for i in cv_file: # print(i) # word_set.append(i) # print(word_set[1]) # print("hello") new_word = [] label = [] num =0 for w in word_set: word = list(w) # print(word) # print(num) k=0 for i in word: if i == word[k-1]: if(i=="o" ): new = word.copy() new.pop(k-1) new.pop(k-1) new.insert(k-1,"u") new = ''.join(map(str,new)) new_word.append(new) label.append(num) k = k+1 elif((k<len(word)-1 ) and i+i == word[k+1]+i ): new = word.copy() new.pop(k) new1 = ''.join(map(str,new)) new_word.append(new1) label.append(num) if (i=='a'or i == 'e' or i == 'o' ): new1 = new.copy() new1.insert(k+1,i) new1 = ''.join(map(str,new1)) new_word.append(new1) label.append(num) if (k<(len(word)-1) and k<(len(word)-1) and word[k+1]=="a") : new1 = new.copy() new1.insert(k+1,'h') new1 = ''.join(map(str,new1)) new_word.append(new1) label.append(num) if (k<(len(word)-1) and i == 'e'): new1 = new.copy() new1.pop(k) new1.insert(k,'i') new1 = ''.join(map(str,new1)) new_word.append(new1) label.append(num) if(i=="a" and (new[k-1]=='b' or new[k-1]=='c' or new[k-1]=='d' or new[k-1]=='f' or new[k-1]=='g' or new[k-1]=='j' or new[k-1]=='k' or new[k-1]=='l' or new[k-1]=='m' or new[k-1]=='n' or new[k-1]=='p' or new[k-1]=='q' or new[k-1]=='r' or new[k-1]=='s' or new[k-1]=='t' or new[k-1]=='v' or new[k-1]=='w' or new[k-1]=='x' or new[k-1]=='y' or new[k-1]=='z' )) : new1 = new.copy() new1.insert(k,'ha') new1 = ''.join(map(str,new1)) new_word.append(new1) label.append(num) if(i == "e" and k<(len(word)-1) and new[k+1] == "y") : new1 = new.copy() new1.pop(k+1) new1.insert(k+1,'a') new1 = ''.join(map(str,new1)) new_word.append(new1) label.append(num) if( i =="y" and k<(len(word)-1) and new[k+1] == "e") : new1 = new.copy() new1.pop(k) new1 = ''.join(map(str,new1)) new_word.append(new1) label.append(num) if(i == "h" and k<(len(word)-1)and new[k+1]=="r") : new1 = new.copy() new1.pop(k) new1 = ''.join(map(str,new1)) new_word.append(new1) label.append(num) if(i == "h" and k<(len(word)-1) and new[k+1]=="a") : new1 = new.copy() new1.pop(k) new1 = ''.join(map(str,new1)) new_word.append(new1) label.append(num) if(i == "a" and k<(len(word)-1) and new[k+1]=="i") : new1 = new.copy() new1.pop(k) new1 = ''.join(map(str,new1)) new_word.append(new1) label.append(num) if(i == "y") : new1 = new.copy() new1.pop(k) new1.pop(k) new1.pop(k-1) new1.insert(k,"a") new1.insert(k,"i") new1.append("a") new1.append("h") new1 = ''.join(map(str,new1)) new_word.append(new1) label.append(num) if(k<len(word)): k = k+1 else: if(k<(len(word)-1) and (i == 'b' or i=="c" or i == "d" or i =="f" or i == "g" or i == "j" or i == "k" or i == "p" or i == "q" or i == "s" or i == "t" or i == "w" or i == "x" or i == "z") and (word[k+1]!="h")): new = word.copy() new.insert(k+1,"h") new = ''.join(map(str,new)) new_word.append(new) label.append(num) if (i=='a'or i == 'e' or i == 'o' ): new = word.copy() new.insert(k+1,i) new = ''.join(map(str,new)) new_word.append(new) label.append(num) if (k<(len(word)-1) and word[k+1]=="a" and i != "h" and (i != "r" and i != "y" and i!="l" and i!="v" ) ) : new = word.copy() new.insert(k+1,'h') new = ''.join(map(str,new)) new_word.append(new) label.append(num) if (k<(len(word)-1) and i == 'e'): new = word.copy() new.insert(k,'i') new = ''.join(map(str,new)) new_word.append(new) label.append(num) # if((new_word[len(new_word)]=='a'or new[k] == 'e' or new[k]== 'i' or new[k]== 'o' or new[k] == 'u')and(k<(len(word)-1) or k<(len(word)-1) )and(i+i == new[k+1]+i or i+i == new[k-1]+i or i+i+i == new[k-1]+i+new[k+1]) ): # print("5") # new = word.copy() # print("new",new) # new.pop(k) # print("after new",new) # new = ''.join(map(str,new)) # print("new str",new) # new_word.append(new) # if(new[k]=='e'): # new.insert(k,'i') # print("after new",new) # new = ''.join(map(str,new)) # print("new str",new) # new_word.append(new) # if(new[k]==a) : # new.insert(k,'ha') # print("after new",new) # new = ''.join(map(str,new)) # print("new str",new) # new_word.append(new) if(i=="a" and (word[k-1]=='b' or word[k-1]=='c' or word[k-1]=='d' or word[k-1]=='f' or word[k-1]=='g' or word[k-1]=='j' or word[k-1]=='k' or word[k-1]=='m' or word[k-1]=='n' or word[k-1]=='p' or word[k-1]=='q' or word[k-1]=='s' or word[k-1]=='t' or word[k-1]=='w' or word[k-1]=='x' or word[k-1]=='z' )) : new = word.copy() if(word[k-1]==word[k-2]): new.pop(k) new.pop(k-1) new.insert(k,'a') new.insert(k,'h') new = ''.join(map(str,new)) new_word.append(new) label.append(num) if(i == "e" and k<(len(word)-1) and word[k+1] == "y") : new = word.copy() new.pop(k+1) new.insert(k+1,'a') new = ''.join(map(str,new)) new_word.append(new) label.append(num) if( i =="y" and k<(len(word)-1) and word[k+1] == "e") : new = word.copy() new.pop(k) new = ''.join(map(str,new)) new_word.append(new) label.append(num) if(i == "h" and k<(len(word)-1) and word[k+1]=="r") : new = word.copy() new.pop(k) new = ''.join(map(str,new)) new_word.append(new) label.append(num) if(i == "h" and k<(len(word)-1) and word[k+1]=="a") : new = word.copy() new.pop(k) new = ''.join(map(str,new)) new_word.append(new) label.append(num) if(i == "a" and k<(len(word)-1) and word[k+1]=="i") : new = word.copy() new.pop(k) new = ''.join(map(str,new)) new_word.append(new) label.append(num) if(i == "i" ): new = word.copy() new.pop(k) new.insert(k,'e') new.insert(k,"e") new = ''.join(map(str,new)) new_word.append(new) label.append(num) new = word.copy() new.pop(k) new.insert(k,"y") new = ''.join(map(str,new)) new_word.append(new) label.append(num) if(i == "y" and (word[k-1]=='b' or word[k-1]=='c' or word[k-1]=='d'or word[k-1]=='f' or word[k-1]=='g' or word[k-1]=='j' or word[k-1]=='k' or word[k-1]=='l' or word[k-1]=='m' or word[k-1]=='n' or word[k-1]=='p' or word[k-1]=='q' or word[k-1]=='r' or word[k-1]=='s' or word[k-1]=='t' or word[k-1]=='v' or word[k-1]=='w' or word[k-1]=='x' or word[k-1]=='y' or word[k-1]=='z' ) ): new = word.copy() new.pop(k) new.insert(k,"i") new.insert(k,"a") new = ''.join(map(str,new)) new_word.append(new) label.append(num) if(i == "a" and k<(len(word)-1) and word[k+1]=="u"): new = word.copy() new.pop(k) new.insert(k,"o") # new.insert(k,"a") new = ''.join(map(str,new)) new_word.append(new) label.append(num) if(k<len(word)): k = k+1 num = num+1 # print(num) # if (word[i]) print(len(new_word)) t = 0 for k in new_word: print(label[t]) t = t+1 print(k)
6924c1a2527b8344c92a05788d34974e54079be3
luozhiping/leetcode
/middle/minesweeper.py
1,412
3.671875
4
# 529. 扫雷游戏 # https://leetcode-cn.com/problems/minesweeper/ class Solution(object): def updateBoard(self, board, click): """ :type board: List[List[str]] :type click: List[int] :rtype: List[List[str]] """ if board[click[0]][click[1]] == 'M': board[click[0]][click[1]] = 'X' return board queue = [click] direction = [(0, -1), (0, 1), (-1, 0), (1, 0), (-1, -1), (1, -1), (-1, 1), (1, 1)] while queue: MCount = 0 c = queue.pop(0) ECount = 0 for dir in direction: pos = [c[0]+dir[0], c[1]+dir[1]] if 0 <= pos[0] < len(board) and 0 <= pos[1] < len(board[0]): if board[pos[0]][pos[1]] == 'M': MCount += 1 elif board[pos[0]][pos[1]] == 'E': if pos not in queue: queue.append(pos) ECount += 1 if MCount == 0: board[c[0]][c[1]] = 'B' else: board[c[0]][c[1]] = str(MCount) if ECount > 0: queue = queue[:-ECount] return board s = Solution() print(s.updateBoard( [['B', '1', 'E', '1', 'B'], ['B', '1', 'M', '1', 'B'], ['B', '1', '1', '1', 'B'], ['B', 'B', 'B', 'B', 'B']] ,[1,2]))
7e07e839c0ec7167bbab93d54cf958b5376aa12d
luozhiping/leetcode
/middle/reverse_nodes_in_k_group.py
1,802
3.65625
4
# 25. k个一组翻转链表 # https://leetcode-cn.com/problems/reverse-nodes-in-k-group/ # Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def reverseKGroup(self, head, k): """ :type head: ListNode :type k: int :rtype: ListNode """ if not head: return head if k == 1: return head def beginReverse(lastHead, head, tail): lastHead.next = head current = head.next while current != tail: first = lastHead.next next = current.next #first.next = first.next.next lastHead.next = current current.next = first current = next first = lastHead.next head.next = current.next lastHead.next = current current.next = first return head h = head t = head.next step = 1 lastHead = ListNode(-1) lastHead.next = head head = lastHead while t: if step < k - 1: step += 1 t = t.next else: tmp = t nextH = t.next head = beginReverse(head, h, t) h = nextH if not h: break t = h.next step = 1 return lastHead.next head = ListNode(1) # head.next = ListNode(2) # head.next.next = ListNode(3) # head.next.next.next = ListNode(4) # head.next.next.next.next = ListNode(5) s = Solution() result = s.reverseKGroup(head, 5) while result: print(result.val) result = result.next
eba9799e6a330d640966f14db1762c4f9ad751eb
luozhiping/leetcode
/middle/longest_mountain_in_array.py
1,138
3.609375
4
# 845. 数组中的最长山脉 # https://leetcode-cn.com/problems/longest-mountain-in-array/ class Solution(object): def longestMountain(self, A): """ :type A: List[int] :rtype: int """ if not A: return 0 bpUp = [1 for _ in range(len(A))] bpDown = [1 for _ in range(len(A))] result = 0 for i in range(1, len(A)): upIndex = i downIndex = len(A) - 1 - i if A[upIndex] > A[upIndex - 1]: bpUp[upIndex] = bpUp[upIndex - 1] + 1 if A[downIndex] > A[downIndex + 1]: bpDown[downIndex] = bpDown[downIndex + 1] + 1 for i in range(1, len(A) - 1): if bpUp[i] > 1 and bpDown[i] > 1: result = max(result, bpUp[i]+bpDown[i] - 1) # print(bpUp) # print(bpDown) print(A) return result s = Solution() # print(s.longestMountain([2,1,4,7,3,2,5])) print(s.longestMountain([0,1,0])) import random test = [] for i in range(random.randint(0, 10000)): test.append(random.randint(0, 10000)) print(s.longestMountain(test))