blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
21fbb16cd1da3148922030c29f5f6f0563d12463
Ahmedatef-09/machine_learning
/python_files/ML_English/logistic_regreesion/logistic_regression.py
1,681
3.578125
4
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import statsmodels.api as sm sns.set() from sklearn.linear_model import LinearRegression from sklearn.feature_selection import f_regression from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split raw_data = pd.read_csv('2.02. Binary predictors.csv') # print(raw_data) data = raw_data.copy() data['Admitted'] = data['Admitted'].map({'Yes':1,'No':0}) data['Gender'] = data['Gender'].map({'Female':1,'Male':0}) # print(data) y = data['Admitted'] x1 = data[['SAT','Gender']] # print(x1) # '''lets create the regression using stats model''' x = sm.add_constant(x1) # # print(x) reg_log = sm.Logit(y,x) #this is logistic_regression code line result_log = reg_log.fit() # # print(reg_log) # print(reg_log.summary()) '''if we take np.exp(gender_coef) it will result 7 which mean in the same sat score female has 7 times higher odd than males''' #if we want to predict values the use reg_log.predict() np.set_printoptions(formatter={'float':lambda x: "{0:0.2f}".format(x)}) #format output # print(result_log.predict()) '''if you want to compare result predicted with actual you use this method''' # print(result_log.pred_table()) '''lets try to show the table in gopod look ''' df = pd.DataFrame(result_log.pred_table(),columns=['predicted 0 ','predicted 1'],index=['actual 0 ','actual 1']) # print(df) '''to calculate the accuracy ''' accuracy_df = np.array(df) accuracy_final = (accuracy_df[0,0]+accuracy_df[1,1])/accuracy_df.sum() # print(accuracy_final) '''now lets test our model ''' # print(x)
266cb9b64f570b1262f7bfd62d9d81892ced05fe
Ahmedatef-09/machine_learning
/python_files/ML_Arabic/pandas_groupby.py
618
3.546875
4
import numpy as np import pandas as pd dic = {'a':[1,2,3], 'b':[4,5,6], 'c':[7,8,9], 'key':'a b c'.split()} dic2 = {'a':[10,20,30], 'b':[40,50,60], 'c':[70,80,90], 'key':'a b c'.split()} df = pd.DataFrame(dic,index=[0,1,2]) df2 = pd.DataFrame(dic2,index=[0,1,2]) df3 = pd.concat([df,df2],axis=0) #paste dataframe,df2 under each other df4 = pd.merge(df,df2,how= 'inner',on='key')#inner join df,df2 u can merge more than one ke #df.join(df2)( in this case merge by index index df = index df2 ) but in .merge merge done by column print(df)
6e825fd8dbd70ac20d3502995a7a1efa4da77ab9
shivangsoni/NLP
/HW/ShivangSoni_HW1/CustomLanguageModel
2,439
3.546875
4
import math from collections import Counter from collections import defaultdict class CustomLanguageModel: def __init__(self, corpus): """Initialize your data structures in the constructor.""" self.unigram_count = Counter() self.bigram_count = Counter() self.trigram_count = Counter() self.vocabulary_size = 0 self.num_words = 0 self.backoff_multiplier = 0.4 self.train(corpus) def train(self, corpus): """ Takes a corpus and trains your language model. Compute any counts or other corpus statistics in this function. """ for sentence in corpus.corpus: prev_word1 = None prev_word2 = None for datum in sentence.data: word = datum.word self.unigram_count[tuple([word])] += 1 if prev_word1 != None: self.bigram_count[tuple([prev_word1,word])] += 1 if prev_word2 != None: self.trigram_count[tuple([prev_word2,prev_word1,word])] += 1 prev_word2 = prev_word1 prev_word1 = word self.vocabulary_size = len(self.unigram_count) self.num_words = sum(self.unigram_count.values()) def score(self, sentence): """ Takes a list of strings as argument and returns the log-probability of the sentence using your language model. Use whatever data you computed in train() here. """ score = 0.0 prev_word1 = None prev_word2 = None for word in sentence: three_words_count = self.trigram_count[tuple([prev_word2, prev_word1, word])] two_words_count = self.bigram_count[tuple([prev_word2, prev_word1])] # Use the trigram if it exists if (three_words_count > 0): score += math.log(three_words_count) score -= math.log(two_words_count) else: two_words_count = self.bigram_count[tuple([prev_word1, word])] one_word_count = self.unigram_count[tuple([prev_word1])] # Use the bigram if it exists if (two_words_count > 0): score += math.log(self.backoff_multiplier) score += math.log(two_words_count) score -= math.log(one_word_count) # Use the unigram in case all else fails else: score += 2 * math.log(self.backoff_multiplier) score += math.log(self.unigram_count[tuple([word])] + 1.0) score -= math.log(self.num_words + self.vocabulary_size) prev_word2 = prev_word1 prev_word1 = word return score
26a5cbe6f6590d875069427d1b72cf5f7d6a86c1
nikolajjsj/IntoToCSPython
/week2/tower_of_hanoi.py
418
3.8125
4
def printMove(from_stack, to_stack): print('Move from ' + str(from_stack) + ' to ' + str(to_stack)) def towers_of_hanoi(n, from_stack, to_stack, spare_stack): if n == 1: printMove(from_stack, to_stack) else: towers_of_hanoi(n-1, from_stack, spare_stack, to_stack) towers_of_hanoi(n, from_stack, to_stack, spare_stack) towers_of_hanoi(n-1, spare_stack, to_stack, from_stack)
dfabde0a7eddb09e12accbde3198111ff9f0cfa0
770847573/Python_learn
/Hello/正则/3.边界匹配.py
2,098
3.890625
4
""" --------------锚字符(边界字符)------------- ^ 行首匹配,和在[]里的^不是一个意思 [^xxxxx] $ 行尾匹配 \A 匹配字符串开始,它和^的区别是,\A只匹配整个字符串的开头,即使在re.M模式下也不会匹配它行的行首 \Z 匹配字符串结束,它和$的区别是,\Z只匹配整个字符串的结束,即使在re.M模式下也不会匹配它行的行尾 \b 匹配一个单词的边界,也就是值单词和空格间的位置 \B 匹配非单词边界 """ import re # search():使用指定的正则在指定的字符串中从左往右依次进行搜索,只要找到一个符合条件的子字符串,则立即停止查找,返回一个对象 # search函数的底层调用的是match # findall():使用指定的正则在指定的字符串中匹配所有符合条件的子字符串,返回一个列表 print(re.search(r"^this","this is a text")) # startswith() print(re.search(r"text$","this is a text")) # endswith() print("this is a text\nthis is a text\nthis is a text\nthis is a text") # 默认情况下,即使字符串有多行,使用^和$进行行首和行尾的匹配,都将字符串当做一行处理 print(re.findall(r"^this","this is a text\nthis is a text\nthis is a text\nthis is a text")) # ['this'] print(re.findall(r"text$","this is a text\nthis is a text\nthis is a text\nthis is a text")) # ['text'] # 如果需要匹配每个行的行首和行尾,需要设置flags=re.M,表示多行模式 print(re.findall(r"^this","this is a text\nthis is a text\nthis is a text\nthis is a text",flags=re.M)) # ['this', 'this', 'this', 'this'] print(re.findall(r"text$","this is a text\nthis is a text\nthis is a text\nthis is a text",flags=re.M)) # ['text', 'text', 'text', 'text'] # \A和\Z即使在re.M模式下也不会匹配它行的行首和行尾 print(re.findall(r"\Athis","this is a text\nthis is a text\nthis is a text\nthis is a text",flags=re.M))# ['this'] print(re.findall(r"text\Z","this is a text\nthis is a text\nthis is a text\nthis is a text",flags=re.M))# ['text']
d4509f58c0d0721b86336e567946646df9431717
770847573/Python_learn
/Hello/错误和异常/抛出异常raise.py
391
4.15625
4
# 产生异常的形式 # 形式一:根据具体问题产生异常【异常对象】 try: list1 = [12, 3, 43, 34] print(list1[23]) except IndexError as e: print(e) #形式2:直接通过异常类创建异常对象, # raise异常类(异常描述)表示在程序中跑出一个异常对象 try: raise IndexError("下标越界~~~") except IndexError as e: print(e)
fdc709509a4898c4be7205c77a5f0a7c3a3f029e
770847573/Python_learn
/Hello/正则/1.数量词匹配.py
1,759
3.875
4
""" -------------------匹配多个字符------------------------ 说明:下方的x、y、z均为假设的普通字符,n、m(非负整数),不是正则表达式的元字符 (xyz) 匹配小括号内的xyz(作为一个整体去匹配) x? 匹配0个或者1个x x* 匹配0个或者任意多个x(.* 表示匹配0个或者任意多个字符(换行符除外)) x+ 匹配至少一个x x{n} 匹配确定的n个x(n是一个非负整数) x{n,} 匹配至少n个x x{n,m} 匹配至少n个最多m个x。注意:n <= m x|y |表示或,匹配的是x或y """ """ () 表示分组,其中的内容可以当做一个整体处理 {} 数量匹配,限定指定的字符出现的次数 | 表示或,,语法:正则一|正则二,表示只要其中一个正则能够匹配上,则就可以得到结果 ? 匹配0个或者1个,非贪婪匹配 * 匹配0个或者多个,贪婪匹配 + 匹配1个或者多个【匹配至少1个】,贪婪匹配 """ import re # findall():使用指定的正则在指定的字符串中匹配所有符合条件的子字符串,返回一个列表 print(re.findall(r"a+","aaaaaaaaaaaaaaaaaaaaa")) # ['aaaaaaaaa'],至少匹配1个,尽可能多的匹配 print(re.findall(r"a?","aaaaaaaaa")) # ['a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', ''],优先匹配1个,最后必定有一个"" print(re.findall(r"a*","aaaaaaaaa")) # ['aaaaaaaaa', ''],尽可能多的匹配,最后必定有一个"" print(re.findall(r"a{3}","aaaaaaaaaa")) # ['aaa', 'aaa', 'aaa'],一次只能匹配3个 print(re.findall(r"a{3,}","aaaaaaaaa")) # ['aaaaaaaaa'],尽可能多的匹配 print(re.findall(r"a{3,5}","aaaaaaaaa")) # ['aaaaa', 'aaaa'],尽可能多的匹配
df37cd6d0c236e8f92f0892484ea4d63bfcd1d93
770847573/Python_learn
/Hello/Day13Code/4.装饰器使用一.py
2,245
4
4
# 1.闭包 def func1(): n = 45 def func2(): print(n) return func2 # 方式一 f = func1() f() # 方式二 func1()() # 2. """ 假设我们要增强某个函数的功能,但又不希望修改原函数的定义, 这种在代码运行期间动态增加功能的方式,称之为“装饰器”(Decorator) """ # 装饰器的本质:实际上是一个闭包 # 闭包的书写形式 # 方式一 def outter1(a): def inner1(b): print(a,b) return inner1 f1 = outter1(3) f1(4) # 方式二 def outter1(a): def inner1(b): print(a,b) inner1(79) outter1(3) # 实现装饰器,使用方式一 # 3.装饰器的语法 def now(): # 7 print("拼搏到无能为力,坚持到感动自己") # 需求:给now函数增加一个新的功能,但是要求不能修改now函数 # 装饰器的书写步骤 # a.书写一个闭包,外部函数的函数名其实就是装饰器的名称 # b.给外部函数设置参数,该参数表示需要被装饰的函数,一般命名为func,fun,f... def outter(func): # 2 def inner(): # 3,5 # c.调用原函数 func() # 在内部函数中调用了外部函数中的变量 6 # d.新增功能 print("new~~~~") # 8 # e.inner中包含了原函数的功能和新的功能,也就是原函数被装饰器之后的结果, 所以必须将装饰之后的结果返回 return inner # 3 # f.调用外部函数【装饰器】,将原函数作为参数传递 f = outter(now) # func = now f = inner 1 f() # 4 """ 掌握: a.语法 b.执行顺序 使用场景: 在实际项目开发中,有ABC三个人同时开发同一个项目 对于整个项目中的公共文件,一个公共文件有可能在多个地方 如果其中一个人需要使用公共文件中的功能,但是还需要增加新的功能,一定不能直接修改文件,可以使用装饰器 """ """ 注意: a.好处:在不修改原函数的基础上增加新的功能 b.调用原函数和增加新功能没有绝对的先后顺序,根据具体的需求进行调整 c.装饰器实际上还是普通的函数,所以一定要注意参数的匹配 """
7b756c270d420e1256cfe977fb7576833a54b4d5
770847573/Python_learn
/Hello/简单排序算法/1.作业讲解.py
900
3.796875
4
# 需求:利用列表推导式将已知列表中的整数提取出来 list1 = [True, 17, "hello", "bye", 98, 34, 21] # 注意:isdigit()是字符串的功能,其他类型的变量无法使用 # 方式一:str() list2 = [ele for ele in list1 if str(ele).isdigit()] print(list2) # 方式二:type() # [17, 98, 34, 21] list2 = [ele for ele in list1 if type(ele) == int] print(list2) # 方式三:isinstance(变量,类型)判断一个变量是否是指定的数据类型 list2 = [ele for ele in list1 if isinstance(ele,int) and not isinstance(ele,bool)] print(list2) # [17, 98, 34, 21] # 需求:利用列表推导式存放指定列表中字符串的长度 # 注意:列表,元组,字符串,字典和集合都可以使用len()统计元素的个数或者计算容器的长度 list1 = ["good", "nice", "see you", "bye"] # print(len("good")) list2 = [len(word) for word in list1] print(list2)
69ecb5fe76a1dee7a56808755922d0a942c069cb
770847573/Python_learn
/shopcar1/storage.py
2,479
3.65625
4
""" 仓库类:【信息保存在本地磁盘:程序刚启动时把列表先存储到文件中,之后使用再读取出来】 商品列表 商品名称 价格 剩余量 Mac电脑 20000 100 PthonBook 30 200 草莓键盘 80 60 iPhone 7000 70 """ import os,pickle from shopcar1.goods import Goods # 注意:导入类和导入函数以及变量的方式相同 # 假设存储仓库中商品列表的文件名为goodslist.txt path = r"goodslist.txt" # 任何用户,任何一次访问到仓库的时候应该访问的都是同一个仓库,所以需要将仓库类定义为单例类 def singleton(cls): instance = None def getinstance(*args,**kwargs): nonlocal instance if not instance: instance = cls(*args,**kwargs) return instance return getinstance @singleton class Storage(object): __slots__ = ("goods_list",) # 如果程序第一次启动:文件不存在,需要商品列表先存储到文件中 # 如果程序第二次以上启动:文件存在,则需要将文件中的内容读取出来 def __init__(self): # 注意:在实际项目开发中,建议早构造函数中的代码尽量简洁 self.__load_goods() # 加载商品,对于其中的操作,只在当前类中可以进行 def __load_goods(self): if os.path.exists(path): # 存在,说明程序不是第一次运行 self.get_goods() else: # 不存在,说明程序是第一次运算 # a.定义商品列表,用于存储仓库中的商品对象 self.goods_list = [] # b.模拟商品信息 name_list = ["Mac电脑","food","book","kindle"] price_list = [130000,20,78,500] num_list = [100,100,100,100] # c.遍历上述三个列表,将对应的信息获取出来,然后创建商品对象并添加到商品列表中 for i in range(len(name_list)): goods = Goods(name_list[i],price_list[i],num_list[i]) self.goods_list.append(goods) # d.将商品列表存储到文件中【对象的序列化和反序列化】 self.save_goods() def save_goods(self): with open(path, "wb") as f: pickle.dump(self.goods_list, f) def get_goods(self): with open(path, "rb") as f: self.goods_list = pickle.load(f)
7bbf2b2e59d035278ed1512201e70391af6c2e8a
770847573/Python_learn
/day19/4.多态的应用.py
1,664
4.4375
4
# 1.多态的概念 # a. class Animal(object): pass class Cat(Animal): pass # 在继承的前提下,一个子类对象的类型可以是当前类,也可以是父类,也可以是祖先类 c = Cat() # isinstance(对象,类型)判断对象是否是指定的类型 print(isinstance(c,object)) # True print(isinstance(c,Animal)) # True print(isinstance(c,Cat)) # True a = Animal() print(isinstance(a,Cat)) # False # b. class Animal(object): def show(self): print("父类") class Cat(Animal): def show(self): print("cat") class Dog(Animal): def show(self): print("dog") class Pig(Animal): def show(self): print("pig") # 定义a的时候不确定a的类型,所以不能确定a.show()调用的是哪个类中的函数 def func(a): a.show() c = Cat() d = Dog() p = Pig() # 当运行程序的时候,才能确定a的类型 func(c) func(d) func(p) # 2.多态的应用 # 好处:简化代码 # 需求:人喂养动物 class Animal(object): def __init__(self,name): self.name = name def eat(self): print("eating") class Cat(Animal): pass class Dog(Animal): pass class Pig(Animal): pass class Person(object): """ def feed_cat(self,cat): cat.eat() def feed_dog(self,dog): dog.eat() def feed_pig(self,pig): pig.eat() """ # 定义的时候ani的类型并不确定,只有当函数被调用,传参之后才能确定他的类型 def feed_animal(self,ani): ani.eat() per = Person() c = Cat("小白") d = Dog("旺财") p = Pig("小黑") per.feed_animal(c) per.feed_animal(d) per.feed_animal(p)
37cb9c59405d6f6c92945782ff7c68b5adff0388
770847573/Python_learn
/Hello/Day15/day15作业.py
504
3.609375
4
#获取当前时间,判断是否是元旦,如果不是,计算和元旦差了多少天 import datetime def get_time(): time_now = datetime.datetime.now() time_now_day = time_now.strftime('%Y/%m/%d') if time_now_day == '2021/01/01': print('今天是是元旦') else: yuandan_date =datetime.datetime(2021,1,1,0,0,0) days1= time_now - yuandan_date days2 = days1.days print('今天不是元旦,距元旦相差了{}天'.format(days2)) get_time()
bccdae6959d7354f0a68014f753b98a6e7075dc0
770847573/Python_learn
/Hello/抽象类的使用.py
400
4.125
4
import abc class MyClass(metaclass=abc.ABCMeta): @abc.abstractmethod def mymethod(self): pass class My1(MyClass): def mymethod(self): print('Do something!!!') my = My1()#如果一个类继承自抽象类,而未实现抽象方法,仍然是一个抽象类 my.mymethod() #my1 = MyClass() TypeError: Can't instantiate abstract class MyClass with abstract methods mymethod
a5fc666c80858fc0a3f313bfe562b0e25115e840
770847573/Python_learn
/Hello/Day13Code/5.装饰器使用二.py
1,517
3.875
4
# 1.需求:书写一个装饰器,对年龄进行校验 def get_age(age): print("年龄:%d" % (age)) def check_age(func): def inner(n): # 新的功能:校验传进来的年龄是否是负数,如果是负数,则改为相反数 if n < 0: n = -n # 调用原函数 func(n) return inner f = check_age(get_age) f(-6) # 使用场景:如果原函数有参数,而且在装饰器中需要对原函数中的参数做出操作,则在装饰器的内部函数中设置参数 print("*" * 30) # 2.使用 @xxx 简化装饰器的使用 # 注意1:@xxx表示将一个指定的装饰器直接作用于需要装饰的函数,xxx表示装饰器的名称 # 注意2:使用@xxx装饰函数,则装饰器必须先存在,然后才能使用 def check_age1(func): print("外部函数被执行了~~~~~~") def inner1(n): print("内部函数被执行了~~~~~") if n < 0: n = -n # 调用原函数 func(n) return inner1 # @xxx会调用装饰器的外部函数,同时将外部函数的返回值返回,原函数的函数名指向了内部函数的引用 @check_age1 # @xxx的作用相当于 check_age(get_age) def get_age1(age): print("年龄:%d" % (age)) # get_age1(-18)调用的将不再是原函数,而是装饰器的内部函数 get_age1(-18) """ 工作原理: 假设: 原函数:a 装饰器:wrapper(func) @wrapper:func = a原 a------》inner a() : inner() """
7a61d100ca4bd6b29b7642691b09b1de68709424
770847573/Python_learn
/Hello/正则/7.正则练习一.py
551
3.609375
4
# 1.要求从控制台输入用户名和密码,如果用户名和密码都输入合法,则注册成功 """ 要求: 用户名:只能由数字或字母组成,长度为6~12位 密码:只能由数字组成,长度必须为6位 """ import re username = input("请输入用户名:") pwd = input("请输入密码:") # 匹配上,返回一个对象,匹配不上,返回None r1 = re.match(r"^[0-9a-zA-Z]{6,12}$",username) r2 = re.match(r"^\d{6}$",pwd) if r1 and r2: print("注册成功") else: print("注册失败")
b10c4327168a5edd2d50a588ac0731f3b67bc4c9
KurinchiMalar/DataStructures
/DynamicProgramming/MaximumSumContiguousSubsequence.py
3,855
3.78125
4
''' Given a sequence of n numbers A(1)....A(n) give an algorithm for finding a contiguous subsequence A(i)....A(j) for which the sum of elements in the subsequence is maximum. Example : {-2, 11,-4, 13, -5, 2} --> 20 (11 + -4 + 13) {1, -3, 4, -2, -1, 6} --> 7 (4 + -2,+ -1 + 6) ''' # Time Complexity : O(n) # Space Complexity : O(1) ''' Kadane's Algorithm: Look at all positive contiguous segments of the array and keep track of the maximum sum contiguous segment(sum_end_here) among all the positvite segments(sum_so_far). Each time we get a positive sum , update sum_so_far accordingly. ''' def max_sum_contiguous_subseq_KadaneAlgorithm(Ar): sum_end_here = 0 sum_so_far = 0 for i in range(0,len(Ar)): sum_end_here = sum_end_here + Ar[i] if sum_end_here < 0: sum_end_here = 0 continue if sum_so_far < sum_end_here: sum_so_far = sum_end_here return sum_so_far # Time Complexity : O(n) # Space Complexity : O(n) # M[i] indicates maximum sum of all windows ending at i. def max_sum_contiguous_subseq_dynamic(Ar): M = [0]*(len(Ar)+1) result = [] if Ar[0] > 0: M[0] = Ar[0] else: M[0] = 0 for i in range(0,len(Ar)): if M[i-1]+Ar[i] > 0 : M[i] = M[i-1]+Ar[i] else: M[i] = 0 max_sum = 0 max_index = 0 for i in range(0,len(M)): # one complete scan to find the max value. if M[i] > max_sum: max_sum = M[i] max_index = i for i in range(0,max_index+1): if M[i] == 0: result = [] else: result.append(Ar[i]) print "The maxsum_contiguous_subseq_fromlefttoright:"+str(result) # to print the maximum seq return max_sum # Time Complexity : O(n) # Space Complexity : O(n) # M[i] indicates maximum sum of all windows starting at i. def max_sum_contiguous_subseq_dynamic_fromrighttoleft(Ar): n = len(Ar) M = [0]*(n+1) result = [] if Ar[n-1] > 0: M[n-1] = Ar[n-1] else: M[n-1] = 0 for i in range(n-2,-1,-1): if M[i+1]+Ar[i] > 0 : M[i] = M[i+1]+Ar[i] else: M[i] = 0 max_sum = 0 max_index = 0 for i in range(0,len(M)): # one complete scan to find the max value. if M[i] > max_sum: max_sum = M[i] max_index = i for i in range(n-1,max_index-1,-1): if M[i] == 0: result = [] else: result.append(Ar[i]) print "The maxsum_contiguous_subseq_fromrighttoleft:"+str(result) # to print the maximum seq return max_sum # Time Complexity : O(nlogn) # Divide and Conquer approach # Recurrence : 2T(n/2) + O(n) import sys def max_crossing_sum(Ar,l,m,hi): left_max = -sys.maxint-1 left_sum = 0 for i in range(m,l-1,-1): left_sum += Ar[i] if left_sum > left_max: left_max = left_sum right_max = -sys.maxint-1 right_sum = 0 for i in range(m+1,hi+1): right_sum += Ar[i] if right_sum > right_max: right_max = right_sum return left_max + right_max def max_value_contiguous_subsequence(Ar,low,high): if low == high: return Ar[low] mid = (low + high) // 2 return max( max_value_contiguous_subsequence(Ar,low,mid),\ max_value_contiguous_subsequence(Ar,mid+1,high),\ max_crossing_sum(Ar,low,mid,high)) Ar = [2, 3, 4, 5, 7] Ar = [-2, 11,-4, 13, -5, 2] print "max_Recursive_O(nlogn):"+str(max_value_contiguous_subsequence(Ar,0,5)) print "max_DP_O(n):"+str(max_sum_contiguous_subseq_dynamic(Ar)) print "max_DP_O(n):"+str(max_sum_contiguous_subseq_dynamic_fromrighttoleft(Ar)) print "max_Kadane's Algorithm_O(n):"+str(max_sum_contiguous_subseq_KadaneAlgorithm(Ar))
9e97f5a89008686e2f7317b30441b7f2eeffe933
KurinchiMalar/DataStructures
/Sorting/CountingSort.py
1,053
3.671875
4
# Time Complexity : O(n+k) # Space Complexity : O(n+k) def counting_sort(Ar,k): B = [0 for el in Ar] C = [0 for el in range(0,k+1)] print "Ar :"+str(Ar) print "B :"+str(B) print "C :"+str(C) for j in range(0,len(Ar)): #Build the counting array...how many times current index has occured in original Ar C[Ar[j]] = C[Ar[j]] + 1 print "C now :"+str(C) # Build array such that each index says "I have x number of smaller elements in result array less than or equal to x" for j in range(1,k+1): C[j] = C[j-1] + C[j] print "C new :" + str(C) #Put element 5 in input array = C[5] - 1 th position in Result array B. # In this eg) 5 in input array = 6th position (C[5] - 1) in B # Then subtract 1 since one occurence is captured in result already now. for i in range(len(Ar)-1,-1,-1): B[C[Ar[i]]-1] = Ar[i] C[Ar[i]] = C[Ar[i]] - 1 #print B[C[Ar[i]]-1] print "Result :" + str(B) if __name__ == '__main__': Ar = [5,2,3,1,2,3,0] counting_sort(Ar,5)
9a97498c8f5dfe49b5a0118718c8e6b81dbd97f2
KurinchiMalar/DataStructures
/Strings/RemoveAdjacentDuplicatesRecursively.py
1,016
3.890625
4
''' Recursively remove all adjacent duplicates. Given a string of characters, recursively remove adjacent duplicate characters from string. The output string should not have any adjacent duplicates. ''' # Time Complexity : O(n) # Space Complexity : O(1) ... inplace, no stack. def remove_adj_duplicates(mystring): result = [] res_idx = 0 mystring[res_idx] = mystring[0] i = 1 while i < len(mystring): if mystring[i] != mystring[res_idx]: res_idx = res_idx + 1 mystring[res_idx] = mystring[i] i = i + 1 else: while i < len(mystring) and mystring[i] == mystring[res_idx]: # recursively remove all equals. res_idx = res_idx - 1 i = i + 1 print "mystring:"+str(mystring[0:res_idx+1]) # our desired chars are only upto res_idx. mystring = "azxxzy" mystring = "geeksforgeeks" mystring = "careermonk" mystring = "mississippi" mystring = list(mystring) remove_adj_duplicates(mystring)
6b1dc96656928464dc9fd37109885b88c9560134
KurinchiMalar/DataStructures
/Searching/FirstRepeatingElement.py
2,180
3.578125
4
#https://ideone.com/daLlg9 #Time Complexity = O(n) (Building hash_ar and finding max of negatives) #Space Complexity = O(k) ---- k is the range of numbers in the input array. Here 0 to 5. Hence k = 5 ''' Solution: 1) Store the position of occurence in input array in hash_ar 2) On second occurence negate 3) If already negated just skip 4) Index of the largest negative value is the first repeating element ''' def first_repeating_element_hashing_withpositions(Ar,n): hash_ar = [0] * (n+1) for i in range(0,len(Ar)): position = hash_ar[Ar[i]] if position == 0: # first occurence hash_ar[Ar[i]] = i+1 #Array index starts from zero. hence index 0 == position 1 elif position > 0: # repeating for the first time hash_ar[Ar[i]] = -(hash_ar[Ar[i]]) # if position is negative .... just skip and move to next element. we have already registered it's repetition. print hash_ar # Find the largest negative value and return the index of it from hash_ar. result_val = 0 result_index = -1 for i in range(0,len(hash_ar)): if hash_ar[i] < 0: # seeing oly negatives if result_val == 0 or hash_ar[i] > result_val: result_val = hash_ar[i] result_index = i print "first repeating element is:"+ str(result_index) print "result_val:"+str(result_val) return result_index #YET TO UNDERSTAND THIS IMPLEMENTATION '''def FirstRepeatedElementAmongRepeatedElementsWithHash(A): table = {} # hash max = 0 for element in A: if element in table and table[element] == 1: table[element] = -2 elif element in table and table[element] < 0: table[element] -= 1 elif element != " ": table[element] = 1 else: table[element] = 0 for element in A: if table[element] < max: max = table[element] maxRepeatedElement = element print maxRepeatedElement, "repeated for ", abs(max), " times" ''' #A = [3,2,1,2,3] #FirstRepeatedElementAmongRepeatedElementsWithHash(A) #Ar = [3,2,1,2,3] Ar = [3, 2, 1, 1, 2, 1, 2, 5, 5] first_repeating_element_hashing_withpositions(Ar,5) #FirstRepeatedElementAmongRepeatedElementsWithHash(Ar)
d15a8a84b1a7e7ac54f74d47180757109a17782a
KurinchiMalar/DataStructures
/Medians/FindLargestInArray.py
505
4.28125
4
__author__ = 'kurnagar' import sys # Time Complexity : O(n) # Worst Case Comparisons : n-1 # Space Complexity : O(1) def find_largest_element_in_array(Ar): max = -sys.maxint - 1 # pythonic way of assigning most minimum value #print type(max) #max = -sys.maxint - 2 #print type(max) for i in range(0,len(Ar)): if Ar[i] > max: max = Ar[i] return max Ar = [2, 1, 5, 234, 3, 44, 7, 6, 4, 5, 9, 11, 12, 14, 13] print ""+str(find_largest_element_in_array(Ar))
dcd5df108f3668bfb8e8c2228d1cc86350703500
KurinchiMalar/DataStructures
/LinkedLists/DoublyLinkedListInsert.py
1,889
4.03125
4
class Node(object): def __init__(self, data=None, next_node=None, prev_node=None): self.data = data self.next = next_node self.prev = prev_node def SortedInsert(head, data): if head == None: head = Node(data) return head p = head newNode = Node(data) if p.data > data: # insert in beginning newNode.next = p p.prev = newNode head = newNode return head while p.next != None: if p.data > data: # insert in middle p.prev.next = newNode newNode.prev = p.prev newNode.next = p p.prev = newNode return head p = p.next if p.data < data: p.next = newNode # insert at last newNode.prev = p return head p.prev.next = newNode newNode.prev = p.prev newNode.next = p p.prev = newNode return head def print_dlist(head): current = head while current != None: print current.data, current = current.next print def swap(current): temp = current.next current.next = current.prev current.prev = temp def Reverse(head): if head == None: return head current = head while current != None: swap(current) #current.next,current.prev = swap(current.next,current.prev) #current.next,current.prev = current.prev,current.next if current.prev == None: head = current return current current = current.prev return head one = Node(1) head = one two = Node(2) three = Node(3) four = Node(4) six = Node(6) one.next = two two.prev = one three.prev = two two.next = three four.prev = three three.next = four six.prev = four four.next = six print_dlist(head) # head = SortedInsert(head,5) # print_dlist(head) head = Reverse(head) print_dlist(head)
f0a64396e3cd7998f6c982d1b059344d2adfb94d
KurinchiMalar/DataStructures
/Medians/MajorityElement_Copy.py
4,505
3.875
4
# Sorting Solution # Time Complexity : O(nlogn) + O(n) from Sorting.MergeSort import mergesort from Sorting.Median import getMedian_LinearTime def find_majorityelem_bruteforce(Ar): Ar = mergesort(Ar) print Ar max_elem = -1 max_count = 0 for i in range(0,len(Ar)): count = 1 for j in range(i+1,len(Ar)): if Ar[i] != Ar[j]: break count = count + 1 if count > max_count: max_elem = Ar[i] max_count = count count = 0 print "max elem is :"+ str(max_elem) +"occured :"+str(max_count)+"times." if max_count > len(Ar)/2: return max_elem return -1 # Median Logic # Time Complexity : O(n) + O(n) ---> worst case LinearSelection - O(n*n) ''' 1) Use Linear Selection to find median of Ar 2) Do one more pass to count number of occurences of median. Return true if it is more than n/2 ''' def find_majority_median_logic(Ar): median = getMedian_LinearTime(Ar) print "median is "+str(median) count = 0 for i in range(0,len(Ar)): if Ar[i] == median: count = count + 1 if count > len(Ar)/2: return median return -1 # BST logic #Time Complexity - O(n) + O(logn) --> n (creation) + logn for insertion #Space Complexity - O(2n) = O(n) since every node in BST needs two extra pointers. class BstNode: def __init__(self,key): self.key = key self.left = None self.right = None self.count = 1 def insert_bst(root,node): if root is None: root = node return root max_elem = None max_count = 0 while root != None: if root.key == node.key: root.count = root.count+1 if max_count < root.count: max_count = root.count max_elem = root break elif node.key < root.key: if root.left is None: root.left = node else: root = root.left else: if root.right is None: root.right = node else: root = root.right return root def create_bst(Ar): root = BstNode(Ar[0]) for i in range(1,len(Ar)): max_node = insert_bst(root,BstNode(Ar[i])) return max_node def find_majority_bst_logic(Ar): r = create_bst(A) print "result"+str(r.key) if r.count > len(Ar) // 2: return r.key else: return -1 ''' This is a two step process. 1. Get an element occurring most of the time in the array. This phase will make sure that if there is a majority element then it will return that only. 2. Check if the element obtained from above step is majority element. 1. Finding a Candidate: The algorithm for first phase that works in O(n) is known as Moore’s Voting Algorithm. Basic idea of the algorithm If we cancel out each occurrence of an element e with all the other elements that are different from e then e will exist till end if it is a majority element. The algorithm loops through each element and maintains a count of a[maj_index], If next element is same then increments the count, if next element is not same then decrements the count, and if the count reaches 0 then changes the maj_index to the current element and sets count to 1. First Phase algorithm gives us a candidate element. 2. In second phase we need to check if the candidate is really a majority element. Second phase is simple and can be easily done in O(n). We just need to check if count of the candidate element is greater than n/2. ''' # Time Complexity : O(n) # Space Complexity : O(1) def find_majority_MooresVotingAlgorithm(Ar): # Find candidate element = 0 count = 0 for i in range(0,len(Ar)): if count == 0: element = Ar[i] count = 1 elif element == Ar[i]: count = count + 1 else: count = count -1 print "majority_candidate:"+str(element) count_in_ar = 0 for i in range(0,len(Ar)): if Ar[i] == element: count_in_ar = count_in_ar + 1 if count_in_ar > len(Ar) // 2: return element return -1 A = [3,3,4,2,4,4,2,4,4] A = [7,3,2,3,3,6,9] #print ""+str(find_majorityelem_bruteforce(A)) #print ""+str(find_majority_median_logic(A)) #print ""+str(find_majority_bst_logic(A)) print ""+str(find_majority_MooresVotingAlgorithm(A))
f2640a1412c6ee3414bf47175439aba242d5c81f
KurinchiMalar/DataStructures
/LinkedLists/SqrtNthNode.py
1,645
4.1875
4
''' Given a singly linked list, write a function to find the sqrt(n) th element, where n is the number of elements in the list. Assume the value of n is not known in advance. ''' # Time Complexity : O(n) # Space Complexity : O(1) import ListNode def sqrtNthNode(node): if node == None: return None current = node count = 1 sqrt_index = 1 crossedthrough = [] result = None while current != None: if count == sqrt_index * sqrt_index: crossedthrough.append(current.get_data()) result = current.get_data() print "Checking if current count = sq( "+str(sqrt_index)+" )" sqrt_index = sqrt_index + 1 count = count + 1 current = current.get_next() print "We have crossed through: (sqrt(n))== 0 for :"+str(crossedthrough) return result head = ListNode.ListNode(1) #print ListNode.ListNode.__str__(head) n1 = ListNode.ListNode(2) n2 = ListNode.ListNode(3) n3 = ListNode.ListNode(4) n4 = ListNode.ListNode(5) n5 = ListNode.ListNode(6) n6 = ListNode.ListNode(7) n7 = ListNode.ListNode(8) n8 = ListNode.ListNode(9) n9 = ListNode.ListNode(10) n10 = ListNode.ListNode(11) n11 = ListNode.ListNode(12) n12 = ListNode.ListNode(13) n13 = ListNode.ListNode(14) n14 = ListNode.ListNode(15) #orig_head = ListNode.ListNode(1) #orig_head.set_next(n1) head.set_next(n1) n1.set_next(n2) n2.set_next(n3) n3.set_next(n4) n4.set_next(n5) n5.set_next(n6) n6.set_next(n7) n7.set_next(n8) n9.set_next(n10) n10.set_next(n11) n11.set_next(n12) n12.set_next(n13) n13.set_next(n14) print "Sqrt node (last from beginning): "+str(sqrtNthNode(head))
1133d5be23312ce519c55837cea5880fd729c3f6
KurinchiMalar/DataStructures
/Medians/PairComparisonMinMax.py
991
4.09375
4
# Time Complexity : O(n) # Space Complexity : O(1) ''' Number of Comparisons: n is even : (3n/2) - 2 n is odd : (3n/2) - 3/2 ''' def get_MinMax_using_paircomparison(Ar): start = -1 if len(Ar)% 2 == 0 : # even min_elem = Ar[0] max_elem = Ar[1] start = 2 else: # odd min_elem = max_elem = Ar[0] start = 1 for i in range(start,len(Ar),2): #print ""+str(i) first = Ar[i] second = Ar[i+1] if first < second: if first < min_elem: min_elem = first if second > max_elem: max_elem = second else: if second < min_elem: min_elem = second if first > max_elem: max_elem = first return min_elem,max_elem Ar = [2,67,1,5,3,7,8,234,55,72,9] Ar = [2,3,1,5,6,7] min_elem , max_elem = get_MinMax_using_paircomparison(Ar) print "min: "+str(min_elem)+"max: "+str(max_elem)
ec4a2fc2faea5acfea8a352c16b768c79e679104
KurinchiMalar/DataStructures
/Hashing/RemoveGivenCharacters.py
507
4.28125
4
''' Give an algorithm to remove the specified characters from a given string ''' def remove_chars(inputstring,charstoremove): hash_table = {} result = [] for char in charstoremove: hash_table[char] = 1 #print hash_table for char in inputstring: if char not in hash_table: result.append(char) else: if hash_table[char] != 1: result.append(char) result = ''.join(result) print result remove_chars("hello","he")
82ecc3e32e7940422238046cd7aa788979c51f9c
KurinchiMalar/DataStructures
/Stacks/Stack.py
1,115
4.125
4
from LinkedLists.ListNode import ListNode class Stack: def __init__(self,head=None): self.head = head self.size = 0 def push(self,data): newnode = ListNode(data) newnode.set_next(self.head) self.head = newnode self.size = self.size + 1 def pop(self): if self.head is None: print "Nothing to pop. Stack is empty!" return -1 toremove = self.head self.head = self.head.get_next() self.size = self.size - 1 return toremove def peek(self): if self.head is None: print "Nothing to peek!. Stack is empty!" return -1 return self.head.get_data() def print_stack(self): current = self.head while current != None: print current.get_data(), current = current.get_next() print ''' stack = Stack() stack.push(1) stack.push(2) stack.push(3) stack.push(4) stack.push(5) stack.push(6) stack.print_stack() stack.pop() stack.print_stack() print stack.size print "top: "+str(stack.peek()) print stack.size '''
0bd2a4006643ef1a0955fa89137bc9dc280efecc
KurinchiMalar/DataStructures
/DynamicProgramming/CountOccurenceOfStringInAnotherString.py
1,821
3.90625
4
''' Given two strings S and T, give an algorithm to find the number of times S appears in T. It's not compulsory that all the characters of S should appear contiguous to T. eg) S = ab and T = abadcb ---> ab is occuring 2 times in abadcb. ''' ''' Algorithm: if dest[i-1] == source[j-1]: T[i][j] = T[i][j-1] + T[i-1][j] else: T[i][j] = T[i][j-1] If same --> a b a a b x y x indicates how many times ab occurs in ab substring of aba. y indicates how many times ab occurs in aba Logic --> if equal --> left + top ( how many times a has occured till now(top) + how many times ab has appeared (left) ) if not equal --> copy the left alone. ''' # Time Complexity : O(n1 * n2) # Space Complexity : O(n1 * n2) def count_number_of_times_dest_in_source(source,dest): n1 = len(source) n2 = len(dest) T= [[0]*(n1+1) for x in range(n2+1)] #T[0][0] = 1 # since searching \0 in \0 is 1 i = 1 # starting from 1 for the above reason j = 0 #print T while i <= n2: # dest T[i][0] = 0 # if source string is empty, then nothing to check. i = i + 1 while j <= n1: # source T[0][j] = 1 # /0 in dest , will be available in non empty source. j = j + 1 #print T for i in range(1,n2+1): for j in range(1,n1+1): if dest[i-1] == source[j-1]: T[i][j] = T[i][j-1] + T[i-1][j] else: T[i][j] = T[i][j-1] print T return T[n2][n1] #source = "geeksforgeeks" #dest = "geek" source = "abadcb" dest = "ab" source = "ababab" dest ="ab" #print source.count(dest) print "Number of times : "+str(dest)+" appears in : "+str(source)+" is :"+str(count_number_of_times_dest_in_source(list(source),list(dest)))
ace208de8edd92accd7286e73e99b99c89c1eadc
KurinchiMalar/DataStructures
/DynamicProgramming/LongestIncreasingSubsequence.py
2,826
3.90625
4
''' Given an array find longest increasing subsequence in this array. https://www.youtube.com/watch?v=CE2b_-XfVDk ''' # Time Complexity : O(n*n) # Space Complexity : O(n) def get_length_of_longest_increasing_subsequence(Ar): n = len(Ar) T = [1]*(n) #print T for i in range(1,n): for j in range(0,i): if Ar[j] < Ar[i]: T[i] = max(T[i],T[j]+1) # i contributes to 1 and till now how many increasing in T[j] ==> 1+T[j] # if T[i] has a bigger number, occurence of -1 should not be reducing it, so see a max... #print T max_subseq_len = T[0] for i in range(1,n): if T[i] > max_subseq_len: max_subseq_len = T[i] return max_subseq_len def do_binary_search(Ar,T,end,elem): start = 0 while start <= end: if start == end: return start+1 middle = (start+end)//2 if middle < end and Ar[T[middle]] <= elem and elem <= Ar[T[middle+1]]: return middle + 1 # we are returning the ceil... elif Ar[T[middle]] < elem: start = middle+1 else: end = middle -1 return -1 # https://www.youtube.com/watch?v=S9oUiVYEq7E # Time Complexity : O(nlogn) # Space Complexity : O(n) def longest_increasing_subsequence_nlogn(Ar): n = len(Ar) T = [0] * (n) R = [-1] * (n) res_length = 0 # if greater append # if less replace for i in range(1,len(Ar)): if Ar[i] > Ar[T[res_length]]: # append R[i] = T[res_length] res_length = res_length + 1 T[res_length] = i else: # replace if Ar[i] <= Ar[T[0]]: T[0] = i else: # should be between 0 and res_len ceil_index = do_binary_search(Ar,T,res_length,Ar[i]) #print "ceil for : "+str(Ar[i])+" is :"+str(ceil_index) T[ceil_index] = i # found the place to put i R[i] = T[ceil_index-1] # put the mapping for i in result. #print R #print T #print res_length # holds the end index of T list. Hence the actual length will be res_length + 1 # to print the sequence.. index = T[res_length] result = [] result.insert(0,Ar[index]) while index >= 0: if R[index] == -1: break else: result.insert(0,Ar[R[index]]) index = R[index] return res_length+1,result Ar = [3,4,-1,0,6,2,3] Ar = [3,4,-1,5,8,2,3,12,7,9,10] print "length of longest incr subseq O(n*n): "+str(get_length_of_longest_increasing_subsequence(Ar)) print length,result = longest_increasing_subsequence_nlogn(Ar) print "length of longest increasing subseq O(nlogn) :"+str(length) print "longest increasing subseq O(nlogn) :"+str(result)
bd92e67855f505019f17694631ca04db74aa3fc4
KurinchiMalar/DataStructures
/lcaBT.py
1,309
3.71875
4
# Time Complexity : O(n) class BTNode: def __init__(self,data): self.data = data self.left = None self.right = None def isNodePresentBT(root, node): if node == None: return True if root == None: return False if root == node: return True return isNodePresentBT(root.left, node) or isNodePresentBT(root.right, node) def lca_bt(root, a, b): if root == None: return None if root == a or root == b: return root isAOnLeft = isNodePresentBT(root.left, a) isBOnLeft = isNodePresentBT(root.left, b) if isAOnLeft != isBOnLeft: return root if isAOnLeft == True and isBOnLeft == True: return lca_bt(root.left, a, b) return lca_bt(root.right, a, b) def util(root, a, b): if (not isNodePresentBT(root, a)) or (not isNodePresentBT(root, b)): return None if a.data < b.data: return lca_bt(root, a, b) return lca_bt(root, b, a) root = BTNode(1) two = BTNode(2) three = BTNode(2) four = BTNode(4) five = BTNode(5) six = BTNode(6) seven = BTNode(7) eight = BTNode(8) root.left = two root.right = three two.left = four two.right = five three.left = six three.right = seven seven.right = eight lca = util(root,four,five) print(str(lca.data))
61aca3793e81011ff08632c1b110e7fe4a7b7e7d
KurinchiMalar/DataStructures
/LinkedLists/Stack.py
1,133
4.0625
4
import ListNode class Stack: def __init__(self,head=None): self.head = None self.size = 0 def print_stack(self): current = self.head while current != None: print current.get_data(), current = current.get_next() print #return self.size def push(self,data): newnode = ListNode.ListNode(data) newnode.set_next(self.head) self.head = newnode self.size = self.size + 1 def pop(self): if self.head is None: print "Nothing to pop. Stack is empty!" return -1 toremove = self.head self.head = self.head.get_next() self.size = self.size - 1 return toremove def peek(self): if self.head is None: print "Nothing to peek!. Stack is empty!" return -1 return self.head.get_data() '''stack = Stack() stack.push(1) stack.push(2) stack.push(3) stack.push(4) stack.push(5) print "Printing: "+str(stack.print_stack()) stack.pop() print "Printing: "+str(stack.print_stack()) print "Peek: "+str(stack.peek())'''
98783f5bfd44ae9259f05242baaac5ff796008e5
KurinchiMalar/DataStructures
/Searching/SeparateOddAndEven.py
799
4.25
4
''' Given an array A[], write a function that segregates even and odd numbers. The functions should put all even numbers first and then odd numbers. ''' # Time Complexity : O(n) def separate_even_odd(Ar): even_ptr = 0 odd_ptr = len(Ar)-1 while even_ptr < odd_ptr: while even_ptr < odd_ptr and Ar[even_ptr] % 2 == 0: even_ptr = even_ptr + 1 while even_ptr < odd_ptr and Ar[odd_ptr] % 2 == 1: odd_ptr = odd_ptr -1 # now odd and even are positioned appropriately. #if Ar[odd_ptr] % 2 == 0 and Ar[even_ptr] % 2 == 1: Ar[odd_ptr],Ar[even_ptr] = Ar[even_ptr],Ar[odd_ptr] odd_ptr = odd_ptr-1 even_ptr = even_ptr+1 return Ar Ar = [12,34,45,9,8,90,3] #Ar = [1,2] print ""+str(separate_even_odd(Ar))
c407defd7ab9eef69e27f3ca7134e49d068962b0
KurinchiMalar/DataStructures
/LinkedLists/PalindromeOrNot.py
3,930
4.1875
4
''' Give a function to check if linked list is palindrome or not. ''' import ListNode import Stack def reverse_recursive(node): if node == None: return if node.get_next() == None: head = node return node head = reverse_recursive(node.get_next()) node.get_next().set_next(node) node.set_next(None) return head def get_middle_node(node): prev_tort = node tort = node hare = node while hare != None and hare.get_next() != None: prev_tort = tort tort = tort.get_next() hare = hare.get_next().get_next() # Let's return middle node, start of next list # for odd list tort will be the middle node. if hare != None: # odd list. return tort,tort.get_next() else: # for even list prev_tort will be the middle node. return prev_tort,tort def compare_lists(list1,list2): temp1 = list1 temp2 = list2 while temp1 != None and temp2 != None: if temp1.get_data() != temp2.get_data(): return 0 temp1 = temp1.get_next() temp2 = temp2.get_next() if temp1 == None and temp2 == None: return 1 return 0 # Time Complexity : O(n) # Space Complexity : O(1) def chec_pali(node): if node == None: return 1 if node.get_next() == None: return 1 prev_tort = node tort = node hare = node while hare != None and hare.get_next() != None: prev_tort = tort tort = tort.get_next() hare = hare.get_next().get_next() if hare != None: # for odd list tort will be the middle node. so secondhalf starting will be tort.get_next() middle_node = tort tort = tort.get_next() else: # for even list prev_tort will be the middle node. so secondhalf starting will be tort. middle_node = None prev_tort.set_next(None) # breaking firsthalf tort = reverse_recursive(tort) # reversing second half print "Comparing .... " traverse_list(node) traverse_list(tort) result = compare_lists(node,tort) # comparing if middle_node != None: # resetting odd list. prev_tort.set_next(middle_node) middle_node.set_next(reverse_recursive(tort)) else: prev_tort.set_next(reverse_recursive(tort)) #traverse_list(node) return result def traverse_list(node): current = node count = 0 while current != None: print current.get_data(), count = count + 1 current = current.get_next() print # Time Complexity : O(n) # Space Complexity : O(n) def chec_pali_stackmethod(node): if node == None: return 1 if node.get_next() == None: return 1 stack = Stack.Stack() prev_tort = node tort = node hare = node while hare != None and hare.get_next() != None: prev_tort = tort tort = tort.get_next() hare = hare.get_next().get_next() if hare != None: # odd list topush = tort.get_next() else: topush = tort while topush != None: stack.push(topush.get_data()) topush = topush.get_next() print "stack" stack.print_stack() print stack.size current = node while stack.size > 0: if current.get_data() != stack.peek(): return -1 current = current.get_next() stack.pop() return 1 head = ListNode.ListNode(1) #print ListNode.ListNode.__str__(head) n1 = ListNode.ListNode(2) n2 = ListNode.ListNode(3) n3 = ListNode.ListNode(4) n4 = ListNode.ListNode(3) n5 = ListNode.ListNode(2) n6 = ListNode.ListNode(1) #orig_head = ListNode.ListNode(1) #orig_head.set_next(n1) head.set_next(n1) n1.set_next(n2) n2.set_next(n3) n3.set_next(n4) n4.set_next(n5) n5.set_next(n6) traverse_list(head) #head1 = reverse_recursive(head) #print "isPalindrome: "+str(chec_pali(head)) print "isPalindrome stackmethod: "+str(chec_pali_stackmethod(head))
c0a0d05abe2be7af0b67b81d46002b4b8cdcbd40
KurinchiMalar/DataStructures
/LinkedLists/OddFirstThenEven.py
2,091
4.03125
4
__author__ = 'kurnagar' import ListNode ''' Segregate a link list to put odd nodes in the beginning and even behind ''' # Time Complexity : O(n) # Space Complexity : O(1) def swap_values_nodes(node1,node2): temp = node1.get_data() node1.set_data(node2.get_data()) node2.set_data(temp) def segregate_odd_and_even(node): if node == None: return node if node.get_next() == None: return node oddptr = node evenptr = oddptr.get_next() while oddptr != None and evenptr != None: while oddptr != None and oddptr.get_data() % 2 != 0: if oddptr.get_data() % 2 == 0: # found even location. #oddptr = current break oddptr = oddptr.get_next() if oddptr == None: return node evenptr = oddptr.get_next() while evenptr != None and evenptr.get_data() % 2 == 0: if evenptr.get_data() % 2 != 0: # found odd location #evenptr = current break evenptr = evenptr.get_next() if evenptr == None: return node print "oddptr: "+str(ListNode.ListNode.__str__(oddptr)) print "evenptr: "+str(ListNode.ListNode.__str__(evenptr)) swap_values_nodes(oddptr,evenptr) oddptr = oddptr.get_next() evenptr = evenptr.get_next() return node def traverse_list(node): current = node count = 0 while current != None: print current.get_data(), count = count + 1 current = current.get_next() print head = ListNode.ListNode(12) #print ListNode.ListNode.__str__(head) n1 = ListNode.ListNode(92) n2 = ListNode.ListNode(32) n3 = ListNode.ListNode(12) n4 = ListNode.ListNode(19) n5 = ListNode.ListNode(8) n6 = ListNode.ListNode(7) #orig_head = ListNode.ListNode(1) #orig_head.set_next(n1) head.set_next(n1) n1.set_next(n2) n2.set_next(n3) n3.set_next(n4) n4.set_next(n5) n5.set_next(n6) traverse_list(head) #swap_values_nodes(n5,n6) #traverse_list(head) head1 = segregate_odd_and_even(head) traverse_list(head1)
2661ddc368e29f81cb002a4a5c413580f227d284
KurinchiMalar/DataStructures
/Searching/CountOccurence.py
1,957
3.953125
4
''' Given a sorted array of n elements, possibly with duplicates. Find the number of occurrences of a number. ''' # BruteForce # Time Complexity - O(n) from FirstAndLastOccurence import find_first_occurence,find_last_occurence def count_occurence_bruteforce(Ar,k): count = 0 for i in range(0,len(Ar)): if Ar[i] == k: count = count + 1 return count def do_binary_search(Ar,low,high,elem): if low == high: if Ar[low] == elem: return low if low+1 == high: if Ar[low] == elem: return low if Ar[high] == elem: return high while low < high: middle = (low+high) // 2 if Ar[middle] == elem: return middle if Ar[middle] > elem: return do_binary_search(Ar,low,middle,elem) else: return do_binary_search(Ar,middle+1,high,elem) # BinarySearch + Scan # Time Complexity : O(log n) + S ...where S is the number of occurences of the data. def count_occurence_binarysearch(Ar,k): searched_index = do_binary_search(Ar,0,len(Ar)-1,k) count = 1 for i in range(searched_index-1,-1,-1): if Ar[i] != k: break count = count + 1 for j in range(searched_index+1,len(Ar)): if Ar[j] != k: break count = count + 1 print "The number "+str(k)+"occured:"+str(count)+"times..." return count # With First and Last Occurence # Time Complexity = O(log n) + O(log n) = O(log n) def count_occurence_withfirstandlast(Ar,k): first_occur = find_first_occurence(Ar,0,len(Ar)-1,k) last_occur = find_last_occurence(Ar,0,len(Ar)-1,k) return (last_occur-first_occur)+1 Ar = [1,3,3,3,6,6,7] #Ar = [1,2,3,4,5,6,7] #print ""+str(do_binary_search(Ar,0,len(Ar)-1,7)) #print ""+str(count_occurence_bruteforce(Ar,6)) #print ""+str(count_occurence_binarysearch(Ar,6)) print ""+str(count_occurence_withfirstandlast(Ar,1))
30a81157968dcd8771db16cf6ac48e9cd235d713
KurinchiMalar/DataStructures
/Stacks/InfixToPostfix.py
2,664
4.28125
4
''' Consider an infix expression : A * B - (C + D) + E and convert to postfix the postfix expression : AB * CD + - E + Algorithm: 1) if operand just add to result 2) if ( push to stack 3) if ) till a ( is encountered, pop from stack and append to result. 4) if operator if top of stack has higher precedence pop from stack and append to result push the current operator to stack else push the current operator to stack ''' # Time Complexity : O(n) # Space Complexity : O(n) import Stack def get_precedence_map(): prec_map = {} prec_map["*"] = 3 prec_map["/"] = 3 prec_map["+"] = 2 prec_map["-"] = 2 prec_map["("] = 1 return prec_map def convert_infix_to_postfix(infix): if infix is None: return None prec_map = get_precedence_map() #print prec_map opstack = Stack.Stack() result_postfix = [] for item in infix: print "--------------------------item: "+str(item) # if operand just add it to result if item in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or item in "0123456789": print "appending: "+str(item) result_postfix.append(item) opstack.print_stack() # if "(" just push it to stack elif item == "(": opstack.push(item) opstack.print_stack() # add to result upto open brace elif item == ")": top_elem = opstack.pop() while top_elem.get_data() != "(" and opstack.size > 0: print "appending: "+str(top_elem.get_data()) result_postfix.append(top_elem.get_data()) top_elem = opstack.pop() opstack.print_stack() #result_postfix.append(top_elem) # no need to append paranthesis in result. else: # should be an operator while opstack.size > 0 and prec_map[opstack.peek()] >= prec_map[item]: temp = opstack.pop() print "appending: "+str(temp.get_data()) result_postfix.append(temp.get_data()) opstack.push(item) # after popping existing operator , push the current one. (or) without popping just push. based on the precedence check. opstack.print_stack() #print result_postfix while opstack.size != 0: result_postfix.append(opstack.pop().get_data()) return result_postfix infixstring = "A*B-(C+D)+E" infix = list(infixstring) postfix = convert_infix_to_postfix(infix) postfix = "".join(postfix) print "Postfix for :"+str(infixstring)+" is : "+str(postfix)
982e3cb81b9a194b629434923943f919b3e36ab8
KurinchiMalar/DataStructures
/LinkedLists/floyd_LoopLinkList.py
3,145
4.125
4
__author__ = 'kurnagar' import ListNode # Time Complexity : O(n) # Space Complexity : O(n) for hashtable def check_if_loop_exits_hashtable_method(node): if node == None: return -1 hash_table = {} current = node while current not in hash_table: hash_table[current] = current.get_data() current = current.get_next() #print hash_table if current in hash_table: print "Loop at: "+ListNode.ListNode.__str__(current) return 1 ''' Floyd's Cycle Finding Algorithm ''' # Time Complexity : O(n) # Space Complexity : O(1) def check_if_loop_exits_and_return_loopnode_and_lengthofloop(node): if node == None: return -1,None,-1 tort = node hare = node while tort and hare and hare.get_next(): tort = tort.get_next() hare = hare.get_next().get_next() if tort == hare: print "tort and hare met at: "+str(ListNode.ListNode.__str__(tort)) #return 1 break if tort != hare: return -1,None # noloop meeting_point = tort # will be useed for length of loop and remove loop # To find the loop node # Bring tort to beginning tort = node print "tort:"+str(tort.get_data()) print "hare:"+str(hare.get_data()) while tort != hare: tort = tort.get_next() hare = hare.get_next() loopnode = tort # To find length of loop length_of_the_loop = 1 # current meeting point is 1. tort = meeting_point hare = tort.get_next() while tort != hare: length_of_the_loop = length_of_the_loop + 1 hare = hare.get_next() return 1,loopnode,length_of_the_loop,meeting_point def traverse_list(node): current = node count = 0 while current != None: print current.get_data(), count = count + 1 current = current.get_next() print return count # Time Complexity : O(n) # Space Complexity : O(1) def remove_loop(node,loopnode,meeting_point): current = meeting_point while current.get_next() != loopnode: current = current.get_next() if current.get_next() == loopnode: current.set_next(None) return node head = ListNode.ListNode(1) #print ListNode.ListNode.__str__(head) n1 = ListNode.ListNode(2) n2 = ListNode.ListNode(3) n3 = ListNode.ListNode(4) n4 = ListNode.ListNode(5) n5 = ListNode.ListNode(6) n6 = ListNode.ListNode(7) #orig_head = ListNode.ListNode(1) #orig_head.set_next(n1) head.set_next(n1) n1.set_next(n2) n2.set_next(n3) n3.set_next(n4) n4.set_next(n5) n5.set_next(n6) n6.set_next(n2) # loop set here print "HashTable method : is loop exists: "+str(check_if_loop_exits_hashtable_method(head)) isloop_exists,loopnode,length_of_loop,meeting_point = check_if_loop_exits_and_return_loopnode_and_lengthofloop(head) print "Check if loop exists: "+str(isloop_exists) print "Meeting point: "+str(meeting_point) print "Loop node :"+str(ListNode.ListNode.__str__(loopnode)) print "Length of loop: "+str(length_of_loop) head = remove_loop(head,loopnode,meeting_point) print "Removed loop:"+str(traverse_list(head))
22f1d817b2d292a4b3fae09a77e3013b9d45bd31
KurinchiMalar/DataStructures
/Sorting/NearlySorted_MergeSort.py
1,528
4.125
4
#Complexity O(n/k * klogk) = O(nlogk) # merging k elements using mergesort = klogk # every n/k elem group is given to mergesort # Hence totally O(nlogk) ''' k = 3 4 5 9 | 7 8 3 | 1 2 6 1st merge sort all blocks 4 5 9 | 3 8 9 | 1 2 6 Time Complexity = O(n * (n/k) log k) i.e to sort k numbers is k * log k to sort n/k such blocks = (n/k) * k log k = n log k 2nd start merging two blocks at a time i.e to merge k + k elements 2k log k to merge 2k + k elements 3k log k similarly it has to proceed until qk + k = n, so it becomes n log k where q = (n/k) - 1 ''' from MergeSort import mergesort def split_into_groups_of_size_k(Ar,k): r = [] for j in range(0,(len(Ar)/k)+1): start = k * j end = start + k if start >= len(Ar): break if end >=len(Ar) and start < len(Ar): r.append(Ar[start:end]) break #print "start,end = "+str(start)+","+str(end) r.append( Ar[start:end]) #print r[j] return r def merge_two_lists(list1,list2): list1.extend(list2) return list1 Ar = [6,9,10,1,2,3,5] Ar = [8,9,10,1,2,3,6,7] Ar = [8,9,10,1,2,3] print Ar split_blocks = split_into_groups_of_size_k(Ar,3) print str(split_blocks) for i in range(0,len(split_blocks)): mergesort(split_blocks[i]) print "Sorted blocks:" +str(split_blocks) while len(split_blocks) > 1 : split_blocks[1] = merge_two_lists(split_blocks[0],split_blocks[1]) split_blocks.pop(0) mergesort(split_blocks[0]) print str(split_blocks)
6d878bd6ab1e0dbecb0c2a5a2803ee41359b51b8
KurinchiMalar/DataStructures
/LinkedLists/MergeZigZagTwoLists.py
2,040
4.15625
4
''' Given two lists list1 = [A1,A2,.....,An] list2 = [B1,B2,....,Bn] merge these two into a third list result = [A1 B1 A2 B2 A3 ....] ''' # Time Complexity : O(n) # Space Complexity : O(1) import ListNode import copy def merge_zigzag(node1,node2,m,n): if node1 == None or node2 == None: return node1 or node2 p = node1 q = p.get_next() r = node2 s = r.get_next() while q != None and s != None: p.set_next(r) r.set_next(q) p = q if q != None: q = q.get_next() r = s if s != None: s = s.get_next() if q == None: p.set_next(r) if s == None: p.set_next(r) r.set_next(q) return node1 def get_len_of_list(node): current = node count = 0 while current != None: #print current.get_data(), count = count + 1 current = current.get_next() #print return count def traverse_list(node): current = node count = 0 while current != None: print current.get_data(), count = count + 1 current = current.get_next() print head1 = ListNode.ListNode(1) #print ListNode.ListNode.__str__(head) n1 = ListNode.ListNode(3) n2 = ListNode.ListNode(5) n3 = ListNode.ListNode(7) n4 = ListNode.ListNode(9) n5 = ListNode.ListNode(10) n6 = ListNode.ListNode(12) head2 = ListNode.ListNode(2) m1 = ListNode.ListNode(4) m2 = ListNode.ListNode(6) m3 = ListNode.ListNode(8) m4 = ListNode.ListNode(11) m5 = ListNode.ListNode(14) m6 = ListNode.ListNode(19) head1.set_next(n1) n1.set_next(n2) n2.set_next(n3) n3.set_next(n4) n4.set_next(n5) n5.set_next(n6) head2.set_next(m1) m1.set_next(m2) m2.set_next(m3) m3.set_next(m4) m4.set_next(m5) m5.set_next(m6) orig_head1 = copy.deepcopy(head1) orig_head2 = copy.deepcopy(head2) traverse_list(head1) traverse_list(head2) m = get_len_of_list(head1) n = get_len_of_list(head2) result = merge_zigzag(head1,head2,m,n) print "RESULT:" traverse_list(result)
d1c079ea514b668ac8e2ca32afbaa2aa171754d0
kwichmann/euler
/pe012.py
437
3.6875
4
def factor_count(n): count = 0 for i in range(1, n + 1): if n % i == 0: count += 1 return count def triangle(n): return int(n * (n + 1) / 2) num = 1 while True: if num % 2 == 0: fac = factor_count(int(num / 2)) * factor_count(num + 1) else: fac = factor_count(int((num + 1)/ 2)) * factor_count(num) if fac > 500: print(triangle(num)) quit() num += 1
f4726dd533c9efdff032b1e5d3b8589b7469d56f
kwichmann/euler
/pe003.py
505
3.53125
4
num = 600851475143 def divides(n, p): return n % p == 0 def divides_list(n, l): for p in l: if divides(n, p): return True return False def next_prime(l): counter = max(l) + 1 while divides_list(counter, l): counter += 1 return counter cur_prime = 2 prime_list = [2] while num != 1: while divides(num, cur_prime): print(cur_prime) num /= cur_prime cur_prime = next_prime(prime_list) prime_list.append(cur_prime)
3304d188c15ebea8b0f4f7d4846e90c1dbd9420c
cdpn/htb-challenges
/misc/eternal-loop/unzip-loop.py
811
3.71875
4
#!/usr/bin/env python3 import zipfile zip_file = "Eternal_Loop.zip" password = "hackthebox" # Take care of the first zip file since password won't be the filename inside with zipfile.ZipFile(zip_file) as zr: zr.extractall(pwd = bytes(password, 'utf-8')) # namelist() returns an array, so take the first index to get the filename zip_file = zr.namelist()[0] # print(zip_file) while True: with zipfile.ZipFile(zip_file) as zr: # gets a list of all the files within the zip archive for files in zr.namelist(): password = files.split(".")[0] print(f"Now extracting {zip_file} with the password of: {password}") # unzip p/w protected zip with filename of zip inside zr.extractall(pwd = bytes(password, 'utf-8')) zip_file = files
c1bb89404de014f6a188d04c61ba6bc32f68a4f4
slw2/library-python
/Books.py
1,710
3.734375
4
from Book import Book import random class Books: database = "" def __init__(self, database): self.database = database def books(self): self.database.cursor.execute('''SELECT title, author, code FROM books''') allrows = self.database.cursor.fetchall() list_of_books = [] for row in allrows: newBook = Book() newBook.init(row[0], row[1], row[2]) list_of_books.append(newBook) return list_of_books def booksearch_by_title(self, title): bookList = self.books() books_with_title = [] for book in bookList: if book.title == title: books_with_title.append(book) return books_with_title def booksearch_by_author(self, author): bookList = self.books() books_by_author = [] for book in bookList: if book.author == author: books_by_author.append(book) return books_by_author def booksearch_by_code(self, code): bookList = self.books() for book in bookList: if book.code == code: return book return False def add_book(self, title, author): code = random.randint(1, 1000) while self.booksearch_by_code(code) != False: code = random.randint(1, 1000) self.database.cursor.execute('''INSERT INTO books(title, author, code) VALUES(?,?,?)''', (title, author, code)) self.database.db.commit() def remove_book(self, book): self.database.cursor.execute('''DELETE FROM books WHERE code = ? ''', (book.code,)) self.database.db.commit()
36e1619c70ac8f322aaa1ac085dc3c9c3e61f099
slw2/library-python
/LoanController.py
2,356
3.921875
4
class LoanController: books = "" users = "" loans = "" def __init__(self, books, users, loans): self.books = books self.users = users self.loans = loans def borrow(self, book_code, user_code): book = self.books.booksearch_by_code(book_code) user = self.users.usersearch_by_code(user_code) if not book: print("The book code does not match any books") elif not user: print("The user code does not match any users") elif book in self.loans.loans(user): print("You have already taken this book out") elif not self.loans.borrow(book, user): print("This book is already on loan") else: self.loans.borrow(book, user) print("You have successfully borrowed a book!") def return_book(self, book_code): book = self.books.booksearch_by_code(book_code) if not book: print("The book code does not match any books") else: self.loans.return_book(book) print("You have successfully returned the book!") def user_loans(self, user_code): user = self.users.usersearch_by_code(user_code) if not user: print("The user code does not match any users") on_loan = self.loans.loans(user) if on_loan == []: print("You have no books on loan") else: print("These are your loans: ") for book in on_loan: book.print() def print_books_loaned(self): books_loaned = self.loans.books_loaned() if books_loaned == []: print("There are currently no books on loan") else: for book in books_loaned: book.print() def print_books_not_loaned(self): books_not_loaned = self.loans.books_not_loaned() if books_not_loaned == []: print("There are no books currently available in the library") else: for book in books_not_loaned: book.print() def print_users_with_loans(self): users_with_loans = self.loans.users_with_loans() if users_with_loans == []: print("There are currently no users with loans") else: for user in users_with_loans: user.print()
228ee138bdc254c9cb229ae19fb4432dadb2e43c
yeyifu/python
/other/set.py
621
4.03125
4
#集合的创建:1.初始化{1,2,3},2.set()函数声明 #特点:无序,无下标,去重 # set = {10, 20, 30, 40, 50, 10} # print(set) #增加 # set1 = {10,20} # set1.add(30) #增加单一数据 # print(set1) # # set1.update([5,6,9,5]) #追加数据序列 # print(set1) #删除 # set2 = {10,20,30,40,50} # set2.remove(10) #删除不存在的值则报错 # print(set2) # set2.discard(20) # print(set2) # # set2.pop() #随机删除,返回删除值 # print(set2) #查找,判断是否在集合里 # set4 = {10,20,30,40,50} # print(10 in set4) # if 80 in set4: # print('yes') # else: # print('no')
b61a043aedd39dc9120e0b4066327d0095979556
yeyifu/python
/other/function.py
602
3.90625
4
# 定义函数说明文档 def info_print(): """函数说明文档""" print(1+2) info_print() # 查看函数文档 help(info_print) # 一个函数返回多个值 def return_num(): # return 1, 3 #返回的是元组(默认) # return(10,20) #返回的是元组 # return[10,20] #返回的是列表 return {'name':'python','age':'30'} #返回的是字典 print(return_num()) #函数的参数 # 1.位置参数:传递和定义参数的顺序及个数必须一致 def user_info(name,age,add): print(f'我叫{name},今年{age}岁,来自{add}') user_info('yyf',20,'china')
2a5e1828f8e2bc9f46274bd166d3f566f0225d22
yeyifu/python
/other/test.py
1,561
3.75
4
# import sys # print(sys.argv) # num1 = 1 # num2 = 1.1 # print(type(num2)) # name = 'tom' # age = 18 # weight = 55.5 # stu_id = 2 # print('我叫%s,学号是%.10d,今年%d岁,体重%.2f' % (name, stu_id, age, weight)) # print(f'我叫{name},学号是{stu_id}') # print('hello\nworld') # print('hello\tworld') # print('hello', end='\t') # print('world') #输入 # str = input('请输入字符:') # print(str) #数据转换 # str = input(f'请输入:') # print(type(str)) # num = int(str) # print(type(num)) # print(float(str, 2)) #eval() # str1 = '4' # print(type(eval(str1))) # str = input('请输入年龄:') # if int(str) < 18: # print('童工') # elif 18 <= int(str) <= 60: # print('合法') # else: # print('年龄过大') # import random # print(random.randint(1,3)) # i=1 # while i<10: # print(i) # i = i+1 # str = '01234545678' # print(str[1:8:2]) # print(str[-1:1:-1]) # print(str.find('34')) # print(str.count('45',4,10)) # print(str.find('45')) # print(str.count('45')) str = ' hello World and itcast and itheima and pythoN' str3 = 'df34d6f' num='123456' # print(str.replace('and','he')) # print(str.split('and',3)) str1 = ['hello world ', ' itcast ', ' itheima ', ' python'] str2 = ''.join(str1) # print(str2) # print(''.join(str1).replace(' ','')) # print(str.capitalize()) # print(str.title()) # print(str.lower()) # print(str.strip()) # # str.ljust() # # str.rjust() # # str.center() # # print(str.startswith('')) # print(str.endswith('n')) # print(str.isalpha()) # print(num.isdigit()) print(str3.isalnum())
10b994ebf775a1ad965e7522fae132d5bdc1e1ee
colorfulComeMonochrome/data_analysis
/matplotlib/fish.py
555
3.546875
4
import pandas as pd import numpy as np import matplotlib.pyplot as plt imdata = plt.imread('fish.png') # 数据变换 # mydata = np.random.rand(100*100*3).reshape(100,100,3) # mydata = np.ones(100*100*3).reshape(100,100,3) mydata = np.zeros(100*100*3).reshape(100,100,3) # mydata = mydata + np.array([1, 0, 0]) mydata = mydata + np.array([0.5, 0.3, 0.7]) # print(imdata) # print(imdata.shape) # plt.imshow(imdata[:, :, ::-1]) # plt.imshow(imdata[::50, ::50, ::]) plt.imshow(mydata) plt.show()
c10b5596458ddc22d97f6dd93968adf9e7766833
HyunAm0225/Python_Algorithm
/study/programmers/kakao_dart_game.py
1,163
3.625
4
from collections import deque dartResult = input() dartque = deque(dartResult) point = [] def check_dart_point(dartque,point): index = -1 while dartque: data = dartque.popleft() if data.isnumeric(): if data =="0" and index== -1: point.append(int(data)) index +=1 elif data == "0": if point[index] == 1: point[index] = 10 else: point.append(int(data)) index +=1 else: point.append(int(data)) index +=1 else: if data == "S": point[index] **=1 elif data == "D": point[index] **=2 elif data == "T": point[index] **=3 elif data == "#": point[index] *=(-1) else: if index == 0: point[index] *=2 else: point[index-1] *=2 point[index] *=2 print(point) return point print(sum(check_dart_point(dartque,point)))
ad9b99eef4faff4186c37a26516e4dc085ae9060
HyunAm0225/Python_Algorithm
/코딩테스트책/7-5.py
687
3.71875
4
# 이진 탐색 실전 문제 # 부품찾기 import sys input = sys.stdin.readline def search_binary(array,start,end,target): while start <= end: mid = (start + end)//2 if array[mid] == target: return mid elif array[mid] > target: end = mid -1 else: start = mid + 1 return None n = int(input()) store = list(map(int,input().split())) store.sort() m = int(input()) host = list(map(int,input().split())) for product in host: # 해당 부품이 있는지 확인하기 result = search_binary(store,0,n-1,product) if result != None: print('yes', end=' ') else: print('no', end=' ')
16e12fbf8289dfb9d62274ccae8196bb06849314
HyunAm0225/Python_Algorithm
/study/9012.py
875
3.65625
4
# 9012 # 괄호 # 스택문제 # 테스트 케이스의 숫자를 입력받음 t = int(input()) ans = [] data = [] def check_vps(stack_list): # pop 한 괄호를 담을 list temp_list = [] temp_list.append(stack_list.pop()) for i in range(len(stack_list)): # temp_list 비어있을 경우 append if not temp_list: temp_list.append(stack_list.pop()) # temp에는 ), stackList 는 ( elif (temp_list[-1] == ')' and stack_list[-1] =='('): temp_list.pop() stack_list.pop() else: temp_list.append(stack_list.pop()) if not temp_list: print(temp_list) return "YES" else: print(temp_list) return "NO" for _ in range(t): data = list(input()) ans.append(check_vps(data)) # 결과값 출력 for i in ans: print(i)
ca0de2eabb70373eccdefd891484900c21fef0fb
HyunAm0225/Python_Algorithm
/study/1181.py
203
3.5625
4
n = int(input()) data = [] ans = [] for _ in range(n): data.append(input()) data.sort(key = lambda x:(len(x),x)) for x in data: if x not in ans: ans.append(x) for i in ans: print(i)
65f583ecf0cd952237b9dcd7130cc71a7a519177
HyunAm0225/Python_Algorithm
/코딩테스트책/10-7.py
889
3.796875
4
# 팀결성 문제 # 서로소 집합 자료구조를 이용하여 구한다 def find_parent(parent,x): if parent[x] !=x: return find_parent(parent,parent[x]) return parent[x] def union_parent(parent,a,b): a = find_parent(parent,a) b = find_parent(parent,b) if a<b: parent[b] = a else: parent[a] = b n,m = map(int,input().split()) parent = [0] * (n+1) # 부모 테이블 초기화 # 부모 테이블 상에서, 부모를 자기 자신으로 초기화 for i in range(0,n+1): parent[i] = i # 각 연산을 하나씩 확인 for i in range(m): oper,a,b = map(int,input().split()) # 합집합 (union) if oper ==0: union_parent(parent,a,b) # 찾기(find) 연산 일 경우 elif oper == 1: if find_parent(parent,a) == find_parent(parent,b): print("YES") else: print("NO")
194086367cacb0dffa9a8e996b35edfe94887754
HyunAm0225/Python_Algorithm
/hello_coding/chap04/quick_sum.py
180
3.78125
4
def sum(lst): if lst == []: return 0 else: print(f"sum({lst[:]}) = {lst[0]} + sum({lst[1:]})") return lst[0] + sum(lst[1:]) print(sum([1,2,3,4,5]))
1b1a4d3bd63310edc10c7e0add62526b041591bb
HyunAm0225/Python_Algorithm
/study/programmers/ternary.py
443
3.9375
4
# 3진법으로 만드는 코드 def ternary(n): tern_list = [] ans = '' while n > 0: # print(f"현재 n값 : {n}") tern_list.append(n%3) n //=3 tern_list.reverse() return tern_list def solution(n): tern_list = ternary(n) ans = 0 for i,num in enumerate(tern_list): num = num * (3**i) ans += num return ans n = int(input()) print(ternary(n)) print(solution(n))
83115abfeb4394433aafa7fd291614a826743049
HyunAm0225/Python_Algorithm
/2292.py
265
3.625
4
# 백준 # 백준 수학 문제 def room_count(number): six_num = 1 count = 1 while number > six_num and number >1: six_num+=(6*count) count +=1 # print(f"six_num : {six_num}") return count n = int(input()) print(room_count(n))
0e08b45d1f4917cd9d4854344441c635283d683c
hucatherine7/cs362-hw4
/test_question1.py
451
3.734375
4
#Unit testing question 1 import unittest import question1 class Question1(unittest.TestCase): def test_calcVolume(self): #Normal test case self.assertEqual(question1.calcVolume(4), 64) #Negative number test case self.assertEqual(question1.calcVolume(-1), -1) #Wrong input type self.assertEqual(question1.calcVolume("bad input"), -1) if __name__ == '__main__': unittest.main(verbosity=2)
40ef7592544d316ec0fe22e2d0a08e6f95e5611d
lavakin/bioinformatics_tools
/bioinf/distance.py
1,094
3.875
4
#!/usr/bin/env python3 from Bio import pairwise2 def editing_distance(seq1:str, seq2:str): """ :param seq1: sequence one :param seq2: sequence two :return: editing distance of two sequences along with all alignments with the maximum score """ align = list(pairwise2.align.globalms(seq1, seq2, 0, -1, -1, -1)) align = [list(a)[:3] for a in align] for a in align: a[2] = str((-1)*int(a[2])) return align class SequencesNotTheSameLength(Exception): def __init__(self, message="Sequences does not have the same length"): """ :param message: error message """ self.message = message super().__init__(self.message) def __str__(self): return f'{self.message}' def hamming_distance(seq1, seq2): """ :param seq1: sequence one :param seq2: sequence two :return: hamming distance of the two sequences, if they are the same length """ if len(seq1) == len(seq2): return sum(c1 != c2 for c1, c2 in zip(seq1, seq2)) else: raise SequencesNotTheSameLength()
77990bea69aff99c9201bc80da4e4ede8e2e7f93
WYHNUS/old-xirvana
/assets/Practice/practice02/skeleton/mile_to_km.py
317
4.0625
4
# mile_to_km.py # Converts distance in miles to kilometers. import sys # main function def main(): KMS_PER_MILE = 1.609 miles = float(raw_input("Enter distance in miles: ")) kms = KMS_PER_MILE * miles print "That equals %9.2f km." % kms # Runs the main method if __name__ == "__main__": main() sys.exit(0)
f07201523a286803dafc06c5a4305451f9ea9fd9
ibbles/HousyBuying
/Stepper.py
6,811
3.859375
4
from datetime import timedelta import datetime import calendar class FastDateNumberList(object): """ This may be a bit unnecessary. It is a fixed sized, pre-allocated DateNumberList used when running the stepper. The purpose is to avoid reallocations inside the innermost loop, where hundreds of thousands of appends are performed distributed over a handful of lists. """ endIndex = 0 """ The index one-past the end of the populated part of the list. I.e., the index where the next append should write. """ dates = None numbers = None def __init__(self, numItems): self.dates = [datetime.date(1,1,1)] * numItems self.numbers = [0.0] * numItems def append(self, date, number): self.dates[self.endIndex] = date self.numbers[self.endIndex] = number self.endIndex += 1 def appendAccumulated(self, date, number): """At least one call to append must have been made before calling appendAccumulated.""" self.dates[self.endIndex] = date self.numbers[self.endIndex] = self.numbers[self.endIndex-1] + number self.endIndex += 1 def done(self): del self.dates[self.endIndex:] del self.numbers[self.endIndex:] class StepResult(object): """ Data container class holding the results of the stepper calculations for one account. Contains a number of FastDateNumberLists, one for each data item that is calculated. Some lists hold one element per day, and some one element per month. """ def __init__(self, startDate, years, months, days): self.balances = FastDateNumberList(days) self.addedInterests = FastDateNumberList(days) self.accumulatedIterests = FastDateNumberList(days+1) self.accumulatedIterests.append(startDate, 0.0) self.collectedInterests = FastDateNumberList(months) self.accumulatedCollectedInterests = FastDateNumberList(months+1) self.accumulatedCollectedInterests.append(startDate, 0.0) self.savings = FastDateNumberList(months) self.accumulatedSavings = FastDateNumberList(months+1) self.accumulatedSavings.append(startDate, 0.0) def addBalance(self, date, balance): self.balances.append(date, balance) def addInterest(self, date, interest): self.addedInterests.append(date, interest) self.accumulatedIterests.appendAccumulated(date, interest) def addCollectedInterest(self, date, collectedInterest): self.collectedInterests.append(date, collectedInterest) self.accumulatedCollectedInterests.appendAccumulated(date, collectedInterest) def addSaving(self, date, saving): self.savings.append(date, saving) self.accumulatedSavings.appendAccumulated(date, saving) def done(self): self.balances.done() self.addedInterests.done() self.accumulatedIterests.done() self.collectedInterests.done() self.accumulatedCollectedInterests.done() self.savings.done() self.accumulatedSavings.done() class Stepper(object): """ Main stepper algorithm. Moves a date forward day by day and updates a number of given accounts for each day, calculating savings and interests and such whenever appropriate. Can send progress information to a progress listener. """ def __init__(self): pass def stepAccounts(self, accounts, startDate, endDate, progressListener): # Worst case estimate of the number of years, months, and days that will # be recorded. USed to preallocate result lists. numYears = endDate.year - startDate.year + 1 numMonths = numYears * 12 numDays = numYears * 366 # Create a result object for each account. results = [] for account in accounts: results.append(StepResult(startDate, numYears, numMonths, numDays)) # Setup a progress bar for "long" calculations. Not sure how to determine # that a calculation is long in the best way. if progressListener != None: if numYears > 10: progressListener.progressStarted(numYears) else: progressListener = None # Iterate through the dates. date = startDate aborted = False # The progress listener can abort the calculation. The results so far will be returned. while date < endDate and not aborted: # Record current balance and interests for the current day. self.recordCurrentBalance(date, accounts, results) self.recordInterest(date, accounts, results) # Move to the next day. date += timedelta(days=1) # Special handling for every new month. if date.day == 1: self.recordSavings(date, accounts, results) self.collectInterestsForLoans(date, accounts, results) # Special handling for every new year. if date.month == 1 and date.day == 1: self.collectInterestsForSavingAccounts(date, accounts, results) # Progress bar is updated on a per-year basis. if progressListener != None: currentYear = date.year - startDate.year aborted = progressListener.progressUpdate(currentYear) # Iteration is done, record final balance and truncate result lists. self.recordCurrentBalance(date, accounts, results) self.markAsDone(results) # Remove progress bar. if progressListener != None: progressListener.progressDone() return results def recordCurrentBalance(self, date, accounts, results): for index in range(0, len(accounts)): account = accounts[index] result = results[index] result.addBalance(date, account.getBalance()) def recordInterest(self, date, accounts, results): if calendar.isleap(date.year): timeFraction = 1.0/366.0 else: timeFraction = 1.0/365.0 for index in range(0, len(accounts)): account = accounts[index] result = results[index] addedInterest = account.applyInterest(date, timeFraction) result.addInterest(date, addedInterest) def recordSavings(self, date, accounts, results): for index in range(0, len(accounts)): account = accounts[index] result = results[index] saving = account.addSaving(date) result.addSaving(date, saving) def collectInterestsForSavingAccounts(self, date, accounts, results): for index in range(0, len(accounts)): account = accounts[index] result = results[index] if not account.isLoan(): collectedInterest = account.collectInterest() result.addCollectedInterest(date, collectedInterest) def collectInterestsForLoans(self, date, accounts, results): for index in range(0, len(accounts)): account = accounts[index] result = results[index] if account.isLoan(): collectedInterest = account.collectInterest() result.addCollectedInterest(date, collectedInterest) def markAsDone(self, results): for result in results: result.done()
276faf09e77e69979004b00a910df2d0ce4c7923
sumanthreddy07/GOST_Algorithm
/src/main.py
2,163
3.65625
4
#import section import os import argparse from encryption import encrypt,encrypt_cbc from decryption import decrypt,decrypt_cbc #locate function returns the path for the txt files in the data folder def locate(filename): __location__ = os.path.dirname(os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))) return os.path.join(__location__,'data',filename) def main(args): print("would you like to encrypt or decrypt?") opt = int(input("1.Encrypt 2.Decrypt: 3:EncryptCBC 4:DecryptCBC: ")) if opt==1: encrypt( locate(args.main_file),locate(args.key_file),locate(args.encrypted_file),locate(args.decrypted_file)) elif opt==2: decrypt( locate(args.encrypted_file),locate(args.key_file),locate(args.decrypted_file)) elif opt==3: encrypt_cbc(locate(args.vector_file), locate(args.main_file),locate(args.key_file),locate(args.encrypted_file),locate(args.decrypted_file)) else: decrypt_cbc(locate(args.vector_file), locate(args.encrypted_file),locate(args.key_file),locate(args.decrypted_file)) if __name__ == "__main__": #parser arguments parser = argparse.ArgumentParser(description='Main Script to run the code') parser.add_argument('--main_file', type=str, default='original.txt', help='The name of the file to be encrypted. This file must be placed in the data folder.') parser.add_argument('--key_file', type=str, default='key.txt', help='The key for encryption, with size = 32 Characters. This file must be placed in the data folder.') parser.add_argument('--encrypted_file', type=str, default='encrypted.txt', help='The name of the file to be decrypted. This file must be placed in the data folder.') parser.add_argument('--decrypted_file', type=str, default='decrypted.txt', help='The name of the file in which decrypted data is written. This file must be placed in the data folder.') parser.add_argument('--vector_file', type=str, default='vector.txt', help='The initialization vector in string format .') args = parser.parse_args() main(args)
3b91de50d77f86a93f67b9da205573ca8231b874
Shuguberu/Hello-World
/猜整数.py
383
3.84375
4
import random secret=random.randint(1,10) print("=======This is Shuguberu=======") temp=input("输入数字") guess=int(temp) while guess!=secret: temp=input("wrong,once again:") guess=int(temp) if guess==secret: print("right") else: if guess>secret: print("大了") else: print("小了") print("over")
f3ab92ce7e915013dc8d62cb87d0dbbc05a16275
mangrisano/ProjectEuler
/euler17.py
1,646
4.03125
4
# If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 # letters used in total. # # If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used? # # Result: 21124 def problem(): result = 0 all_numbers = list() one_digit_numbers = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine"] two_digits_numbers = ["ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"] three_digits_numbers = ["hundred"] for number in one_digit_numbers: all_numbers.append(number) for number in two_digits_numbers: all_numbers.append(number) if number.endswith("ty"): for digit in one_digit_numbers: all_numbers.append(number + digit) for digit in one_digit_numbers: for number in three_digits_numbers: all_numbers.append(digit + number) for n in one_digit_numbers: all_numbers.append(digit + number + 'and' + n) for n in two_digits_numbers: all_numbers.append(digit + number + 'and' + n) if n.endswith("ty"): for y in one_digit_numbers: all_numbers.append(digit + number + 'and' + n + y) all_numbers.append("onethousand") for number in all_numbers: result += len(number) return result print problem()
21a192f8d31f93d63fa60d4b2b19f7e6821a171d
mangrisano/ProjectEuler
/euler6.py
650
3.5625
4
# The sum of the squares of the first ten natural numbers is, # # 12 + 22 + ... + 102 = 385 # The square of the sum of the first ten natural numbers is, # # (1 + 2 + ... + 10)2 = 552 = 3025 # Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum # is 3025 - 385 = 2640. # # Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum. # # Answer: 25164150 def problem(n): sum_squares = sum([i**2 for i in range(1, n + 1)]) squares_of_sum = ((n * (n + 1)) / 2)**2 return squares_of_sum - sum_squares print(problem(100))
3fd420c5f119f608dda0a1bb30f6014a76a6f82a
mangrisano/ProjectEuler
/euler38.py
1,318
4.03125
4
# Take the number 192 and multiply it by each of 1, 2, and 3: # # 192 x 1 = 192 # 192 x 2 = 384 # 192 x 3 = 576 # By concatenating each product we get the 1 to 9 pandigital, 192384576. # We will call 192384576 the concatenated product of 192 and (1,2,3) # # The same can be achieved by starting with 9 and multiplying by 1, 2, 3, 4, and 5, giving # the pandigital, 918273645, which is the concatenated product of 9 and (1,2,3,4,5). # # What is the largest 1 to 9 pandigital 9-digit number that can be formed as the concatenated # product of an integer with (1,2, … , n) where n > 1? # # Answer: 932718654 def problem(limit=10000, range_numbers=9): max_number = 0 pandigital = 0 for number in list(range(1, limit+1)): ispandigital, pandigital = is_pandigital(number, range_numbers) if ispandigital: if pandigital > max_number: max_number = pandigital return max_number def is_pandigital(number, limit): st_pandigit = '' pandigital = '123456789' for i in list(range(1, limit+1)): st_pandigit += str(number * i) if len(st_pandigit) >= 9: break if ''.join(sorted(st_pandigit)) == pandigital: return True, int(st_pandigit) return False, int(st_pandigit) if __name__ == '__main__': print(problem())
0ec6ab37481600c42bb40b7d7560afd1cfa06e67
SubrataSarkar32/college3rdsem3035
/class12pythoncbse-master/Chapter 6&7/studentrecord.py
2,470
3.90625
4
class Student: def __init__(self,name,classs,section,rollno): self.name=name self.classs=classs self.section=section self.rollno=rollno def __str__(self): string='Student Name:'+str(self.name)+'\nStudent Class:'+\ str(self.classs)+'\nStudent Section:'+str(self.section)+\ '\nStudent Roll No.:'+str(self.rollno) return string class stack: '''Implementing stack with list''' from copy import deepcopy def __init__(self,limit,L=[],pos=-1): self.L=L if len(self.L)==0: for i in range(limit): self.L+=[None] self.pos=pos self.limit=limit else: self.limit=limit self.pos=pos def add(self,element): if self.pos<self.limit-1: self.pos+=1 self.L[self.pos]=element else: print 'OVERFLOW!!' def remove(self): if self.pos!=-1: print 'Element removed is ',self.L[self.pos] self.pos-=1 else: print 'UNDERFLOW!!' def display(self): if self.pos==self.limit-1: print 'Stack is empty' for i in range(self.pos,-1,-1): print self.L[i], print print '#'*30 def __len__(self): return len(self.L) def __str__(self): print self.L print self.pos,self.limit return str(self.L) #--------------------------main---------------------------------- while True: g=[] print 'Creating new stack' limit=input('Enter number of students you want to store:') st1=stack(limit) print 'Stack created' print '1.PUSH element' print '2.POP element' print '3.Display element' print '5.Display list' print '4.Quit' while True: res=raw_input('Enter your choice: ') if res=='1': rollno=input("Enter roll no: ") name=raw_input("Enter name: ") classs=raw_input("Enter class: ") section=raw_input("Enter section: ") stu=Student(name,classs,section,rollno) from copy import deepcopy st1.add(deepcopy(stu)) elif res=='2': st1.remove() elif res=='3': st1.display() elif res=='4': import sys sys.exit() elif res=='5': print st1 else: print 'Invalid command'
e818073196e6fabaf47145fab615f345237bf7e3
SubrataSarkar32/college3rdsem3035
/class12pythoncbse-master/Practical3/binsearch.py
924
4.03125
4
class binsearch: def __init__(self): self.n=input('Enter number of elements: ') self.L=[] for i in range (self.n): self.L.append(input('Enter element: ')) itemi=input('Enter element to be searched for : ') self.L.sort(reverse=True) self.index=self.binsearchdec(itemi) if self.index: print 'Element found at index:',self.index,'position:',self.index+1 else: print 'The element could not be found' def binsearchdec(self,item): array=self.L beg=0 last=len(array)-1 while(beg<=last): mid=(beg+last)/2 if item==array[mid]: return mid elif array[mid]<item: last=mid-1 else: beg=mid+1 else: return False #--------------------------main-------------------- fiop=binsearch()
3f1f068d1d557358a42db8bbb9534e5236e2f0f9
SubrataSarkar32/college3rdsem3035
/class12pythoncbse-master/Chapter 4/Question5.py
1,123
3.65625
4
class Bowler: def __init__(self): self.fname='' self.lname='' self.oversbowled=0 self.noofmaidenovers=0 self.runsgiven=0 self.wicketstaken=0 def inputup(self): self.fname=raw_input("Player's first name: ") self.lname=raw_input("Player's last name: ") self.oversbowled=input('Number of over bowled: ') self.noofmaidenovers=input('Number of maiden over bowled: ') self.runsgiven=input('Runs given: ') self.wicketstaken=input('Wickets taken: ') def infup(self): self.oversbowled=input('Number of over bowled: ') self.noofmaidenovers=input('Number of maiden over bowled: ') self.runsgiven=input('Runs given: ') self.wicketstaken=input('Wickets taken: ') def display(self): print "Player's first name ",self.fname print "Player's last name ",self.lname print 'Number of over bowled ',self.oversbowled print 'Number of maiden over bowled ',self.noofmaidenovers print 'Runs given ',self.runsgiven print 'Wickets taken ',self.wicketstaken
4ad77d79088f85449035804824a12f6beb2e1e7a
SubrataSarkar32/college3rdsem3035
/class12pythoncbse-master/Chapter 5/int.py
503
3.515625
4
def compare(listsuper,listsub): stat=None for element in listsuper: if listsuper.count(element)==listsub.count(element): pass else: stat=False if stat==None: for element in listsub: if element in listsub and element in listsuper: pass else: stat=False if stat==None: stat=True return stat print compare([2,3,3],[2, 2])
8147118c98c5d7bf084f405607d3b15c22ea1d3f
SubrataSarkar32/college3rdsem3035
/class12pythoncbse-master/Chapter 4/Question10.py
1,464
3.625
4
class HOUSING: def __init__(self): self.__REG_NO=0 self.__NAME='' self.__TYPE='' self.__COST=0.0 def Read_Data(self): while not(self.__REG_NO>=10 and self.__REG_No<=1000): self.__REG_NO=input('Enter registraton number betwee 10-1000: ') self.__NAME=raw_input('Enter name: ') self.__TYPE=raw_input('Enter house type: ') self.__COST=float(input('Enter cost: ')) def Display(self): print 'Registration number ',self.__REG_NO print 'Name: ',self.__NAME print 'House type: ',self.__TYPE print 'Cost: ',self.__COST def Draw_Nos(self,list1): if len(list1)==10: c=0 for i in range(10): if self.__name__=='HOUSING': c+=1 if c==10: import random c1=2 while c1!=2: print 'raw No.',i print '-----------' draw=random.randint(10,1000) if draw==self.__REG_NO: self.Display() c1+=1 else: for i in range(10): x=list1[i] if draw==x._HOUSING__REG_NO: x.Display() c1+=1 break
e8cee8af302c88e5e20ff072a466e28c2aa808ae
SubrataSarkar32/college3rdsem3035
/class12pythoncbse-master/Chapter 6&7/queue.py
1,875
3.96875
4
class queue: '''This normal queue''' def __init__(self,limit): self.L=[] self.limit=limit self.insertstat=True def insertr(self,element): if self.insertstat==True: if len(self.L)==0: self.L.append(element) elif len(self.L)<self.limit: L1=[element] L1=self.L+L1 from copy import deepcopy self.L=deepcopy(L1) if len(self.L)==self.limit: self.insertstat=False else: print 'OVERFLOW!!' else: print 'OVERFLOW!!' def deletel(self): if len(self.L)==0: print 'UNDERFLOW!!' else: k=self.L.pop(0) print 'Element removed ',k def display(self): for i in self.L: print i, if len(self.L)==0: for j in range(len(self.L)-1,self.limit): print '_', print print '#'*30 def __str__(self): return str(self.L) #--------------------------main---------------------------------- while True: g=[] print 'Creating new queue' limit=input('Enter number of blocks you want in queue:') st1=deque(limit) print 'queue created' print '1.Enqueue element' print '2.Dequeue element' print '3.Display queue' print '4.Display list' print '5.Quit' while True: res=raw_input('Enter your choice: ') if res=='1': element=input('Enter element: ') st1.insertr(element) elif res=='2': st1.deletel() elif res=='3': st1.display() elif res=='5': import sys sys.exit() elif res=='4': print st1 else: print 'Invalid command'
4ff55a48679abadf58c65cd9e92f86231c089424
SubrataSarkar32/college3rdsem3035
/class12pythoncbse-master/Chapter 4/Question8.py
539
3.65625
4
class ticbooth: price=2.50 people=0 totmoney=0.0 def __init__(self): self.totmoney=float(input('Enter the amount if paid else 0:')) ticbooth.people+=1 if self.totmoney==2.50: ticbooth.totmoney+=2.50 @staticmethod def reset(): ticbooth.people=0 ticbooth.totmoney=0.0 def dis(self): print 'Number of people ',ticbooth.people,'amount paid ',ticbooth.totmoney def distics(self): print 'Number of people who paid money',ticbooth.totmoney/2.50
6ad09ceb2ab4a05697fb9673000154dcae6d3e0a
SubrataSarkar32/college3rdsem3035
/class12pythoncbse-master/Chapter 4/Question11.py
876
3.796875
4
class DATE: monda=[[1,31],[2,28],[3,31],[4,30],[5,31],[6,30],[7,31],[8,31],[9,30],[10,31],[11,30],[12,31]] def __init__(self,month,day): a=len(DATE.monda) self.month=month self.day=day while self.month<1 or self.month>12: self.month=input('Enter month (1 to 12):') while self.day<1 or self.day>DATE.monda[self.month-1][1]: self.day=input('Enter day within limit of respective month: ') def days_in_month(self): return DATE.monda[self.month-1][1] def next_day(self): if self.day+1<=DATE.monda[self.month-1][1]: self.day+=1 else: if self.month<12: self.month+=1 self.day=1 else: self.month=1 self.day=1 def __str__(self): print str(self.month),'/',str(self.day)
b31f09ab94e4cbddb88f5180b3d2951c55d4b868
Kmr-Chetan/python_practice
/Palindrome.py
907
4
4
class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head= None def isPalindromeUtil(self, string): return (string == string[:: -1]) def isPalindrome(self): node = self.head temp = [] while(node is not None): temp.append(node.data) node = node.next string = "".join(temp) return self.isPalindromeUtil(string) def printList(self): temp =self.head while(temp): print(temp.data), temp = temp.next llist = LinkedList() llist.head = Node('a') llist.head.next =Node('b') llist.head.next.next =Node('c') llist.head.next.next.next =Node('b') llist.head.next.next.next.next =Node('a') llist.head.next.next.next.next.next =Node('c') print("true" if llist.isPalindrome() else "false")
4277a08cf47b4f91712841ef2e3757a49090650f
IStealYourSkill/python
/les3/3_3.py
579
4.28125
4
'''3. Проверить, что хотя бы одно из чисел a или b оканчивается на 0.''' a = int(input('Введите число A: ')) b = int(input('Введите число B: ')) if ((a >= 10) or (b >= 10)) and (a % 10 == 0 or b % 10 == 0): print("Одно из чисел оканчивается на 0") else: print("Числа {}, {} без нулей".format(a, b)) ''' if (10 <= a <= -10) and (a % 10 == 0): print("ноль, естЬ! {}".format(a)) else: print("Без нулей {}".format(a)) '''
36c1f3a4606a1e9cc61a363387495cb2f8fdb31d
charlottekosche/compciv-2018-ckosche
/week-05/ezsequences/ezlist.py
2,581
3.546875
4
################################# # ezsequences/ezlist.py # # This skeleton script contains a series of functions that # return ez_list = [0, 1, 2, 3, 4, ['a', 'b', 'c'], 5, ['apples', 'oranges'], 42] def foo_hello(): """ This function should simply return the `type` of the `ez_list` object. This guarantees that you'll past at least one of the tests/assertions in test_ezlist.py """ return type(ez_list) ################## # Exercises foo_a through foo_e cover basic list access ################## def foo_a(): """ Return the very first member of `ez_list` """ return ez_list [0] def foo_b(): """ Return the sum of the 2nd and 4th members of `ezlist` """ sum_second_and_forth = ez_list [1] + ez_list [3] return sum_second_and_forth def foo_c(): """ Return the very last member of `ez_list`. Use a negative index to specify this member """ return ez_list [-1] def foo_cx(): """ Return the type of the object that is the second-to-last member of `ez_list` """ return type(ez_list [-2]) def foo_d(): """ Return the very last member of the sequence that itself is the second-to-last member of `ez_list` """ second_to_last_member_of_ez_list = ez_list [-2] last_member_of_sequence = second_to_last_member_of_ez_list [-1] return last_member_of_sequence def foo_e(): """ Calculate and return the length of `ez_list`, i.e., the number of members it contains. """ return len(ez_list) def foo_f(): """ Return the 6th member of `ez_list` as a single, semi-colon delimited string i.e. the separate values are joined with the semi-colon character """ whole_string = "" sixth_member = ez_list [5] for i in sixth_member: single_string = str(i) if i == sixth_member [0]: whole_string = single_string else: whole_string = whole_string + ";" + single_string return whole_string """ Alternatively, I could have used the join function: return ';'.join(ez_list[5]) """ def foo_g(): """ Return a list that contains the 2nd through 5th elements of `ez_list` (it should have 4 members total) """ new_list = ez_list [1:5] return new_list def foo_h(): """ Return a list that consists of the last 3 members of `ez_list` in *reverse* order """ new_list = ez_list [-3::] reverse_list = list(reversed(new_list)) return reverse_list
cfdeb5d426d745a6986a5da2c172d9ff4293ab35
storm2513/Task-manager
/task-manager/library/tmlib/models/notification.py
755
3.640625
4
import enum class Status(enum.Enum): """ Enum that stores values of notification's statuses CREATED - Notification was created PENDING - Notification should be shown SHOWN - Notification was shown """ CREATED = 0 PENDING = 1 SHOWN = 2 class Notification: """Notification class that is used remind user about task""" def __init__( self, task_id, title, relative_start_time, status=Status.CREATED.value, id=None, user_id=None,): self.id = id self.user_id = user_id self.task_id = task_id self.title = title self.relative_start_time = relative_start_time self.status = status
ec5f0599d0af4f726978ea37e17c66b4e67da986
sweetkristas/mercy
/utils/citygen.py
4,065
3.5625
4
from random import randint, random import noise # variables: block_vertical block_horizontal road_vertical road_horizontal # start: block_vertical # rules: (block_vertical -> block_horizontal road_vertical block_horizontal) # (block_horizontal -> block_vertical road_horizontal block_vertical) block_vertical = 1 block_horizontal = 2 road_vertical = 10 road_horizontal = 11 road_width = 2 min_width = road_width + 4 min_height = road_width + 4 def as_string(data): if data == block_vertical: return "block_vertical" elif data == block_horizontal: return "block_horizontal" elif data == road_vertical: return "road_vertical" return "road_horizontal" class Tree(object): def __init__(self): self.left = None self.right = None self.data = None def recurse_tree(root, num_iterations, x, y, width, height): if num_iterations == 0 or (width <= min_width and height <= min_height): return if root.data[0] == block_vertical and width > min_width: w = int(width * random())/2 if w < min_width: w = min_width root.data = (road_vertical, x+w, y, road_width, height) root.left = Tree() root.left.data = (block_horizontal, x, y, w-road_width, height) root.right = Tree() root.right.data = (block_horizontal, x+w+road_width, y, width - w - road_width, height) recurse_tree(root.left, num_iterations-1, x, y, w, height) recurse_tree(root.right, num_iterations-1, x+w+road_width, y, width - w - road_width, height) elif root.data[0] == block_horizontal and height > min_height: h = int(height * random())/2 if h < min_height: h = min_height root.data = (road_horizontal, x, y+h, width, road_width) root.left = Tree() root.left.data = (block_vertical, x, y, width, h-road_width) root.right = Tree() root.right.data = (block_vertical, x, y+h+road_width, width, height - h - road_width) recurse_tree(root.left, num_iterations-1, x, y, width, h) recurse_tree(root.right, num_iterations-1, x, y+h+road_width, width, height - h - road_width) def print_tree(root): if root == None: return print_tree(root.left) print "%s" % as_string(root.data) print_tree(root.right) def create_grid(root, output): if root == None: return output create_grid(root.left, output) x = root.data[1] y = root.data[2] w = root.data[3] h = root.data[4] #print "%d, %d, %d, %d %s" % (x, y, w, h, as_string(root.data[0])) for m in range(y, y+h): for n in range(x, x+w): if root.data[0] == block_vertical: output[m][n] = '+' elif root.data[0] == block_horizontal: output[m][n] = '+' elif root.data[0] == road_vertical: output[m][n] = ' ' elif root.data[0] == road_horizontal: output[m][n] = ' ' create_grid(root.right, output) return output def main(width, height, num_iterations=10): root = Tree() root.data = (block_vertical, width) recurse_tree(root, num_iterations, 0, 0, width, height) output = [] for i in range(0, height): output.append([]) for j in range(0, width): output[-1].append(' ') output = create_grid(root, output) #print_tree(root) return output ascii_noise_map = [(0.0,'~'), (0.1,'-'), (0.25,'.'), (0.6,'+'), (1.0,'^')] def noise_map(width, height): ascii_noise_map.reverse() output = [] for i in range(0, height): output.append([]) for j in range(0, width): nv = noise.snoise2(float(j) / width, float(i) / height) outc = ' ' for np in ascii_noise_map: if nv < np[0]: outc = np[1] output[-1].append(outc) return output if __name__ == '__main__': #res = main(120, 50, 1000) #for row in res: # print ''.join(row) res2 = noise_map(150, 1000) for row in res2: print ''.join(row)
31d6a644a8962ddabee4d3d9140d47b131880667
ivanifp/tresEnRaya
/main.py
641
3.625
4
from utils import numJugadores,getFicha,colocaFicha,imprimirTablero,tableroLibre,victoria #me creo mi tablero con nueve posiciones tablero = [' ']*9 numJu = numJugadores() fichaj1,fichaj2 = getFicha() while tableroLibre(tablero) or victoria(tablero,fichaj1)== False or victoria(tablero,fichaj2)== False: imprimirTablero(tablero) pos = int(input("Diga movimiento jugador Uno"+fichaj1)) colocaFicha(tablero,pos,fichaj1) imprimirTablero(tablero) pos2 = int(input("Diga movimiento jugador Dos"+fichaj2)) colocaFicha(tablero,pos2,fichaj2) imprimirTablero(tablero) #fin tableroLibre
264b622be15b275164a1259f3906c9d69fe00819
stteem/Python
/MyPython/SearchExercise.py
689
3.875
4
# -*- coding: utf-8 -*- """ Created on Tue Jun 20 13:29:27 2017 @author: Uwemuke """ print("Please think of a number between 0 and 100!") high = 100 low = 0 guess = (high - low)//2.0 while guess**2 < high: print('Is your secret number' + str(guess) + '?') (input("Enter 'h' to indicate the guess is too high. \ Enter 'l' to indicate the guess is too low.\ Enter 'c' to indicate I guessed correctly.\ :" )) if ans == 'h': high = guess elif ans == 'l': low = guess elif ans == 'c': print('Game over. Your secret number was: ' + str(guess)) else: print('Sorry, i did not understandd your input.')
fb43e3221791f1b84663b42bb5d3b7e2917270a5
stteem/Python
/MyPython/Finding biggest value of a key.py
471
3.875
4
# -*- coding: utf-8 -*- """ Created on Mon Jun 26 12:04:30 2017 @author: Uwemuke """ def biggest(aDict): ''' aDict: A dictionary, where all the values are lists. returns: The key with the largest number of values associated with it ''' result = None biggestValue = 0 for key in aDict.keys(): if len(aDict[key]) >= biggestValue: result = key biggestValue = len(aDict[key]) return result
25dcce43a2306b81de2040ec215ae16dd77a2136
stteem/Python
/MyPython/midterm1 unfinished.py
569
3.875
4
# -*- coding: utf-8 -*- """ Created on Sat Jul 1 23:48:44 2017 @author: Uwemuke """ def largest_odd_times(L): L1 = {} for i in L: if i in L1: L1[i] += 1 else: L1[i] = 1 return L1 def even(k): k = max(freq) for i in range(0, k, 2): return i def odd_times(p): best = max(L1.values()) bestkey = max(L1.keys()) if bestkey not in even: return freq = largest_odd_times([3,9,5,3,5,3])
a63221aca27c99efdc063aa6a716b4fa4f6670c0
stteem/Python
/Pset4/Pset402.py
797
3.96875
4
# -*- coding: utf-8 -*- """ Created on Mon Jul 10 00:19:54 2017 @author: Uwemuke """ def updateHand(hand, word): """ Assumes that 'hand' has all the letters in word. In other words, this assumes that however many times a letter appears in 'word', 'hand' has at least as many of that letter in it. Updates the hand: uses up the letters in the given word and returns the new hand, without those letters in it. Has no side effects: does not modify hand. word: string hand: dictionary (string -> int) returns: dictionary (string -> int) """ update_hand = hand.copy() for i in word: update_hand[i] -= 1 return update_hand updateHand({'u': 1, 'a': 1, 'i': 1, 'l': 2, 'q': 1, 'm': 1}, 'quail')
861508bd3e5b4eeeeb8fcfe56fff987e723f4176
stteem/Python
/MyPython/multiplication_iterative_solution.py
225
3.6875
4
# -*- coding: utf-8 -*- """ Created on Wed Jun 21 12:58:11 2017 @author: Uwemuke """ def multi_iter(a, b): result = 0 while b > 0: result += a b -= 1 return result multi_iter(4, 8)
0f9bc0663d9c38f5e3be9a5051cf0e960736d148
unbecomingpig/scotchbutter
/scotchbutter/util/database.py
4,711
3.515625
4
"""Contains functions to help facilitate reading/writing from a database. NOTE: Currently only supporting sqlite databases """ import logging import sqlite3 import time from scotchbutter.util import environment, tables DB_FILENAME = 'tvshows.sqlite' logger = logging.getLogger(__name__) class DBInterface(): """Provides a contraced API to query the DataBase. Providing a contracted API allows for an transparent backend changes. # TODO: Add DB connections beyond sqlite. """ library_name = 'library' def __init__(self, db_file: str = DB_FILENAME): """Create an interface to query the DataBase.""" self._settings_path = environment.get_settings_path() self._db_file = self._settings_path.joinpath(db_file) logger.info('Using database located at %s', self._db_file) self._conn = None self._cursor = None self.close() @property def conn(self): """Create a DB connection if it doesn't already exist.""" if self._conn is None: self.connect() return self._conn @property def cursor(self): """Create a cursor to interact with the database.""" if self._cursor is None: self.connect() return self._cursor @property def existing_tables(self): """List tables currently in the database.""" query = "SELECT name FROM sqlite_master WHERE type='table'" results = self.cursor.execute(query) table_names = sorted([name for result in results for name in result]) return table_names def connect(self): """Create a new connection to DB.""" # If the database file doesn't exist, this will create it. self._conn = sqlite3.connect(self._db_file) self._cursor = self.conn.cursor() def close(self, commit: bool = True): """Close the DB connections.""" if self._conn is not None: if commit is True: self.conn.commit() self.conn.close() self._conn = None self._cursor = None def __enter__(self): """Context management protocol.""" self.connect() return self def __exit__(self, exc_type, exc_value, traceback): """Closes any existing DB connection.""" self.close() def create_table(self, name, columns): """Create a table in the database.""" table = tables.Table(name) for column in columns: table.add_column(column) if name not in self.existing_tables: self.cursor.execute(table.create_table_string) logger.info('Created table %s', name) return table def add_series(self, series): """Add a series to the database.""" table = self.create_table(self.library_name, tables.LIBRARY_COLUMNS) values = [series[column.name] for column in table.columns] self.cursor.execute(table.insert_string, values) logger.info('Added seriesId %s to %s', series.series_id, self.library_name) show_table = self.create_table(series.series_id, tables.SHOW_COLUMNS) episodes = [] for episode in series.episodes: values = [episode[column.name] for column in show_table.columns] episodes.append(values) logger.info('Added %s episodes to table %s', len(series.episodes), series.series_id) self.cursor.executemany(show_table.insert_string, episodes) def remove_series(self, series_id): """Remove a series from the database.""" drop_string = f"DROP TABLE IF EXISTS '{series_id}'" delete_string = f"DELETE FROM '{self.library_name}' WHERE seriesId = {series_id}" self.cursor.execute(delete_string) logger.info('Removed %s from table %s', series_id, self.library_name) self.cursor.execute(drop_string) logger.info('Removed table %s', series_id) def _select_from_table(self, table_name: str): """Select all entries from a table.""" # TODO: expand this to accept where statements results = self.cursor.execute(f'SELECT * from {table_name}') column_names = [x[0] for x in results.description] rows_values = [dict(zip(column_names, row)) for row in results] logger.debug('Selected %s rows from table %s', len(rows_values), table_name) return rows_values def get_library(self): """return a list of series dicts for shows in the library.""" return self._select_from_table(self.library_name) def get_episodes(self, series_id): """Return a list of episode dicts for the requested series.""" return self._select_from_table(series_id)
08ef8703147476759e224e66efdc7b5de5addf6e
chaoma1988/Coursera_Python_Program_Essentials
/days_between.py
1,076
4.65625
5
''' Problem 3: Computing the number of days between two dates Now that we have a way to check if a given date is valid, you will write a function called days_between that takes six integers (year1, month1, day1, year2, month2, day2) and returns the number of days from an earlier date (year1-month1-day1) to a later date (year2-month2-day2). If either date is invalid, the function should return 0. Notice that you already wrote a function to determine if a date is valid or not! If the second date is earlier than the first date, the function should also return 0. ''' import datetime from is_valid_date import is_valid_date def days_between(year1,month1,day1,year2,month2,day2): if is_valid_date(year1,month1,day1): date1 = datetime.date(year1,month1,day1) else: return 0 if is_valid_date(year2,month2,day2): date2 = datetime.date(year2,month2,day2) else: return 0 delta = date2 - date1 if delta.days <= 0: return 0 else: return delta.days # Testing #print(days_between(1988,7,19,2018,7,3))
d53544648c25cc8d0562cc4cd92ce70341e8d353
lch172061365/Computational-Physics
/Project3/3e(for jupiter of original mass).py
3,370
3.640625
4
import matplotlib.pyplot as plt import matplotlib.animation as animation import numpy as np import math from mpl_toolkits.mplot3d import Axes3D import matplotlib.image as img G = 6.67*10**(-11) m1 = 6*10**24 #earth m2 = 2*10**30 #sun m3 = 1.9*10**27 #jupiter #m1 x10 = -149597870000 y10 = 0 z10 = 0 p10 = 0 q10 = 29783 r10 = 0 #m2 x20 = 0 y20 = 0 z20 = 0 p20 = 0 q20 = 0 r20 = 0 #m3 x30 = 778547200000 y30 = 0 z30 = 0 p30 = 0 q30 = -13070 r30 = 0 dt = 2000 n = 1000000 #initialize the position x1 = [0] y1 = [0] z1 = [0] x2 = [0] y2 = [0] z2 = [0] x3 = [0] y3 = [0] z3 = [0] x1[0] = x10 #set up initial position y1[0] = y10 z1[0] = z10 x2[0] = x20 y2[0] = y20 z2[0] = z20 x3[0] = x30 y3[0] = y30 z3[0] = z30 #initialzie the speed, create a list p1 = [0] q1 = [0] r1 = [0] p2 = [0] q2 = [0] r2 = [0] p3 = [0] q3 = [0] r3 = [0] p1[0] = p10 #set up initial speed q1[0] = q10 r1[0] = r10 p2[0] = p20 q2[0] = q20 r2[0] = r20 p3[0] = p30 q3[0] = q30 r3[0] = r30 #loop i = 0 while i < n-1: #three distances S12 = math.sqrt((x2[i]-x1[i])**2+(y2[i]-y1[i])**2+(z2[i]-z1[i])**2) S13 = math.sqrt((x3[i]-x1[i])**2+(y3[i]-y1[i])**2+(z3[i]-z1[i])**2) S23 = math.sqrt((x2[i]-x3[i])**2+(y2[i]-y3[i])**2+(z2[i]-z3[i])**2) x1.append(x1[i]+p1[i]*dt) y1.append(y1[i]+q1[i]*dt) z1.append(z1[i]+r1[i]*dt) x2.append(x2[i]+p2[i]*dt) y2.append(y2[i]+q2[i]*dt) z2.append(z2[i]+r2[i]*dt) x3.append(x3[i]+p3[i]*dt) y3.append(y3[i]+q3[i]*dt) z3.append(z3[i]+r3[i]*dt) p1.append(dt*(G*m3*(x3[i+1]-x1[i+1])/((S13)**3)+G*m2*(x2[i+1]-x1[i+1])/((S12)**3))+p1[i]) q1.append(dt*(G*m3*(y3[i+1]-y1[i+1])/((S13)**3)+G*m2*(y2[i+1]-y1[i+1])/((S12)**3))+q1[i]) r1.append(dt*(G*m3*(z3[i+1]-z1[i+1])/((S13)**3)+G*m2*(z2[i+1]-z1[i+1])/((S12)**3))+r1[i]) p2.append(dt*(G*m1*(x1[i+1]-x2[i+1])/((S12)**3)+G*m3*(x3[i+1]-x2[i+1])/((S23)**3))+p2[i]) q2.append(dt*(G*m1*(y1[i+1]-y2[i+1])/((S12)**3)+G*m3*(y3[i+1]-y2[i+1])/((S23)**3))+q2[i]) r2.append(dt*(G*m1*(z1[i+1]-z2[i+1])/((S12)**3)+G*m3*(z3[i+1]-z2[i+1])/((S23)**3))+r2[i]) p3.append(dt*(G*m1*(x1[i+1]-x3[i+1])/((S13)**3)+G*m2*(x2[i+1]-x3[i+1])/((S23)**3))+p3[i]) q3.append(dt*(G*m1*(y1[i+1]-y3[i+1])/((S13)**3)+G*m2*(y2[i+1]-y3[i+1])/((S23)**3))+q3[i]) r3.append(dt*(G*m1*(z1[i+1]-z3[i+1])/((S13)**3)+G*m2*(z2[i+1]-z3[i+1])/((S23)**3))+r3[i]) #next loop i += 1 import mpl_toolkits.mplot3d.axes3d as p3 #make plot def update_lines(num,datalines,lines): for line,data in zip(lines,datalines): line.set_data(data[0:2, :num]) line.set_3d_properties(data[2, :num]) return lines fig = plt.figure() ax = p3.Axes3D(fig) #data turple data=[np.array([x1,y1,z1])[:,0:1000000:100], np.array([x2,y2,z2])[:,0:1000000:100], np.array([x3,y3,z3])[:,0:1000000:100]] lines =[ax.plot(dat[0, 0:1], dat[1, 0:1], dat[2, 0:1])[0] for dat in data] #make plot ax.set_xlim3d([-10**12,10**12]) ax.set_xlabel('X') ax.set_ylim3d([-10**12,10**12]) ax.set_ylabel('Y') ax.set_zlim3d([-10**12,10**12]) ax.set_zlabel('Z') ax.set_title('Simulation on three-body') #figure show line_ani = animation.FuncAnimation(fig, update_lines,fargs = (data,lines),interval =1,blit = False) plt.show()
95357539ad5ea90938cb13440a9e419206ba42f3
moisindustries/Leetcode-practice
/238-product-of-array-except-self.py
855
3.546875
4
""" Problem Link: https://leetcode.com/problems/product-of-array-except-self/description/ Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i]. Example: Input: [1,2,3,4] Output: [24,12,8,6] Note: Please solve it without division and in O(n). Follow up: Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.) """ class Solution(object): def productExceptSelf(self, nums): p = 1 n = len(nums) result = [] for i in range(0,n): result.append(p) p = p * nums[i] p = 1 for i in range(n-1,-1,-1): result[i] = result[i] * p p = p * nums[i] return result
b2ead9da892231c4d5e5c610d88797290a1cda29
ken4815/CP3-Pakkapong-Thonchaisuratkrul
/Lexture 46.py
87
3.546875
4
n = int(input("N:")) for x in range(24): x = x+1 print(n ,"*",x,"=",n * (x))
562ac5cebcf516d7e40724d3594186209d79c2f4
Vyara/First-Python-Programs
/quadratic.py
695
4.3125
4
# File: quadratic.py # A program that uses the quadratic formula to find real roots of a quadratic equation. def main(): print "This program finds real roots of a quadratic equation ax^2+bx+c=0." a = input("Type in a value for 'a' and press Enter: ") b = input("Type in a value for 'b' and press Enter: ") c = input("Type in a value for 'c' and press Enter: ") d = (b**2.0 - (4.0 * a * c)) if d < 0: print "No real roots" else: root_1 = (-b + d**0.5) / (2.0 * a) root_2 = (-b - d**0.5) / (2.0 * a) print "The answers are:", root_1, "and", root_2 raw_input("Press Enter to exit.") main()
301a8410b1a192e4c0c40b404e0bdaca03005de6
chilu49/python
/deck-blackjack.py
321
3.6875
4
#from random import shuffle #ranks = range(2,11) + ['JACK', 'QUEEN', 'KING', 'ACE'] #print ranks #suits = ['S', 'H', 'D', 'C'] #print suits #def get_deck(): # """Return new deck of cards""" # return [[rank,suit] for rank in ranks for suit in suits] #deck = get_deck() #shuffle(deck) #print deck #print len(deck)
2981b59c33aec6471398075ff81f7757888d68e5
hurenkam/AoC
/2022/Day02/part2.py
538
3.765625
4
#!/bin/env python with open('input.txt','r') as file: lines = [line.strip() for line in file] lookup = { "A X": "A C", "A Y": "A A", "A Z": "A B", "B X": "B A", "B Y": "B B", "B Z": "B C", "C X": "C B", "C Y": "C C", "C Z": "C A" } scores = { "A A": 4, "A B": 8, "A C": 3, "B A": 1, "B B": 5, "B C": 9, "C A": 7, "C B": 2, "C C": 6 } total = 0 while (len(lines)): line = lines.pop(0) score = scores[lookup[line]] total += score print(total)
f8ce648c17349a1b550f4e22d6146a9bffe2509f
hurenkam/AoC
/2022/Day11/part2.py
2,832
3.625
4
#!/bin/env python with open('input.txt','r') as file: lines = [line.strip() for line in file] def parseInput(lines): while len(lines): while not lines[0].startswith("Monkey"): lines.pop(0) parseMonkey(lines) monkeys={} def parseMonkey(lines): global monkeys index = parseIndex(lines.pop(0)) items = parseStartItems(lines.pop(0)) operation = parseOperation(lines.pop(0)) divider = parseDivider(lines.pop(0)) monkeytrue = parseTargetIndex(lines.pop(0)) monkeyfalse = parseTargetIndex(lines.pop(0)) monkeys[index] = { "index": index, "items": items, "operation": operation, "divider": divider, "targets": [monkeytrue,monkeyfalse], "inspections":0 } def parseIndex(line): p1 = line.split(':') p2 = p1[0].split(' ') return int(p2[1]) def parseStartItems(line): p1 = line.split(':') p2 = p1[1].split(',') items = [] for item in p2: items.append(int(item)) return items def parseOperation(line): p1 = line.split(':') p2 = p1[1].split('=') p3 = p2[1].strip().split(' ') operator = p3[1].strip() if operator == '+': return (add,int(p3[2])) if operator == '*': if p3[2] == 'old': return (power,None) return (multiply,int(p3[2])) raise Exception("unsupported operation") def power(old,arg): return old * old def add(old,arg): return old + arg def multiply(old,arg): return old * arg def parseDivider(line): p1 = line.split(':') p2 = p1[1].split(' ') divider = int(p2.pop()) return divider def parseTargetIndex(line): p1 = line.split(':') p2 = p1[1].split(' ') index = int(p2.pop()) return index def doRound(): monkeysToVisit = sorted(monkeys) for index in sorted(monkeys): doRoundForMonkey(index) #printMonkeys() def doRoundForMonkey(index): items = monkeys[index]["items"] monkeys[index]["items"] = [] for item in items: doItemForMonkey(item,index) def doItemForMonkey(item,index): monkeys[index]["inspections"] += 1 op = monkeys[index]["operation"][0] arg = monkeys[index]["operation"][1] item = op(item,arg) % moduloFactor test = (item % monkeys[index]["divider"] == 0) if (test): target = monkeys[index]["targets"][0] else: target = monkeys[index]["targets"][1] monkeys[target]["items"].append(item) moduloFactor = 1 def calculateModuloFactor(): global moduloFactor for key in sorted(monkeys): moduloFactor *= monkeys[key]["divider"] parseInput(lines) calculateModuloFactor() for i in range(0,10000): doRound() inspections = [] for key in sorted(monkeys): inspections.append(monkeys[key]["inspections"]) inspections.sort() l = len(inspections) print(inspections[l-1]*inspections[l-2])
4dcb005342c13a213a78196aab6a4739aa80776a
hurenkam/AoC
/2022/Day08/part2.py
1,310
3.578125
4
#!/bin/env python with open('input.txt','r') as file: lines = [line.strip() for line in file] def buildMatrix(): forrest = [] for line in lines: treeline = [] for tree in line: height = int(tree) treeline.append(height) forrest.append(treeline) return forrest def calculateScenicScore(forrest,x,y): current = forrest[y][x] left = countVisibleTrees(forrest,current,x,y,-1,0) right = countVisibleTrees(forrest,current,x,y,1,0) top = countVisibleTrees(forrest,current,x,y,0,-1) bottom = countVisibleTrees(forrest,current,x,y,0,1) result = left*right*top*bottom return left * right * top * bottom def countVisibleTrees(forrest,current,x,y,dx,dy): height = len(forrest) width = len(forrest[0]) count = 0 x += dx y += dy if (x>=0) and (x<width) and (y>=0) and (y<height): if (forrest[y][x] < current): return 1 + countVisibleTrees(forrest,current,x,y,dx,dy) else: return 1 return 0 forrest = buildMatrix() height = len(forrest) width = len(forrest[0]) score = 0 for y in range(0,height): for x in range(0,width): result = calculateScenicScore(forrest,x,y) if (result > score): score = result print(score)
23aeb35a5d118fe8e57e355514ff5bb71652b62b
hurenkam/AoC
/2020/Day13/solve.py
1,214
3.703125
4
#!/usr/bin/env python3 #=================================================================================== def Part1(): departures={} tmp = [int(bus) for bus in busses if bus !='x'] for bus in tmp: departs = (int(arrival / bus) +1) * bus waittime = departs - arrival departures[waittime] = bus best = min(departures.keys()) return departures[best] * best def FindEarliestDepartureTime(desired,bus): return (int(desired / bus) +1) * bus #=================================================================================== def Part2(): mods = {bus: -i % bus for i, bus in enumerate(busses) if bus != "x"} sortedbusses = list(reversed(sorted(mods))) t = mods[sortedbusses[0]] r = sortedbusses[0] for bus in sortedbusses[1:]: while t % bus != mods[bus]: t += r r *= bus return t #=================================================================================== print("Day 13") with open('input','r') as file: lines = [line.strip() for line in file] arrival = int(lines[0]) busses = ["x" if x == "x" else int(x) for x in lines[1].split(",")] print("Part1: ",Part1()) print("Part2: ",Part2())
852cba828e67b97d2ddd91322a827bfdc3c6a849
ridhamaditi/tops
/Assignments/Module(1)-function&method/b1.py
287
4.3125
4
#Write a Python function to calculate the factorial of a number (a non-negative integer) def fac(n): fact=1 for i in range(1,n+1): fact *= i print("Fact: ",fact) try: n=int(input("Enter non-negative number: ")) if n<0 : print("Error") else: fac(n) except: print("Error")
287f5f10e5cc7c1e40e545d958c54c8d01586bfb
ridhamaditi/tops
/Assignments/Module(1)-Exception Handling/a2.py
252
4.15625
4
#write program that will ask the user to enter a number until they guess a stored number correctly a=10 try: n=int(input("Enter number: ")) while a!=n : print("Enter again") n=int(input("Enter number: ")) print("Yay") except: print("Error")
4337d05a72684cdfc0bdef255ccfcce72d5f6432
ridhamaditi/tops
/Assignments/Module(1)-modules/I2.py
188
4.375
4
# Aim: Write a Python program to convert degree to radian. pi=22/7 try: degree = float(input("Input degrees: ")) radian = degree*(pi/180) print(radian) except: print("Invalid input.")
e3eca8bce227d8d6c6b4526189945c2cd79e0c41
ridhamaditi/tops
/functions/prime.py
234
4.1875
4
def isprime(n,i=2): if n <= 2: return True elif n % i == 0: return False elif i*i > n: return True else: return isprime(n,i+1) n=int(input("Enter No: ")) j=isprime(n) if j==True: print("Prime") else: print("Not prime")
bcc1edf1be77b38dff101b8221497dc5baa3f2ec
ridhamaditi/tops
/modules/math_sphere.py
237
4.15625
4
import math print("Enter radius: ") try: r = float(input()) area = math.pi * math.pow(r, 2) volume = math.pi * (4.0/3.0) * math.pow(r, 3) print("\nArea:", area) print("\nVolume:", volume) except ValueError: print("Invalid Input.")
1d2389112a628dbf8891f85d6606ec44543fc81d
ridhamaditi/tops
/Assignments/Module(1)-Exception Handling/a4.py
791
4.21875
4
#Write program that except Clause with No Exceptions class Error(Exception): """Base class for other exceptions""" pass class ValueTooSmallError(Error): """Raised when the input value is too small""" pass class ValueTooLargeError(Error): """Raised when the input value is too large""" pass # user guesses a number until he/she gets it right number = 10 while True: try: inum = int(input("Enter a number: ")) if inum < number: raise ValueTooSmallError elif inum > number: raise ValueTooLargeError break except ValueTooSmallError: print("This value is too small, try again!") except ValueTooLargeError: print("This value is too large, try again!") print("Congratulations! You guessed it correctly.")