blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
d39d0b079fa0ce61a129c37a2663a6751ec02f69
ftakanashi/LearningPractice
/PythonAlgorithm/图/Kruskal.py
2,107
3.5625
4
# -*- coding:utf-8 -*- ''' Kruskal算法用来获得图的一棵最小生成树 输入是一个图(以GraphAL实现为例),输出是一个列表形式记录的最小生成树,记录树中每条边的 两个端点和权值 算法中途要用的辅助结构包括一个reps列表用来记录每个端点所在联通分量的代表元 关键词:有序的全边列表,代表元,直到只剩一个联通分量为止 算法复杂度: 时间复杂度 O(max(ElogE,V^2)) 空间复杂度 O(E) ''' def kruskal_mine(graph): vnum = graph.vertex_num() edges = [] for vi,out_edges in enumerate(graph.getMat()): for vj,weight in out_edges: edges.append((weight,vi,vj)) edges.sort(key=lambda x:x[0]) reps = range(vnum) mst = [None] * vnum for edge in edges: w,vi,vj = edge if reps[vi] == reps[vj]: continue mst[vj] = (w,vi) for i in range(len(reps)): if reps[i] == reps[vj]: reps[i] = reps[vi] reps[vj] = reps[vi] return mst def kruskal(graph): vnum = graph.vertex_num() reps = [i for i in range(vnum)] # 最开始没有连接任何一条边,所以所以联通分量的代表元都是端点自己 mst,edges = [],[] # 不用[None] * vnum来初始化mst,方便在主循环里面做一个小优化 for vi in range(vnum): # 把所有边都整合在一起然后按照权值排序 for v,w in graph.out_edges(vi): edges.append((w,v,vi)) edges.sort() for w,vi,vj in edges: # 从权值最小者开始遍历各个边,有需要就将这个边连起来(就是将边的信息加入了mst中) if reps[vi] == reps[vj]: # vi和vj已经处于同一联通分量,可以直接跳过 continue mst.append((w,vi,vj)) if len(mst) >= vnum - 1: # 小优化,达到vnum-1说明已经有了完整的生成树,可以结束遍历 break for i,repv in enumerate(reps): if reps[i] == reps[vj]: reps[i] = reps[vi] reps[vj] = reps[vi] return mst
e1522e3393ee3750cdc6169781cc88490b039238
ysun232/piethon
/list1.py
349
3.96875
4
list1 = ["apple", "banana", "cherry", "banana", "watermelon", "blueberry"] print(list1.count("banana")) print(len(list1)) #with bracketes its a list[], elements can be moved around #with tuples, created with (), elements cannot be moved around. TO USE A TUPLE, YOU NEED TO INCLUDE A COMMA AT THE END t1=(5,) t2=(5) print(type(t1)) print(type(t2))
e982040b8e8cf20f8aec95903eb9a465156ac124
aindrila2412/DSA-1
/dynamicProgramming/LCS/longest_common_subsequence_length.py
2,766
4.15625
4
""" Given two strings ‘s1’ and ‘s2’, find the length of the longest subsequence which is common in both the strings. A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements. Example 1: Input: s1 = "abdca" s2 = "cbda" Output: 3 Explanation: The longest common subsequence is "bda". Example 2: Input: s1 = "passport" s2 = "ppsspt" Output: 5 Explanation: The longest common subsequence is "psspt". """ def length_of_longest_common_subsequence_recursive(s1, s2, s1_len, s2_len): if s1_len == 0 or s2_len == 0: return 0 if s1[s1_len - 1] == s2[s2_len - 1]: return 1 + length_of_longest_common_subsequence_recursive( s1, s2, s1_len - 1, s2_len - 1 ) else: return max( length_of_longest_common_subsequence_recursive(s1, s2, s1_len - 1, s2_len), length_of_longest_common_subsequence_recursive(s1, s2, s1_len, s2_len - 1), ) def length_of_longest_common_subsequence_memoize(s1, s2, s1_len, s2_len, dp): if s1_len == 0 or s2_len == 0: return 0 if dp[s1_len][s2_len] != -1: return dp[s1_len][s2_len] if s1[s1_len - 1] == s2[s2_len - 1]: dp[s1_len][s2_len] = 1 + length_of_longest_common_subsequence_memoize( s1, s2, s1_len - 1, s2_len - 1, dp ) return dp[s1_len][s2_len] else: dp[s1_len][s2_len] = max( length_of_longest_common_subsequence_memoize( s1, s2, s1_len, s2_len - 1, dp ), length_of_longest_common_subsequence_memoize( s1, s2, s1_len - 1, s2_len, dp ), ) return dp[s1_len][s2_len] def length_of_longest_common_subsequence_top_down(s1, s2): dp = [[None for _ in range(len(s2) + 1)] for _ in range(len(s1) + 1)] # initialization for i in range(len(s1) + 1): for j in range(len(s2) + 1): if i == 0 or j == 0: dp[i][j] = 0 max_length = 0 for i in range(1, len(s1) + 1): for j in range(1, len(s2) + 1): if s1[i - 1] == s2[j - 1]: dp[i][j] = 1 + dp[i - 1][j - 1] else: dp[i][j] = max(dp[i][j - 1], dp[i - 1][j]) max_length = max(max_length, dp[i][j]) return max_length if __name__ == "__main__": s1 = "abdca" s2 = "cbda" print(length_of_longest_common_subsequence_recursive(s1, s2, len(s1), len(s2))) dp = [[-1 for _ in range(len(s2) + 1)] for _ in range(len(s1) + 1)] print(length_of_longest_common_subsequence_memoize(s1, s2, len(s1), len(s2), dp)) print(length_of_longest_common_subsequence_top_down(s1, s2))
6b8777f7efdd5308cff43c803bf8229e40404067
Tobztj/Advent-of-code
/app/Day_1/Day1.py
840
3.984375
4
from app.file_paths import day1_file as file # ------------------------------------------------------------------------------------------------------- # Function to read input file def read(path): with open(path, 'r') as day_1: nums = [int(line) for line in day_1] return nums # ------------------------------------------------------------------------------------------------------- # Day 1 Part 1 def product_numbers(): num = read(file) for x in num: if (2020 - x) in num: return (2020 - x) * x # ------------------------------------------------------------------------------------------------------- # Day 1 Part 2 def product_of_three(): num = read(file) for x in num: for y in num: if (2020 - (x + y)) in num: return (2020 - (x + y)) * x * y
95a23a4cfd11f6f4db7871cd7f7e614b47db82b1
YounessTayer/Tk-Assistant
/squirts/window/centre_window.py
459
3.796875
4
"""Centre window. Stand-alone example from Tk Assistant. Updated March 2021 By Steve Shambles stevepython.wordpress.com """ from tkinter import Tk from tkinter.ttk import Label root = Tk() root.title('Centre window on screen') root.eval('tk::PlaceWindow . Center') # This is the line msg_lbl = Label(root, text='This window should be in the ' 'centre of your screen.') msg_lbl.grid() root.mainloop()
ecc151e6a55357c75cbf4d30faada7869063e858
Harshhg/Apache_Spark
/py code/Spark SQL/Dataframe_creating_View.py
1,777
3.671875
4
#!/usr/bin/env python # coding: utf-8 # In[1]: import findspark findspark.init('/home/ec2-user/spark') # In[2]: import pyspark from pyspark import SparkContext # In[3]: sc = SparkContext() # In[4]: # Creating SparkSession bcoz this is the entry point to create DataFrame.. from pyspark.sql import SparkSession spark = SparkSession.builder.appName("My App").config("spark.some.config.option", "some-value").getOrCreate() # In[5]: # Creating a DataFrame from csv file. df = spark.read.csv("/home/ec2-user/wc.csv" , header=True, inferSchema=True) df.show() # header=True -- means it will take the first line of csv file as header or column name # inferSchema=True -- fetches the schema of the table. # In[6]: # Register the dataframe as SQL temporary view (creating table) df.createOrReplaceTempView("student") # This view is temporary(session-scoped) will disappear if session is terminated. # In[7]: # Now we can programmaticaly run SQL queries.. sqldf = spark.sql("select * from student") sqldf.show() # In[8]: # To create temporary view that is shared across all sessions and keep alive till spark application terminates - # We will create GlobalTemporary view. df.createGlobalTempView("st") # In[9]: # To use the global temporary view, we have to use it with name "global_temp.nameofview" sqldf = spark.sql("select * from global_temp.st") sqldf.show() # In[10]: # To check the global temporary view in cross sessions, we are creating new session spark.newSession().sql("select * from global_temp.st").show() # In[13]: # Now lets perform some SQL operations using spark query1 = " Select * from student where age > 20" query2 = "Select * from student order by age" # In[14]: spark.sql(query1).show() spark.sql(query2).show()
8cb04fc62782a5d76b6226aa2b25abadc67b058e
k-kushal07/Algo-Daily
/Day 25 - Two Sum.py
364
3.65625
4
def sumPair(arr, key): s = set() for i in range(0, len(arr)): temp = key - arr[i] if (temp in s): return (temp, arr[i]) s.add(arr[i]) inpArr = [int(ele) for ele in input('Enter the array element: ').split()] key = int(input('Enter the key value: ')) print(f'The pair that evaluates to {key} is {sumPair(inpArr, key)}')
6e6986413f91138a8dba20b9f26a33e6adb80160
VitorArthur/Pratica-Python
/ex035.py
415
3.796875
4
print('\033[34m-=-\033[m' * 20) print('\033[30;41mAnalizador de Triângulos\033[m') print('\033[34m-=-\033[m' * 20) r1 = float(input('Primeiro segmento: ')) r2 = float(input('Segundo segmento: ')) r3 = float(input('Terceiro segmento: ')) if r1 < r2 + r3 and r2 < r1 + r2 and r3 < r2 + r1: print('Os segmentos acima PODEM FORMAR triângulo!') else: print('Os segmentos acima NÃO PODEM FORMAR triângulos!')
de0a4864f951e2689be8d1527e96f408c20a995b
furkankocyigit/dataAIPython
/Object Oriented Programming/encapsulation.py
781
4
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Mar 22 09:45:45 2020 @author: furkan """ class BankAccount(object): def __init__(self, name, money, address): self.__money = money #private self.name = name #public self.address = address #get and set def getMoney(self): return self.__money def setMoney(self, amount): self.__money = amount #private def __increase(self, amount): self.__money += amount p1 = BankAccount("messi", 1000, "barcelona") p2 = BankAccount("neymar", 2000, "barcelona") print("get method: ",p1.getMoney()) p1.setMoney(2500) print("after set method: ",p1.getMoney()) # p1.__increase(300) # print("after inc method: ", p1.getMoney())
fdfdcf3d006000185adc2dca539964717fb7f995
finddeniseonline/sea-c34-python.old
/students/KarenWong/session05/lambda.py
221
3.734375
4
def function_builder(n): l = [] for i in range(n + 1): l.append(lambda x, y=i: x + y) return l the_list = function_builder(5) print the_list[0](2) == 2 print the_list[1](2) == 3 print the_list[5](1)
339985bfc89691b3444472358cd41e389729e147
AntonYordanov/Start
/Python/Programming Basics/Lesson 2/concatenate_data.py
193
3.765625
4
first_name = input() last_name = input() age = input() fromtown = input() print ('You are ' + first_name +' '+ last_name + ' a ' + str (age) + ' years old person ' + 'from ' + fromtown)
d0849180d1c214a08d3ee2b1eaec9c7576c75c3d
yafeile/Simple_Study
/Simple_Python/algorithm/recusion2.py
1,116
3.84375
4
#coding:utf-8 import math def recusion(data,value,start=0): ''' 本函数是利用递归法来实现对数组中元素的查找工作。 当数组索引并没有超过数组长度的时候,对数组中的元素进行递归的查找。 当数组的元素被查找到的时候,将其返回。 当数组的元素大于目标元素时,将中间数值的索引减一。 例如数组的长度为100,从0到100,而此时元素值是50,而目标元素值是40,此时将在值0~49之间进行查找。 当数组的元素小于目标元素时,将中间数值的索引加一。然后再次进入循环,类似二分法缩小了查找的范围。 例如数组的长度为100,从0到100,而此时元素值是50,而目标元素值是60,此时将在值51~100之间进行查找。 ''' length=len(data) num=0 while start < length: middle=start+int(math.floor(length-start)/2) if data[middle]==value: print 'Has Found',num,'times' return middle+1 elif(data[middle] > value): length=middle-1 else: start=middle+1 num +=1 return False print recusion(range(-1,100),2)
04d9613e77704ab57f9e572f939d3af5fd950c09
aralyekta/METU
/CENG111/Recu/graycode.py
373
3.5625
4
def n_bit_Gray_code(n): list_to_return = [] if n == 1: return ["0","1"] returned_list = n_bit_Gray_code(n-1) for elem in returned_list: elem_to_append = "0"+elem list_to_return.append(elem_to_append) elem_to_append = "1"+elem list_to_return.append(elem_to_append) return list_to_return print (n_bit_Gray_code(3))
90bc5798e1ba2a274c5e8f02a13c2e8c89835854
wintercameearly/I4G
/week3assignment.py
2,035
4.1875
4
# "in" and "not in" Logical Operators ? # These logical operators are responsible for checking whether a particular condition is true or not, and then returning the boolean status of the condition # The in operator checks if a value is in a sequence and not in is responsible for checking if a value is not in a subsequence # EXAMPLE : THe code below checks whether the letter "w" is in a word oin the list, then returns the number of words in the list with that particular letter items = ["whirring", "wow!", "calendar", "wry", "glass", "", "llama","tumultuous","owing"] acc_num = 0 for word in items: if "w" in word: acc_num = acc_num +1 # How does precedence of operators work ? # In an expression, the Python interpreter evaluates operators with higher precedence first. # for example, the multiplication operation is interpreted before the addition in a simple equation of addition and multiplication only. # Multiplication get evaluated before the addition operation 5 + 5 * 3 # Result: 20 # Parentheses () overriding the precedence of the arithmetic operators (5 + 5) * 3 # Output: 30 # Conditional Execution statements ? : # Conditional statements are statements that can be used to check if conditions exist, then return a boolean, and based on the returned boolean, execute a block of code or not # Conditional operators in ptyhon are if, else, elif # How does accumulator pattern work ? # Accumulator pattern refers to the process of iterating and updating a variable # Accumulator pattern is often used to count instances of a sequence or of elements in a sequence # An EXAMPLE of accumulator pattern can be seen below, counting the number of vowels in each word in the sentence s . s = "singing in the rain and playing in the rain are two entirely different situations but both can be fun" vowels = ['a','e','i','o','u'] # Write your code here. num_vowels = 0 for ele in s: for vowel in vowels: if vowel in ele: num_vowels = num_vowels + 1
cd1b56b6906a6cfa49e96aaa067ac1d254473e35
itry1997/python_work_ol
/3_4嘉宾名单.py
880
3.875
4
lists=['Liuxuan','David','Sherry'] message=lists[0]+','+lists[1]+' and '+lists[2]+",would you like to have dinner with me?" print(message) cant_come='David' print(cant_come+" can't come.") latest_invited="Cuiwei" lists.remove(cant_come) lists.append(latest_invited) message=lists[0]+','+lists[1]+' and '+lists[2]+",would you like to have dinner with me?" print(message) lists.insert(0,'Xiaoming') message=lists[0]+','+lists[1]+','+lists[2]+' and '+lists[-1]+",would you like to have dinner with me?" print(message) bad_news="Sorry,I can have dinner with only two people." print(bad_news) name_1=lists.pop() print('Sorry '+name_1+" I can't have dinner with you.") name_2=lists.pop() print('Sorry '+name_2+" I can't have dinner with you.") print(lists[0]+",you are still invited.") print(lists[-1]+",you are still invited.") del lists[0] print(lists) del lists[0] print(lists)
5d812db213387fd6cd89fd1a1d9f472c81a1e5d1
snsunlee/LeetCode
/字符串/14.最长公共前缀.py
1,274
3.515625
4
# # @lc app=leetcode.cn id=14 lang=python3 # # [14] 最长公共前缀 # # https://leetcode-cn.com/problems/longest-common-prefix/description/ # # algorithms # Easy (32.68%) # Total Accepted: 72.4K # Total Submissions: 220K # Testcase Example: '["flower","flow","flight"]' # # 编写一个函数来查找字符串数组中的最长公共前缀。 # # 如果不存在公共前缀,返回空字符串 ""。 # # 示例 1: # # 输入: ["flower","flow","flight"] # 输出: "fl" # # # 示例 2: # # 输入: ["dog","racecar","car"] # 输出: "" # 解释: 输入不存在公共前缀。 # # # 说明: # # 所有输入只包含小写字母 a-z 。 # # class Solution: def longestCommonPrefix(self, strs: List[str]) -> str: if len(strs)==0 or '' in strs: return '' strs.sort(key=lambda x:len(x))##min_len sort subString=strs[0][0] res=all(subString== item[0] for item in strs[1:]) if not res: return '' for i in range(len(strs[0])): subString=strs[0][:i+1] len_subString=len(subString) res=all([subString in everString[:len_subString] for everString in strs[1:]]) if not res: return subString[:-1] return subString
4c870df1cb07fc75fa02e08aa90ac9c10fe68d48
pranay22/Cryptography-1
/Week 5/Problem 1/run.py
1,184
3.734375
4
#!/usr/bin/env python # Cryptography 1 - Stanford University [Week 5 - Question 1] import sys import gmpy2 P = 13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946569946433649006084171 G = 11717829880366207009516117596335367088558084999998952205599979459063929499736583746670572176471460312928594829675428279466566527115212748467589894601965568 H = 3239475104050450443565264378728065788649097520952449527834792452971981976143292558073856937958553180532878928001494706097394108577585732452307673444020333 def trivial_calculate(p, g, h): x = 1 while x <= 2**40: if pow(g, x, p) == h: return x x += 1 def meetinthemiddle_calculate(p, g, h, maxexp=40): B = gmpy2.mpz(2**(maxexp/2)) g = gmpy2.mpz(g) h = gmpy2.mpz(h) p = gmpy2.mpz(p) middle = {} for x1 in range(B): middle[gmpy2.divm(h, gmpy2.powmod(g, x1, p), p)] = x1 for x0 in range(B): v = gmpy2.powmod(g, B*x0, p) if middle.has_key(v): x1 = middle[v] return B*x0+x1 return None def main(argv): x = meetinthemiddle_calculate(P, G, H) print "x = {0}".format(x) if __name__ == "__main__": main(sys.argv)
6386cc4ec830f86654e404037be56550f108e001
AsyaAndKo/RTSlab1.1
/lab1.py
1,132
3.8125
4
import numpy as np import random from math import sin import matplotlib.pyplot as plt # expected value def expectation(x, N): return np.sum(x)/N # standard deviation def dispersion(x, mx, N): return np.sum((x - mx)**2)/N def frequency(n, w): return w - n * number # values for 11 variant n = 10 w = 1500 N = 256 number = w/(n - 1) # frequency w_values = [frequency(n, w) for n in range(n)] harmonics = np.zeros((n, N)) resulted = np.array([]) # generating harmonics for n in range(n): amplitude = random.choice([i for i in range(-10, 10) if i != 0]) phi = random.randint(-360, 360) for t in range(N): harmonics[n, t] = amplitude * sin(w_values[n] * t + phi) # this part is showing plots for all generated harmonics, we don't really need them but still # for i in harmonics: # plt.plot(i) # plt.show() # last harmony for i in harmonics.T: resulted = np.append(resulted, np.sum(i)) plt.figure(figsize=(20, 15)) plt.plot(resulted) plt.grid(True) plt.show() mx = expectation(resulted, N) dx = dispersion(resulted, mx, N) print(f"Expected value: {mx}") print(f"Deviation: {dx}")
9bc84be8c224ed258004bc793ec2019231a4f153
Chandler-Song/sample
/python/feature/do_slice.py
1,629
3.96875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- L=['Michael','Sarah','Tracy','Bob','Jack'] # Python提供了切片(Slice)操作符 # L[0:3]表示,从索引0开始取,直到索引3为止,但不包括索引3。即索引0,1,2,正好是3个元素。 print('01.',L[0:3]) # 如果第一个索引是0,还可以省略: print('02.',L[:3]) # 也可以从索引1开始,取出2个元素出来: print('03.',L[1:3]) # 取最后两个 print('04.',L[-2:]) # 取倒数2,3个 print('05.',L[-3:-1]) # 记住倒数第一个元素的索引是-1。 # 切片操作十分有用。我们先创建一个0-99的数列: L=list(range(100)) # 前11-20个数 print('06.',L[10:20]) # 前10个数,每两个取一个 print('07.',L[:10:2]) # 所有数,每5个取一个 print('08.',L[::5]) # 甚至什么都不写,只写[:]就可以原样复制一个list print('09.',L[:]) # tuple也是一种list,唯一区别是tuple不可变。因此,tuple也可以用切片操作,只是操作的结果仍是tuple print('10.',(1,2,3,4,5)[1:2]) # 字符串'xxx'也可以看成是一种list,每个元素就是一个字符。因此,字符串也可以用切片操作,只是操作结果仍是字符串 print('11.','ABCDEFG'[3:4]) # 在很多编程语言中,针对字符串提供了很多各种截取函数(例如,substring),其实目的就是对字符串切片。Python没有针对字符串的截取函数,只需要切片一个操作就可以完成,非常简单。 # 有了切片操作,很多地方循环就不再需要了。Python的切片非常灵活,一行代码就可以实现很多行循环才能完成的操作。
a209464bac0d41987cf1e715c0b0cd93f9d48c92
vanhawn/python_study
/str_list_tuple_dictionary/高阶函数_sorted,lambda.py
1,075
3.578125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #sorted() 函数就可以对list进行排序 l = sorted([1,5,8,77,-11,-78]) #sorted()函数也是一个高阶函数,它还可以接收一个key函数来实现自定义的排序 l1 = sorted([1,5,8,77,-11,-78],key=abs) #abs是绝对值 #再看一个字符串排序的例子 l2 = sorted(['aVB','ve','VE','zg'],key=str.lower) #str.lower是大写转小写 #要进行反向排序,不必改动key函数,可以传入第三个参数reverse=True l3 = sorted(['aVB','ve','VE','zg'], key=str.lower, reverse = True) #lambda (匿名函数) #关键字lambda表示匿名函数,冒号前面的x表示函数参数 #匿名函数有个限制,就是只能有一个表达式,不用写return,返回值就是该表达式的结果 l4 = list(map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9])) #匿名函数lambda x: x * x 实际上就是: def f(x): return x * x #也可以把匿名函数作为返回值返回 def build(x, y): return lambda: x * x + y * y l = build(22,44) print(l())
c011d71c9d36572cb5402624364876045d97d5cc
Rodrigo-Novas/python
/udemy/ejercicios/ejerciciosParte1.py
1,650
4.125
4
import os #Multiplicar dos numeros sin usar la multiplicacion def multiplicarSinMulti(*numArgs): cantidad=numArgs[1] multi=0 for x in range(cantidad): multi=numArgs[0]+multi return multi #print(multiplicarSinMulti(6,3)) #ingresar apellido y nombre e imprimirlos al reves def reversear(nombre, apellido): concat= f"{nombre} {apellido}" print(concat[::-1]) #reversear("Rodrigo", "Novas") #sacar numero par def esPar(numero): if numero%2==0: print("Es par") else: print("No es par") #esPar(4) #escribir una funcion que indique cuantas vocales tiene una palabra def contadorVocales(palabra="murcielago"): contadorVoc=0 for x in range(len(palabra)): if palabra[x]== "a" or palabra[x] =="e" or palabra[x]== "i" or palabra[x] =="o" or palabra[x] =="u": contadorVoc +=1 return contadorVoc #print(contadorVocales()) #Escribir una funcion que pida nombre y apellido y los vaya agregando a un archivo def nombreApp(): while True: nombre= input("Escribe tu puto nombre: ") apellido= input("Escribe tu fucking apellido: ") if os.path.exists("archivoNombres.txt"): with open("archivoNombres.txt", "a") as f: f.writelines(f"{nombre} {apellido}\n") else: with open("archivoNombres.txt", "w") as f: f.writelines(f"{nombre} {apellido}") salir= input("Desea seguir ingresando nombres? s") if salir.upper() != "S": break print("Adios") try: nombreApp() except Exception as ex: print("No se pudo realizas", ex)
e139e5f0a42a9baa227cbd7e183d5f6cd27967ed
MasterMind7777777/hw_python_oop
/homework.py
4,715
3.890625
4
import datetime as dt # for data type to be used # for showing type of the variable from typing import Dict, List, Optional, Tuple class Calculator(): """Main class for both calculators. Parent class to CashCalculator and CaloriesCalculator.""" def __init__(self, limit: float) -> None: self.limit = limit self.records: List['Record'] = [] def add_record(self, inp_record: 'Record') -> bool: """Adds object of type record to the list.""" self.records.append(inp_record) def get_today_stats(self) -> float: """Counts amount of money/calories used used up in a day.""" # Summ all records of amount (callories/Cash) where day = today. dt_now = dt.datetime.now() amount_records: List[float] = [ record.amount for record in self.records if record.date == dt_now.date()] count_day: float = sum(amount_records) return count_day def get_week_stats(self): """Counts amount of money/calories used used up in a week.""" dt_now = dt.datetime.now() dt_now_date = dt_now.date() week_ago: dt.datetime = dt_now - dt.timedelta(days=7) week_ago: dt.date = week_ago.date() count_week: float = 0 # Summ all records of amount (callories/Cash) where # day = one of the previous 7 days inclusive. for record in self.records: if (week_ago < record.date <= dt_now_date): count_week = count_week + record.amount return count_week def today_remained(self): """Calculates money/calories left below limit""" remaining: float = self.limit - self.get_today_stats() return(remaining) class CashCalculator(Calculator): """Representing calculator for money management.""" # Unit test accept only this rates??? USD_RATE = 60.00 EURO_RATE = 70.00 RUB_RATE = 1.00 currencys: Dict[str, Tuple[str, float]] = { 'eur': ('Euro', EURO_RATE), 'usd': ('USD', USD_RATE), 'rub': ('руб', RUB_RATE)} def converter(self, inpAmount: float, rate: float) -> float: """Converst rubles to dollars or euro using information from yandex.ru and returns answer to 2dp.""" converted = inpAmount / rate converted = (round(converted, 2)) return converted def get_today_cash_remained(self, currency: str) -> str: """Shows how much money is left to spend for today.""" remaining = self.today_remained() debt: float = abs(remaining) # Convert currency and rename for better look. # Raises error if gets unknown currency. try: currencys_out = self.currencys[currency] cur_out = currencys_out[1] remaining = self.converter(remaining, cur_out) debt = self.converter(debt, cur_out) currency_name = currencys_out[0] except KeyError: raise ValueError('Такая валюта не доступна.') # Compere's money spends today and comperes to limit that was set. # Returns msg string accordingly. if remaining > 0: return f'На сегодня осталось {remaining} {currency_name}' elif remaining == 0: return 'Денег нет, держись' else: return f'Денег нет, держись: твой долг - {debt} {currency_name}' class CaloriesCalculator(Calculator): """Representing calculator for managing calories""" def get_calories_remained(self) -> str: """Shows how many calories are stil left to eat""" remaining = self.today_remained() # Compere's calories consumed today and comperes to limit that was set. # Returns msg string accordingly. if remaining > 0: return ('Сегодня можно съесть что-нибудь ещё, ' f'но с общей калорийностью не более {remaining} кКал') return 'Хватит есть!' class Record: """Class representing single record with fields: amount, comment, date""" date = dt.datetime.now().date() def __init__(self, amount: float, comment: str, date: Optional[str] = None) -> None: self.amount = amount self.comment = comment if type(date) is str: date_format = '%d.%m.%Y' date = (dt.datetime.strptime(date, date_format)).date() else: date = dt.datetime.now().date() self.date = date
cb19549a3637fe11dd866798ac0b40b841e48527
dmkalash/TechnoSphere-information-Retrieval
/Spellchecker/spellchecker/heap.py
7,717
4.15625
4
class MinHeap: def __init__(self, max_heap_size, init=[-1e8, -1, -1, '']): """ On this implementation the heap list is initialized with a value """ self.init = init self.heap_list = [init] + [None] * max_heap_size # cur_weight, node_num, origin_i, preffix self.current_size = 0 self.map = dict() # {(init[2], init[3]) : 0} # (origin_i, preffix): heap_node_num self.max_heap_size = max_heap_size def merge(self, heap_b): # TODO: new_heap можно через обычный список делать и индексировать с 0 for elem in heap_b.heap_list[1: heap_b.current_size + 1]: self.insert(elem) def sift_up(self, i): """ Moves the value up in the tree to maintain the heap property. """ # print('sift_up') while i // 2 > 0: if self.heap_list[i][0] < self.heap_list[i // 2][0]: self.map_swap(i, i // 2) self.heap_list[i], self.heap_list[i // 2] = self.heap_list[i // 2], self.heap_list[i] i = i // 2 def insert(self, k): """ Inserts a value into the heap """ # print(my_heap.heap_list, self.map.get((k[2], k[1]), None)) heap_node_num = self.map.get((k[2], k[3]), None) if heap_node_num is None: self.current_size += 1 self.heap_list[self.current_size] = k self.map[(k[2], k[3])] = self.current_size self.sift_up(self.current_size) if self.current_size >= self.max_heap_size: # TODO: может быть по порогу лучше отсекать(правда мб будет 0 вариантов), тк # сейчас мы не максимальный штраф удаляем, а рандомный в конце списка # print('DELETE!') # print( len(self.map, len(self.heap_list)) ) del self.map[ (self.heap_list[self.current_size][2], self.heap_list[self.current_size][3])] # TODO: change # del self.heap_list[-1] self.current_size -= 1 # print( len(self.map, len(self.heap_list)) ) # print() elif k[0] < self.heap_list[heap_node_num][0]: self.heap_list[heap_node_num] = k self.sift_up(heap_node_num) def sift_down(self, i): # print('sift_down') while i * 2 <= self.current_size: mc = self.min_child(i) if self.heap_list[i][0] > self.heap_list[mc][0]: self.map_swap(i, mc) self.heap_list[i], self.heap_list[mc] = self.heap_list[mc], self.heap_list[i] i = mc else: break def min_child(self, i): if i * 2 + 1 > self.current_size: return i * 2 else: if self.heap_list[i * 2] < self.heap_list[i * 2 + 1]: return i * 2 else: return i * 2 + 1 def map_swap(self, i, j): self.map[(self.heap_list[i][2], self.heap_list[i][3])], \ self.map[(self.heap_list[j][2], self.heap_list[j][3])] = j, i def __len__(self): return self.current_size def delete_min(self): root = self.heap_list[1] self.heap_list[1], self.heap_list[self.current_size] = self.heap_list[self.current_size], self.heap_list[1] self.map_swap(1, self.current_size) del self.map[(self.heap_list[self.current_size][2], self.heap_list[self.current_size][3])] self.current_size -= 1 self.sift_down(1) return root # def free(self): # del self.heap_list # del self.map # # self.heap_list = self.init # cur_weight, node_num, origin_i, preffix # self.current_size = 0 # self.map = {(t[2], t[3]): 0} # (origin_i, trie_node_num): heap_node_num # def get_head_origin_index(self): # if self.curent_size > 0: # return self.heap_list[1][2] # return None class QueryMinHeap: def __init__(self, max_heap_size, init=[-1e8, [-1]]): """ On this implementation the heap list is initialized with a value """ self.init = init self.heap_list = [init] + [None] * max_heap_size # cur_weight, node_num, origin_i, preffix self.current_size = 0 self.map = dict() # {(init[2], init[3]) : 0} # (origin_i, preffix): heap_node_num self.max_heap_size = max_heap_size def merge(self, heap_b): # TODO: new_heap можно через обычный список делать и индексировать с 0 for elem in heap_b.heap_list[1: heap_b.current_size + 1]: self.insert(elem) def sift_up(self, i): """ Moves the value up in the tree to maintain the heap property. """ # print('sift_up') while i // 2 > 0: if self.heap_list[i][0] < self.heap_list[i // 2][0]: self.map_swap(i, i // 2) self.heap_list[i], self.heap_list[i // 2] = self.heap_list[i // 2], self.heap_list[i] i = i // 2 def insert(self, k): """ Inserts a value into the heap """ # print(my_heap.heap_list, self.map.get((k[2], k[1]), None)) heap_node_num = self.map.get(k[1], None) if heap_node_num is None: self.current_size += 1 self.heap_list[self.current_size] = k self.map[k[1]] = self.current_size self.sift_up(self.current_size) if self.current_size >= self.max_heap_size: del self.map[self.heap_list[self.current_size][1]] self.current_size -= 1 elif k[0] < self.heap_list[heap_node_num][0]: self.heap_list[heap_node_num] = k self.sift_up(heap_node_num) def sift_down(self, i): # print('sift_down') while i * 2 <= self.current_size: mc = self.min_child(i) if self.heap_list[i][0] > self.heap_list[mc][0]: self.map_swap(i, mc) self.heap_list[i], self.heap_list[mc] = self.heap_list[mc], self.heap_list[i] i = mc else: break def min_child(self, i): if i * 2 + 1 > self.current_size: return i * 2 else: if self.heap_list[i * 2] < self.heap_list[i * 2 + 1]: return i * 2 else: return i * 2 + 1 def map_swap(self, i, j): # t = len(self.map) # ind_i = # ind_j = self.map[self.heap_list[i][1]], self.map[self.heap_list[j][1]] = j, i def __len__(self): return self.current_size def delete_min(self): # if len(self.heap_list) == 1: # raise ValueError('empty heap') root = self.heap_list[1] self.heap_list[1], self.heap_list[self.current_size] = self.heap_list[self.current_size], self.heap_list[1] self.map_swap(1, self.current_size) del self.map[self.heap_list[self.current_size][1]] self.current_size -= 1 self.sift_down(1) return root # def free(self): # del self.heap_list # del self.map # # self.heap_list = self.init # cur_weight, node_num, origin_i, preffix # self.current_size = 0 # self.map = {(t[2], t[3]): 0} # (origin_i, trie_node_num): heap_node_num # def get_head_origin_index(self): # if self.curent_size > 0: # return self.heap_list[1][2] # return None
04940f08d7fc56a63aba7b9f7c923999dbead593
tonydavidx/Python-Crash-Course
/chapter7/counting.py
258
3.9375
4
# number = 1 # while number <= 10: # print(number) # number += 1 # number = 0 # while number < 10: # number += 1 # if number % 2 != 0: # continue # print(number) number = 0 while number < 55: number += 1 print(number)
6167fa0f57d5677d77da1b7611d0f264b0da9ff3
ebsbfish4/classes_lectures_videos_etc
/video_series/sentdex_python3_basic/python_files/function_parameters.py
219
4.03125
4
#! python3 def simple_addition(num1,num2): answer = num1 + num2 print('num 1 is',num1) print('answer =',answer) simple_addition(5,3) # If you want to make sure you print 3 simple_addition(num2=5, num1=3)
1904fa172490da1f5f13bd725600d02e0bfb0644
matesmoliere/pythonlager
/19.99cervezas.py
1,041
4
4
def noventainueve_cervezas(): ''' Es un canción anglosajona que va cantando el número de cervezas que se van bebiendo, y las que van quedando. Así, hasta llegar a cero cervezas: '99 bottles on the wall, 99 bottles of beer. Take one down, pass it around, 98 bottles on the wall' (99 botellas en la pared, 99 botellas de cerveza. Coge una y pásala, 98 botellas en la pared ) ''' x= 99 while x != 0: print(x, 'botellas de cerveza en la pared,') x -= 1 print('coge una y pásala, quedan', x, 'botellas') print() ## x = 1 ## while x != 101: ## print(x,'elefantes se columpiaban,\n como vieron que resistían\n fueron a llamar a otro elefante') ## x += 1 ## print() ## if x == 100: ## print('Ya no!,Ploff!') ## break ## ## i = 99 ## while i > 0: ## print(i,'bottles on the wall, ',i,' bottles of beer') ## i = i-1 ## print('Take one down, pass it around, ',i,' bottles on the wall')
e5c3ddac68744ead76c5becc99fc193221f698a3
RafaelSilva7/seq-align
/matriz_score/matrizScore.py
1,121
3.734375
4
def matriz_score(x, y, matriz): """ Calcula o valor de score (match/mismatch) do alinhamento entre os dois aminoacidos com base no valores da Blosum62 :param x: primeiro aminoacido (linha) :param y: segundo aminoacido (coluna) :param matriz: nome da tabela de score a ser utilizado pela funcao :return: retorna o valor do score (na forma de inteiro) """ if matriz == "global": return score_global(x, y) local = "./matrizes/" + matriz + ".txt" with open(local) as file: amino_acids = " ARNDCQEGHILKMFPSTWYVBZX*" i = 0 while amino_acids[i] != x: i += 1 j = 0 while amino_acids[j] != y: j += 1 j *= 3 for k in range(0, i + 1): amino_acids = file.readline() score = amino_acids[j - 1] + amino_acids[j] return int(score) def score_global(x, y): """ Verifica o valor de scoring dos aminoacidos informados :param x: primeiro aminoacido :param y: segundo aminoacido :return: valor de scoring """ if x == y: return 5 return -4
cd81e784543ed2bb0e70a2108efdc9ebeb4ae952
RyanLongRoad/Iteration
/n! development exercise.py
219
3.578125
4
#Ryan Cox #16/10/14 (fixed on 19/20/10) #Development exercis - factorial program n = int(input("input value of n: ")) if n>=0: f = 1 while (n > 0): f = f * n n = n - 1 print(f)
36629b29b00afe409474c3b82371050eca44dfc2
makrandp/python-practice
/Other/CoderPro/AddTwoLinkedLists.py
2,773
3.984375
4
''' #4 Given two numbers represented in reverse as linked list, add the two numbers together. Return in the form of a reversed linked list. Assuming no leading zeros ''' from typing import List # Recurse down to the bottom, recurse back up adding the numbers together # 345 + 2567 = # 5 -> 4 -> 3 # 7 -> 6 -> 5 -> 2 # 2 -> 1 -> 9 -> 2 # Time complexity is O(n + m) where n is the length of the first number and m is the length of the second number. # Space complexity is also O(n + m) where, again, n is the length of the first number and m is the length of the second number. # Overall solution is iteratively, not recursive, which preserves the stackspace from recursive abuse. class LinkedListNode(): def __init__(self, next=None, val: int=0): self.next, self.val = next, val def __str__(self): return str(self.val) + ('' if not self.next else str(self.next)) class Solution(): def addTwoLinkedLists(self, num1: LinkedListNode, num2: LinkedListNode) -> LinkedListNode: # Carry value c = 0 # Empty header node outputNode = LinkedListNode() nodePointer = outputNode # While both digits are valid, we iterate through both linked lists adding the numbers together while num1 or num2: num1Val = (num1.val if num1 else 0) num2Val = (num2.val if num2 else 0) # Adding the two numbers together including the carry digit value = (num1Val + num2Val + c) % 10 # Setting our new carry c = 1 if num1Val + num2Val + c >= 10 else 0 # Setting our digit into the linked list nodePointer.next = LinkedListNode(val=value) nodePointer = nodePointer.next # Moving our pointers forward num1 = (num1.next if num1 else None) num2 = (num2.next if num2 else None) return outputNode.next # Helper test function. def buildLinkedListFromList(values: List[int]) -> LinkedListNode: header = LinkedListNode() pointer = header for value in values: pointer.next = LinkedListNode(val=value) pointer = pointer.next return header.next s = Solution() # Two normal test cases num1 = buildLinkedListFromList([5,4,3]) num2 = buildLinkedListFromList([7,6,5,2]) print(str(s.addTwoLinkedLists(num1,num2))) num1 = buildLinkedListFromList([7,9,8]) num2 = buildLinkedListFromList([1,2,3,4,5,6,7,8,9]) print(str(s.addTwoLinkedLists(num1,num2))) # Some weird test cases num1 = buildLinkedListFromList([]) num2 = buildLinkedListFromList([1,2,3,4,5,6,7,8,9]) print(str(s.addTwoLinkedLists(num1,num2))) num1 = buildLinkedListFromList([5,1]) num2 = buildLinkedListFromList([0]) print(str(s.addTwoLinkedLists(num1,num2)))
64e426cb01f490277713ec866ba3c5c0ebb3a848
ksayee/programming_assignments
/python/CodingExercises/RearrangeArrayMaxMinForm.py
766
4.125
4
# Rearrange an array in maximum minimum form | Set 1 # Given a sorted array of positive integers, rearrange the array alternately i.e # first element should be maximum value, second minimum value, third second max, fourth second min and so on. def RearrangeArrayMaxMinForm(ary): lst=[0]*len(ary) min=0 max=len(ary)-1 flg=True for i in range(0,len(ary)): if flg==True: lst[i]=ary[max] max=max-1 flg=False else: lst[i]=ary[min] min=min+1 flg=True return lst def main(): ary=[1, 2, 3, 4, 5, 6, 7] print(RearrangeArrayMaxMinForm(ary)) ary = [1, 2, 3, 4, 5, 6] print(RearrangeArrayMaxMinForm(ary)) if __name__=='__main__': main()
1791e172bc2791a35e8622ca0a340801e3f8a679
patrickrewers/Project3
/project3.py
35,332
3.984375
4
# # CS 177 # Patrick Rewers, Nicole Gillespie, Shelby Nelson # # The purpose of this program is to run and display a maze game # where users try to solve the maze in as few members as # possible. The game tracks players' names, moves, and scores. # # Import Graphics library from graphics import Point, Rectangle, GraphWin, Line, Entry, Text, Circle, Polygon from random import random, randint, choice from datetime import datetime from time import sleep # ==================================[ MAIN }=================================== # Define main() function def main(): # Draw the Game Panel game_panel = drawGamePanel() # Define current game settings and set score to 0 close = False in_game = False score = 0 # Create dummy variables to prevent errors when calling function field = "" check_second = datetime.now().second # Draw initial game panel new_player_text, score_box, score_text, phase, scores = drawInitialPanel(game_panel) # Loop game functions until user clicks "Exit" button while close is False: # Get panel location and x and y coordinates of click panel, x, y = getClick(game_panel, field, in_game) # Check if user clicked "Exit" button close = checkExit(panel, x, y) # Change score in top score box every second second = datetime.now().second if second != None and second > check_second: changeScores(scores, score_text) check_second = second # Check if user clicked in game panel if panel == "game_panel": # Whenever user presses the green button, change the game mode if checkGreenButton(panel, x, y) is True: # Clicking during Initial phase changes panel to New Player # phase if phase == "initial": player_name_text, player_name_entry, phase = drawNewPlayerPanel( new_player_text, score_box, score_text, game_panel, phase) # Clicking during New Player phase launches the game elif phase == "new_player": in_game = True player_name_display, player_name, reset_button, reset_text, current_score_text, current_score_display, phase = drawInGamePanel(new_player_text, player_name_entry, game_panel, score) field, pete, sensors, spin_square,blackcenter1, blackcenter2,goodsensors = drawFieldPanel() # Clicking while in game close the game and reverts panel to New # Player panel elif phase == "in_game": if in_game is True: field.close() score = 0 player_name_display.undraw() current_score_display.undraw() in_game = False player_name_text, player_name_entry, phase = drawNewPlayerPanel( new_player_text, score_box, score_text, game_panel, phase) # Whenever the user presses the reset button, close the game and # draw Initial panel if checkResetButton(panel, phase, x, y) is True: field.close() score = 0 current_score_text, current_score_display = updateScore(current_score_text, current_score_display, game_panel, score) field, pete, sensors, spin_square, blackcenter1,blackcenter2,goodsensors = drawFieldPanel() # Check if user clicked in field panel if panel == "field": # Move pete based on click pete, pete_center, score = movePete(pete, field, x, y, score, sensors, spin_square, blackcenter1, blackcenter2, goodsensors) # Update score with every click during game if phase == "in_game": # If score is less than 0 (crossing good sensor with a score of # 0, set score back to 0) if score < 0: score = 0 current_score_text, current_score_display = updateScore(current_score_text, current_score_display, game_panel, score) # Check if user won game, and set close to the result if checkWinGame(pete_center) is True: close = endGame(field, game_panel, player_name, score) # When user close condition is true, close both panels game_panel.close() if in_game is True: field.close() # =========================[ GAME PANEL ELEMENTS ]============================= # Define gamePanel() function def drawGamePanel(): # Creates gray Game Panel window game_panel = GraphWin("Game Panel", 300, 300) game_panel.setBackground("gray") # Creates title text with background title_background = Rectangle(Point(0, 0), Point(300, 40)) title_background.setFill("white") title_background.draw(game_panel) title_text = Text(Point(150, 20), "BoilerMazer") title_text.setSize(30) title_text.setStyle("bold") title_text.draw(game_panel) # Creates exit button and text exit_button = Rectangle(Point(250, 260), Point(300, 300)) exit_button.setFill("red") exit_button.draw(game_panel) exit_text = Text(Point(275, 281), "EXIT") exit_text.setSize(14) exit_text.draw(game_panel) # Creates green button, which will be used for new player and start options green_button = Rectangle(Point(100, 260), Point(200, 300)) green_button.setFill("green") green_button.draw(game_panel) return game_panel # Define drawScoreDisplay() function def drawScoreDisplay(game_panel): # Draws box that serves as the background the score displays score_box = Rectangle(Point(50, 155), Point(250, 240)) score_box.setFill("white") score_box.draw(game_panel) # Call readScores() function, and store top 4 scores from topscores.txt top_scores = readScores() # Print title for top scores table scores = ["TOP SCORES", "=========="] # For each of the top scores, create a string with the name and score for element in top_scores: # Convert tuple to list element = list(element) # Loop through name and score for each player for item in element: # Assign name to name if type(item) == str: name = item # Convert score to int and assign to score elif type(item) == int: score = str(item) # Create a string from the name and score with space between elements string = name + " " + str(score) # Add player to scores list scores.append(string) # Create a text object of the top scores title and players and draw in game # panel score_text = Text(Point(150, 198), "\n".join(scores[:6])) score_text.draw(game_panel) # Return objects return (score_box, score_text, scores) # Define drawPlayerText() function def drawPlayerText(game_panel): # Create and stylize "NEW PLAYER" text over green button new_player_text = Text(Point(150, 281), "NEW PLAYER") new_player_text.setSize(14) new_player_text.draw(game_panel) # Return objects return (new_player_text) # Define drawPlayerNameEntry() function def drawPlayerNameEntry(game_panel): # Creates text prompting user for player name player_name_text = Text(Point(80, 70), "Player Name:") player_name_text.setStyle("bold") player_name_text.setSize(14) player_name_text.draw(game_panel) # Provides an entry box for user to enter player name player_name_entry = Entry(Point(195, 70), 18) player_name_entry.setFill("white") player_name_entry.draw(game_panel) # Return objects return player_name_text, player_name_entry # Define drawPlayerNameDisplay() function def drawPlayerNameDisplay(player_name_entry, game_panel): # Takes player name from entry box and creates Text object with it player_name = player_name_entry.getText() player_name_entry.undraw() player_name_display = Text(Point(195, 70), player_name) player_name_display.setSize(14) player_name_display.draw(game_panel) # Return objects return player_name_display, player_name # Define undrawPlayerNameDisplay() function def undrawPlayerNameDisplay(player_name_text, player_name_display): # Undraws player name Text objects player_name_text.undraw() player_name_display.undraw() # Define drawCurrentScore() function def drawCurrentScore(game_panel, score): # Draws and decorates score Text objects current_score_text = Text(Point(102, 120), "Score:") current_score_text.setStyle("bold") current_score_text.setSize(14) current_score_text.draw(game_panel) current_score_display = Text(Point(195, 120), score) current_score_display.setStyle("bold") current_score_display.setSize(14) current_score_display.draw(game_panel) # Return objects return current_score_text, current_score_display # Define undrawCurrentScore() function def undrawCurrentScore(current_score_text, current_score_display): # Undraws score Text objects current_score_text.undraw() current_score_display.undraw() # Define drawResetButton() function def drawResetButton(game_panel): # Creates yellow reset button to create new game with same player reset_button = Rectangle(Point(0, 260), Point(50, 300)) reset_button.setFill("yellow") reset_button.draw(game_panel) reset_text = Text(Point(25, 281), "RESET") reset_text.setSize(14) reset_text.draw(game_panel) # Return objects return reset_button, reset_text # Define undrawResetButton() function def undrawResetButton(reset_button, reset_text): # Undraws the reset button reset_button.undraw() reset_text.undraw() # Define drawSensors() function def drawSensors(field): # Set initial coordinates to potentially draw sensors and empty list # of sensor locations x = 40 y = 40 sensors = [] goodsensors=[] # Initialize loop to create horizontal sensors for column in range(10): for row in range(10): # Create random number between 0 and 1 h_chance_border = random() v_chance_border = random() # Creates 40% chance horizontal sensor will be drawn if h_chance_border >= 0.6: # Define, draw, and append location of sensor horizontal_sensor = Rectangle(Point(x-35.5, y), Point(x-4.5, y)) horizontal_sensor.setWidth(2.5) horizontal_sensor.setOutline("orange") horizontal_sensor.draw(field) h_x = horizontal_sensor.getCenter().getX() h_y = horizontal_sensor.getCenter().getY() sensors.append([h_x, h_y]) # Creates 40% chance horizontal sensor will be drawn if v_chance_border >= 0.6: # Define, draw, and append location of sensor vertical_sensor = Rectangle(Point(x, y-35.5), Point(x, y-4.5)) vertical_sensor.setWidth(2.5) vertical_sensor.setOutline("orange") vertical_sensor.draw(field) v_x = vertical_sensor.getCenter().getX() v_y = vertical_sensor.getCenter().getY() sensors.append([v_x, v_y]) # Move to next row y += 40 # Set back to first row after finishing final row y = 40 # Move to the next column x += 40 x=40 y=40 # Initialize loop to create good horizontal sensors for column in range(9): for row in range(9): # Create random number between 0 and 1 h_chance_border = random() v_chance_border = random() # Creates 40% chance horizontal sensor will be drawn if h_chance_border <= .25: # Define, draw, and append location of sensor horizontal_sensorgood = Rectangle(Point(x-35.5, y), Point(x-4.5, y)) horizontal_sensorgood.setWidth(2.5) horizontal_sensorgood.setOutline("green") h_xg = horizontal_sensorgood.getCenter().getX() h_yg = horizontal_sensorgood.getCenter().getY() if [h_xg,h_yg] not in sensors: horizontal_sensorgood.draw(field) goodsensors.append([h_xg, h_yg]) # Creates 40% chance horizontal sensor will be drawn if v_chance_border <= 0.25: # Define, draw, and append location of sensor vertical_sensorgood = Rectangle(Point(x, y-35.5), Point(x, y-4.5)) vertical_sensorgood.setWidth(2.5) vertical_sensorgood.setOutline("green") v_xg = vertical_sensorgood.getCenter().getX() v_yg = vertical_sensorgood.getCenter().getY() if [v_xg,v_yg] not in sensors: vertical_sensorgood.draw(field) goodsensors.append([v_xg, v_yg]) # Move to next row y += 40 # Set back to first row after finishing final row y = 40 # Move to the next column x += 40 # Draw vertical sensors return sensors, goodsensors # =================================[ PANELS }================================== # Define DrawInitialPanel() def drawInitialPanel(game_panel): # Draw score display, "NEW PLAYER" text on green button score_box, score_text, scores = drawScoreDisplay(game_panel) new_player_text = drawPlayerText(game_panel) # Set game panel phase to "initial" phase = "initial" # Return objects return new_player_text, score_box, score_text, phase, scores # Define DrawNewPlayerPanel() function def drawNewPlayerPanel(new_player_text, score_box, score_text, game_panel, phase): # Set green button text to "START!", remove Initial conditions, and draw New # Player entry new_player_text.setText("START!") player_name_text, player_name_entry = drawPlayerNameEntry(game_panel) # Set game panel phase to "new_player" phase = "new_player" # Return objects return player_name_text, player_name_entry, phase # Define DrawInGamePanel() function def drawInGamePanel(new_player_text, player_name_entry, game_panel, score): # Set green button text to "NEW PLAYER", finalize player name, creat reset # button, and draw score display new_player_text.setText("NEW PLAYER") player_name_display, player_name = drawPlayerNameDisplay( player_name_entry, game_panel) reset_button, reset_text = drawResetButton(game_panel) current_score_text, current_score_display = drawCurrentScore(game_panel, score) # Set game panel phase to "in_game" phase = "in_game" # Return objects return player_name_display, player_name, reset_button, reset_text, current_score_text, current_score_display, phase # Define DrawResetPanel() def drawResetPanel(reset, game_panel, reset_button, reset_text, current_score_text, current_score_display, player_name_text, player_name_display): # Remove reset button, set back to inital phase # * Game panel phase not set to inital because drawInitialPanel() is called undrawResetButton(reset_button, reset_text) undrawScoreDisplay(current_score_text, current_score_display) undrawPlayerNameDisplay(player_name_text, player_name_display) new_player_text, score_box, score_text, phase, scores = drawInitialPanel(game_panel) # Return objects return new_player_text, score_box, score_text, phase # Define fieldPanel() function def drawFieldPanel(): # Create Field panel field = GraphWin("The Field", 400, 400) # Create vertical and horizontal lines on Field panel for i in range(9): v_field_line = Line(Point(40*(i+1), 0), Point(40*(i+1), 400)) v_field_line.setOutline("light gray") v_field_line.draw(field) h_field_line = Line(Point(0, 40*(i+1)), Point(400, 40*(i+1))) h_field_line.setOutline("light gray") h_field_line.draw(field) # Color start and end squares start = Rectangle(Point(0, 0), Point(40, 40)) start.setFill("green") start.setOutline("light gray") start.draw(field) end = Rectangle(Point(360, 360), Point(400, 400)) end.setFill("red") end.setOutline("light gray") end.draw(field) # Draw black holes blackcenter1, blackcenter2 = blackHoles(field) # Create spin square Rectangle while True: # Make sure spin square is not drawn on top of black holes, and repeat # location process if it is on top of a black hole spin_x = randint(2, 9) * 40 - 20 spin_y = randint(2, 9) * 40 - 20 spin_square = Rectangle(Point(spin_x-17, spin_y-17), Point(spin_x+17, spin_y+17)) if spin_x != blackcenter1.getX() and spin_y != blackcenter1.getY() or spin_x != blackcenter2.getX() and spin_y != blackcenter2.getY(): break spin_square.setFill("blue") spin_square.draw(field) spin_text = Text(Point(spin_x, spin_y), "SPIN") spin_text.setTextColor("white") spin_text.draw(field) # Create initial Pete Rectangle pete = Rectangle(Point(4, 4), Point(36, 36)) pete.setFill("gold") pete.draw(field) # Draw and return sensors sensors, goodsensors = drawSensors(field) # Return objects return field, pete, sensors, spin_square, blackcenter1, blackcenter2, goodsensors # ================================[ CLICK }==================================== # Define clickCoords() function def clickCoords(click): # Separate click Point into x and y coordinates x = click.getX() y = click.getY() # Return coordinates return (x, y) # Define getClick() function def getClick(game_panel, field, in_game): # When not in game, get click from game panel if in_game is False: click = game_panel.checkMouse() if click is not None: panel = "game_panel" else: panel = "none" # When game is played, check panel and return result and click location else: panel, click = checkPanel(game_panel, field) # Get the coordinates of the click, regardless of panel try: x, y = clickCoords(click) except AttributeError: x = 0 y = 0 # Return objects return panel, x, y # ================================[ CHECKS }================================== # Define checkPanel() function def checkPanel(game_panel, field): # Until a click occurs, check panels for a click click1 = game_panel.checkMouse() click2 = field.checkMouse() # When user clicks in the game panel, return "game" and click location if click1 is not None: return "game_panel", click1 # When user clicks in field panel, return "field" and click location elif click2 is not None: return "field", click2 else: return "none", click1 # Define checkExit() function def checkExit(panel, x, y): # If user clicks in game panel on red exit button, return True if panel == "game_panel" and x >= 250 and y >= 260: return True else: return False # Define checkGreenButton() function def checkGreenButton(panel, x, y): # If user clicks in game panel on green button, return True if panel == "game_panel" and x >= 100 and x <= 200 and y >= 260: return True else: return False # Define checkResetButton() function def checkResetButton(panel, phase, x, y): # If reset button exists, and user clicks on it in the game panel, return True if panel == "game_panel" and phase == "in_game" and x <= 50 and y >= 260: return True else: return False # Define checkWinGame() function def checkWinGame(pete_center): # If Pete Rectangle is located in the center of the red Rectangle that # represents the goal, return True peteX, peteY = clickCoords(pete_center) if peteX == 380.0 and peteY == 380.0: return True else: return False # Define checkSensor() function def checkSensor(direction, sensors, score, peteX, peteY, goodsensors): # Define Pete's location as a set of coordinates to check against coordinate = [peteX, peteY] # Check sensors related to Pete moving up if direction == "up": if [coordinate[0], coordinate[1] + 20] in sensors: score += 3 elif [coordinate[0], coordinate[1]+20] in goodsensors: score -= 1 else: score += 1 # Check sensors related to Pete moving down if direction == "down": if [coordinate[0], coordinate[1] - 20] in sensors: score += 3 elif [coordinate[0], coordinate[1]-20] in goodsensors: score -= 1 else: score += 1 # Check sensors related to Pete moving left if direction == "left": if [coordinate[0] + 20, coordinate[1]] in sensors: score += 3 elif [coordinate[0]+20, coordinate[1]] in goodsensors: score -= 1 else: score += 1 # Check sensors related to Pete moving right if direction == "right": if [coordinate[0] - 20, coordinate[1]] in sensors: score += 3 elif [coordinate[0]-20, coordinate[1]] in goodsensors: score -= 1 else: score += 1 # Check sensors related to Pete moving diagonally up and left if direction == "up,left": if [coordinate[0], coordinate[1] + 20] in sensors: score += 3 if [coordinate[0] + 20, coordinate[1]] in sensors: score += 3 if [coordinate[0] + 20, coordinate[1] + 40] in sensors: score += 3 if [coordinate[0] + 40, coordinate[1] + 20] in sensors: score += 3 if [coordinate[0], coordinate[1] + 20] not in sensors and [coordinate[0] + 20, coordinate[1]] not in sensors and [coordinate[0] + 20, coordinate[1] + 40] not in sensors and [coordinate[0] + 40, coordinate[1] + 20] not in sensors: score += 1 #Check for goodsensors if [coordinate[0], coordinate[1] + 20] in goodsensors: score -= 1 if [coordinate[0] + 20, coordinate[1]] in goodsensors: score -= 1 if [coordinate[0] + 20, coordinate[1] + 40] in goodsensors: score -= 1 if [coordinate[0] + 40, coordinate[1] + 20] in goodsensors: score -= 1 # Check sensors related to Pete moving diagonally up and right if direction == "up,right": if [coordinate[0], coordinate[1] + 20] in sensors: score += 3 if [coordinate[0] - 20, coordinate[1]] in sensors: score += 3 if [coordinate[0] - 20, coordinate[1] + 40] in sensors: score += 3 if [coordinate[0] - 40, coordinate[1] + 20] in sensors: score += 3 if [coordinate[0], coordinate[1] + 20] not in sensors and [coordinate[0] - 20, coordinate[1]] not in sensors and [coordinate[0] - 20, coordinate[1] + 40] not in sensors and [coordinate[0] - 40, coordinate[1] + 20] not in sensors: score += 1 #Check for goodsensors if [coordinate[0], coordinate[1] + 20] in goodsensors: score -= 1 if [coordinate[0] - 20, coordinate[1]] in goodsensors: score -= 1 if [coordinate[0] - 20, coordinate[1] + 40] in goodsensors: score -=1 if [coordinate[0] - 40, coordinate[1] + 20] in goodsensors: score -= 1 # Check sensors related to Pete moving diagonally down and left if direction == "down,left": # Check if Pete crossed a penalty sensor if [coordinate[0], coordinate[1] - 20] in sensors: score += 3 if [coordinate[0] + 20, coordinate[1]] in sensors: score += 3 if [coordinate[0] + 20, coordinate[1] - 40] in sensors: score += 3 if [coordinate[0] + 40, coordinate[1] - 20] in sensors: score += 3 if [coordinate[0], coordinate[1] - 20] not in sensors and [coordinate[0] + 20, coordinate[1]] not in sensors and [coordinate[0] + 20, coordinate[1] - 40] not in sensors and [coordinate[0] + 40, coordinate[1] - 20] not in sensors: score += 1 # Check if Pete crossed a good sensor if [coordinate[0], coordinate[1] - 20] in goodsensors: score -= 1 if [coordinate[0] + 20, coordinate[1]] in goodsensors: score -= 1 if [coordinate[0] + 20, coordinate[1] - 40] in goodsensors: score -= 1 if [coordinate[0] + 40, coordinate[1] - 20] in goodsensors: score -= 1 # Check sensors related to Pete moving diagonally down and right if direction == "down,right": # Check if Pete crossed a penalty sensor if [coordinate[0], coordinate[1] - 20] in sensors: score += 3 if [coordinate[0] - 20, coordinate[1]] in sensors: score += 3 if [coordinate[0] - 20, coordinate[1] - 40] in sensors: score += 3 if [coordinate[0] - 40, coordinate[1] - 20] in sensors: score += 3 if [coordinate[0], coordinate[1] - 20] not in sensors and [coordinate[0] - 20, coordinate[1]] not in sensors and [coordinate[0] - 20, coordinate[1] - 40] not in sensors and [coordinate[0] - 40, coordinate[1] - 20] not in sensors: score += 1 # Check if Pete crossed a good sensor if [coordinate[0], coordinate[1] - 20] in goodsensors: score -= 1 if [coordinate[0] - 20, coordinate[1]] in goodsensors: score -= 1 if [coordinate[0] - 20, coordinate[1] - 40] in goodsensors: score -= 1 if [coordinate[0] - 40, coordinate[1] - 20] in goodsensors: score -= 1 # If user did not move, do nothing if direction == "none": pass # Return score after any changes return score # ===========================[ FIELD METHODS ]================================= # Define movePete() function def movePete(pete, field, x, y, score, sensors, spin_square,blackcenter1, blackcenter2, goodsensors): # Find the location of Pete and spin square, and derive the edges of Pete pete_center = pete.getCenter() clickX = x clickY = y peteX, peteY = clickCoords(pete_center) spinX, spinY = clickCoords(spin_square.getCenter()) # Define bounds of Pete object peteUpperX = peteX + 20 peteLowerX = peteX - 20 peteUpperY = peteY + 20 peteLowerY = peteY - 20 # Undraw Pete object so it can be re-drawn pete.undraw() # Check if Pete is on spin square, and randomly move him in a direction # that is not a wall if peteX == spinX and peteY == spinY: direction = {'-1,-1':'up,left', '-1,0':'left', '-1,1':'down,left', '0,-1':'up', '0,0':'none', '0,1':'down', '1,-1':'up,right', '1,0':'right', '1,1':'down,right'} x_movement = randint(-1, 1) y_movement = randint(-1, 1) peteX += x_movement * 40 peteY += y_movement * 40 direction_key = str(x_movement) + "," + str(y_movement) direction_value = direction[direction_key] score = checkSensor(direction_value, sensors, score, peteX, peteY, goodsensors) # If not on spin tile, perform a normal action else: # Create list of directions direction = [] # Move Pete up if the user clicks above him if clickY < peteLowerY: peteY -= 40 direction.append("up") # Move Pete down if the user clicks below him if clickY > peteUpperY: peteY += 40 direction.append("down") # Move Pete left if the user clicks left of him if clickX < peteLowerX: peteX -= 40 direction.append("left") # Move Pete right if the user clicks to the right of him if clickX > peteUpperX: peteX += 40 direction.append("right") direction = ",".join(direction) score = checkSensor(direction, sensors, score, peteX, peteY, goodsensors) # Define and re-draw Pete Rectangle object pete = Rectangle(Point(peteX-16, peteY-16), Point(peteX+16, peteY+16)) pete.setFill("gold") pete.draw(field) # Return the center of Pete so the victory condition can be checked pete_center = pete.getCenter() # Get the center of Pete petecenter=pete.getCenter() # If center of Pete matches blackcenter1, move him to blackcenter2 if petecenter.getX()==blackcenter1.getX() and petecenter.getY()==blackcenter1.getY(): pete.undraw() petecenter=blackcenter2 pete=Rectangle(Point(blackcenter2.getX()-20,blackcenter2.getY()-20),Point(blackcenter2.getX()+20,blackcenter2.getY()+20)) pete.setFill('gold') pete.draw(field) # If center of Pete matches blackcenter2, move him to blackcenter1 elif petecenter.getX()==blackcenter2.getX() and petecenter.getY()==blackcenter2.getY(): pete.undraw() petecenter=blackcenter1 pete=Rectangle(Point(blackcenter1.getX()-20,blackcenter1.getY()-20),Point(blackcenter1.getX()+20,blackcenter1.getY()+20)) pete.setFill('gold') pete.draw(field) # Return objects return pete, pete_center, score # Define updateScore() function def updateScore(current_score_text, current_score_display, game_panel, score): # Update score by re-drawing objects undrawCurrentScore(current_score_text, current_score_display) current_score_text, current_score_display = drawCurrentScore(game_panel, score) # Return objects return current_score_text, current_score_display # Define endGame() function def endGame(field, game_panel, player_name, score): # Let the user know the game is finished end_game_text = Text(Point(200, 200), "Finished! Click to close") end_game_text.draw(field) # Draw graphic objects at different places that represent balloons with a # string connected to it. balloon_1 = Circle(Point(145,110),18) balloon_1.setFill("red") balloon_1.setOutline("red") balloon_1.draw(field) triangle_1 = Polygon(Point(137,135),Point(145,128),Point(153,135)) triangle_1.setFill("red") triangle_1.setOutline('red') triangle_1.draw(field) string_1 = Line(Point(145,135),Point(145,180)) string_1.draw(field) balloon_2 = Circle(Point(340,300),18) balloon_2.setFill("red") balloon_2.setOutline("red") balloon_2.draw(field) triangle_2 = Polygon(Point(332,325),Point(340,318),Point(348,325)) triangle_2.setFill("red") triangle_2.setOutline('red') triangle_2.draw(field) string_2 = Line(Point(340,325),Point(340,370)) string_2.draw(field) balloon_3 = Circle(Point(75,275),18) balloon_3.setFill("red") balloon_3.setOutline("red") balloon_3.draw(field) triangle_3 = Polygon(Point(67,300),Point(75,293),Point(83,300)) triangle_3.setFill("red") triangle_3.setOutline('red') triangle_3.draw(field) string_3 = Line(Point(75,300),Point(75,345)) string_3.draw(field) # Create a while loop that moves the objets every 0.05 seconds upwards to # make it appear as if they are floating while True: sleep(0.05) balloon_1.move(0,-10) triangle_1.move(0,-10) string_1.move(0,-10) balloon_2.move(0,-10) triangle_2.move(0,-10) string_2.move(0,-10) balloon_3.move(0,-10) triangle_3.move(0,-10) string_3.move(0,-10) # If a click is detetced in the field, the window will close even if the # balloons are still moving in the while loop click = field.checkMouse() if click != None: break # Add player score to top_scores.txt writeScores(player_name, score) # Set close condition to True close = True # Return close condition return close # ===========================[ SCORE METHODS ]================================= # Define writeScores() function def writeScores(name, score): # Open top_scores.txt in appending mode score_file = open("top_scores.txt", 'a') # Create new score String using Player entered information new_score = name+","+str(score)+"\n" # Output String object to file score_file.write(new_score) # Close text file score_file.close() # Define readScores() function def readScores(): # Create empty list of top scores top_scores = [] # Open top_scores.txt in read mode score_file = open("top_scores.txt", 'r') # For each line of top_scores.txt, strip the newline character, split into # name and score, convert score to an integer, and append to list for line in score_file.readlines(): line = line[:-1] name, score = line.split(",") score = int(score) top_scores.append((name, score)) # Close text file score_file.close() # Sort list by score component top_scores.sort(key=lambda s: s[1]) # Return top scores in list form return top_scores # Define changeScores() function def changeScores(scores, score_text): scores.append(scores.pop(2)) score_text.setText("\n".join(scores[:6])) # Define blackHoles() function def blackHoles(field): # Create a list of numbers that could be X and Y coordinates numbers=[] for i in range (60,360,40): numbers.append(i) # From that list, ceate first blackhole coordinates blackX1=int(choice(numbers)) blackY1=int(choice(numbers)) # Create second blackhole coordinates blackX2=int(choice(numbers)) blackY2=int(choice(numbers)) # Draw the black holes black1=Circle(Point(blackX1,blackY1), 5) black1.setFill('black') black1.draw(field) black2=Circle(Point(blackX2,blackY2), 5) black2.setFill('black') black2.draw(field) # Get the centers of the circles blackcenter1=black1.getCenter() blackcenter2=black2.getCenter() # Return the center locations for the black holes return blackcenter1, blackcenter2 # ==============================[ CALL MAIN }================================== # Call main() function main()
d06a0e041a0b02c62d269478382d468e475e58fb
harsh04/Machine_Learning_Projects
/Machine Learning A-Z/Part 2 - Regression/Section 4 - Simple Linear Regression/simple_Linear_regression.py
1,203
3.625
4
# -*- coding: utf-8 -*- """ Created on Sat May 27 11:51:31 2017 @author: Harsh Mathur """ #import libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd #import dataset dataset = pd.read_csv('Salary_Data.csv') X = dataset.iloc[:, :-1].values y = dataset.iloc[:, 1].values #splitting data for learning and training set from sklearn.cross_validation import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 1/3, random_state = 0) #fitting simple linear regression from sklearn.linear_model import LinearRegression regressor = LinearRegression() regressor.fit(X_train, y_train) #predict test result y_pred = regressor.predict(X_test) #visualising training result plt.scatter(X_train, y_train, color = 'red') plt.plot(X_train, regressor.predict(X_train), color = 'blue') plt.title('Salary vs Experience (Training set)') plt.xlabel('years of experience') plt.ylabel('Salary') plt.show() #visualising test result plt.scatter(X_test, y_test, color = 'red') plt.plot(X_train, regressor.predict(X_train), color = 'blue') plt.title('Salary vs Experience (Test set)') plt.xlabel('years of experience') plt.ylabel('Salary') plt.show()
dd42b21d7be962313efcafc0f2f177da84b1c0de
dserver/old_sedgewick
/Sort.py
1,263
3.515625
4
from ParseSites import parse_sites import random import time def swap(a_list, pos1, pos2): temp = a_list[pos1] a_list[pos1] = a_list[pos2] a_list[pos2] = temp return a_list def selection_sort(a_list): for l in xrange(len(a_list)): for m in xrange(l, len(a_list)): if a_list[m]<a_list[l]: swap(a_list, l, m) def insertion_sort(a_list): sorted_start = 0 while (sorted_start != len(a_list)-1): j = sorted_start + 1 number = a_list[j] # number is the value to insert in the list while (number < a_list[j] and j > 0): j -= 1 sorted_start += 1 def create_numbers(size): f = open(str(size) + "numbers.txt", "w") for i in xrange(0, size): print >>f, "%6d" % (random.randint(0, 10000)) # shift a_list one to the right starting from b to c def shift_list(a_list, b, c): print a_list print "b: %3d \t c: %3d" % (b, c) for x in range(b, c-1, -1): temp = a_list[x+1] a_list[x+1] = a_list[x] return a_list if __name__ == "__main__": # ln = [] # with open("10000numbers.txt", "r") as f: # line = f.readline() # n = parse_sites(line) # ln.append(n[0]) # start = time.time() # selection_sort(ln) # print "%d seconds for 10,000 numbers" % (time.time() - start) ln = [8, 7, 5, 30, 1] insertion_sort(ln) print ln
43ffa657b6700c43739fa0ad3377bf71a423f9a8
jih3508/study_ml
/PyTorch/모두를 위한 딥러닝 시즌2/MAX_Argmax.py
322
3.703125
4
#Max and Argmax with PyTorch #Max: ū #Argmax: ū ε import torch import numpy as np t = torch.FloatTensor([[1, 2], [3, 4]]) print(t) print(t.max()) print(t.max(dim = 0)) print('Max: ', t.max(dim=0)[0]) print('Argmax: ', t.max(dim=0)[1]) print(t.max(dim=1)) print(t.max(dim=-1))
14ac1080a711d1b6b90389c81f4f94aaa933482a
jiaz/leetpy
/leetcode/Q129_SumRootToLeafNumbers.py
838
4.125
4
# -*- coding: utf-8 -*- # Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number. # An example is the root-to-leaf path 1->2->3 which represents the number 123. # # Find the total sum of all root-to-leaf numbers. # # For example, # # 1 # / \ # 2 3 # # The root-to-leaf path 1->2 represents the number 12. # The root-to-leaf path 1->3 represents the number 13. # # Return the sum = 12 + 13 = 25. # # # Link: # https://leetcode.com/problems/sum-root-to-leaf-numbers/ # 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 sumNumbers(self, root): """ :type root: TreeNode :rtype: int """
11f455115e12711b22b118ff5d5527a348ed95db
bmorale1/Program-Repository
/Python/Morales_brandon_lab10_dateChecker.py
1,550
4.5
4
#Author: Isaac Morales #File name: Morales_brandon_lab10_dateChecker.py #Purpose: To check if the date the user enter is valid #date: September 16, 2015 month =int(input('enter the number of a month.')) day = int(input('enter a day of the month.')) year = int(input('enter a year.')) print('you entered',day,'/',month,'/',year) leapYear=False if(year%400==0) or (year%4==0 and year%100!=0): leapYear=True if (0>month)or(month>12): print('not a valid date') elif(month == 1) and ( 0>day or 31<day): print('not a valid date.') elif(month == 3) and ( 0>day or 31<day): print('not a valid date.') elif(month == 5) and ( 0>day or 31<day): print('not a valid date.') elif(month == 7) and ( 0>day or 31<day): print('not a valid date.') elif(month == 8) and ( 0>day or 31<day): print('not a valid date.') elif(month == 10) and ( 0>day or 31<day): print('not a valid date.') elif(month == 12) and ( 0>day or 31<day): print('not a valid date.') elif(month == 4) and ( 0>day or 30<day): print('not a valid date.') elif(month == 6) and ( 0>day or 30<day): print('not a valid date.') elif(month == 9) and ( 0>day or 30<day): print('not a valid date.') elif(month == 11) and ( 0>day or 30<day): print('not a valid date.') elif(month==2)and(leapYear==True)and (0>day or 29<day): print('not a valid date.') elif(month==2)and(leapYear==False) and (0>day or 28<day): print('not a valid date.') else: print('the date is valid.')
ab3da031e33f75dff72d75935b9aa60ad6f313e2
cemar-ortiz/coding_challenges
/challenges/string_compression.py
325
4.09375
4
# Implement a method to perform basic string compression using the counts of repeated characters ('aaabbbbcc' should become 'a2b4c2'). If the output is not 'smaller' than the input, it should return the input. Assume only letters will be used as input, uppercase or lowercase. def task(string: str): return 'dummy string'
7e55bda9fef8d3bfb556485370de1cc95e2ce132
amudera/assessment
/Question3/employee.py
1,110
3.890625
4
import sqlite3 from orm import ORM class Employee(ORM): dbpath = "employees.db" tablename = "employees" fields = ['Last_name','First_name','employee_id','salary'] def __init__(self, **kwargs): self.pk = kwargs.get("pk") self.last_name = kwargs.get("Last_name") self.first_name = kwargs.get('First_name') self.employee_id = kwargs.get('employee_id') self.salary = kwargs.get('salary') def branch(self): employee_id = input("ID: ") SQL = "SELECT * FROM employees JOIN employees_branches ON employees.pk = employees_branches.employees_pk JOIN branches ON branches.pk = employees_branches.branches_pk WHERE employee_id=?;".format(employee_id) with sqlite3.connect(dbpath) as conn: conn.row_factory = sqlite3.Row curs = conn.cursor() curs.execute(SQL) results = curs.fetchall() print(results) #unittest would create a new user for a new branch, save the user and then use the above to check if Equal the new branch that was added
f8a302f15a7bb77aa50b146c856b06b106c270e1
Atabekarapov/Week2_Task1
/Task1.py
919
3.9375
4
# Homework --> Atabek # 1) # name = "Hello World!" # print(len(name)) # 2) # name = "Hello world!" # print(name.lower(), name.upper()) # 3) # name = "Hellow world!" # print(name.replace('H', '$') .replace('!', '$')) # 4) ???? # a = input("Write your words: ") # b = (a.split( maxsplit = 4)) # print(b) # 5) # a = input("Write your name: ") # b = "Hello, " # c = "!" # print(b + a + c) # 6) # a = "Hello word I am backend developer!" # res = len(a.split()) # print(res) # 7) # 7.1 # a = "Hello world" # b = (a[2]) # print(b) # 7.2 # a = "Hello world" # b = (a[-1]) # print(b) # 7.3 # a = "Hello world" # print(a[0:5]) # # 7.4 # a = "Hello world" # print(a[0:10]) # 7.5 # a = "Hello world" # print(a[:12:2]) # 7.6 # a = "Hello world!" # print (a[1:12:2]) # 7.7 # a = "Hello world!" # print(a[::-1]) # 7.8 ???? # a = "Hello world!" # print(a[-1:2:-4]) # 7.9 # a = "Hello world!" # print(len(a))
dd96c6c752273527f92b59829fe5a2dd37b5c84e
mbarbour0/Practice
/Stringclasses.py
365
3.90625
4
import string def stringcases(arg1): upperc = arg1.upper() lowerc = arg1.lower() titlec = string.capwords(arg1, ' ') reversec = list(arg1) reversec = reversec[-1::-1] reversec = ''.join(reversec) return(upperc, lowerc, titlec, reversec) print(stringcases("Hey, my name is, what? My name is, Who? My name is tcka tcka Slim Shady."))
793ae440226da15ec3300c5d484d802c90a26d79
MikeMillard/EEE3097S-Project-Repository
/compression.py
2,058
3.6875
4
# Imports import zlib import sys import time compressedFile = "Project Folder\Compressed Files\compressed_data1.csv" decompressedFile = "Project Folder\Decompressed Files\decompressed_data1.csv" # Compression method, takes the input file as its input parameter def myCompress (inputFile): # Start timer for compression testing purposes compress_start = time.time() with open(inputFile, mode="rb") as fin, open(compressedFile, mode="wb") as fout: data = fin.read() compressed_data = zlib.compress(data, zlib.Z_BEST_COMPRESSION) # Display the file sizes before and after compression, for testing purposes print("\nCompression:") print(f"- Input file size: {sys.getsizeof(data)} bytes.") print(f"- Compressed file size: {sys.getsizeof(compressed_data)} bytes.") fout.write(compressed_data) compress_time_taken = time.time() - compress_start print("- It took " + str(round(compress_time_taken, 3)) + " seconds to read in, compress, and return the data.") # Decompression method, takes the decrypted compressed file as input def myDecompress (compressedFile): # Start timer for decompression testing purposes decompress_start = time.time() with open(compressedFile, mode="rb") as fin, open(decompressedFile, mode="wb") as fout: data = fin.read() decompressed_data = zlib.decompress(data) # Display the file sizes before and after decompression, also to be compared with file sizes displayed in the compression sub-subsystem print("\nDecompression:") print(f"- Compressed file size: {sys.getsizeof(data)} bytes.") print(f"- Decompressed file size: {sys.getsizeof(decompressed_data)} bytes.") fout.write(decompressed_data) # Stop the decompression timer decompress_time_taken = time.time() - decompress_start print("- It took " + str(round(decompress_time_taken, 3)) + " seconds to read in, decompress, and return the data.")
d73b67f6a4d311575545366e346da33c6ce461a8
YoYolops/URI
/Iniciante/Idade em Dias.py
421
3.703125
4
# 5% errado day = int(input()) mes = int(day/30) ano = int(mes/12) if day < 30: print("0 ano(s)") print("0 mes(es)") print("%d dia(s)"%day) elif 365 > day >= 30: day = day - mes*30 print("0 ano(s)") print("%d mes(es)"%mes) print("%d dia(s)"%day) elif day >= 365: day = day - mes*30 mes = mes - ano*12 print("%d ano(s)"%ano) print("%d mes(es)"%mes) print("%d dia(s)"%day)
8efd18c54af365679cc63e68d233b5ed1f71e5f6
AmirHussein96/Machine-Translation-with-CRFs
/libitg.py
34,313
4.28125
4
# coding: utf-8 # This notebook should help you with project 2, in particular, it implements a basic ITG parser. # # Symbols # # Let's start by defining the symbols that can be used in our grammars. # # We are going to design symbols as immutable objects. # # * a symbol is going to be a container # * Terminal and Nonterminal are basic symbols, they simply store a python string # * Span is a composed symbol, it contains a Symbol and a range represented as two integers # * Internally a Span is a python tuple of the kind (symbol: Symbol, start: int, end: int) # * We define two *3* special methods to interact with basic and composed symbols # * root: goes all the way up to the root symbol (for example, returns the Symbol in a Span) # * obj: returns the underlying python object (for example, a str for Terminal, or tuple for Span) # * translate: creates a symbol identical in structure, but translates the underlying python object of the root symbol (for example, translates the Terminal of a Span) # class Symbol: """ A symbol in a grammar. In this class we basically wrap a certain type of object and treat it as a symbol. """ def __init__(self): pass def is_terminal(self) -> bool: """Whether or not this is a terminal symbol""" pass def root(self) -> 'Symbol': """Some symbols are represented as a hierarchy of symbols, this method returns the root of that hierarchy.""" pass def obj(self) -> object: """Returns the underlying python object.""" pass def translate(self, target) -> 'Symbol': """Translate the underlying python object of the root symbol and return a new Symbol""" pass class Terminal(Symbol): """ Terminal symbols are words in a vocabulary. """ def __init__(self, symbol: str): assert type(symbol) is str, 'A Terminal takes a python string, got %s' % type(symbol) self._symbol = symbol def is_terminal(self): return True def root(self) -> 'Terminal': # Terminals are not hierarchical symbols return self def obj(self) -> str: """The underlying python string""" return self._symbol def translate(self, target) -> 'Terminal': return Terminal(target) def __str__(self): return "'%s'" % self._symbol def __repr__(self): return 'Terminal(%r)' % self._symbol def __hash__(self): return hash(self._symbol) def __eq__(self, other): return type(self) == type(other) and self._symbol == other._symbol def __ne__(self, other): return not (self == other) class Nonterminal(Symbol): """ Nonterminal symbols are variables in a grammar. """ def __init__(self, symbol: str): assert type(symbol) is str, 'A Nonterminal takes a python string, got %s' % type(symbol) self._symbol = symbol def is_terminal(self): return False def root(self) -> 'Nonterminal': # Nonterminals are not hierarchical symbols return self def obj(self) -> str: """The underlying python string""" return self._symbol def translate(self, target) -> 'Nonterminal': return Nonterminal(target) def __str__(self): return "[%s]" % self._symbol def __repr__(self): return 'Nonterminal(%r)' % self._symbol def __hash__(self): return hash(self._symbol) def __eq__(self, other): return type(self) == type(other) and self._symbol == other._symbol def __ne__(self, other): return not (self == other) # The notion of *span* will come in handy when designing parsers, thus let's define it here. class Span(Symbol): """ A span can be a terminal, a nonterminal, or a span wrapped around two integers. Internally, we represent spans with tuples of the kind (symbol, start, end). Example: Span(Terminal('the'), 0, 1) Span(Nonterminal('[X]'), 0, 1) Span(Span(Terminal('the'), 0, 1), 1, 2) Span(Span(Nonterminal('[X]'), 0, 1), 1, 2) """ def __init__(self, symbol: Symbol, start: int, end: int): assert isinstance(symbol, Symbol), 'A span takes an instance of Symbol, got %s' % type(symbol) self._symbol = symbol self._start = start self._end = end def is_terminal(self): # a span delegates this to an underlying symbol return self._symbol.is_terminal() def root(self) -> Symbol: # Spans are hierarchical symbols, thus we delegate return self._symbol.root() def obj(self) -> (Symbol, int, int): """The underlying python tuple (Symbol, start, end)""" return (self._symbol, self._start, self._end) def translate(self, target) -> 'Span': return Span(self._symbol.translate(target), self._start, self._end) def __str__(self): return "%s:%s-%s" % (self._symbol, self._start, self._end) def __repr__(self): return 'Span(%r, %r, %r)' % (self._symbol, self._start, self._end) def __hash__(self): return hash((self._symbol, self._start, self._end)) def __eq__(self, other): return type(self) == type(other) and self._symbol == other._symbol and self._start == other._start and self._end == other._end def __ne__(self, other): return not (self == other) # # Rules # # # A context-free rule rewrites a nonterminal LHS symbol into a sequence of terminal and nonterminal symbols. # We expect sequences to be non-empty, and we reserve a special terminal symbol to act as an epsilon string. from collections import defaultdict class Rule(object): """ A rule is a container for a LHS symbol and a sequence of RHS symbols. """ def __init__(self, lhs: Symbol, rhs: list): """ A rule takes a LHS symbol and a list/tuple of RHS symbols """ assert isinstance(lhs, Symbol), 'LHS must be an instance of Symbol' assert len(rhs) > 0, 'If you want an empty RHS, use an epsilon Terminal' assert all(isinstance(s, Symbol) for s in rhs), 'RHS must be a sequence of Symbol objects' self._lhs = lhs self._rhs = tuple(rhs) def __eq__(self, other): return type(self) == type(other) and self._lhs == other._lhs and self._rhs == other._rhs def __ne__(self, other): return not (self == other) def __hash__(self): return hash((self._lhs, self._rhs)) def __str__(self): return '%s ||| %s' % (self._lhs, ' '.join(str(s) for s in self._rhs)) def __repr__(self): return 'Rule(%r, %r)' % (self._lhs, self._rhs) @property def lhs(self): return self._lhs @property def rhs(self): return self._rhs @property def arity(self): return len(self._rhs) # # CFG # # Now let us write a CFG class, which will organise rules for us in a convenient manner. # We will design CFGs to be immutable. class CFG: """ A CFG is nothing but a container for rules. We group rules by LHS symbol and keep a set of terminals and nonterminals. """ def __init__(self, rules=[]): self._rules = [] self._rules_by_lhs = defaultdict(list) self._terminals = set() self._nonterminals = set() # organises rules for rule in rules: self._rules.append(rule) self._rules_by_lhs[rule.lhs].append(rule) self._nonterminals.add(rule.lhs) for s in rule.rhs: if s.is_terminal(): self._terminals.add(s) else: self._nonterminals.add(s) @property def nonterminals(self): return self._nonterminals @property def terminals(self): return self._terminals def __len__(self): return len(self._rules) def __getitem__(self, lhs): return self._rules_by_lhs.get(lhs, frozenset()) def get(self, lhs, default=frozenset()): """rules whose LHS is the given symbol""" return self._rules_by_lhs.get(lhs, default) def can_rewrite(self, lhs): """Whether a given nonterminal can be rewritten. This may differ from ``self.is_nonterminal(symbol)`` which returns whether a symbol belongs to the set of nonterminals of the grammar. """ return len(self[lhs]) > 0 def __iter__(self): """iterator over rules (in arbitrary order)""" return iter(self._rules) def items(self): """iterator over pairs of the kind (LHS, rules rewriting LHS)""" return self._rules_by_lhs.items() def iter_rules(self, lhs: Symbol): return iter(self.get(lhs)) def __str__(self): lines = [] for lhs, rules in self.items(): for rule in rules: lines.append(str(rule)) return '\n'.join(lines) # # ITG # # We do not really need a special class for ITGs, they are just a generalisation of CFGs for multiple streams. # What we can do is to treat the source side and the target side of the ITG as CFGs. # # We will represent a lexicon # # * a collection of translation pairs \\((x, y) \in \Sigma \times \Delta\\) where \\(\Sigma\\) is the source vocabulary and \\(\Delta\\) is the target vocabulary # * these vocabularies are extended with an empty string, i.e., \\(\epsilon\\) # * we will assume the lexicon expliclty states which words can be inserted/deleted # # We build the source side by inspecting a lexicon # # * terminal rules: \\(X \rightarrow x\\) where \\(x \in \Sigma\\) # * binary rules: \\(X \rightarrow X ~ X\\) # * start rule: \\(S \rightarrow X\\) # # Then, when the time comes, we will project this source grammar using the lexicon # # * terminal rules of the form \\(X_{i,j} \rightarrow x\\) will become \\(X_{i,j} \rightarrow y\\) for every possible translation pair \\((x, y)\\) in the lexicon # * binary rules of the form \\(X_{i,k} \rightarrow X_{i,j} ~ X_{j,k}\\) will be copied and also inverted as in \\(X_{i,k} \rightarrow X_{j,k} ~ X_{i,j}\\) # * the start rule will be copied # def read_lexicon(path): """ Read translation dictionary from a file (one word pair per line) and return a dictionary mapping x \in \Sigma to a set of y \in \Delta """ lexicon = defaultdict(set) with open(path) as istream: for n, line in enumerate(istream): line = line.strip() if not line: continue words = line.split() if len(words) != 2: raise ValueError('I expected a word pair in line %d, got %s' % (n, line)) x, y = words lexicon[x].add(y) return lexicon def make_source_side_itg(lexicon, s_str='S', x_str='X') -> CFG: """Constructs the source side of an ITG from a dictionary""" S = Nonterminal(s_str) X = Nonterminal(x_str) def iter_rules(): yield Rule(S, [X]) # Start: S -> X yield Rule(X, [X, X]) # Segment: X -> X X for x in lexicon.keys(): yield Rule(X, [Terminal(x)]) # X - > x return CFG(iter_rules()) # We typically represent sentences using finite-state automata, this allows for a more general view of parsing. # Let's define an FSA class and a function to instantiate the FSA that corresponds to a sentence. class FSA: """ A container for arcs. This implements a deterministic unweighted FSA. """ def __init__(self): # each state is represented as a collection of outgoing arcs # which are organised in a dictionary mapping a label to a destination state self.sent = str self._states = [] # here we map from origin to label to destination self._initial = set() self._final = set() self._arcs = [] # here we map from origin to destination to label def nb_states(self): """Number of states""" return len(self._states) def nb_arcs(self): """Number of arcs""" return sum(len(outgoing) for outgoing in self._states) def add_state(self, initial=False, final=False) -> int: """Add a state marking it as initial and/or final and return its 0-based id""" sid = len(self._states) self._states.append(defaultdict(int)) self._arcs.append(defaultdict(str)) if initial: self.make_initial(sid) if final: self.make_final(sid) return sid def add_arc(self, origin, destination, label: str): """Add an arc between `origin` and `destination` with a certain label (states should be added before calling this method)""" self._states[origin][label] = destination self._arcs[origin][destination] = label def destination(self, origin: int, label: str) -> int: """Return the destination from a certain `origin` state with a certain `label` (-1 means no destination available)""" if origin >= len(self._states): return -1 outgoing = self._states[origin] if not outgoing: return -1 return outgoing.get(label, -1) def label(self, origin: int, destination: int) -> str: """Return the label of an arc or None if the arc does not exist""" if origin >= len(self._arcs): return None return self._arcs[origin].get(destination, None) def make_initial(self, state: int): """Mark a state as initial""" self._initial.add(state) def is_initial(self, state: int) -> bool: """Test whether a state is initial""" return state in self._initial def make_final(self, state: int): """Mark a state as final/accepting""" self._final.add(state) def is_final(self, state: int) -> bool: """Test whether a state is final/accepting""" return state in self._final def iterinitial(self): """Iterates over initial states""" return iter(self._initial) def iterfinal(self): """Iterates over final states""" return iter(self._final) def iterarcs(self, origin: int): return self._states[origin].items() if origin < len(self._states) else [] def __str__(self): lines = ['states=%d' % self.nb_states(), 'initial=%s' % ' '.join(str(s) for s in self._initial), 'final=%s' % ' '.join(str(s) for s in self._final), 'arcs=%d' % self.nb_arcs()] for origin, arcs in enumerate(self._states): for label, destination in sorted(arcs.items(), key=lambda pair: pair[1]): lines.append('origin=%d destination=%d label=%s' % (origin, destination, label)) return '\n'.join(lines) def make_fsa(string: str) -> FSA: """Converts a sentence (string) to an FSA (labels are python str objects)""" fsa = FSA() fsa.sent = string fsa.add_state(initial=True) for i, word in enumerate(string.split()): fsa.add_state() # create a destination state fsa.add_arc(i, i + 1, word) # label the arc with the current word fsa.make_final(fsa.nb_states() - 1) return fsa # # Deductive system # # We implement our parser using a deductive system. # # ## Items # # First we represent the items of our deductive system (again immutable objects). """ An item in a CKY/Earley program. """ class Item: """A dotted rule used in CKY/Earley where dots store the intersected FSA states.""" def __init__(self, rule: Rule, dots: list): assert len(dots) > 0, 'I do not accept an empty list of dots' self._rule = rule self._dots = tuple(dots) def __eq__(self, other): return type(self) == type(other) and self._rule == other._rule and self._dots == other._dots def __ne__(self, other): return not(self == other) def __hash__(self): return hash((self._rule, self._dots)) def __repr__(self): return '{0} ||| {1}'.format(self._rule, self._dots) def __str__(self): return '{0} ||| {1}'.format(self._rule, self._dots) @property def lhs(self) -> Symbol: return self._rule.lhs @property def rule(self) -> Rule: return self._rule @property def dot(self) -> int: return self._dots[-1] @property def start(self) -> int: return self._dots[0] @property def next(self) -> Symbol: """return the symbol to the right of the dot (or None, if the item is complete)""" if self.is_complete(): return None return self._rule.rhs[len(self._dots) - 1] def state(self, i) -> int: """The state associated with the ith dot""" return self._dots[i] def advance(self, dot) -> 'Item': """return a new item with an extended sequence of dots""" return Item(self._rule, self._dots + (dot,)) def is_complete(self) -> bool: """complete items are those whose dot reached the end of the RHS sequence""" return len(self._rule.rhs) + 1 == len(self._dots) # ## Agenda # # Next we define an agenda of active/passive items. # Agendas are much like queues, but with some added functionality (see below). """ An agenda of active/passive items in CKY/Ealery program. """ from collections import defaultdict, deque class Agenda: def __init__(self): # we are organising active items in a stack (last in first out) self._active = deque([]) # an item should never queue twice, thus we will manage a set of items which we have already seen self._seen = set() # we organise incomplete items by the symbols they wait for at a certain position # that is, if the key is a pair (Y, i) # the value is a set of items of the form # [X -> alpha * Y beta, [...i]] self._incomplete = defaultdict(set) # we organise complete items by their LHS symbol spanning from a certain position # if the key is a pair (X, i) # then the value is a set of items of the form # [X -> gamma *, [i ... j]] self._complete = defaultdict(set) # here we store the destinations already discovered self._destinations = defaultdict(set) def __len__(self): """return the number of active items""" return len(self._active) def push(self, item: Item): """push an item into the queue of active items""" if item not in self._seen: # if an item has been seen before, we simply ignore it self._active.append(item) self._seen.add(item) return True return False def pop(self) -> Item: """pop an active item""" assert len(self._active) > 0, 'I have no items left.' return self._active.pop() def make_passive(self, item: Item): """Store an item as passive: complete items are part of the chart, incomplete items are waiting for completion.""" if item.is_complete(): # complete items offer a way to rewrite a certain LHS from a certain position self._complete[(item.lhs, item.start)].add(item) self._destinations[(item.lhs, item.start)].add(item.dot) else: # incomplete items are waiting for the completion of the symbol to the right of the dot self._incomplete[(item.next, item.dot)].add(item) def waiting(self, symbol: Symbol, dot: int) -> set: """return items waiting for `symbol` spanning from `dot`""" return self._incomplete.get((symbol, dot), set()) def complete(self, lhs: Symbol, start: int) -> set: """return complete items whose LHS symbol is `lhs` spanning from `start`""" return self._complete.get((lhs, start), set()) def destinations(self, lhs: Symbol, start: int) -> set: """return destinations (in the FSA) for `lhs` spanning from `start`""" return self._destinations.get((lhs, start), set()) def itercomplete(self): """an iterator over complete items in arbitrary order""" for items in self._complete.itervalues(): for item in items: yield item # ## Inference rules # # Now, let's implement an Earley parser. It is based on a set of *axioms* and 3 inference rules (i.e. *predict*, *scan*, and *complete*). # # The strategy we adopt here is to design a function for each inference rule which # * may consult the agenda, but not alter it # * infers and returns a list of potential consequents # def axioms(cfg: CFG, fsa: FSA, s: Symbol) -> list: """ Axioms for Earley. Inference rule: -------------------- (S -> alpha) \in R and q0 \in I [S -> * alpha, [q0]] R is the rule set of the grammar. I is the set of initial states of the automaton. :param cfg: a CFG :param fsa: an FSA :param s: the CFG's start symbol (S) :returns: a list of items that are Earley axioms """ items = [] for q0 in fsa.iterinitial(): for rule in cfg.get(s): items.append(Item(rule, [q0])) return items def predict(cfg: CFG, item: Item) -> list: """ Prediction for Earley. Inference rule: [X -> alpha * Y beta, [r, ..., s]] -------------------- (Y -> gamma) \in R [Y -> * gamma, [s]] R is the ruleset of the grammar. :param item: an active Item :returns: a list of predicted Items or None """ items = [] for rule in cfg.get(item.next): items.append(Item(rule, [item.dot])) return items def scan(fsa: FSA, item: Item, eps_symbol: Terminal=Terminal('-EPS-')) -> list: """ Scan a terminal (compatible with CKY and Earley). Inference rule: [X -> alpha * x beta, [q, ..., r]] ------------------------------------ where (r, x, s) \in FSA and x != \epsilon [X -> alpha x * beta, [q, ..., r, s]] If x == \epsilon, we have a different rule [X -> alpha * \epsilon beta, [q, ..., r]] --------------------------------------------- [X -> alpha \epsilon * beta, [q, ..., r, r]] that is, the dot moves over the empty string and we loop into the same FSA state (r) :param item: an active Item :param eps_symbol: a list/tuple of terminals (set to None to disable epsilon rules) :returns: scanned items """ assert item.next.is_terminal(), 'Only terminal symbols can be scanned, got %s' % item.next if eps_symbol and item.next.root() == eps_symbol: return [item.advance(item.dot)] else: destination = fsa.destination(origin=item.dot, label=item.next.root().obj()) # we call .obj() because labels are strings, not Terminals if destination < 0: # cannot scan the symbol from this state return [] return [item.advance(destination)] def complete(agenda: Agenda, item: Item): """ Move dot over nonterminals (compatible with CKY and Earley). Inference rule: [X -> alpha * Y beta, [i ... k]] [Y -> gamma *, [k ... j]] ---------------------------------------------------------- [X -> alpha Y * beta, [i ... j]] :param item: an active Item. if `item` is complete, we advance the dot of incomplete passive items to `item.dot` otherwise, we check whether we know a set of positions J = {j1, j2, ..., jN} such that we can advance this item's dot to. :param agenda: an instance of Agenda :returns: a list of items """ items = [] if item.is_complete(): # advance the dot for incomplete items waiting for item.lhs spanning from item.start for incomplete in agenda.waiting(item.lhs, item.start): items.append(incomplete.advance(item.dot)) else: # look for completions of item.next spanning from item.dot for destination in agenda.destinations(item.next, item.dot): items.append(item.advance(destination)) return items def earley(cfg: CFG, fsa: FSA, start_symbol: Symbol, sprime_symbol=None, eps_symbol=Terminal('-EPS-')): """ Earley intersection between a CFG and an FSA. :param cfg: a grammar or forest :param fsa: an acyclic FSA :param start_symbol: the grammar/forest start symbol :param sprime_symbol: if specified, the resulting forest will have sprime_symbol as its starting symbol :param eps_symbol: if not None, the parser will support epsilon rules :returns: a CFG object representing the intersection between the cfg and the fsa """ # start an agenda of items A = Agenda() # this is used to avoid a bit of spurious computation have_predicted = set() # populate the agenda with axioms for item in axioms(cfg, fsa, start_symbol): A.push(item) # call inference rules for as long as we have active items in the agenda while len(A) > 0: antecedent = A.pop() consequents = [] if antecedent.is_complete(): # dot at the end of rule # try to complete other items consequents = complete(A, antecedent) else: if antecedent.next.is_terminal(): # dot before a terminal consequents = scan(fsa, antecedent, eps_symbol=eps_symbol) else: # dot before a nonterminal if (antecedent.next, antecedent.dot) not in have_predicted: # test for spurious computation consequents = predict(cfg, antecedent) # attempt prediction have_predicted.add((antecedent.next, antecedent.dot)) else: # we have already predicted in this context, let's attempt completion consequents = complete(A, antecedent) for item in consequents: A.push(item) # mark this antecedent as processed A.make_passive(antecedent) def iter_intersected_rules(): """ Here we convert complete items into CFG rules. This is a top-down process where we visit complete items at most once. """ # in the agenda, items are organised by "context" where a context is a tuple (LHS, start state) to_do = deque() # contexts to be processed discovered_set = set() # contexts discovered top_symbols = [] # here we store tuples of the kind (start_symbol, initial state, final state) # we start with items that rewrite the start_symbol from an initial FSA state for q0 in fsa.iterinitial(): to_do.append((start_symbol, q0)) # let's mark these as discovered discovered_set.add((start_symbol, q0)) # for as long as there are rules to be discovered while to_do: nonterminal, start = to_do.popleft() # give every complete item matching the context above a chance to yield a rule for item in A.complete(nonterminal, start): # create a new LHS symbol based on intersected states lhs = Span(item.lhs, item.start, item.dot) # if LHS is the start_symbol, then we must respect FSA initial/final states # also, we must remember to add a goal rule for this if item.lhs == start_symbol: if not (fsa.is_initial(start) and fsa.is_final(item.dot)): continue # we discard this item because S can only span from initial to final in FSA else: top_symbols.append(lhs) # create new RHS symbols based on intersected states # and update discovered set rhs = [] for i, sym in enumerate(item.rule.rhs): context = (sym, item.state(i)) if not sym.is_terminal() and context not in discovered_set: to_do.append(context) # book this nonterminal context discovered_set.add(context) # mark as discovered # create a new RHS symbol based on intersected states rhs.append(Span(sym, item.state(i), item.state(i + 1))) yield Rule(lhs, rhs) if sprime_symbol: for lhs in top_symbols: yield Rule(sprime_symbol, [lhs]) # return the intersected CFG :) return CFG(iter_intersected_rules()) # # Target side of the ITG # # Now we can project the forest onto the target vocabulary by using ITG rules. def make_target_side_itg(source_forest: CFG, lexicon: dict) -> CFG: """Constructs the target side of an ITG from a source forest and a dictionary""" def iter_rules(): for lhs, rules in source_forest.items(): for r in rules: if r.arity == 1: # unary rules if r.rhs[0].is_terminal(): # terminal rules x_str = r.rhs[0].root().obj() # this is the underlying string of a Terminal targets = lexicon.get(x_str, set()) if not targets: pass # TODO: do something with unknown words? else: for y_str in targets: yield Rule(r.lhs, [r.rhs[0].translate(y_str)]) # translation else: yield r # nonterminal rules elif r.arity == 2: yield r # monotone if r.rhs[0] != r.rhs[1]: # avoiding some spurious derivations by blocking invertion of identical spans yield Rule(r.lhs, [r.rhs[1], r.rhs[0]]) # inverted else: raise ValueError('ITG rules are unary or binary, got %r' % r) return CFG(iter_rules()) # # Legth constraint # # To constrain the space of derivations by length we can parse a special FSA using the forest that represents \\(D(x)\\), i.e. `tgt_forest` in the code above. # # For maximum lenght \\(n\\), this special FSA must accept the language \\(\Sigma^0 \cup \Sigma^1 \cup \cdots \cup \Sigma^n\\). You can implement this FSA designing a special FSA class which never rejects a terminal (for example by defining a *wildcard* symbol). # class LengthConstraint(FSA): """ A container for arcs. This implements a deterministic unweighted FSA. """ def __init__(self, n: int, strict=False): """ :param n: length constraint :param strict: if True, accepts the language \Sigma^n, if False, accepts union of \Sigma^i for i from 0 to n """ # each state is represented as a collection of outgoing arcs # which are organised in a dictionary mapping a label to a destination state super(LengthConstraint, self).__init__() assert n > 0, 'We better use n > 0.' self.add_state(initial=True) # we start by adding an initial state for i in range(n): self.add_state(final=not strict) # then we add a state for each unit of length self.add_arc(i, i + 1, '-WILDCARD-') # and an arc labelled with a WILDCARD # we always make the last state final self.make_final(n) def destination(self, origin: int, label: str) -> int: """Return the destination from a certain `origin` state with a certain `label` (-1 means no destination available)""" if origin + 1 < self.nb_states(): outgoing = self._states[origin] if not outgoing: return -1 return origin + 1 else: return -1 # # Enumerating paths def forest_to_fsa(forest: CFG, start_symbol: Symbol) -> FSA: """ Note that this algorithm only works with acyclic forests. Even for such forests, this runs in exponential time, so make sure to only try it with very small forests. :param forest: acyclic forest :param start_symbol: :return FSA """ fsa = FSA() # here we find out which spans end in an accepting state (the spans of top rules contain that information) accepting = set() for rule in forest.iter_rules(start_symbol): # S' -> S:initial-final for sym in rule.rhs: # the RHS contains of top rules contain the accepting states s, initial, final = sym.obj() accepting.add(final) def visit_forest_node(symbol: Symbol, bos, eos, parent: Symbol): """Visit a symbol spanning from bos to eos given a parent symbol""" if symbol.is_terminal(): fsa.add_arc(bos, eos, symbol.root().obj()) if isinstance(parent, Span) and parent.obj()[-1] in accepting: fsa.make_final(eos) else: for rule in forest.get(symbol): # generate the internal states states = [bos] states.extend([fsa.add_state() for _ in range(rule.arity - 1)]) states.append(eos) # recursively call on nonterminal children for i, child in enumerate(rule.rhs): visit_forest_node(child, states[i], states[i + 1], symbol) fsa.add_state(initial=True) # state 0 fsa.add_state(final=True) # state 1 visit_forest_node(start_symbol, 0, 1, None) return fsa def enumerate_paths_in_fsa(fsa: FSA, eps_str='-EPS-') -> set: # then we enumerate paths in this FSA paths = set() def visit_fsa_node(state, path): if fsa.is_final(state): paths.add(' '.join(x for x in path if x != eps_str)) for label, destination in fsa.iterarcs(state): visit_fsa_node(destination, path + [label]) visit_fsa_node(0, []) return paths
826b5a0545ec7c019ce008b39023fdadc40451ac
krishsharan/BUDDI-HEALTH
/deduplicate .py
407
3.65625
4
lines_read = set() # holds lines already seen outfile = open('orig.txt', "w") infile = open('correct.txt', "r") print "The file orig.txt is as follows" for line in infile: print line if line not in lines_read: # not a duplicate outfile.write(line) lines_read.add(line) outfile.close() print "The file correct.txt is as follows" for line in open('correct.txt', "r"): print line
29c81470fc2ee01f4bf0393f6b515c1451a16a3e
zTaverna/Logica-de-Programacao
/Unidade 01/teste 03.py
230
3.828125
4
compra = float(input("Digite o valor da compra: ")) valor1 = compra*1.45 valor2 = compra*1.30 if compra<20.00: print("Essse deve ser o valor da venda:",valor1) else: print("Essse deve ser o valor da venda:",valor2)
b273de9bbae377fa1b0d9101a53a0140e0ba543d
goodgoodwish/code_tip
/python/tricks.py
13,143
3.609375
4
2 Patterns for cleaner Python 2.1 Covering your ass with Assertions - debugging aid, test bugs assert_statement ::= "assert" test_condition [, error_message] if __debug__: if not test_condition: raise AssertionError(error_message) assert 0 <= price <= product["prince"] 2.2 Complacent comma placement names = [ "Zhang 3", "Li 4", "Wang 5", ] 2.3 Context managers and the with statement with open("hello.txt", "w") as f: f.write("Hellow, Yi. \n") f = open("hello.txt", "w") try: f.write("Hello, Yi. \n") finally: f.close() class ManageFile: def __init__(self, name): self.name = name def __enter__(self): self.file = open(self.name, "w") return self.file def __exit__(self, exc_type, exc_val, exc_tb): if self.file: self.file.close() with ManageFile("h1.txt") as f: f.write("Hi 1 \n") f.write("bye now. \n") from contextlib import contextmanager @contextmanager def managed_file(name): try: f = open(name, "w") yield f finally: f.close() with managed_file("h2.txt") as f: f.write("Hi 2 \n") f.write("bye now. \n") 2.4 Underscore, dunder, and more _var : intend for internal use. var_ : break (keyword) naming conflict. __var: name mangling, to rewrite attribute name to avoid naming conflicts in subclass. class Test: def __init__(self): self.foo = 18 self.__bazz = 7 def get_mangled(self): return self.__bazz def __method(self): return 42 def call_it(self): return self.__method() t = Test() dir(t) ['_Test__bazz', 'foo'] t.get_mangled() 7 t.__method() Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'Test' object has no attribute '__method' t.call_it() 42 t._Test__bazz 7 t._Test__method() 42 __var__ : reserved for special use. _ : a variable is temporary or insignificant. car = ("red", "auto", 2005, 1812.5) color, _, _, mileage = car # 2.5 String formatting, my_name = 'Jusling' my_id = 101 s1 = 'Hey %(name)s, %(id)i ' % {"name": my_name, "id": my_id} s1n = 'Hello, {}'.format(my_name) s1n1 = 'Hello, {}, {}'.format(my_name, my_id) # positional formatting s2n = 'Hello, {name}, {id}'.format(name=my_name, id=my_id) # substitution by name # Literal string interpolation, python 3.6+ s1i = f'Hello, {my_name}, you are {my_id} ' print(s1n) print(s2n) from string import Template sql_tmpl = "PARTITION = {ds} " t = Template("Hi $ds.abc") u = '{ds.__init__}' # potentially leak secret keys for ds in [1,2,3]: sql_fill = f"PARTITION = {ds}" print (sql_tmpl.format(ds=ds)) print(t.substitute(ds=ds)) print(u.format(ds=ds)) list(filter(lambda x: x>1, range(3))) # Lambda [x for x in range(4) if x > 1] # list comprehension, or generator expression # type hints def foo(a: str, b: int) -> str: ms: str = a + str(b) print(a, b) return ms foo("25", 78) # date time import datetime week_ago = datetime.date.today() - datetime.timedelta(days=7) # return example: datetime.date(2018, 7, 20) week_ago_str = "{:%Y-%m-%d}".format(week_ago) # example: 2018-07-20 sql_tmpl = "INSERT INTO table_abc PARTITION = {ds} " start_date = datetime.datetime.strptime("2017-01-01", "%Y-%m-%d") for i in range(40): curr_day = start_date + datetime.timedelta(days=i) ds = "{:%Y-%m-%d}".format(curr_day) print (sql_tmpl.format(ds=ds)) 2.6 The Zen of Python import this 3. Effective functions 3.1 Python function are first-class def yell(text): return text.upper() + "!" bark = yell # Function is object, can be stored in data structures func_list = [bark, str.lower, str.capitalize] for f in func_list: print(f("Hi there"), f) HI THERE! <function yell at 0x10129be18> hi there <method 'lower' of 'str' objects> Hi there <method 'capitalize' of 'str' objects> # Function can be passed to other functions def greet(func_a): greeting = func_a("Hi, I like swimming.") print(greeting) list(map(bark, ["hello", "hey", "hi"])) ['HELLO!', 'HEY!', 'HI!'] # Function can be nested # Function can be returned from another function. def get_speak_func(volume): def whisper(text): return text.lower() + "..." def yell(text): return text.upper() + "!" if volume > 0.5: return yell else: return whisper get_speak_func(0.8)("Watch for horse poo") 'WATCH FOR HORSE POO!' # Function can capture local state. Closure. def make_adder(base): def add(x): return base + x return add plus_2 = make_adder(base=2) plus_5 = make_adder(base=5) plus_2(2) # 4 plus_5(5) # 10 # Object can behave like function class Adder: def __init__(self, base): self.base = base def __call__(self, x): return self.base + x plus_20 = Adder(20) plus_20(2) # 22 3.2 Lambda is single-expression function # implicit return expression result, add = lambda x, y: x + y # Evaluate when access, add(1, 7) (lambda x, y: x + y)(1, 7) # Function expression list( filter(lambda x: x[0] + x[1] > 4, [(1,2),(2,3),(3,4),(4,5)]) ) [(2, 3), (3, 4), (4, 5)] 3.3 Decorator def null_decorator(func): def box(): result = func() return result + ", Zhang 3." return box @null_decorator def greet(): return "Hi" # Decorator can modify behavior. # multi decorator def strong(func): def box(): return "<strong>" + func() + "</strong>" return box def li(func): def box(): return "<li>" + func() + "</li>" return box @li @strong def greet(): return "How are you?" greet() '<li><strong>How are you?</strong></li>' # accept arguments # forward arguments def trace(func): def box(*args, **kwargs): print(f"LOG: {func.__name__}() start." f"with {args}, {kwargs}") result = func(*args, **kwargs) print(f"LOG: {func.__name__}() end.") return result return box @trace def greet(a,b,key,key2): return "How are you?" greet("a","b",key="1",key2="2") LOG: greet() start.with ('a', 'b'), {'key': '1', 'key2': '2'} LOG: greet() end. 'How are you?' # Debuggable decorators ,functools.wraps() def greet(): """return a friendly greeting.""" return "How are you?" greet.__doc__ 'return a friendly greeting.' greet.__name__ 'greet' import functools def upper_case(func): @functools.wraps(func) # <<< def wrapper(): result = func().upper() return result return wrapper @upper_case def greet(): """return a friendly greeting.""" return "How are you?" greet.__doc__ 'return a friendly greeting.' greet.__name__ 'greet' 3.4 Fun with *args and **kwargs def foo(required_arg, *args, **kwargs): print(required_arg) if args: print(args) for idx, item in enumerate(args): print(idx, item) if kwargs: print(kwargs) for (key, value) in kwargs.items(): print(f"key: {key}, value: {value} ") foo("required_arg1", 1, 2, key1="value_1", key2 = 789) required_arg1 (1, 2) 0 1 1 2 {'key1': 'value_1', 'key2': 789} key: key1, value: value_1 key: key2, value: 789 * Forwarding optional or keyword arguments, class Car: def __init__(self, color, wheel): self.color = color self.wheel = wheel class AlwaysRedCar(Car): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.color = "red" AlwaysRedCar("green", 4).color 'red' AlwaysRedCar("green", wheel=8).wheel 8 3.5 Function argument unpacking def print_vector(x, y, z, *args, **kwargs): print(f"<{x}, {y}, {z}. {args}. {kwargs} > ") tuple_vec = (1, 2, 3) print_vector(*tuple_vec) gen_expr = (x * x for x in range(5)) print_vector(*gen_expr) <0, 1, 4. (9, 16)> dict_vec = {"y":2, "z":3, "x":1, "u":4} print_vector(**dict_vec) <1, 2, 3. (). {'u': 4} > 3.6 Nothing to return here # 4 Class and OOP # 4.7 Class vs instance variable class Noodle: ingredient = "flour" name = "Noodle" count = 0 def __init__(self, name): self.name = name self.count = 0 def eat(self): self.__class__.count += 1 self.count += 2 print("instance name: ", self.name) print("class name: ", self.__class__.name) print("class var, ingr: ", self.__class__.ingredient) print("instance var, count: ", self.count) print("class var, count: ", self.__class__.count) qi_shan = Noodle("qi_shan") qi_shan.eat() # 5 Common data structures # 5.1 phone_book = { "bob": 1002, "alice": 1003, "jusling": 1004, } squares = {x: x*x for x in range(4)} {0: 0, 1: 1, 2: 4, 3: 9} import collections d = collections.OrderedDict(one=1, two=2, three=3) d["four"] = 4 d.keys() odict_keys(['one', 'two', 'three', 'four']) from collections import defaultdict dd = defaultdict(list) dd["dogs"].append("Rufus") dd["dogs"].append("Juliet") dd["dogs"] from collections import ChainMap dict1 = {'one': 1, 'two': 2} dict2 = {'three': 3, 'four': 4} chain = ChainMap(dict1, dict2) chain ChainMap({'one': 1, 'two': 2}, {'three': 3, 'four': 4}) # ChainMap searches each collection in the chain # from left to right until it finds the key (or fails): chain['three'] 3 chain['one'] 1 chain['ten'] KeyError: 'ten' # 6 Looping and Iteration list(range(0, 10, 2)) for i in range(0, 10, 2): print(i) 0 2 4 6 8 my_itmes = ["A","B","C"] for item in my_itmes: print(item) for i, item in enumerate(my_itmes): print(f"{i}: {item}") emails = { "Bob": "bob@abc.com", "Alice": "alice@abc.com", } for name, email in emails.items(): print(f"{name} -> {email}" ) 7. 7.1 Dictionary default values id_name = { 58: "Linton", 92: "Tom", 21: "Drewsling" } def greeting(user_id): if user_id in id_name: return f"Hi {id_name[user_id]} ! " else: return "Hi friend." """easier to ask for forgiveness than permission, EAFP""" try: return f"Hi {id_name[user_id]} ! " except KeyError: return "Hi friend." user_id=18 "Hi %s!" % id_name.get(user_id, "friend") user_id=21 f"""Hi {id_name.get(user_id, "friend")}""" 7.2 Sorting Dictionary for fun xs = { "b": 3, "c": 4, "a": 2, "d": 1, } sorted(xs.items()) [('a', 2), ('b', 3), ('c', 4), ('d', 1)] sorted(xs.items(), key=lambda x: x[1]) sorted(xs.items(), key=lambda x: x[1]) [('d', 1), ('a', 2), ('b', 3), ('c', 4)] # using itemgetter() to retrieve specific fields, import operator sorted(xs.items(), key=operator.itemgetter(1)) [('d', 1), ('a', 2), ('b', 3), ('c', 4)] sorted(xs.items(), key=operator.itemgetter(0)) [('a', 2), ('b', 3), ('c', 4), ('d', 1)] sorted(xs.items(), key=operator.itemgetter(0), reverse=True) [('d', 1), ('c', 4), ('b', 3), ('a', 2)] 7.3 Emulating Switch/Case statement with Dict, and function variable def my_func_1(a, b): return a + b def my_func_2(a, b): return a * b def my_func_other(a, b): return max(a, b) my_functions = [my_func_1, my_func_2] my_functions[0](3,5) 8 function_dict = { "plus": my_func_1, "multi": my_func_2, } function_dict["multi"](3,5) 15 def dispatch_dict(operator, x, y): return function_dict.get(operator, my_func_other)(x, y) dispatch_dict("unknow", 7, 8) 8 dispatch_dict("plus", 7, 8) 15 7.4 The craziest dict expression, >>> {True: "yes", 1: "no", 1.0: "maybe"} {True: 'maybe'} >>> True == 1 == 1.0 True xs = dict() xs[True] = 'yes' xs[1] = 'no' xs[1.0] = 'maybe' ["no", "yes"][True] # "yes" , True == 1. class AlwaysEqual: def __eq__(self, other): return True def __hash__(self): return id(self) AlwaysEqual() == 28 # True a = AlwaysEqual() b = AlwaysEqual() hash(a), hash(b) # (4390785152, 4390785264) 7.5 Many ways to merge Dictionary xs = {"a": 1, "b": 2} ys = {"c": 3, "d": 4} zs = {} zs.update(xs) zs.update(ys) zs {'a': 1, 'b': 2, 'c': 3, 'd': 4} # Python 3.5 zs = {**xs, **ys} {'a': 1, 'b': 2, 'c': 3, 'd': 4} 7.6 Dictionary pretty printing zs = {'a': 1, 'b': 2, 'c': 0xc0ffee, 'd': 4} str(zs) import json json.dumps(zs, indent=4, sort_keys=True) zs["e"] = {1,2,3} import pprint pprint.pprint(zs) {'a': 1, 'b': 2, 'c': 12648430, 'd': 4, 'e': {1, 2, 3}} 8 Pythonic productivity techniques 8.1 Exploring Python modules and objects import datetime dir(datetime) dir(datetime.date) [x for x in dir(datetime) if "date" in x.lower()] ['date', 'datetime', 'datetime_CAPI'] help(datetime.date) 8.2 Isolating project dependencies with virtualenv cd ~/app/python python -m venv ./env1 source ./env1/bin/activate which pip which python pip list pip install schedule pip list deactivate find ./ -name requirements.txt .//git/bi-cloud/etl/requirements.txt 8.3 Peeking behind the Bytecode curtain def greet(name): return "Hi, " + name + "!_!" greet.__code__.co_code greet.__code__.co_varnames greet.__code__.co_consts import dis dis.dis(greet) 2 0 LOAD_CONST 1 ('Hi, ') 2 LOAD_FAST 0 (name) 4 BINARY_ADD 6 LOAD_CONST 2 ('!_!') 8 BINARY_ADD 10 RETURN_VALUE
f344b77283cabc4161306abb8b6880666efb53cd
Sorrou/Programming-for-Everybody
/8.1.py
262
3.78125
4
fname = input("Enter file name: ") fh = open(fname) lst = list() for line in fh: if line.rstrip().split() not in lst: lst = lst + (line.rstrip().split()) lst.sort() lst2 = list() for i in lst: if i not in lst2: lst2.append(i) print(lst2)
db00ada9c50df7ca19c5df69769970d1728135aa
jakehoare/leetcode
/python_1_to_1000/785_Is_Graph_Bipartite.py
2,019
4.09375
4
_author_ = 'jake' _project_ = 'leetcode' # https://leetcode.com/problems/is-graph-bipartite/ # Given an undirected graph, return true if and only if it is bipartite. # Recall that a graph is bipartite if we can split it's set of nodes into two independent subsets A and B such that # every edge in the graph has one node in A and another node in B. # The graph is given as follows: graph[i] is a list of indexes j for which the edge between nodes i and j exists. # Each node is an integer between 0 and graph.length - 1. # There are no self edges or parallel edges: graph[i] does not contain i, and it doesn't contain any element twice. # Set the "colour" of each node to True or False. Iterate over nodes ignoring those that have been visited before. # Set the colour of an unvisited node arbitrarily to True and add it to queue. Queue contains all nodes whose # neighbours still have to be explored. Explore the queue with depth-first search, popping off a node setting its # colour opposite to parent and failing if has same colour of parent. # Time - O(n) the number of edges # Space - O(m) the number of nodes class Solution(object): def isBipartite(self, graph): """ :type graph: List[List[int]] :rtype: bool """ n = len(graph) colours = [None] * n # initially all nodes are not coloured for i in range(len(graph)): if colours[i] is not None: continue colours[i] = True queue = [i] # coloured nodes whose edges have not been checked while queue: v = queue.pop() for nbor in graph[v]: if colours[nbor] is None: colours[nbor] = not colours[v] # set to opposite colour of v queue.append(nbor) elif colours[nbor] == colours[v]: # inconsistency, cannot create bipartite graph return False return True
ba5e2bf242e065b12ecda08ef7d840170283a648
dev-area/Python
/Examples/generators/collections-comp.py
359
3.515625
4
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Sun Jul 23 08:58:52 2017 @author: liran """ ls = [1,2,3,4] ls2 = [i for i in ls if i>2] print ls2 ls2 = [i*2 for i in ls if i>2] print ls2 d1 = {x: x**2 for x in (2, 4, 6)} print d1 d1 = {x: 'item' + str(x**2) for x in (2, 4, 6)} print d1 a = {x for x in 'abracadabra' if x not in 'abc'} print a
aae0c0cd031094ff27f9bea13707d368857457f1
xinli2/Two-dancing-figures
/two_dancing_figures.py
2,862
3.546875
4
""" File: two_dancing_figures.py Author: Xin Li Purpose: This program draws two dancing figures """ from graphics import graphics def people(x): """This function draws the First left person Arguments: x is an integer """ # Head p.ellipse(x+200,100,100,100) # Body p.line(x,250,x+400,250) p.line(x+200,100,x+200,400) p.line(x+200,400,x,600) p.line(x+200,400,x+400,600) p.line(x,250,x,50) p.line(x+400,250,x+400,50) def people2(x): """This function draws the Second left perosn Arguments: x is an integer """ p.ellipse(x+200,100,100,100) p.line(x,250,x+400,250) p.line(x+200,100,x+200,400) p.line(x+200,400,x,600) p.line(x+200,400,x+400,600) p.line(x,250,x,450) p.line(x+400,250,x+400,450) def people3(x,y): """This function Moves the person Arguments: x and y are integers """ p.ellipse(x+200,y+100,100,100) p.line(x,y+250,x+400,y+250) p.line(x+200,y+100,x+200,y+400) p.line(x+200,y+400,x,y+600) p.line(x+200,y+400,x+400,y+600) p.line(x,y+250,x,y+450) p.line(x+400,y+250,x+400,y+450) # Main carvent p=graphics(1500,1000,"short") def move1(): """This function is for movement """ people(100) people(600) p.update_frame(1) p.clear() people3(100,50) people3(600,50) p.update_frame(1) p.clear() people(100) people(600) p.update_frame(1) p.clear() people3(100,50) people3(600,50) p.update_frame(1) p.clear() people(100) people(600) p.update_frame(1) p.clear() people3(100,50) people3(600,50) p.update_frame(1) p.clear() people2(100) people2(600) p.update_frame(1) p.clear() people3(100,50) people3(600,50) p.update_frame(1) p.clear() people2(100) people2(600) p.update_frame(1) p.clear() people3(100,50) people3(600,50) p.update_frame(1) p.clear() def move2(): """This function is also for movement """ people(200) people(800) p.update_frame(1) p.clear() people3(200,50) people3(800,50) p.update_frame(1) p.clear() people(200) people(800) p.update_frame(1) p.clear() people3(200,50) people3(800,50) p.update_frame(1) p.clear() people(200) people(800) p.update_frame(1) p.clear() people3(200,50) people3(800,50) p.update_frame(1) p.clear() people2(200) people2(800) p.update_frame(1) p.clear() people3(200,50) people3(800,50) p.update_frame(1) p.clear() people2(200) people2(800) p.update_frame(1) p.clear() people3(200,50) people3(800,50) p.update_frame(1) p.clear() # Main loop while(1): move1() move2() # Hold the carvet p.mainloop()
965b80c055c4bc284fb7530498e520a23f010053
jjspetz/digitalcrafts
/py-exercises1/coins.py
604
4
4
''' builds an infinite loop ask the user if they want a single coin if they answer 'yes' or 'y' they get one and see thier total an answer of 'no' or 'n' exits the loop other answers throw an error message ''' ans = "" coins = 0 # initial setup print("You have {} coins".format(coins)) ans = input("Do you want a coin? ") while ans.lower() != 'no' and ans.lower() != 'n': if ans.lower() == 'yes' or ans.lower() == 'y': coins += 1 print("You have {} coins".format(coins)) ans = input("Do you want another? ") else: ans = input("Enter yes or no: ") print("Bye")
68aea679972caed20e3eaa679872b1da66d002d1
tyler-pruitt/PHYS-129L
/hw2_3658887/ex5_hw2_3658887.py
358
4.375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Oct 19 13:40:03 2020 @author: tylerpruitt """ def sum5thpowers(num): sum = 0 for integer in range(num,0,-1): sum += integer**5 return sum x = int(input("Enter a positive integer: ")) if x > 0: print(sum5thpowers(x)) else: print(x, 'is not a positive integer')
7cd6570ffa0f6dde2e3fe63e34d766a7634da2e3
Andy1213/Python-and-Physical-Computing
/Sunset_Blink2.py
2,169
3.875
4
# Python 3.x # Purpose: simple demo of how to blink an LED based on the position of the sun # # 2019 04 30 AJL Created file # standard library import time # site packages import RPi.GPIO as GPIO import json import urllib.request import requests # loop forever or run once loop_forever = 0 # setup GPIO using BCM numbering GPIO.setmode(GPIO.BCM) # Pin assignments LED_Pin = 23 hltPin = 13 # exit program Button_Pin = 20 # GPIO setup GPIO.setup(LED_Pin, GPIO.OUT) GPIO.setup(hltPin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.setup(Button_Pin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # sunset check URLall = "http://www.l3nhart.io/cgi-bin/SunRiseSunSetJSONwDST.py" #URLall = "https://api.sunrise-sunset.org/json?lat=42.4606&lng=-83.1346" #URLall = "http://192.168.1.91/cgi-bin/SunRiseSunSetJSONwDST.py" while True: # check if we need to halt the program if GPIO.input(hltPin): GPIO.cleanup() # cleanup all GPIO print("Shutting Down") exit() # check for sunset try: urlhand = requests.get(URLall) except: print ('Error SunriseSusnet.org') # read the raw response url_raw = urlhand.text print(url_raw) json_lines = urlhand.json() print ('Dump of json_lines >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>') print (json_lines) # pretty print the JSON print('Pretty print of json_lines >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>') print(json.dumps(json_lines, indent=4, separators=(',', ': '))) # parse the JSON - the file only contains one line # get the position of the sun (up or down) print ('Dump of sun_pos >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>') sun_pos = json_lines['TheSunIs'] print(sun_pos) # convert str to int isun_pos = str(sun_pos) # switch the light on if the sun has set if isun_pos: GPIO.output(LED_Pin, GPIO.LOW) else: GPIO.output(LED_Pin, GPIO.HIGH) time.sleep(60) # stop the loop or keep going if not loop_forever: exit()
2df720b3a5b82b1f7e41781ca0a50b8d08491d37
cuixd/PythonStudy
/2.list类型与str类型/list.py
332
3.59375
4
list1 = [1,8,2,5,8,4,5,9,9,5,9] while 5 in list1: list1.remove(5) print(list1) list2 = [3,8,6,4,7,7,8] i = 0 max = 0 sec = 0 while i < len(list2): if list2[i] > max: sec = max max = list2[i] elif list2[i] == max: pass elif list2[i] > sec: sec = list2[i] i += 1 print(max, sec)
d62bc606735d9069d199591360ad56222a43c10e
mpettersson/PythonReview
/questions/list_and_recursion/len_longest_nondecreasing_subsequence.py
5,843
4.15625
4
""" LEN LONGEST NONDECREASING SUBSEQUENCE (EPI 17.12: FIND THE LONGEST NONDECREASING SUBSEQUENCE) Write a function that takes an integer list l, then computes and returns the length of the longest nondecreasing subsequence in the list. Remember, elements of a non-decreasing subsequence are NOT required to immediately follow each other in the given list. Example: Input = [0, 8, 4, 12, 2, 10, 6, 14, 1, 9] Output = 4 # either len([0, 4, 10, 14]), len([0, 2, 6, 9]), or len([0, 8, 10, 14]) Variations: - Define a sequence of points in the plane to be ascending if each point is above and to the right of the previous point. How would you find a maximum ascending subset of a set of points in the plane? Applications: - String matching. - Analyzing card games. """ from bisect import bisect_right # APPROACH: Memoization/Dynamic Programming Approach # # This approach uses a memoization cache (which is initialized to all 1s) to record the length of the longest # nondecreasing subsequence ending at the respective index. Starting from index 1, each previous value is compared to # the current value; if the previous value is less or equal than the current, memo[current] is equal to the larger of # the memo[previous]+1 OR memo[current]. Once all of the values have been compared, the maximum memo value is returned # as the result. The following is an example of the memo table for the example (above): # # list: [0, 8, 4, 12, 2, 10, 6, 14, 1, 9] # memo (initial): [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] # [1, 2, 1, 1, 1, 1, 1, 1, 1, 1] # [1, 2, 2, 1, 1, 1, 1, 1, 1, 1] # [1, 2, 2, 3, 1, 1, 1, 1, 1, 1] # [1, 2, 2, 3, 2, 1, 1, 1, 1, 1] # [1, 2, 2, 3, 2, 3, 1, 1, 1, 1] # [1, 2, 2, 3, 2, 3, 3, 1, 1, 1] # [1, 2, 2, 3, 2, 3, 3, 4, 1, 1] # [1, 2, 2, 3, 2, 3, 3, 4, 2, 1] # memo (final): [1, 2, 2, 3, 2, 3, 3, 4, 2, 4] # # Time Complexity: O(n**2), where n is the number of elements in the list. # Space Complexity: O(n), where n is the number of elements in the list. def len_longest_nondecreasing_subsequence_memo(l): if isinstance(l, list): memo = [1] * len(l) # Each element of l has a length of one to start with. for i in range(1, len(l)): # Start at the second element (the first won't change): for j in range(0, i): # And for each of the previous elements (starting at idx 0): if l[i] >= l[j] and memo[i] < memo[j] + 1: # If they are smaller than the current element AND their memo[i] = memo[j] + 1 # length (memo) is higher, use their length (memo) + 1 return max(memo) if len(memo) > 0 else 0 # APPROACH: Greedy With Binary Search (AKA Modified Patience Sort) # # Patience Sort uses 'piles' (or lists) of 'cards' (numbers), where each 'new card' (or a current value) is placed on # the furthest left 'pile' (list) with a value greater than the current value. If there is no 'pile' with a top 'card' # less than the current 'card' a new 'pile' (list) is created (on the right). The number of 'piles' at the end of the # sort is the length of the longest nondecreasing subsequence. Consider the following example: # # cards: [0, 8, 4, 12, 2, 10, 6, 14, 1, 9] # piles: 0 8 12 14 # 4 10 9 # 2 6 # 1 # # This approach DOES NOT use multiple 'piles' due to the high overhead to sort/search multiple lists. However, a single # list can be used to emulate the tops of the piles; the list of 'top cards' can be quickly searched via binary search. # Then the value of the 'top car' is replaced (as opposed to being stacked on) thus maintaining the number and top value # of the piles. Once complete the length of the list of top values is returned. Consider the example above with this # new Greedy/Binary Search approach: # # l: [0, 8, 4, 12, 2, 10, 6, 14, 1, 9] # piles: [] # [0] # [0, 8] # [0, 4] # [0, 4, 12] # [0, 2, 12] # [0, 2, 10] # [0, 2, 6] # [0, 2, 6, 14] # [0, 1, 6, 14] # [0, 1, 6, 9] # # Time Complexity: O(n * log(n)), where n is the number of elements in the list. # Space Complexity: O(n), where n is the number of elements in the list. def len_longest_nondecreasing_subsequence(l): if isinstance(l, list): tops = [] # This emulates the tops of the piles in a Patience Sort. for e in l: # For each value in the list: if len(tops) == 0 or e >= tops[-1]: # If no 'piles' yet, or current value is greater than top values: tops.append(e) # Make a new 'pile'. else: # Else tops[bisect_right(tops, e)] = e # Binary search for the value to replace with the current value. return len(tops) # Return the number of 'piles'. lists = [[0, 8, 4, 12, 2, 10, 6, 14, 1, 9], [0, 8, 0, 0, 2, 8, 2, 8, 0, 8], [10, 5, 8, 3, 9, 4, 12, 11], [9, 11, 7, 16, 7, 15, 10, 14, 19, 2], [7, 3, 7, 6, 5, 3, 4, 2, 4, 10], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [10, 9, 8, 7, 6, 5, 4, 3, 2, 1], []] fns = [len_longest_nondecreasing_subsequence_memo, len_longest_nondecreasing_subsequence] for l in lists: print(f"l: {l}") for fn in fns: print(f"{fn.__name__}(l): {fn(l[:])}") print()
ed475cf75f3db1be5357d77e149bf8598206692e
AAUCrisp/Python_Tutorials
/Susanne/06_opgave.py
770
4.3125
4
#Write a function that takes two lists and one integer as inputs and moves the last element of the first list to the second list at the specific position defined by the integer #defining a function that prompts the user to enter a integer to be moved: def PositionMove(list1, list2): move = int(input("Enter the number you want the last element of first list to be moved to in the second list:")) lastNumber = list1[-1] list1.remove(lastNumber) list2.insert(move, lastNumber) #defining a function that defines the lists and calls the above function def main(): list1 = [1,2,3,4,5,6,7,8,9,10] list2 = [10,9,8,7,6,5,4,3,2,1] PositionMove(list1, list2) print("The new list is", list2) #calling the main function main()
53af5a732b4f9c08e07edf907c3d6f54fc6cbce4
JohnSV18/sky-is-falling-game
/run.py
1,797
3.859375
4
import pygame import random from screen import Screen from ball import Ball from basket import Basket def main(): """Runs the whole game and also stops it once the requirements are met""" target_score = random.randint(7,11) health = 10 points = 0 velocity = 7 screen = Screen() basket = Basket() clock = pygame.time.Clock() game_is_running = True balls = [] while game_is_running: clock.tick(screen.frames_per_second) for event in pygame.event.get(): if event.type == pygame.QUIT: game_is_running = False while len(balls) < 3: ball = Ball(balls.count) ball.set_position_x() balls.append(ball) for ball in balls: if health > 0: ball.rect.y += random.randint(2,6) else: ball.rect.y = -10 if points == target_score: ball.rect.y = -10 if ball.check_ball_collision(basket): points += 1 balls.remove(ball) if ball.rect.y > screen.screen_size[1]: health -= 1 balls.remove(ball) # This allows the cart to move from left to right based on the keys the user is pressing keys_pressed = pygame.key.get_pressed() if keys_pressed[pygame.K_LEFT] and basket.rect.x - velocity >0: basket.rect.x -= velocity if keys_pressed[pygame.K_RIGHT] and basket.rect.x + velocity + basket.rect.width < screen.screen_size[0]: basket.rect.x += velocity screen.draw_window(basket, balls, health, points, target_score) if __name__ == "__main__": main()
ce7b1f0f8eba1c58701439ee10d64420c8e21d1a
noicht/practicaspython
/binary_search.py
503
3.75
4
#Busqueda binaria -> busca un elemento dentro de una lista ordenada y devuelve su posicion dentro de ella en O(log n) def binary_search(list, item): low = 0 high = len(list) - 1 while low <= high: mid = (low + high) guess = list[mid] if guess == item: return mid if guess > item: high = mid - 1 else: low = mid + 1 return None my_list = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25] print(binary_search(my_list, 10)) print(binary_search(my_list, 25))
eb0f22c439b77d5bc73f8910145649bb333fe74a
MaximillianPurnomo/bootcamp2021S1
/programming boothcamp-2021S1.py
894
4.25
4
# BY : Maximillian Purnomo # This is a code for sorting an array of numbers # The code works by going through the each items inside the array and use an index as a bench mark # Then compare it to the rest of the items inside the array, it will swap the position when it found a smaller number # than the current benchmark's number. # So when it finished going through the array of numbers, it will be sorted already # as it will always try to put smaller number to the front # The sorting function def sortingCode(aList): length=len(aList) for index in range(0,length): for index2 in range(index+1,length): if aList[index2]<aList[index]: temp=aList[index] aList[index]=aList[index2] aList[index2]=temp return aList # The testing code list1=[5,4,3,2,5.5] list1=sortingCode(list1) print(list1)
f94aa395604ae4be921baaa97b275d109e53936f
KapilArora26/Python
/Data Structures/LinkedList/CircularLLst.py
1,217
3.953125
4
#Circular Linked List class Node: def __init__(self, dataval): self.datav = dataval self.next = None class CLinkedList: def __init__(self): self.head = None def insert(self, dataval): var = Node(dataval) var.next = self.head #print("Curr Value is {} and next value is {}".format(var.datav,var.next)) if self.head is None: self.head = var return else: start = self.head while start is not None: if start.next is None: start.next = var return elif start.next == self.head: start.next = var return else: print("Next value is {}".format(start.next)) start = start.next return def printlist(self): printval = self.head while printval is not None: print (printval.datav) printval = printval.next if printval == self.head: break list = CLinkedList() list.insert(1) list.insert(2) list.insert(3) list.printlist()
3e29b5278a5bbae2f5cb92b8c8043c082fb46e5c
AkashSDas/python_code_snippets
/Numpy/Basics/05-Mathematical-Operation-using-Numpy.py
1,097
4.3125
4
# ###### Mathematical Operations using Numpy ###### # ================================= # Importing numpy module import numpy as np # ================================= # ### Basic Mathematical Operations ### # Creating a an array a = np.array([1,2,3,4]) # These effects will be on every element in the array print(a + 2) print(a - 3) print(a * 10) print(a / 3) print(a ** 2) a += 2 print(a) # Performing mathematical operations between arrays b = np.array([1,0,1,0]) print(a + b) # ================================= # ### sin method ### a = np.sin(a) print(a) # ================================= # ### cos method ### a = np.cos(a) print(a) # ================================= # So we can use mathematical functions like: # - Trignometric Functions # - Hyperbolic Functions # - Rounding # - Sums, Products, Differences # - Exponents and Logarithms # - Other special functions # > i0(x) --> Modified Bessel function of the first kind, order 0 # > sinc(x) --> Return the sinc function # - Floating point routines # - Rational routine # - Arithmetic Operations # - Handling complex numbers
a2cdeff3141373b7844de2c2549a1664f981f1ed
rbk1234567/python_basics
/classes.py
1,837
4.5
4
print("class in python -----------------------------------------------------------------------------------------------") class Car1: name = "car with 4x4" def printname(self): print(self.name) a = Car1() # creation of new Car class object (instatination) a.printname() # use class method printname print("class in python (with constructor) -----------------------------------------------------------------------------------------------") class Car2: def __init__(self,name): # constructor, self must be first argument self.name = name def printname(self): print(self.name) a = Car2("really fast car") # creation of new Car class object and initialization of its values by constructor (instatination) a.printname() # use class method printname print("class in python (with constructor and default value) -----------------------------------------------------------------------------------------------") # constructor can pass default values but rules as with functions default attributes apply class Car3: def __init__(self,company,model,color = "red"): # constructor, self must be first argument self.company = company self.model = model self.color = color def printcardata(self): print(self.company,self.model,self.color,sep="-") a = Car3("BMW","M3") # creation of new Car class object and initialization of its values by constructor (instatination) b = Car3("FIAT","500","black") a.printcardata() # use class method printname b.printcardata() a.__setattr__("company","AUDI") # setter (mutator) print(a.__getattribute__("company")) # getter (accessor) #a.__delattr__("company") #deletes attribute company but generate error when method using it is called a.printcardata() del b # deletes instance of Car3 (to garbage collector)
82434a2f9f45f513db80c28351af23e7d11a3718
wing603/python3
/06_名片管理/cards_tools.py
3,992
3.90625
4
# 列表记录所有的名片字典 card_list = [] def show_menu(): #显示菜单 print("*" * 50) print("欢迎使用名片管理系统\n") print("1.新建名片\t") print("2.显示全部\t") print("3.查询名片\n") print("0.退出系统") print("*" * 50) def new_card(): """新增名片""" print("-" * 50) print("新增名片") # 提示用户输入名片信息 name_str = input("请输入姓名 :") phone_str = input("请输入电话 :") qq_str = input("请输入qq :") email_str = input("请输入邮箱 :") # 使用用户信息建立名片字典 card_dict = {"name":name_str, "phone":phone_str, "qq":qq_str, "email":email_str} # 将名片字典添加到列表中 card_list.append(card_dict) print(card_list) # 提示用户添加成功 print("添加 %s 成功" % name_str) def show_all(): """显示所有名片""" print("-" * 50) print("显示所有名片") # 判断是否存在名片 如果没有 提示用户返回 if len(card_list) == 0: print("当前没有任何的名片记录,请使用新增功能添加名片") # 可以返回一个函数的执行结果 # return 下方的代码不会被执行 return # 打印表头 for name in ["姓名","电话","QQ","邮箱"]: print(name,end="\t\t") print("") # 打印分割线 print("=" * 50) # 遍历名片依次显示名片信息 for card_dict in card_list: print("%s\t\t%s\t\t%s\t\t%s" %(card_dict["name"], card_dict["phone"], card_dict["qq"], card_dict["email"])) def search_card(): """搜索名片""" print("-" * 50) print("搜索名片") # 提示用户输入要搜索的姓名 find_name = input("请输入要搜索的姓名 :") # 遍历card_list查询搜索到的姓名 # 如果没有找到,返回抱歉没有找到 for card_dict in card_list: if card_dict["name"] == find_name: print("找到 %s" % find_name) print("姓名\t\t电话\t\tQQ\t\t邮箱\t\t") print("%s\t\t%s\t\t%s\t\t%s" % (card_dict["name"], card_dict["phone"], card_dict["qq"], card_dict["email"])) deal_card(card_dict) break else: print("没有找到%s " %find_name) # 修改删除名片 def deal_card(card_info): """处理查找到的名片 :param card_info:查找到的名片 """ print(card_info) action_str = input("请选择要执行的操作 " "[1]修改 [2]删除 [0]返回主菜单") if action_str == "1": card_info["name"] = input_card_info(card_info["name"],"姓名(回车不修改):") card_info["phone"] = input_card_info(card_info["phone"],"电话(回车不修改):") card_info["qq"] = input_card_info(card_info["qq"],"QQ (回车不修改):") card_info["email"] = input_card_info(card_info["email"],"邮箱(回车不修改):") print("修改名片成功") elif action_str == "2": card_list.remove(card_info) print("删除名片成功") def input_card_info(dict_value,tip_message): """输入名片信息 :param dict_value:字典中原有的键值 :param tip_message:输入的提示文字 :return:如果用户输入内容返回内容;没有输入返回原有的值 """ # 1. 提示用户输入内容 result_str = input(tip_message) # 2. 判断用户是否输入内容 用户输入内容 直接返回结果 if len(result_str) > 0: return result_str # 3. 用户没有输入内容 返回字典原有的键值 else: return dict_value
b1ef18f69b434752dc1e3d672762c2973f1689da
PacoCampuzanoB/Python-Course
/control-de-flujo/break.py
176
3.796875
4
"""Programa que muestra el uso de la sentencia break """ for x in range(1,21): if(x == 10): break print(x) for x in "Hola mundo": if(x == "m"): break print(x)
5a19199fce466448e092ef796e90ffbb48e3db75
whyismefly/learn-python
/100/100-53.py
194
4.0625
4
#!/usr/bin/python # encoding:utf_8 # 题目:学习使用按位异或 ^ 。 # 程序分析:0^0=0; 0^1=1; 1^0=1; 1^1=0 a = 77 b = a ^ 3 print 'a ^ b is %d' % b b ^= 7 print 'a ^ b is %d' % b
2ccdf6fe11ef498427e893324f70b56a19b3250c
HuangJi/crackingInterview
/hackerrank/wangBraces.py
508
3.765625
4
value = raw_input() stack = [] leftBrace = {'[', '{', '('} # rightBrace = {']', '}', ')'} for brace in value: try: if brace in leftBrace: stack.append(brace) elif brace == ']' and stack[-1] == '[' \ or brace == '}' and stack[-1] == '{' \ or brace == ')' and stack[-1] == '(': stack.pop() else: return False except Exception as e: return False if len(stack) == 0: return True else: return False
759f999687314a921f851deb49813999c2404962
rafaelperazzo/programacao-web
/moodledata/vpl_data/455/usersdata/296/109661/submittedfiles/programa.py
327
4.3125
4
# -*- coding: utf-8 -*- n = int(input("Digite a dimensão do quadrado: ")) while not n>=3: n = int(input("Digite a dimensão do quadrado: ")) matriz =[] for i in range (0,n,1): linha = [] for j in range (0,n,1): linha.append(int(input("Digite um valor para o elemento da linha: ")) matriz.append(linha)
24917fa769ae924a96774358a024001eeb4b14a5
nickyfoto/lc
/python/951.flip-equivalent-binary-trees.py
2,697
3.84375
4
# # @lc app=leetcode id=951 lang=python3 # # [951] Flip Equivalent Binary Trees # # https://leetcode.com/problems/flip-equivalent-binary-trees/description/ # # algorithms # Medium (64.87%) # Total Accepted: 21.9K # Total Submissions: 33.8K # Testcase Example: '[1,2,3,4,5,6,null,null,null,7,8]\n[1,3,2,null,6,4,5,null,null,null,null,8,7]' # # For a binary tree T, we can define a flip operation as follows: choose any # node, and swap the left and right child subtrees. # # A binary tree X is flip equivalent to a binary tree Y if and only if we can # make X equal to Y after some number of flip operations. # # Write a function that determines whether two binary trees are flip # equivalent.  The trees are given by root nodes root1 and root2. # # # # Example 1: # # # Input: root1 = [1,2,3,4,5,6,null,null,null,7,8], root2 = # [1,3,2,null,6,4,5,null,null,null,null,8,7] # Output: true # Explanation: We flipped at nodes with values 1, 3, and 5. # # # # # # Note: # # # Each tree will have at most 100 nodes. # Each value in each tree will be a unique integer in the range [0, 99]. # # # # # # # # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # def flipEquiv(self, root1: TreeNode, root2: TreeNode) -> bool: def flipEquiv(self, root1, root2): # print(root1, root2) def equal_in_val(n1, n2): #only compare two node, not their children # if not n1 and not n2: # return True # if n1 and n2: # print(n1.val, n2.val) if n1 and not n2: return False if n2 and not n1: return False # print(n1.val, n2.val) return n1.val == n2.val def dfs(node1, node2): if not node1 and not node2: return True if equal_in_val(node1, node2): return (dfs(node1.left, node2.left) and dfs(node1.right, node2.right)) or (dfs(node1.left, node2.right) and dfs(node1.right, node2.left)) return False return dfs(root1, root2) # from tn import null, buildRoot # s = Solution() # root1 = [1,2,3,4,5,6,null,null,null,7,8] # root2 = [1,3,2,null,6,4,5,null,null,null,null,8,7] # root1 = buildRoot(root1) # root2 = buildRoot(root2) # print(s.flipEquiv(root1, root2)) # root1 = [1,2,3,4,5,6,null,null,null,7,8] # root2 = [1,3,2,null,6,4,5,null,null,null,null,8] # root1 = buildRoot(root1) # root2 = buildRoot(root2) # print(s.flipEquiv(root1, root2))
98bd97b5cf86772415de7e91658c7a65aeb2e21d
diesarrollador/Code-war--Code-logic
/season-2/juice-maker-class.py
909
4.125
4
""" Se le da una clase de jugo, que tiene propiedades de nombre y capacidad. Debe completar el código para habilitar y agregar dos objetos Juice, lo que da como resultado un nuevo objeto Juice con la capacidad combinada y los nombres de los dos jugos que se agregan. Por ejemplo, si agrega un jugo de naranja con una capacidad de 1.0 y un jugo de manzana con una capacidad de 2.5, el jugo resultante debe tener: nombre: capacidad de naranja y manzana: 3.5 Los nombres se han combinado usando un símbolo &. """ class Juice: def __init__(self, name, capacity): self.name = name self.capacity = capacity def __str__(self): return (self.name + ' ('+str(self.capacity)+'L)') def __add__(self, otro): return '{}&{} ({}L)'.format(self.name, otro.name, self.capacity + otro.capacity) a = Juice('Orange', 1.5) b = Juice('Apple', 2.0) result = a + b print(result)
66d560c3dfb667dfb003d119fec5517f5e2d8712
rafaelperazzo/programacao-web
/moodledata/vpl_data/148/usersdata/275/65220/submittedfiles/testes.py
180
3.796875
4
# -*- coding: utf-8 -*- #COMECE AQUI ABAIXO c= float(input('Digite a temperatua em graus Celcius')) f= ((9*(c))+160)/5 print(c, 'graus celcius corresponde a', f, 'em fahrenhiet')
7372ddc5f54d969f26b620cc9e9bf67cfbd8ad3a
fowbi/advent-of-code
/2020/star_09/encoding_error.py
1,258
3.734375
4
"""https://adventofcode.com/2020/day/9""" data = [] with open('./input.txt', 'r') as file: for line in file: data.append(int(line)) def isValid(value, numbers): for n1 in numbers: for n2 in numbers: if (n1 != n2) and (n1 + n2 == value): return True return False def findInvalidNumber(data, preamble): for index, num in enumerate(data): if index < preamble: continue f = index - preamble to = index if not isValid(num, data[f:to]): return num return 0 def solve_first_part(data, preamble): return findInvalidNumber(data, preamble) def solve_second_part(data, preamble): invalidNumber = findInvalidNumber(data, preamble) check = data for index, num in enumerate(data): if (num >= invalidNumber): continue s = 0 col = [] for n2 in data[index:]: if s == invalidNumber: return min(col) + max(col) break if (n2 >= invalidNumber) or (s > invalidNumber): break s += n2 col.append(n2) return 0 print(solve_first_part(data, 25)) print(solve_second_part(data, 25))
8b8b2a5220317fe32f3e3cbf5d76147d645840bf
whoaks/Automation_Hadoop_Docker_AWS
/salary.py
388
3.625
4
import pandas dataset=pandas.read_csv('/root/Salary_Data.csv') y=dataset['Salary'] x=dataset['YearsExperience'] from sklearn.linear_model import LinearRegression x=x.values x=x.reshape(-1,1) model=LinearRegression() model.fit(x,y) exp=input('\t\t\t\tEnter Value to Predict from DataSet :- ') print('\t\t\t\tPredicted Value is :- ', end='') print(model.predict([[float(exp)]])) print()
27f02ab2284f08049b090df3dc042f4916127c48
iliangos/Anomaly-Detection-using-Machine-Learning-Techniques-Thesis
/DeepAutoencoder.py
5,747
3.625
4
import numpy as np from keras import models from keras import layers from sklearn.metrics import mean_squared_error as mse class DeepAutoencoder: """This class implements Deep Autoencoder for anomaly detection. More specific, creates a Deep Autoencoder where the number of neuron defined by the given compression ratio. The predictions are made by calculating the mean squared error from predicted and target data. Parameters ---------- xTrain : numpy array This contains the training data. validationData: numpy array This contains the validation data. threshold : float This is the mininum acceptable mean squared error from predicted and target data. Attributes ---------- trainData : numpy array This contains the training data. validationData: numpy array This contains the validation data. threshold : float This is the mininum acceptable mean squared error from predicted and target data. autoencoder : instance of models This contains the deep autoencoder. """ def __init__(self, trainData, validationData=None, threshold=None): """Implement constructor of Autoencoder class. The constructor initialize the attributes of the class Autoencoder. """ self.threshold = threshold self.trainData = np.array(trainData) self.validationData = np.array(validationData) self.autoencoder = None def createAutoencoder(self, compressionRatio, numberOfHiddenLayers=4, numberOfEpochs=200, batchSize=35, printAutoencoderSummary=False): """Creates the Autoencoder. This function creates and trains the autoencoder. More spesific creates an autoencoder with given number of neurons per layer is considered by the compression ratio. Parameters ---------- compressionRatio : float The compression ratio of autoencoder. numberOfHiddenLayers : int The number of hidden layers. numberOfEpochs : int This is the number of epochs in model's training. batchSize : int The number of batchSize in model's training. printAutoencoderSummary : boolean The flag to print autoencoder's summary information. Attributes ---------- compressionRatioPerLayer : float The compression ratio of layers. autoencoder : instance of models class The deep autoencoder model. inputSize : int The size of input data in axis 1. neurons : int The number of neurons per layer. neuronsPerLayer : list Contains the neurons of every layer. """ #Create autoencoder compressionRatioPerLayer = np.power(compressionRatio,(1 / (int(numberOfHiddenLayers / 2) + 1))) autoencoder = models.Sequential() inputSize = np.size(self.trainData, axis=1) neurons = int(np.rint(inputSize * compressionRatioPerLayer)) neuronsPerLayer = [] autoencoder.add(layers.Dense(neurons,activation="relu",input_shape=(inputSize,))) for index in range(0, int(np.round((numberOfHiddenLayers + 1) / 2))): neuronsPerLayer.append(neurons) neurons = int(np.rint(neurons * compressionRatioPerLayer)) neuronsPerLayer = np.array(neuronsPerLayer) neuronsPerLayer = np.concatenate((neuronsPerLayer,np.flip(neuronsPerLayer[:-1])),axis=0) for neurons in neuronsPerLayer[1:]: autoencoder.add(layers.Dense(neurons,activation="relu")) autoencoder.add(layers.Dense(inputSize,activation=None)) #Print autoencoder summary if printAutoencoderSummary: autoencoder.summary() #Train autoencoder autoencoder.compile(optimizer="adam", loss='mean_squared_error') autoencoder.fit(self.trainData, self.trainData, epochs=numberOfEpochs, batch_size=batchSize, shuffle=True) self.autoencoder = autoencoder if self.threshold == None: self.__calcThreshold(self.trainData, self.autoencoder.predict(self.trainData)) def __calcThreshold(self, targets, predictions): """Calculates the prediction threshold. This method calculates the threshold of mean squared error between the pedictions and the targets. Parameters ---------- targets : numpy array The target values. predictions : numpy array The model's predictions. Returns ------- : float The max mean squared error of targets and predictions. """ self.threshold = np.max(mse(targets,predictions, multioutput="raw_values")) def predict(self, data): """Predict the class of one or more instances. This function choose the candidate class by taking into consideration the mean squared error and the threshold. Parameters ---------- data : ndarray The instances. Attributes ---------- predictedData : numpy array Contains the predicted data. finalPredictions : numpy array Contains the the final predictions. Returns ------- : numpy array The final predictions. """ predictedData = self.autoencoder.predict(data) finalPredictions = np.zeros((np.size(data, axis=0), 1)) for index in range(np.size(predictedData,axis=0)): if mse(data[index],predictedData[index],multioutput="raw_values") > self.threshold: finalPredictions[index] = 1 return finalPredictions
d5b7bd160a06fca7d98347b998d69782e8cac065
zhanshen/seanlab
/python/src/list_action.py
904
3.859375
4
''' Created on Mar 24, 2011 @author: xiaoxiao ''' if __name__ == '__main__': sample_list = [1, 2, 3, 4, 5] print 3 in sample_list print 2 not in sample_list """ Slice actions """ print sample_list[1] print sample_list[1:3] print sample_list[:2] print sample_list[::2] print sample_list + sample_list print sample_list * 3 print str(sample_list) #Convert to tuple print tuple(sample_list) #max print max(sample_list) #reverse for i in reversed(sample_list): print i #length print len(sample_list * 2) sample_list[3] = 123 print (sample_list) sample_list.append(5) print sample_list sample_list.insert(2, 99) print sample_list sample_list.remove(5) print sample_list
1240ab851bcd566309284ae6187d8693d05dd98d
shashanksub42/Sorting
/sort_urls.py
1,988
3.65625
4
def get_domain_name(url): var_split = url.split('/') var_split = var_split[2].split('.') return var_split[1] def print_list(stuffs): for stuff in stuffs: print(stuff) def sort_urls(urls): #Convert the urls to {index : url} pairs domain_key_val = {} for i in range(len(urls)): domain_key_val[i] = urls[i] #Filter out the domain names from the URL domains = [] for d in domain_key_val: domains.append((get_domain_name(domain_key_val[d]), d)) #Sort the domain names sorted_domains = sorted(domains) #Replace the sorted domain names with the correct URLs i = 0 sorted_urls = [] while i < len(sorted_domains)-1: #If the current domain is the same as the next domain if sorted_domains[i][0] == sorted_domains[i+1][0]: #Split both domains by '.' and save the last element in two variables #The last element will tell us whether the URL has only ended with .com, or #it has more information like port number etc. url1 = domain_key_val[sorted_domains[i][1]].split('.')[-1] url2 = domain_key_val[sorted_domains[i+1][1]].split('.')[-1] #Check if the URL ended with just 'com' or it has more information #Append to the sorted_urls only if it has more information if url1 != 'com': sorted_urls.append(domain_key_val[sorted_domains[i][1]]) if url2 != 'com': sorted_urls.append(domain_key_val[sorted_domains[i+1][1]]) i += 1 else: sorted_urls.append(domain_key_val[sorted_domains[i][1]]) i += 1 return list(dict.fromkeys(sorted_urls)) if __name__ == "__main__": with open ('sample_urls', 'r') as f: urls = f.readlines() #Strip the escape character urls = [url.strip('\n') for url in urls] print_list(sort_urls(urls))
cbdf55ac17c3b5ec6217f2f864fbbea13387ed9c
deepakgandla/prep
/objects.py
587
3.59375
4
class Student: def __init__(self, name, rollNo, m, s): self.name = name self.rollNo = rollNo self.mathScore = m self.scienceScore = s def totalGrade(self): return self.mathScore + self.scienceScore def highestScore(self): return 'math' if self.mathScore > self.scienceScore else 'science' def __str__(self): return self.name s1=Student("Deepak", 68, 95, 90) s2=Student("John", 69, 90, 90) s3=Student("Robb", 70, 85, 95) s4=Student("Jaime", 71, 95, 95) ls=[s1, s2, s3, s4] for i in ls: print(i.highestScore())
bfaeab887bd6c01c1424fe99c80a6574191363f7
piotrbartnik/pythonCodewars
/34.py
179
3.75
4
def find_all(array, n): result = [] i = 0 while i < len(array): if array[i] == n: result.append(i) i += 1 return result find_all([6, 9, 3, 4, 3, 82, 11], 3)
19611a13aa229a20dc71fe392809cfd70a442a1b
soli1101/python_workspace
/d20200730/test03.py
1,212
3.828125
4
# 0-9 사이의 정수를 랜덤하게 생성 # 예외란? 프로그램 실행 중 발생한 예상치 못한 오류: 가벼운 오류 # 예외를 처리 해 줄 수 있다. # casebycase # try: # 문장1 # 문장2 # except ????: # 예외처리문장1: # 예외처리문장2: ##사용자 정의형 에러 class EvenError(Exception): def __init__(self,msg): self.msg = msg def __str__(self): return self.msg import random try: n = int(input("숫자입력: ")) # 사용자 정의형 에러 # 사용자가 입력한 값이 짝수이면 실행안함 # 원래 시스템상의 에러가 아니라 내가 만든 것 if n%2 == 0 : raise EvenError("짝수만 입력해라... -.-") for i in range(10): a = random.randint(0,10) print(n/a) except EvenError as ee: # EvenError의 이름을 ee라고 해 print(ee) # ee를 찍어봐 print("짝수는 계산 안해줘~~") except ValueError: print("숫자만 입력하세요") except ZeroDivisionError: print("0으로 나눌 수 없음") finally: print("이 부분은 예외가 있던 없던 항상 실행됩니다 ♥ ") E1 = EvenError("안뇽") print(E1)
a6a2191feb43b176a6a3e08315584b8fd4ab1266
sidv/Assignments
/sachin/aug_10_assignments/4_num_grt.py
578
3.859375
4
num1=int(input("enter your first number :")) num2=int(input("enter your second number :")) num3=int(input("enter your third number :")) num4=int(input("enter your fourth number :")) if (num1 > num2) and (num1 > num3) and (num1 > num4): print("greatest num :",num1) elif (num2 > num1) and (num2 > num3) and (num2 > num4): print("greatest num :",num2) elif (num3 > num1) and (num3 > num2) and (num3 > num4): print("greatest num :",num3) elif (num4 > num1) and (num4 > num2) and (num4 > num3): print("greatest num :",num4) else: print("invalid input")
ff69a29f883cbb92c5d7e13696b9c780ce6db440
vicb1/miscellaneous-notes
/educational-resources/algorithms/Algorithms-master/src/main/python/algorithms/datastructures/queue/LinkedQueue.py
2,000
4.53125
5
''' * @file LinkedQueue.py * @author (original JAVA) William Fiset, william.alexandre.fiset@gmail.com * (conversion to Python) Armin Zare Zadeh, ali.a.zarezadeh@gmail.com * @date 23 Jun 2020 * @version 0.1 * @brief A simple queue implementation with a linkedlist. ''' from Queue import Queue from DoublyLinkedList import DoublyLinkedList class LinkedQueue(Queue): ''' A linked list implementation of a queue ''' def __init__(self): self.list = DoublyLinkedList() self.iterList = iter(self.list) def size(self): """ Return the size of the queue """ return self.list.size() def isEmpty(self): """ Returns whether or not the queue is empty """ return self.size() == 0 def peek(self): """ Peek the element at the front of the queue The method throws an error is the queue is empty """ if self.isEmpty(): raise Exception('Queue Empty') return self.list.peekFirst() def poll(self): """ Poll an element from the front of the queue The method throws an error is the queue is empty """ if self.isEmpty(): raise Exception('Queue Empty') return self.list.removeFirst() def offer(self, elem): """ Add an element to the back of the queue """ self.list.addLast(elem) def __iter__(self): """ Called when iteration is initialized Return an iterator to allow the user to traverse through the elements found inside the queue """ self.iterList = iter(self.list) return self def __next__(self): """ To move to next element. """ return next(self.iterList) if __name__ == '__main__': q = LinkedQueue() q.offer(1); q.offer(2); q.offer(3); q.offer(4); q.offer(5); print(q.poll()) # 1 print(q.poll()) # 2 print(q.poll()) # 3 print(q.poll()) # 4 print(q.isEmpty()) # false q.offer(1) q.offer(2) q.offer(3) print(q.poll()) # 5 print(q.poll()) # 1 print(q.poll()) # 2 print(q.poll()) # 3 print(q.isEmpty()) # true
d4b95d31f05e4ccc2e19791e7e964f710f8630c5
juyi212/Algorithm_study
/0805/배열순회.py
314
3.953125
4
arr=[ [1,2,3], [4,5,6] ,[7,8,9] ] #행우선 n=len(arr) #행의 길이 m=len(arr[0]) #열의 길이 for i in range(n): for j in range(m): print(arr[i][j],end=" ") print() print() for j in range(m): #열 for i in range(n): print(arr[i][j],end=" ") print() print()
bc878651fef6a1c6290f1dec3024fd23a8f6ef34
Ahsan196/FYP
/GetSpecificColumnsByRemovingExtraColumns.py
702
3.75
4
import csv cols_to_remove = [3] # Column indexes to be removed (starts at 0) cols_to_remove = sorted(cols_to_remove, reverse=True) # Reverse so we remove from the end first row_count = 0 # Current amount of rows processed with open("D:/FYP/newsnet/dataset/politifact_real.csv", "r",encoding="utf-8") as source: reader = csv.reader(source) with open("I:/done/bt.csv", "a", newline='',encoding="utf-8") as result: writer = csv.writer(result) for row in reader: row_count += 1 print('\r{0}'.format(row_count), end='') # Print rows processed for col_index in cols_to_remove: del row[col_index] writer.writerow(row)
7122b7e7abe8cb3b92ca5e8bb96325f91a9150d5
cehmet/python
/calismalar/quicksort.py
865
3.9375
4
def quicksort(alist,first,last): if first<last: split=partition(alist,first,last) quicksort(alist,first,split-1) quicksort(alist,split+1,last) def partition(alist,first,last): pivot=alist[first] leftmark,rightmark=first+1,last done=False while not done: while leftmark<=rightmark and alist[leftmark]<pivot: leftmark=leftmark+1 while rightmark>=leftmark and alist[rightmark]>pivot: rightmark=rightmark+1 if rightmark< leftmark: done=True else: alist[leftmark],alist[rightmark]=alist[rightmark],alist[leftmark] alist[rightmark],alist[first]=alist[first],alist[rightmark] return rightmark #----------------------------TEST--------------------------- alist = [54, 26, 93, 17, 77, 31, 44, 55, 20] quicksort(alist,0,8)
6e80fb0db1e1f8b01a6a02c9015a6fb7a29e9cdb
astafjew/trash
/threads/thread_classes.py
571
3.515625
4
import threading class CustomThread(threading.Thread): def __init__(self, id_, count, mutex): self.id = id_ self.count = count self.mutex = mutex super().__init__(self) def run(self): for i in range(self.count): with self.mutex: print(f'[{self.id}] => {i}') stdout_mutex = threading.Lock() threads = [] for i in range(10): thread = CustomThread(i, 100, stdout_mutex) thread.start() threads.append(thread) for thread in threads: thread.join() print('Main thread exiting.')
ebd663062a82872818f764699e3faef3774643fa
dikshaa1702/ml
/day12/Day_12_Code_Challenge.py
4,848
4.15625
4
""" Code Challenge Name: Titanic Analysis Filename: titanic.py Dataset: training_titanic.csv Problem Statement: It’s a real-world data containing the details of titanic ships passengers list. Import the training set "training_titanic.csv" Answer the Following: How many people in the given training set survived the disaster ? How many people in the given training set died ? Calculate and print the survival rates as proportions (percentage) by setting the normalize argument to True. Males that survived vs males that passed away Females that survived vs Females that passed away Does age play a role? since it's probable that children were saved first. Another variable that could influence survival is age; since it's probable that children were saved first. You can test this by creating a new column with a categorical variable Child. Child will take the value 1 in cases where age is less than 18, and a value of 0 in cases where age is greater than or equal to 18. Then assign the value 0 to observations where the passenger is greater than or equal to 18 years in the new Child column. Compare the normalized survival rates for those who are <18 and those who are older. To add this new variable you need to do two things 1. create a new column, and 2. Provide the values for each observation (i.e., row) based on the age of the passenger. Hint: To calculate this, you can use the value_counts() method in combination with standard bracket notation to select a single column of a DataFrame """ """ Code Challenge Name: Exploratory Data Analysis - Automobile Filename: automobile.py Dataset: Automobile.csv Problem Statement: Perform the following task : 1. Handle the missing values for Price column 2. Get the values from Price column into a numpy.ndarray 3. Calculate the Minimum Price, Maximum Price, Average Price and Standard Deviation of Price """ """ Code Challenge Name: Thanks giving Analysis Filename: Thanksgiving.py Problem Statement: Read the thanksgiving-2015-poll-data.csv file and perform the following task : Discover regional and income-based patterns in what Americans eat for Thanksgiving dinner Convert the column name to single word names Using the apply method to Gender column to convert Male & Female Using the apply method to clean up income (Range to a average number, X and up to X, Prefer not to answer to NaN) compare income between people who tend to eat homemade cranberry sauce for Thanksgiving vs people who eat canned cranberry sauce? find the average income for people who served each type of cranberry sauce for Thanksgiving (Canned, Homemade, None, etc). Plotting the results of aggregation Do people in Suburban areas eat more Tofurkey than people in Rural areas? Where do people go to Black Friday sales most often? Is there a correlation between praying on Thanksgiving and income? What income groups are most likely to have homemade cranberry sauce? Verify a pattern: People who have Turducken and Homemade cranberry sauce seem to have high household incomes. People who eat Canned cranberry sauce tend to have lower incomes, but those who also have Roast Beef have the lowest incomes Find the number of people who live in each area type (Rural, Suburban, etc) who eat different kinds of main dishes for Thanksgiving: Hint: """ """ Code Challenge Name: Telecom Churn Analysis☺ Dataset: Telecom_churn.csv Filename: telecom_churn.py Problem Statement: Read the telecom_churn.csv file and perform the following task : File Name : Telecom_Churn.py problem Statement: To perfrom analysis on the Telecom industry churn dataset - 1. Predict the count of Churned customer availing both voice mail plan and international plan schema 2. Total charges for international calls made by churned and non-churned customer and visualize it 3. Predict the state having highest night call minutes for churned customer 4. Visualize - a. the most popular call type among churned user b. the minimum charges among all call type among churned user 5. Which category of customer having maximum account lenght? Predict and print it 6. Predict a relation between the customer and customer care service that whether churned customer have shown their concern to inform the customer care service about their problem or not 7. In which area code the international plan is most availed? """ """"""""
88164ae6b51254db83f02a0d753fc8d7858406fd
Will-Gao99/snake
/linkedlist.py
1,931
3.796875
4
class Node: def __init__(self, v, n = None): self.val = v self.next = n def get_next(self): return self.next def set_next(self, n): self.next = n def get_val(self): return self.val def set_val(self, val): self.val = val """ Returns True if this node has a succesor and False otherwise """ def has_next(self): return not self.next == None def to_string(self): pass class LinkedList: def __init__(self, r = None): self.root = r self.size = 0 def get_size(self): return self.size def get_last(self): this_node = self.root while this_node is not None: if this_node.get_next() == None: return this_node else: this_node = this_node.get_next() def prepend(self, v): new_node = Node(v, self.root) self.root = new_node self.size += 1 def append(self, v): self.get_last().set_next(Node(v)) self.size += 1 def remove(self, v): this_node = self.root prev_node = None while this_node is not None: if this_node.get_val() == v: if prev_node is not None: prev_node.set_next(this_node.get_next()) else: self.root = this_node.get_next() self.size -= 1 return True # Node removed else: prev_node = this_node this_node = this_node.get_next() return False # Node not found def find(self, v): this_node = self.root while this_node is not None: if this_node.get_val() == v: return v elif this_node.get_next() == None: return False else: this_node = this_node.get_next() #
ad46b8653109fd295bb85a7edd71cc019268c4c5
tanawootc/sqliteDemo
/demoCon.py
1,109
4.09375
4
import sqlite3 from sqlite3.dbapi2 import Cursor conn =sqlite3.connect("test.db") print("connect") # conn.execute ('''CREATE TABLE COMPANY # (ID INT PRIMARY KEY NOT NULL, # NAME TEXT NOT NULL, # AGE INT NOT NULL, # ADDRESS CHAR (50), # SALARY REAL);''') # print ("Table created successfully") # conn.execute("INSERT INTO COMPANY (ID, NAME, AGE, ADDRESS, SALARY) \ # VALUES (1, 'Paul', 32, 'California', 20000.00) ") # conn.execute ( "INSERT INTO COMPANY (ID, NAME, AGE, ADDRESS, SALARY) \ # VALUES (2, 'Allen', 25, 'Texas', 15000.00) ") # conn.execute ( "INSERT INTO COMPANY (ID, NAME, AGE, ADDRESS, SALARY) \ # VALUES (3, 'Teddy', 23, 'Norway', 20000.00) ") # conn.execute ( "INSERT INTO COMPANY (ID, NAME, AGE, ADDRESS, SALARY) \ # VALUES (4, 'Mark', 25, 'Rich-Mond', 65000.00) ") # conn.commit() # print("Saved") conn.execute("DELETE from COMPANY where ID = 2;") conn.commit() print("Delete") cursor = conn.execute("select * from company") for row in cursor: print("ID ",row[0]) print("Name ",row[1]) print(row) conn.close()
e266a068bfd7f8117743d70c418b32021d184752
HarshitGulgulia/SMVIT_CODE_IT
/Vote.py
162
4.21875
4
Age=int(input("Enter your age ")) if Age>18: print("Eligible to vote") elif Age==18: print("Eligible to vote") else: print("Not Eligible to vote")
46d4b7eb66b41b480caa6b23a8ad8e4c3bb55ce4
loong520/Data-Structures-and-Algorithms-in-Python
/src/ch07/singlyl_linked_list/abstract_queue.py
597
3.609375
4
from abc import ABC, abstractmethod class AbstractQueue(ABC): def __init__(self): self._size = 0 def __len__(self): return self._size def __repr__(self): return "->".join(map(str, self)) def is_empty(self): return self._size == 0 @abstractmethod def enqueue(self, e): raise NotImplementedError @abstractmethod def dequeue(self): raise NotImplementedError @abstractmethod def peek(self): raise NotImplementedError @abstractmethod def __iter__(self): raise NotImplementedError
0e0f8d3978b8ff1f5b9809ed79318cafab014482
SaradhaRam/python-finacial-analysis-ellection-analysis
/PyBank/main.py
3,855
3.859375
4
# First import the os module # This will create file paths across operating systems import os # Module for reading CSV files import csv import datetime # Set path for file csvpath = os.path.join("Resources","budget_data.csv") ## analysis = os.path.join("..", "Analysis", "budget.txt") #Improved Reading using CSV module with open(csvpath) as csvfile: # CSV reader specifies delimiter and variable that holds contents csv_reader = csv.reader(csvfile,delimiter =",") #dict_reader = csv.DictReader(csvfile) # Read the header row first (skip this step if there is no header) csv_header = next(csvfile) # For readability, it can help to assign your values to variables with descriptive names months=[] profits =[] monthly_change =[] # Read each row of data after the header for row in csv_reader: #appending the months and profit in the csvfile to a collections(list) months.append(str(row[0])) profits.append(int(row[1])) #Calculate the total months by len() method. It counts the total rows. total_months = len(months) #Calculates the net total by sum() method net_total = sum(profits) #print the total months and net total of the budget_data print( "Financial Analysis") print("--------------------") print(f'Total Months: {total_months}') print(f"Total :${net_total}") #loop through the first row to the last row of profit/losses for x in range(1,len(profits)): #Calculate monthly change by subtracting the profit of first row to the previous row monthly_change_temp = int(profits[x])-int(profits[x-1]) #append the monthly changes to the monthly_change list monthly_change.append(monthly_change_temp) #Calculate average change by dividing the total monthly change by the count of rows # and the keep only 2 decimal places by rounding method average_change = round(sum(monthly_change)/len(monthly_change),2) #Calculate the greatest increase by max() method greatest_increase_profit= max(monthly_change) #Calculate the greatest decrease by min() method greatest_decrease_profit= min(monthly_change) #index() method to find the matching month coresponding to the greatest increase in profit. index_greatest_profit = monthly_change.index(greatest_increase_profit) #index() method to find the matching month coresponding to the greatest decrease in profit. index_decrease_profit = monthly_change.index(greatest_decrease_profit) #print the average change,greatest increase in profit and greatest decrease in profit print(f"Average Change :${average_change}") print(f"Greatest Increase in Profits: {months[index_greatest_profit+1]} (${greatest_increase_profit})") print(f"Greatest Decrease in Profits: {months[index_decrease_profit+1]} (${greatest_decrease_profit})") # Specify the file to write to output_path = os.path.join("Analysis", "report.csv") # Open the file using "write" mode. Specify the variable to hold the contents with open(output_path, 'w', newline='') as csvfile: # Initialize the csv.writer csvwriter = csv.writer(csvfile, delimiter=",") # Write the rows in csv file csvwriter.writerow(['Finacial Analysis']) csvwriter.writerow(['-----------------']) csvwriter.writerow(['Total Months:'+ str(total_months)]) csvwriter.writerow(['Total :$'+ str(net_total)]) csvwriter.writerow(['Average Change :$' + str(average_change)]) csvwriter.writerow(['Greatest Increase in Profits: '+ (months[index_greatest_profit+1]) + ' $('+ str(greatest_increase_profit)+')']) csvwriter.writerow(['Greatest Decrease in Profits: '+ (months[index_decrease_profit+1]) + ' $('+ str(greatest_decrease_profit)+')'])
3e23b78996878aa8a3a4a9328ca2529def140a5d
ashokgaire/Machine-Learning-Templates
/regression/random_forest_regression.py
1,480
3.75
4
############## Random Forest Regression #################################### import numpy as np import matplotlib.pyplot as plt import pandas as pd #import dataset datasets = pd.read_csv("data/Position_Salaries.csv") X = datasets.iloc[:, 1:2].values Y = datasets.iloc[:,2].values #Fitting Simple Vector Regression to the dataset from sklearn.ensemble import RandomForestRegressor regressor = RandomForestRegressor(n_estimators = 100, random_state= 0) regressor.fit(X,Y) # Predicting the Test set results Y_pred = regressor.predict(np.array([6.5]).reshape(-1, 1)) # Visuaizing the Regression results (for higher resolution and smooth curves) X_grid = np.arange(min(X), max(X), 0.01) X_grid = X_grid.reshape((len(X_grid),1)) plt.scatter(X, Y, color = 'red') plt.plot(X_grid, regressor.predict(X), color = 'blue') plt.title('Truth or bluff ( Random forest Regression)') plt.xlabel('Position level') plt.ylabel('Salary') plt.show() # Algorithm ########################################### ''' step 1: Pick at random K data points from the Training set. step 2: Buid the Decision Tree associated to these K data points. step 3: hoose the number Ntree of tress you want to build and repeat step 1 & 2 step 4: for a new data point, make each one of your Ntree trees predict the value of Y to for the data point in question, and assign the new data point the average across all of the predicted Y values. '''
1dbecb37eb78fb57a7a366ff4c78552dc74ae321
jkmartin5500/Rosalind
/bfs.py
1,243
3.515625
4
import re def parse_data(filename): # Get all numbers from the input data file = open(filename, 'r') contents = file.read() file.close() contents = re.compile('-?\d+').findall(contents) contents = [int(i) for i in contents] # Returned the parsed input data graph = {} for i in range(contents[0]): graph[i+1] = [] for i in range(contents[1]): graph[contents[2 * i + 2]].append(contents[2 * i + 3]) return graph, contents[0] def bfs(graph, vertices, start): distances = [-1] * vertices distances[start-1] = 0 visited = [False] * vertices visited[start-1] = True queue = [start] while len(queue) > 0: node = queue.pop(0) for neighbor in graph[node]: if not visited[neighbor-1]: distances[neighbor-1] = distances[node-1] + 1 queue.append(neighbor) visited[neighbor-1] = True return distances def main(): input = parse_data("rosalind_bfs.txt") answer = bfs(input[0], input[1], 1) output = open("output.txt", 'w') print(answer) for i in range(len(answer)): output.write(str(answer[i]) + ' ') output.close() if __name__ == "__main__": main()
d84b2846b2e748cb67a601dd36f7269cf26edd8a
mikolajGrom/SPD---Python
/lab1/pr1-master/instance.py
2,689
3.75
4
import itertools from operator import itemgetter class Instance(): def __init__(self, name, machines, jobs, tasks): self.name = name self.machines = machines self.jobs = jobs self.tasks = tasks def print_info(self): print("INFO: Instance {} consists of {} machines and {} jobs." .format(self.name, self.machines, self.jobs)) def permutation_list(self): return [x+1 for x in range(0, int(self.jobs))] def generate_permutations(self): return list(itertools.permutations(self.permutation_list())) def c_max(self, queue): time_unit = [0] * int(self.machines) for item in queue: time_unit[0] += self.tasks[item-1][0] for machine_id in range(1, int(self.machines)): if time_unit[machine_id] < time_unit[machine_id-1]: time_unit[machine_id] = time_unit[machine_id-1] time_unit[machine_id] += self.tasks[item-1][machine_id] return max(time_unit) def generate_best_cmax(self): queue = self.permutation_list() min_makespan = self.c_max(queue) for option in itertools.permutations(queue): print(">>> For " + str(option) + " c-max value is: " + str(self.c_max(option))) if self.c_max(option) < min_makespan: queue = list(option) min_makespan = self.c_max(option) print("{} option generates minimal c-max value: {}".format(queue, min_makespan)) def johnsons_algorithm(self): virtual_tasks = [[] for i in range(len(self.tasks))] optimal_begining = [] optimal_ending = [] list_of_jobs = self.permutation_list() if self.machines == "3": for item in range(len(self.tasks)): virtual_tasks[item] = [self.tasks[item][0] + self.tasks[item][1], self.tasks[item][1] + self.tasks[item][2]] elif self.machines == "2": virtual_tasks = self.tasks.copy() while len(virtual_tasks) != 0: p1 = min(virtual_tasks, key=itemgetter(0)) p2 = min(virtual_tasks, key=itemgetter(1)) if p1[0] <= p2[1]: index_of_p1 = virtual_tasks.index(p1) optimal_begining.append(list_of_jobs.pop(index_of_p1)) virtual_tasks.remove(p1) else: index_of_p2 = virtual_tasks.index(p2) optimal_ending.insert(0, list_of_jobs.pop(index_of_p2)) virtual_tasks.remove(p2) optimal_order = optimal_begining + optimal_ending print("Johnson's algorithm optimal order: {}".format(optimal_order))
f96bcb28e15d0ff5d47b6b6e0e58a7678ff7efa6
nickest14/Leetcode-python
/python/easy/Solution_141.py
653
3.84375
4
# 141. Linked List Cycle from typing import Optional # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def hasCycle(self, head: Optional[ListNode]) -> bool: fast, slow = head, head while fast and fast.next: slow = slow.next fast = fast.next.next if slow == fast: return True return False node = ListNode(1) node.next = node2 = ListNode(2) node.next.next = ListNode(3) node.next.next.next = node4 = ListNode(4) node4.next = node2 ans = Solution().hasCycle(node) print(ans)
cda284ce44a15ad78279fb9d38aa9e6dad46f154
t11a/leetcode
/easy/0014_longest_common_prefix.py
620
3.8125
4
class Solution: def longestCommonPrefix(self, strs): if len(strs) == 0: return "" min_len = float('inf') shortest = "" for i, word in enumerate(strs): if len(word) < min_len: min_len = len(word) shortest = word for i, ch in enumerate(shortest): for other in strs: if other[i] != ch: return shortest[:i] return shortest print(Solution().longestCommonPrefix(["flower","flow","flight"]) == "fl") print(Solution().longestCommonPrefix(["dog","racecar","car"]) == "")
746c67ebe41cfb57867ccf142c1b8b21d0ae2f96
AryanFazelipour/ICS3U1d-2018-19
/Working/2_3_ifstatements.py
346
3.859375
4
def caught_speeding(speed, is_birthday): if speed <= 60 and is_birthday == True or speed >= 61 and speed >= 65 and is_birthday == True: return (0) elif speed >= 61 and speed >= 80 and is_birthday == False or speed >= 81 and speed <= 85 and is_birthday == True: return (1) else: return (2) caught_speeding()
b02d25edb7e0e3d6079b10539afe2ab98a97d184
nithin-kumar/clrs_algorithms
/Orderstatitics/random_selection.py
558
3.546875
4
import random def randomized_select(a,p,r,i): if p==r: return a[p] q=randomized_partition(a,p,r) k=q-p+1 if i==k: return a[q] elif i<k: return randomized_select(a,p,q-1,i) else: return randomized_select(a,q+1,r,i-k) def randomized_partition(a,p,r): pivot=random.randrange(p,r+1) a[p],a[pivot]=a[pivot],a[p] i=p+1 x=a[p] for j in range(p+1,r+1): if a[j]<=x: a[i],a[j]=a[j],a[i] i=i+1 a[p],a[i-1]=a[i-1],a[p] return i-1 def main(): a=[3,5,7,2,4,6,8,0,-1] print randomized_select(a,0,len(a)-1,3) if __name__ == '__main__': main()
378094ad24246e03c88ee2fcc065defcff446687
djrrb/Python-for-Visual-Designer-Summer-2021
/session-3/image.py
208
3.515625
4
# call an image # move to the center translate(width()/2, height()/2) # loop 10 times for i in range(10): # draw our image image('hello-world.pdf', (0, 0)) # rotate the canvas rotate(-45)
3b226ebf67f85bc4a33b854607624271e53230ab
mahinsagotra/Python
/NumPy/accessing.py
647
4.03125
4
import numpy as np a = np.array([[1, 2, 3, 4, 5, 6, 7], [8, 9, 10, 11, 12, 13, 14]]) print(a) print(a.shape) # Get a specific element [r,c] print(a[1][5]) print(a[1][-1]) # Get a specific row print(a[0, :]) # Get a specific column print(a[:, 2]) # Getting a little fancy [startindex:endindex:stepsize] print(a[0, 1:6:2]) print(a[0, 1:-1:2]) # Change a[1, 5] = 20 print(a[1, 5]) print(a) a[:, 2] = 5 print(a) a[:, 2] = [1,2] print(a) # 3-D b= np.array([[[1,2],[3,4]],[[5,6],[7,8]]]) print(b) #Getting a specific element (work outside in) print(b[0,1,1]) print(b[0,1,:]) print('///////') print(b[:,1,:]) b[:,1,:] = [[9,9],[8,8]] print(b)
6a8d236ea375b23ca9f4292a9ecd66116cdd052e
GingerBeardx/Python
/Python_Fundamentals/strings.py
1,402
4.5
4
print "this is a sample string" name = "Zen" print "My name is", name name = "Yen" print "My name is " + name integer = 42 print "The number I am thinking of is", integer integer_2 = 68 # The following line will not work as Python cannot concatenate 'str' and 'int' objects # print "Just kidding, I am really thinking of " + integer_2 first_name = "Zen" last_name = "Coder" # using {} to inject variables into the string is known as string interpolation. print "My name is {} {}".format(first_name, last_name) ''' string.count(substring): returns number of occurrences of substring in string. string.endswith(substring): returns a boolean based upon whether the last characters of string match substring. string.find(substring): returns the index of the start of the first occurrence of substring within string. string.isalnum(): returns boolean depending on whether the string's length is > 0 and all characters are alphanumeric (letters and numbers only). Strings that include spaces and punctuation will return False for this method. Similar methods include .isalpha(), .isdigit(), .islower(), .isupper(), and so on. All return booleans. string.join(list): returns a string that is all strings within our set (in this case a list) concatenated. string.split(): returns a list of values where string is split at the given character. Without a parameter the default split is at every space. '''