blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
baa949c6168222dda0cf63624ca31138942b4e1a
dfeusse/codeWarsPython
/06_june/08_dieRolling.py
520
4.0625
4
''' Hello! Today your task is to build a basic die feature, where you will get a range in the form (min, max) - both included - and return a random number in the inclusive range. Props if you don't use your language's random library! dice(2, 7) # returns a value that can be 2, 3, 4, 5, 6, 7 Good luck! ''' from random import randint def dice(minNum, maxNum): return range(minNum, maxNum+1)[randint(0,maxNum-minNum)] print dice(2, 7) ''' def dice(minimum, maximum): return random.randint(minimum, maximum) '''
11a0d32519e918d1181b79c8385b0a4e2ef76399
ibogorad/CodeWars
/Thinkful - Object Drills.py
179
3.546875
4
class Vector(object): def __init__(self, x, y, ): self.x = x self.y = y def add(self, other): return Vector(self.x + other.x,self.y + other.y)
63af1268a161465ab368d8b59dc438b15a925ce4
vietthanh179980123/VoVietThanh_58474_CA20B1
/page_100_project_08.py
1,073
4.125
4
""" Author: Võ Viết Thanh Date: 18/09/2021 Program: The greatest common divisor of two positive integers, A and B, is the largest number that can be evenly divided into both of them. Euclid’s algorithm can be used to find the greatest common divisor (GCD) of two positive integers. You can use this algorithm in the following manner: a. Compute the remainder of dividing the larger number by the smaller number. b. Replace the larger number with the smaller number and the smaller number with the remainder. c. Repeat this process until the smaller number is zero The larger number at this point is the GCD of A and B. Write a program that lets the user enter two integers and then prints each step in the process of using the Euclidean algorithm to find their GCD. Solution: .... """ def EuclideanGCD(a,b): if a < b: a , b = b , a if(a % b) == 0: return b else: T = a % b return (EuclideanGCD(b,T)) a = float(input(" nhap so a : ")) b = float(input(" nhap so b: ")) print('GDC: ', EuclideanGCD(a,b))
fa9a72623ca46f790c45f84aa46b9cba9a10c287
hsycamp/algorithm
/leetcode/valid_anagram.py
789
3.671875
4
''' LeetCode 242. Valid Anagram https://leetcode.com/problems/valid-anagram/ Description: Given two strings s and t , write a function to determine if t is an anagram of s. Example 1: Input: s = "anagram", t = "nagaram" Output: true Example 2: Input: s = "rat", t = "car" Output: false Note: You may assume the string contains only lowercase alphabets. ''' class Solution: def isAnagram(self, s: str, t: str) -> bool: dic = {} if len(s) != len(t): return False for i in s: if i in dic.keys(): dic[i] += 1 else: dic[i] = 1 for j in t: if j in dic.keys() and dic[j] != 0: dic[j] -= 1 else: return False return True
45758db3365fc9dc51dd1960173a144a206bc7ce
Passionatecricketer/100-days-code-challenge
/day100/delete linklist.py
2,026
4.28125
4
#class to create structure of the node class node: def __init__(self,data): self.data=data self.next=None #class to perform the operation in linked list class linklist: def __init__(self): self.head=None #Function to insert data in beginning of the list def begin(self,newdata): newnode=node(newdata) newnode.next=self.head self.head=newnode #function for delettion of the node #with first paramater as head and second as node to be deleted def deletenode(self,head,key): #condition to check if head node is the node to be deleted if self.head.data==key: #condition to check if list contains only one node if self.head.next is None: print "Given list contains only one node and the list cannot be empty so terminating the process." #Initializing net node as head node after deletion of head node self.head=self.head.next else: temp=self.head while (temp is not None): if (temp.data==key): break prev=temp temp=temp.next #Condition in key is not present in the list if (temp==None): print "Key not in linked list" prev.next=temp.next temp=None #Function to print the list def printlist(self): temp=self.head while(temp): print temp.data, temp=temp.next #Driver program if __name__ == '__main__': lis=linklist() lis.begin(4) lis.begin(9) lis.begin(5) print "Original list" lis.printlist() print print "List after deletion" #If node to be deleted is 4 lis.deletenode(5,4) lis.printlist() print #If node to be deleted is head node lis.deletenode(5,5) lis.printlist() print #If only one node is left lis.deletenode(9,9) lis.printlist() print
b81a0d3baefd3482c68a0957b82050cf3dd9826c
goaguilar/GoAguilar_CS50_Projects
/goaguilar-cs50-2017-fall-sentimental-caesar/caesar.py
784
3.765625
4
from cs50 import get_string from cs50 import get_int def main(): print("plaintext: ") plaintext = get_string() ciphertext = list(plaintext) print("code: ") code = get_int() for i,plainchar in enumerate(ciphertext): ##for lowercase if (plainchar >= 'a' and plainchar <= 'z'): cipherfunct = (ord(plainchar) + code - 97) % 26 + 97; cipherchar = chr(cipherfunct) ciphertext[i] = cipherchar ##for uppercase if (plainchar >= 'A' and plainchar<= 'Z'): cipherfunct = (ord(plainchar) + code - 65) % 26 + 65; cipherchar = chr(cipherfunct) ciphertext[i] = cipherchar print("ciphertext:" + "".join(ciphertext)) return 0 if __name__ == "__main__": main()
468f2592da5ddd36c19a0637378310f6618d2b8f
Zadigo/my_python_codes
/automation/pdf.py
1,686
3.984375
4
import PyPDF2 from PyPDF2 import PdfFileWriter def decrypt_pdf(path, page=0, password=None): """A simple program that takes a PDF file in order to return the text """ with open(path, 'rb', encoding='utf-8') as f: source_file = PyPDF2.PdfFileReader(f) # The file might require a password. # In which case we need to provide one # for us to be able to read it is_encrypted = source_file.isEncrypted if is_encrypted: if password is not None: source_file.decrypt(password) else: raise TypeError('The file you provided is encrypted with '\ 'a password. Received {password}'.format(password=password)) page = source_file.getPage(0) return page or None def copy_pages(file_names:list, new_file_name, passwords:list=None): """A function that takes PDF files and copies the pages into a new document""" with open(new_file_name, 'wb', encoding='utf-8') as new_file: raw_files = (open(file_name, 'rb', encoding='utf-8') for file_name in file_names if file_name.endswith('pdf')) source_files = (PyPDF2.PdfFileReader(raw_file) for raw_file in raw_files if raw_file) writer = PdfFileWriter() def set_pages(source_file, number_of_pages): """Sets the pages to copy in the new document""" for i in range(0, number_of_pages): page = source_file.getPage(i) writer.addPage(page) for source_file in source_files: set_pages(source_file, source_file.numPages) source_file.close() writer.write(new_file)
6ccc78ca167a52059e9a731bccc5e29629ba1306
LuizVinicius38/03-Quiz
/Desafio_Quiz 3.py
753
4
4
print("Qual é minha comida preferida") resposta = input("").lower() print("Qual a minha cor favorita") respostas = input("").lower() print("Eu prefiro frio ou calor") respost = input("").lower() print("Qual animal que eu mas amo?(escreva em inglês)") res = input("").lower() print("Qual time de futebol eu torço?") re = input("").lower() score = 0 if resposta == "pizza": score = +1 if respostas == "vermelho": score = score + 1 if respost == "frio": score = score + 1 if res == "cat": score = score + 1 if re == "nenhum": score = score + 1 print(f"Você tem {score} pontos") else: print(f"Você tem {score} pontos") if score == 5: print("Muito bem") else: print("Tente novamente")
b405ed976fe440b549fc714ace4a5a1c72ab6421
minjung0/scaffold
/hello.py
75
3.5625
4
def add(x, y): return x+y print(f"This is the sum : 5, 1, {add(5,1)}")
c61da17cf06a737e870ea38da5cf21a375a41c7f
jzdmdxww66666/myedu-1902-
/day03/assert_demo.py
854
3.796875
4
if __name__ == '__main__': ##断言为ture 不会有报错 #assert 4>2 ##断言为false会报错 AssertionError #assert 1>2 ##断言字符串 astr = '的经费和大家回复大家更好地' ##判断astr字符内 是有包含 你 这个字 #assert '你 'in astr ##判断 astr字符内 是否不包含 你 这个字 #assert '你 'not in astr #a=0 ##while语法 : while(当)条件:--> 条件为true 进入循环, 知道 条件为false #while a<5: # print('hellow world') # a+=1 #try用于异常处理;如果出现异常 则执行except内的代码;不会影响后面的代码 继续执行 #应用场景;用于包裹 可能会出错的代码块,出错执行except内的代码, #try: # assert '你' in astr #except: # print('报错了')
1f8a376082760571e7062e67b3ad3e1c30d8e54f
angnicolas/cs50_ai
/tictactoe/tictactoe.py
4,953
4.0625
4
""" Tic Tac Toe Player """ import math X = "X" O = "O" ALPHA = -math.inf BETA = math.inf EMPTY = None def initial_state(): """ Returns starting state of the board. """ return [[EMPTY, EMPTY, EMPTY], [EMPTY, EMPTY, EMPTY], [EMPTY, EMPTY, EMPTY]] def player(board): """ Returns player who has the next turn on a board. # """ vals = sum([1 for row in board for x in row if x != EMPTY]) player = X if vals % 2 == 0 else O return player def actions(board): """ Returns set of all possible actions (i, j) available on the board. """ moves = [(i,j) for i in range(3) for j in range(3) if board[i][j] == EMPTY] return moves def result(board, action): """ Returns the board that results from making move (i, j) on the board. """ p = player(board) i,j = action if board[i][j] != EMPTY: print('board',board) print('action',action) board[i][i] == p print('board',board) raise Exception('Not a playable move') else: board[i][j] = p return board def winner(board): """ Returns the winner of the game, if there is one. """ first_row = board[0][:] second_row = board[1][:] third_row = board[2][:] first_col = [col[0] for col in board] second_col = [col[1] for col in board] third_col = [col[2] for col in board] diag_1 = [board[i][i] for i in range(3)] diag_2 = [board[2-i][2-1] for i in range(3)] data = [first_row,second_row,third_row, first_col,second_col,third_col,diag_1,diag_2] for d in data: if all([x == 'X' for x in d]): return 'X' elif all([x == 'O' for x in d]): return 'O' return None def terminal(board): """ Returns True if game is over, False otherwise. """ if winner(board) != None or [item for row in board for item in row].count(EMPTY) == 0: return True else: return False def utility(board): """ Returns 1 if X has won the game, -1 if O has won, 0 otherwise. """ win = winner(board) if win == 'X': return 1 elif win == '0': return -1 else: return 0 def evaluate_utility(row,value=0.45) -> float: score = 0 if (row[0] and row[1] == 'X' and row[2] == EMPTY) or ( row[1] and row[2] == 'X' and row[0] == EMPTY) or ( row[0] and row[2] == 'X' and row[1] == EMPTY): score += value elif ( row[0] and row[1] == 'O' and row[2] == EMPTY) or ( row[1] and row[2] == 'O' and row[0] == EMPTY) or ( row[0] and row[2] == 'O' and row[1] == EMPTY): score -= value return score def evaluate_utility_board(board): score = 0 first_row = board[0][:] second_row = board[1][:] third_row = board[2][:] first_col = [col[0] for col in board] second_col = [col[1] for col in board] third_col = [col[2] for col in board] diag_1 = [board[i][i] for i in range(3)] diag_2 = [board[2-i][2-1] for i in range(3)] data = [first_row,second_row,third_row, first_col,second_col,third_col,diag_1,diag_2] score = 0 for d in data: score += evaluate_utility(row = d) return score def minimax(board): p = player(board) if p == 'X': best = [(-1,-1),-math.inf] if p == 'O': best = [(-1,-1),math.inf] if terminal(board): score = utility(board) return [(-1,-1),score] for move in actions(board): state = 0 board = result(board,move) score = minimax(board) state +=1 i,j = move board[i][j] = EMPTY score[0] = (i,j) if p == 'X': if score[1] > best[1]: best = score else: if score[1] < best[1]: best = score return best # def minimax_alpha_beta(board,alpha=ALPHA,beta = BETA): def minimax_alpha_beta(board): p = player(board) global ALPHA global BETA if p == 'X': best = [(-1,-1),-math.inf] if p == 'O': best = [(-1,-1),math.inf] if terminal(board): score = utility(board) return [(-1,-1),score] for move in actions(board): print('ALPHA',ALPHA) state = 0 board = result(board,move) score = minimax_alpha_beta(board) state +=1 i,j = move board[i][j] = EMPTY score[0] = (i,j) if p == 'X': if score[1] > best[1]: best = score if best[1] >= BETA: return score if best[1] > ALPHA: ALPHA = best[1] else: if score[1] < best[1]: best = score if best[1] <= ALPHA: return score if best[1] < BETA: BETA = best[1] return best
d35407718a5792ccbfa6e607885dc90d0c7bb3cd
ComSciCtr/vroom
/vroom/utils/generators.py
1,691
4.28125
4
# System imports from random import random, randrange def random_vertex(start, stop): ''' Return a random [x,y,z] value in the range (start, stop).''' return [randrange(start, stop, _int=float) for i in range(3)] def random_color(): ''' Return a random [r,g,b] value in the range (0, 1).''' return [random() for i in range(3)] def random_vertex_generator(n, start=-1.0, stop=1.0): ''' Generator for creating n random vertices. Returns a generator that creates vertex values randomly distributed inside a cube. For example, the following code will generate 10,000 random vertices with values from -100.0 to 100.0: vertices = list(random_vertex_generator(10000, -100.0, 100.0)) n -- number of vertices start -- minimum value for vertex elements stop -- maximum value for vertex elements return -- generator object ''' for i in range(n): yield random_vertex(start, stop) def random_color_generator(n, type='rgb'): ''' Generator for creating n random color values. Returns a generator that creates random color values. Both RGB and greyscale colors can be returned depending on the type specified. To generate 500 RGB color values: colors = list(random_color_generator(500)) To generate 500 greyscale values: colors = list(random_color_generator(500, type='greyscale')) n -- number of color values type -- type of color values (must be either 'RGB' or 'greyscale') return -- generator object ''' if type == 'rgb': for i in range(n): yield random_color() elif type == 'greyscale': for i in range(n): yield random()
299db2665fb0cf5c09d84c19e21de62db7a6c7bb
chongjing001/Python-Basis
/python project/Day3-Python基础语法2/tj_00_test.py
1,901
3.609375
4
# # x = 51561456156 # x = str(x) # x = list(x) # print(x) # # a = "1231556" # print(a[::-1]) def reverse_num(): x = input("请输入要反转的数字") if x == "0": return x elif int(x) > 0: return x[::-1] else: x = -int(x) x = str(x) x = x[::-1] return -int(x) # new_x = reverse_num() # print(new_x) print(2**31) print(-2**31) class Solution: def reverse(self, x): """ :type x: int :rtype: int """ if x > 0 and x < 2**31: x = str(x) x = x[::-1] if int(x) > 2**31: return 0 else: return int(x) elif x < 0 and x >= -(2**31): x = -x x = str(x) x = x[::-1] if -int(x) < -(2**31): return 0 else: return -int(x) else: return 0 reverse_num = Solution() result = reverse_num.reverse(1534236469) print(result) class Solution: def addBinary(self, a, b): """ :type a: str :type b: str :rtype: str """ # if int(a) and int(b) is bin: # # result_bin = 0b(int(a)) + 0b(int(b)) # return str(bin(result_bin)) abc = 0b10101 + 0b10101 print(bin(abc)) class Solution: def addBinary(self, a, b): """ :type a: str :type b: str :rtype: str """ # for j,k in a,b: # if j and k in ["0","1"]: # result_bin = 0bint(a) + 0bint(b) # return str(bin(result_bin)) a = "101010" l = "1110101" # help(int) num = int(a, base=2) print(num) print(bin(42)) a = int('00111000', 2) b = int('10000010', 2) print (bin(a ^ b)) # 设x 是一个整数(16位).若要通过x|y使x低度8位置1,高8位不变,则y的二进制数是
dfa1074cf4bc0665c39a7fb81be2cd8fdfc02cd9
qkrwldnjs89/dojang_python
/UNIT_11_시퀀스 자료형 활용하기/143p_인덱스 생략하기.py
96
3.59375
4
# 인덱스 생략하기 a = list(range(0, 100, 10)) print(a[:7]) print(a[7:]) print(a[:])
4cbe8d449c71a82b4676266d1058f7c7eda9aacd
Slidem/coding-problems
/permutations/permutations.py
459
3.953125
4
def permute(nums): if not nums: return [] permutations = [] for x in nums: remaining = nums.copy() remaining.remove(x) remaining_permutations = permute(remaining) if not remaining_permutations: permutations.append([x]) continue for p in remaining_permutations: p.append(x) permutations.append(p) return permutations print(permute([1, 2, 3]))
6419b19b713a29c89f908b95d63ed26a6d0a90bd
coblan/py2
/try/scin/pad.py
513
3.84375
4
from pandas import Series, DataFrame import pandas as pd obj = Series([4, 7, -5, 3]) sdata = {'Ohio': 35000, 'Texas': 71000, 'Oregon': 16000, 'Utah': 5000} obj3 = Series(sdata) states = ['California', 'Ohio', 'Oregon', 'Texas'] obj4 = Series(sdata, index=states) print(obj4) data = {'state': ['Ohio', 'Ohio', 'Ohio', 'Nevada', 'Nevada'], 'year': [2000, 2001, 2002, 2001, 2002], 'pop': [1.5, 1.7, 3.6, 2.4, 2.9]} frame = DataFrame(data, columns=['year', 'state', 'pop']) print(frame)
8d90d444764b2abe5bf1ae714c37b23ded050e2e
aidanrfraser/CompSci106
/reverse.py
383
3.90625
4
from cisc106 import assertEqual #working with Ben def reverse(alist): """ Reverses a list """ if not alist: return alist else: return reverse(alist[1:]) + [alist[0]] assertEqual(reverse([1, 2, 3]), [3, 2, 1]) assertEqual(reverse([0, 1, 0]), [0, 1, 0]) assertEqual(reverse([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]), [10, 9, 8, 7, 6, 5, 4, 3, 2, 1])
0f51f948f0b9596accbfd72abfe95609aa24dba2
qzwj/learnPython
/learn/基础部分/多线程.py
5,663
4
4
#!/usr/bin/env python3 # -*- coding:utf-8 -*- #多任务可以由多进程完成, 也可以由一个进程内的多个线程完成, 线程是程序的最基本的执行单元 #python提供了: 低级模块_thread, 和高级模块 _threading #启动一个线程就是把一个函数传入并创建Thread实例, 然后调用start()开始执行 import time, threading #默认有一个主线程, 这个函数很清晰 def loop(): print('thread %s is running...' % threading.current_thread().name) n = 0 while n < 5: n += 1 print('thread %s >> %s' % (threading.current_thread().name, n)) #%s可以用作整型 time.sleep(1) print('thread %s ended.' % threading.current_thread().name) print('thread %s is running...' % threading.current_thread().name) t = threading.Thread(target=loop, name='LoopThread') t.start() t.join() print('thread %s ended' % threading.current_thread().name) #Lock # 多线程和多进程最大的不同在于,多进程中,同一个变量,各自有一份拷贝存在于每个进程中,互不影响,而多线程中,所有变量都由所有线程共享,所以,任何一个变量都可以被任何一个线程修改,因此,线程之间共享数据最大的危险在于多个线程同时改一个变量,把内容给改乱了。 import time, threading balance = 0 # def change_it(n): # global balance # balance = balance + n # balance = balance - n # def run_thread(n): # for i in range(100000): # change_it(n) # t1 = threading.Thread(target=run_thread, args=(5,))#后面是参数 # t2 = threading.Thread(target=run_thread, args=(8,)) # t1.start() # t2.start() # t1.join() # t2.join() # print(balance) #balance不一定是0, 原因如下 # 一条语句在CPU执行时是若干条语句 # x = balance + n # balance = x # t1和t2交替执行, 可以顺序会乱 #所以需要上锁, 同时只能一个线程访问 lock = threading.Lock() def change_it(n): global balance balance = balance + n balance = balance - n def run_thread(n): for i in range(100000): lock.acquire() #先获取锁 try: change_it(n) # 这里就可以安全的修改 finally: lock.release() #释放锁 t1 = threading.Thread(target=run_thread, args=(5,))#后面是参数 t2 = threading.Thread(target=run_thread, args=(8,)) t1.start() t2.start() t1.join() t2.join() print(balance) # 当多个线程同时执行lock.acquire()时,只有一个线程能成功地获取锁,然后继续执行代码,其他线程就继续等待直到获得锁为止。 # 获得锁的线程用完后一定要释放锁,否则那些苦苦等待锁的线程将永远等待下去,成为死线程。所以我们用try...finally来确保锁一定会被释放。 # 锁的好处就是确保了某段关键代码只能由一个线程从头到尾完整地执行,坏处当然也很多,首先是阻止了多线程并发执行,包含锁的某段代码实际上只能以单线程模式执行,效率就大大地下降了。其次,由于可以存在多个锁,不同的线程持有不同的锁,并试图获取对方持有的锁时,可能会造成死锁,导致多个线程全部挂起,既不能执行,也无法结束,只能靠操作系统强制终止。 #了解 # 多核CPU # 如果你不幸拥有一个多核CPU,你肯定在想,多核应该可以同时执行多个线程。 # 如果写一个死循环的话,会出现什么情况呢? # 打开Mac OS X的Activity Monitor,或者Windows的Task Manager,都可以监控某个进程的CPU使用率。 # 我们可以监控到一个死循环线程会100%占用一个CPU。 # 如果有两个死循环线程,在多核CPU中,可以监控到会占用200%的CPU,也就是占用两个CPU核心。 # 要想把N核CPU的核心全部跑满,就必须启动N个死循环线程。 # 试试用Python写个死循环: # import threading, multiprocessing # def loop(): # x = 0 # while True: # x = x ^ 1 # for i in range(multiprocessing.cpu_count()): # t = threading.Thread(target=loop) # t.start() # 启动与CPU核心数量相同的N个线程,在4核CPU上可以监控到CPU占用率仅有102%,也就是仅使用了一核。 # 但是用C、C++或Java来改写相同的死循环,直接可以把全部核心跑满,4核就跑到400%,8核就跑到800%,为什么Python不行呢? # 因为Python的线程虽然是真正的线程,但解释器执行代码时,有一个GIL锁:Global Interpreter Lock,任何Python线程执行前,必须先获得GIL锁,然后,每执行100条字节码,解释器就自动释放GIL锁,让别的线程有机会执行。这个GIL全局锁实际上把所有线程的执行代码都给上了锁,所以,多线程在Python中只能交替执行,即使100个线程跑在100核CPU上,也只能用到1个核。 # GIL是Python解释器设计的历史遗留问题,通常我们用的解释器是官方实现的CPython,要真正利用多核,除非重写一个不带GIL的解释器。 # 所以,在Python中,可以使用多线程,但不要指望能有效利用多核。如果一定要通过多线程利用多核,那只能通过C扩展来实现,不过这样就失去了Python简单易用的特点。 # 不过,也不用过于担心,Python虽然不能利用多线程实现多核任务,但可以通过多进程实现多核任务。多个Python进程有各自独立的GIL锁,互不影响。 # 小结 # 多线程编程,模型复杂,容易发生冲突,必须用锁加以隔离,同时,又要小心死锁的发生。 # Python解释器由于设计时有GIL全局锁,导致了多线程无法利用多核。多线程的并发在Python中就是一个美丽的梦。
3d4941e60802680aa19b7795f82e0969b67811d9
brainiacpimp/mystuff
/encryption/utils.py
997
4.125
4
#!/usr/bin/env python3 # utils.py """ Module that holds helper functions. """ import math import string SYMBOLS = string.printable def findModInverse(a, m): """ Returns the modular inverse of a % m, the number x such that a*x % m = 1 This is a function from InventWithPython. :param a: int to find modular inverse of. :param m: int to modular by :return: int if inverse is found or None if no inverse is there """ if math.gcd(a, m) != 1: return None # no mod inverse exists if a & m aren't relatively prime u1, u2, u3 = 1, 0, a v1, v2, v3 = 0, 1, m while v3 != 0: q = u3 // v3 # // is the integer division operator v1, v2, v3, u1, u2, u3 = (u1 - q * v1), (u2 - q * v2), (u3 - q * v3), v1, v2, v3 return u1 % m if __name__ == '__main__': # tests for i in range(1000): print("Mod Inverse of {0} is {1}".format(i, findModInverse(i, len(SYMBOLS)))) print("Working symbols are....\n{}".format(SYMBOLS))
737990eb61fe6f18eebdcd4bab902216cc0576ec
filipo18/-uwcisak-filip-unit3
/numberorder.py
826
4.15625
4
# This program will put numbers defined in array in order # Define the array num = [3, 4, 1, 100, 34, 17, 21, 16] # Set the variable that will check if program is complete or not check = 0 # measure length of the array n = len(num) # looping through the program until numbers are in order while check < 8: # set to numbers in pairs as left and right variable that will be compared for val in range(n - 1): left = num[val] right = num[val + 1] # if first number is smaller than next one move to checking next 2 numbers if left < right: check += 1 # if fist number is bigger than next one switch them elif left > right: num[val] = right num[val+1] = left # Print every step to the user print(*num, sep = ", ")
6e8a9f22a955ff00875a0629a7f88205aa52136b
LindseyAnneHello/New-Project2
/wordjumble_Caldwell.py
1,161
4.53125
5
#Lindsey Caldwell #3/27/17 #Word Jumble #the computer picks a random word and then "jumbles" it #the player has to guess the original word import random #create a sentence of words to choose from WORDS = ("oyster", "river", "high", "school", "is", "cool") #pick one word randomly from the sequence word = random.choice(WORDS) #create a variable to use later to see if the guess is correct correct = word #create a jumbled version of the word jumble="" while word: position = random.randrange(len(word)) jumble += word[position] word = word[:position] + word[(position + 1):] #start the game print( """ Welcome to Word Jumble! Unscramble the letters to make a word. (Press the enter key at the promt to quit.) """ ) print("The jumble is:", jumble) guess = input("\nYour guess: ") while guess != correct and guess !="": print("Sorry, that's not it.") guess = input ("Your guess: ") if guess == correct: print("That's it! You've guessed it!\n") print("Thanks for palying.") input("\n\nPress the enter key to exit.")
4abc5b9f5088458a0684f561a511630833a289ad
Jreamz/100DaysOfCode
/day-3-love-calculator.py
2,062
4.03125
4
## JREAMZ VERSION ## #################### print("Welcome to the Love Calculator!") name1 = input("What is your name? \n") name2 = input("What is their name? \n") lower_name1 = name1.lower() lower_name2 = name2.lower() t_counter = lower_name1.count("t") + lower_name2.count("t") r_counter = lower_name1.count("r") + lower_name2.count("r") u_counter = lower_name1.count("u") + lower_name2.count("u") e_counter = lower_name1.count("e") + lower_name2.count("e") true_total = str(t_counter + r_counter + u_counter + e_counter) l_counter = lower_name1.count("l") + lower_name2.count("l") o_counter = lower_name1.count("o") + lower_name2.count("o") v_counter = lower_name1.count("v") + lower_name2.count("v") e_counter = lower_name1.count("e") + lower_name2.count("e") love_total = str(l_counter + o_counter + v_counter + e_counter) true_love_str = true_total + love_total true_love = int(true_love_str) if true_love <= 10 or true_love > 90: print(f"Your score is {true_love}, you go together like coke and mentos.") elif true_love >= 40 and true_love <= 50: print(f"Your score is {true_love}, you are alright together.") else: print(f"Your score is {true_love}.") ## INSTRUCTOR VERSION ## ######################## print("Welcome to the Love Calculator!") name1 = input("What is your name? \n") name2 = input("What is their name? \n") combined_string = name1 + name2 lower_case_string = combined_string.lower() t = lower_case_string.count("t") r = lower_case_string.count("r") u = lower_case_string.count("u") e = lower_case_string.count("e") l = lower_case_string.count("l") o = lower_case_string.count("o") v = lower_case_string.count("v") e = lower_case_string.count("e") true = t + r + u + e love = l + o + v + e love_score = int(str(true) + str(love)) if (love_score < 10) or (love_score > 90): print (f"Your love score is {love_score}, you go together like coke and mentos.") elif (love_score >= 40) and (love_score <=50): print (f"Your score is {love_score}, you are alright together.") else: print(f"Your score is {love_score}.")
049a568b08c1275221379affff010b2f0598130b
willianflasky/growup
/python/day02/字典.py
666
3.671875
4
#!/usr/bin/env python # coding:utf8 __author__ = "willian" names = { "stu1101": {"name": 'alex', 'age': 22, 'hobbie': 'girl'}, "stu1102": "jack", "stu1103": "rain", } """ # search print(names["stu1101"]['hobbie']) print(names.get('stu1108', 'nobody')) # add names['stu1104'] = ['yy', 32, 'DBA'] # update names['stu1104'][0] = "杨板" print(names["stu1104"][0]) # del names.pop('stu1104', 'nobody') del names['stu1103'] print(names) """ # 效率高 for key in names: print(key, names[key]) # 效率低 for k, v in names.items(): print(k, v) # l = [1,2,3] # print(names.fromkeys(l,[11,22,33])) # 共享内存 # copy and copy.deepcopy()
8c9207a393423a904b286cc881ea6289dbac99ec
vishwanathj/python_learning
/python_hackerrank/BuiltIns/input.py
969
4.15625
4
''' This challenge is only forPython 2. input() In Python 2, the expression input() is equivalent to eval(raw _input(prompt)). Code >>> input() 1+2 3 >>> company = 'HackerRank' >>> website = 'www.hackerrank.com' >>> input() 'The company name: '+company+' and website: '+website 'The company name: HackerRank and website: www.hackerrank.com' Task You are given a polynomial P of a single indeterminate (or variable), x. You are also given the values of x and k. Your task is to verify if P(x) = k. Constraints All coefficients of polynomial P are integers. x and y are also integers. Input Format The first line contains the space separated values of x and k. The second line contains the polynomial P. Output Format Print True if P(x) = k. Otherwise, print False. Sample Input 1 4 x**3 + x**2 + x + 1 Sample Output True Explanation P(1) = 1*pow(3)+1*pow(2)+1+1 = 4 = k Hence, the output is True. ''' x,k=map(int, raw_input().split()) print (k==input())
1244aa3a7cc809f92334f35bdc35a55c79065a9e
jdleo/130
/Project4/Solution1/solution1.py
440
4.03125
4
#!/bin/python3 import sys def introTutorial(V, arr): #enumerate array and iterate through for (index, element) in enumerate(arr): #if current element == V, then return the index if element == V: return index if __name__ == "__main__": V = int(input().strip()) n = int(input().strip()) arr = list(map(int, input().strip().split(' '))) result = introTutorial(V, arr) print(result)
73383aac59d48f325127ec0b83604f7861d9ada6
girishteli/firstrepository
/date time.py
134
3.765625
4
import datetime current=datetime.datetime.now() print("current date & time is ::") print(current.strftime("%Y-%m-%d %H:%M:%S"))
ef4b1f9b167c368dbd47e7bd9c270db6326bc7af
Dervun/Python-at-Stepik
/1/11.5/11.5.py
754
4.3125
4
''' Напишите программу, которая получает на вход три целых числа, по одному числу в строке, и выводит на консоль в три строки сначала максимальное, потом минимальное, после чего оставшееся число. На ввод могут подаваться и повторяющиеся числа. ''' arr = sorted([int(input()) for i in range(3)]) print(arr[2], arr[0], arr[1], sep='\n') #other ''' a = input() b = input() c = input() arr = sorted([a, b, c]) print(arr[2], arr[0], arr[1], sep='\n') ''' ''' arr = sorted([int(input()), int(input()), int(input())]) print(arr[2], arr[0], arr[1], sep='\n') '''
514c79089b0b910f251629a8a27ea1fa783df09b
MattR-GitHub/Python-1
/L6 Input Counter.py
700
3.96875
4
#!/usr/lo#!/usr/local/bin/python3 mywordset2 = set() mydict = {} while True: text = input("Please enter a sentence or type nothing and select Enter to end: ") # intitalize set if not text: # no data entry exit break for punc in ",?;.": # punc out text = text.replace(punc," ") for word in text.lower().split(): # text to words mywordset2.add(word) #add words to set #print(wordset2) mycount =len(mywordset2) mydict[word] = mycount # adds both print (mydict)
5b714b49c4622abe411a299b44e2f1cbfd9b52ee
rajlath/rkl_codes
/BB_PythonDS/backtracking.py
527
3.859375
4
# -*- coding: utf-8 -*- # @Date : 2018-09-06 10:20:42 # @Author : raj lath (oorja.halt@gmail.com) # @Link : Benjamin Baka PythonDSandAlgo Examples # @Version : 1.0.0 def main(): print(bit_str("abc", 3)) def bit_str(s, l): ''' returns a set of permutation ( of a length ) of a string @param str - s @param int - l : length of each element @rets set ''' if l == 1: return s return [ digit + bits for digit in bit_str(s, 1)for bits in bit_str(s, l - 1)] if __name__ == "__main__": main()
fcc0d90c7df9d10dae79e8c464afb8fa88ab809a
Rodrigodebarros17/Livropython
/CAP5/5-22.py
1,205
4.125
4
operacao = input("Digite a operação (+ para soma, - para subtração, * para multiplicação, / para divisão, ^ para potenciação, 0 para sair): ") while operacao != "0": base = int(input("Digite o valor da tabuada: ")) operando = 1 if operacao == "+": while operando <= 10: print(f"{base} + {operando} = {base + operando}") operando += 1 elif operacao == "-": while operando <= 10: print(f"{base} - {operando} = {base - operando}") operando += 1 elif operacao == "*": while operando <= 10: print(f"{base} x {operando} = {base * operando}") operando += 1 elif operacao == "/": while operando <= 10: print(f"{base} / {operando} = {base / operando}") operando += 1 elif operacao == "^": while operando <= 10: print(f"{base} ^ {operando} = {base ** operando}") operando += 1 else: print("Você digitou uma opção de operação incorreta") operacao = input("Digite a operação (+ para soma, - para subtração, * para multiplicação, / para divisão, ^ para potenciação, 0 para sair): ")
c8ce10b1c1c9875bd48d0e0e80e520537b52717b
wghreg/pystudy
/height/heigher-order-function.py
1,282
4.1875
4
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # 高阶函数-小结 # 把函数作为参数传入,这样的函数称为高阶函数,函数式编程就是指这种高度抽象的编程范式。 print(abs(-1)) print(abs) f = abs print("f =", f) print("f(-10) =", f(-10)) # 由于abs函数实际上是定义在import builtins模块中的,所以要让修改abs变量的指向在其它模块也生效,要用import builtins; builtins.abs = 10。 # 既然变量可以指向函数,函数的参数能接收变量,那么一个函数就可以接收另一个函数作为参数,这种函数就称之为高阶函数。 # 例如:一个简单的高阶函数: def add(x, y, f): return f(x) + f(y) print(add(1, -5, abs)) # 6 ''' a = 3 a, b = 1, a print('a=',a,'\n''b=',b) 输出:a= 1 b= 3 如果按正常思维肯定是先将1赋值给a,然后再将a值赋给b,实际上也确实是这样的,但是前面提到这样赋值其实右边相当于一个元组tuple, 而tuple中的元素是不变的,所以后面的b=a中的a相当于t(1)是不变的,是前面a=3就已经确定好的,就是说a, b = 1, a这条语句是先执行右边即先创建一个元组, 然后再是分为两条语句执行的先将1赋值给a,然后将元组中的a赋值给b '''
23abf2cab0794c82f3f26e182502f80b55464f31
daigo0927/ctci-6th
/chap8/Q13_alt2.py
1,247
3.5625
4
class Box: def __init__(self, width, height, depth): self.width = width self.height = width self.depth = depth def is_smaller(self, box_tar): if self.width < box_tar.width and self.height < box_tar.height and self.depth < box_tar.depth: return True else: return False def create_stack(boxes, box_b, offset, stack_map): if offset >= len(boxes): return 0 box_b_new = boxes[offset] height_with_bottom = 0 if box_b is None or box_b_new.is_smaller(box_b): if stack_map[offset] == 0: stack_map[offset] = create_stack(boxes, box_b_new, offset+1, stack_map) stack_map[offset] += box_b_new.height height_with_bottom = stack_map[offset] height_without_bottom = create_stack(boxes, box_b, offset+1, stack_map) return max(height_with_bottom, height_without_bottom) if __name__ == '__main__': boxes = [Box(6, 4, 4), Box(8, 6, 2), Box(5, 3, 3), Box(7, 8, 3), Box(4, 2, 2), Box(9, 7, 3)] boxes = sorted(boxes, key = lambda b: b.height, reverse = True) stack_map = [0]*len(boxes) max_height = create_stack(boxes, None, 0, stack_map) print(f'Max height is {max_height}')
70e3660177db87442a91019a14b235e496862af5
Dallas98/Applet
/Experiment/OrderingSystem/Customer.py
937
3.84375
4
from Experiment.OrderingSystem.Employee import Employee class Customer(object): def __init__(self, customer_name, name_list, number_list): self.__name = customer_name self.__name_list = name_list self.__number_list = number_list def get_customer_name(self): return self.__name def place_order(self, employee, food_name, number): if not isinstance(employee, Employee): print('参数错误') return menu = employee.take_order(food_name, number) self.__name_list.append(food_name) self.__number_list.append(number) return menu def print_order(self): result = [] for i in range(len(self.__name_list)): temp = [] temp.append(self.__name_list[i]) temp.append(':') temp.append(self.__number_list[i]) result.append(''.join(temp)) return result
ea9cb32bf762363ee4887e39125319b56b7cbad3
zxy-zhang/python
/返回值.py
1,819
4.03125
4
def get_formatted_name(first_name,last_name): full_name=first_name+' '+last_name return full_name.title() muician=get_formatted_name('jimi','hendrix') #提供一个变量,用于存储返回的值(这里返回值存储在muicain中) print(muician) def get_formatted_name(first_name,middle_name,last_name): full_name=first_name+' '+middle_name+' '+last_name return full_name.title() muician=get_formatted_name('john','lee','hooker') #只要提供名,中间名,姓,在适当的地方加上空格,将结果转换为首字母大写模式,就可以输出一个人的名字 print(muician) #适用于由中间名和没有中间名的,让实参变为可选的 def get_formatted_name(first_name,last_name,middle_name=''): if middle_name: full_name=first_name+' '+middle_name+' '+last_name else: full_name=first_name+' '+last_name return full_name.title() muician=get_formatted_name('john','lee','hooker') print(muician) muician=get_formatted_name('jimi','hendrix') print(muician) #返回字典 def build_person(first_name,last_name): person={'first':first_name,'last':last_name} return person muician=build_person('jimi','hendrix') print(muician) def build_person(first_name,last_name,age=''): person={'first':first_name,'last':last_name} if age: person['age']=age return person muician=build_person('jimi','hendrix',age=27) print(muician) #结合使用函数和while循环 def get_formatted_name(first_name,last_name): full_name=first_name+' '+last_name return full_name while True: print("\nPlease tell me your name:") print("(enter'q' at any time to quit)") f_name=input("First name:") if f_name=='q': break l_name=input("Last name:") if l_name=='q': break formatted_name=get_formatted_name(f_name,l_name) print("\nHello "+formatted_name+".")
95a7b82043cff001db70cf433bf16d3db12b46c0
afarizap/holbertonschool-machine_learning
/supervised_learning/0x08-deep_cnns/2-identity_block.py
1,665
3.6875
4
#!/usr/bin/env python3 """ 2-identity_block task """ import tensorflow.keras as K def identity_block(A_prev, filters): '''Builds an identity block as described in Deep Residual Learning for Image Recognition (2015) Args: A_prev is the output from the previous layer filters is a tuple or list containing F11, F3, F12, respectively: - F11 is the number of filters in the first 1x1 convolution - F3 is the number of filters in the 3x3 convolution - F12 is the number of filters in the second 1x1 convolution Important: All convolutions inside the inception block use a rectified linear activation (ReLU) Returns: the activated output of the projection block ''' F11, F3, F12 = filters w = K.initializers.he_normal(seed=None) l1 = K.layers.Conv2D(filters=F11, kernel_size=(1, 1), padding="same", kernel_initializer=w)(A_prev) l2 = K.layers.BatchNormalization()(l1) l2 = K.layers.Activation("relu")(l2) l3 = K.layers.Conv2D(filters=F3, kernel_size=(3, 3), padding="same", kernel_initializer=w)(l2) l4 = K.layers.BatchNormalization()(l3) l4 = K.layers.Activation("relu")(l4) l5 = K.layers.Conv2D(filters=F12, kernel_size=(1, 1), padding="same", kernel_initializer=w)(l4) l6 = K.layers.BatchNormalization()(l5) l7 = K.layers.Add()([l6, A_prev]) return K.layers.Activation("relu")(l7)
287721a8ffaf70c408bbe4d34665ccfee9e76b93
Prasanth-G/HackerRank
/Python/Regex_and_Parsing.py
9,467
3.984375
4
######1.Introduction to Regex Module ''' Sample input : 5 1.414 +.5486468 0.5.0 1+1.0 0 Sample output : True True False False False ''' import re for i in range(int(input())): print(bool(re.match("^[\+\-]?\d*\.\d+$",input()))) ######2.re.split() ''' Sample input : .172..16.52.207,172.16.52.117 Sample Output : 172 16 52 207 172 16 52 117 #print only the numbers ''' import re [ print(i) for i in re.split("[.,]",input()) if i] ######3.Group(), Groups() & Groupdict() ''' Sample Input : ..12345678910111213141516171820212223 Sample Output : 1 Explanation .. is the first repeating character, but it is not alphanumeric. 1 is the first (from left to right) alphanumeric repeating character of the string in the substring 111. ''' import re out = re.findall(r'([A-Za-z0-9])\1',input()) if out: print(out[0]) else: print(-1) ######4.Re.findall() & Re.finditer() ''' Sample Input : rabcdeefgyYhFjkIoomnpOeorteeeeet Sample Output : ee Ioo Oeo eeeee Explanation : ee is located between d consonant f and . Ioo is located between k consonant m and . Oeo is located between p consonant r and . eeeee is located between t consonant t and . ''' import re pattern = re.compile(r'[QWRTYPSDFGHJKLZXCVBNMqwrtypsdfghjklzxcvbnm]*([AEIOUaeiou]+)[QWRTYPSDFGHJKLZXCVBNMqwrtypsdfghjklzxcvbnm]') match = pattern.findall(input()) match = [each for each in match if len(each) >= 2] if match: print(*match, sep='\n') else: print("-1") ######5.Re.start() & Re.end() ''' Sample Input : aaadaa aa Sample Output : (0, 1) (1, 2) (4, 5) ''' import re s, k = input(), input() l = list(re.finditer('(?=('+ k +'))',s)) if l: for each in l: print((each.start(),each.end()+len(k)-1)) else: print((-1,-1)) ######6.Regex Substitution ''' Sample Input : 11 a = 1; b = input(); if a + b > 0 && a - b < 0: start() elif a*b > 10 || a/b < 1: stop() print set(list(a)) | set(list(b)) #Note do not change &&& or ||| or & or | #Only change those '&&' which have space on both sides. #Only change those '|| which have space on both sides. Sample Output : a = 1; b = input(); if a + b > 0 and a - b < 0: start() elif a*b > 10 or a/b < 1: stop() print set(list(a)) | set(list(b)) #Note do not change &&& or ||| or & or | #Only change those '&&' which have space on both sides. #Only change those '|| which have space on both sides. ''' import re import functools for i in range(int(input())): print(functools.reduce(lambda x,z: re.sub(z[0],z[1],x),[(r'(?<=\s)\|\|(?=\s)','or'), (r'(?<=\s)&&(?=\s)','and')], input())) ######7.Validating Roman Numerals ''' Sample Input : CDXXI Sample Output : True ''' import re print(bool(re.fullmatch(r'M{0,3}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})',input()))) ######8.Validating Phone numbers ''' Sample Input : 2 9587456281 1252478965 Sample Output : YES NO ''' import re for i in range(int(input())): if re.fullmatch(r'[987][0-9]{9}',input()): print("YES") else: print("NO") ######9.Validating and Parsing email addresses ''' Sample Input : 2 DEXTER <dexter@hotmail.com> VIRUS <virus!@variable.:p> Sample Output : DEXTER <dexter@hotmail.com> Explanation : A valid email address meets the following criteria: => It's composed of a username, domain name, and extension assembled in this format: username@domain.extension => The username starts with an English alphabetical character, and any subsequent characters consist of one or more of the following: alphanumeric characters, -,., and _. => The domain and extension contain only English alphabetical characters. => The extension is 1,2,3 or characters in length. ''' import email.utils import re for i in range(int(input())): name, addr = email.utils.parseaddr(input()) if re.fullmatch(r'[a-zA-Z][\w\-\.]*@[a-zA-Z]+?\.[a-zA-Z]{0,3}', addr): print(email.utils.formataddr((name, addr))) ######10.Hex colour code ''' Sample Input : 11 #BED { color: #FfFdF8; background-color:#aef; font-size: 123px; background: -webkit-linear-gradient(top, #f9f9f9, #fff); } #Cab { background-color: #ABC; border: 2px dashed #fff; } Sample Output : #FfFdF8 #aef #f9f9f9 #fff #ABC #fff ''' import re for i in range(int(input())): line = input() if len(line) and line[0] != '#': output = re.findall('#[0-9A-Fa-f]{6}|#[0-9A-Fa-f]{3}',line) if output: print(*output,sep='\n') ######11.HTML parser - part 1 ''' Sample Input : 2 <html><head><title>HTML Parser - I</title></head> <body data-modal-target class='1'><h1>HackerRank</h1><br /></body></html> Sample Output : Start : html Start : head Start : title End : title End : head Start : body -> data-modal-target > None -> class > 1 Start : h1 End : h1 Empty : br End : body End : html ''' from html.parser import HTMLParser # create a subclass and override the handler methods class MyHTMLParser(HTMLParser): def handle_starttag(self, tag, attrs): print ("Start :", tag) self.print_(attrs) def handle_endtag(self, tag): print ("End :", tag) def handle_startendtag(self, tag, attrs): print ("Empty :", tag) self.print_(attrs) def print_(self,attrs): for each in attrs: print("-> %s > %s"%each) # instantiate the parser and fed it some HTML parser = MyHTMLParser() for i in range(int(input())): parser.feed(input()) ######12.HTML parser - part 2 ''' Sample Input : 4 <!--[if IE 9]>IE9-specific content <![endif]--> <div> Welcome to HackerRank</div> <!--[if IE 9]>IE9-specific content<![endif]--> Sample Output : >>> Multi-line Comment [if IE 9]>IE9-specific content <![endif] >>> Data Welcome to HackerRank >>> Single-line Comment [if IE 9]>IE9-specific content<![endif] ''' from html.parser import HTMLParser class MyHTMLParser(HTMLParser): def handle_comment(self, comment): l = comment.split('\n') if len(l) > 1: print(">>> Multi-line Comment") else: print(">>> Single-line Comment") print(*l, sep='\n') def handle_data(self, data): if data != '\n': print(">>> Data\n%s"%data) html = "" for i in range(int(input())): html += input().rstrip() html += '\n' parser = MyHTMLParser() parser.feed(html) parser.close() ######13.Detect HTML Tags, Attributes and Attribute Value ''' Sample Input : 9 <head> <title>HTML</title> </head> <object type="application/x-flash" data="your-file.swf" width="0" height="0"> <!-- <param name="movie" value="your-file.swf" /> --> <param name="quality" value="high"/> </object> Sample Output : head title object -> type > application/x-flash -> data > your-file.swf -> width > 0 -> height > 0 param -> name > quality -> value > high ''' from html.parser import HTMLParser class myhtmlparser(HTMLParser): def handle_starttag(self, tag, attrs): print(tag) self.print_(attrs) def handle_startendtag(self, tag, attrs): print(tag) self.print_(attrs) def print_(self, attrs): for each in attrs: print("-> %s > %s"%each) html = '' for i in range(int(input())): html = html + input() + '\n' htmlparser = myhtmlparser() htmlparser.feed(html) htmlparser.close() ######14.Validating UID ''' Sample Input : 2 B1CD102354 B1CDEF2354 Sample Output : Invalid Valid ''' import re print(*[ 'Valid ' if not re.search(r'([A-Z0-9a-z]).*\1', text) and re.search(r'[A-Z].*[A-Z]', text) and re.search(r'\d.*\d.*\d', text) and len(text) == 10 else 'Invalid' for text in [input() for i in range(int(input()))]], sep='\n') ######15.Validating Credit Card Numbers ''' Sample Input : 6 4123456789123456 5123-4567-8912-3456 61234-567-8912-3456 4123356789123456 5133-3367-8912-3456 5123 - 3567 - 8912 - 3456 Sample Output : Valid Valid Invalid Valid Invalid Invalid Explanation : A valid credit card from ABCD Bank has the following characteristics: ► It must start with a 4,5 or 6. ► It must contain exactly 16 digits. ► It must only consist of digits (0-9). ► It may have digits in groups of 4 , separated by one hyphen "-". ► It must NOT use any other separator like ' ' , '_', etc. ► It must NOT have 4 or more consecutive repeated digits. ''' import re print(*['Valid' if re.search(r'^[4-6][0-9]{3}\-{0,1}[0-9]{4}\-{0,1}[0-9]{4}\-{0,1}[0-9]{4}$',text) and not re.findall(r'([0-9])\1\1\1',''.join(text.split('-'))) else 'Invalid' for text in [input() for i in range(int(input()))]], sep='\n') ######16.Validating Postal Codes ''' Sample Input : 110000 Sample Output : False Explanation : A postal code P must be a number in the range of (100000, 999999). A postal code P must not contain more than one alternating repetitive digit pair. Alternating repetitive digits are digits which repeat immediately after the next digit. In other words, an alternating repetitive digit pair is formed by two equal digits that have just a single digit between them. ''' import re code = input() print(len(code) == 6 and code.isdigit() and len(re.findall(r'(?=([0-9])\d\1)', code)) <= 1) ######17.Matrix Script ''' Sample Input : 7 3 Tsi h%x i # sM $a #t% ir! Sample Output : This is Matrix# %! ''' import re def func(string): string = string.group(0) return ' '.join([string[0], string[-1]]) m, n = map(int, input().split()) l = [input() for i in range(m)] decoded_str = ''.join([ ''.join([each[i] for each in l]) for i in range(n)]) print(re.sub(r'\w[!@#$%& ]+\w', func, decoded_str))
01624ccf508809a693ca50892692b90cd78126d1
siddhism/leetcode
/array/hash-table/insert-delete-getrandom-o1.py
1,646
4
4
# import time class RandomizedSet(object): def __init__(self): """ Initialize your data structure here. """ self.pos = {} # store index of each value self.nums = [] self.idx = 0 def insert(self, val): """ Inserts a value to the set. Returns true if the set did not already contain the specified element. :type val: int :rtype: bool """ if val in self.pos: return False self.pos[val] = idx self.nums.append(val) self.idx += 1 return True def remove(self, val): """ Removes a value from the set. Returns true if the set contained the specified element. :type val: int :rtype: bool """ if val not in self.pos: return False # here we want to do remove in O(1). so we need to swap last index and current index idx, last = self.pos[val], len(self.nums) - 1 self.nums[idx], self.nums[last] = self.nums[last], self.nums[idx] # now we can pop last element from self.nums self.nums.pop() # update index in pos for the swapped element self.pos[self.nums[idx]] = idx self.pos.pop(val) return True def getRandom(self): """ Get a random element from the set. :rtype: int """ return self.nums[random.randint(0, len(self.nums) - 1)] # Your RandomizedSet object will be instantiated and called as such: # obj = RandomizedSet() # param_1 = obj.insert(val) # param_2 = obj.remove(val) # param_3 = obj.getRandom()
a96e5553ace1fa48eb07deeec10f99827d053ae8
Gam1999/Practice-Python
/RightTriangleDown.py
127
3.734375
4
Input = int(input("Enter the number of rows: ")) i = 0 for i in range(Input): print(' '*((i-1)+1) + "*"*(Input-(i+1)+1))
5666ed93a786969da407cd866814109cd7d41972
TheDycik/algPy
/les1/les_1_task_3.py
1,467
4.25
4
# 3. Написать программу, которая генерирует в указанных пользователем границах: # a. случайное целое число, # b. случайное вещественное число, # c. случайный символ. # Для каждого из трех случаев пользователь задает свои границы диапазона. # Например, если надо получить случайный символ # от 'a' до 'f', то вводятся эти символы. # Программа должна вывести на экран любой символ алфавита от 'a' до 'f' включительно. from random import random i1 = int(input("Введите первое целое число: ")) i2 = int(input("Введите второе целое число: ")) n = int(random() * (i2 - i1 + 1)) + i1 print("Случайное число %d" % n) f1 = float(input("Введите первое вещественное число: ")) f2 = float(input("Введите второе вещественное число: ")) n = random() * (f2 - f1) + f1 print("Случайное число %f" % (round(n, 3))) o1 = ord(input("Введите первый символ: ")) o2 = ord(input("Введите втсорой символ: ")) n = int(random() * (o2 - o1 + 1)) + o1 print("Случайный символ %c" % (chr(n)))
8ddf50c6c620ba96d175825171669405ad79eca2
wzxedu/Recurrent-Autoencoder
/utils/metrics.py
571
3.53125
4
class AverageMeter: """ Class to be an average meter for any average metric like loss, accuracy, etc.. """ def __init__(self): self.value = 0 self.avg = 0 self.sum = 0 self.count = 0 self.reset() def reset(self): self.value = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.value = val self.sum += val * n self.count += n self.avg = self.sum / self.count @property def val(self): return self.avg
3450baf922e78831110470ef18175d6ea85b0d00
KWMalik/py-coursera
/ML/mlclass-ex1/ex1.py
4,132
3.875
4
## Machine Learning Online Class - Exercise 1: Linear Regression # Instructions # ------------ # # This file contains code that helps you get started on the # linear exercise. You will need to complete the following functions # in this exericse: # # warmUpExercise.py # plotData.py # gradientDescent.py # computeCost.py # gradientDescentMulti.py # computeCostMulti.py # featureNormalize.py # normalEqn.py # # For this exercise, you will not need to change any code in this file, # or any other files other than those mentioned above. # # x refers to the population size in 10,000s # y refers to the profit in $10,000s # import pdb ## Initialization from warmUpExercise import * from plotData import * from computeCost import * from gradientDescent import * from mpl_toolkits.mplot3d import axes3d, Axes3D # is there any equivalent to "clear all; close all; clc"? ## ==================== Part 1: Basic Function ==================== # Complete warmUpExercise.py print 'Running warmUpExercise ... ' print '5x5 Identity Matrix: ' print warmUpExercise() print('Program paused. Press enter to continue.') raw_input() ## ======================= Part 2: Plotting ======================= print 'Plotting Data ...' data = loadtxt('ex1data1.txt') X = data[:, 0]; y = data[:, 1] m = len(y) # number of training examples # Plot Data # Note: You have to complete the code in plotData.m firstPlot = plotData(X, y) firstPlot.show() print 'Program paused. Press enter to continue.' raw_input() ## =================== Part 3: Gradient descent =================== print 'Running Gradient Descent ...' X = hstack((ones((m, 1)), vstack(data[:,0]))) # Add a column of ones to x theta = zeros((2, 1)) # initialize fitting parameters # Some gradient descent settings iterations = 1500 alpha = 0.01 # compute and display initial cost computeCost(X, y, theta) # run gradient descent (theta, J_history) = gradientDescent(X, y, theta, alpha, iterations) # print theta to screen print 'Theta found by gradient descent: ' print '%f %f \n' % (theta[0].var(), theta[1].var()) # Plot the linear fit #hold on; # keep previous plot visible plot(vstack(X[:,1]), X.dot(theta), '-') legend(('Training data', 'Linear regression')) # not sure how to avoid overlaying any more plots on this figure - call figure()? # Predict values for population sizes of 35,000 and 70,000 # note this it outputting too many times TODO fix this.... predict1 = array([1, 3.5]) *theta print 'For population = 35,000, we predict a profit of %f\n' % (predict1.var()*10000) predict2 = array([1, 7]) * theta print 'For population = 70,000, we predict a profit of %f\n' % (predict2.var()*10000) print 'Program paused. Press enter to continue.\n' raw_input() ## ============= Part 4: Visualizing J(theta_0, theta_1) ============= print 'Visualizing J(theta_0, theta_1) ...\n' # Grid over which we will calculate J theta0_vals, theta1_vals = meshgrid(linspace(-10, 10, 100),linspace(-1, 4, 100)) # initialize J_vals to a matrix of 0's J_vals = zeros((len(theta0_vals), len(theta1_vals))) # Fill out J_vals for i in range(len(theta0_vals)): for j in range(len(theta1_vals)): t = vstack((theta0_vals[i], theta1_vals[j])) J_vals[i][j] = computeCost(X, y, t) # Because of the way meshgrids work in the surf command, we need to # transpose J_vals before calling surf, or else the axes will be flipped J_vals = J_vals.transpose() # Surface plot fig = figure() ax = Axes3D(fig) #pdb.set_trace() ax.plot_surface(theta0_vals, theta1_vals, J_vals) xlabel('\\theta_0') ylabel('\\theta_1') fig.show() # Contour plot fig = figure() ax = Axes3D(fig) # Plot J_vals as 15 contours spaced logarithmically between 0.01 and 100 ax.contour(theta0_vals, theta1_vals, J_vals, logspace(-2, 3, 20)) xlabel('\\theta_0') ylabel('\\theta_1') fig.show() # TODO want this to be plotted onto firstPlot, but not sure how firstPlot.show() plot(theta[0], theta[1], 'rx', markersize=10, linewidth=2) firstPlot.show() print 'Program paused. Press enter to continue. Note figures will disappear when Python process ends\n' raw_input()
d6d68bbee298e379f45c5a2fdb02af2d9bd0b64a
VasuShashi/Practice-Python
/linkedlist.py
2,350
3.765625
4
from node import Node class UnorderedList: def __init__(self): self.head = None self.tail = None def isEmpty(self): return self.head == None def add(self, val): n = Node(val) n.setNext(self.head) self.tail = self.head self.head = n def size(self): n = self.head count = 0 while not n == None: count+=1 n = n.getNext() return count def search(self,item): n = self.head found = False while not n == None: if n.getData() == item: found = True break else: n = n.getNext() if found: return True else: return False def remove(self, item): curn = self.head prev = None removed = False while curn != None: if curn.getData() != item: prev = curn curn = curn.getNext() else: if curn == self.head: self.head = curn.getNext() elif curn.getNext() == None: prev.setNext(None) else: prev.setNext(curn.getNext()) curn.setNext(None) removed = True return True if curn == None and removed == False: return False def display(self): curn = self.head while curn != None: print ("{}".format(curn.getData())) curn = curn.getNext() def append(self, val): curn = self.head newnode = Node(val) while curn.getNext() != None: curn = curn.getNext() curn.setNext(newnode) self.tail = newnode def fast_append(self,val): newnode = Node(val) if self.head == None: self.head = newnode self.tail = newnode else: lastnode = self.tail lastnode.setNext(newnode) self.tail = newnode mylist = UnorderedList() mylist.add(31) mylist.add(77) mylist.add(17) mylist.add(93) mylist.add(26) mylist.add(54) print("Size is {}".format(mylist.size())) mylist.append(1) mylist.display() mylist.fast_append(23) print("After fast append:") mylist.display()
288445aa9c0e70bc6980cc69fd3ea8458d632ddc
Aasthaengg/IBMdataset
/Python_codes/p02730/s113613633.py
269
3.5625
4
def main(): S = input() L = len(S) def check(s): return s == s[::-1] cond = check(S) cond = cond and check(S[:L // 2]) cond = cond and check(S[(L + 1) // 2:]) print('Yes' if cond else 'No') if __name__ == '__main__': main()
036fc7bc5ec55f5f5042da1c4c67f09e3845fa36
spencergoles/Blackjack
/blackjack.py
4,284
3.5625
4
# Blackjack # By: Spencer Goles @2019 import sys from random import shuffle from time import sleep # 4 suites in a deck is 52 - 4*13 = 52 # In blackjack suite is irrelevant only facevalue is needed deck = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] * 4 # Function shuffles the deck and deals two cards to the hand def deal(deck): hand = [] for x in range(2): shuffle(deck) card = deck.pop() if card == 11: card = "J" if card == 12: card = "Q" if card == 13: card = "K" if card == 14: card = "A" hand.append(card) return hand # Function counts the point total of the hand def countHand(hand): count = 0 for card in hand: if card == "J" or card == "Q" or card == "K": count += 10 elif card == "A" and count >= 11: count += 1 elif card == "A": count += 11 else: count += card return count # Prints player and deal hands and scores def printScores(playerHand, dealerHand): print("\n\nYour hand is " + str(playerHand) + " with a total of " + str(countHand(playerHand))) print("The dealer's hand is " + str(dealerHand) + " with a total of " + str(countHand(dealerHand)) + "\n\n") # Adds card to the hand def hit(hand): card = deck.pop() if card == 11: card = "J" if card == 12: card = "Q" if card == 13: card = "K" if card == 14: card = "A" hand.append(card) return hand # Checks score and outputs game ending def checkScore(playerHand, dealerHand): if countHand(dealerHand) == 21: printScores(playerHand, dealerHand) print("The dealer has a blackjack, better luck next game.") repeatMenu() if countHand(playerHand) == 21: printScores(playerHand, dealerHand) print("You have a blackjack and win!") repeatMenu() if countHand(dealerHand) > 21: printScores(playerHand, dealerHand) print("The dealer has busted, you win!") repeatMenu() if countHand(playerHand) > 21: printScores(playerHand, dealerHand) print("You have busted and the dealer wins.") repeatMenu() if countHand(dealerHand) > countHand(playerHand): printScores(playerHand, dealerHand) print("The dealer has a higher score and wins.") repeatMenu() if countHand(playerHand) > countHand(dealerHand): printScores(playerHand, dealerHand) print("You have a higher score than the dealer and win!") repeatMenu() # Checks for immediate blackjack upon dealing def checkBlackjack(playerHand, dealerHand): if countHand(dealerHand) == 21: printScores(playerHand, dealerHand) print("The dealer has a blackjack, better luck next game.") repeatMenu() if countHand(playerHand) == 21: printScores(playerHand, dealerHand) print("You have a blackjack and win!") repeatMenu() # Runs game logic automatically playing as the dealer def runGame(): playerHand = deal(deck) dealerHand = deal(deck) while True: print("\n\nDealer's Card: ", str(dealerHand[0])) print("Your Cards: " + str(playerHand[0]) + " and " + str(playerHand[1])) checkBlackjack(playerHand, dealerHand) response = input("\nHit or Stay? (H/S)\n\n") if response.lower() == "h": hit(playerHand) while countHand(dealerHand) < 17: hit(dealerHand) checkScore(playerHand, dealerHand) repeatMenu() elif response.lower() == "s": while countHand(dealerHand) < 17: hit(dealerHand) checkScore(playerHand, dealerHand) repeatMenu() else: print("\n\nInvalid Input") # Allows player to play again or exit game def repeatMenu(): print("\n\n\nWould you like to play again? (Y/N)\n\n") response = input() if response.lower() == "y": deck = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] * 4 runGame() if response.lower() == "n": print("\n\nThanks for playing!\n") sleep(1) exit() else: print("\n\nInvalid Input") # Begins program if __name__ == "__main__": print("\nWelcome to Blackjack!\n") runGame()
8228c6ab3569ab9d47bac1e6723a85f26434fefd
1rjun/pythonbasics
/functions.py
178
3.6875
4
def currency(oldnotes): if oldnotes==500 or oldnotes==1000: print("You need to change your currency") else: print("yes currency is valid") currency(1000)
e35352f5cb33f6b721c0b6b7148450586e514412
hari819/python_related_courses
/00.FullSpeedPython/07.Iterators/01.range.py
451
3.796875
4
class MyRange: def __init__(self, a, b): self.a = a self.b = b def __iter__(self):# returns the iterator object itself return self def next(self): if self.a < self.b:# returns the next item in the sequence value = self.a self.a += 1 return value else: raise StopIteration myrange = MyRange(1, 4) print (myrange.next()) print (myrange.next()) print (myrange.next()) ##print (myrange.next())
0169aa865b823ce172ae752f7ad7624c91f83f67
albertsunn/working
/letters_count.py
223
3.671875
4
sentence = list(input("Enter a string: ")) collected = {} for i in range(len(sentence)): if sentence[i] not in collected: collected[sentence[i]] = 1 else: collected[sentence[i]] +=1 print(collected)
4bc2c95438437843f1be7f6f963ebdec8c471430
pruthu-vi/CV-Project2
/circle_shape_detect.py
1,221
3.6875
4
import numpy as np import matplotlib.pyplot as plt import cv2 print('Loaded') # read the image #img = cv2.imread('Resources/test_image.jpg') img = cv2.imread('resources/file-shapes-for-kids-1592568510.jpg') # convert BGR to RGB to be suitable for showing using matplotlib library img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # make a copy of the original image cimg = img.copy() # convert image to grayscale img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # apply a blur using the median filter img = cv2.medianBlur(img, 5) # finds the circles in the grayscale image using the Hough transform circles = cv2.HoughCircles(image=img, method=cv2.HOUGH_GRADIENT, dp=0.9, minDist=80, param1=110, param2=39, maxRadius=70) for co, i in enumerate(circles[0, :], start=1): # draw the outer circle in green cv2.circle(cimg, (i[0], i[1]), int(i[2]), (0, 255, 0), 2) # draw the center of the circle in red cv2.circle(cimg, (i[0], i[1]), 2, (0, 0, 255), 3) # print the number of circles detected print("Number of circles detected:", co) # save the image, convert to BGR to save with proper colors # cv2.imwrite("coins_circles_detected.png", cimg) # show the image plt.imshow(cimg) plt.show()
e41f9757704c33857ad00544d3f2c02a8aa9ec96
PrabuddhaBanerjee/Python
/Chapter3/Ch3P8.py
266
3.9375
4
import math def main(): print("This program is used to figure out the date of Easter") year = eval(input("Please enter an year:")) c = year // 100 epact= (8 + (C // 4) - C + ((80+13) // 25) + 11( year % 19)) % 30 print("Value of epact is ", epact) main()
2f72df61ca0be03efd876f43b4254038bceabf96
Cindylopes17/Premier-TP
/TP/TPEX4.py
1,095
3.90625
4
#Compagnie d'assurance age: int = int(input("Quel age avez-vous?")) permis: int = int(input("Nombre d'années de permis?")) accidents: int = int(input("Nombre d'accidents ?")) annéesAssurance: int = int(input("Nombre d'années d'assurance ?")) Vert: str = "vert" Bleu: str = "bleu" Rouge: str = "rouge" Orange: str = "orange" couleur: str = None if age < 25 and permis < 2 and accidents == 0: couleur = Rouge elif (age < 25 and permis > 2 and accidents == 0) or (age > 25 and permis < 2 and accidents == 0): couleur = Orange if accidents == 1: couleur = Rouge elif age > 25 and permis > 2 and accidents <= 1: if accidents == 1: couleur = Orange else: couleur = Vert else: #accidents == 2: print("Refusé") #if annéesAssurance > 5: #vert devient bleu #Orange devient vert #Rouge devient orange if annéesAssurance > 5: if couleur == Orange: couleur = Vert elif couleur == Rouge: couleur = Orange elif couleur == Vert: couleur = Bleu print(couleur)
4614cb138f8c4bf5a88ff9e7d91ced3e2b98ee0a
JDGC2002/programacion
/Talleres/TallerCondicionalesPunto1.py
631
3.859375
4
#---------CONSTANTES-----# PREGUNTA_A = "¿Cuál es el número A?: " PREGUNTA_B = "¿Cuál es el número B?: " MENSAJE_A_MAYOR = "El número A es mayor al número B" MENSAJE_B_MAYOR = "El número B es mayor al número A" MENSAJE_IGUALES = "Los números son iguales" #---------ENTRADA AL CÓDIGO-----# NumeroA = int(input(PREGUNTA_A)) NumeroB = int(input(PREGUNTA_B)) AreIguales = NumeroA == NumeroB isMayorA = NumeroA > NumeroB isMayorB = NumeroB > NumeroA resultado = "" if (AreIguales): resultado = MENSAJE_IGUALES elif (isMayorA): resultado = MENSAJE_A_MAYOR else: resultado = MENSAJE_B_MAYOR print (resultado)
083b5ece7d805493daad91fe98b8c163509b6a42
AliBeec/TheServer2
/Beec/Checking.py
2,245
3.921875
4
import re EnglishLitters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" ArabicLitters = "اأإبتثجحخدذرزسشصضطظعغفقكلمنهويةلآآلإئءؤ" ArabicNumbers = "1234567890" EnglishLitters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" def RemoveUnwantedChar(inputText:str): result = "" for oneChar in inputText: if oneChar in EnglishLitters or oneChar in ArabicLitters or oneChar in ArabicNumbers: result = result + oneChar return result def onlyNumber(inputStr:str): result = "" for oneChar in inputStr: if oneChar in ArabicNumbers: result = result + oneChar return result def CheckEamilFormat(email:str): regex = '^[\w_.-]+@([\w-]+\.)+\w{2,4}$' if (re.search(regex, email)): return True else: return False def passwordComplexity(password): """ Verify the strength of 'password' Returns a dict indicating the wrong criteria A password is considered strong if: 8 characters length or more 1 digit or more 1 symbol or more 1 uppercase letter or more 1 lowercase letter or more """ # calculating the length length_error = len(password) < 8 # searching for digits digit_error = re.search(r"\d", password) is None # searching for uppercase uppercase_error = re.search(r"[A-Z]", password) is None # searching for lowercase lowercase_error = re.search(r"[a-z]", password) is None # searching for symbols symbol_error = re.search(r"\W", password) is None # overall result password_ok = not ( length_error or digit_error or uppercase_error or lowercase_error or symbol_error ) result = { 'password_ok' : password_ok, 'length_error' : length_error, 'digit_error' : digit_error, 'uppercase_error' : uppercase_error, 'lowercase_error' : lowercase_error, 'symbol_error' : symbol_error } if password_ok == True: return "OK" else: for r in result: if r != "password_ok": if result[r] == True: return r if __name__ == "__main__": print(passwordComplexity("Hdaddoken#6487"))
249bb04ad159c1a07013dba8b8864343f53ba25d
mido1003/atcorder
/152/B.py
101
3.5
4
a,b = (int(x) for x in input().split()) if a > b: print(str(b)*a) else: print(str(a)*b)
bdb583c54c547d8ebf8a0b48f8ceeb26a30b05d5
thiago5171/python.
/exercicios/ex024.py
825
4.15625
4
"""Faça um programa que leia o ano de nascimento de um jovem e informe, de acordo com a sua idade, se ele ainda vai se alistar ao serviço militar, se é a hora exata de se alistar ou se já passou do tempo do alistamento. Seu programa também deverá mostrar o tempo que falta ou que passou do prazo. """ ano = int(input("digite seu ano de nascimento")) idade = 2021 - ano anoa = ano + 18 print("quem nasceu em {} tem {} anos em 2021".format(ano,idade) ) if idade == 18 : print("voce tem que se alistar IMEDIATAMENTE!") elif idade > 18 : alistam = idade - 18 print("voce ja deveria ter se alistado há {} anos".format(alistam)) print("seu alistamento foi em ",anoa) else: alistam = 18 - idade print("faltam {} para seu alistamento".format(alistam)) print("seu alistamneto sera em ",anoa)
cffc9be0bb56436c2168bf6c40c908faa29aad3b
WallysonGalvao/Python
/CursoEmVideo/1 - OneToTen/Challenge008.py
527
4.3125
4
""""Measurement converter""" # Challenge 008 # Write a program that reads a value in meters and displays it converted to centimeters and millimeters. print("Challenge 008") print("Write a program that reads a value in meters and displays it converted to centimeters and millimeters.") distanceInMeters = float(input("A distance in meters: ")) centimeters = distanceInMeters * 100 millimeters = distanceInMeters * 1000 print("The average of {}m corresponds to {}cm and {}mm".format(distanceInMeters, centimeters, millimeters))
b3cf7b4d2573db99cb9ada6127106b1c58e100c3
JosephLevinthal/Research-projects
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/222/users/4067/codes/1643_1055.py
416
3.625
4
# Teste seu código aos poucos. # Não teste tudo no final, pois fica mais difícil de identificar erros. # Use as mensagens de erro para corrigir seu código. from math import* v0 = float(input("velocidade inicial: ")) a = radians(float(input("angulo: "))) d = float(input("distancia: ")) g = 9.8 r = (v0**2 * sin(2*a))/g if d + 0.1 >= r and d - 0.1 <= r: mensagem = "sim" else: mensagem = "nao" print(mensagem)
ab17f5530a005e6a478c246b644420c7e69b6e43
leognon/2048Bots
/2048/simulation.py
4,129
3.859375
4
import random DOWN = 0 RIGHT = 1 UP = 2 LEFT = 3 def made_2d(w, h, val): arr = [] for i in range(w): tempArr = [] for j in range(h): tempArr.append(val) arr.append(tempArr) return arr def flip_arr(arr): new_arr = [] for i in range(len(arr)-1, -1, -1): new_arr.append(arr[i]) return new_arr class Game: def __init__(self): self.board = made_2d(4, 4, 0) self.add_tile() self.add_tile() # Two starting tiles def add_tile(self): available_positions = [] for x in range(4): for y in range(4): if self.board[x][y] == 0: available_positions.append((x, y)) if len(available_positions) > 0: index = random.randint(0, len(available_positions)-1) chosen_position = available_positions[index] amt = 1 if random.random() < .9 else 2 self.board[chosen_position[0]][chosen_position[1]] = amt else: print("No pos found! You lose!") def move(self, direction): # global DOWN # I MIGHT HAVE TO RECOMMENT THIS! new_board = self.board.copy() if direction == DOWN: new_board = self.move_down(new_board) else: new_board = self.rotate_2d((direction + 2) % 4, new_board) new_board = self.move_down(new_board) new_board = self.rotate_2d(direction, new_board) if self.board != new_board: # If there is a change, update it and add a tile self.board = new_board self.add_tile() def rotate_2d(self, direction, board): new_board = made_2d(4, 4, 0) if direction == RIGHT: # Right for x in range(len(board)): for y in range(len(board[0])): new_board[y][3 - x] = board[x][y] elif direction == UP or direction == DOWN: # Up/Down new_board[0] = flip_arr(board[3]) new_board[1] = flip_arr(board[2]) new_board[2] = flip_arr(board[1]) new_board[3] = flip_arr(board[0]) elif direction == LEFT: # Left for x in range(len(board)): for y in range(len(board[0])): new_board[3-y][x] = board[x][y] return new_board def move_down(self, board): new_board = made_2d(4, 4, 0) for x in range(len(board)): prev = -1 lvl = 3 tiles_found = 0 i = len(board[0]) - 1 while i >= 0: # print(f'I: {i}') current = board[x][i] if current > 0: tiles_found += 1 if prev == -1: # Find the lowest (position-wise) tile # print("Set previous") prev = current i -= 1 if i == -1 and tiles_found == 1: # If the only tile is on top row new_board[x][lvl] = current lvl -= 1 else: if current == prev: # Do we have a match? new_board[x][lvl] = current + 1 board[x][i] = 0 lvl -= 1 prev = -1 i -= 1 tiles_found -= 2 # print("Match") else: new_board[x][lvl] = prev # No match! prev = current lvl -= 1 prev = -1 tiles_found -= 2 # print("Not a Match") else: if i == 0 and tiles_found == 1: # We only found one tile! new_board[x][lvl] = prev lvl -= 1 i -= 1 # print("-----------------------------------------") return new_board
8d3ddada32a53f405dc4b94c286dc705c43eed6e
lim-jonguk/ICE_HW3
/임종욱_2.py
249
3.609375
4
# C111152 임종욱 from random import randint a = randint(0,100) b = randint(0,100) c = a + b print(a,' + ', b,'의 값은? ',end=" ") d = int(input()) if c == d: print('맞았습니다.') else : print('틀렸습니다')
7f52d8ae37ef58e61e0e37d0d714a028025ef2cd
johngaitho05/CohMat
/data_structures/LinkedLists/SingleLinkedList.py
12,310
3.78125
4
class InvalidOperationException(Exception): pass class Node: def __init__(self, value): self.info = value self.link = None def _merge(p1, p2): if p1.info <= p2.info: startM = Node(p1.info) p1 = p1.link else: startM = Node(p2.info) p2 = p2.link pM = startM while p1 is not None and p2 is not None: if p1.info <= p2.info: pM.link = p1 p1 = p1.link else: pM.link = p2 p2 = p2.link pM = pM.link if p1 is None: pM.link = p2 else: pM.link = p1 return startM def _merge1(p1, p2): if p1.info <= p2.info: startM = Node(p1.info) p1 = p1.link else: startM = Node(p2.info) p2 = p2.link pM = startM while p1 is not None and p2 is not None: if p1.info <= p2.info: pM.link = Node(p1.info) p1 = p1.link else: pM.link = Node(p2.info) p2 = p2.link pM = pM.link # second list has finished and there are elements remaining in the first list while p1 is not None: pM.link = Node(p1.info) p1 = p1.link pM = pM.link # first list has finished and there are elements remaining in the second list while p2 is not None: pM.link = Node(p2.info) p2 = p2.link pM = pM.link return startM def divide_list(p): q = p.link.link while q is not None and q.link is not None: p = p.link q = q.link.link start2 = p.link p.link = None return start2 class SingleLinkedList: def __init__(self, initial_elements=None): self.start = None if initial_elements is not None: for element in initial_elements: self.insert_at_end(element) def display_list(self): if self.start is None: return [] else: p = self.start lst = [] while p is not None: lst.append(p.info) p = p.link return lst def count_nodes(self): p = self.start n = 0 while p is not None: n += 1 p = p.link return n def search(self, x): position = 1 p = self.start while p is not None: if p.info == x: return position position += 1 p = p.link else: return def insert_in_beginning(self, data): temp = Node(data) temp.link = self.start self.start = temp def insert_at_end(self, data): temp = Node(data) if self.start is None: self.start = temp return p = self.start while p.link is not None: p = p.link p.link = temp def insert_after(self, data, x): p = self.start while p is not None: if p.info == x: break p = p.link if p is None: print(x, "is not in the list") else: temp = Node(data) temp.link = p.link p.link = temp def insert_before(self, data, x): if self.start is None: print("List is empty") return if x == self.start.info: self.insert_in_beginning(data) return p = self.start while p.link is not None: if p.link.info == x: break p = p.link if p.link is None: return else: temp = Node(data) temp.link = p.link p.link = temp def insert_at_position(self, data, k): if k == 1: self.insert_in_beginning(data) return p = self.start i = 1 while i<k-1 and p is not None: p = p.link i+=1 if p is None: raise InvalidOperationException("Index out of range: You can only insert up to position", i) else: temp = Node(data) temp.link = p.link p.link = temp def delete_node(self, x): if self.start is None: return if self.start.info == x: self.delete_first_node() return p = self.start while p.link is not None: if p.link.info == x: break p = p.link if p.link is None: return else: p.link = p.link.link def delete_first_node(self): if self.start is None: return p = self.start self.start = self.start.link return p.info def delete_last_node(self): if self.start is None: return if self.start.link is None: self.start = None return p = self.start while p.link.link is not None: p = p.link p.link = None def reverse_list(self): prev = None p = self.start while p is not None: next = p.link p.link = prev prev = p p = next self.start = prev def bubble_sort_exdata(self): end = None while self.start.link != end: p = self.start while p.link != end: q = p.link if p.info > q.info: p.info, q.info = q.info, p.info p = q end = p def bubble_sort_exlinks(self): end = None while self.start.link != end: r = p = self.start while p.link != end: q = p.link if p.info > q.info: p.link = q.link q.link = p if p != self.start: r.link = q else: self.start = q p, q = q, p r = p p = p.link end = p def has_cycle(self): if self.find_cycle() is None: return False else: return True def find_cycle(self): if self.start is None or self.start.link is None: return False slowR = fastR = self.start while slowR is not None and fastR is not None: slowR = slowR.link fastR = fastR.link.link if slowR == fastR: return slowR return None def remove_cycle(self): c = self.find_cycle() if c is None: return p = c q = c len_cycle = 0 while True: len_cycle += 1 q = q.link if p == q: break len_rem_list = 0 p = self.start while p != q: len_rem_list += 1 p = p.link q = q.link length_list = len_cycle + len_rem_list p = self.start for i in range(length_list-1): p = p.link p.link = None def insert_cycle(self, x): if self.start is None: return p = self.start px = None prev = None while p is not None: if p.info == x: px = p prev = p p = p.link if px is not None: prev.link = px else: return # merge by re-arranging links def merge(self, list2): merge_list = SingleLinkedList() merge_list.start = _merge(self.start, list2.start) return merge_list # merge by creating new list def merge1(self,list2): merge_list = SingleLinkedList() merge_list.start = _merge1(self.start, list2.start) return merge_list def merge_sort(self): self.start = self._merge_sort_rec(self.start) # recursive merge sort def _merge_sort_rec(self, list_start): if list_start is None or list_start.link is None: return list_start start1 = list_start start2 = divide_list(list_start) start1 = self._merge_sort_rec(start1) start2 = self._merge_sort_rec(start2) startM = _merge(start1, start2) return startM def concatenate(self, list2): # appends list2 to the original list1 if self.start is None: self.start = list2.start return if list2.start is None: return p = self.start while p.link is not None: p = p.link p.link = list2.start if __name__ == '__main__': default_values = input('Enter a list of default values(separated ' 'by commas) or press enter to initialize an empty list: ') if default_values != '': my_list = SingleLinkedList([int(value) for value in default_values.split(',')]) else: my_list = SingleLinkedList() while True: print("1.Display List") print("2.Count the number of nodes") print("3.Search for an element") print("4.Insert in an empty list/insert in beginning") print("5.Insert a node at the end of the list") print("6.insert a node after a specified node") print("7.Insert a node before a specified node") print("8.insert a node at a given position") print("9.delete first node") print("10.Delete last node") print("11.delete any node") print("12.reverse the list") print("13.Bubble sort by exchanging data") print("14.Bubble sort by exchanging links") print("15.MergeSort") print("16.Insert Cycle") print("17.Detect Cycle") print("18.remove Cycle") print("19.Quit") option = int(input('Enter your choice: ')) if option == 1: print(my_list.display_list()) elif option == 2: my_list.count_nodes() elif option == 3: user_data = int(input("Enter the element to be searched: ")) position = my_list.search(user_data) if position is not None: print("Element found at position", my_list.search(user_data)) else: print("Element not found") elif option == 4: user_data = int(input("Enter the element to be inserted: ")) my_list.insert_in_beginning(user_data) elif option == 5: user_data = int(input("Enter the element to be inserted: ")) my_list.insert_at_end(user_data) elif option == 6: user_data = int(input("Enter the element to be inserted: ")) x1 = int(input("Enter the element after which to insert: ")) my_list.insert_after(user_data, x1) elif option == 7: user_data = int(input("Enter the element to be inserted: ")) x1 = int(input("Enter the element before which to insert: ")) my_list.insert_before(user_data, x1) elif option == 8: user_data = int(input("Enter the element to be inserted: ")) k1 = int(input("Enter the position at which to insert: ")) my_list.insert_at_position(user_data, k1) elif option == 9: my_list.delete_first_node() elif option == 10: my_list.delete_last_node() elif option == 11: user_data = int(input("Enter the element to be deleted: ")) my_list.delete_node(user_data) elif option == 12: my_list.reverse_list() elif option == 13: my_list.bubble_sort_exdata() elif option == 14: my_list.bubble_sort_exlinks() elif option == 15: my_list.merge_sort() elif option == 16: user_data = int(input("Enter the element at which the cycle has to be to be inserted: ")) my_list.insert_cycle(user_data) elif option == 17: if my_list.has_cycle(): print("List has cycle") else: print("List do not have a cycle") elif option == 18: my_list.remove_cycle() elif option == 19: break else: print("Invalid choice!") print()
bda46b97aa3735b8c31a7040479e86bf542cc7c8
mateusleiteaalmeida/trybe-projects
/Computer-Science/sd-07-project-ting/ting_file_management/queue.py
553
3.578125
4
class Queue: def __init__(self): self.files = list() def __len__(self): return len(self.files) def enqueue(self, value): self.files.append(value) def dequeue(self): if self.files.__len__() == 0: raise IndexError("list index out of range") return self.files.pop(0) def search(self, index): if index not in range(self.__len__()): raise IndexError("list index out of range") return self.files[index] def get_files(self): return self.files
e3b8e077337692eead00f504ab92f00d7adac482
ivoryli/myproject
/class/phase1/day09/code02.py
309
3.78125
4
class Wife: def __init__(self,name,age): self.name = name #缺点:缺乏对象数据的封装,外界可以随意赋值 self.age = age class Wife: def __init__(self,name,age): self.name = name self.__age = age w01 = Wife("芳芳",26) w01 = Wife("铁锤",74)
abe9f3bdb1f8d872f1c96b705bb1e7e89d61e575
chaimleib/intervaltree
/test/intervals.py
3,929
3.515625
4
""" intervaltree: A mutable, self-balancing interval tree for Python 2 and 3. Queries may be by point, by range overlap, or by range envelopment. Test module: utilities to generate intervals Copyright 2013-2018 Chaim Leib Halbert Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from __future__ import absolute_import from intervaltree import Interval from pprint import pprint from random import randint, choice from test.progress_bar import ProgressBar import os try: xrange except NameError: xrange = range try: unicode except NameError: unicode = str def make_iv(begin, end, label=False): if label: return Interval(begin, end, "[{0},{1})".format(begin, end)) else: return Interval(begin, end) def nogaps_rand(size=100, labels=False): """ Create a random list of Intervals with no gaps or overlaps between the intervals. :rtype: list of Intervals """ cur = -50 result = [] for i in xrange(size): length = randint(1, 10) result.append(make_iv(cur, cur + length, labels)) cur += length return result def gaps_rand(size=100, labels=False): """ Create a random list of intervals with random gaps, but no overlaps between the intervals. :rtype: list of Intervals """ cur = -50 result = [] for i in xrange(size): length = randint(1, 10) if choice([True, False]): cur += length length = randint(1, 10) result.append(make_iv(cur, cur + length, labels)) cur += length return result def overlaps_nogaps_rand(size=100, labels=False): l1 = nogaps_rand(size, labels) l2 = nogaps_rand(size, labels) result = set(l1) | set(l2) return list(result) def write_ivs_data(name, ivs, docstring='', imports=None): """ Write the provided ivs to test/name.py. :param name: file name, minus the extension :type name: str :param ivs: an iterable of Intervals :type ivs: collections.i :param docstring: a string to be inserted at the head of the file :param imports: executable code to be inserted before data=... """ def trepr(s): """ Like repr, but triple-quoted. NOT perfect! Taken from http://compgroups.net/comp.lang.python/re-triple-quoted-repr/1635367 """ text = '\n'.join([repr(line)[1:-1] for line in s.split('\n')]) squotes, dquotes = "'''", '"""' my_quotes, other_quotes = dquotes, squotes if my_quotes in text: if other_quotes in text: escaped_quotes = 3*('\\' + other_quotes[0]) text = text.replace(other_quotes, escaped_quotes) else: my_quotes = other_quotes return "%s%s%s" % (my_quotes, text, my_quotes) data = [tuple(iv) for iv in ivs] with open('test/data/{0}.py'.format(name), 'w') as f: if docstring: f.write(trepr(docstring)) f.write('\n') if isinstance(imports, (str, unicode)): f.write(imports) f.write('\n\n') elif isinstance(imports, (list, tuple, set)): for line in imports: f.write(line + '\n') f.write('\n') f.write('data = \\\n') pprint(data, f) if __name__ == '__main__': # ivs = gaps_rand() # write_ivs_data('ivs3', ivs, docstring=""" # Random integer ranges, with gaps. # """ # ) pprint(ivs)
442b818222e83aedb1c899f8b301c224dcb626d8
ICC3103-202110/laboratorio-01-MariM-16
/LABORATORIO_1_MARIN_MARIA.py
3,535
3.921875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Mar 25 00:33:02 2021 @author: mariamarin """ from numpy import * from numpy import random from random import shuffle from tabulate import tabulate import random print ("BIENVENIDO A MEMORICE \n") print('Ingrese el numero de cartas a jugar: ') num_cards=int(input()) score_j1=0 score_j2=0 board=[[row for col in range(2)] for row in range(num_cards)] def Generate_board(board,num_cards): k=[] i=0 j=num_cards-1 for col in range(num_cards): for row in range(2): if i!=num_cards: k.append([i,j]) i+=1 j=j-1 elif i==num_cards: break return k boardfinish=Generate_board(board, num_cards) random.shuffle(boardfinish) for sublist in boardfinish: random.shuffle(sublist) boardx=[["*" for col in range(2)] for row in range(num_cards)] coord=[] for i in range(len(boardx)): c=0 if c!=len(boardx): a=i,c b=i,c+1 j=[a,b] coord.append(j) c+=1 elif c==len(boardx)-1: c=0 i=0 tab=boardx+coord def Choice(coordinates): coordinat=[int(x) for x in coordinates.split(',')] row_num=coordinat[0] col_num=coordinat[1] return coordinat def revelation(choic): x=choic[0] y=choic[1] tab[x][y]=boardfinish[x][y] num=boardfinish[x][y] return tab, num def verification(choic1, choic2,n1,n2): if n1==n2: x=choic1[0] y=choic1[1] tab[x][y]=" " boardfinish[x][y]=" " x=choic2[0] y=choic2[1] tab[x][y]=" " boardfinish[x][y]=" " print("\nSI SON PARES\n") elif n1!=n2: x=choic1[0] y=choic1[1] tab[x][y]="*" x=choic2[0] y=choic2[1] tab[x][y]="*" print("\nNO SON PARES\n") return tab, boardfinish def winer (score_j1,score_j2): if score_j1>score_j2: print ("EL GANADOR ES EL JUGADOR 1, y su puntaje es: ", score_j1,"\n") elif score_j1<score_j2: print("\nEL GANADOR ES EL JUGADOR 2, y su puntaje es: ", score_j2,"\n") elif score_j1==score_j2: print("\nEMPATE\n") return print("FIN") i=1 while len(boardfinish)!=0: print("\n*** TURNO JUGADOR",i,"***\n") print('El tablero se mostrará a continuación como: (carta - coordenada)') print(tabulate(tab),"\n") print("Ingrese la coordenada de la carta que desea ver en formato: 0,1 ") coordinates1=input() choic1=Choice(coordinates1) res1,n1=revelation(choic1) print(tabulate(res1)) print("\nIngrese la coordenada de la carta que desea ver en formato: 0,1 ") coordinates2=input() choic2=Choice(coordinates2) res2,n2=revelation(choic2) if i==1: if n1!=n2: i=2 elif n1==n2: i=1 score_j1+=1 else: i=2 else: if n1!=n2: i=1 elif n1==n2: i=2 score_j2+=1 print(tabulate(res2)) print ("\n*** PUNTAJES ***\n") print("JUGADOR 1: ", score_j1) print("\nJUGADOR 2: ", score_j2) tab,boardfinish=verification(choic1, choic2, n1, n2) if score_j1+score_j2==num_cards: print ("*** TERMINÓ EL JUEGO ***") finish=winer(score_j1,score_j2) print (finish) break
1b8abf77b9e61e5e72263f409a452bb11b0bb5b6
harbm17/snakeGame
/snake.py
4,223
3.8125
4
#snake game tutorial from TokyoEdtech import turtle import time import random delay = 0.1 #score score = 0 highscore = 0 # screen window = turtle.Screen() window.title("Snake Game") window.bgcolor("black") window.setup(width=1250, height=700) window.tracer(0) # snake head snakeHead = turtle.Turtle() snakeHead.speed(0) snakeHead.shape("square") snakeHead.color("green") snakeHead.penup() snakeHead.goto(0,0) snakeHead.direction = "stop" # food food = turtle.Turtle() food.speed(0) food.shape("circle") food.color("red") food.penup() food.goto(0,100) segments = [] # pen pen = turtle.Turtle() pen.speed(0) pen.shape("square") pen.color("white") pen.penup() pen.hideturtle() pen.goto(0, 260) pen.write("Score: 0 High Score: 0" , align="center", font=("Courier", 24, "normal")) # func def goUp(): if snakeHead.direction != "down": snakeHead.direction = "up" def goDown(): if snakeHead.direction != "up": snakeHead.direction = "down" def goLeft(): if snakeHead.direction != "right": snakeHead.direction = "left" def goRight(): if snakeHead.direction != "left": snakeHead.direction = "right" def move(): if snakeHead.direction == "up": y = snakeHead.ycor() snakeHead.sety(y+20) if snakeHead.direction == "down": y = snakeHead.ycor() snakeHead.sety(y-20) if snakeHead.direction == "left": x = snakeHead.xcor() snakeHead.setx(x-20) if snakeHead.direction == "right": x = snakeHead.xcor() snakeHead.setx(x+20) # kybd window.listen() window.onkeypress(goUp, "Up") window.onkeypress(goDown, "Down") window.onkeypress(goLeft, "Left") window.onkeypress(goRight, "Right") # main game loop while True: window.update() # collision w border if snakeHead.xcor()>600 or snakeHead.xcor()<-600 or snakeHead.ycor()>325 or snakeHead.ycor()<-325: time.sleep(1) snakeHead.goto(0, 0) snakeHead.direction = "stop" # hide seg for segment in segments: segment.goto(1000, 1000) # clear seg list segments.clear() # reset score score = 0; pen.clear() pen.write("Score: {} High Score: {}".format(score, highscore) , align="center", font=("Courier", 24, "normal")) # collision of head and food if snakeHead.distance(food) < 20: x = random.randint(-600, 600) y = random.randint(-325, 325) food.goto(x, y) # add segment newSeg = turtle.Turtle() newSeg.speed(0) newSeg.shape("square") newSeg.color("grey") newSeg.penup() segments.append(newSeg) # shorten delay delay -= .001 # increase score score += 10 if score > highscore: highscore = score pen.clear() pen.write("Score: {} High Score: {}".format(score, highscore) , align="center", font=("Courier", 24, "normal")) # move end seg 1st in reverse for index in range(len(segments) - 1, 0, -1): x = segments[index - 1].xcor() y = segments[index - 1].ycor() segments[index].goto(x, y) # move seg 0 to head if len(segments) > 0: x = snakeHead.xcor() y = snakeHead.ycor() segments[0].goto(x, y) move() # check for body collision for segment in segments: if segment.distance(snakeHead) < 20: time.sleep(1) snakeHead.goto(0, 0) snakeHead.direction = "stop" # hide seg for segment in segments: segment.goto(1000, 1000) # clear seg list segments.clear() # reset score score = 0 pen.clear() pen.write("Score: {} High Score: {}".format(score, highscore) , align="center", font=("Courier", 24, "normal")) time.sleep(delay) window.mainloop()
26838ed325263a93b7c48b911ccac8e0e098a7cf
brij2020/Ds-pythonic
/Quiz-Linked-List/Remove_first_elem_add_at_end.py
545
3.6875
4
import Singly_linked_list # Linked List function lis = Singly_linked_list.List() def remove_first(): node = lis.head prev = None while node : prev = node node = node.next pass xnode = lis.head lis.head = xnode.next prev.next = xnode xnode.next = None pass def main(): for x in ['C#','Ruby','Python','Pascal']: lis.createList(x) lis.print_list() remove_first() print('\n-------------\n') lis.print_list() pass if __name__ == '__main__': main()
801887630567cedcb3cbeb8260590f948726f019
wuqunfei/algopycode
/leetcode/editor/en/[155]Min Stack.py
2,026
4
4
# Design a stack that supports push, pop, top, and retrieving the minimum # element in constant time. # # Implement the MinStack class: # # # MinStack() initializes the stack object. # void push(int val) pushes the element val onto the stack. # void pop() removes the element on the top of the stack. # int top() gets the top element of the stack. # int getMin() retrieves the minimum element in the stack. # # # # Example 1: # # # Input # ["MinStack","push","push","push","getMin","pop","top","getMin"] # [[],[-2],[0],[-3],[],[],[],[]] # # Output # [null,null,null,null,-3,null,0,-2] # # Explanation # MinStack minStack = new MinStack(); # minStack.push(-2); # minStack.push(0); # minStack.push(-3); # minStack.getMin(); // return -3 # minStack.pop(); # minStack.top(); // return 0 # minStack.getMin(); // return -2 # # # # Constraints: # # # -2³¹ <= val <= 2³¹ - 1 # Methods pop, top and getMin operations will always be called on non-empty # stacks. # At most 3 * 10⁴ calls will be made to push, pop, top, and getMin. # # Related Topics Stack Design 👍 6046 👎 534 # leetcode submit region begin(Prohibit modification and deletion) from collections import deque class MinStack: def __init__(self): self.deque_data = deque() self.deque_mini = deque() def push(self, val: int) -> None: self.deque_data.append(val) if len(self.deque_mini) == 0 or val <= self.deque_mini[-1]: self.deque_mini.append(val) def pop(self) -> None: val = self.deque_data.pop() if val == self.deque_mini[-1]: self.deque_mini.pop() def top(self) -> int: return self.deque_data[-1] def getMin(self) -> int: return self.deque_mini[-1] # Your MinStack object will be instantiated and called as such: obj = MinStack() obj.push(1) obj.push(2) obj.push(-2) obj.pop() param_3 = obj.top() param_4 = obj.getMin() # leetcode submit region end(Prohibit modification and deletion)
da55eb650fa3ecff2ca63bd0e78c1262bbd2903d
sethmsk88/Bioinformatics
/Week1/find_reverseDNA.py
172
3.828125
4
#Read text file file1 = open("myfile.txt","r") print file1.read() trans = str.maketrans('ATGC', 'TACG') y=file1.translate(trans) y_reversed = y[-1::-1] print(y_reversed)
d8bb120f994e5ced0ac6e01e3f3bb4d629daf9f6
trwhitcomb/euler
/prob104.py
587
3.59375
4
""" Solve Project Euler Problem 104 Pandigital numbers in Fibonacci numbers """ is_pandigital = lambda s: ''.join(sorted(s)) == '123456789' def fib_stream(): a, b = 1L, 1L while True: yield a a, b = b, a+b def solve(): fibs = fib_stream() for i, f in enumerate(fibs): if i % 1000 == 0: print i if i > 329000: s = str(f) first_9 = s[:9] last_9 = s[-9:] if is_pandigital(first_9) and is_pandigital(last_9): print 'Answer is %d' % (i+1) return
b90c33817576430ce31c85b7a60eff39695e14ad
quangngoc/CodinGame
/Python/mars-lander-episode-1.py
433
3.625
4
# https://www.codingame.com/training/easy/mars-lander-episode-1 def solution(): surface_n = int(input()) for i in range(surface_n): land_x, land_y = map(int, input().split()) while True: x, y, h_speed, v_speed, fuel, rotate, power = list(map(int, input().split())) if abs(v_speed) > 36: print(0, min(4, power + 1)) else: print(0, max(0, power - 1)) solution()
6771e00b4a95ff832d819e558594d406971b5c39
15751064254/pythonDemo
/threading/3_join.py
468
3.5625
4
import threading import time def T1_job(): print('T1 start \n') for i in range(10): time.sleep(0.1) print('T1 finish \n') def T2_job(): print('T2 start \n') print('T2 finish \n') def main(): thread_1 = threading.Thread(target = T1_job, name = 'T1') thread_1.start() thread_2 = threading.Thread(target = T2_job, name = 'T2') thread_2.start() thread_1.join() thread_2.join() print('all done \n') if __name__ == '__main__': main()
dd4031a552f1dd301cf755f8d3bcaa9b5e7a43bd
wanchai-saetang/meme-generator
/src/MemeEngine/MemeEngine.py
1,840
3.515625
4
"""Represent meme engine to create meme with quote.""" from PIL import Image, ImageDraw, ImageFont import random import os import textwrap import pathlib class MemeEngine(): """A MemeEngine class for auto generate meme with quote base on directory that is given.""" def __init__(self, directory) -> None: """Create a MemeEngine object to store directory. :param directory: A directory for store meme """ self.directory = directory pathlib.Path(self.directory).mkdir(exist_ok=True) def make_meme( self, img_path: str, body: str, author: str, width=500) -> str: """Make meme base on parameter include img_path, body and author and optional parameter width. param img_path: image for generate meme param body: sentence for meme param author: set author param width: image resize default 500 """ img = Image.open(img_path) ratio = width / float(img.size[0]) height = int(ratio * float(img.size[1])) img = img.resize((width, height), Image.NEAREST) self.path = os.path.join( self.directory, f"{random.randint(0, 100000000)}.jpg") draw = ImageDraw.Draw(img) font = ImageFont.truetype('fonts/MonteCarlo-Regular.ttf', size=35) lines = textwrap.wrap(f"{body}\n- {author}", 20) y_text = height for line in lines: w, h = font.getsize(line) draw.text(((width - w) / 2 + 30, y_text / 2), line, font=font, fill="yellow") draw.text(((width - w) / 2 + 30, y_text / 2 + 30), " ", font=font, fill="yellow") y_text += h img.save(self.path) return self.path
f76e1270fa3273653d92fccb16319e7b1000a766
ian0011/PythonStudy
/estruturas_de_controle/for_2.py
515
3.828125
4
# percorrendo lista, tupla e set palavra = 'paralelepípedo' for letra in palavra: print(letra, end=',') print('Fim') aprovados = ['Rafaela', 'Pedro', 'Renato', 'Maria'] for nome in aprovados: print(nome) for posicao, nome in enumerate(aprovados): print(posicao + 1, nome) dias_semana = ('Domingo', 'Segunda', 'Terça', 'Quarta', 'Quinta', 'Sexta', 'Sábado') for dia in dias_semana: print(f'Hoje é {dia}') for letra in set('muito legal'): print(letra)
ce973afbcdb428927001672e0ebc67453a2cfedd
AkashC96/python_training
/T6.py
750
3.9375
4
# Q1 print('Q1: uppercase using list comprehension ') input_Str= str(input()) print([x for x in input_Str if x.isupper()]) # Q2 print('Q2: Use Zip function') alist=['Smit', 'Jaya', 'Rayyan'] blist=['CSE', 'Networking', 'Operating System'] mydict=dict(zip(alist,blist)) print(mydict) # Q3 print('Q3:') print('Learned about Yield,next and Generators') # Q4 print('Q4: using generators to reverse the string.') inp = 'Consultadd Training' print(inp) print(inp[::-1]) # Q5 print('Q5: example on decorators') def revmethod(txt): return txt[::-1] def lowermethod(txt): return txt.upper() newMethod1= revmethod newMethod2= lowermethod txt='Text String for test' print(newMethod1(txt)) print(newMethod2(txt))
c8f5a59148832b12a56f3008b75f256e4ceaf523
kirihar2/coding-competition
/find_parallel.py
1,559
3.96875
4
##Method 1: Create all rectangles and filter out ones that are not parallel to x ##Method 2: Find all lines parallel to x, then try to find the lines that have the same start and end x values ##Method 3: Find all y values with the same x. Like a bucket for each x value and their counts. set of 2 lines that have same y # with each other is a rectangle parallel to x-axis def choose(n, k): """ A fast way to calculate binomial coefficients by Andrew Dalke (contrib). """ if 0 <= k <= n: ntok = 1 ktok = 1 for t in range(1, min(k, n - k) + 1): ntok *= n ktok *= t n -= 1 return ntok // ktok else: return 0 def find_parallel(points): x_bucket={} for point in points: if point[0] not in x_bucket: x_bucket[point[0]] = {} if point[1] not in x_bucket[point[0]]: x_bucket[point[0]][point[1]] = 1 else: x_bucket[point[0]][point[1]]+=1 x_bucket = [x_bucket[i] for i in x_bucket.keys()] ret = 0 for i in range(len(x_bucket)): curr_x = x_bucket[i] for j in range(i+1,len(x_bucket)): other_x = list(v for v in x_bucket[j]) number_lines_y = 0 for ind in range(len(other_x)): y1 = other_x[ind] if y1 in curr_x: number_lines_y += 1 ret+= choose(number_lines_y,2) return ret points = [[10,20],[10,30],[20,30],[20,40],[20,20],[10,40],[10,50],[20,50]] print(find_parallel(points))
0a138af8b492b06275978151558178d9d8860262
yogeshkhola/python1
/Datastructure/cinema.py
899
3.90625
4
# first elemment is age and 2nd is seats films={ "Finding Dory":[3,5], "Tarzen":[18,5], "Bhaubali":[20,2], "Krish 3":[18,6] } # to maintain the infinite loop while True: choice=input("Which movie would you like to watch? :").strip().title() if choice in films: # pass # chk users age age=int(input("How old are you? :").strip()) if age >= films[choice][0]: # chk enough seats num_seats=films[choice][1] if num_seats > 0: # if films[choice][1>0]: print("Enjoy the show") # num_seats films[choice][1]=films[choice][1]-1 else:` ` print("sry we are sold out") else: print("Baap ko bhej tere bski nhi") else: print("Sorry this movie isn't listed in our show")
0c07e96fa0f943caaff4b9e85b608d276a621a70
spicy-crispy/python
/py4e/exercises/exercise6_5/fileread.py
155
3.734375
4
# Prints each line of a file count = 0 samplefile = open('sample.txt') for i in samplefile: count = count + 1 print(i) print('Line Count:', count)
103db8e8c5eca497360a576b5fa12262e06d63a8
macrdona/UserLogin
/Completed Login App/Hash.py
530
3.765625
4
import hashlib #creating class hash class Hash: #contructor to initialize password def __init__(self, password): self.password = password #return the hash value of the given password '''After the password has been hashed, it is then converted into hexadecimal form. It returns as a string that can be store into the database''' def hashFunction(self, salt): result = hashlib.pbkdf2_hmac('sha256',self.password.encode('utf-8'), salt, 100000).hex() return result
a2fc3ac9e21355322be38cea46e0d77ad1c7b050
AnDsergey13/Bot
/example/ex10_json.py
457
3.796875
4
import json #не использовать модуль pickle!!! data = [ {'a' : 10,'b' : 20,'c' : 30}, {'a' : 100,'b' : 200,'c' : 300}, {'a' : 1000,'b' : 2000,'c' : 3000} ] print(type(data),data) with open('data.json', 'w') as file: data = json.dumps(data) file.write(data) print(type(data),data) with open('data.json') as file: data = file.read() print(type(data),data) data = json.loads(data) print(type(data),data) print(data[2]['a'])
0471ebe82c65e3e89281423bfd48b385c1bf47eb
Saigurram235/Mastering-Python
/Ass4.py
1,184
4.375
4
class Box: def area(self): return self.width * self.height def __init__(self, width, height): self.width = width self.height = height # Create an instance of Box. x = Box(10, 2) # Print area. print(x.area()) ''' Write a program to calculate distance so that it takes two Points (x1, y1) and (x2, y2) as arguments and displays the calculated distance, using Class. ''' # # class Distence: # # def __init__(self, x1, y1, x2, y2): # self.x1 = x1 # self.y1 = y1.x # self.x2 = x2 # self.y2 = y2 # # def length(self): # return (((self.x2 - self.x1)**2) + ((self.y2 - self.y1)**2))**(0.5) # # # x = input().split(' ') # x1 = int(x[0]) # y1 = int(x[1]) # y = input().split(' ') # x2 = int(y[0]) # y2 = int(y[1]) # x = Distence(x1, y1, x2, y2) # print(x.length()) class Point: def __init__(self, x=0, y=0): self.x = x self.y = y def __str__(self): return "x-value: " + str(self.x) + " y-value: " + str(self.y) def __add__(self, other): self.x = self.x+other.x self.y = self.y+other.y return self p1 = Point(3,4) p2 = Point(2,3) print (p1+p2)
f6acd601f877f1e50d2c75843a975b9609403864
daniel-reich/turbo-robot
/BeCSQjqycsY8JadFT_10.py
2,035
4
4
""" Create a **recursive** function that identifies the very first item that has recurred in the string argument passed. It returns the identified item with the index where it **first appeared** and the very next index where it **resurfaced** \- entirely as an object; or an empty object if the passed argument is either `None`, an _empty_ string, or no recurring item exists. ### Examples recur_index("KDXTDATTDD") ➞ {"D": [1, 4]} // D first appeared at index 1, resurfaced at index 4 // though D resurfaced yet again at index 8, it's no longer significant // T appeared and resurfaced at indices 3 and 6 but D completed the cycle first recur_index("AKEDCBERSD") ➞ {"E": [2, 6]} recur_index("DXKETRETXD") ➞ {"E": [3, 6]} recur_index("ABCKPEPGBC") ➞ {"P": [4, 6]} recur_index("ABCDEFGHIJ") ➞ {} recur_index(None) ➞ {} ### Notes * There will be no exceptions to handle, all inputs are strings and string-like objects. You just need to be extra careful on `None`, and _empty_ string inputs to avoid undesirable results. * It is expected from the challenge-takers to come up with a solution using the concept of **recursion** or the so-called **recursive approach**. * You can read on more topics about recursion (see **Resources** tab) if you aren't familiar with it yet or haven't fully understood the concept behind it before taking up this challenge or unless otherwise. * A non-recursive version of this challenge can be found [here](https://edabit.com/challenge/9jhTpvYgTCJyD46hA). """ def recur_index(txt, c='', i=0): if not txt: return {} if i > 0: return txt.find(c, i) cycle = ('', 0, len(txt)) chrs = set() for j, ch in enumerate(txt): if j > cycle[2]: break if not ch in chrs: end = recur_index(txt, ch, j + 1) if end >= 0 and end < cycle[2]: cycle = (ch, j, end) chrs.add(ch) return {cycle[0]: [cycle[1], cycle[2]]} if cycle[0] else {}
13e8ecf4cbd5a978513025bc55891198df20e1b6
tabletenniser/leetcode
/5921_max_path_quality.py
3,882
3.515625
4
''' There is an undirected graph with n nodes numbered from 0 to n - 1 (inclusive). You are given a 0-indexed integer array values where values[i] is the value of the ith node. You are also given a 0-indexed 2D integer array edges, where each edges[j] = [uj, vj, timej] indicates that there is an undirected edge between the nodes uj and vj, and it takes timej seconds to travel between the two nodes. Finally, you are given an integer maxTime. A valid path in the graph is any path that starts at node 0, ends at node 0, and takes at most maxTime seconds to complete. You may visit the same node multiple times. The quality of a valid path is the sum of the values of the unique nodes visited in the path (each node's value is added at most once to the sum). Return the maximum quality of a valid path. Note: There are at most four edges connected to each node. Example 1: Input: values = [0,32,10,43], edges = [[0,1,10],[1,2,15],[0,3,10]], maxTime = 49 Output: 75 Explanation: One possible path is 0 -> 1 -> 0 -> 3 -> 0. The total time taken is 10 + 10 + 10 + 10 = 40 <= 49. The nodes visited are 0, 1, and 3, giving a maximal path quality of 0 + 32 + 43 = 75. Example 2: Input: values = [5,10,15,20], edges = [[0,1,10],[1,2,10],[0,3,10]], maxTime = 30 Output: 25 Explanation: One possible path is 0 -> 3 -> 0. The total time taken is 10 + 10 = 20 <= 30. The nodes visited are 0 and 3, giving a maximal path quality of 5 + 20 = 25. Example 3: Input: values = [1,2,3,4], edges = [[0,1,10],[1,2,11],[2,3,12],[1,3,13]], maxTime = 50 Output: 7 Explanation: One possible path is 0 -> 1 -> 3 -> 1 -> 0. The total time taken is 10 + 13 + 13 + 10 = 46 <= 50. The nodes visited are 0, 1, and 3, giving a maximal path quality of 1 + 2 + 4 = 7. Example 4: Input: values = [0,1,2], edges = [[1,2,10]], maxTime = 10 Output: 0 Explanation: The only path is 0. The total time taken is 0. The only node visited is 0, giving a maximal path quality of 0. Constraints: n == values.length 1 <= n <= 1000 0 <= values[i] <= 108 0 <= edges.length <= 2000 edges[j].length == 3 0 <= uj < vj <= n - 1 10 <= timej, maxTime <= 100 All the pairs [uj, vj] are unique. There are at most four edges connected to each node. The graph may not be connected. ''' from collections import defaultdict class Solution: def maximalPathQuality(self, values, edges, maxTime: int) -> int: adj_matrix = defaultdict(list) for a, b, t in edges: adj_matrix[a].append((b, t)) adj_matrix[b].append((a, t)) # print(adj_matrix) # node, timeLeft, nodes_visited, path_used q = [(0, 0, {0}, set())] res = values[0] while len(q) > 0: node, timeUsed, nodes_visited, path_used = q.pop(0) print(node, timeUsed, nodes_visited, path_used) for next_node, time_cost in adj_matrix[node]: if timeUsed+time_cost <= maxTime: path = (min(node, next_node), max(node, next_node)) new_nodes_visited = set.union(nodes_visited, {next_node}) if next_node == 0 or 2*(timeUsed + time_cost) <= maxTime: value = sum([values[i] for i in list(new_nodes_visited)]) res = max(value, res) if path not in path_used: new_path_used= set.union(path_used, {path}) q.append((next_node, timeUsed+time_cost, new_nodes_visited, new_path_used)) if 2*(timeUsed + time_cost) <= maxTime: new_path_used= set.union(path_used, {path}) q.append((0, 2*(timeUsed+time_cost), new_nodes_visited, new_path_used)) return res s = Solution() values = [0,32,10,43] edges = [[0,1,10],[1,2,15],[0,3,10]] maxTime = 49 res = s.maximalPathQuality(values, edges, maxTime) print(res)
a890e2b834b074b48b470dadc91f02238e898add
nbro/ands
/ands/algorithms/sorting/comparison/heap_sort.py
3,112
4.09375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ # Meta-info Author: Nelson Brochado Created: 09/09/2015 Updated: 19/09/2017 # Description Heap-sort is one of the best sorting methods being in-place and with no quadratic worst-case scenarios. Heap-sort algorithm is divided into two basic parts: 1. Creating a heap from a (possibly) unsorted list, then 2. a sorted list is created by repeatedly removing the largest/smallest element from the heap, and inserting it into the list. The heap is reconstructed after each removal. Heap-sort is somehow slower in practice on most machines than a well-implemented quick-sort, but it has the advantage of a more favorable worst-case O(n * log n) runtime. Heap-sort is an in-place algorithm, but it is not a stable sort. # TODO - Add ASCII animation of a sorting example using heap-sort! # References - https://en.wikipedia.org/wiki/Binary_heap - https://en.wikipedia.org/wiki/Heapsort - http://video.mit.edu/watch/introduction-to-algorithms-lecture-4-heaps-and-heap-sort-14154/ - http://www.studytonight.com/data-structures/heap-sort - https://en.wikipedia.org/wiki/Sorting_algorithm#Stability """ __all__ = ["heap_sort", "build_max_heap", "max_heapify"] def max_heapify(ls: list, heap_size: int, i: int) -> None: """This operation is also sometimes called "push down", "shift_down" or "bubble_down". Time complexity: O(log(n)).""" m = i left = 2 * i + 1 right = 2 * i + 2 if left < heap_size and ls[left] > ls[m]: m = left if right < heap_size and ls[right] > ls[m]: m = right if i != m: ls[i], ls[m] = ls[m], ls[i] max_heapify(ls, heap_size, m) def build_max_heap(ls: list) -> None: """Converts a list ls, which can be thought as a binary tree (not a binary-search tree!) with n = len(ls) nodes, to a list representing a max-heap by repeatedly using max_heapify in a bottom up manner. It is based on the observation that the list of elements indexed by floor(n/2) + 1, floor(n/2) + 2, ..., n are all leaves for the tree (assuming that indices start at 1), thus each is a 1-element heap. It runs max_heapify on each of the remaining tree nodes. For more info see: https://en.wikipedia.org/wiki/Binary_heap#Building_a_heap This algorithm initially proposed by Robert W. Floyd as an improvement to the sub-optimal algorithm to build heaps proposed by the inventor of max-heap and of the heap data structure, that is J. Williams. Time complexity: O(n).""" for i in range(len(ls) // 2, -1, -1): max_heapify(ls, len(ls), i) def heap_sort(ls: list) -> None: """Heap-sort in-place sorting algorithm. Time complexity +-------------+-------------+-------------+ | Best | Average | Worst | +-------------+-------------+-------------+ | O(n*log(n)) | O(n*log(n)) | O(n*log(n)) | +-------------+-------------+-------------+ Space complexity: O(1).""" build_max_heap(ls) for i in range(len(ls) - 1, 0, -1): ls[i], ls[0] = ls[0], ls[i] max_heapify(ls, i, 0)
7b41ad2fad49bb6759dcf61d501224bc51f1f3b3
TimothyRBinding/UniPortfolioV3
/UniPortfolio/ComputerNetworks/CW2/State.py
757
3.515625
4
class State: state = None #abstract class CurrentContext = None def __init__(self, Context): self.CurrentContext = Context class StateContext: stateIndex = 0; CurrentState = None availableStates =[] #availableStates = ["CLOSED", "LISTEN", "SYNSENT", "SYNRECVD", "ESTABLISHED", "FINWAIT1", "CLOSEWAIT", "FINWAIT2", "TIMEDWAIT", "LASTACK",] def setState(self, newstate): self.CurrentState = self.availableStates[newstate] self.stateIndex = newstate def getStateIndex(self): return self.stateIndex ''' States key: CLOSED = 0 LISTEN = 1 SYNSENT = 2 SYNRECVD = 3 ESTABLISHED = 4 FINWAIT1 = 5 CLOSEWAIT = 6 FINDWAIT2 = 7 TIMEDWAIT = 8 LASTACK = 9 '''
9f899133c88e5b284d13f2b286365315132822ca
laferna/python
/Fun_with_Functions.py
1,415
4.8125
5
#Fernandez_Python_Assignment: Fun with Functions #Create a series of functions based on the below descriptions. Odd/Even: #Create a function called odd_even that counts from 1 to 2000. #As your loop executes, print the number of that iteration and specify whether it's an odd or even number. #Your program output should look like below: # Number is 1. This is an odd number. # Number is 2. This is an even number. # Number is 3. This is an odd number. # ... # Number is 2000. This is an even number. >>> def odd_even(): >>> for x in range(1, 2001): ... if x % 2 == 0: ... print x, "is an even number." ... else: ... print x, "is an odd number." ... 1 is an odd number. 2 is an even number. 3 is an odd number. 4 is an even number. ... 2000 is an even number. __________ Multiply: #Create a function called 'multiply' that iterates through each value in a list (e.g. a = [2, 4, 10, 16]) #and returns a list where each value has been multiplied by 5. #The function should multiply each value in the list by the second argument. For example, let's say: #a = [2,4,10,16] #Then: #b = multiply(a, 5) #print b #Should print [10, 20, 50, 80 ]. >>> def multiply(arr, num): ... for x in range(0, len(arr)): ... arr[x] *= num ... return arr ... >>> numbers_array = [3, 6, 8, 10, 67] >>> >>> print multiply(numbers_array, 5) [15, 30, 40, 50, 335] >>>
364fc390558435ae387555cf009ff5ad89192da4
pangyouzhen/data-structure
/contest/reverseList.py
655
3.78125
4
from typing import List class Solution: def permute(self, nums: List[int]) -> List[List[int]]: all_ans = [] one_ans = [] def permute_memo(nums, one_ans): if len(one_ans) == len(nums): all_ans.append(one_ans[:]) for i in nums: if i in one_ans: continue one_ans.append(i) permute_memo(nums, one_ans) one_ans.pop() permute_memo(nums, one_ans) return all_ans if __name__ == '__main__': func = Solution().permute nums = [1, 2, 3] print(func(nums))
f82835be88165ccdcbfdb4f8facaab05a83bea4f
zhengxiang1994/JIANZHI-offer
/test1/demo24.py
1,172
3.78125
4
# -*- coding:utf-8 -*- class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def __init__(self): self.result = [] self.temp = [] # 返回二维列表,内部每个列表表示找到的路径 def FindPath(self, root, expectNumber): # write code here if not root: return self.result self.temp.append(root.val) expectNumber -= root.val if expectNumber == 0 and root.left is None and root.right is None: self.result.append(self.temp[:]) # python2.x deep copy self.FindPath(root.left, expectNumber) self.FindPath(root.right, expectNumber) self.temp.pop(-1) return self.result if __name__ == "__main__": s = Solution() node0 = TreeNode(1) node1 = TreeNode(2) node2 = TreeNode(3) node3 = TreeNode(4) node4 = TreeNode(5) node5 = TreeNode(3) node6 = TreeNode(6) node0.left = node1 node0.right = node2 node1.left = node3 node1.right = node4 node2.left = node5 node2.right = node6 print(s.FindPath(node0, 7))
0b93e8f102c95fae9189001148325937dcb520f9
davide990/IRSW-lab
/PythonApplication1/nltk_ex1.py
3,791
3.8125
4
'''from nltk.book import *''' import nltk import math import numpy def main(): print("hi") ''' Open a text file, tokenize and return an nltk.Text object ''' def open_textfile(fname): f = open(fname, 'r') raw_text = f.read() tokens = nltk.word_tokenize(raw_text) text = nltk.Text(tokens) return text ''' Get the n most common words from a given text text -> nltk.Text object ''' def get_n_most_common_words(text, n): fdist = nltk.FreqDist(text) # creates a frequency distribution from a list most_commons = fdist.most_common(n) return most_commons ''' Remove the n most common words from a given text text -> nltk.Text object ''' def remove_most_common(text, n): # get the frequency distribution for the input text fdist = nltk.FreqDist(text) most_common_words = fdist.most_common(n) most_common = [w[0] for w in most_common_words] ret_text = [word for word in text if word not in most_common] return nltk.Text(ret_text) ''' Remove the n less common words from a given text text -> nltk.Text object ''' def remove_less_common_words(text, n): # get the frequency distribution for the input text fdist = nltk.FreqDist(text) most_common_words = fdist.most_common(len(text)) most_common_words.sort(key=lambda x: x[1]) most_common_words = most_common_words[0:n-1] most_common = [w[0] for w in most_common_words] ret_text = [word for word in text if word not in most_common] return nltk.Text(ret_text) ''' Calculate the shannon information entropy for the specified text, and returns a list of word ordered by information entropy text -> nltk.Text object ''' def calculate_text_entropy(text): # get the frequency distribution for the input text fdist = nltk.FreqDist(text) # get the text lenght words_count = len(set(text)) # initialize the output list, that is, the most relevant words output_list = [] # iterate each word for parola in set(text): # get the word frequency within the text (== Pwi) freq_word = fdist.freq(parola) # calculate the information quantity information = -(freq_word * math.log(freq_word)) # append the couple word-information to the output list output_list.append([parola,information]) # sort the output list by the information quantity in reverse order output_list.sort(key=lambda x: x[1], reverse=True) return output_list def esercizio(text): # get the frequency distribution for the input text fdist = nltk.FreqDist(set(text)) dict = [] for parola in set(text): # get the word frequency within the text dict.append([w,fdist.freq(parola)]) def lexical_diversity(text): return len(set(text)) / len(text) def percentage(count, total): return 100 * (count / total) def jakkard(d1,d2): return len(set(d1).intersection(d2)) / len(set(d1).union(d2)) ''' Calculate the Jakkard distance between all the documents in the input list testi -> list of nltk.Text objects ''' def jakkard_distance(testi): coppie = [[i,j] for i in testi for j in testi] coefficienti = [] for coppia in coppie: j = jakkard(coppia[0],coppia[1]) if(j < 1): coefficienti.append([coppia[0],coppia[1],j]) coefficienti.sort(key=lambda x: x[2]) return coefficienti if __name__ == "__main__": '''main()''' txt = open_textfile('C:\promessi_sposi.txt') cleaned_text = remove_most_common(text, 100) re_cleaned_text = remove_less_common_words(cleaned_text, 100) print(re_cleaned_text) #cleaned = calculate_text_entropy(txt) #print(cleaned) '''lexical_diversity(text3) lexical_diversity(text5) percentage(4,5) percentage(text4.count('a'),len(text4))'''
cc6a6626b17e99079ed2af78acd6d3360be2d84d
JimYin88/ProjectEuler
/Problem036.py
561
3.6875
4
# Created on Jun 2, 2022 # # @author: Jim Yin import time def palin(n): """ :param n: an integer number you are checking whether it is palindrome :return: True if number is palindrome, False otherwise """ return str(n) == str(n)[::-1] def main(): print(sum(i for i in range(1, 10**6) if palin(i) and palin(str(bin(i))[2:]))) if __name__ == '__main__': start_time = time.perf_counter() main() end_time = time.perf_counter() print(f'Time taken = {end_time - start_time} sec') # 872187 # Time taken = 0.5549615 sec
6c3b3ec7b02ac86e7fb389ffb3d86d29c4f06742
KickItAndCode/Algorithms
/LeetCode/FindTheDifference.py
675
3.6875
4
# 389. Find the Difference # Given two strings s and t which consist of only lowercase letters. # String t is generated by random shuffling string s and then add one more letter at a random position. # Find the letter that was added in t. # Example: # Input: # s = "abcd" # t = "abcde" # Output: # e # Explanation: # 'e' is the letter that was added. from collections import defaultdict def findTheDifference(s, t): map = defaultdict(int) for i in range(len(t)): map[t[i]] += 1 for i in range(len(s)): map[s[i]] -= 1 for k, v in map.items(): if v > 0: return k print(findTheDifference("abcd", "abcde")) # "e"
f8989478af137f6833fb830fe3c4e91b3f9142d6
0010abhi/Python201
/assignment10/assign10_1scrapFromUrl.py
619
3.6875
4
from bs4 import BeautifulSoup import urllib2 ## get url from the user print "We will give you 10 href present in the url." url = raw_input("Please enter the url to scrap data:") ## Read Html Data from Url using urllib2 # url = "https://www.reddit.com" print "Url Accepted:", url.strip() url_to_scrap = urllib2.urlopen(url) scrap_html_string = url_to_scrap.read() url_to_scrap.close() ## Converting Html into python tree object structure using BeautifulSoup soup = BeautifulSoup(scrap_html_string,"html.parser") all_a_tags = soup.find_all("a",limit=10) for tag_a in all_a_tags: print tag_a['href'],":",tag_a.next
fc374af7587643a9e9edc4d5ac4b12287c3bb535
jiahenglu/VeblenWedderburn
/NumberSystem.py
1,535
3.734375
4
listoflists = [] list = [] for i in range(0,10): list.append(i) if len(list)>3: list.remove(list[0]) listoflists.append((list, list[0])) def numeric_compare(alist1, alist2): list1 = alist1[0] list2 = alist2[0] for i in range(0,len(list1)): if list1[i] != list2[i]: return list1[i] - list2[i] return 0 def cmp_to_key(mycmp): 'Convert a cmp= function into a key= function' class K: def __init__(self, obj, *args): self.obj = obj def __lt__(self, other): return mycmp(self.obj, other.obj) < 0 def __gt__(self, other): return mycmp(self.obj, other.obj) > 0 def __eq__(self, other): return mycmp(self.obj, other.obj) == 0 def __le__(self, other): return mycmp(self.obj, other.obj) <= 0 def __ge__(self, other): return mycmp(self.obj, other.obj) >= 0 def __ne__(self, other): return mycmp(self.obj, other.obj) != 0 return K list1 = [4,4,8] list2 = [1,2,3] list3 = [1,3,9] alist1 = [list1,-1] alist2 = [list2,1] alist3 = [list3,-7] listoflists = [alist1,alist2,alist3] listoflists.sort(key=cmp_to_key(numeric_compare)) def multiply(onelist,varlist): for i in range(0,len(onelist)): partlist1 = (onelist[i])[0] partlist1.append(varlist[0]) partlist1.sort() (onelist[i])[1] = (onelist[i])[1] * varlist[1] return onelist varlist = [6, 2] n = multiply(listoflists,varlist) print(n)
6690e06f240abe5ccd227f41148814bc5d63dfa9
farihanoor/Codecademy
/Data Science/Python Fundamentals/Python Loops/LIST COMPREHENSION - CODE CHALLENGE/Greater Than Two.py
223
3.75
4
""" Create a new list called greater_than_two, in which an entry at position i is True if the entry in nums at position i is greater than 2. """ nums = [5, -10, 40, 20, 0] greater_than_two = [ item > 2 for item in nums]
be1dc507b17ffb8484ca6077a048841e97781300
Ngwind/PycharmProjects
/practise_20180719/if.py
258
3.703125
4
print("hello world!".center(50, "=")) user_id = input("inter the id,please!\n") user_pwd = input("inter the password,please!\n") if user_id == "xiaoming" and user_pwd == "123456": print("welcome! {}\n".format(user_id)) else: print("error!\n")
d47a13ae0fe6c8de5c90852efe91435be06dafca
redoctoberbluechristmas/100DaysOfCodePython
/Day14 - Higher Lower Game/Day14Exercise1_HigherLowerGame.py
1,390
3.9375
4
import random import art from os import system from game_data import data # Need to select two celebrities def choose_accounts(): return random.choice(data) def format_entry(choice): return f'{choice["name"]}, a {choice["description"]}, from {choice["country"]}' def compare_accounts(player_choice, not_choice): if player_choice["follower_count"] > not_choice["follower_count"]: return -1 else: return 1 score = 0 choice_a = choose_accounts() # Start Loop Here correct_choice = True while correct_choice: print(art.logo) choice_b = choose_accounts() # Make it so you can't compare same things while choice_a == choice_b: choice_b = choose_accounts() print(f"Compare A: {format_entry(choice_a)}") print(art.vs) print(f"Against B: {format_entry(choice_b)}") player_choice = input("Who has more followers? Type 'A' or 'B': ").lower() if player_choice == 'a': player_choice = choice_a not_choice = choice_b elif player_choice == 'b': player_choice = choice_b not_choice = choice_a system("clear") if compare_accounts(player_choice, not_choice) == 1: print(f"Sorry, that's wrong. Final score = {score}") correct_choice = False break else: score += 1 print(f"Correct! Your score is {score}") choice_a = choice_b
67312b3a6300a8ad00d2ec393655b8ec6f8f9c4d
AdamZhouSE/pythonHomework
/Code/CodeRecords/2163/60677/287625.py
455
3.6875
4
answerlist=[] def recursion(degree,list,answer): if answer.__len__()==degree: answerlist.append(answer[:]) return for i in list: answer.append(i) index=list.index(i) list.remove(i) recursion(degree,list,answer) list.insert(index,answer[-1]) answer.pop(-1) x=int(input()) k=int(input()) nums=[i+1 for i in range(x)] recursion(x,nums,[]) print("".join([str(x) for x in answerlist[k]]))
e6159d10ef6fab6b94d0e1eb6ef39d0e27decaaa
slingam00/Introduction_to_Python
/Collection Data Types/Tuple.py
168
4.03125
4
myTuple1 = (1, 2, 3, 4, 5) myTuple2 = ('a', 1, 'b', 2, 'c', 3') # Indexing print(myTuple1[2]) # Result is 3 # Range Indexing print(myTuple1[2:4]) # Result is (3, 4)
26e995195e3a5dba4c138d9742a9c0fb2038ff00
9998546789/firstpart
/python/lesson1/first/Task4.py
274
3.796875
4
value = int(input("Введите число: ")) remainder = value % 10 last_part = value // 10 while last_part > 0: if remainder == 9: break if last_part % 10 > remainder: remainder = last_part % 10 last_part = last_part // 10 print(remainder)
74fd3c26c2f171e2371e9f05998a03d82dd8f014
apoorva9s14/pythonbasics
/CompetetiveProblems/hash_table.py
1,261
4.03125
4
import pprint class Hashtable: def __init__(self, elements): self.bucket_size = 2 self.buckets = [[] for i in range(self.bucket_size)] self._assign_buckets(elements) def _assign_buckets(self, elements): for key, value in elements: hashed_value = hash(key) index = hashed_value % self.bucket_size print(hashed_value,index) self.buckets[index].append((key, value)) def get_value(self, input_key): hashed_value = hash(input_key) index = hashed_value % self.bucket_size bucket = self.buckets[index] for key, value in bucket: if key == input_key: return(value) return None def __str__(self): return pprint.pformat(self.buckets) # here pformat is used to return a printable representation of the object if __name__ == "__main__": capitals = [ ('France', 'Paris'), ('United States', 'Washington D.C.'), ('Italy', 'Rome'), ('Canada', 'Ottawa'), ('A', 'B'), ('C', 'D'), ('E', 'F'), ('G', 'H') ] hashtable = Hashtable(capitals) print(hashtable) print(f"The capital of Italy is {hashtable.get_value('Italy')}")
c79786b93479280b8b1d1357da5e84893143223d
osdmaria/Hacktoberfest-2k20
/projects/Text Adventure Fantasy Game/adventure.py
5,168
3.8125
4
import random # playables class wizard (object): hp = 100 stregth = 12 defence = 12 magic = 30 class warrior (object): hp = 100 stregth = 30 defence = 18 magic = 10 class elf (object): hp = 100 stregth = 20 defence = 18 magic = 18 # enemies class goblin (object): name = "Goblin" hp = 60 stregth = 10 defence = 10 magic = 8 loot = random.randint(0,2) class witch (object): name = "Witch" hp = 90 stregth = 15 defence = 15 magic = 20 loot = random.randint(0,2) class orc (object): name = "Orc" hp = 100 stregth = 20 defence = 18 magic = 10 loot = random.randint(0,2) def death(character): if character.hp < 1: print("YOU DIED!") print(".\n.\n.\n.") exit() # selecting hero def heroselect(): print("select your character: ") selection = input("1. Wizard \n2. Warrior \n3. Elf\n") if selection == "1": character = wizard print("So, you're a warrior!\nYour stats:") print("Health: ", character.hp) print("Health: ", character.stregth) print("Health: ", character.defence) print("Health: ", character.magic) return character elif selection == "2": character = warrior print("So, you're a warrior!\nYour stats:") print("Health: ", character.hp) print("Health: ", character.stregth) print("Health: ", character.defence) print("Health: ", character.magic) return character elif selection == "3": character = elf print("So, you're an Elf!\nYour stats:") print("Health: ", character.hp) print("Health: ", character.stregth) print("Health: ", character.defence) print("Health: ", character.magic) return character else: print("\n Only press 1, 2 or 3\n") heroselect() # spawn enemy def enemyselect(goblin, witch, orc): enemylist = [goblin, witch, orc] encounter = random.randint(0,2) enemy = enemylist[encounter] return enemy #spawn loot def loot(): loot = ["weapon","armor","potion"] lootRate = random.randint(0,2) lootDrop = loot[lootRate] return lootDrop def battleState(): enemy = enemyselect(goblin, witch, orc) print("A wild", enemy.name, "has appeared!") while enemy.hp > 0: action = input("Take action:\n1. Weapon \n2. Magic \n3.Run!\n>> ") ### Option 1 if action == "1": print("You swing your sword, attacking the", enemy.name, " enemy!") hitrate = random.randint(0, 10) if hitrate > 3: enemy.hp = enemy.hp - character.stregth print ("You hit the enemy!\n", enemy.name, "health: ", enemy.hp) if enemy.hp > 0: character.hp = character.hp - (enemy.stregth/character.hp) print("The ", enemy.name, "enemy attacks you! You are hit!") print("You got", character.hp, "health left.\n") death(character) else: if enemy.name == "Goblin": enemy.hp = 60 elif enemy.name == "Witch": enemy.hp = 150 elif enemy.name == "Orc": enemy.hp = 150 print("You have defeated the ", enemy.name, "\nIt dropped an item!") lootDrop = loot() print("You found a", lootDrop) break else: print("You missed your hit!") print("The ", enemy.name, "hits you directly!") character.hp = character.hp - enemy.stregth print("Your health stat is: ", character.hp) death(character) ### Option 2 elif action == "2": print("You cast your spell, attacking the", enemy.name, " enemy!") hitrate = random.randint(0, 10) if hitrate > 3: enemy.hp = enemy.hp - character.magic print ("You hit the enemy!\n", enemy.name, "health: ", enemy.hp) if enemy.hp > 0: character.hp = character.hp - (enemy.magic/character.hp) print("The ", enemy.name, "enemy attacks you! You are hit!") print("You got", character.hp, "health left.\n") death(character) else: if enemy.name == "Goblin": enemy.hp = 60 elif enemy.name == "Witch": enemy.hp = 150 elif enemy.name == "Orc": enemy.hp = 150 print("You have defeated the ", enemy.name, "\nIt dropped an item!") lootDrop = loot() print("You found a", lootDrop) break else: print("You missed your hit!") print("The ", enemy.name, "hits you directly!") character.hp = character.hp - enemy.magic print("Your health stat is: ", character.hp) death(character) ### Option 3 elif action == "3": print("You try to run") hitrate = random.randint(0, 10) if hitrate > 4: print ("You got away!") break else: print ("You fail to escape.") print ("The enemy hits you directly!") character.hp = character.hp - enemy.stregth print("You got", character.hp, "health left.\n") death(character) else: print("Please press: 1, 2 or 3 only.") character = heroselect() battleState()
19aed679c934a30610e1b4f69d818b37e4125559
uamhforever/pyraytrace
/pyraytrace/pyraytrace.py
12,616
3.609375
4
# pylint: disable=invalid-name """ Basic routines for ray tracing To do: * Add lenses and mirrors * Properly document Scott Prahl May 2018 """ import numpy as np import matplotlib.pyplot as plt __all__ = ['Plane', 'Ray', 'Sphere', 'Prism', 'Lens', 'ThinLens'] class Plane: """ A class to help to ray-trace planar objects A plane is defined by the equation: u*x + v*y + w*z + D = 0 where (u,v,w) is a unit normal vector to the plane. """ def __init__(self, xyz=(0, 0, 0), uvw=(0, 0, 1)): """ Args: xyz: array describing any point in the plane uvw: array with the direction cosines for the unit vector normal to the plane """ self.xyz = np.array(xyz) self.uvw = np.array(uvw) self.D = -np.dot(xyz, uvw) def __str__(self): a = "xyz=[%.3f,%.3f,%.3f]" % (self.xyz[0], self.xyz[1], self.xyz[2]) b = "uvw=[%.3f,%.3f,%.3f]" % (self.uvw[0], self.uvw[1], self.uvw[2]) length = np.dot(self.uvw, self.uvw) return a + ", " + b + " norm=%.4f" % length + " D=%f" % self.D def __repr__(self): a = "[%f,%f,%f]" % (self.xyz[0], self.xyz[1], self.xyz[2]) b = "[%f,%f,%f]" % (self.uvw[0], self.uvw[1], self.uvw[2]) return "Plane(" + a + ", " + b + ")" def draw_zy(self, ymin=0, ymax=1, zmin=0, zmax=1): """ Draw representation in the zy-plane (x==0) that lies in the rectangle bounded by ymin,ymax and zmin,zmax Thus v*y + w*z + D = 0 """ if self.uvw[2] != 0: ymn = ymin ymx = ymax zmn = -(self.D + self.uvw[1] * ymin) / self.uvw[2] zmx = -(self.D + self.uvw[1] * ymax) / self.uvw[2] zmn = max(zmin, zmn) zmx = min(zmax, zmx) print(" zy=(%.2f,%.2f), zy=(%.2f,%.2f)" % (zmn, ymn, zmx, ymx)) plt.plot([zmn, zmx], [ymn, ymx], 'k') return if self.uvw[1] != 0: ymn = -(self.D + self.uvw[2] * zmin) / self.uvw[1] ymx = -(self.D + self.uvw[2] * zmax) / self.uvw[1] ymn = max(ymn, ymin) ymx = min(ymx, ymax) zmn = zmin zmx = zmax print(" zy=(%.2f,%.2f), zy=(%.2f,%.2f)" % (zmn, ymn, zmx, ymx)) plt.plot([zmn, zmx], [ymn, ymx], 'k') def distance(self, ray): """ distance from start of ray to plane """ cos_angle = np.dot(ray.uvw, self.uvw) if abs(cos_angle) < 1e-8: return np.inf return -(np.dot(ray.xyz, self.uvw) + self.D) / cos_angle def is_in_plane(self, point): """ return True/False if point is in the plane """ dist = abs(np.dot(point, self.uvw) + self.D) return dist < 1e-6 class Ray: """ A 3D ray specified by a starting point and a set of direction cosines """ def __init__(self, xyz=(0, 0, 0), uvw=(0, 0, 1)): """ Args: xyz: array describing the starting point for the ray uvw: array with the direction cosines """ self.xyz = np.array(xyz) self.uvw = np.array(uvw) def __str__(self): a = "xyz=[%.3f,%.3f,%.3f]" % (self.xyz[0], self.xyz[1], self.xyz[2]) b = "uvw=[%.3f,%.3f,%.3f]" % (self.uvw[0], self.uvw[1], self.uvw[2]) length = np.dot(self.uvw, self.uvw) return a + ", " + b + " norm=%.4f" % length def __repr__(self): a = "[%f,%f,%f]" % (self.xyz[0], self.xyz[1], self.xyz[2]) b = "[%f,%f,%f]" % (self.uvw[0], self.uvw[1], self.uvw[2]) return "Ray(" + a + ", " + b + ")" def reflect_from_plane(self, plane): """ Spencer and Murty equation 46 """ a = np.dot(self.uvw, plane.uvw) out = self.uvw - 2 * a * plane.uvw self.uvw = out def move(self, d, draw_zy=False): """ Spencer and Murty equation 5 """ dest = self.xyz + d * self.uvw if draw_zy: # vertical is y and horizontal is z plt.plot([self.xyz[2], dest[2]], [self.xyz[1], dest[1]], 'b') self.xyz = dest def refract(uvw, normal, ni, nt): """ Spencer and Murty, equation 36 """ cosine = np.dot(normal, uvw) if cosine < 0: cosine *= -1 normal *= -1 refractive_index = nt/ni a = refractive_index * cosine b = refractive_index ** 2 - 1 disc = a ** 2 - b if disc < 0: # reflected out = uvw - 2 * cosine * normal else: g = -a + np.sqrt(disc) out = refractive_index * uvw + g * normal return out class Sphere: """ A class to help to ray-trace spherical objects A sphere is defined by the equation: (x-x0)**2 + (y-y0)**2 + (z-z0)**2 = R**2 where (x0,y0,z0) is the center of the sphere and R is the radius """ def __init__(self, xyz=(0, 0, 0), R=1.0, n=1.0): """ Args: xyz: array describing the center of the sphere in cartesian coordinates R: radius of the sphere n: index of refraction of the sphere """ self.xyz = np.array(xyz) self.radius = R self.n = n def __str__(self): a = "center=[%.3f,%.3f,%.3f]" % (self.xyz[0], self.xyz[1], self.xyz[2]) b = ", radius = %f" % self.radius return a + b def __repr__(self): a = "[%f,%f,%f]" % (self.xyz[0], self.xyz[1], self.xyz[2]) return "Sphere(" + a + ", %f" % self.radius + ")" def draw_zy(self, ymax=np.inf, side='both'): """ Draw representation in the zy-plane """ RR = np.sqrt(self.radius**2 - self.xyz[0]**2) yy = min(ymax, RR) y = np.linspace(-yy, yy, 50) r = RR**2 - (y - self.xyz[1])**2 np.place(r, r < 0, 0) z = np.sqrt(r) if side == 'both' or side == 'right': plt.plot(z + self.xyz[2], y, 'k') if side == 'both' or side == 'left': plt.plot(-z + self.xyz[2], y, 'k') def unit_normal_at(self, point): """ Return outward normal to point on sphere """ diff = point - self.xyz mag = np.sqrt(np.dot(diff, diff)) return diff / mag def distance(self, ray): """ Return the nearest positive distance of a ray to the sphere """ OS = ray.xyz - self.xyz b = 2 * np.dot(ray.uvw, OS) c = np.dot(OS, OS) - self.radius * self.radius disc = b * b - 4 * c if disc < 0: return np.inf disc = np.sqrt(disc) d1 = (-b - disc) / 2 d2 = (-b + disc) / 2 if d1 > 1e-6: return d1 if d2 > 1e-6: return d2 return np.inf def refract(self, ray, outside=True): """ Spencer and Murty, equation 36 """ normal = self.unit_normal_at(ray.xyz) if outside: return refract(ray.uvw, normal, 1, self.n) return refract(ray.uvw, normal, self.n, 1) class Prism: """ A class to help to ray-trace through prisms A prism is defined by three planes """ def __init__(self, A, B, C, n): """ Args: A: plane object for first side B: plane object for second side C: plane object for third side """ self.A = A self.B = B self.C = C self.n = n def __str__(self): return self.A.__str__() + '\n' + self.B.__str__() + '\n' + self.C.__str__() def __repr__(self): return self.A.__repl__() + self.B.__repl__() + self.C.__repl__() def draw_zy(self, ymin=0, ymax=1, zmin=0, zmax=1): """ Draw representation in the zy-plane each plane satisfies u*x + v*y + w*z + D = 0. In the zy-plane x==0 therefore v*y + w*z + D = 0 the corners (y,z) can be found by solving v1*y + w1*z + D1 = 0 v2*y + w2*z + D2 = 0 y = -(D1*w2-D2*w1)/(w2*v1-w1*v2) z = (D1*v2-D2*v1)/(w2*v1-w1*v2) """ denom = self.B.uvw[2]*self.A.uvw[1]-self.A.uvw[2]*self.B.uvw[1] y1 = -(self.A.D*self.B.uvw[2]-self.B.D*self.A.uvw[2])/denom z1 = -(self.A.D*self.B.uvw[1]-self.B.D*self.A.uvw[1])/denom self.A.draw_zy(ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax) self.B.draw_zy(ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax) self.C.draw_zy(ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax) def unit_normal_at(self, point): """ Return outward normal to point on prism """ if self.A.is_in_plane(point): return self.A.uvw if self.B.is_in_plane(point): return self.B.uvw if self.C.is_in_plane(point): return self.C.uvw # need to fail here return np.array([0, 0, 0]) def distance(self, ray): """ Return the nearest positive distance of a ray to a prism face """ d1 = self.A.distance(ray) d2 = self.B.distance(ray) d3 = self.C.distance(ray) dd = np.array([d1, d2, d3]) np.place(dd, dd <= 1e-6, 999) # print("side 1 d=%.3f\n"%dd[0]) # print("side 2 d=%.3f\n"%dd[1]) # print("side 3 d=%.3f\n"%dd[2]) return min(dd) def refract(self, ray, outside): """ Spencer and Murty, equation 36 """ normal = self.unit_normal_at(ray.xyz) if outside: return refract(ray.uvw, normal, 1, self.n) return refract(ray.uvw, normal, self.n, 1) class Lens: """ A class to help to ray-trace through a lens A lens is defined by two surfaces """ def __init__(self, surface1, surface2, refractive_index, thickness): """ Args: surface1: first surface surface2: second surface refractive_index: index of refraction d: thickness of lens """ self.surface1 = surface1 self.surface2 = surface2 self.refractive_index = refractive_index self.thickness = thickness def __str__(self): a = str(self.surface1) b = str(self.surface2) c = "refractive index = %f" % self.refractive_index d = "thickness = %f" % self.thickness return a + "\n" + b + "\n" + c + "\n" + d def __repr__(self): a = repr(self.surface1) b = repr(self.surface2) c = ", %f, %f)" % (self.refractive_index, self.thickness) return "Lens(" + a + "," + b + c def distance(self, ray, which_surface): """ Distance to surface """ if which_surface == 1: return self.surface1.distance(ray) return self.surface2.distance(ray) def refract(self, ray, which_surface): """ Bend light at surface """ if which_surface == 1: return self.surface1.refract(ray, 1/self.refractive_index) return self.surface2.refract(ray, self.refractive_index) def draw_zy(self): """ Draw representation in the zy-plane """ self.surface1.draw_zy(side='left') self.surface2.draw_zy(side='right') class ThinLens: """ A class for a thin lens """ def __init__(self, focal_length, vertex, diameter=10): """ Args: vertex: first surface f: focal length diameter: diameter of lens """ self.f = focal_length self.vertex = vertex self.diameter = diameter def __str__(self): a = "focal length = %f" % self.f b = "vertex = %f" % self.vertex c = "diameter = %f" % self.diameter return a + "\n" + b + "\n" + c def __repr__(self): return "ThinLens(%f, %f, diameter=%f)" % (self.f, self.vertex, self.diameter) def distance(self, ray): """ Distance to the lens """ z0 = ray.xyz[2] z1 = self.vertex w = ray.uvw[2] if w == 0: return np.inf return (z1-z0)/w def refract(self, ray): """ Bend light at surface """ w = ray.uvw[2] yf = self.f/w y0 = ray.xyz[1] return self.f/np.sqrt((yf-y0)**2+self.f**2) def draw_zy(self): """ Draw representation in the zy-plane """ plt.plot([self.vertex, self.vertex], [-self.diameter/2, self.diameter/2], ':r')