blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
18f6de56fc61ce088b3a8bcbeb4eae9266bcc013
anantbarthwal/pythonCodes
/lecture2/bubbleSort.py
260
3.9375
4
list1 = [10, 8, 12, 2] length = len(list1) print("list1 = ", list1) for i in range(length-1): for j in range(length - i - 1): if list1[j] > list1[j+1]: list1[j], list1[j+1] = list1[j+1], list1[j] print("list after sorting= ", list1)
edf71f8f296c4e8a6748445bef1d3b14c5b36e85
rakeshsukla53/interview-preparation
/Rakesh/python-iterators/groupby_clause.py
364
3.78125
4
from itertools import groupby class Solution(object): def groupStrings(self, strings): """ :type strings: List[str] :rtype: List[List[str]] """ result = [] for k, g in groupby(strings, key=len): result.append(sorted(list(g))) return result print Solution().groupStrings(["ab", "ba", "d"])
d265372b8b5d3a294bcfd0eb292ceea82f131516
qsunny/python
/coding-200/chapter11/thread_queue.py
1,919
3.578125
4
#线程间通信 import time import threading from chapter11 import variables from threading import Condition #1. 生产者当生产10个url以后就就等待,保证detail_url_list中最多只有十个url #2. 当url_list为空的时候,消费者就暂停 def get_detail_html(lock): #爬取文章详情页 detail_url_list = variables.detail_url_list while True: if len(variables.detail_url_list): lock.acquire() if len(detail_url_list): url = detail_url_list.pop() lock.release() # for url in detail_url_list: print("get detail html started") time.sleep(2) print("get detail html end") else: lock.release() time.sleep(1) def get_detail_url(lock): # 爬取文章列表页 detail_url_list = variables.detail_url_list while True: print("get detail url started") time.sleep(4) for i in range(20): lock.acquire() if len(detail_url_list) >= 10: lock.release() time.sleep(1) else: detail_url_list.append("http://projectsedu.com/{id}".format(id=i)) lock.release() print("get detail url end") #1. 线程通信方式- 共享变量 if __name__ == "__main__": lock = RLock() thread_detail_url = threading.Thread(target=get_detail_url, args=(lock,)) for i in range(10): html_thread = threading.Thread(target=get_detail_html, args=(lock,)) html_thread.start() # # thread2 = GetDetailUrl("get_detail_url") start_time = time.time() # thread_detail_url.start() # thread_detail_url1.start() # # thread1.join() # thread2.join() #当主线程退出的时候, 子线程kill掉 print ("last time: {}".format(time.time()-start_time))
bd35e4b9008cdc438ce338c3b7861ced84d559d9
Sasikumar-P/Python_revision-
/Directory.py
1,423
4.1875
4
print "*****TELEPHONE DIRECTORY*****" list1 = [] list2 = [] dict1 = {} temp = 100 n = input("enter the number of contacts :") for i in range(0,n): name1 = raw_input("Enter your name :") num1 = input("Enter your phonenumber") list1.extend([name1]) list2.extend([num1]) dict1 = dict(zip(list1,list2)) #to convert two lists into dictionary print dict1 print """ 1.Add a contact 2.Search a contact 3.Delete a contact 4.Update a contact 5.View a contact 6.Exit """ choice = input("Enter your choice") def add(dict1): name3 = raw_input("Enter new name that you want to add :") num3 = input("Enter the new number") dict1[name3] = num3 print dict1 def search(dict1, n, list1, temp): name2 = raw_input("Enter the name whose number is to be found") for i in range(0,n): if list1[i] == name2: temp = i if temp !=100: print "Number is :",list2[temp] def delete(dict1): name4 = raw_input("Enter the name you want to delete") del dict1[name4] print dict1 def update(dict1, n, list1): name5 = raw_input("Enter the name you want to update :") for i in range(0,n): if list[i] == name5: temp = i if temp!=100: num5 = input("Enter the new number") dict1[name5] = num5 print dict1 def view(dict1): print dict1 if (choice == 1): add(dict1) elif(choice == 2): search(dict1, n, list1,temp) elif(choice == 3): delete(dict1) elif(choice == 4): update(dict1, n, list1) else: view(dict1)
4ab51bf7845a4eb3e88974e119848c83156b4299
karangale/Airbnb_price_prediction
/airbnb_price_prediction/markers.py
1,478
3.5625
4
"""Markers for airbnb and restaurant locations.""" def airbnb_popup_frame(each): """ Create airbnb listing marker details. Args: param (tuple): This input is each row of the dataframe Returns: str: String with HTML format listing information """ picture_url = each['picture_url'] listing_url = each['listing_url'] info = '<h4> Listing Information </h4>' info = info + '<b> House Info </b><br>' info = info + '<img src =' + picture_url +\ 'height = "300" width = "300">' + '<br><br>' info = info + '<b>Location: </b>' + each['street'] + '<br>' info = info + '<b>Property Type: </b>' + each['property_type'] + '<br>' info = info + '<b>Number of Bathrooms: </b>' +\ str(int(each['bathrooms'])) + '<br>' info = info + '<b>Number of Bedrooms: </b>' +\ str(int(each['bedrooms'])) + '<br>' info = info + '<b>Number of Beds: </b>' +\ str(int(each['beds'])) + '<br>' info = info + '<b>Listing URL: </b>' + '<a href="' +\ listing_url + '" target="_blank">' + listing_url + '</a>' + '<br>' def restaurant_popup_frame(each): """ Create restaurant marker details. Args: param (str): This input is the row of the dataframe Returns: str: String with HTML format listing information """ info = '<h4>' + each['Name'].title() + '</h4>' info = info + '<b>Address: </b>' + each['Address'].title() + '<br>' return info
daa95e1d0332847f4d8352cd704faa809e55ab8a
abhaj2/Phyton
/sample programs_cycle_1_phyton/17.py
124
4.0625
4
#To count the number of digits in an integer c=0 x=int(input("Enter the digit")) while x!=0: x=x//10 c=c+1 print(c)
47d92a4cf671dff8897bf52b0a2325f0647eaf11
jinurajan/Datastructures
/crack-the-coding-interview/stacks_and_queues/queue_using_two_stacks.py
1,171
4
4
class Stack(object): def __init__(self): self.stack = [] def push(self, data): self.stack.append(data) def pop(self): return self.stack.pop() def peek(self): return self.stack[-1] def isempty(self): return True if not self.stack else False class QueueUsing2Stacks(object): def __init__(self): self.stack1 = Stack() self.stack2 = Stack() def enqueue(self, data): self.stack1.push(data) def dequeue(self): if self.stack1.isempty() and self.stack2.isempty(): return "Queue Empty" if self.stack2 is None: # second stack is empty while not self.stack1.isempty(): x = self.stack1.pop() print x self.stack2.push(x) print self.stack2.stack # x = self.stack2.peek() # self.stack2.pop() # return x if __name__ == "__main__": q = QueueUsing2Stacks() q.enqueue(1) q.enqueue(2) q.enqueue(3) q.enqueue(4) print q.stack1.stack print q.dequeue() # print q.dequeue() # print q.dequeue() # print q.dequeue()
933ac2242e32bbd3fe95e0a69e11fa0088ad794e
Akshidhlavanya/san
/p32.py
133
3.734375
4
x,y=map(int,input("Enter two value").split(' ')) a=map(int,input("Enter values").split(' ')) if y in a:print("yes") else:print("no")
e6ee702cd0d91f42da50f8ec0288ac1ca6ecacab
warrenzhoujing/sirbot
/rook.py
1,507
3.8125
4
#!/usr/bin/env python3 import logging from position import Position from constants import Color logging.basicConfig(level=logging.DEBUG) class Rook: def __init__(self, color=Color.WHITE.value, col=1): if col != 1 and col != 8: raise AssertionError self._color = color row = 1 if self._color == Color.WHITE.value else 8 self._position = Position(col, row) def __str__(self): return "Rook(%s, %s)" % (self._color, self._position) def __repr__(self): return self.__str__() @property def position(self): return self._position @position.setter def position(self, position): self._position = position def next_valid_positions(self): """Calculate the next valid positions based on the current position. 1. Make a list of positions the Knight can move no matter if it's legal or not 2. Filter out the illegal positions Illegal positions: Outside of board (DONE) Returns: list: A list of legal positions """ positions = [] row = self._position.row col = self._position.col for i in range(1, 8): positions.append(Position(row=row + i, col=col)) positions.append(Position(row=row - i, col=col)) positions.append(Position(row=row, col=col + i)) positions.append(Position(row=row, col=col - i)) return [p for p in positions if p.is_onboard()]
67e849d52323534b3e507e5d2bf87ce31fc65db4
SirajKarim/Python-Crash-Course
/tempCodeRunnerFile.py
151
3.546875
4
active = True while active: message = input("Enter Something \n") if message == 'quit': active = False else: print(message)
f5a1d5411fa95763b3165c9ea274dacfbd923d8b
Jongveloper/hanghae99_algorithm_class
/algorithm_practice/1157.py
867
3.9375
4
# 알파벳 대소문자로 된 단어가 주어지면, 이 단어에서 가장 많이 사용된 알파벳이 무엇인지 알아내는 프로그램을 작성 단, 대문자와 소문자 구분 x # 입력 : 첫째 줄에 알파벳 대소문자로 이루어진 단어가 주어짐 # 출력 : 첫째 줄에 이 단어에서 가장 많이 사용된 알파벳을 대문자로 출력 단, 가장 많이 사용된 알파벳이 여러개 존재하는경우 ?를 출력 # 문제 접근 방식 : 대소문자 구분을 하지 않기 위해 모두 대문자로 변환 words = input().upper() set_words = list(set(words)) max_word_cnt = [] for word in set_words: word = words.count(word) max_word_cnt.append(word) if max_word_cnt.count(max(max_word_cnt)) > 1: print("?") else: max_index = max_word_cnt.index(max(max_word_cnt)) print(set_words[max_index])
6b8061f5ca3c69aa11860b16f47ed6458b5f3e27
srp2210/PythonBasic
/dp_w3resource_solutions/regular-expression/22_ find_occurrence_and_position_of_substrings_within_string.py
452
3.828125
4
""" * @author: Divyesh Patel * @email: pateldivyesh009@gmail.com * @date: 23/05/20 * @decription: the occurrence and position of the substrings within a string """ # Related Article can be found here: https://docs.python.org/3.7/howto/regex.html import re text = 'hello world this is divyesh patel, how beautiful this world is.' pattern = 'world' cpattern = re.compile(pattern) thelist = cpattern.finditer(text) for each in thelist: print(each.group(), each.span())
e3026fc9ce23f25604e6706b73078490c15d280a
lceric/study-workspace
/Python/study/study-function.py
9,402
3.8125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # 第一行注释是为了告诉Linux/OS X系统,这是一个Python可执行程序,Windows系统会忽略这个注释; # 第二行注释是为了告诉Python解释器,按照UTF-8编码读取源代码,否则,你在源代码中写的中文输出可能会有乱码。 # 使用def语句声明函数 # *args是可变参数,args接收的是一个tuple; # **kw是关键字参数,kw接收的是一个dict。 # 写一个abs函数 def my_abs(num): if not isinstance(num, (int, float)): raise TypeError('bad operand type') if num < 0: return -num else: return num print(my_abs(-99)) # 99 print(my_abs(9)) # 9 # print(my_abs('a')) # 错误参数自检 # 占位, pass, 占位,开发的时候可以让代码先跑起来 def nop_fun(): pass import math def move(x, y, step, angle=0): nx = x + step * math.cos(angle) ny = y - step * math.sin(angle) return nx, ny x,y = move(100, 100, 60, math.pi / 6) print(x, y) def quadratic(a, b, c): if not isinstance(a, (int, float)): raise TypeError('a 必须是数值') if not isinstance(b, (int, float)): raise TypeError('b 必须是数值') if not isinstance(c, (int, float)): raise TypeError('c 必须是数值') if a == 0: raise TypeError('a不能等于0') x1 = (-b + math.sqrt(b*b - 4*a*c)) / (2*a) x2 = (-b - math.sqrt(b*b - 4*a*c)) / (2*a) return x1, x2 print(quadratic(2, 3, 1)) if quadratic(2, 3, 1) != (-0.5, -1.0): print('测试失败') elif quadratic(1, 3, -4) != (1.0, -4.0): print('测试失败') else: print('测试成功') # 定义一个x n次方 def power(x, n = 2): res = x idx = 1 if n == 0: return 1 while idx < n: res = res * x idx = idx + 1 return res print(power(3, 0)) # 1 print(power(3)) # 9 def power2(x = 2, n = 2): res = 1 while n > 0: n = n - 1 res = res * x return res print(power2(3, 0)) # 1 print(power2()) # 4 # 默认参数值 def enroll(name, sex, age = 8, city = 'xian'): print('name%s'%name) print('sex%s'%sex) print('age%s'%age) print('city%s'%city) enroll('lc', 'man') # 可以不按顺序 enroll('lc', 'man', city = 'zhouzhi') def end_add(L = []): L.append('END') return L print(end_add([1])) print(end_add([1])) print(end_add()) # ['END'] print(end_add()) # ['END', '#END'] # 修复后 def end_add1(L = None): if L == None: L = [] L.append('END') return L print(end_add1()) # ['END'] print(end_add1()) # ['END'] # 可变参数 def calc(numbers=[]): sum = 0 for n in numbers: sum = sum + n * n return sum print(calc([1, 2, 3])) print(calc()) #### *使得参数接受的是一个tuple def calc1(*numbers): sum = 0 for n in numbers: sum = sum + n * n return sum print(calc1(1, 2, 3)) #### 如果需要传入一个list params = [1, 2, 3] print(calc1(*params)) #关键字参数 def person(name, age, **ke): ke['sex'] = 'woman' print('name:', name, 'age:', age, 'other:', ke) person('lc', 18) person('kebi', 18, city='xian') person('kebi', 18, city='xian', weight=200) extra = {'city': 'xian', 'weight': 200, 'sex': 'man'} # print(**extra) #只能在function中使用 person('kebi', 18, **extra) print(extra) # **在函数中操作,是不会影响外部的extra的 # def person1(name, age, *, city = 1, sex = 2): print('name:', name, 'age:', age, 'city:', city, 'sex', sex) person1('kebi', 18) # 递归函数 # n! = 1 * 2 * 3 * 4... def fact(n): if n == 1: return 1 return n * fact(n - 1) print(fact(1)) print(fact(3)) print(fact(5)) # 尾递归做优化,可惜python解释器并没有对尾递归做优化,所以过多的递归还是会导致栈溢出 def fact1(n): return fact_iter(n, 1) def fact_iter(num, pro): if num == 1: return pro return fact_iter(num - 1, pro * num) print(fact1(5)) # 汉诺塔 64个 def tower(num): return math.pow(2, num) - 1 print(tower(64)) # 思路 不管在什么情况下都是把n-1个从a挪到b 然后a再挪到c, 最后再把n-1个从b挪到c def move(n, a, b, c): if n == 1: print(a, '---->', c) else: move(n-1, a, c, b) move(1, a, b, c) move(n-1, b, a, c) move(10, 'A', 'B', 'C') ############################################### # 返回函数 ############################################### # 利用闭包返回一个计数器函数,每次调用它返回递增整数: def createCounter(): def num(): # def g(): # return t # return g n = 0 while True: n = n + 1 yield n f = num() def create(): return next(f) return create counterA = createCounter() print(counterA(), counterA(), counterA(), counterA(), counterA()) # 测试: counterA = createCounter() print(counterA(), counterA(), counterA(), counterA(), counterA()) # 1 2 3 4 5 counterB = createCounter() if [counterB(), counterB(), counterB(), counterB()] == [1, 2, 3, 4]: print('测试通过!') else: print('测试失败!') ############################################### # 匿名函数 ############################################### # lambda 返回表达式的结果 # f(x) = x * x f = lambda x: x * x print(f(2)) # def is_odd(n): # return n % 2 == 1 # L = list(filter(is_odd, range(1, 20))) is_odd = lambda n: n % 2 == 1 L = list(filter(is_odd, range(1, 20))) print(L) ############################################### # 装饰器 ############################################### # 函数也是一个对象,可以赋值给变量,通过变量调用 def now(): print('2018年') f = now f() # 函数有一个__name__属性,可以拿到函数的名字 print(now.__name__) print(f.__name__) # 打印日志的装饰器 def log(func): def wrapper(*arg, **kw): print('call %s():'%func.__name__) return func(*arg, **kw) return wrapper @log def now(): print('2015-3-25') now() # 带参数的装饰器 def log(text): def decorator(func): def wrapper(*args, **kw): print('%s %s():' % (text, func.__name__)) return func(*args, **kw) return wrapper return decorator # 调用 @log('测试execute') def now(): print('2099-1-1') now() print(now.__name__) # 因为返回的那个wrapper()函数名字就是'wrapper',所以,需要把原始函数的__name__等属性复制到wrapper()函数中,否则,有些依赖函数签名的代码执行就会出错。 # 不需要编写wrapper.__name__ = func.__name__这样的代码,Python内置的functools.wraps就是干这个事的,所以,一个完整的decorator的写法如下: import functools def log(func): @functools.wraps(func) def wrapper(*arg, **kw): print('call %s():'%func.__name__) return func(*arg, **kw) return wrapper # 带参数的decorator def log(text): def decorator(func): @functools.wraps(func) def wrapper(*arg, **kw): print('call %s():'%func.__name__) return func(*arg, **kw) return wrapper return decorator @log('测试execute') def now(): print('2099-1-1') now() print(now.__name__) # 设计一个decorator,它可作用于任何函数上,并打印该函数的执行时间 import time, functools def metric(fn): @functools.wraps(fn) def wrapper(*arg, **kw): t = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())) print('%s executed start in %s ms'%(fn.__name__, t)) start_time = time.time() result = fn(*arg, **kw) end_time = time.time() runtime = end_time - start_time print('运行总共耗费时间: %sms'%(runtime)) t = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())) print('%s executed end in %s ms'%(fn.__name__, t)) return result return wrapper # 测试 @metric def fast(x, y): time.sleep(0.0012) return x + y; @metric def slow(x, y, z): time.sleep(0.1234) return x * y * z; f = fast(11, 22) s = slow(11, 22, 33) if f != 33: print('测试失败!') elif s != 7986: print('测试失败!') else: print('测试成功!') import functools def logtest(func): # 判断是否是方法 if callable(func): @functools.wraps(func) def wrapper(*arg, **kw): print('%s方法执行' % func.__name__) return func(*arg, **kw) return wrapper else: def decorator(fn): @functools.wraps(fn) def wrapper(*arg, **kw): print('参数是%s的%s方法执行'%(func, fn.__name__)) return fn(*arg, **kw) return wrapper return decorator @logtest def f1(): print('无参数') f1() @logtest('你好,hello') def f2(): print('有参数') f2() ############################################### # 偏函数 ############################################### # functools模块提供, 下面是改造的函数 def int2(x, base=2): return int(x, base) # 使用fuctools可以完成 import functools int2 = functools.partial(int, base=2) print(int2('100000')) # 32 ############################################### # 导入模块 ############################################### # 默认情况下,Python解释器会搜索当前目录、所有已安装的内置模块和第三方模块,搜索路径存放在sys模块的path变量中: import sys print(sys.path) # 如果我们要添加自己的搜索目录,有两种方法: # 一是直接修改sys.path,添加要搜索的目录: # import sys # sys.path.append('/Users/michael/my_py_scripts') # 这种方法是在运行时修改,运行结束后失效。 # 第二种方法是设置环境变量PYTHONPATH,该环境变量的内容会被自动添加到模块搜索路径中。设置方式与设置Path环境变量类似。注意只需要添加你自己的搜索路径,Python自己本身的搜索路径不受影响。
e693accf8d77053c220e9e1ec17add0b2b8c41b7
ravduggal/Python
/ProgramFlow/guessinggame.py
1,445
4.1875
4
answer = 5 print("Please guess number between 1 and 10: ") guess = int(input()) if guess<answer: print("Please guess higher") elif guess>answer: print("Please guess lower") else: print("You got it first time right") if guess<answer: print("Please guess higher") guess=int(input()) if guess==answer: print("Well done, you guessed it") else: print("Sorry, you have not guessed correctly") elif guess>answer: print("Please guess lower") guess=int(input()) if guess==answer: print("Well done, you guessed it") else: print("Sorry, you have not guesses correctly") else: print("You got it first time right") #Using Operators if guess != answer: if guess<answer: print("Please guess higher") else: print("Please guess lower") guess=int(input()) if guess == answer: print("Well done, you guessed it") else: print("Sorry, you have not guessed correctly") else: print("You got it first time right") #Challenge if guess==answer: print("You got it first time right") else: if guess<answer: print("Please guess higher") else: print("Please guess lower") guess=int(input()) if guess==answer: print("Well done, you got it right") else: print("Sorry, you have not guesses correctly")
1b2316d1a7eb4534090ebb11f8191e0776408a07
carefulcoder/PythonExercises
/Tuples.py
191
3.765625
4
# numbers = (1, 2, 3) # numbers[0] = 10 # print(numbers[0]) # unpacking coordinates = (1, 2, 3) # x = coordinates[0] # y = coordinates[1] # z = coordinates[2] x, y, z = coordinates print(y)
da32e6249ab6bd2ece18bc60f4fa18046592f420
Ferkze/fatec_python
/aulas/aula7/media_digitos.py
295
3.71875
4
def media_digitos(n): 'Media dos dígitos de um número inteiro' def soma_digitos(n): nums_str = str(n) if len(nums_str) == 1: return int(n) else: return int(nums_str[0]) + soma_digitos(nums_str[1:]) return soma_digitos(n) / len(str(n)) print(media_digitos(1234))
dadd8bb247908155ed27b2098831bda3d58fe018
minwinmin/Atcoder
/ABC153/DP.py
2,194
3.84375
4
""" ここのロジック通りにプログラムを組んでいく。 https://qiita.com/drken/items/a5e6fe22863b7992efdb#%E5%95%8F%E9%A1%8C-2%E3%83%8A%E3%83%83%E3%83%97%E3%82%B5%E3%83%83%E3%82%AF%E5%95%8F%E9%A1%8C http://wakabame.hatenablog.com/entry/2017/09/10/211428 """ """ 最大和問題 N要素を持つ数列 a[0],a[1],⋯,a[N−1] から任意の個数の項を選んで和を取った時の最大値 """ N = int(input()) a = list(map(int, input().split())) def max_sum(N,a): dp=[0]*(N+1) #0の配列を0〜N用意する、初期値0みたいな感じ for i in range(N): #イメージするとちゃんとわかる、今回はリストaにマイナス値があると弾かれる感じ dp[i+1]=max(dp[i],dp[i]+a[i]) return dp[N] print(max_sum(N, a)) """ ナップザック問題 重さと価値の情報を持つ N 個の荷物を重さが W 以下になるように詰め込むとき価値の和を最大化 """ def knapsack(N, W, weight, value): #初期化 #Pythonでは浮動小数点数float型に無限大を表すinf inf = float("inf") #2次元配列だから行列みたいな感じ、表を思い受けべよう dp = [[-inf for i in range(W+1)] for j in range(N+1)] for i in range(W+1): dp[0][i]=0 #初期値みたいな感じ #DP for i in range(N): for w in range(W+1): #dp[i][w-weight[i]]の状態にi番目の荷物が入る可能性がある if weight[i]<=w: dp[i+1][w]=max(dp[i][w-weight[i]]+value[i], dp[i][w]) #入る可能性がない else: dp[i+1][w]=dp[i][w] return dp[N][W] """ dpは最大化するものをあらわす、例えば価値とか N = 3 W = 5 (weight,value)=(2,3),(1,2),(3,6) W j 0 1 2 3 4 5 N 0 0 0 0 0 0 0 i 1 2 3 i=0 w=0 weight[0]=2 <= w=0 else dp[1][0] = dp[0][0] = 0 i=0 w=1 weight[0]=2 <= w=1 else dp[1][0] = dp[0][0] = 0 i=0 w=2 weight[0]=2 <= w=2 if dp[1][0] = max(dp[0][2-2]+3 = 3, dp[0][3]=0) = 3 ・ ・ ・ と繰り返していく i=0 w=3 weight[0]=3 <= w=3 if dp[1][0] = max(dp[0][3-2], dp[0][3]=0) i=1 w =0 weight[0]=3 <= w=0 else: dp[2][0] = dp[1][0] """
3d4161d4ca9150761be7564fd4732a632a2324f7
weizhengda/Python3
/code/11.第十一章/5.枚举的注意事项/code.py
217
3.5625
4
from enum import Enum class VIP(Enum): YELLOW = 1 GREEN = 2 BLACK = 3 RED = 4 # 别名 class Common(): YELLOW = 1 for v in VIP: print(v) for v in VIP._menbers_: print(v)
22bea87dd0d96cf13c7c7a445da304dc03d5a7be
KellyKokka/Python-snakify-exercises
/question4.py
1,193
4.21875
4
def shortest_continuous_segment(s): '''implement the function''' i = s[0] n = 0 while n<len(s): if s[n] != i: break n += 1 #after execution of the above, i will be the number forming the first continuous segment #and n will be the length of the first continuous segment done_until = n #the variable done_until records until which position we scanned s so far while done_until < len(s): cur_i = s[done_until] cur_n = 0 while cur_n+done_until < len(s): if s[cur_n+done_until]!=cur_i: break cur_n +=1 #after execution of the above in the inner loop, #cur_i will be the number forming the next segment #and cur_n will be the length of the next segment done_until+=cur_n #this updates until where we scanned s so far if cur_n < n: n,i = cur_n, cur_i if cur_n == n and cur_i > i: i = cur_i #the two lines above possibly update (i,n) so that #i is the number forming the shortest segment so far and #n is the length of this shortest so far segment return (i,n)
540e06892960523cb6fe31e6d74e11df96fb8cd2
MatejGladis/DiscordBot
/Roll.py
4,093
3.765625
4
# Created by Matko import random # Function IsValid checks if the entered input is number def IsValid(Expression): try: int(Expression) return True except: return False # Function AddSpaces isolate numbers and characters form each other def AddSpaces(Expression): #plus checker for i in range(len(Expression)): if i > 1 and IsValid(Expression[i]) == True and Expression[i-1] == " ": a = 0 for j in range (i): if Expression[i-j] == "+" or Expression[i-j] == "d" or Expression[i-j] == "D": a=1 if Expression[i-j] != "+" and Expression[i-j] != "d" and Expression[i-j] != "D" and Expression[i-j] != "D" and Expression[i-j] != " " and a == 0 and j != 0: return False # SpaceRamover creates ramoves spaces for the Expression in for i cyclus SpaceRamover = Expression.split(" ") Expression = "" for i in range(len(SpaceRamover)): Expression += SpaceRamover[i] Position = 0 # While isolate numbers and characters form each other while True: # This while works while it find first nonnumber character while True: Position += 1 if Position >= len(Expression): break if IsValid(Expression[(Position - 1):(Position + 1)]) == False: break if Position >= len(Expression): break # This adds space between characters Expression = Expression[:Position] + " " + Expression[(Position):] Position += 1 return Expression # random roll def Roll(a): sum = random.randint(1, a) return sum # Write each roll and final sum of rolls def Calc(Expression): ExpressionList = Expression.split(" ") Positon = 0 FinalList = [] FinalSum = 0 while True: if IsValid(ExpressionList[Positon]) == True: # for + or - if len(ExpressionList) == Positon + 1 or IsValid(ExpressionList[Positon + 1]) == True: FinalList.append(ExpressionList[Positon]) FinalSum += int(ExpressionList[Positon]) # for dices #elif ExpressionList[Positon + 1] == "d" or ExpressionList[Positon + 1] == "D" and IsValid(ExpressionList[Positon + 2]) == False: #return False elif ExpressionList[Positon + 1] == "d" or ExpressionList[Positon + 1] == "D" and IsValid(ExpressionList[Positon + 2]) == True: for i in range(int(ExpressionList[Positon])): Calc = Roll((int(ExpressionList[Positon + 2]))) FinalList.append(str(Calc)) FinalSum += int(Calc) Positon += 2 elif ExpressionList[Positon+1] == "+" and IsValid(ExpressionList[Positon + 2]) == False and ExpressionList[Positon + 2] != "d" and ExpressionList[Positon + 2] != "D": return False elif ExpressionList[Positon+1] == "+" and IsValid(ExpressionList[Positon + 2]) == True or ExpressionList[Positon + 2] == "d" or ExpressionList[Positon + 2] == "D": FinalList.append(ExpressionList[Positon]) FinalSum += int(ExpressionList[Positon]) Positon += 1 else: return False elif ExpressionList[Positon] == "d" and len(ExpressionList) != Positon + 1: if IsValid(ExpressionList[Positon + 1]) == True: Calc = Roll((int(ExpressionList[Positon + 1]))) FinalList.append(str(Calc)) FinalSum += int(Calc) Positon += 1 else: return False else: return False Positon += 1 if Positon == len(ExpressionList) == Positon: break return FinalList, FinalSum #Core of the program def Main(Expression): Expression = str(Expression) Expression = AddSpaces(Expression) if Expression == False: return False Expression = Calc(Expression) return Expression
aa4893929f9d990243444fc4416637e7eeb6149d
SulyunLee/NFL_team_embedding
/src/generate_coach_features.py
8,510
3.5625
4
''' This script generates feature vectors for each coach in each season. ''' import pandas as pd import numpy as np import argparse from POSITION_ASSIGNMENT import * from tqdm import tqdm def total_years_NFL_feature(row, df): name = row.Name year = row.Year # extract the coach'es previous year seasons previous_NFL_seasons = df[(df.Name == name) & (df.NFL == 1)] if previous_NFL_seasons.shape[0] == 0: total_years_NFL = 0 else: year_list = [] for i, row in previous_NFL_seasons.iterrows(): year_list.extend(range(int(row.StartYear), int(row.EndYear)+1)) # only select the years before the current year year_list = [num for num in year_list if num < year] # count the number of years total_years_NFL = len(set(year_list)) return total_years_NFL def past_seasons_winning_features(row, record_df, win_result_df): name = row.Name year = row.Year # collect last 5 years of game records previous_5yr_NFL_seasons = record_df[(record_df.Name == name) & (record_df.Year < year) & (record_df.Year >= year-5)] if previous_5yr_NFL_seasons.shape[0] == 0: best_prev5yr_winperc, avg_prev5yr_winperc = 0, 0 else: # retrieve the game results (winning percentages) previous_5yr_NFL_seasons_results = previous_5yr_NFL_seasons.merge(win_result_df, how="left") # compute best and average winning percentages best_prev5yr_winperc = previous_5yr_NFL_seasons_results.Win_Percentage.max() avg_prev5yr_winperc = round(previous_5yr_NFL_seasons_results.Win_Percentage.mean(),3) return best_prev5yr_winperc, avg_prev5yr_winperc def position_name_features(row): position_id = row.final_position hier_num = row.final_hier_num # head coach indicator if position_id == "HC": HC = 1 else: HC = 0 # Coordinator indicator if hier_num == 2: Coord = 1 else: Coord = 0 return HC, Coord if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('-collab_type', '--collab_type', default='all', type=str, help="Collaboration type to consider when constructing collaboration networks ('NFL' or 'all' for both NFL and college coaching)") parser.add_argument('-hier', '--hier', default=False, type=bool, help="If node embeddings are learned based on the hierchical networks (mentorship)") parser.add_argument('-biased', '--biased', default=False, type=bool, help="If node embeddings are learned based on biased random walk") parser.add_argument('-prob', '--prob', type=int) parser.add_argument('-w', '--w', default=3, type=int, help="window size") args = parser.parse_args() collab_type = args.collab_type hier = args.hier biased = args.biased prob = args.prob w = args.w ################################################################# # Load datasets all_coaching_record_filename = "../datasets/all_coach_records_cleaned.csv" NFL_coach_record_filename = "../datasets/NFL_Coach_Data_final_position.csv" total_win_filename = "../datasets/Total_Win.csv" cumulative_node_embedding_filename = "../datasets/final_embedding/cumulative_collab_G_node_embedding_{}_hier{}_biased{}_selectionprob{}_w{}_df.csv".format(collab_type, hier, biased, prob, w) all_record_df = pd.read_csv(all_coaching_record_filename) NFL_record_df = pd.read_csv(NFL_coach_record_filename) total_win_df = pd.read_csv(total_win_filename) cumulative_node_embedding_df = pd.read_csv(cumulative_node_embedding_filename) ################################################################# # exclude interim head coaches NFL_coach_instances = NFL_record_df[NFL_record_df.final_position != "iHC"] NFL_coach_instances.reset_index(drop=True, inplace=True) # exclude coaches with no proper positions NFL_coach_instances = NFL_coach_instances[(NFL_coach_instances.final_position != -1) & (NFL_coach_instances.final_hier_num != -1)] NFL_coach_instances.reset_index(drop=True, inplace=True) # Include only 2002-2019 seasons NFL_coach_instances = NFL_coach_instances[(NFL_coach_instances.Year >= 2002) & (NFL_coach_instances.Year <= 2019)] NFL_coach_instances.reset_index(drop=True, inplace=True) print("Total number of NFL coach instances: {}".format(NFL_coach_instances.shape[0])) tqdm.pandas() # total win dataset modification print("Calculating winning percentages...") win_perc = total_win_df.Total_Win / 16 team_name_modified = total_win_df.Team + " (NFL)" total_win_df = total_win_df.assign(Win_Percentage = win_perc.round(3)) total_win_df = total_win_df.assign(Team = team_name_modified) ## Feature 1: Total years in NFL - print("Feature 1: Total years in NFL") total_years_NFL = NFL_coach_instances.progress_apply(total_years_NFL_feature, \ args=[all_record_df], axis=1) NFL_coach_instances = NFL_coach_instances.assign(TotalYearsInNFL = total_years_NFL) ## Feature 2: Winning percentage during the past 5 years as college or NFL coach print("Feature 2: Best winning percentage during the past 5 years in NFL") print("Feature 3: Average winning percentage during the past 5 years in NFL") best_prev5yr_winperc, avg_prev5yr_winperc = zip(*NFL_coach_instances.progress_apply(past_seasons_winning_features, args=[NFL_record_df, total_win_df], axis=1)) NFL_coach_instances = NFL_coach_instances.assign(Past5yrsWinningPerc_best = best_prev5yr_winperc) NFL_coach_instances = NFL_coach_instances.assign(Past5yrsWinningPerc_avg = avg_prev5yr_winperc) ## Feature 3: Position names (head coach or coordinator) print("Feature 4: Head coach") print("Feature 5: Coordinator") # distinguish head coaches by position ID because there is interim HC. HC, Coord = zip(*NFL_coach_instances.progress_apply(position_name_features, axis=1)) NFL_coach_instances = NFL_coach_instances.assign(HC=HC) NFL_coach_instances = NFL_coach_instances.assign(Coord=Coord) ## Feature 4: Node embedding (collaboration) # Node embedding that contains the collaboration information during the past seasons. # node embedding for predicting year t = average of embedding upto year t-2 # and yearly embedding at year t-1 print("Feature 6: Collaboration features (node embedding)") cumul_emb_columns = cumulative_node_embedding_df.columns[cumulative_node_embedding_df.columns.str.contains("cumul_emb")].tolist() coach_emb_features = np.zeros((NFL_coach_instances.shape[0], len(cumul_emb_columns))) no_node_emb_arr = np.zeros((NFL_coach_instances.shape[0])).astype(int) # if there is no node embedding for the corresponding coach for idx, row in tqdm(NFL_coach_instances.iterrows(), total=NFL_coach_instances.shape[0]): year = row.Year name = row.Name cumulative_emb = cumulative_node_embedding_df[(cumulative_node_embedding_df.Name==name) & (cumulative_node_embedding_df.Year==year)] cumulative_emb = np.array(cumulative_emb[cumul_emb_columns]) if cumulative_emb.shape[0] != 0: coach_emb_features[idx,:] = cumulative_emb else: no_node_emb_arr[idx] = 1 NFL_coach_instances = pd.concat([NFL_coach_instances, pd.DataFrame(coach_emb_features,\ index=NFL_coach_instances.index, columns=cumul_emb_columns)], axis=1) NFL_coach_instances = NFL_coach_instances.assign(no_node_emb=no_node_emb_arr) # check nodes with no embedding learned from Deepwalk on cumulative network until previous years. for hier_num in range(1, 4): print("Hier_num: {}".format(hier_num)) for year in range(2002, 2020): num_no_emb = NFL_coach_instances[(NFL_coach_instances.final_hier_num==hier_num) & (NFL_coach_instances.Year==year)].no_node_emb.sum() print(num_no_emb) no_node_emb_instances = NFL_coach_instances[NFL_coach_instances.no_node_emb==1] no_node_emb_instances.reset_index(drop=True, inplace=True) for idx, coach in no_node_emb_instances.iterrows(): year = coach.Year college_coaching_record = all_record_df[(all_record_df.StartYear<year) & (all_record_df.Name==coach.Name)] NFL_coach_instances.to_csv("../datasets/NFL_Coach_Data_with_features_collab{}_hier{}_biased{}_selectionprob{}_w{}.csv".format(collab_type, hier, biased, prob, w),\ index=False, encoding="utf-8-sig")
e96bdd44689ad5fa16340db1c7862568067bc50c
cyberchaud/cracking_wPython
/p_questions/chap01/c01q02.py
1,978
3.578125
4
# Cracking Codes with Python # Chapter 01 # Practice Set 01 # Rot(x) challenges import logging import sys import getopt logging.basicConfig(filename='chap01ques02.log', level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s') logging.debug('Start of question') def main(argv): cText = '' cRot = 0 try: logging.debug('Trying to get args') opts, args = getopt.getopt(argv, "hc:s:", ["ciphertext=", "shifts="]) except getopt.GetoptError: logging.debug('Invalid arguments') print('c01q01.py -c <ciphertext> -s <number of shifts>') logging.debug('Ending.') sys.exit(2) for opt, arg in opts: if opt == "-h": logging.debug('Help argument was passed. Displaying help') print('c01q01.py -c <ciphertext> -r <number of shifts>') logging.debug('Ending.') sys.exit() elif opt in ("-c", "--ciphertext="): cText = arg elif opt in ("-s", "--shifts"): cRot = int(arg) logging.debug('Decoding cipher text {} and rotating {} times'.format(cText, cRot)) print('The cipher text is: ', cText) print('The shifts is: ', cRot) print('The ciphertext is: ', decrypt(cText, cRot)) def encrypt(text, rotation): result = '' for i in text: if i.isalpha(): if i.isupper(): result += chr((ord(i) + rotation - 65) % 26 + 65) else: result += chr((ord(i) + rotation - 97) % 26 + 97) else: result += chr((ord(i))) return result def decrypt(text, rotation): result = '' for i in text: if i.isalpha(): if i.isupper(): result += chr((ord(i) - rotation - 65) % 26 + 65) else: result += chr((ord(i) - rotation - 97) % 26 + 97) else: result += chr((ord(i))) return result if __name__ == "__main__": main(sys.argv[1:])
3c7bd1ff86bee9bbe2e3e7a74a8dbb733de10cf4
chinkushah/PyAcademy
/PyAcacdemy.py
38,491
4.15625
4
import math print("Welcome to Py Academy") for ch in range(1,100): what_subject = input("What subject may I help you with today?(Math/Physics/Chemistry) ") if what_subject == "math" or what_subject == "Math" or what_subject == "mathematics" or what_subject == "Mathematics": what_chap = input("What chapter may I help you with?(Progressions/Straight Lines(sl)/ Calculus)") if what_chap == "progressions" or what_chap == "Progressions": print("The topics involved along with their formulae are:") print('''For any Arithmetic Progression; a = first term of an AP, d = common difference of an AP nth term of an AP: a + (n-1)d Sum of n terms of an AP: n/2[2a + (n-1)d] Arithmetic Mean of two numbers 'a' and 'b'; AM = [a+b]/2 d = [b-a]/[n+1] For any Geometric Progression; a = first term of a GP, r = common ratio of GP nth term of a GP: ar^(n-1) Sum of n terms of GP: [a(r^n - 1)]/r-1 Geometric Mean of two numbers 'a' and 'b'; GM = (ab)^[1/2] r = (b/a)^[1/n+1]''') more_help=input("Do you need further assistance?(Yes/No) ") if more_help == "yes" or more_help == "Yes": ProgOrMean = (input("Do you want to find AM/GM or nth term/sum or insertion of AM/GM(ins)? ")) if ProgOrMean == "nth term/sum" or ProgOrMean == "nth term/Sum": first_term = input("Enter First Term of the Progression: ") first_term = float(first_term) is_ap_or_gp = input("Is the Progression AP or GP?") is_ap_or_gp = str(is_ap_or_gp) if is_ap_or_gp == "AP" or is_ap_or_gp == "ap": common_difference = input("Enter Common Difference:") common_difference = float(common_difference) term = input("Enter the Term:") term = int(term) find_nth_term_or_sum = input("Do You Want to Find nth term or sum? ") find_nth_term_or_sum = str(find_nth_term_or_sum) if find_nth_term_or_sum == "nth term" or find_nth_term_or_sum == "nth Term": nth_term = first_term + ((term - 1) * common_difference) print("the nth Term is", nth_term) elif find_nth_term_or_sum == "sum" or find_nth_term_or_sum == "Sum": Sum = (term/2)*((2*first_term) + ((term-1)*common_difference)) print("The Sum is", Sum) else: common_ratio = input("Enter Common Ratio of GP:" ) common_ratio = float(common_ratio) term = input("Enter nth Term of GP:") term = int(term) find_nth_term_or_sum = input("Do You Want to Find nth term or sum?") if find_nth_term_or_sum == "nth term" or find_nth_term_or_sum == "nth Term": nth_term = round(((first_term)*((common_ratio)**(term-1)),2)) print("The nth Term is", nth_term) elif find_nth_term_or_sum == "sum" or find_nth_term_or_sum == "Sum": Sum = ((first_term*(1-common_ratio**term))/(1-common_ratio)) print("The Sum is", Sum) elif ProgOrMean == "AM/GM" or ProgOrMean == "am/gm": AM_GM = input("Do you want to find AM or GM?") if AM_GM == "AM" or AM_GM == "am": term_one = int(input("Enter one term:")) term_two = int(input("Enter second term:")) AM = (term_one + term_two)/2 print("The AM is",AM) else: term_one = int(input("Enter one term:")) term_two = int(input("Enter second term:")) GM = (term_one*term_two)**(1/2) print("The GM is",GM) else: AMorGM = input("Insertion of AMs or GMs?") if AMorGM == "AM" or AMorGM == "AMs": a = int(input("Enter first term: ")) b = int(input("Enter last term: ")) n = int(input("Enter the number of terms you want to enter: ")) d = (b-a)/(n+1) series = 0 print("The AP thus formed is") for ch in range(0,n+2): Series = a + (d*ch) print(Series) else: a = int(input("Enter first term: ")) b = int(input("Enter last term: ")) n = int(input("Enter the number of terms you want to insert: ")) r = (b/a)**(1/(n+1)) series = 1 print("The GP thus formed is") for ch in range(0,n+2): Series = a*(r**ch) print(Series) elif what_chap == 'straight lines' or what_chap == 'sl': print('''The topics involved along with their formulae are: General equation of a line is ax + by + c = 0. If equation of a line is of the form y = mx+c, then m is the slope of the line. Slope of a line given two points (a,b) and (c,d); (d-b)/(c-a) = (y-b)/(x-a). Angle(A) between two lines with slopes m and M ; tanA = (M-m)/(1+mM).''') more_help = input("Do you need further assistance?") if more_help == "yes" or more_help == "Yes": dist = input("Do you want to find the distance of a point from a line?") if dist == "yes" or dist == "Yes": y_coordinate = float(input("Enter y-coordinate of the point:")) x_coordinate = float(input("Enter x-coordinate of the point:")) coeff_y = float(input("Enter coefficient of y from the equation of the line:")) coeff_x = float(input("Enter coefficient of x from the equation of the line:")) constant = float(input("Enter constant term from the equation of the line:")) distance = round((y_coordinate*coeff_y + x_coordinate*coeff_x + constant)/((coeff_x**2) + (coeff_y**2))**(1/2),2) print("The perpendicular distance of the point from the line is",distance) else: coordinates_given = input("Are the coordinates of line given?") if coordinates_given == "yes" or coordinates_given == "Yes": y1 = float(input("Enter first y-coordinate:")) y2 = float(input("Enter second y-coordinate:")) x1 = float(input("Enter first x-coordinate:")) x2 = float(input("Enter second x-coordinate:")) slope = ((y2-y1)/(x2-x1)) print("The slope of the line is",slope) y_diff = y2-y1 x_diff = x1-x2 constant = (x1*(y1-y2) + y1*(x2-x1)) angle = round(math.degrees(math.atan(slope)),2) print("The angle made by the line with the x-axis is",angle,"degrees") print("The equation of the line is",y_diff,"x +",x_diff,"y" "+",constant,"= 0") from matplotlib import pyplot as plt plt.plot([x1,x2],[y1,y2]) plt.show() else: slope = float(input("Enter slope of the line:")) y_int = float(input("Enter y-intercept of the line:")) print("The equation of the line is y =", slope,"x +", y_int) from matplotlib import pyplot as plt plt.plot([0,(-y_int/slope)],[y_int,0]) plt.show() elif what_chap == 'c' or what_chap == 'Calculus': from sympy import * import matplotlib.pyplot as plt x = Symbol('x') y = Symbol('y') calc = input("Do you want to differentiate or integrate a function? (diff/int)") if calc == 'diff': f = input("Enter function to be differentiated :") print(diff(f,x)) else: f = input("Enter function to be integrated :") print(integrate(f,x)) continue elif what_subject == "physics" or what_subject == "Physics": what_chap = input("What chapter do you need help with, Projectile Motion(pm) or Circular Motion(cm)? ") if what_chap == "projectile motion" or what_chap == "Projectile Motion" or what_chap == "Projectile motion" or what_chap == "pm": x = float(input("Enter Initial Velocity(m/s):")) t = float(input("Enter Angle of Projection(degrees):")) y = math.radians(t) time_of_flight = ((x*(math.sin(y)))/5) print("Time of Flight is",time_of_flight,"seconds") horizontal_range = (((x**2)*(math.cos(y))*(math.sin(y)))/5) print("Horizontal Range of the Projectile is",horizontal_range,"meters") maximum_height = (((x**2)*((math.sin(y)**2)))/20) print("Maximum Height of the Projectile is",maximum_height,"meters") coeff_x = (5/(x*math.cos(y))**2) eqn = ('y =',math.tan(y),'x -',coeff_x,'x^2') print("The equation of the projectile is") print('y =',math.tan(y),'x -',coeff_x,'x^2') elif what_chap == "Circular Motion" or what_chap == "circular motion" or what_chap == "cm": find = input("What do you want to find, Angular Velocity(av), Angular Acceleration(aa)? ") if find == "angular velocity" or find == "Angular Velocity" or find == "av": accn_giv = input("Is the angular acceleration given?") if accn_giv == "Yes" or accn_giv == "yes": ang_accn = float(input("Enter the angular acceleration(in rad/s^2):")) ang_disp = float(input("Enter the angular displacement(in rad):")) ang_vel = (2*ang_accn*ang_disp)**(1/2) print("The angular velocity is",ang_vel,"rad/s") else: cent_accn = input("Is the centripetal acceleration given?") if cent_accn == "yes" or cent_accn == "Yes": cent_accn == float(input("Enter the centripetal acceleration(in m/s^2):")) radius = float(input("Enter the radius of circular motion(in m):")) vel = (cent_accn*radius)**(1/2) ang_vel = (vel/radius) print("The angular velocity is",ang_vel,"rad/s") else: lin_accn = float(input("Enter the linear acceleration(in m/s^2):")) radius = float(input("Enter the radius of circular motion(in m):")) ang_disp = float(input("Enter the angular displacement(in rad):")) ang_accn = lin_accn/radius ang_vel = (2*ang_accn*ang_disp)**(1/2) print("The angular velocity is",ang_vel,"rad/s") elif find == "angular acceleration" or find == "Angular Acceleration" or find == "aa": ang_vel = input("Is the angular velocity given?") if ang_vel == "Yes" or ang_vel == "yes": ang_vel = float(input("Enter the angular velocity(in rad/s):")) ang_disp = float(input("Enter the angular displacement(in rad):")) ang_accn = (ang_vel/(2*ang_disp)) else: cent_accn = input("Is the centripetal acceleration given?") if cent_accn == "Yes" or cent_accn == "yes": cent_accn = float(input("Enter the centripetal acceleration(in m/s):")) accn = float(input("Enter net acceleration(in m/s^2):")) ang_accn = ((accn**2)-(cent_accn**2))**(1/2) print("The angular acceleration is",ang_accn) elif what_subject == "Chemistry" or what_subject == "chemistry": import pandas as pd df = pd.read_csv("") #ENTER 'PERIODIC TABLE OF ELEMENTS.csv' FILE LOCATION IN THE QUOTES TO THE LEFT df = pd.DataFrame(df) df["MassNumber"] = df["NumberofNeutrons"] + df["NumberofProtons"] df_atno = df.set_index("AtomicNumber") df_atmass = df.set_index("AtomicMass") df_massno = df.set_index("MassNumber") chem_chp = input("Which chapter do you need help with? Mole Concepts (mc) or Atomic Structure (as): ") if chem_chp == "Mole concepts" or chem_chp == "mole concepts" or chem_chp == "Mole Concepts" or chem_chp == "mc": print('''Here are some helpful formulae of this chapter: No. of moles: n = (Given mass)/(Molar mass) = (No. of particles)/Na _Where Na is Avogadros's Nomber. = (Vol. of gas at STP)/(22.4l) Average Atomic Mass of Elements having different isotopes: Mavg= (M1a1 + M2a2 + M3a3..Mnan)/(a1 + a2 + a3...+an) _where a is percentage of abundance of isotope. Mass percent of an element = (mass of that element in compound*100)/(mass of compound) Vapour density: (Molar Mass of gas)/2 Molarity: M = (moles of solute)/(volume of solution) Molality: m = (moles of solute)/(mass of solvent)Z Mole fraction: Of solute A (XA) = nA/(nA + nB) , Of solvent B (XB) = nB/(nA + nB)''') mole_concept_notes = input("Do you require any further assisstance? ") if mole_concept_notes == "Yes" or mole_concept_notes == "yes": help_mole_concept = input("What do you need help with? Mass Percent (mp) , Molarity , Molality , Empirical Formula (ef) ") if help_mole_concept == "Mass Percent" or help_mole_concept == "mass percent" or help_mole_concept == "mp": totalMass = 0 elements = int(input("How many elements are present in the compound?")) for mass in range(1,elements + 1): Atmass = input("Enter the element:") atomicMass = float(df_atmass[df_atmass["Symbol"] == Atmass].index.values) NumMolecule = int(input("Enter the number of atoms of the particular element: ")) mass = atomicMass * NumMolecule totalMass += mass print("The mass of this compound is",totalMass) Element = input("Which element's mass percent would you like to find? ") moles = float(input("Give number of atoms of element: ")) Mass = float(df_atmass[df_atmass["Symbol"] == Element].index.values*moles) print("Mass of element is atomic mass*moles = ", Mass) print("Mass Percent of the element is: ", Mass*100/totalMass) elif help_mole_concept == "Molarity" or help_mole_concept == "molarity": moles = float(input("Give moles of element: ")) vol = float(input("Give volume of solution: ")) print("Molarity =", moles/vol ) elif help_mole_concept == "Molality" or help_mole_concept == "molality": moles = float(input("Give moles of element: ")) mass = float(input("Give mass of solvent in kg: ")) print("Molality= ", moles/mass) elif help_mole_concept == "Empirical Formula" or help_mole_concept == "empirical formula" or help_mole_concept == "ef": totalMass = 0 elements = int(input("How many elements are present in the compound?")) if elements == 3: ele1 = input("Enter the element: ") per1 = float(input("Percentage of this element: ")) ele2 = input("Enter the element: ") per2 = float(input("Percentage of this element: ")) ele3 = input("Enter the element: ") per3 = float(input("Percentage of this element: ")) mol1 = per1/float(df_atmass[df_atmass["Symbol"] == ele1].index.values) mol2 = per2/float(df_atmass[df_atmass["Symbol"] == ele2].index.values) mol3 = per3/float(df_atmass[df_atmass["Symbol"] == ele3].index.values) if mol1<mol2 and mol1<mol3: Mol1 = round(mol1/mol1) Mol2 = round(mol2/mol1) Mol3 = round(mol3/mol1) print("The empirical formula is",ele1,ele2,Mol2,ele3,Mol3) elif mol2<mol1 and mol2<mol3: Mol1 = round(mol1/mol2) Mol2 = 1 Mol3 = round(mol3/mol2) print("The empirical formula is",ele1,Mol1,ele2,ele3,Mol3) else: Mol1 = round(mol1/mol3) Mol2 = round(mol2/mol3) Mol3 = 1 print("The empirical formula is",ele1,Mol1,ele2,Mol2,ele3) mass_emp = (float(df_atmass[df_atmass["Symbol"] == ele1].index.values*Mol1) + float(df_atmass[df_atmass["Symbol"] == ele2].index.values*Mol2) + float(df_atmass[df_atmass["Symbol"] == ele3].index.values*Mol3)) emp_form = ele1,Mol1,ele2,Mol2,ele3,Mol3 else: ele1 = input("Enter the element: ") per1 = float(input("Percentage of this element: ")) ele2 = input("Enter the element: ") per2 = float(input("Percentage of this element: ")) mol1 = per1/float(df_atmass[df_atmass["Symbol"] == ele1].index.values) mol2 = per2/float(df_atmass[df_atmass["Symbol"] == ele2].index.values) if mol1<mol2: Mol2 = round(mol2/mol1) Mol1 = 1 print("The emperical formula is", ele1,ele2,Mol2) else: Mol1 = round(mol1/mol2) Mol2 = 1 print("The emperical formula is",ele1,Mol1,ele2) mass_emp = float((df_atmass[df_atmass["Symbol"] == df_atmass[df_atmass["Symbol"] == ele1].index.values].index.values*Mol1) + (df_atmass[df_atmass["Symbol"] == ele2].index.values*Mol2)) emp_form = ele1,Mol1,ele2,Mol2 giv_mass = float(input("Enter given mass of compound: ")) ratio = giv_mass/mass_emp print("The molecular formula of the compound is ",emp_form,ratio) elif chem_chp == "Atomic Structure" or chem_chp == "as": h = 6.626*(10**-34) c = 3*(10**8) Na = 6.022*(10**23) Me = 9.11*(10**-31) Mp = 1.67*(10**-27) Mn = 1.67*(10**-27) pi = 3.14 Help_atm = input("What do you need help with? Mass number (mn) , Wavelength , Frequency , Energy of photons (ep) , No. of photons emitted (npe) , KE of electron (ke) , Frequency of raditations emitted (fre) , Angular momentum of electron (ame) , Energy of sinlge electron species (esep) , Radius of single electron species (rsep) , Wavelength using de Broglie's equation (wdb), Mass using de Broglie's equation (mdb), Uncertainty in measurement (um) , Orbitals: ") if Help_atm == "Mass number" or Help_atm == "mass number" or Help_atm == "mn": print("Mass number is the sum of number of neutrons and number of protons") Massno = input('Enter the element of which you wish to find mass number:') mass_number = int(df_massno[df_massno["Symbol"] == Massno].index.values) print("Mass number is", mass_number) elif Help_atm == "Wavelength" or Help_atm == "wavelength": print("Wavelength w = c/v where c = speed of electromagnetic radiation in vacuum, v = frequency") frequency = float(input("Enter frequency(in Hz): ")) Wavelength = c/frequency print("Wavelength is", Wavelength,"m") elif Help_atm == "frequency" or Help_atm == "Frequency": print("Frequency v = c/w where c = speed of electromagnetic radiation in vacuum, w = wavelength.") w = float(input("Enter wavelength(in nm)")) frequency = c/(w*(10**-9)) print("Frequency is", frequency,"Hz") elif Help_atm == "Energy of photon" or Help_atm == "energy of photon" or Help_atm == "ep": print("Energy E = hv where h = Planck'constant, v = frequency") v = float(input("Enter frequency(in Hz): ")) E = h*v print("Energy of 1 photon is", E,"J") print("Energy of 1 mole of photons is", Na*E) elif Help_atm == "No. of photons emitted" or Help_atm == "no. of photons emitted" or Help_atm == "npe": print("No. of photons emitted = Power of bulb/Energy of photon") P = float(input("Enter power of bulb(in Watt): ")) print("Energy of photon = h*v = (h*c)/w where h = planck's constant, c =speed of electromagnetic radiation in vacuum, w = wavelength. ") given = input("Is frequency given or wavelength given?") if given == "frequency" or given == "Frequency": v = float(input("Enter frequency(in Hz): ")) E = h*v print("Energy of photon is", E,"J") NPE = P/E print("No. of photons emitted is", NPE) else: w = float(input("Enter wavelength: ")) E = (h*c)/(w*(10**-9)) print("Energy of photon is", E) NPE = P/E print("No. of photons emitted is", NPE) elif Help_atm == "KE of electron" or Help_atm == "ke": print("KE of electron = mass of electron/ (frequency**2) = h(v-vo) where h = Planck's constant, v = frequency, vo = threshold frequency") v = float(input("Enter frequency: ")) vo = float(input("Enter threshold frequency of metal: ")) KE =h*(v-vo) print("Kinetic energy of electron is", KE) elif Help_atm == "Frequency of radiation emitted" or Help_atm == "frequency of radiation emitted" or Help_atm == "fre": print("Frequency of radiation emitted = difference in energy/Planck's constant ") fe = float(input("Enter final energy: ")) ie = float(input("Enter initial energy: ")) energy_diff = fe-ie fore = energy_diff/h print("Frequency of radiation emitted or absorbed is", fore) elif Help_atm == "Angular momentum of electron" or Help_atm == "angular momentum of electron" or Help_atm == "ame": print("Angular momentum of momentum = nh/2pi where n is the principal quantum number") n = int(input("Enter principal quantum number: ")) AM = (n*h)/(2*pi) print("Angular momentum of electron is", AM) elif Help_atm == "Energy of single electron species" or Help_atm == "energy of single electron species" or Help_atm == "esep": print("Energies are given by this expression: En = -2.18 x 10**-18*(Z**2/n**2) where z = atomic number , n is principal quantum no.") Z = int(input("Enter atomic number of element: ")) n = int(input("Enter the principal quantum number: ")) En = -2.18*(10**-18)*(Z**2/n**2) print("Energy of single electron species is", En) elif Help_atm == "Radius of single electron species" or Help_atm == "radius of single electron species " or Help_atm == "rsep": print("Expression: Rn = 52.9*((Z**2)/n") Z = int(input("Enter atomic number of element: ")) n = int(input("Enter the principal quantum number: ")) Rn = 52.9*((Z**2)/n) print("Radius of single electron species is", Rn) elif Help_atm == "Wavelength using de Broglie's equation" or Help_atm == "wavelength using de Broglie's equation" or Help_atm == "wdb": print("Expression: w = h/(m*v) = h/p where m is mass of particle, h is Planck's equation and v is frequency") m = float(input("Enter mass of particle: ")) v = float(input("Enter frequency of particle: ")) w = h/(m*v) print("Wavelength of particle is", w) elif Help_atm == "Mass using de Broglie's equation" or Help_atm == "mass using de Broglie's equation" or Help_atm == "mdb": print("Expression: m = h/(v*w) where w is wavelength of particle, v is frequency and h is Planck's constant" ) v = float(input("Enter frequency of particle: ")) w = float(input("Enter wavelength of particle: ")) m = h/(v*w) print("Mass of particle is", m) elif Help_atm == "Uncertainty in measurement" or Help_atm == "uncertainty in measurement" or Help_atm == "um": print("According to Heisenberg's Uncertainty Principle: x*p = h/(4*pi*m) where x is uncertainty in postition and p is uncertainty in momentum") xorp = input("What do you want to find the uncertainty of? ") if xorp == "x": m = float(input("Enter mass of particle: ")) p = float(input("Enter uncertainty in momentum: ")) x = h/(4*pi*m*p) print("Uncertainty in position is", x) else: m = float(input("Enter mass of particle: ")) x = float(input("Enter uncertainty in position: ")) p = h/(4*pi*m*x) print("Uncertainty in momentum is", p) elif Help_atm == "Orbitals" or Help_atm == "orbitals": n = int(input("Enter principal quantum number: ")) l = int(input("Enter Azimuthal quantum number: ")) if l == 0: print("Orbital is {}s".format(n)) elif l == 1: print("Orbital is {}p".format(n)) elif l == 2: print("Orbital is {}d".format(n)) elif l == 3: print("Orbital is {}f".format(n)) else: print("Please enter valid subject.") quiz = input("Would you like to take a small test based on what you have learnt? (y/n)") if quiz == "y" or quiz == "yes" or quiz == "Y": sub = input("What subject do you want to take the quiz on? (P/C/M)") if sub == "M" or sub == "m" or sub == "math": import random chp = input("What Math chapter would you like to take a test for: Progressions (pr) or Straight lines(sl): ") #IDHAR PROGRESSIONS if chp == "Progressions" or chp == "progressions" or chp == "pr": num = random.randint(1,2) if num == 1: print("Q1) The 4 arithmetic means between 3 and 23 are: ") print("A) 5,9,11,13") print("B) 7,11,15,19") print("C) 5,11,15,22") print("D) 7,15,19,21") ans = input("Enter correct option: ") if ans == "B": print("Correct") else: print("Incorrect") print() print("Q2) The GM of the numbers 3,(3^2),(3^3),...(3^n) is: ") print("A) 3^(2/n)") print("B) 3^((n+1)/2)") print("C) 3^(n/2)") print("D) 3^((n-1)/2)") ans = input("Enter correct option: ") if ans == "B": print("Correct") else: print("Incorrect") else: print("Q1) The nth term of the series 3+10+17+... and 63+65+67+... are equal, then the value of n is?") print("A) 11") print("B) 12") print("C) 13") print("D) 15") ans = input("Enter correct option: ") if ans == "C": print("Correct") else: print("Incorrect") print() print("Q2) The sum of few terms of any GP is 728, if common ratio is 3 and last term is 486, then first term of series will be?") print("A) 2") print("B) 1") print("C) 3") print("D) 4") ans = input("Enter correct option: ") if ans == "A": print("Correct") else: print("Incorrect") #IDHAR SE STRAIGHT LINES elif chp == "Straight lines" or chp == "sl" or chp == "straight lines": print("Q1) The equation of the line perpenicular to the line x/a - y/b = 1 and passing through the point at which it cuts x axis, is?") print("A) x/a + y/b + a/b = 0") print("B) x/b + y/a = b/a") print("C) x/b + y/a = 0") print("D) x/b + y/a = a/b") ans = input("Enter correct option: ") if ans == "A": print("Correct") else: print("Incorrect") print("Q2) Find the distance of the point (1,-1) from the line 12(x+6) = 5(y-2).") print("A) 4units") print("B) 8units") print("C) 6units") print("D) 5units") ans = input("Enter correct option: ") if ans == "D": print("Correct") else: print("Incorrect") else: print("Enter valid chapter") elif sub == "P" or sub == "p" or sub == "physics": chp = input("What physics chapter would you like to take the quiz for: Projectile Motion(pm) or Circular Motion(cm)?") if chp == "Projectile Motion" or chp == "pm": import random from PIL import Image num = random.randint(1,2) if num == 1: print('''Question 1. A particle is projected at an angle 37 deg with the incline plane in upward direction with speed 10 m/s. The angle of inclination of plane is 53 deg. Then the maximum distance from the incline plane attained by the particle will be: A)3m B)4m C)5m D)0m''') ans1 = input('Enter answer:') if ans1 == 'A': print("Good job! That's the correct answer!") else: print('''That answer is incorrect.''') print('''Question 2. It was calculated that a shell when fired from a gun with a certain velocity and at an angle of elevation 5pi/36 rad should strike a given target in same horizontal plane. In actual practice, it was found that a hill just prevented the trajectory. At what angle of elevation should the gun be fired to hit the target: A)5pi/36 rad B)11pi/36 rad C)7pi/36 rad D)13pi/36 rad''') ans2 = input('Enter answer:') if ans2 == 'D': print("Good job that's the correct answer") else: print("Incorrect") else: print('''Question 1. A point mass is projected, making an acute angle with the horizontal. If the angle between velocity vector and acceleration vector g is theta at any time t during the motion, then theta is given by: A)0 < theta < 90 B)theta = 90 C)theta < 90 D)0 < theta < 180''') ans3 = input("Enter answer:") if ans3 == 'D': print("Good job! That's the correct answer.") else: print("Incorrect") print('''Question 2. What is the maximum speed of oblique projectile from the ground in the vertical plane passing through a point (30m,40m) and projection point is taken as the origin (g = 10 m/s^2): A)30 m/s B)20m/s C)10root5 m/s D)50 m/s''') ans4 = input("Enter answer:") if ans4 == "A": print("Good job! That answer's correct!") else: print("Incorrect") else: import random from PIL import Image num = random.randint(1,2) if num == 1: print('''Question 1. The maximum velocity with which a car driver must traverse a flat curve of radius 150m, coeff of friction 0.6 to avoid skidding A)60 m/s B)30 m/s C)15 m/s D)25 m/s''' ) ans5 = input("Enter your answer:") if ans5 == "B": print("Good job! That's the correct answer!") else: print("Incorrect") print('''Question 2. A wheel is at rest. Its angular velocity increases uniformly and becomes 80 rad/s after 5 sec. Total angular displacement is: A)800 rad B)400 rad C)200 rad D)100 rad''') ans6 = input("Enter your answer:") if ans6 == 'C': print("Good job! That's the correct answer!") else: print("Incorrect") else: print('''Question 1. A particle moves along a circle of radius 20/pi m with constant tangential acceleration. If the speed of particle is 80 m/s at the end of the second revolution after the motion has begun, find tangential acceleration: A)160pi m/s^2 B)40pi m/s^2 C)40 m/s^2 D)640pi m/s^2''') ans7 = input("Enter your answer:") if ans7 == "C": print("Good job! That's the correct answer!") else: print("Incorrect") print('''Question 2. A bucket's whirled in a vertical circle with a string. The water in bucket doesn't fall even when bucket's inverted at top of its path. In this position: A)mg = mv^2/r B)mg is greater than mv^2/r C)mg is not greater than mv^2/r D)mg is not less than mv^2/r''') ans8 = input("Enter your answer:") if ans8 == "C": print("Good job! That's the correct answer!") else: print("Incorrect") elif sub == "C" or sub == "c" or sub == "chemistry": import random chp = input("What Chemistry chapter would you like to take the quiz for: Mole Concept (mc) or Atomic Structure (as)?") if chp == "mc" or chp == "Mole Concept" or "mole concept": num = random.randint(1,2) if num == 1: print("Q1) Calculate the molarity of NaOH in the solution prepared by dissolving its 4 gms in enough water to form 250mL of the solution.") print("A) 0.3M") print("B) 4M") print("C) 0.4M") print("D) 3M") ans = input("Enter correct option: ") if ans == "C": print("Correct") else: print("Incorrect") print() print("Q2) An organic compound contains 49.3% Carbon, 6.84% Hydrogen and its vapour density is 73. Molecular formula of compound is:") print("A) C3H5O2") print("B) C6H10O4") print("C) C3H10O2") print("D) C4H10O4") ans = input("Enter correct option: ") if ans == "B": print("Correct") else: print("Incorrect") else: print("Q1) The mole fraction of NaCl in a soltuion containing 1 mole of NaCl in 1000g of Water is: ") print("A) 0.0177") print("B) 0.001") print("C) 0.5") print("D) 1.5") ans = input("Enter correct option: ") if ans == "A": print("Correct") else: print("Incorrect") print() print("Q2) A sample of clay was partially dried and then it contained 50% silica and 7% water. The original clay contained 12% water. Find the % of silica in the original sample.") print("A) 52.7%") print("B) 50%") print("C) 43%") print("D) 47.3%") ans = input("Enter correct option: ") if ans == "D": print("Correct") else: print("Incorrect") elif chp == "as" or chp == "atomic structure" or chp == "Atomic Structure": num = random.randint(1,2) if num == 1: print("Q1) The energy of hydrogen atom in its ground state is -13.6eV. The energy of the level corresponding to n=5 is:") print("A) -0.54eV") print("B) -5.40eV") print("C) -0.85eV") print("D) -2.72eV") ans = input("Enter correct option: ") if ans == "A": print("Correct") else: print("Incorrect") print() print("Q2) de-Broglie wavelength of electron in second orbit of Li2+ ion will be equal to de-Broglie of wavelength of electron in:") print("A) n=3 of H-atom") print("B) n=4 of C5+ atom") print("C) n=6 of Be3+ atom") print("D) n=3 of He+ atom") ans = input("Enter correct option: ") if ans == "B": print("Correct") else: print("Incorrect") else: print("Q1 The frequency of yellow light having wavelength 600nm is:") print("A) 5 x 10^14 Hz") print("B) 2.5 x 10^7 Hz") print("C) 5 x 10^7 Hz") print("D) 2.5 x 10^14 Hz") ans = input("Enter correct option: ") if ans == "A": print("Correct") else: print("Incorrect") print() print("Q2) The uncertainty in the moment of an electron is 1 x 10^-5 kgm/s. The uncertainty in its position will be: (h = 6.626 x 10^-34Js)") print("A) 1.05 x 10^-28 m") print("B) 1.05 x 10^-26 m") print("C) 5.27 x 10^-30 m") print("D) 5.25 x 10^-28 m") ans = input("Enter correct option: ") if ans == "C": print("Correct") else: print("Incorrect") else: print("Enter valid chapter") else: print("Enter valid subject") else: print("Happy learning!")
fc44fe6794164926a2bc428e5fde1725ac1463f1
karthikjosyula/GrokkingAlgorithms
/GrokkingAlgorithms/BreadthFirstSearch.py
1,157
3.609375
4
#Hash table to store the friends of 1st connection friends and friends of second connection friends and so on... friendshash = {} friendshash['karthik'] = ['nani','shravan','rafi','phani'] friendshash['nani'] = ['kishore','kranthi','jaideep','joe','videesh'] friendshash['shravan'] = [] friendshash['rafi'] = ['kishore','ravi'] friendshash['phani'] = ['hari'] friendshash['kishore'] = ['tittu'] friendshash['kranthi'] = [] friendshash['jaideep'] = [] friendshash['joe'] = [] friendshash['videesh'] = [] friendshash['tittu'] = [] friendshash['ravi'] = [] friendshash['hari'] = [] #load the names of frinends into a queue. import deque, append the hashtable keys of a given value to queue from collections import deque search_queue = deque() search_queue += friendshash['karthik'] #creating an array with names who own a bike bikeowners = ['tittu','hari'] searched = [] #breadth first search while search_queue: friend = search_queue.popleft() if friend in bikeowners and not friend in searched: print(friend + " is the closest bike owner") break else: search_queue += friendshash[friend] searched.append(friend)
ecfd202a86c64669565f43c3b6cfb7302ef567db
neha-sharmaa/python-practice
/celcius_farh.py
143
3.671875
4
def temprature(frah): return (frah * (5/9)) -32 temp = temprature(100) print(str(temp)) print('hi', end=" ") print('hello', end=" ")
482bb73b3b666c1a659db534c46bec792027039f
loveclj/DesignPatterns
/python/factory.py
1,537
3.765625
4
__author__ = 'lizhifeng' class Pizza: def cook(self): pass def cut(self): pass def get(self): pass class CherryPizza(Pizza): def cook(self): print "cook cherry pizza" def cut(self): print "cut cherry pizza" def get(self): self.cook() self.cut() class ApplePizza(Pizza): def cook(self): print "cook apple pizza" def cut(self): print "cut apple pizza" def get(self): self.cook() self.cut() class PorkPizza(Pizza): def cook(self): print "cook pork pizza" def cut(self): print "cut pork pizza" def get(self): self.cook() self.cut() class BeefPizza(Pizza): def cook(self): print "cook beef pizza" def cut(self): print "cut beef pizza" def get(self): self.cook() self.cut() class PizzaStor: def orderPizza(self, name): pass class MeatPizzaStore(PizzaStor): def orderPizza(self, name): if( name == "pork"): self.pizza = PorkPizza() if( name == "beef"): self.pizza = BeefPizza() return self.pizza class FruitPizzaStore(PizzaStor): def orderPizza(self, name): if( name == "cherry"): self.pizza = CherryPizza() if( name == "apple"): self.pizza = ApplePizza() return self.pizza if __name__ == "__main__": storeA = FruitPizzaStore() pizzaA = storeA.orderPizza("apple") pizzaA.get()
c233acbdce355b5fbcc49ab93bdc3d07ad1268f7
GerbendH/Advent_of_Code_2020
/Day 2/main.py
1,699
3.59375
4
class Password: def __init__(self, pw): self.pw_split = pw.split(' ') self.pw_string = '' self.policy_min = 0 self.policy_max = 0 self.policy_key = '' self.get_data() def get_data(self): policy_min_max = self.pw_split[0].split('-') self.policy_min = int(policy_min_max[0]) self.policy_max = int(policy_min_max[1]) self.policy_key = self.pw_split[1][0] self.pw_string = self.pw_split[2] def check_password_sled(self): if self.policy_min <= self.pw_string.count(self.policy_key) <= self.policy_max: return True else: return False def check_password_toboggan(self): if self.pw_string[(self.policy_min - 1)] == self.policy_key: if self.pw_string[(self.policy_max - 1)] == self.policy_key: return False else: return True else: if self.pw_string[(self.policy_max - 1)] == self.policy_key: return True else: return False def get_passwords(file): with open(file) as password_file: passwords = password_file.readlines() return passwords def check_passwords(): file = "input.txt" valid_password_count = 0 passwords = get_passwords(file) for password in passwords: current_password = Password(password.strip()) password_check = current_password.check_password_toboggan() if password_check: valid_password_count += 1 print(valid_password_count) # Press the green button in the gutter to run the script. if __name__ == '__main__': check_passwords()
ebe884b4a19212d3e4c59e636c2601f063c98f54
armaan2k/Training-Exercises
/DataStructuresAndAlgorithms/Queues/QueueLinkedList.py
1,155
3.734375
4
class _Node: __slots__ = '_element','_next' def __init__(self,element,next): self._element = element self._next = next class QueueLinkedList: def __init__(self): self._front = None self._rear = None self._size = 0 def __len__(self): return self._size def isempty(self): return self._size == 0 def enqueue(self,e): newest = _Node(e,None) if self.isempty(): self._front = newest else: self._rear._next = newest self._rear = newest self._size +=1 def dequeue(self): if self.isempty(): print('Queue is empty') return e = self._front._element self._front = self._front._next self._size -= 1 if self.isempty(): self._rear = None return e def first(self): if self.isempty(): print('Queue is empty') return return self._front._element def display(self): p = self._front while p: print(p._element,end=" ") p = p._next print()
531830eeb79bee0822b719d6dddf718f0e879764
uma-c/CodingProblemSolving
/back_tracking/target_sum_symbols.py
2,839
4.28125
4
''' You are given a list of non-negative integers, a1, a2, ..., an, and a target, S. Now you have 2 symbols + and -. For each integer, you should choose one from + and - as its new symbol. Find out how many ways to assign symbols to make sum of integers equal to target S. Example 1: Input: nums is [1, 1, 1, 1, 1], S is 3. Output: 5 Explanation: -1+1+1+1+1 = 3 +1-1+1+1+1 = 3 +1+1-1+1+1 = 3 +1+1+1-1+1 = 3 +1+1+1+1-1 = 3 There are 5 ways to assign symbols to make the sum of nums be target 3. Constraints: ----------- The length of the given array is positive and will not exceed 20. The sum of elements in the given array will not exceed 1000. Your output answer is guaranteed to be fitted in a 32-bit integer. ''' import unittest from typing import List, Dict def find_target_sum_ways_backtrack(nums: List[int], t: int, i: int, cache: Dict[int, Dict[int, int]]) -> int: if i == len(nums): if t == 0: return 1 else: return 0 if cache[i].get(t + 2000): return cache[i][t + 2000] pos_ways = find_target_sum_ways_backtrack(nums, t - nums[i], i + 1, cache) neg_ways = find_target_sum_ways_backtrack(nums, t + nums[i], i + 1, cache) cache[i][t + 2000] = pos_ways + neg_ways return (pos_ways + neg_ways) def find_target_sum_ways(nums: List[int], t: int) -> int: cache = dict() for i in range(len(nums)): cache[i] = dict() return find_target_sum_ways_backtrack(nums, t, 0, cache) class Tests(unittest.TestCase): def test_example1(self): self.assertEqual(find_target_sum_ways([1], 1), 1) def test_example2(self): self.assertEqual(find_target_sum_ways([1,1], 0), 2) def test_example3(self): self.assertEqual(find_target_sum_ways([1,1,1,1,1], 3), 5) def test_example4(self): self.assertEqual(find_target_sum_ways([9,7,0,3,9,8,6,5,7,6], 2), 40) def test_example5(self): self.assertEqual(find_target_sum_ways([2,107,109,113,127,131,137,3,2,3,5,7,11,13,17,19,23,29,47,53], 1000), 0) def test_example6(self): self.assertEqual(find_target_sum_ways([40,21,33,25,8,20,35,9,5,27,0,18,50,21,10,28,6,19,47,15], 3), 7050) def test_example7(self): self.assertEqual(find_target_sum_ways([46,49,5,7,5,21,27,4,4,27,45,24,7,22,25,5,38,14,50,28], 45), 6273) def test_example8(self): self.assertEqual(find_target_sum_ways([17,2,1,20,17,36,6,47,5,23,19,9,4,26,46,41,12,11,12,8], 26), 7664) def test_example9(self): self.assertEqual(find_target_sum_ways([2,107,109,113,127,131,137,3,2,3,5,7,11,13,17,19,23,29,47,53], 2147483647), 0) def test_example10(self): self.assertEqual(find_target_sum_ways([2,107,109,113,127,131,137,3,2,3,5,7,11,13,17,19,23,29,47,53], 333), 0) if __name__ == "__main__": unittest.main(verbosity=2)
88c34a41a599feeb42db383d361d37bbb2b56014
bhav09/rock_paper_scissor
/rockpaperscissor.py
1,238
4.0625
4
# game of rock paper scissor import random choice=['rock','scissor','paper'] def game(): game_is_still_going=True while game_is_still_going==True: player_input=input('Your turn:') pc=random.choice(choice) if pc==player_input: print('Tie') game() elif pc=='rock' and player_input=='scissor' or pc=='paper' and player_input=='rock' or pc=='scissor' and player_input=='paper': print('Random_Output was:',pc) print('PC won') play_again=input('Want to play again?(y/n)') if play_again=='y' or play_again=='Y': game() else : game_is_still_going=False elif player_input=='rock' and pc=='scissor' or player_input=='paper' and pc=='rock' or player_input=='scissor' and pc=='paper': print('Random_Output was:',pc) print('Player won') play_again=input('Want to play again?(y/n)') if play_again=='y' or play_again=='Y': game() else : print('Game over') game_is_still_going=False game()
3a14d4a60be3ebdd499c1dab766ce95120046c6e
Amnesia-f/Code-base
/Python/if-else和if-elif-else.py
481
3.875
4
import random computer = random.randint(0, 2) player = int(input("请输入【石头(0)、剪刀(1)、布(2)】:")) if 0 <= player <= 2: if (((player == 0) and (computer == 1)) or ((player == 1) and (computer == 2)) or ((player == 2) and (computer == 0))): print("玩家获胜,恭喜!") elif player == computer: print("平手!") else: print("玩家输了,再接再厉!") else: print("输入错误")
2e91518aff395e6fad10c5148b4692b045134cd3
lukassn/CodeQuests
/URI/inPython/seis_numeros_impares.py
108
3.578125
4
#coding: utf-8 x = int(input()) sai = 0 while sai < 6: if x % 2 != 0: sai += 1 print(x) x += 1
5da6e6bdcf0bc645eb5fec6e858013dd660cbb2d
NiuNiu-jupiter/Leetcode
/472. Concatenated Words.py
1,854
4.25
4
""" Given a list of words (without duplicates), please write a program that returns all concatenated words in the given list of words. A concatenated word is defined as a string that is comprised entirely of at least two shorter words in the given array. Example: Input: ["cat","cats","catsdogcats","dog","dogcatsdog","hippopotamuses","rat","ratcatdogcat"] Output: ["catsdogcats","dogcatsdog","ratcatdogcat"] Explanation: "catsdogcats" can be concatenated by "cats", "dog" and "cats"; "dogcatsdog" can be concatenated by "dog", "cats" and "dog"; "ratcatdogcat" can be concatenated by "rat", "cat", "dog" and "cat". Note: The number of elements of the given array will not exceed 10,000 The length sum of elements in the given array will not exceed 600,000. All the input string will only include lower case letters. The returned elements order does not matter. """ # #it's O(N * L^2 * 2^L) where N is the number of words and L is the max length of a word, for the unmemoized solution and O(N * L^3) for the memoized one. def findAllConcatenatedWordsInADict(words: List[str]) -> List[str]: if not words: return [] dict = set(words) mem = {} def dfs(word): if word in mem: return mem[word] mem[word] = False for i in range(1,len(words)): prefix = word[:i] suffix = word[:i] if prefix in dict and suffix in dict: mem[word] = True return True if prefix in dict and dfs(suffix): mem[word] = True return True if suffix in dict and dfs(prefix): mem[word] = True return True return False return [word for word in words if dfs(word)]
2e51398ada73bde04ac2bd924d140a810278ee65
SimeonTsvetanov/Coding-Lessons
/SoftUni Lessons/Python Development/Python Fundamentals September 2019/Problems And Files/19 EXERCISE OBJECTS AND CLASSES - Дата 25-ти октомври, 1430 - 1730/05. Class.py
2,085
3.984375
4
""" Objects and Classes - Exericse Check your code: https://judge.softuni.bg/Contests/Practice/Index/1734#4 SUPyF2 Objects/Classes-Exericse - 05. Class Problem: Create a class Class. The __init__ method should receive the name of the class. It should also have 2 lists (students and grades). Create a class attribute __students_count equal to 22. The class should also have 3 additional methods: • add_student(name, grade) - if there is space in the class, add the student and the grade in the two lists • get_average_grade() - returns the average of all existing grades formatted to the second decimal point • __repr__ - returns the string (single line): "The students in {class_name}: {students}. Average grade: {get_average_grade()}". The students must be seperated by ", " Example: Test Code: a_class = Class("11B") a_class.add_student("Peter", 4.80) a_class.add_student("George", 6.00) a_class.add_student("Amy", 3.50) print(a_class) Output: The students in 11B: Peter, George, Amy. Average grade: 4.77 #TODO Judge result - 75/100 """ class Class: def __init__(self, name: str): self.name = name self.students = [] self.grades = [] self.__students_count = 22 def add_student(self, name: str, grade: float): if len(self.students) < self.__students_count: self.students += [name] self.grades += [grade] def get_average_grade(self): return sum(self.grades) / len(self.students) def __repr__(self): return f"The students in {self.name}: {', '.join(self.students)}. Average grade: {self.get_average_grade()}" a_class = Class("11B") a_class.add_student("Peter", 4.80) a_class.add_student("George", 6.00) a_class.add_student("Amy2", 3.50) a_class.add_student("Peter3", 4.80) a_class.add_student("George4", 6.00) a_class.add_student("Amy5", 3.50) print(a_class) b_class = Class("11B") b_class.add_student("Peter", 4.80) b_class.add_student("George", 6.00) b_class.add_student("Amy", 3.50) print(b_class)
b1189ab6bf4fdfdeb621c00ed24e1dde09928837
Curtis26/techport
/Python/Assgs/The A-Team.py
2,154
4.21875
4
""" Assignment 4 Program 1 The A-Team Write a program to read the text from a provided text file into a list, display the text on-screen, make some alterations to the text and outputs the changed text to the screen, then save the altered text as a new file. Name..: Yu Wang, Student ID....: W0421944 """ """ Pseudocode #######I use a random to get random number which stand for the row which will be deleted. #######I use a function to make sure the case is right. It is newline(lines,number,newlines,randomnum). #######At last, I use a for loop to write the new file. """ __AUTHOR__ = "Yu Wang <w0421944@.nscc.ca>" def origintxt(): print("------------------------------------") print("Original Text") print("------------------------------------") def alteredtxt(): print("------------------------------------") print("Altered Text") print("------------------------------------") def newline(lines,number,newlines,randomnum): #the function that format the alterd text for line in lines: if len(line) > 20: line = line.lower() else: line = line.upper() number += 1 newline = (str(number) + ": " + line) newlines.extend([newline]) newlines[randomnum-1] = " " for resultline in newlines: print(resultline) return(newlines) def main(): file_obj = open("assg4prog1original.txt") #open the file content = file_obj.read() file_obj.close() origintxt() print(content + "\n") alteredtxt() import random #import random to dicide which is the random line to delete lines = content.split("\n") count = len(lines) randomnum = random.randint(1,count) number = 0 newlines = [] newlines = newline(lines,number,newlines,randomnum) #call the function to make the case format and delete the chosen row. file_obj = open("assg4prog1altered.txt","w") #write the new file for line in newlines: file_obj.write(line) file_obj.write("\n") file_obj.close() if __name__ == "__main__": main()
d1a6eba14da57f8edc9bee8a08284ca91bedf026
mariadaan/Programmeren1_2
/Week 6/adventure/item.py
456
3.875
4
class Item(object): """ Representation of an item in Adventure """ def __init__(self, name, description, initial_room_id): """ Initialize an Item give it a name, description and initial location """ self.name = name self.description = description self.initial_room_id = initial_room_id def __str__(self): return (f"{self.name} {self.description} {self.initial_room_id}")
0a090e12578bc30731db9f744d3d4b389e975259
dtingg/Fall2018-PY210A
/students/DrewSmith/session06/close_far.py
442
3.8125
4
#!/usr/bin/env python """ Given three ints, a b c, return True if one of b or c is "close" (differing from a by at most 1), while the other is "far", differing from both other values by 2 or more. Note: abs(num) computes the absolute value of a number. """ def close_far(a, b, c): if abs(b - c) < 2: return False ab = abs(a - b) ac = abs(a - c) return (ab <= 1 and ac >= 2) or (ac <= 1 and ab >= 2)
128b748aabccbe65c84516401e792b27672799ed
LuisTavaresJr/cursoemvideo
/ex58.py
632
3.8125
4
from random import randint from time import sleep tenta = 0 print('VOU PENSAR EM UM NÚMERO ENTRE 0 E 10 ! TENTE ADIVINHAR') computador = randint(0, 10) acertou = False while not acertou: tenta += 1 jogador = int(input('Qual seu palpite: ')) print('PROCESSANDO...') sleep(1) if jogador == computador: acertou = True else: if jogador < computador: print('Mais... Tente mais uma vez!') elif jogador > computador: print('Menos... Tente mais uma vez!') print(f'Parabéns você acertou! Eu e você pensamos em {computador} !') print(f'Você tentou {tenta} vezes!')
1995f8607d414db87c40ead6316b774e976e8784
vuthysreang/python_bootcamp
/Documents/week02/sreangvuthy17/week02/ex/34_current_date.py
1,009
4.53125
5
""" Description : You will write a function that return the current date with the following format: YYYY-MM-DD. The return value must be a string. Requirements : ● Program must be named : 34_current_date.py and saved into week02/ex folder Hint : ❖ function ❖ datetime Output : current_date() >> 2021-06-14 """ from datetime import datetime # Define current_date() method/function def current_date (): # inside the function/method # print output print('current_date()') # declare (my_current_date) and to assign current date with only date format: YYYY-MM-DD my_current_date = datetime.date(datetime.now()) # convert date into string format my_current_date.strftime("%Y-%M-%D") # print output of (my_current_date) print(">> " + str(my_current_date)) # return output of (my_current_date) return my_current_date # outside the function/method # call the current_date() function/method current_date()
dcea147faf481ff1684a8e3ef45ffe037669acdb
microease/runoob-python-100-examples
/OK/015ok.py
351
3.890625
4
# 题目:利用条件运算符的嵌套来完成此题:学习成绩>=90分的同学用A表示,60-89分之间的用B表示,60分以下的用C表示。 source = int(input("请输入您的分数:")) if source >= 90: grade = 'A' elif source >= 60 and source < 90: grade = 'B' else: grade = 'C' print("%d 属于 %s" % (source, grade))
15724b841e808e8c7c232d9bf9954d060c64d772
Maciel-Dev/ExerciciosProg2
/Exercicio5.py
304
3.71875
4
def main(): listaTeste = [1,3,4,534,62344,8534,25783902,1,613721,8,10,12] maiorNum = 0 #Função for i in listaTeste: if i > maiorNum: maiorNum = i print(maiorNum) #Utilizando Max print(max(listaTeste)) if __name__ == "__main__": main()
f1566cfc6a474eb3a8f459a5e71c9ad5197c14fd
Shreets/Python-basics-III
/search&sort/insertion_sort.py
237
3.859375
4
array = [7,2,4,1,5,3] array_length = len(array) for i in range(array_length): value = array[i] index = i while i > 0 and array[i - 1] > value: array[i] = array[i-1] i = i-1 array[i] = value print(array)
aae9a1a63e883d421e3dbe3f7e6be1c869fe5e02
Yangidan/LeetCode50
/1line.py
1,078
3.625
4
""" Fractal """ # print('\n'.join([''.join(['*'if abs((lambda a: lambda z, c, n: a(a, z, c, n))(lambda s, z, c, n: z if n == 0 else s(s, z*z+c, c, n-1))(0, 0.02*x+0.05j*y, 40)) < 2 else ' ' for x in range(-80, 20)]) for y in range(-20, 20)])) """ Heart """ # print('\n'.join([''.join([('DanLove'[(x-y)%8]if((x*0.05)**2+(y*0.1)**2-1)**3-(x*0.05)**2*(y*0.1)**3<=0 else' ')for x in range(-30,30)])for y in range(15,-15,-1)])) """ Archimedean spiral """ # exec("""\nfrom turtle import *\nfor i in range(500): \n forward(i)\n left(91)\n""") """ quick sort """ # quickSort = lambda array: array if len(array) <= 1 \ # else quickSort([item for item in array[1:] \ # if item <= array[0]]) + [array[0]] + quickSort([item for item in array[1:] if item > array[0]]) # array = [9, 11, 88, 32, 8] # print(quickSort(array)) """ cmd line """ # python -c "while 1:import random;print(random.choice('|| __'), end='')" ab = [[1, 2, 3], [5, 8], [7, 8, 9]] # print([i for i in item for item in ab]) """ NameError: name 'item' is not defined """ print([i for item in ab for i in item])
3e77614cc277f17d6d2ae2d12fd2dd7431a8b000
Programacion-Algoritmos-18-2/2bim-clase-01-CarlosCastillo10
/ejercicio-clases/clase1-2bim/manejo-excepciones/principal.py
372
3.828125
4
""" Ejemplos de manejo de excepciones """ try: edad = int(input("Ingrese su edad por favor: ")) print("Su edad es: %d" %(edad)) except NameError as e: print("Existe un error %s" %e) except ValueError as e: print("Existe un error (%s) %s" %(e.__class__ ,e)) #except Exception as e: #print("Existe un error (%s) %s" %(e.__class__ ,e))
a49116753888039f05929473b5110033e1ddbd24
Saloni399/Leetcode-Solutions
/sets_generators_collections.py
7,556
4.1875
4
# Sets: unorder collection with unique values def count_unique(s): """ Count the number of unique characters in s >>> count_unique('aabb') 2 >>> count_unique('abcdef') 6 """ seen_c = [] # O(1) for c in s: # O(n) if c not in seen_c: # AS list gets longer, lenth of seen_c gets longer, O(n) # In most cases seen_c will be proportional to the length of s # 0+ 1+ 2+ 3+... +(n-1) = n^2, considering only the largest polynomial # Best case will be all repeated characters are same, then seen_c will contain only one character and loop through only one character seen_c.append(c) return len(seen_c) # O(n*n), O(n^2) print(count_unique('hdgfyjkshsa')) # Getting unique characters using set() seen_c = set() # O(1), intialization is constant def count_unique2(s): for c in s: # O(n), loop thorugh n elements if c not in seen_c: # O(1), sets() like dictionaries can hash the values and hence lookup values in constant time seen_c.add(c) # O(1), add also takes constant time return len(seen_c) # Therefore, runtime will be O(n) print(count_unique2('hdgfyjkshsa')) # Getting unique characters using set comprehension def count_unique3(s): return len({c for c in s}) # O(n), loop through n elements print(count_unique3('hdgfyjkshsa')) def count_unique4(s): return len(set(s)) # O(n), loop through n elements print(count_unique4('hdgfyjkshsa')) # set(s) is same as {c for c in s} # Generators # Generators are special type of iterators that iterate over a sequence of values # They are special because they are lazzy iterators which means they iterate over a values only when it is needed. # It is like a list comprehension except we use paranthesis l = [i for i in range(5)] # list print(l) # [0, 1, 2, 3, 4] g = (i for i in range(5)) # generator print(g) # <generator object <genexpr> at 0x000002188E438740> # To accees the values in the iterator object, the next() function has to be used on generator print(next(g)) # 0 print(next(g), next(g), next(g), next(g)) # 1 2 3 4 #print(next(g), next(g), next(g), next(g), next(g), next(g)) # gives StopIteration error when all the elements in the iterator have been accessed # once all the values in the generator have been accessed and exhausted then the values cannot be called again # to get the values agian you will have ti instantiate it again and call next() function again # Comparing generators with a list print(sum([i for i in range(1, 1001)])) # sum() on list print(sum((i for i in range(1,1001)))) # sum() on generator # sum under the hood calls an iterator on the generator and calls next() over and over on generator iterator = iter([i for i in range(1,1001)]) print(next(iterator)) iterator = iter((i for i in range(1,1001))) print(next(iterator)) # Why use generator? lst = [i for i in range(1, 1001)] import sys print(sys.getsizeof(lst)) # 8856 bytes g = (i for i in range(1,1001)) print(sys.getsizeof(g)) # 104 bytes g = (i for i in range(1,2001)) print(sys.getsizeof(g)) # 104 bytes # Generator will always use a constant size even though the sequence grow #lst = [slow_method(i) for i in range(1, 1001)] # This will evaludate slow_method on all the values in the list at once #g = (slow_method(i for i in range(1, 1001))) # This will evaluate the slow_method on i only when it needs to # Generator function # Any function is generator function if it contains the word yield instead of return def y(): yield 1 yield 2 yield 3 # It behaves like function with return , except when calling next() that it will start off from the point after value return from last call # To go inside the function you have to call next() on generator function instead of passing any value as argument or calling directly print(y()) print(next(y())) # Dictionaries and default dictionaries def get_grades_naive(name): student_grades = {"Jack": [85, 90], "Jill": [80, 95] } if name in student_grades: return student_grades[name] return [] print(get_grades_naive("Jack")) print(get_grades_naive("Joe")) def get_grades_better(name): student_grades = {"Jack": [85, 90], "Jill": [80, 95] } return student_grades.get(name, []) # gets the valus of key from dictionary and gives a default value if the key is not found print(get_grades_better("Jack")) print(get_grades_better("Joe")) # The setdefault() method will help add the default value for a key that does not exist in the list def get_grades_with_assignment_better(name): student_grades = {"Jack": [85, 90], "Jill": [80, 95] } return student_grades.setdefault(name, []) print(get_grades_with_assignment_better("Jack")) print(get_grades_with_assignment_better("Joe")) # Add new scores for students or new students with their score def update_grades_with_assignment_better(name, score): student_grades = {"Jack": [85, 90], "Jill": [80, 95] } if name in student_grades: grades = student_grades[name] else: student_grades[name] = [] grades = student_grades[name] grades.append(score) print(student_grades) update_grades_with_assignment_better("Jack", 100) update_grades_with_assignment_better("Joe", 50) def set_grade_better(name, score): student_grades = {"Jack": [85, 90], "Jill": [80, 95] } grades = student_grades.setdefault(name, []) grades.append(score) print(student_grades) set_grade_better("Jack", 100) set_grade_better("Joe", 120) # Using default dict from collections module to achive this from collections import defaultdict student_grades = defaultdict(list) #it will return default value [] when a key is not found in the dictionary def set_grade_best(name, score): student_grades[name].append(score) # the syntax for dictionary gets access to grades value for a studnet name and then appends new score to it # if name is not fould then it binds the score to the default value of dict which is [] and then returns the grade print(student_grades) # defaultdict(<class 'list'>, {}) set_grade_best("Jack", 100) set_grade_best("Joe", 120) print(student_grades) # defaultdict(<class 'list'>, {'Jack': [100], 'Joe': [120]}) # This is adding new items to default dict instead of checking if they already exist # so to do that, we can pass a secong argument to the default dict which will be the actual dictionary along with a default value if any key does not exist in that dictionary student_grades = {"Jack": [85, 90], "Jill": [80, 95] } student_grades = defaultdict(list, student_grades) def set_grade_best(name, score): student_grades[name].append(score) print(student_grades) # defaultdict(<class 'list'>, {'Jack': [85, 90], 'Jill': [80, 95]}) set_grade_best("Jack", 100) set_grade_best("Joe", 120) print(student_grades) # defaultdict(<class 'list'>, {'Jack': [85, 90, 100], 'Jill': [80, 95], 'Joe': [120]}) student_score = defaultdict(lambda: 70) print(student_score) # defaultdict(<function <lambda> at 0x0000026DBB312CB0>, {}) student_score["Jack"] print(student_score) # defaultdict(<function <lambda> at 0x0000026DBB312CB0>, {'Jack': 70}) print(student_score["Joe"] + 10) # 80 print(student_score) # defaultdict(<function <lambda> at 0x0000026C62692CB0>, {'Jack': 70, 'Joe': 70})
54aa8be84033d1cf349fccb8231bedaba73649b6
threebodyyouzi/python_exercise
/day05/text_yuanzu.py
279
3.59375
4
# #!/usr/local/bin/python3.6 mytuplke1=1,2,3 mytuplke2=1,3,["a","b"] print(mytuplke1) print(mytuplke2) mytuplke2[-1].append("c") print(mytuplke2) a=("hello") b=("hello",) print(len(a)) print(len(b)) # with open("text_dict.py.dos","rb") as f: # data=f.read() # print(data)
6ea21f4fe17bbf9b0676926cf726927e7932ebda
Thitsugaya1/python
/factorial.py
260
3.828125
4
# -*- coding: utf-8 -*- """ Created on Tue Apr 22 19:29:28 2014 @author: Toshiron """ def factorial(n): f = 1 for i in range(1, n + 1): f *= i return f n = int(raw_input("n? ")) f = factorial(n) print f #GG para esto :P
0991d549ad38eef0a4870ded942afbfab53f355f
liu666197/data1
/8.10/13 字典的方法.py
918
3.65625
4
a = { 'name': '小明', 'age': 13, 'height': 150, 'weight': 300, 'like': '篮球' } print(a) # 根据key删除 # a.pop('like') # 复制字典 b = a.copy() # 清空字典 # a.clear() # 给某个key设置一个默认值: a['aaa'] = 'bbb' # a.setdefault('aaa','bbb') # a['aaa'] = 'ccc' # 默认删除最后一项(键值对) # a.popitem() # 类似于extend # 可以将新字典当中的键值对,直接加入到原字典里面 # a.update({'aaa': '111','bbb': '222','ccc': '333'}) # 根据key获取value值:和a[key]类似 a = { 'name': '小明', 'age': 13, 'height': 150, 'weight': 300, 'like': '篮球' } a['aaa'] = 'ccc' # get(key,value): 如果key,value不存在,value为None;如果value值存在,key不存在,获取到的值则是value值(默认值),如果字典当中有key,则显示字典中的key所对应的value值 b = a.get('aaa','bbb') # b = a['aaa'] print(b) # print(b)
7952bbc7a733b4a56411c862e8fe2b4699cb7108
amit-kr-debug/CP
/Geeks for geeks/array/First Repeating Element.py
1,489
3.875
4
""" Given an integer array. The task is to find the first repeating element in the array i.e., an element that occurs more than once and whose index of first occurrence is smallest. Input : The first line contains an integer T denoting the total number of test cases. In each test cases, First line is number of elements in array N and second line contains N space separated integer values of the array. Output: In each separate line print the index of first repeating element, if there is not any repeating element then print “-1” (without quotes). Use 1 Based Indexing. Expected Time Complexity: O(N). Expected Auxiliary Space: O(N). Constraints: 1 <= T <= 500 1 <= N <= 106 0 <= Ai <= 106 Example: Input: 3 7 1 5 3 4 3 5 6 4 1 2 3 4 5 1 2 2 1 3 Output: 2 -1 1 Explanation: Testcase 1: 5 is appearing twice and its first appearence is at index 2 which is less than 3 whose first occuring index is 3. Testcase 2: None of the elements are occuring twice . So, the answer is -1. Testcase 3: 1 is appearing twice and its first appearence is at index 1 which is less than 2 whose first occuring is at index 2. """ tCases = int(input()) for _ in range(tCases): n = int(input()) arr = list(map(int, input().split())) dupDict = {} ans = -1 for i in arr: if i in dupDict: dupDict[i] += 1 else: dupDict.update({i: 1}) for i in range(n): if dupDict[arr[i]]>1: ans = i+1 break print(ans)
87f49313038daba1051fb4099cc4a98b5026604f
wcsanders1/HackerRank
/EvenTree/Python/EventTree.py
1,605
3.71875
4
#!/bin/python3 class Node: value = 0 total_children = 0 children = [] def __init__(self, value): self.value = value self.children = [] self.total_children = 0 def get_or_create_node(value, nodes_map): if value not in nodes_map: new_node = Node(value) nodes_map[value] = new_node return nodes_map[value] def get_even_subtrees(node): if node is None: return 0 if not node.children: node.total_children = 0 return 0 even_subtrees = 0 total_children = 0 for subnode in node.children: even_subtrees += get_even_subtrees(subnode) for subnode in node.children: children = subnode.total_children + 1 if children > 1 and children % 2 == 0: subnode.total_children = 0 even_subtrees += 1 else: total_children += children node.total_children += total_children return even_subtrees def even_forest(t_nodes, t_edges, t_from, t_to): root = Node(1) nodes_map = {1: root} for i in range(len(t_from)): child = get_or_create_node(t_from[i], nodes_map) parent = get_or_create_node(t_to[i], nodes_map) parent.children.append(child) return get_even_subtrees(root) if __name__ == '__main__': t_nodes, t_edges = map(int, input().rstrip().split()) t_from = [0] * t_edges t_to = [0] * t_edges for i in range(t_edges): t_from[i], t_to[i] = map(int, input().rstrip().split()) res = even_forest(t_nodes, t_edges, t_from, t_to) print(str(res) + '\n')
39b39a2d225e9a31ea07ec6fdd523f7f88123918
asmaaelk/RaspberryPiBakeOff
/RPBO.py
954
3.609375
4
import pygame from Tkinter import * ''' class MainApp(): width, height = 640, 480 screen = pygame.display.set_mode((width,height)) MainApp() class MainApp(): app = Tk() app.title("Raspberry Pi Bake-Off") app.geometry('640x480') app.mainloop() def quitApp(): app.destroy() quitButton = Button(app,text = "quit", width = 10, commmand = quitApp) quitButton.pack(size = 'left') ''' app = Tk() app.title("Raspberry Pi Bake-Off") app.geometry('640x480') def quitApp(): app.destroy() quitButton = Button(app, text = 'quit', width = 10, command = quitApp) quitButton.pack() questionFrame = Canvas(app,width=640,height = 300, background = 'blue') questionFrame.pack(side = 'bottom') Label(questionFrame,text =" Questions?", font = ("Times",32)).pack(side = 'top') Label(questionFrame,text = "Baloons", font = ("Times",16)).pack(side = 'bottom') #Label(questionFrame).grid(sticky = W) app.mainloop()
f06bc0a8ea0aad44d48e5f112caa7c7bda3de981
ptrompeter/math-series
/src/series.py
1,095
4.03125
4
#_*_ coding: utf-8 _*_ def fib(num): """Return value of ath number in fib sequence.""" if num <= 0: return 0 elif num == 1: return 1 else: return fib(num - 1) + fib(num - 2) def lucas(num): """Return value of ath number in lucas sequence.""" if num <= 0: return 2 elif num == 1: return 1 else: return lucas(num - 1) + lucas(num - 2) def sum(num, first=0, second=1): """Return value of ath number in lucas sequence.""" if num <= 0: return first elif num == 1: return second else: return sum(num - 1, first, second) + sum(num - 2, first, second) if __name__ == "__main__": print(u"Our fibonacci sequence:") print(u"fib(0) = ", fib(0)) print(u"fib(10) = ", fib(10)) print(u"Our Lucas series:") print(u"lucas(0) = ", lucas(0)) print(u"lucas(10) = ", lucas(10)) print(u"Our sum series:") print(u"sum(0) = ", sum(0)) print(u"sum(10) = ", sum(10)) print(u"sum(0, 2, 1) = ", sum(0, 2, 1)) print(u"sum(10, 2 ,1) = ", sum(10, 2, 1))
58ba6bdc1d375db884933057766ab1349de5aede
MohamedHajr/Problem-Solving
/leetCode/single_number.py
417
3.625
4
# class Solution: # def singleNumber(self, nums: 'List[int]') -> 'int': # hashset = set() # for num in nums: # if num in hashset: # hashset.remove(num) # else: # hashset.add(num) # return hashset.pop() from functools import reduce def singleNumber(nums): return reduce(lambda x, y: x ^ y, nums) print(singleNumber([1,2,2,3,3]))
0822e4d596de1bb806f6409f783e296400d51123
kevin-d-mcewan/ClassExamples
/Chap8_StringsDeepLook/ReplacingSubstring.py
417
4.09375
4
'''Method REPLACE takes two substrings. It searches a string for the substring in its first argument and replaces EACH occurrence with the substring in its second argument. The method returns a new string containing the results''' values = '1\t2\t3\t4\t6' print(values) print(values.replace('\t', ',')) # REPLACING can receive an optional third argument specifying in # the maximum number of replacements to perform
19aa94fcc090e7e89be6e320c74798ea0a15431f
hywu1996/TCP_UDP_DateTime_App
/Client_TCP.py
874
3.953125
4
import socket #Take IP as input from user TCP_IP = input("Please enter the server's IP Address: ") #Take PORT as input from user, make sure it is castable to int or re-prompt while True: TCP_PORT = input("Please enter the port the server is listening at: ") try: TCP_PORT = int(TCP_PORT) break except ValueError: pass #Ask user for request to send to server request = input("Please enter message to send to server: ") print ("Attempting to contact server at ",TCP_IP,":",TCP_PORT) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((TCP_IP, TCP_PORT)) #connect with connection settings print ("Connection to Server Established") s.sendall(request.encode()) #encode and send message to server response = s.recv(1024) #get response from server s.close() #close socket print("Server Response: ", response.decode()) #decode and echo response to user
521bd785819288401810a2cb4f6a8459705241a9
shaurtoonetwork/Data-Structures-Implemented-In-Python
/LinkedLists/LinkedList1.py
2,762
4
4
class Node: def __init__(self,data): self.data=data self.next=None class Linkedlist: def __init__(self): self.head=None def printlist(self): cur_node=self.head while cur_node: print(cur_node.data) cur_node=cur_node.next def append(self,data): new_node=Node(data) if self.head is None: self.head=new_node return last_node=self.head while last_node.next: last_node=last_node.next last_node.next=new_node def prepend(self,data): new_node=Node(data) new_node.next=self.head self.head=new_node def add_after_node(self,prev_node,data): new_node=Node(data) new_node.next=prev_node.next prev_node.next=new_node def delete_node(self,key): cur_node=self.head if cur_node and cur_node.data==key: self.head=cur_node.next cur_node=None prev=None while cur_node and cur_node.data!=key: prev=cur_node cur_node=cur_node.next if cur_node is None: return prev.next=cur_node.next cur_node = None def delete_node_pos(self,pos): cur_node = self.head if pos==0: self.head = cur_node.next cur_node = None return prev = None count = 0 while cur_node and count != pos: prev = cur_node cur_node = cur_node.next count += 1 if cur_node is None: return prev.next=cur_node.next cur_node = None def len_iterative(self): count = 0 cur_node = self.head while cur_node: count+=1 cur_node = cur_node.next print(count) def len_recursive(self,node): if node is None: return 0 return 1+self.len_recursive(node.next) def swap_nodes(self,node1,node2): if node1 == node2: return prev1=None cur1=self.head while cur1 and cur1.data!=node1: prev1=cur1 cur1=cur1.next prev2=None cur2=self.head while cur2 and cur2.data!=node2: prev2=cur2 cur2=cur2.next if not cur1 or not cur1: return if prev1: prev1.next=cur2 else: self.head=cur2 if prev2: prev2.next=cur1 else: self.head=cur1 cur1.next,cur2.next=cur2.next,cur1.next llist=Linkedlist() llist.append("A") llist.append("B") llist.append("C") llist.append("D") llist.append("E") llist.swap_nodes("B","C") llist.printlist()
18dbd776ff100c2d0f4222fa3bee4dd0ba3783e8
naqveez/assignment2
/assignment2.py
501
3.546875
4
import random as r arr = [] for i in range(50): arr.append(r.randint(1,1000)) print(arr) exercise = arr[0] k = 0 for j in range(0, len(arr) ,1): if exercise > arr[j] : exercise = arr[j] k = j print("Min :", exercise, " index : ", k) for j in range(0, len(arr), 1): if exercise < arr[j]: exercise = arr[j] k = j print("Max :" , exercise , " index :" , k) sum = 0 for l in range(0, len(arr), 1): sum = sum + arr[l] avg = sum/len(arr) print("Mean :" , avg)
4dfafe3dc3b680d9ca736fc915fc71461f41c912
zhuyoujun/DSUP
/CountBagADT.py
1,437
3.734375
4
#------------------------------------------ #Book:Data Structures and Algorithms Using Python #Author:zhuyoujun #Date:20150129 #Chapter1: ADT # Programming Projects 1.3 #Counting Bag ADT #------------------------------------------ #Implements the Counting Bag ADT using ADT. class CountBag: def __init__(self): self._theElements = list() def __len__(self): return len(self._theElements) def __contains__(self,item): return item in self._theElements def add(self,item): self._theElements.append(item) def remove(self,item): #print item assert item in self._theElements,"There is no item in the Bag." ndx = self._theElements.index(item) return self._theElements.pop(ndx) def numOf(self,item): assert item in self._theElements,"There is no item in the Bag." count = 0 for elem in self._theElements: if item == elem: count +=1 return count def main(): myBag = CountBag() myBag.add( 19 ) myBag.add( 74 ) myBag.add( 23 ) myBag.add( 19 ) myBag.add( 12 ) ## value = int( input("Guess a value contained in the bag.") ) ## if value in myBag: ## print( "The bag contains the value", value ) ## else : ## print( "The bag does not contain the value", value ) print myBag.remove(74) print myBag.numOf(19) main()
e6e894c6d9bc8b37556ca5f0fa88a7ce87f9bc78
davidadeola/My_Hackerrank_Solutions
/python/mutate_str.py
173
3.671875
4
def mutate_string(string, position, character): arr = list(string) arr[position] = character return "".join(arr) print(mutate_string("Hellothere", 5, "w"))
d44fbb08a82ce10a63315113b274c0a9f989a0de
benniatli/hotel-search-engine
/lesaGogn.py
1,413
3.5
4
import sqlite3 as lite import sys import random files = open("hotelGogn.txt",'r') file_list = files.readlines() con = lite.connect('HotelSearch.db') con.text_factory = str stringList = file_list[1].split('"') with con: cur = con.cursor() cur.execute("DROP TABLE IF EXISTS Hotels") cur.execute("CREATE TABLE Hotels(Id INTEGER PRIMARY KEY, Name TEXT, Location TEXT, Stars INTEGER, Price INTEGER, Description TEXT)") for line in file_list[1:len(file_list)]: line = line.strip(); stringList = line.split('"') hotelID = int(stringList[1]) hotelName = stringList[3] hotelLocation = stringList[5] hotelStars = int(stringList[7]) price = stringList[9][1:len(stringList[9])] hotelPrice = int(price) hotelDescription = stringList[11] cur.execute("INSERT INTO Hotels VALUES(?,?,?,?,?,?)",(hotelID, hotelName, hotelLocation, hotelStars, hotelPrice, hotelDescription)) cur.execute("DROP TABLE IF EXISTS Rooms") cur.execute("CREATE TABLE Rooms(Id INTEGER PRIMARY KEY AUTOINCREMENT, hotelID INTEGER REFERENCES Hotels(Id), RoomSpace INT)") for i in range(1,368): cur.execute("ALTER TABLE Rooms ADD COLUMN '{cn}' TEXT DEFAULT '{df}'".format(cn = i, df = "")) #104 hotel eins og er for i in range(1, 105): numRooms = random.randint(2,10) for j in range(1,numRooms): numPeople = random.randint(1,4) cur.execute("INSERT INTO Rooms(hotelID, RoomSpace) VALUES (?,?)",(i,numPeople))
ab05f6d770729f38ffe543d48f2a49962c5ad91d
sharda2001/Loop_PYTHON
/multi.py
136
4.03125
4
num1=int(input("enter the num1= ")) num2=int(input("enter the num2= ")) i=1 count=0 while i<=num2: count=count+num1 i=i+1 print(count)
d355c7e8ab5300c03df417194230cd58aea51cf5
Kimmix/PythonDataSci
/Day4.py
272
3.53125
4
import pandas as pd df = pd.read_csv( "http://rcs.bu.edu/examples/python/data_analysis/Salaries.csv") df_sex = df.groupby(['sex']) # print(df_sex.mean()) print(df_sex.head()) # print(df[ df['salary'] > 120000]) # print(df[ df['salary'] > 120000]) # print(df.cumsum())
b42303781bb4be9a8fc92e75b524e943046fc438
asterix135/algorithm_design
/directed_graph.py
4,710
4.21875
4
"""Vertex and Graph Classes for a directed graph""" class Vertex: """ class to keep track of vertices in a graph and their associated edges """ def __init__(self, key): """ initialize vertex with id number and empty dictionary of edges """ self._id = key self._connected_to = {} def add_neighbor(self, neighbor, weight=1): """ add information about a connected vertex to the vertex's _connected_to dictionary key is vertex, value is weight """ self._connected_to[neighbor] = weight def remove_neighbor(self, neighbor, weight=1): """ remove neighbor information """ if neighbor in self._connected_to.keys(): self._connected_to.pop(neighbor) def __str__(self): """ returns human-readable version of vertex's connections """ return str(self._id) + ' connected to ' + str([node._id for node in self._connected_to]) def get_connections(self): """return list of connections""" return self._connected_to.keys() def get_id(self): """ returns id of vertex""" return self._id def get_weight(self, neighbor): """ returns the weight of an edge betweeen self and a given neighbor """ return self._connected_to[neighbor] class Graph: """class to manage verices and edges in a directed graph""" def __init__(self, graph_type='u'): """ contains a dictionary - _vertex_list - mapping vertex keys to vertex objects and a count of the number of vertices in the graph """ self._graph_type = graph_type self._vertex_list = {} self._vertex_count = 0 def create_vertex(self, key): """ creates a new vertex and returns that vertex """ self._vertex_count += 1 new_vertex = Vertex(key) self._vertex_list[key] = new_vertex return new_vertex def get_vertex(self, key): """ returns the vertex object associated with a key """ if key in self._vertex_list: return self._vertex_list[key] else: return None def __contains__(self, key): """ returns a boolean indicating whether a given vertex is in the graph """ return key in self._vertex_list def add_edge(self, tail_key, head_key, weight=1): """ adds a new edge to the graph. If either vertex is not present, it will be added first. in directed graph, edge is only added for the tail vertex """ if tail_key not in self._vertex_list: self.create_vertex(tail_key) if head_key not in self._vertex_list: self.create_vertex(head_key) self._vertex_list[tail_key].add_neighbor(self._vertex_list[head_key], weight) if self._graph_type == 'u': self._vertex_list[head_key].add_neighbor(self._vertex_list [tail_key], weight) def get_vertices(self): """ return a list of keys of all vertices in the graph """ return self._vertex_list.keys() def __iter__(self): """returns an iterator of all vertices""" return iter(self._vertex_list.values()) def remove_vertex(self, key): # TODO implement remove_vertex function # 1. make sure vertex is in graph # 2. get list of connected vertices # 3. remove all relevant edges from connected vertices # 4. remove actual vertex # 5. update vertex count pass def remove_edge(self, tail_id, head_id, weight=1): # TODO implment remove_edge function # 1. check list in tail_id & remove if found pass def get_edges(self): """ returns a list of edges in the graph edges represented as a tuple: (tail, head, weight) """ edge_list = [] for node in self._vertex_list: edge_list.extend(node.get_connections()) return edge_list def get_edge_count(self): return len(self.get_edges()) def __str__(self): # TODO create __str__ method for Graph Class pass def test(): g = Graph() g.create_vertex(1) g.create_vertex(2) g.add_edge(1, 2) g.add_edge(2, 3) g.add_edge(3, 1) g.add_edge(1, 2, 1) print(str(g.get_vertex(1))) print(str(g.get_vertex(2))) print(str(g.get_vertex(3))) if __name__ == '__main__': test()
9ccefe2963dd51991f0a990e1e85e932ce21ef98
gabriellaec/desoft-analise-exercicios
/backup/user_358/ch21_2020_09_30_12_06_32_392790.py
269
3.75
4
dias=int(input('digite o valor ') horas=int(input('digite o valor ') minutos=int(input('digite o valor ') segundos=int(input('digite o valor ') a=dias*86400 b=horas*3600 c=minutos*60 d=segundos total_segundos=(a+b+c+D) print(total_segundos)
c7a813a24a9a4ea16146066553911e10cc891d00
QiliWu/leetcode-and-Project-Euler
/Project Euler/046 - Goldbach's other conjecture.py
973
3.765625
4
# -*- coding: utf-8 -*- """ Goldbach's other conjecture Problem 46 It was proposed by Christian Goldbach that every odd composite number can be written as the sum of a prime and twice a square. 9 = 7 + 2×12 15 = 7 + 2×22 21 = 3 + 2×32 25 = 7 + 2×32 27 = 19 + 2×22 33 = 31 + 2×12 It turns out that the conjecture was false. What is the smallest odd composite that cannot be written as the sum of a prime and twice a square? """ from math import sqrt def isprime(x): if x <= 1: return False if x == 2: return True else: for i in range(2, int(sqrt(x)+1)): if x % i == 0: return False return True primes = [2] n = 3 while True: if isprime(n): primes.append(n) else: for i in primes: m = sqrt((n-i)/2) if m % 1 == 0: print(n, i, m) break else: print(n) break n = n + 2 #print(n)
a9a191affbdbfbfcfd22098eec93762a7e39f6f7
dixieduke/pythonLearning
/readfile.py
297
3.859375
4
filename = 'file.txt' with open(filename) as f: content = f.readlines() print(content) infile = open(filename, 'r') data = infile.read() infile.close() print(data) with open(filename) as fp: for i, line in enumerate(fp): print(i) print(fp.readline())
cb170204cd22f741c15fb1ee40b3bf3717b5e0ca
xxd59366/python
/pycharmContent/else/testList.py
984
3.890625
4
# 使用位置参数 str01='{} is {}'.format('bob', 15) # str02='{1} is {0}'.format(15, 'bob') # 当str01与02值相同时,索引到0就停了,所以原本不会出现index is 1的输出 # 加上一个感叹号,index输出值出现变化 str02='{1} is {0}!'.format(15, 'bob') # 使用关键字参数 str03='name is {name},age is {age}'.format(name='bob',age=23) str04='姓名:{name} ,年龄:{age}'.format(**{'name': 'bob', 'age': 23}) str05='姓名:{0[name]} ,年龄:{1[age]}'.format({'name': 'bob', 'age': 23},{'age':24}) # 填充与格式化 # {:[填充字符][对齐方式:<表示左对齐,>表示右对齐][宽度]} str06='{:<10} is {:<8}'.format('bob', 15) str07='{:<10} is {:0>8}'.format('bob', 15) # 使用索引 str08='姓名:{0[0]},年龄:{0[1]}'.format(['bob',23]) s=[str01,str02,str03,str04,str05,str06,str07,str08] for i in range(1,len(s)+1): print(i,end=' ') print(s[i-1]) print('index is', s.index(s[i-1]))
5636309511c5a585c7018fe83cb0c608c25b531d
anilbhatt1/Deep_Learning_EVA4_Phase2_webapp
/src/gan.py
1,713
3.578125
4
import streamlit as st from io import BytesIO from src.utils import local_css import src.gan_process as gp def write(): """ Deep Learning Model to generate images of Indian car from random vector supplied """ local_css("style.css") st.markdown("<h1 style='text-align: center; color: black;font-size: 40px;'>Car Image Generation using GAN</h1>", unsafe_allow_html=True) st.write( """ Generative Adverserial Networks (GANs) are neural networks that are trained in an adversarial manner to generate data by mimicking some distribution. GANs are comprised of two neural networks, pitted one against the other (hence the name adversarial). Applications of GANs are vast that include Generate Examples for Image Datasets, Generate Photographs of Human Faces, Generate Realistic Photographs, Generate Cartoon Characters, Drug Research etc. Here, GANs are employed to generate images of Indian cars based on input vector values. DCGAN is the type of GAN used. - [Reference link for approach followed](https://github.com/anilbhatt1/Deep_Learning_EVA4_Phase2/tree/master/S6_GAN/Model%20Weights/Yangyangii%20Cars%20Example%20Github) - [Github link for model](https://github.com/anilbhatt1/Deep_Learning_EVA4_Phase2/tree/master/S6_GAN) - [Github link for webapp](https://github.com/anilbhatt1/Deep_Learning_EVA4_Phase2_webapp) """ ) st.set_option('deprecation.showfileUploaderEncoding', False) #GAN if st.checkbox("Car Image generation for given range of values"): gp.explore() elif st.checkbox("Random Car Image generation"): gp.generate()
77bc55fb00daf192980300ec10137828baffb64b
NWood-Git/phase1_assessment
/ANSWER_4_5/app/person.py
268
3.625
4
class Person: def __init__(self, first_name, last_name): self.first_name = first_name self.last_name = last_name def __repr__(self): return f"{self.last_name.title()}, {self.first_name.title()}" # x = Person("Jack","Ryan") # print(x)
95981e6865fa1c7d45442c6b26888a84fff3594b
parveza7/euler2
/4.py
763
3.796875
4
############################################################################### # Project Euler Problem 4 # Largest palindrome product # A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. # Find the largest palindrome made from the product of two 3-digit numbers. ############################################################################### def largest_palindrome(digits): largest = 0 for i in range((10 ** digits) - 1, (10 ** (digits - 1)) - 1, -1): for j in range((10 ** digits) - 1, (10 ** (digits - 1)) - 1, -1): if str(i * j)[::-1] == str(i * j): largest = max(i * j, largest) return largest print(largest_palindrome(3))
413f79aee492bfe3b71a3ece8cc11d7db352ad32
Rossel/Solve_250_Coding_Challenges
/chal130.py
183
3.734375
4
x = [list(range(5)), list(range(5,9)), list(range(1,10,3))] if sum(x[0]) > sum(x[2]): print("True!") elif max(x[1]) > max(x[2]): print("False!") else: print("None!")
ea188d8858a6b171f8b23bff2d2d244eb68f8edf
Varuzhan11/My_Python_Homeworks
/day_5_practice.py
3,359
3.921875
4
"""DATA STRUCTURES""" # 1. Write a program to find the sum of the even elements in the list. Use loops and not the sum() function! lst = [21, 56, 66, 45, 42, 14, 86, 12, 31, 69, 86, 38, 82, 25, 59, 17, 6, 63, 41, 67] x = len(lst) counter = 0 for i in range(x): if lst[i] % 2 == 0: counter += lst[i] print(counter) # 2. A dictionary is given, containing different foods as keys and their contents as values. Unfortunately, we are # lactose intolerant. Loop through the dictionary and output the food name and 'I can't consume that' if it contains # lactose and 'Yum!' otherwise. # The output for the milk may look like this: # 'Milk? I can't consume that' foods = {'Milk': 'Calcium, Lactose', 'Nutella': 'Calcium', 'Cheese': 'Calcium', 'Yoghurt': 'Calcium, Lactose', 'Spinach': 'Calcium', 'Fish': 'Calcium'} for food, ingredients in foods.items(): if "Lactose" in ingredients: print(f'{food}? I can\'t consume that') else: print("Yum!") # 3. A dictionary is given, containing student's grades. The student has failed if the effective grade is lower than 40, # his grade is satisfactory if it's in between 40-59, good if it's in between 60-79 and outstanding if it's in # between 80-100. Print the corresponding grade and description. grades = {'Maths': 7, 'Physics': 11, 'Geography': 10, 'History': 8, 'Geometry': 19} total = sum(grades.values()) if 0 <= total < 40: print("Fail") elif 40 <= total < 60: print("Satisfactory") elif 60 <= total < 80: print("Good") elif 60 <= total <= 100: print("Outstanding") else: print("Grades are wrong Somehow...") # 4. Create a list using a comprehension, which will contain odd numbers only. lst_1 = [i for i in range(1, 1001) if i % 2 == 1] print(lst_1) # 5. Add to a list all the words in the given string that have a length <=4. Do this using both loops and a # comprehension. litany = """I must not fear. Fear is the mind-killer. Fear is the little-death that brings total obliteration. I will face my fear. I will permit it to pass over me and through me. And when it has gone past, I will turn the inner eye to see its path. Where the fear has gone there will be nothing. Only I will remain.""" lst_2 = litany.split() n = len(lst_2) counter = 0 for i in range(n): if "." in lst_2[i] and len(lst_2[i]) > 4: counter += 1 elif "." not in lst_2[i] and len(lst_2[i]) >= 4: counter += 1 print(counter) # 6. Write a generator comprehension which will contain every 4th number from 100-200. Then loop over it and print the # element. # 7. Write a program that will print a list containing first 50 numbers in Fibonacci sequence. lst_3 = [0, 1] lst_4 = [] for i in range(2, 53): lst_3.append(lst_3[i-2] + lst_3[i-1]) print(lst_3) # 8. Write a program to combine two dictionary adding values for common keys. # 9. Write a program to create a dictionary from a string. The letters are the keys and the values are the counts of # the corresponding letters. # 10. Remove the keys that have None value from the dict. colors = {'Color 1': 'Red', 'Color 2': 'Blue', 'Color 3': 'Green', 'Color 4': None, 'Color 5': 'Yellow', 'Color 6': None} new_dict = colors.copy() for key, value in colors.items(): if value == None: del new_dict[key] print(new_dict)
77bb64c5c4347a95b54e08d90725c0ad8c1e04df
Jagadish2019/Python_Object_Class
/src/Practice/init.py
1,741
3.875
4
#Attributes and Methods ''' 1. What is an attribute? - An attribute is a property that further defines a class. 2. What is a method ? - A method is a function within a class which can access all the attributes of a class and perform a specific task. 3. What is a class attribute? - Class attributes are attributes that are shared across all instances of a class. - They are created either as a part of the class or by using className.attributeName 4. What is an instance attribute ? - Instance attributes are attributes that are specific to each instance of a class. - They are created using obbjectName.attributeName 5. How is self parameter handles ? - The method call objectName.methodName() is interpreted as a className.methodName(objectName) and this parameter is referred to as 'self' in method definition. 6. What is an instance method? - Methods that has the default parameter as the object are static methods. They are used to modify the instance attribute of a class. 7. What is a static method ? - Methods that do not modify the instances attributes of a class are called instance methods. They can still be used to modify class attributes. 8. What is init() method? - init() method is the initializer in Python. It is called when an object is instantiated. - All the attributes of the class should be initialized in this method to make your object a fully initialized object. ''' class Employee(): def __init__(self): self.name='Jagan' def empDetails(self): print(self.name) empOne = Employee() empOne.empDetails() class Employee1(): def __init__(self, name): self.name=name def empDetails(self): print(self.name) empTwo = Employee1("jagadish") empTwo.empDetails()
34313d20a4d9fc40a2d05ad41ca0c762c9ac1855
rishikeshpuri/Algorithms-and-Data-Structure
/searching/Find a local minima in an array.py
470
3.640625
4
def localMinima(A): left = 0 right =len(A)-1 n=len(A) while left<=right: mid = (left+ right)//2 if A[mid] == 0 or A[mid-1] > A[mid] and mid == n-1 or A[mid] < A[mid +1]: return mid elif A[mid] > 0 and A[mid] > A[mid-1]: right = mid-1 elif A[mid] > 0 and A[mid] < A[mid-1]: left = mid+1 return mid arr = [4, 3, 1, 14, 16, 40] print("Index of a local minima is " , localMinima(arr))
46438c638150ab2d6015afd1cf836afa705bcd38
vgomesdcc/UJ_TeoCompPYTHON
/p6.py
248
3.90625
4
print("Insira seu peso") peso = float(input()) print("Insira sua altura") altura = float(input()) imc = peso/(altura*altura) if imc>30: print("O usuario esta obeso") else: print("O usuario esta abaixo da linha da obesidade")
3ff646afc00fb5b0d715df3407af9693c690a6e0
JJURIZ/pymongo
/main.py
2,297
3.765625
4
from pymongo import MongoClient # import datetime so we can have timestamps on things we add to the database. import datetime # import pprint so we can pretty print objects from the database. import pprint # pymongo connects to the default host and port if you don't specify any # parameters to the constructor when it's initialized. If you need to connect # to a non-default MongoDB on your local machine then simply specify the host # and port: # host = 'localhost' # port = 27017 # client = MongoClient(host, port) client = MongoClient() db = client.test_database # drop the collection if it already exists so here's a clean slate. db.drop_collection("blogposts") # grab a reference to a database, access a collection using "db.collectionname" collection = db.blogposts post1 = { "author": "Guido", "text": "Idea for a Programming Language", "tags": ["python", "release", "development"], "date": datetime.datetime(1989, 12, 23, 12) } post2 = { "author": "Mongo Team", "text": "Introducing MongoDB!", "tags": ["mongodb", "release", "development"], "date": datetime.datetime(2009, 11, 12, 12) } post3 = { "author": "Guido", "text": "Using MongoDB, Python and Flask", "tags": ["python", "mongodb", "pymongo", "development"], "date": datetime.datetime(2012, 2, 5, 12) } # insert one blog post to the collection. post_id = db.blogposts.insert_one(post1).inserted_id # verify the blog post has been added. # find a document in collection in a few different ways. db.blogposts.find_one() db.blogposts.find_one({"author": "Guido"}) retrieved_post = db.blogposts.find_one({"_id": post_id}) print("Verifying Guido's post was created:") pprint.pprint(retrieved_post) print() # Add several blog posts to the collection at once using .insert_many() db.blogposts.insert_many([post2, post3]) # query for several blogposts print("Finding all blog posts:") for post in db.blogposts.find(): pprint.pprint(post) print() print("Total posts:", db.blogposts.count()) print("Total posts by Guido:", db.blogposts.find({"author": "Guido"}).count()) print() # use mongo's "dollar-sign" query operators print("Finding blog posts after the year 2000:") d = datetime.datetime(2000, 1, 1, 12) for post in db.blogposts.find({"date": {"$gt": d}}).sort("author"): pprint.pprint(post)
9341a6636cfae3ee89930dbb5c2b0c9ec7067ccf
f2k5/Practice-python-problems
/pp_02.py
329
4.4375
4
""" Ask the user for a number. Depending on whether the number is even or odd, print out an appropriate message to the user. Hint: how does an even / odd number react differently when divided by 2? """ x = int(input("Enter a number: ")) y = (x % 2) if y == 0: print("The number even!") else: print("The number is odd!")
4b904b611a8ef78ed1e435d777ae2de4f1146abe
Offliners/Python_Practice
/code/125.py
355
3.65625
4
# saving a data structure in a file # in JSON import json data = {"alpha" : [3,5,7], "beta" : [4,6,8]} with open("code/Data/data.json","w") as f: json.dump(data,f) # ... # using text format now with open("code/Data/data.json","r") as f: restored = json.load(f) print(restored) # Output: # {'alpha': [3, 5, 7], 'beta': [4, 6, 8]}
b5669988818512182da01330cbfb1cb996d956a0
kaivantaylor/Code-Wars
/007_Accumulator/final.py
1,014
4
4
# Kaivan Taylor # Summary - This time no story, no theory. The examples below show you how to # write the function accum # Examples: # accum("abcd") -> "A-Bb-Ccc-Dddd" # accum("RqaEzty") -> "R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy" # accum("cwAt") -> "C-Ww-Aaa-Tttt" # The paramter of accum is a string which includs only letters from # a..z and A..Z import re test1 = ("abcd") # "A-Bb-Ccc-Dddd" test2 = ("RqaEzty") # "R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy" test3 = ("cwAt") # "C-W-Aaa-Tttt" def accum(text): str_holder = text.lower().strip() answer = '' counter = 0 for x in str_holder: print(x) print(counter) if counter == 0: print(x.upper()) opt1 = x.upper() answer += opt1 else: print((str("-" + x.upper() + str(x*counter)))) opt2 = (str("-" + x.upper() + str(x*counter))) answer += opt2 counter += 1 return answer
1ca6f13f70c157e948a4a254644d9b5bbf84708c
alchemz/Self-Driving-Car-Engineer-Nanodegree
/Lesson 5 Miniflow/Linear.py
351
3.640625
4
""" Linear Equations """ class Linear(Node): def __init___(self, inputs, weights, bias): Node.__init__(self, [inputs, weights, bias]) def forward(self): inputs = self.inbound_nodes[0].value weights = self.inbound_nodes[1].value bias = self.inbound_nodes[2].value self.value = bias for x, w in zip(inputs, weights): self.value += x*w
5e9dd96d1af0b34d05c181afe7b7170aea60b021
RichardDev01/MazeRunner
/mazerunner_sim/utils/pathfinder.py
6,328
4.03125
4
"""Module containing some useful functions for pathfinding.""" from typing import Callable, Dict, List, Tuple from queue import PriorityQueue import numpy as np Coord = Tuple[int, int] DistanceFunc = Callable[[Coord], float] def manhattan_distance(p1: Coord, p2: Coord) -> int: """ Calculate the Manhattan distance between two coordinates. :param p1: First point :param p2: Second point :return: Distance between the two points """ return abs(p1[0] - p2[0]) + abs(p1[1] - p2[1]) def target_to_distance_func(target: Coord) -> DistanceFunc: """ Create a manhattan distance function to the given coordinate. :param target: the reference point :return: distance function that returns the manhattan distance to target """ return lambda p: manhattan_distance(p, target) def traceback_visited(visited_tree: Dict[Coord, Coord], end: Coord, origin: Coord) -> List[Coord]: """ Use the visited_log to trace the path back to the beginning. :param visited_tree: dictionary that represents the relation between next-tile as key and previous-tile as value :param end: end of the path :param origin: the original coordinate shouldn't get included in the path :return: a list of coordinates from the origin to the end """ path = [end] while visited_tree[end] != origin and end != origin: path.append(visited_tree[end]) end = visited_tree[end] path.reverse() return path def coord_within_boundary(maze: np.array, coord: Coord) -> bool: """ Check if the given coordinate lays within maze boundaries. :param maze: a 2D boolean array where True means walkable tile and False means a wall :param coord: a 2D coordinate :return: false if out of bounds, true if inbounds """ x, y = coord height, width = maze.shape return 0 <= x < width and 0 <= y < height def surrounding_tiles(coord: Coord) -> List[Coord]: """ Get surrounding tiles from giving tile. :param coord: Given coord to check surrounding :return: np array of surrounding_tiles """ x, y = coord surrounding = [(x, y - 1), (x - 1, y), (x + 1, y), (x, y + 1)] return surrounding def compute_explore_paths(start_coord: Coord, runner_known_map: np.array, runner_explored_map: np.array): """ Compute paths for exploring :param start_coord: Start coords :param runner_known_map: Known map of the runner :param runner_explored_map: Explored map of the runner :return: """ edge_tiles = [] visited_tiles = {start_coord: None} # key: next_tile, value: previous_tile q = PriorityQueue() q.put((0, start_coord)) while not q.empty(): # gets the tile with the lowest priority value priority, tile = q.get() for next_tile in surrounding_tiles(tile): if coord_within_boundary(runner_known_map, next_tile): # Check coords with maze if you can walk there if runner_known_map[next_tile[1], next_tile[0]] and next_tile not in visited_tiles: x, y = next_tile[0] + 1, next_tile[1] + 1 explored = np.pad(runner_explored_map, (1, 1), 'constant', constant_values=False) # UP LEFT RIGHT DOWN if not(explored[y - 1, x] and explored[y, x - 1] and explored[y, x + 1] and explored[y + 1, x]): edge_tiles.append(next_tile) q.put((priority + 1, next_tile)) visited_tiles[next_tile] = tile paths = [traceback_visited(visited_tiles, edge_tile, start_coord) for edge_tile in edge_tiles] return paths def paths_origin_targets(origin: Coord, targets: List[Coord], maze: np.array) -> List[List[Coord]]: """ Find the paths from the origin to the targets. Finding the path to multiple targets from the same origin is faster than doing them all separately, by avoiding redoing a bunch of computations. The path to one target can still be done (and just as fast) by giving a list with one item. Warning: This implementation assumes there these paths are possible, otherwise the function will hang. :param origin: the origin coordinate from which each path will start :param targets: the ends where each path should end :param maze: a 2D boolean array where True means walkable tile and False means a wall :return: A list of paths corresponding with each end """ for x, y in targets + [origin]: assert maze[y, x] targets_togo = list(targets) if origin in targets_togo: targets_togo.remove(origin) visited_tree = {origin: None} # key: next tile, value: previous tile q = PriorityQueue() q.put((0, origin)) # Dijkstra to all the targets, until one target is left while len(targets_togo) > 1: priority, tile = q.get() for dx, dy in [(0, -1), (0, 1), (-1, 0), (1, 0)]: next_tile = tile[0] + dx, tile[1] + dy if coord_within_boundary(maze, next_tile): if maze[next_tile[1], next_tile[0]] and (next_tile not in visited_tree): q.put((priority + 1, next_tile)) visited_tree[next_tile] = tile if next_tile in targets_togo: targets_togo.remove(next_tile) if len(targets_togo) == 1: done = False distance_func = target_to_distance_func(targets_togo[0]) else: done = True distance_func = None # A* for the last target for better efficiency while not done: _, tile = q.get() for dx, dy in [(0, -1), (0, 1), (-1, 0), (1, 0)]: next_tile = tile[0] + dx, tile[1] + dy if coord_within_boundary(maze, next_tile): if maze[next_tile[1], next_tile[0]] and (next_tile not in visited_tree): q.put((distance_func(next_tile), next_tile)) visited_tree[next_tile] = tile if next_tile in targets_togo: done = True break # Trace back the path for each of the targets return [traceback_visited(visited_tree, target, origin) for target in targets]
5becfc53c48bf6a6e532bf4c8029ff02c2eb2358
anthonyho007/leetcode
/InsertCycleSortedList.py
897
3.921875
4
""" # Definition for a Node. class Node(object): def __init__(self, val, next): self.val = val self.next = next """ class Solution(object): def insert(self, head, insertVal): """ :type head: Node :type insertVal: int :rtype: Node """ if head == None: return Node(insertVal, None) prev = head curr = head.next if curr != None: while True: if prev.val <= insertVal and curr.val >= insertVal: break elif prev.val > curr.val and (prev.val <= insertVal or curr.val >= insertVal): break if head == curr: break prev = curr curr = curr.next node = Node(insertVal, curr) prev.next = node return head
3964d55ba7fd5a98fde81715fd309eeaabbfc814
mariaEduarda-codes/Python
/estruturas-repetitivas/problema_media_idades.py
646
4.28125
4
""" Faça um programa para ler um número indeterminado de dados, contendo cada um, a idade de um indivíduo. O último dado, que não entrará nos cálculos, contém um valor de idade negativa. Calcular e imprimir a idade média deste grupo de indivíduos. Se for entrado um valor negativo na primeira vez, mostrar a mensagem "IMPOSSÍVEL CALCULAR". """ print("Digite as idades: ") idade = int(input()) soma = 0 contagem = 0 while idade > 0: soma += idade contagem += 1 idade = int(input()) if idade < 0 and contagem == 0: print("IMPOSSÍVEL CALCULAR") else: print(f"MÉDIA = {soma / contagem:.2f}")
f10a40bcb5df9d3cde21bfd98f6717b1c16b2862
tnzw/tnzw.github.io
/py3/def/list_sorted_insert.py
1,463
3.6875
4
# list_sorted_insert.py Version 1.0.0 # Copyright (c) 2021 Tristan Cavelier <t.cavelier@free.fr> # This program is free software. It comes without any warranty, to # the extent permitted by applicable law. You can redistribute it # and/or modify it under the terms of the Do What The Fuck You Want # To Public License, Version 2, as published by Sam Hocevar. See # http://www.wtfpl.net/ for more details. def list_sorted_insert(self, x, *, key=None, reverse=False): """\ >>> l = [1, 3]; list_sorted_insert(l, 4); l [1, 3, 4] >>> l = [1, 3, 5]; list_sorted_insert(l, 4); l [1, 3, 4, 5] >>> l = [3, 1]; list_sorted_insert(l, 4, reverse=True); l [4, 3, 1] >>> l = [5, 3, 1]; list_sorted_insert(l, 4, reverse=True); l [5, 4, 3, 1] """ if reverse: l = len(self) if key is not None: kx = key(x) for i, y in enumerate(reversed(self)): y = key(y) if kx <= y: self.insert(l - i, x) break else: self.insert(0, x) else: for i, y in enumerate(reversed(self)): if x <= y: self.insert(l - i, x) break else: self.insert(0, x) else: if key is not None: kx = key(x) for i, y in enumerate(self): y = key(y) if kx <= y: self.insert(i, x) break else: self.append(x) else: for i, y in enumerate(self): if x <= y: self.insert(i, x) break else: self.append(x)
25e21743f88233690cfa3d616ecf0e7c2e430c21
NessOffice/Sync_Code
/codeforces/round583_div2/D_data.py
223
3.796875
4
import random n = random.randint(3, 10) m = random.randint(3, 10) print(n, m) for i in range(n): ans = "" for j in range(m): grid = random.randint(0, 10) if(grid > 9): ans += "#" else: ans += "." print(ans)
13c169058651efac15f13158d1fd01781a035fd4
anirudhganwal06/pgn2bitboard
/pgn2bitboard/main.py
4,429
3.53125
4
#!/usr/bin/env python # coding: utf-8 import numpy as np import chess import chess.pgn import random def choosePositions(positions, moves, nExcludeStarting=5, nPositions=10): """ Returns positions that will be used in our model Inputs: positions: List of all chessboard positions of a game in FEN format moves: List of all moves that led to the given positions nExcludeStarting: Number of positions not to choose at the start of the game nPositions: Number of random positions to choose from a single game Outputs: chosenPositions: list of randomly chosen positions out of all positions """ # Remove nExcludeStarting number of moves from start of the match chosenPositions = positions[nExcludeStarting:] chosenMoves = moves[nExcludeStarting:] # Choose all positions which were not led by any capture chosenPositions = [chosenPositions[i] for i in range( len(chosenMoves)) if 'x' not in chosenMoves[i]] # Select nPositions random positions from chosenPositions if len(chosenPositions) > nPositions: chosenPositions = random.sample(chosenPositions, k=nPositions) return chosenPositions def winner(game): """ Returns who is the winner, if draw return 'd' Inputs: game: A chess game[PGN] Outputs: winner: White('w') / Black('b') / Draw('d') """ if game.headers['Result'] == '1-0': return 'w' elif game.headers['Result'] == '0-1': return 'b' return 'd' def pgn2fen(game): """ Returns all positions[FEN] and moves[SAN] from game[PGN] Inputs: game: A chess game[PGN] Outputs: positions: All positions of game[List of FEN] moves: All moves that led to the positions[List of SAN] """ node = game positions = [] moves = [] # All positions and moves until the game ends while not node.is_end(): nextNode = node.variation(0) move = node.board().san(nextNode.move) position = nextNode.board().fen() moves.append(move) positions.append(position) node = nextNode return positions, moves def fen2bitboard(fen): """ Returns bitboard [np array of shape(1, 773)] from fen Input: fen: A chessboard position[FEN] Output: bitboard: A chessboard position [bitboard - np array of shape(1, 773)] """ mapping = { 'p': 0, 'n': 1, 'b': 2, 'r': 3, 'q': 4, 'k': 5, 'P': 6, 'N': 7, 'B': 8, 'R': 9, 'Q': 10, 'K': 11 } bitboard = np.zeros((1, 773), dtype=int) currIndex = 0 [position, turn, castling, _, _, _] = fen.split(' ') for ch in position: if ch == '/': continue elif ch >= '1' and ch <= '8': currIndex += (ord(ch) - ord('0')) * 12 else: bitboard[0, currIndex + mapping[ch]] = 1 currIndex += 12 bitboard[0, 768] = 1 if turn == 'w' else 0 bitboard[0, 769] = 1 if 'K' in castling else 0 bitboard[0, 770] = 1 if 'Q' in castling else 0 bitboard[0, 771] = 1 if 'k' in castling else 0 bitboard[0, 772] = 1 if 'q' in castling else 0 return bitboard def pgn2bitboard(pgnFilePath): """ Iterate over all games of pgnFile and returns some good positions from those games Inputs: pgnFilePath: path of the file where pgn games are stored Outputs: bitboards: chessboard positions [np array of shape(None, 773)] labels: labels of corresponding bitboards - winner [np array of shape(None, 1)] """ pgnFile = open(pgnFilePath) game = chess.pgn.read_game(pgnFile) bitboards = np.ndarray((0, 773)) labels = np.ndarray((0, 1)) count = 0 while game is not None: win = winner(game) if win in ['w', 'b']: positions, moves = pgn2fen(game) positions = choosePositions(positions, moves) for position in positions: bitboard = fen2bitboard(position) label = 1 if win == 'w' else 0 label = np.array([[label]]) bitboards = np.append(bitboards, bitboard, axis=0) labels = np.append(labels, label, axis=0) count += 1 game = chess.pgn.read_game(pgnFile) return bitboards, labels
04e74e90548ec2e2dcd64b6f58389718e1813f27
kurbanuglu/lab---pro
/Ders9-BozukParaOyunu-12.03.2019.py
794
3.5625
4
# Bozuk para olarak verilecek para üstünü en az para adedi ile geri döndüren fonksiyon def coin(n): coinlist=[1,5,10,21,50,100] b=[] c=[] a=n z=len(coinlist)-1 while(a!=0): for i in range(z,-1,-1): if(a>=coinlist[i]): while(a>=coinlist[i]): a=a-coinlist[i] b.append(coinlist[i]) a = n z = len(coinlist) - 1 while(a!=0): for j in range(z,-1,-1): if(a%coinlist[j]==0): while(a!=0): a=a-coinlist[j] c.append(coinlist[j]) if(len(b)<len(c)): return b else: return c x=int(input("Para ustunu giriniz: ")) print("Verilecek bozuk paralar: ",coin(x))
ae8deb999791deb33e4d9a6b091562a71d0843c3
mbriseno98/cpsc-example-code
/python/MatchmakerLite-Part1/Matchmaker.py
686
3.734375
4
# Eric Pogue # Matchmaker Lite print("") print("Matchmaker 2021") print("") print("[[Your instructions here.") print("") UserResponse1 = int(input("Iowa Hawkeye football rocks!")) desiredResponse1 = 5 compatability1 = 5 - abs(UserResponse1 - desiredResponse1) print("Question 1 compatability: " + str(compatability1)) print("") UserResponse2 = int(input("European soccer is the greatest sport in the world!")) desiredResponse2 = 2 compatability2 = 5 - abs(UserResponse2 - desiredResponse2) print("Question 2 compatability: " + str(compatability2)) print("") totalCompatibility = (compatability1 + compatability2) * 10 print("Total Compatability: " + str(totalCompatibility)) print("")
d5c216f69fae5be89ad021f5b86bbb9e6edbdca3
jewells07/Python
/tell()&seek().py
307
3.921875
4
with open("File.txt")as f: #It will open and close file in this block: print(f.readline()) print(f.tell()) #f=file pointer tell use where it is f.seek(10) #f=file pointer we set at the point 10 print(f.tell()) print(f.readline())
ea63c231d870fdb24d7fdfcc992eea3081ff9672
boombelka/home_work_python
/hw01_normal.py
2,782
3.6875
4
 __author__ = 'Верещагин А.В.' print(' Задание 1') # Задача-1: Дано произвольное целое число, вывести самую большую цифру этого числа. # Например, дается x = 58375. # Нужно вывести максимальную цифру в данном числе, т.е. 8. # Подразумевается, что мы не знаем это число заранее. # Число приходит в виде целого беззнакового. # Подсказки: # * постарайтесь решить задачу с применением арифметики и цикла while; # * при желании и понимании решите задачу с применением цикла for. # import random as r a = r.randint(1, 10000000) f = 0 print(f'число {a}') while not a < 1: n = a % 10 a = a // 10 if f < n: f = n else: continue print(f'максимальная цифра {f}') # Задача-2: Исходные значения двух переменных запросить у пользователя. # Поменять значения переменных местами. Вывести новые значения на экран. # Решите задачу, используя только две переменные. # Подсказки: # * постарайтесь сделать решение через действия над числами; # * при желании и понимании воспользуйтесь синтаксисом кортежей Python. print(' Задание 2') a = input('Введите число а: ') b = input('Введите число b: ') b, a = (a, b) print(f'число а: {a}') print(f'число b: {b}') # Задача-3: Напишите программу, вычисляющую корни квадратного уравнения вида # ax² + bx + c = 0. # Коэффициенты уравнения вводятся пользователем. # Для вычисления квадратного корня воспользуйтесь функцией sqrt() модуля math: print(' Задание 3') import math # math.sqrt(4) - вычисляет корень числа 4 a = float(input('Введите число а: ')) b = float(input('Введите число b: ')) c = float(input('Введите число c: ')) d = b**2 - 4*a*c print(f'дискриминант {d}') if d < 0: print('Корней нет') elif d == 0: x1 = (-b - math.sqrt(d)) / 2*a print(f'Корень один x = {x1}') else: x1 = (-b - math.sqrt(d)) / 2*a x2 = (-b + math.sqrt(d)) / 2*a print(f'Корни x1 = {x1} и х2 = {x2}')
7f0e99de1d600213984e1f52f33e12210913d6fa
lixinxin2019/LaGou2Q
/homework001.py
269
3.6875
4
def func1(): print("这是没有参数、没有返回值的方法") def func2(a, b): print("这是有参数、有返回值的方法") c = a + b print(f"{a}+{b} = {c}") return c if __name__ == '__main__': print(func1()) print(func2(1, 2))
56b65b480d2eb5f95fc52939b6ce65a1ad04bf52
bensenberner/ctci
/dynamic_recursive/power_set.py
588
3.578125
4
from typing import Set def power_set(original_set): memo = dict() def _power_set(s: Set) -> Set: s_tuple = tuple(s) if s_tuple in memo: return memo[s_tuple] ps = set() # go through each sub element, add them in, then add the full thing for element in s: reduced_set = s.difference({element}) reduced_power_set = _power_set(reduced_set) ps.update(reduced_power_set) ps.add(s_tuple) memo[s_tuple] = ps return ps return [set(e) for e in _power_set(original_set)]
a52835ac1a288d47ae7a4e28915433d13cbadab1
yanshengjia/algorithm
/leetcode/Array/1085. Sum of Digits in the Minimum Number.py
1,117
3.75
4
""" Given an array A of positive integers, let S be the sum of the digits of the minimal element of A. Return 0 if S is odd, otherwise return 1. Example 1: Input: [34,23,1,24,75,33,54,8] Output: 0 Explanation: The minimal element is 1, and the sum of those digits is S = 1 which is odd, so the answer is 0. Example 2: Input: [99,77,33,66,55] Output: 1 Explanation: The minimal element is 33, and the sum of those digits is S = 3 + 3 = 6 which is even, so the answer is 1. Solution: Firstly we find the minimun number of array A. Then we divide the number consecutively and get their remainder modulus 10. Sum those remainders and return the answer as the problem asks. """ # Time: O(M + logN), where M is the length of array A, N is the minimun # Space: O(1) class Solution(object): def sumOfDigits(self, A): """ :type A: List[int] :rtype: int """ m = float('inf') for a in A: if a < m: m = a s = 0 while m > 0: s += m % 10 m //= 10 return 1 if s % 2 == 0 else 0
eedba6e7fe518c3b4451c0c6a6988a06f5725e65
pedroceciliocn/intro-a-prog-py-livro
/Cap_8_Funções/exe_8_6_prog_8_2_usando_for.py
381
4.0625
4
""" Exercício 8.6 Reescreva o Programa 8.2 de forma a utilizar for em vez de while. """ # Programa 8.2 - corrigido (genérico) e com for def soma(L): total = 0 for x in range(len(L)): total += L[x] return total L = [1, 7, 2, 9, 15] print(soma(L)) # deu certo print(soma([7, 9, 12, 3, 100, 20, 4])) # agora também deu certo, pois ela é genérica o suficiente
dbd627ee70e987dc3e5f118b46cb0febab9ac812
NiuNiu-jupiter/Leetcode
/250. Count Univalue Subtrees.py
841
4.0625
4
""" Given a binary tree, count the number of uni-value subtrees. A Uni-value subtree means all nodes of the subtree have the same value. Example : Input: root = [5,1,5,5,5,null,5] 5 / \ 1 5 / \ \ 5 5 5 Output: 4 """ # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None def countUnivalSubtrees(root: TreeNode) -> int: self.res = 0 isunique(root) return self.res def isunique(node): if not node: return True l, r = isunique(node.left), isunique(node.right) if l and r and(not node.left or node.left.val == node.val) and(not node.right or node.right.val == node.val): self.res+=1 return True return False
10869fde785ca577222891ec5fe53c23c31e6d1c
CapsLockAF/python-lessons-2021
/HW7_Tupl-Sets-2/t5.py
781
3.65625
4
# Задано два символьних рядка із малих і великих латинських літер та цифр. # Розробити програму, яка будує і друкує в алфавітному порядку множину # літер, які є в обох масивах, і множини літер окремо першого # і другого масивів. lowSet = set(chr(lowers) for lowers in range(97, 123)) t = ("FXRFGKJHLUjsbfbjdfgdj26568749815hjbJVDhsgfkbH", "a854512111100GFfdh88") t1 = set(t[0].lower()).intersection(lowSet) t2 = set(t[1].lower()).intersection(lowSet) t_equal = t1.union(t2) print(f"Set 1 = {sorted(t1)}", f"Set 2 = {sorted(t2)}", f"Set1 + Set2 = {sorted(t_equal)}", sep="\n")
5873a56607c657cc9705723da582aca6b23ece85
Iliasben96/Theorie-project
/code/algorithms/astar.py
11,206
3.734375
4
import math from code.classes.grid import Grid from code.classes.priority_queue import PriorityQueue from code.heuristics.manhattan import manhattan_heuristic from code.classes.state import State from code.heuristics.neighbor_locker import NeighborLocker class Astar: counter = 0 def __init__(self): self.state = None def start(self, option, grid, connection): if option == 1: path = self.use_clean(grid, connection) return path if option == 2: path = self.use_initial_neighbor_lock(grid, connection) return path if option == 3: path = self.use_runtime_neighbor_lock(grid, connection) return path def use_clean(self, grid, connection): """ A* algorithm to search for the shortest possible distance for a wire, using manhattan distance. It uses heuristics to determine the order of the wires and to decide how to use neighbors. """ start_gate = connection.gate_a goal_gate = connection.gate_b start_coordinates = start_gate.coordinates goal_coordinates = goal_gate.coordinates # Make sure start and end are walkable grid.add_start_end_gates(start_coordinates, goal_coordinates) # Initialise the priority queue frontier = PriorityQueue() # Put start in the queue frontier.put(start_coordinates, 0) # Initialise an archive came_from = {} # The total cost so far cost_so_far = {} # Initialse start with a came from of None came_from[start_coordinates] = None cost_so_far[start_coordinates] = 0 # Explore map untill queue is empty while not frontier.empty(): # Get first item in priority queue current = frontier.get() # Stop if you reach goal if current == goal_coordinates: path = [] position = current while position != came_from[start_coordinates]: path.append(position) grid.all_wires.append(position) position = came_from[position] path.reverse() grid.put_connection(path, connection) return path # Get neighbors from grid neighbors = grid.get_neighbors(current) # Loop over neighbors of current node for next_node in neighbors: # Calculate new cost for each neighbor new_cost = cost_so_far[current] + 1 # See if next node is already visited or if the cost if next_node not in cost_so_far or new_cost < cost_so_far[next_node]: # Store the cost so far cost_so_far[next_node] = new_cost # Add priority priority = new_cost + manhattan_heuristic(next_node, goal_coordinates) # Put child in prioriy queue frontier.put(next_node, priority) # Store where the child came from came_from[next_node] = current def use_initial_neighbor_lock(self, grid, connection): """ A* algorithm to search for the shortest possible distance for a wire, using manhattan distance. It uses heuristics to determine the order of the wires and to decide how to use neighbors. """ start_gate = connection.gate_a goal_gate = connection.gate_b start_coordinates = start_gate.coordinates goal_coordinates = goal_gate.coordinates # Make sure start and end are walkable grid.add_start_end_gates(start_coordinates, goal_coordinates) # Make sure the start and goal neighbor coordinates are walkable grid.add_back_gate_neighbors(start_coordinates, goal_coordinates) # Initialise the priority queue frontier = PriorityQueue() # Put start in the queue frontier.put(start_coordinates, 0) # Initialise an archive came_from = {} # The total cost so far cost_so_far = {} # Initialse start with a came from of None came_from[start_coordinates] = None cost_so_far[start_coordinates] = 0 # Explore map untill queue is empty while not frontier.empty(): # Get first item in priority queue current = frontier.get() # Stop if you reach goal if current == goal_coordinates: path = [] position = current while position != came_from[start_coordinates]: path.append(position) grid.all_wires.append(position) position = came_from[position] path.reverse() grid.put_connection(path, connection) return path # Get neighbors from grid neighbors = grid.get_neighbors(current) # Loop over neighbors of current node for next_node in neighbors: # Calculate new cost for each neighbor new_cost = cost_so_far[current] + 1 # See if next node is already visited or if the cost if next_node not in cost_so_far or new_cost < cost_so_far[next_node]: # Store the cost so far cost_so_far[next_node] = new_cost # Add priority priority = new_cost + manhattan_heuristic(next_node, goal_coordinates) # Put child in prioriy queue frontier.put(next_node, priority) # Store where the child came from came_from[next_node] = current # Relock the neighbor coordinates of the start and goal after each run grid.relock_gate_neighbors(start_coordinates, goal_coordinates) def use_runtime_neighbor_lock(self, grid, connection): """ A* algorithm to search for the shortest possible distance for a wire, using manhattan distance. It uses heuristics to determine the order of the wires and to decide how to use neighbors. """ start_gate = connection.gate_a goal_gate = connection.gate_b start_coordinates = start_gate.coordinates goal_coordinates = goal_gate.coordinates # Make sure start and end are walkable grid.add_start_end_gates(start_coordinates, goal_coordinates) # Initialise the priority queue frontier = PriorityQueue() # Put start in the queue frontier.put(start_coordinates, 0) # Initialise an archive came_from = {} # The total cost so far cost_so_far = {} if Astar.counter == 0: nl = NeighborLocker(grid) self.all_gate_neighbors = nl.get_all_gate_neighbors() available_neighbors = nl.get_available_neighbors_dict() locked_neighbors = nl.lock_neighbors(available_neighbors, {}, start_gate.nr, goal_gate.nr) # Check if locking encites another lock new_available_neighbors = nl.lock_double_neighbors(locked_neighbors, self.all_gate_neighbors, available_neighbors) # Lock again if it does new_locked_neighbors = nl.lock_neighbors(new_available_neighbors, locked_neighbors, start_gate.nr, goal_gate.nr) state = State(start_coordinates, new_locked_neighbors, new_available_neighbors) else: state = self.state state.available_neighbors_amount state_dict = {} # Initialse start with a came from of None came_from[start_coordinates] = None cost_so_far[start_coordinates] = 0 counter = 0 # Explore map untill queue is empty while not frontier.empty(): if counter == 1: break # Get first item in priority queue current = frontier.get() # Stop if you reach goal if current == goal_coordinates: path = [] position = current while position != came_from[start_coordinates]: path.append(position) grid.all_wires.append(position) position = came_from[position] path.reverse() grid.put_connection(path, connection) self.state = state_dict[came_from[current]] return path # If the current state exists in the dict already, fetch it if current in state_dict: state = state_dict[start_coordinates] # If it is not, get the previous state as the current state else: if came_from[current] in state_dict: state = state_dict[came_from[current]] elif came_from[state.coordinates] == None: state_dict[current] = state # Get available neighbors available_neighbors = state.available_neighbors_amount # Lock neighbors that need to be locked locked_neighbors = nl.lock_neighbors(available_neighbors, state.locked_neighbors, start_gate.nr, goal_gate.nr) new_available_neighbors = nl.lock_double_neighbors(locked_neighbors, self.all_gate_neighbors, available_neighbors) locked_neighbors = nl.lock_neighbors(new_available_neighbors, state.locked_neighbors, start_gate.nr, goal_gate.nr) available_neighbors = nl.get_new_available_neighbors(current, self.all_gate_neighbors, locked_neighbors, available_neighbors) # Save any and all changes in a new state new_state = State(current, locked_neighbors, available_neighbors) state = new_state # Store this new state in a dict, with the current coordinate as a key state_dict[current] = state # Get neighbors from grid neighbors = grid.get_neighbors(current) # Loop over neighbors of current node for next_node in neighbors: # Only move to a next node if it isn't locked if next_node not in locked_neighbors: # Calculate new cost for each neighbor new_cost = cost_so_far[current] + 1 # See if next node is already visited or if the cost if next_node not in cost_so_far or new_cost < cost_so_far[next_node]: # Store the cost so far cost_so_far[next_node] = new_cost # Add priority priority = new_cost + manhattan_heuristic(next_node, goal_coordinates) # Put child in prioriy queue frontier.put(next_node, priority) # Store where the child came from came_from[next_node] = current
0751320cf092c9717fe86dc3037e9d84bc61f77e
Talleth/PythonUseOfTkinter
/exercise.py
4,261
3.765625
4
#=================================================================== #    Purpose:   Demonstrate usage of a GUI #=================================================================== from tkinter import* form=Tk() form.title("Change Counter") form.geometry("315x350") # Button event def buttonPress(): # Quarters calculation quartersResult = round((int(quartersText.get()) * 25) / 100, 2) quartersValueText.delete(0, 'end') quartersValueText.insert(0, str(quartersResult)) # Dimes calculation dimesResult = round((int(dimesText.get()) * 10) / 100, 2) dimesValueText.delete(0, 'end') dimesValueText.insert(0, str(dimesResult)) # Nickels calculation nickelsResult = round((int(nickelsText.get()) * 5) / 100, 2) nickelsValueText.delete(0, 'end') nickelsValueText.insert(0, str(nickelsResult)) # Pennies calculation penniesResult = round((int(penniesText.get()) * 1) / 100, 2) penniesValueText.delete(0, 'end') penniesValueText.insert(0, str(penniesResult)) # Halfs calculation halfDollarsResult = round((int(halfDollarsText.get()) * 50) / 100, 2) halfDollarsValueText.delete(0, 'end') halfDollarsValueText.insert(0, str(halfDollarsResult)) # Dollars calculation dollarsResult = round((int(dollarsText.get()) * 100) / 100, 2) dollarsValueText.delete(0, 'end') dollarsValueText.insert(0, str(dollarsResult)) # Result calculation resultValueText.delete(0, 'end') result = round(quartersResult + dimesResult + nickelsResult + penniesResult + halfDollarsResult + dollarsResult, 2) resultValueText.insert(0, str(result)) # Variables quarters = StringVar() quartersValue = StringVar() # Quarters quartersLabel = Label(form, text="Quarters: ") quartersLabel.place(x=10, y=10) quartersText = Entry(form, textvariable=quarters, width=4, bd =5) quartersText.place(x=75, y=10) quartersValueLabel = Label(form, text="Quarters Value: ") quartersValueLabel.place(x=115, y=10) quartersValueText = Entry(form, textvariable=quartersValue, width=4, bd =5) quartersValueText.place(x=210, y=10) # Dimes dimesLabel = Label(form, text="Dimes: ") dimesLabel.place(x=10, y=50) dimesText = Entry(form, width=4, bd =5) dimesText.place(x=75, y=50) dimesValueLabel = Label(form, text="Dimes Value: ") dimesValueLabel.place(x=115, y=50) dimesValueText = Entry(form, width=4, bd =5) dimesValueText.place(x=210, y=50) # Nickels nickelsLabel = Label(form, text="Nickels: ") nickelsLabel.place(x=10, y=90) nickelsText = Entry(form, width=4, bd =5) nickelsText.place(x=75, y=90) nickelsValueLabel = Label(form, text="Nickels Value: ") nickelsValueLabel.place(x=115, y=90) nickelsValueText = Entry(form, width=4, bd =5) nickelsValueText.place(x=210, y=90) # Pennies penniesLabel = Label(form, text="Pennies: ") penniesLabel.place(x=10, y=130) penniesText = Entry(form, width=4, bd =5) penniesText.place(x=75, y=130) penniesValueLabel = Label(form, text="Pennies Value: ") penniesValueLabel.place(x=115, y=130) penniesValueText = Entry(form, width=4, bd =5) penniesValueText.place(x=210, y=130) # Half Dollars halfDollarsLabel = Label(form, text="Half Dol: ") halfDollarsLabel.place(x=10, y=170) halfDollarsText = Entry(form, width=4, bd =5) halfDollarsText.place(x=75, y=170) halfDollarsValueLabel = Label(form, text="Half Dol Value: ") halfDollarsValueLabel.place(x=115, y=170) halfDollarsValueText = Entry(form, width=4, bd =5) halfDollarsValueText.place(x=210, y=170) # Dollars dollarsLabel = Label(form, text="Dollars: ") dollarsLabel.place(x=10, y=210) dollarsText = Entry(form, width=4, bd =5) dollarsText.place(x=75, y=210) dollarsValueLabel = Label(form, text="Dollars Value: ") dollarsValueLabel.place(x=115, y=210) dollarsValueText = Entry(form, width=4, bd =5) dollarsValueText.place(x=210, y=210) # Instructions label instructionsLabel = Label(form, text="Enter the number of each coin type and hit, compute: ") instructionsLabel.place(x=10, y=250) # Results resultValueLabel = Label(form, text="Total Value: ") resultValueLabel.place(x=115, y=290) resultValueText = Entry(form, width=4, bd =5) resultValueText.place(x=210, y=290) # Button button = Button(form, text ="Compute", command = buttonPress) button.place(x=30, y=290) form.mainloop()
4acbd03222536321306cdce0d03541eaa611bda9
TheJambrose/Python-4-Everyone-exercises
/ch_09/ex_09_extra.py
788
3.796875
4
import string fname = input("Enter file name: ") if len(fname) < 1 : fname = 'clown.txt' hand = open(fname) di = dict() for line in hand : line = line.rstrip() # print(line) #remove formatting and punctuation line = line.translate(line.maketrans("","", string.punctuation)) line = line.lower() wds = line.split() # print(wds) for word in wds: di[word] = di.get(word, 0) + 1 # print(di) #now find the most common word big_count = None big_word = None for word,count in di.items() : if big_count is None or count > big_count : big_count = count big_word = word else : continue print(f"The most common word is '{big_word}'' used {big_count} time(s).") sorted_keys = sorted(di.keys()) # print(sorted_keys)
4c94a448fbc534255604c96ce9522ad61102bb81
rfmurray/psyc6273
/03 - functions; strings/workshop3answers.py
3,033
4.5
4
# workshop3.py Lecture 3 workshop problems # Add code below the following comments, to solve the stated problems. # # Some problems will require tools from earlier lectures, such as lists and # loops. This will be the case in workshop problems from now on. # 1. Define a function randt(n, u, v) that returns an n-tuple of random # floating point numbers between u and v. Give u a default value of 0, # and v a default value of 1. (Hint: you could first create a list, # possibly using a list comprehension, and then convert it to a tuple # using tuple().) import random def randt(n, u=0, v=1): x = [ random.uniform(u,v) for i in range(n) ] return tuple(x) # 2. Define a function randl(n, m) that returns a list with n elements, # where each element is an m-tuple of random numbers between 0 and 1, # created using your solution to problem 1. def randl(n, m): return [ randt(m) for i in range(n) ] # 3. Create a function bsort(x) that uses the bubblesort algorithm from # lecture 2 to sort a list x. You can just copy and paste the code from # lecture 2 into the function. def bsort(x): # loop until list is sorted keep_sorting = True while keep_sorting: # step through elements of list keep_sorting = False; for i in range(len(x)-1): # wrong order? if x[i] > x[i+1]: x[i], x[i+1] = x[i+1], x[i] keep_sorting = True # test it x = [ random.uniform(0,1) for i in range(10) ] bsort(x) # 4. Revise your solution to problem 3, so that the bsort function allows # an additional, optional input argument called 'key'. Assign key a default # value of None. Revise the function bsort so that it uses the key argument # like the sort() function for built-in lists, as illustrated in the lecture 3 # code in functions.py. That is, if the user passes an argument key=f, then # the list is sorted based on whether f(x[i]) > f(x[i+1]), instead of # whether x[i] > x[i+1]. def bsort(x, key=None): # loop until list is sorted keep_sorting = True while keep_sorting: # step through elements of list keep_sorting = False; for i in range(len(x)-1): # wrong order? if key is None: flip = x[i] > x[i+1] else: flip = key(x[i]) > key(x[i+1]) if flip: x[i], x[i+1] = x[i+1], x[i] keep_sorting = True # test it by sorting in reverse order x = [ random.uniform(0,1) for i in range(10) ] f = lambda x : -x bsort(x, key=f) # 5. Create a list of ten 3-tuples using your solution to problem 2. Use your # solution to problem 4 to sort this list, based on the sum of the numbers # in each 3-tuple. That is, the 3-tuple with the lowest sum comes first, and # the 3-tuple with the highest sum comes last. (Hint: the function sum() # returns the sum of the elements in a tuple.) x = randl(10, 3) bsort(x, key=sum) # check that the list is sorted in the order we wanted [ sum(u) for u in x ]