blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
e182a243d3428d98f2d1a22cc1ac6da2c6810bb3
gitsoftsun/shiyanlou-code
/jump7.py
86
3.578125
4
for x in range(1,101): if x % 7 == 0 or str(x).find('7') != -1: continue print(x)
dff2131704daeff800788fb4abcf855f01e101ee
abhishek111222/Data-Science-Project
/Models/stacker/data.py
1,040
3.796875
4
import pandas as pd #importing the UK dataset dataset = pd.read_csv("dataset.csv") dataset.set_index("date", inplace = True) #printing a tick tick = u'\2713' #This is to check with the dataset with all the features in case required check = pd.read_csv("dataset.csv") check.set_index("date", inplace = True) str='''The accepted features are : \n1. Hospital patients \n2. New tests \n3. Positive Rate \n4. New vaccinations \n5. Reproduction rate ''' print(str) print("Rest all the features will be dropped.") features = ["hosp_patients", "new_tests", "positive_rate", "new_vaccinations", "reproduction_rate", "Mortality_Rate"] print() print(f"The passed features are : {dataset.columns}") print() dataset = dataset[features] print("First 5 elements after deleting the unwanted features : ") print("-"*100) print(dataset.head()) print("-"*100) print() print("The data is already pre - processed and hence should not have any missing values") print(dataset.isna().sum()) print("No null values " u'\u2713') #20 lines of code for now.
e3f7c87ada45cbc77a675eed12917d9229d341f8
mayurpai/The-Joy-of-Computing-using-Python
/Week 6/Assignment3.py
537
3.96875
4
# Programming Assignment 3: Lower Triangular Matrix n=int(input()) matrix=[] for i in range(n): for j in range(1): ele=[int(a) for a in input().split()] matrix.append(ele) for i in range(n): for j in range(n): if i<j: if j==n-1: print(0,end="") else: print(0,end=" ") else: if j==n-1: print(matrix[i][j],end="") else: print(matrix[i][j],end=" ") if i!=n-1: print()
ad83ec5c51fe7d8d6d74883930a81ae4ebc18c67
fanliu1991/LeetCodeProblems
/26_Remove_Duplicates_from_Sorted_Array.py
1,581
3.90625
4
''' Given a sorted array, remove the duplicates in-place such that each element appear only once and return the new length. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. Example: Given nums = [1,1,2], return length = 2, with the first two elements of nums being 1 and 2 respectively. ''' import sys, optparse, os class Solution(object): def removeDuplicates(self, nums): """ :type nums: List[int] :rtype: int """ ''' Since the array is already sorted, we can keep two pointers i and j, where i is the slow-runner while j is the fast-runner. As long as nums[i] == nums[j], we increment j to skip the duplicate. When we encounter nums[j] != nums[i], the duplicate run has ended so we must copy its value to nums[i+1]. i is then incremented and we repeat the same process again until j reaches the end of array. ''' if len(nums) == 0: return 0 slow_runner = 0 for j in xrange(1, len(nums)): if nums[j] != nums[slow_runner]: slow_runner += 1 nums[slow_runner] = nums[j] # print nums # print nums[:slow_runner+1] return slow_runner+1 nums = [1,2,2,3,4,5,5,5,6,7] solution = Solution() result = solution.removeDuplicates(nums) print result ''' Complexity Analysis Time complexity : O(n) Assume that n is the length of array. Each of i and j traverses at most n steps. Space complexity : O(1). '''
3305d9d0fb42673a80bf1a6c2fbff6ed89b3b857
devprakashtripathi/test.py
/class variable.py
475
3.796875
4
class car: wheel = 4 # it is the class variable belong to the classnamesapce def __init__(self): self.mailage = 10 # so it is the instance variable because it is define in the init method not in the class self.company = 'BMW' # instance variable belongs to instance namespace c1 = car() # calling the object c2 = car() car.wheel = 5 # here we call the class variable for c1.mailage = 8 print(c1.company, c1.wheel) print(c2.company, c2.wheel)
57d2b6247df3d5cef4371e14ea9ac5d60553edd8
GaryZhang15/a_byte_of_python
/001_str_format.py
682
4.15625
4
print('\n******Start Line******\n') age = 28 name = 'Gary Zhang' print('{} was {} years old when he wrote this book'.format(name, age)) print('Why is {} playing with that python?'.format(name)) # decimal (.) precision of 3 for float '0.333' print('{0:.3f}'.format(1.0/3)) # fill with underscores (_) with the text centered print('{0:_^11}'.format('good')) # keyword-based print('{name} wrote {book}'.format(name='Gary', book='The new book')) print('a', end='_') print('b') print('This is the first line\nThis is the second line') print('This is the first sentence. \ This is the second sentence.') print(r'Newlines are indicated by \n') print('\n*******End Line*******\n')
c59244bf47c436ee40881cecf6e2f03a7fc6a201
ansangyoung/algorithmPython
/Queue/leetCode_189.py
659
3.671875
4
# 189. Rotate Array # https://leetcode.com/problems/rotate-array/ from typing import List class Solution: def rotate(self, nums: List[int], k: int) -> None: """ Do not return anything, modify nums in-place instead. """ numsLen = len(nums) k %= numsLen #nums = nums[numsLen-k : numsLen] + nums[0 : numsLen-k] for i in range(k): nums.insert(0, nums.pop()) print(nums) return(nums) testNums1 = [1,2,3,4,5,6,7] testK1 = 3 testNums2 = [-1,-100,3,99] testK2 = 2 print(rotate('', testNums1, testK1)) print(rotate('', testNums2, testK2))
82e6e8339159719b93502ec85bdad22edb3d64ef
GuSilva20/Primeiros-Codigos
/Ex49WhileMediaMaiorMenor.py
444
3.984375
4
media = 0 maior = menor = 0 c = 0 r = "S" while r == "S": n = int(input("Digite um número: ")) if c == 0: maior = n menor = n if n > maior: maior = n if n < menor: menor = n media += n c += 1 r = str(input('Você quer continuar? [ S / N ]')).upper() print('Finalizando programa!') print("Média: {}".format(media/c)) print("Maior: {}".format(maior)) print("Menor: {}".format(menor))
7e551ef3ddf067fa5a7d40293b45fb683c1514f5
fryderykg/exercises
/moderate/digits_doublets.py
2,015
3.984375
4
def checkio(numbers): """ You are given the list of numbers with exactly the same length and you must find the shortest chain of numbers to link the first number to the last Parameters ---------- numbers Numbers as a list of integers Returns ------- The shortest chain from the first to the last number as a list of integers """ digits_tree = {} first_element = numbers.pop(0) last_element = numbers[-1] parent_node = [first_element] child_node = [] while numbers: for parent in parent_node: numbers_to_remove = [] for number in numbers: if parent % 100 == number % 100 or parent // 10 == number // 10 or \ (parent // 100 == number // 100 and parent % 10 == number % 10): digits_tree[number] = parent child_node.append(number) if number == last_element: value = last_element path = [last_element] while value != first_element: value = digits_tree[value] path.append(value) return path[-1::-1] else: numbers_to_remove.append(number) for number in numbers_to_remove: numbers.remove(number) parent_node, child_node = child_node, [] # These "asserts" using only for self-checking and not necessary for auto-testing if __name__ == '__main__': # print(checkio([456, 455, 454, 654])) # print(checkio([111, 222, 333, 444, 555, 666, 121, 727, 127, 777])) assert checkio([123, 991, 323, 321, 329, 121, 921, 125, 999]) == [123, 121, 921, 991, 999], "First" assert checkio([111, 222, 333, 444, 555, 666, 121, 727, 127, 777]) == [111, 121, 127, 727, 777], "Second" assert checkio([456, 455, 454, 356, 656, 654]) == [456, 454, 654], "Third, [456, 656, 654] is correct too"
ffe8ab3fc75dd8061154bc15dbb6998b19aa035a
WilliamL71Oi/python_examples
/爬虫/多线程进程.py
13,578
4.03125
4
# 使用threading模块创建线程 # 创建4个线程, 然后分别用for循环执行4次start()和join()方法,每个子线程分别执行输出3次 import threading,time def process(): for i in range(3): time.sleep(1) print("thread name is %s" % threading.currentThread().name) if __name__ == '__main__': print("----主线程开始----") # 创建4个线程,存入列表 threads = [threading.Thread(target=process) for i in range(4)] for t in threads: t.start() # 开启线程 for t in threads: t.join() # 等待子线程结束 print("---主线程结束---") # 使用thread子类创建线程 # 创建一个继承threading.Thread线程类的子类subthread,并定义一个run()方法。 # 实例化SubThread类创建2个线程,并且调用start(*)方法开启线程,会自动调用run()方法。 import threading import time class SubThread(threading.Thread): def run(self): for i in range(3): time.sleep(1) msg = "子线程" + self.name + "执行,i=" + str(i) # name属性中保存的是当前线程的名字 print(msg) if __name__ == '__main__': print('---主线程开始---') t1 = SubThread() # 创建子线程t1 t2 = SubThread() # 创建子线程t2 t1.start() # 启动子线程t1 t2.start() # 启动子线程t2 t1.join() # 等待子线程t1 t2.join() # 等待子线程t2 print('---主线程结束---') # 验证线程之间是否可以共享信息。顶一个全局变量g_gum,分别创建2个子线程g_num执行不同的操作,并输出操作后的结果。 # 定义一个全局变量g_num,赋值为100,然后创建2个线程:一个线程将g_num增加50,一个线程将g_num减少50。如果g_num最终结果为100,则说明线程之间可以共享数据。 from threading import Thread import time def plus(): print("---子线程1开始---") global g_num g_num -= 50 print('g_num is %d' % g_num) print('---子线程1结束---') def minus(): time.sleep(1) print('---子线程2开始---') global g_num g_num += 50 print('g_num is %d' % g_num) print('---子线程2结束---') g_num = 100 # 定义一个全局变量 if __name__ == '__main__': print('---主线程开始---') print('g_num is %d' % g_num) t1 = Thread(target=plus) # 实例化线程t1 t2 = Thread(target=minus) # 实例化线程t2 t1.start() # 开启线程t1 t2.start() # 开启线程t2 t1.join() # 等待t1线程结束 t2.join() # 等待t2线程结束 print('---主线程结束---') # 使用多线程的互斥锁模拟多人购票功能 # 这里使用多线程和互斥锁模拟实现多人同时订购电影票的功能,假设电影院某个场次只有100张电影票,10个用户同事抢购该电影票,每出售一张,显示一次剩余的电影票张数。 # 创建了10个线程,全部执行task()函数,为解决资源竞争问题,使用mutex.acquire()函数实现资源锁定,第一个获取资源的线程锁定后,其他线程等待mutex.release()解锁。所以每次只有一个线程执行task()函数。 # 使用互斥锁时,要避免死锁。在多任务系统下,当一个或多个线程等待系统资源,而资源又被线程本身或其他线程占用时,就形成了死锁。 from threading import Thread, Lock import time n = 100 # 共100张票 def task(): global n mutex.acquire() # 上锁 temp = n # 赋值给临时变量 time.sleep(0.1) # 休眠0.1秒 n = temp - 1 # 数量减少1 print("购买成功,剩余%d张电影票" % n) mutex.release() # 释放锁 if __name__ == '__main__': mutex = Lock() # 实例化Lock类 t_l = [] # 初始化一个列表 for i in range(10): t = Thread(target=task) # 实例化线程类 t_l.append(t) # 将线程实例存入列表中 t.start() # 创建线程 for t in t_l: t.join() # 等待子线程结束 # 使用Queue队列实现在线程间通信 # 顶一个生产者类Producer,定义一个消费者类Consumer。生产者生成5件产品,依次写入队列,而消费者依次从队列中取出产品。 #!/usr/bin/env python # -*- coding: UTF-8 -*- from queue import Queue import random, threading, time # 生产者类 class Producer(threading.Thread): def __init__(self, name, queue): threading.Thread.__init__(self, name=name) self.data = queue def run(self): for i in range(5): print("生产者%s将产品%d加入队列!" % (self.getName(), i)) self.data.put(i) time.sleep(random.random()) print("生产者%s完成!" % self.getName()) # 消费者类 class Consumer(threading.Thread): def __init__(self, name, queue): threading.Thread.__init__(self, name=name) self.data = queue def run(self): for i in range(5): val = self.data.get() print("消费者%s将产品%d从队列中取出!" % (self.getName(), val)) time.sleep(random.random()) print("消费者%s完成!" % self.getName()) if __name__ == '__main__': print('---主线程开始---') queue = Queue() # 实例化队列 producer = Producer('Producer', queue) # 实例化线程Producer,并传入队列作为参数 consumer = Consumer('Consumer', queue) # 实例化线程Consumer,并传入队列作为参数 producer.start() # 启动线程Producer consumer.start() # 启动线程Consumer producer.join() # 等待线程Producer结束 consumer.join() # 等待线程Consumer结束 print('---主线程结束---') # Process类的方法和属性的使用 # Process类的方法和属性的使用,创建2个子进程,分别使用os模块和time模块输出父进程和子进程的ID以及子进程的时间,并调用Process类的name和pid属性。 # 第一次实例化Process类时,会为name属性默认赋值为“Process-1”,第二次则默认为“process-2”,但是由于在实例化进程p2时,设置了name属性为“mrsoft”,所以p2.name的值为“mrsoft”而不是“Process-2”。 # -*- coding:utf-8 -*- from multiprocessing import Process import time import os # 两个子进程将会调用的两个方法 def child_1(interval): print('子进程(%s)开始执行,父进程为(%s)' % (os.getpid(), os.getpid())) t_start = time.time() # 计时开始 time.sleep(interval) # 程序将会被挂起interval秒 t_end = time.time() # 计时结束 print("子进程(%s)执行时间为'%0.2f'秒" % (os.getpid(), t_end - t_start)) def child_2(interval): print("子进程(%s)开始执行,父进程为(%s)" % (os.getpid(), os.getpid())) t_start = time.time() # 计时开始 time.sleep(interval) # 程序将会被挂起interval秒 t_end = time.time() # 计时结束 print("子进程(%s)执行时间为'%0.2f'秒" % (os.getpid(), t_end - t_start)) if __name__ == '__main__': print("---父进程开始执行---") print("父进程PID:%s" % os.getpid()) # 输出当前程序的PID p1 = Process(target=child_1, args=(1,)) # 实例化进程p1 p2 = Process(target=child_2, name="mrsoft", args=(2,)) # 实例化进程p2 p1.start() # 启动进程p1 p2.start() # 启动进程p2 # 同事父进程仍然往下执行,如果p2进程还在执行,将会返回True print("p1.is_alive=%s" % p1.is_alive()) print("p2.is_alive=%s" % p2.is_alive()) # 输出p1和p2进程的别名和PID print("p1.name=%s" % p1.name) print("p1.pid=%s" % p1.pid) print("p2.name=%s" % p2.name) print("p2.pid=%s" % p2.pid) print("---等待子进程---") p1.join() # 等待p1进程结束 p2.join() # 等待p2进程结束 print("---父进程执行结束---") # 使用Process子类创建进程 # 对于一些简单的小任务,通常使用Process(target=test)方式实现多进程。但是如果要处理复杂任务的进程,通常定义一个类,使其继承Process类,每次实例化一个类的时候,就等同于实例化一个进程对象。 # 使用Process子类创建多个进程 # 使用Process子类方式创建2个进程,分别输出父、子进程的PID,以及每个子进程的状态和运行时间。 # 定义了一个SubProcess子类,继承multiprocess.Process子类。SubProcess子类中定义了2个方法:__init__()初始化方法和run()方法。在__init__()初始化方法中,调用multiprocess.Process父类的__init__() # 初始化方法,否则父类初始化方法会被覆盖,无法开启进程。此外,在SubProcess子类中并没有定义start()方法,但在主进程中却调用了start()方法,此时就会自动执行SubProcess类的run()方法。 # -*- coding:utf-8 -*- from multiprocessing import Process import time import os # 继承Process类 class SubProcess(Process): # 由于Process类本身也有__init__初始化方法,这个子类相当于重写了父类的方法 def __init__(self, interval, name=""): Process.__init__(self) # 调用Process父类的初始化方法 self.interval = interval # 接收参数interval if name: self.name = name # 如果传递参数name,则为子进程创建name属性,否则使用默认属性 # 重写Process类的run()方法 def run(self): print("子进程(%s开始执行,父进程为(%s)" % (os.getpid(), os.getpid())) t_start = time.time() time.sleep(self.interval) t_stop = time.time() print("子进程(%s)执行结束,耗时%0.2f秒" % (os.getpid(), t_stop - t_start)) if __name__ == '__main__': print("---父进程开始执行---") print("父进程PID:%s" % os.getpid()) p1 = SubProcess(interval=1, name='mrsoft') p2 = SubProcess(interval=2) # 对一个不包含target属性的Process类执行start()方法,就会运行这个类中的run()方法 # 所以这里会执行p1.run() p1.start() p2.start() # 输出p1和p2进程的执行状态,如果真正进行,返回True,否则返回False print("p1.is_alive=%s"%p1.is_alive()) print("p2.is_alive=%s"%p2.is_alive()) # 输出p1和p2进程的别名和PID print("p1.name=%s"%p1.name) print("p1.pid=%s"%p1.pid) print("p2.name=%s"%p2.name) print("p2.pid=%s"%p2.pid) print("---等待子进程---") p2.join() # 等待p1进程结束 p2.join() # 等待p2进程结束 print("---父进程执行结束---") # 使用processing.Queue实现多进程队列。 #! /usr/bin/python3 # -*- coding: UTF-8 -*- from multiprocessing import Queue if __name__ == '__main__': q = Queue(3) # 初始化一个Queue对象,最多可接收3条put消息 q.put("消息1") q.put("消息2") print(q.full()) # 返回false q.put("消息3") print(q.full()) # 返回True # 因为消息队列已满,下面的try会抛出异常 # 第一个try会等待2秒后再抛出异常,第二个try会立即抛出异常 try: q.put("消息4", True, 2) except: print("消息队列已满,现有消息数量:%s" % q.qsize()) try: q.put_nowait("消息4") except: print("消息队列已满,现有消息数量:%s" % q.qsize()) # 读取消息时,先判断消息队列是否为空,为空时再读取 if not q.empty(): print("---从队列中获取消息---") for i in range(q.qsize()): print(q.get_nowait()) # 先判断消息队列是否已满,不为满时再写入 if not q.full(): q.put_nowait("消息4") # 创建2个子进程,一个子进程负责向队列中写入数据,另一个子进程负责从队列中读取数据。为保证能够正确从队列中读取数据,设置读取数据的进程等待时间为2秒。如果2秒后仍然无法读取数据,则抛出异常。 #! /usr/bin/python3 # -*- coding: UTF-8 -*- from multiprocessing import Process, Queue import time # 向队列中写入数据 def write_task(q): if not q.full(): for i in range(5): message = "消息" + str(i) q.put(message) print("写入:%s" % message) # 从队列读取数据 def read_task(q): time.sleep(1) # 休眠1秒 while not q.empty(): # 等待2秒,如果还没读取到任何消息 print("读取:%s" % q.get(True, 2)) # 则抛出"Queue.Empty"异常 if __name__ == '__main__': print("---父进程开始---") q = Queue() # 父进程创建Queue,并传给各个子进程 pw = Process(target=write_task, args=(q,)) # 实例化写入队列的子进程,并且传递队列 pr = Process(target=read_task, args=(q,)) # 实例化读取队列的子进程,并且传递队列 pw.start() # 启动子进程pw,写入 pr.start() # 启动子进程pr,读取 pw.join() # 等待pw结束 pr.join() # 等待pr结束 print("---父进程结束---")
e6f1fad118b7c1c16cb664c9b910825f38ffdba6
ChacunGu/SoundEncryption
/rc4.py
1,857
3.6875
4
""" Security course Chacun Guillaume, Feuillade Julien HE-Arc, Neuchâtel 2018-2019 *** rc4.py """ import array MOD = 256 def KSA(key): """ Key-scheduling algorithm from pseudo-code of Wikipedia """ key_length = len(key) tab = list(range(MOD)) j = 0 for i in range(MOD): j = (j + tab[i] + key[i % key_length]) % MOD tab[i], tab[j] = tab[j], tab[i] return tab def PRGA(tab): """ Pseudo-random generation algorithm form pseudo-code of Wikipedia """ i = 0 j = 0 while True: i = (i + 1) % MOD j = (j + tab[i]) % MOD tab[i], tab[j] = tab[j], tab[i] K = tab[(tab[i] + tab[j]) % MOD] yield K def PRGA_custom(tab): """ Custom method used for keystream generation. This method does NOT generate a pseudo random flux as it should be for RC4 to be secure. It is used to demonstrate the importance of a random keystream in RC4. """ i = 0 j = 0 while True: i = (i + 1) % MOD j = (j + tab[i]) % MOD yield i+j def KeyStream(key, use_custom=False): """ Put the two function together to get the key stream """ keyKsa = KSA(key) return PRGA_custom(keyKsa) if use_custom else PRGA(keyKsa) def logic(key, byteArray, use_custom=False): """ Logic of the encryption, encryption key used for encrypting """ key = [ord(c) for c in key] keystream = KeyStream(key, use_custom) result = [] for c in byteArray: value = (c ^ next(keystream)) result.append(value) return result def encrypt(key, byteArray, use_custom=False): return logic(key, byteArray, use_custom) def decrypt(key, cipher, use_custom=False): """ Use codecs library to decode the cipher """ result = logic(key, cipher, use_custom) return array.array("B", result)
3e0e7074da3c99ecdf849581c24500addd640ed9
melodyen/Math-10---Homework-4
/Homework4.py
1,799
4
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Oct 18 11:59:01 2021 @author: melodyen """ import streamlit as st import pandas as pd import numpy as np import altair as alt #Question 1 st.title("Math 10: HW 4") #Question 2 st.markdown("[Melodye Nguyen] (https://github.com/melodyen)") #Question 3 csv = st.file_uploader(label="Choose a CSV file, please!",type=["csv"]) #Question 4 #We want to convert the file to a pandas df #But there will be an error if we don't have an uploaded file first if csv is not None: df = pd.read_csv(csv) #If x is an empty string, make it numpy's not-a-number #otherwise, leave x alone #Question 5 df = df.applymap(lambda x: np.nan if x == " " else x) #Question 6 #See Week 3 Friday Lecture def can_be_numeric(c): try: pd.to_numeric(df[c]) return True except: return False #Now, let's make a list of all the columns that can be made numeric good_cols = [c for c in df.columns if can_be_numeric(c)] #Question 7 #Replace columns in df that can be made numeric with their numeric values df[good_cols] = df[good_cols].apply(pd.to_numeric, axis = 0) #Question 8 x_axis = st.selectbox("Select a value for the x-axis", good_cols) y_axis = st.selectbox("Select a value for the y-axis", good_cols) #Question 9 slider = st.slider("Row selected", 0 ,len(df.index)-1,(0,len(df.index)-1)) #Question 10 st.write(f"{x_axis} and {y_axis} of {slider} is") #Question 11 spotify = alt.Chart(df.loc[slider[0]:slider[1]]).mark_circle().encode( x = x_axis, y = y_axis, color = "Energy" ) st.altair_chart(spotify) #Question 12 #Added color to the altair chart and made it equal to the Energy values
5303f1cf72b5d03a97df07a67f6b0708e2d35102
raketenlurch/automate-the-boring-stuff
/Automate-the-boring-Stuff-with-Python/commaCode.py
303
3.703125
4
# Funktion zur Ausgabe der Indexe def comma_code(list): for i in list: if i == list[len(list) -1]: print('and', end="") print(i, end="") # Eingabe des Users und Ausgabe der Liste print('Bite geben Sie eine Liste ein:') user_list = input() comma_code(user_list)
a4ea40c9d81045fe3fbaabd6ced8ddf73c3bb92e
0CMat/Python
/Exercícios/Exercícios Avulsos/Sequencial/exerc17.py
444
4.21875
4
'''Faça um programa que peça uma nota, entre zero e dez. Mostre uma mensagem caso o valor seja inválido e continue pedindo até que o usuário informe um valor válido.''' nota = int(input('Informe uma nota entre 0 a 10.\n Sua nota: ')) while (nota > 10) or (nota < 0): print('ERRO!\nDigite dentro do parametro pedido!') nota = int(input('Informe uma nota entre 0 a 10.\n Sua nota: ')) else: print("Sua nota foi enviada.")
c5352d97606b0897d436f284028f9b062146d4f7
bengrunfeld/python-exercises
/intro_to_python/unit_4/lab_4_2/tuple_iteration.py
192
3.8125
4
#! /usr/bin/env python lottery_tuple = (32, 81, 74, 16, 25, 90, 53) for index, lottery_number in enumerate(lottery_tuple): print "Lottery number {}: is {}".format(index, lottery_number)
1822e0cbf19fc5b6a9ef6a4e2a62382912334f80
ThatGuy247/Python_EdX_GoToClass_Solutions
/Quiz-2/Part5.py
438
3.640625
4
n = int(input('enter working time hours: ')) if n < 0 or n > 168: print('INVALID') elif n <= 40: pay = int(n*8) print('YOU MADE ' + str(pay) + ' DOLLARS THIS WEEK') elif n <= 50: minus = n - 40 pay = int((40*8) + minus*9) print('YOU MADE ' +str(pay) + ' DOLLARS THIS WEEK') else: minus = n - 50 pay = int((40*8) + (10*9) + minus*10) print('YOU MADE ' + str(pay) + ' DOLLARS THIS WEEK')
0d22bbae07f94535f1d74779c93f4814247673cc
IgorTerriaga/ComputerScienceAlgorithms
/Tabela de Dispersao/01.py
296
3.671875
4
''' Exemplo trivial de utlilizacao ''' votaram = {} def verifica_eleitor(nome): if votaram.get(nome): # se ja votou print("Mande embora") else: votaram[nome] = True print("Deixe votar!") verifica_eleitor("tom") verifica_eleitor("Mike") verifica_eleitor("Mike")
6fb2c7fe20e11231babff806f2f6a816f3404c83
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/hamming/e3c1d61c133c4b82962fae2d5fab27ab.py
447
3.96875
4
def distance(seq_1, seq_2): """ Input: 2 DNA sequences as strings Output: Hamming distance(the number of differences between two strings) as integer The strings must be of the same length """ assert(len(seq_1) == len(seq_2)) sequences = zip(seq_1,seq_2) hamming = 0 for letter_pair in sequences: if letter_pair[0] != letter_pair[1]: hamming += 1 return hamming
f49219150aee97ad260181016ccf0496ad9c3dd2
hollmanluke10/final-project
/final_project.py
4,887
3.9375
4
""" Name: Luke Hollman CS230: Section 1 Data: "Postsecondary_School_Locations_-_Current.csv" URL:In Process Description: This program shows the user the amount of Colleges and Universities that exist in each state in the U.S. in a bar graph. The user then has the option of selecting a state that they want to view the colleges in via a sidebar select box. The state that is selected is displayed on the first map, with each of the colleges having their own label with their names. The use then has the option of selecting a specific school that they would like to view within the previously determined state also via a side bar select box. The college that was selected comes up on the second map, also having its own label with it's name. """ import streamlit as st import pandas as pd import pydeck as pdk def bar_chart(states_list): data = pd.read_csv("Postsecondary_School_Locations_-_Current.csv") data_cleanup = data[data.STATE.isin(states_list.keys())] countByState = data_cleanup.groupby('STATE')['FID'].count() print(countByState) st.title('Schools by State:') st.bar_chart(countByState) def map_1and2(data,states_list): option = st.sidebar.selectbox("Which state do you want to see Universities/Colleges in for Map #1", list(states_list.keys())) state_data = data[data['STATE'] == option] st.title(f"Universities and Colleges in {option}") st.write(state_data[['NAME', 'STREET', 'CITY', 'STATE']]) schools = state_data[['X', 'Y', 'NAME']] schools.columns = ["lon", "lat", 'University'] st.write(f"Map #1: Map of Universities and Colleges in {option}") view_state = pdk.ViewState( latitude=schools['lat'].mean(), longitude=schools["lon"].mean(), zoom = 10, pitch = 0.5) layer1 = pdk.Layer('ScatterplotLayer', data=schools, get_position='[lon, lat]', get_radius = 500, get_color=[0,255,255,], pickable=True) tool_tip = {"html": "University Name:<br/> <b>{University}</b> ", "style": {"backgroundColor": "black", "color": "white"}} map_schools = pdk.Deck(map_style='mapbox://styles/mapbox/light-v9', initial_view_state=view_state, layers=[layer1], tooltip=tool_tip) st.pydeck_chart(map_schools) map_2(option, state_data, data) def map_2(option, state_data,data): option2 = st.sidebar.selectbox(f"Pick a school in {option} for Map #2", list(state_data['NAME'])) single_school = data[data['NAME'] == option2] specific_school = single_school[['X', 'Y', 'NAME']] specific_school.columns = ['lon', 'lat', 'University'] st.write(f"Map #2 Map of {option2}") view_state = pdk.ViewState( latitude=specific_school['lat'].mean(), longitude=specific_school["lon"].mean(), zoom = 10, pitch = 0.5) layer1 = pdk.Layer('ScatterplotLayer', data=specific_school, get_position='[lon, lat]', get_radius = 500, get_color=[255,0,125], pickable=True) tool_tip = {"html": "University Name:<br/> <b>{University}</b> ", "style": {"backgroundColor": "blue", "color": "white"}} map_schools2 = pdk.Deck(map_style='mapbox://styles/mapbox/light-v9', initial_view_state=view_state, layers=[layer1], tooltip=tool_tip) st.pydeck_chart(map_schools2) def main(): states_list = {'AL': 'Alabama', 'AK': 'Alaska', 'AR': 'Arkansas', 'AZ': 'Arizona', 'CA': 'California', 'CO': 'Colorado', 'CT': 'Connecticut', 'DE': 'Deleware', 'DC': 'District of Columbia', 'FL': 'Florida', 'GA': 'Georgia', 'HI' : 'Hawaii', 'ID' : 'Idaho', 'IL' : 'Illinois', 'IN' : 'Indiana', 'IA' : 'Iowa', 'KS' : 'Kansas', 'KY' : 'Kentucky', 'LA' : 'Louisiana', 'ME' : 'Maine', 'MD' : 'Maryland', 'MA' : 'Massachusetts', 'MI' : 'Michigan', 'MN' : 'Minnesota', 'MS' : 'Mississippi', 'MO' : 'Missouri', 'MT' : 'Montana', 'NE' : 'Nebraska', 'NV' : 'Nevada', 'NH' : 'New Hampshire', 'NJ' : 'New Jersey', 'NM' : 'New Mexico', 'NC' : 'North Carolina', 'ND' : 'North Dakota', 'OH' : 'Ohio', 'OK' : 'Oklahoma', 'OR' : 'Oregon', 'PA' : 'Pennsylvania', 'PR' : 'Puerto Rico', 'RI' : 'Rhode Island', 'SC' : 'South Carolina', 'SD' : 'South Dakota', 'TN' : 'Tennessee', 'TX' : 'Texas', 'UT' : 'Utah', 'VT' : 'Vermont', 'VA' : 'Virginia', 'VI' : 'Virgin Islands', 'WA' : 'Washington', 'WV' : 'West Virginia', 'WI' : 'Wisconsin', 'WY' : 'Wyoming'} st.title("Universities/Colleges in the United States") data = pd.read_csv("Postsecondary_School_Locations_-_Current.csv") bar_chart(states_list) map_1and2(data, states_list) main()
36f43d3179bfed224f38ba373425cee4d17421d4
kimjane93/udemy-python-100-days-coding-challenges
/day-10-calculator-app-fns-w-outputs/final-calc.py
941
4.15625
4
from art import * def add(num1, num2): return num1 + num2 def subtract(num1, num2): return num1 - num2 def multiply(num1, num2): return num1 * num2 def divide(num1, num2): return num1 / num2 operations = { "+": add, "-": subtract, "*": multiply, "/": divide } def calculator(): print(logo) first_num = float(input("What's the first number?\n")) should_continue = True while should_continue: operator = input("+\n-\n*\n/\nPick an operation: ") second_num = float(input("What's the next number?\n")) answer = operations[operator](first_num, second_num) print(f"{first_num} {operator} {second_num} = {answer}") if input(f"Type 'y' to continue calculating with {answer}, or 'n' to start a new calculation\n") == 'y': first_num = answer else: should_continue = False calculator() calculator()
3eb80a2d3917410aa991aba35b85bf996c2ab426
tainenko/Leetcode2019
/leetcode/editor/en/[1668]Maximum Repeating Substring.py
1,276
3.78125
4
# For a string sequence, a string word is k-repeating if word concatenated k # times is a substring of sequence. The word's maximum k-repeating value is the # highest value k where word is k-repeating in sequence. If word is not a substring of # sequence, word's maximum k-repeating value is 0. # # Given strings sequence and word, return the maximum k-repeating value of # word in sequence. # # # Example 1: # # # Input: sequence = "ababc", word = "ab" # Output: 2 # Explanation: "abab" is a substring in "ababc". # # # Example 2: # # # Input: sequence = "ababc", word = "ba" # Output: 1 # Explanation: "ba" is a substring in "ababc". "baba" is not a substring in # "ababc". # # # Example 3: # # # Input: sequence = "ababc", word = "ac" # Output: 0 # Explanation: "ac" is not a substring in "ababc". # # # # Constraints: # # # 1 <= sequence.length <= 100 # 1 <= word.length <= 100 # sequence and word contains only lowercase English letters. # # Related Topics String String Matching 👍 395 👎 139 # leetcode submit region begin(Prohibit modification and deletion) class Solution: def maxRepeating(self, sequence: str, word: str) -> int: # leetcode submit region end(Prohibit modification and deletion)
46f8a6ee4acc4fbe65690ecf5bcd958f5494246a
hitigon/leetcode-template
/python/3sum_closest.py
467
3.6875
4
# coding=utf-8 # AC Rate: 27.2% # https://oj.leetcode.com/problems/3sum-closest/ # Given an array S of n integers, find three integers in S such that the sum is # closest to a given number, target. Return the sum of the three integers. You # For example, given array S = {-1 2 1 -4}, and target = 1. # The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). class Solution: # @return an integer def threeSumClosest(self, num, target):
177625bd9d4aae4be33ded4c478748cfbfb9f50a
raychorn/rackspace-repo1
/magento1.py
366
3.671875
4
an_array = [0,1,2,3,4,5,-5,-100000,100000,-200000] def my_max(a,b): return a if (a > b) else b def get_max(a): val = -1 for i in a: val = my_max(i, val) return val def get_max2(a): val = -1 for i in a: val = max(i, val) return val if (__name__ == '__main__'): print get_max(an_array) print get_max2(an_array)
f79d689136d2541a4360b89fc6657198340cbb5e
krose18/HelloWorld
/hello.py
112
3.71875
4
print("Hello, world!") username = input("What's ur name?") print("Hello, ", username, ". Nice to meet you! :D")
150a1bc3c0af2581780e97e7cb5abb94d7c7ebd9
mselivanov/pysharpen-the-tools
/pysharpen/algorithms/graph/bfs_search.py
3,655
4.0625
4
"Module demonstrates breadth-first search algorithm" from collections import deque import unittest class Node: "Class implements graph node" def __init__(self, data): self._data = data @property def data(self): "Node data" return self._data @data.setter def data(self, value): "Set node data" self._data = value class Edge: "Class implements graph edge" def __init__(self, from_node, to_node, weight): "Inits edge connecting two nodes" self._from_node = from_node self._to_node = to_node self._weight = weight @property def from_node(self): "Edge from node" return self._from_node @property def to_node(self): "Edge to node" return self._to_node @property def weight(self): "Edge weight" return self._weight class Graph: "Class implements graph" def __init__(self, directed): self._graph = {} self._directed = directed def _connected_nodes(self, from_node): return (edge.to_node for edge in self._graph[from_node]) def add_node(self, node): "Adds node to graph" if node in self._graph: raise ValueError('Node is already in graph') self._graph[node] = [] def connect(self, from_node, to_node, weight): "Connect two nodes" if not from_node in self._graph: self.add_node(from_node) if not to_node in self._graph: self.add_node(to_node) if to_node in self._connected_nodes(from_node): return edge = Edge(from_node, to_node, weight) self._graph[from_node].append(edge) if not self._directed: self.connect(to_node, from_node, weight) def is_path_exists(self, from_node, to_node): search_path = deque(self._graph[from_node]) searched_edges = {} while search_path: edge = search_path.popleft() if not edge in searched_edges: if edge.to_node == to_node: return True else: searched_edges[edge] = True search_path.extend(self._graph[edge.to_node]) return False class GraphTest(unittest.TestCase): "Class for testing graph" def test_two_node_undirected_graph(self): graph = Graph(directed=False) node1 = Node(None) node2 = Node(None) graph.connect(node1, node2, 1) self.assertTrue(graph.is_path_exists(node1, node2)) self.assertTrue(graph.is_path_exists(node2, node1)) def test_three_node_directed_graph(self): graph = Graph(directed=True) node1 = Node(None) node2 = Node(None) node3 = Node(None) graph.connect(node1, node2, 1) graph.connect(node2, node3, 1) self.assertTrue(graph.is_path_exists(node1, node3)) def test_three_node_directed_graph_with_cycle(self): graph = Graph(directed=True) node1 = Node(None) node2 = Node(None) node3 = Node(None) graph.connect(node1, node2, 1) graph.connect(node2, node3, 1) graph.connect(node3, node1, 1) self.assertTrue(graph.is_path_exists(node1, node3)) def test_three_node_path_not_exists(self): graph = Graph(directed=True) node1 = Node(None) node2 = Node(None) node3 = Node(None) graph.connect(node1, node2, 1) graph.add_node(node3) self.assertFalse(graph.is_path_exists(node1, node3)) if __name__ == '__main__': unittest.main()
4047d09aecce5353fe31ce6586ddd951731b4ece
papan36125/python_exercises
/concepts/Exercises/dictionary_examples.py
778
4.25
4
# empty dictionary my_dict = {} # dictionary with integer keys my_dict = {1: 'apple', 2: 'ball'} # dictionary with mixed keys my_dict = {'name': 'John', 1: [2, 4, 3]} # using dict() my_dict = dict({1:'apple', 2:'ball'}) # from sequence having each item as a pair my_dict = dict([(1,'apple'), (2,'ball')]) my_dict = {'name':'Jack', 'age': 26} # Output: Jack print(my_dict['name']) # Output: 26 print(my_dict.get('age')) # Trying to access keys which doesn't exist throws error # my_dict.get('address') # my_dict['address'] my_dict = {'name':'Jack', 'age': 26} # update value my_dict['age'] = 27 #Output: {'age': 27, 'name': 'Jack'} print(my_dict) # add item my_dict['address'] = 'Downtown' # Output: {'address': 'Downtown', 'age': 27, 'name': 'Jack'} print(my_dict)
19fbf8031446a0cb9b7717d484b5be974caaffc9
pirent/python-playground
/thinkpython/exercise1702.py
962
3.921875
4
class Kangaroo: """Represents a kangaroo """ def __init__(self, name, contents=None): """Initialize the pouch contents name: string contents: initial pouch contents """ self.name = name self.pouch_contents = [] if contents == None else contents def put_in_pouch(self, item): """Adds a new item to pouch contents item: object to be added """ self.pouch_contents.append(item) def __str__(self): """Returns a string representation of this Kangaroo """ t = [self.name + " has pouch: "] for o in self.pouch_contents: s = " " + object.__str__(o) t.append(s) return '\n'.join(t) if __name__ == "__main__": kanga = Kangaroo("Kanga") roo = Kangaroo("Roo") kanga.put_in_pouch('wallet') kanga.put_in_pouch('car keys') kanga.put_in_pouch(roo) print(kanga) print(roo)
55e68ba932be0ade36d663d647cf49d7d75b0ae4
CiaraMadden/Python
/animals.py
365
3.953125
4
class Person(object): def __init__(self, name, address): self.name = name #declaring a name for each object self.address = address #declaring an address for each object def description(self): return '{}, of {}'.format(self.name, self.address) if __name__=='__main__': p1 = Person('Sean', 'Galway') p2 = Person('Mary', 'Cork') print p1.description()
71a798a49b42642bae35f805ff8bea76168b91c9
Neckmus/itea_python_basics_3
/pivak_gennadii/02/03.py
1,347
3.53125
4
#Variant 1 list_array = list(input('Input array digit (like this - 6675675) ')) for i in range(len(list_array)): count_element = 0 # print(f'Search {list_array[i]}') # print(i) for j in range(len(list_array)): if list_array[i] == list_array[j] and i != j: count_element += 1 # print(j) if not count_element % 2: break print(f'Find! {list_array[i]}') #Variant 2 len_array = 0 list_array = list(input('Input array digit (like this - 6675675) ')) len_array = len(list_array) array_2d = [] for i in range(len_array) : row = [] for j in range(len_array): if list_array[i] == list_array[j] and i != j and i not in array_2d: row.append(j) row.append(i) array_2d.append(row) if len(row) % 2: print(list_array[i]) break #print(array_2d) #Variant 3 list_array = list(input('Input array digit (like this - 6675675) ')) transpose = [[1 if list_array[i] == list_array[j] else 0 for j in range(len(list_array))] for i in range(len(list_array))] #print(transpose) row_count = 0 element_sum = 0 for row in transpose: # print(row) for element in row: element_sum += element # print(element_sum) if element_sum % 2: print(f'Find! {list_array[row_count]}') break row_count += 1 element_sum = 0
59418de1c30a913619118358c04ceef0584001f8
vbutoma/ProjectEuler
/160.py
745
3.703125
4
from math import log def power(n, prime): res = 0 while n: n /= prime res += n return res def f(n): #n = base * p + q return (product[base] ** (n / base) * product[n % base]) % base N = 10**12 base = 10**5 product = [0 for _ in range(base + 1)] p = product[0] = 1 for i in range(1, base + 1): if i % 2 and i % 5: p = (p * i) % base product[i] = p result = 1 for p2 in range(0, int(log(N) / log(2)) + 1): for p5 in range(0, int(log(N) / log(5)) + 1): number = (2**p2) * (5**p5) if number > N: break result = (result * f(N / number)) % base print (result * pow(2, power(N, 2) - power(N, 5), base)) % base
8802412197dee90a1ae9577d557950133d11a6cf
malav-parikh/python-for-data-science
/sequence data types.py
2,494
4.34375
4
# python for data science # sequence data types # sequence object initialization # STRING strSample = 'Malav' print(strSample) # strings are immutable i.e. they cannot be changed or altered # LISTS lstNumbers = [1,2,3,3,3,4,5,6] print(lstNumbers) # this is a list containing only numbers basically a single data type # another property of list is that it can contain duplicates lstSample = [1,'Malav',3.0,True,'Hi'] print(lstSample) # this is a list containing mixed data type # lists can contain elements of different data types # lists are mutable i.e they can be changed or altered even after their creation # ARRAYS # to use array in python we need to import from array module # then to define an array we need to pass data type and values in array function # like array('data-type',[value1, value2,...]) from array import * arraySample = array('i',[1,2,3,4]) # printing an array for i in arraySample: print(i) # TUPLES tupeSample = (1,2,3,3,5,'a',3.0,'b') print(tupeSample) # tuples are like list, they can have elements of different data types # they are stored in paranthesis () # they are immutable tupleSample = 1, 2, 'packing' print(tupleSample) # tuples can be written without paranthesis as well # this is called tuple packing # DICTIONARY dictSample = {'1':'one',2:'two', 3.0:'three','four':True} print(dictSample) # dictionary holds key value pairs in between {} # the keys and values can be of any data type but # the keys should be unique i.e, they cannot be repeated # creating dictionary using dict function # the only difference is that the key value pairs are passed as tuples in a list dictSample2 = dict([('1','one'),(2,'two'),(3.0,'three'),('four',True)]) print(dictSample2) # SET setSample = {'sample',1,2,3,4.0,True,3,4.0,True} print(setSample) # a set is also like list where it can hold elements of different data types # the difference is that it cannot hold another list or set inside it # the elements are passed between {} # sets cannot contain duplicates # printing the above example will not print the repeated values only once setSample2 = set([1,2,3,4,5]) print(setSample2) # creating set using set function # another way for creating set setExample = set('example') print(setExample) # RANGE # for creating a sequence of integers # useful in for loop # takes in 3arguments (start, end, skip or step) # if end is 51 considers only upto 50 i.e n-1 rangeSample = range(0,51,10) print(rangeSample) for x in rangeSample: print(x)
fe9af8c98de886886905599f33f42d73a393fe63
CKowalczuk/Python---Ejercicios-de-Practica-info2021
/estvpoo.py
4,071
3.96875
4
## No intentes entender este código, sólo fíjate en cómo se utiliza abajo # Creo una estructura para los clientes """ class Cliente: def __init__(self, dni, nombre, apellidos): self.dni = dni self.nombre = nombre self.apellidos = apellidos def __str__(self): return '{} {}'.format(self.nombre,self.apellidos) # Y otra para las empresas class Empresa: def __init__(self, clientes=[]): self.clientes = clientes def mostrar_cliente(self, dni=None): for c in self.clientes: if c.dni == dni: print(c) return print("Cliente no encontrado") def borrar_cliente(self, dni=None): for i,c in enumerate(self.clientes): if c.dni == dni: del(self.clientes[i]) print(str(c),"> BORRADO") return print("Cliente no encontrado") ### Ahora utilizaremos ambas estructuras # Creemos un par de clientes hector = Cliente(nombre="Hector", apellidos="Costa Guzman", dni="11111111A") juan = Cliente("22222222B", "Juan", "Gonzalez Marquez") # Creemos una empresa con los clientes iniciales empresa = Empresa(clientes=[hector, juan]) # Se muestran todos los clientes print("==LISTADO DE CLIENTES==") print(empresa.clientes) print("\n==MOSTRAR CLIENTES POR DNI==") # Se consulta clientes por DNI empresa.mostrar_cliente("11111111A") empresa.mostrar_cliente("11111111Z") print("\n==BORRAR CLIENTES POR DNI==") # Se borra un cliente por DNI empresa.borrar_cliente("22222222V") empresa.borrar_cliente("22222222B") # Se muestran de nuevo todos los clientes print("\n==LISTADO DE CLIENTES==") print(empresa.clientes) class Producto: def __init__(self, referencia, tipo, nombre, pvp, descripcion, productor=None, distribuidor=None, isbn=None, autor=None): self.referencia = referencia self.tipo = tipo self.nombre = nombre self.pvp = pvp self.descripcion = descripcion self.productor = productor self.distribuidor = distribuidor self.isbn = isbn self.autor = autor adorno = Producto('000A','ADORNO','Vaso Adornado',15, 'Vaso de porcelana con dibujos') print(adorno) print(adorno.tipo) """ class Producto: def __init__(self,referencia,nombre,pvp,descripcion): self.referencia = referencia self.nombre = nombre self.pvp = pvp self.descripcion = descripcion def __str__(self): return f"REFERENCIA\t {self.referencia}\n" \ f"NOMBRE\t\t {self.nombre}\n" \ f"PVP\t\t {self.pvp}\n" \ f"DESCRIPCIÓN\t {self.descripcion}\n" """class Adorno(Producto) pass """ class Alimento(Producto): productor = "" distribuidor = "" def __str__(self): return f"REFERENCIA\t {self.referencia}\n" \ f"NOMBRE\t\t {self.nombre}\n" \ f"PVP\t\t {self.pvp}\n" \ f"DESCRIPCIÓN\t {self.descripcion}\n" \ f"PRODUCTOR\t\t {self.productor}\n" \ f"DISTRIBUIDOR\t\t {self.distribuidor}\n" class Libro(Producto): isbn = "" autor = "" def __str__(self): return f"REFERENCIA\t {self.referencia}\n" \ f"NOMBRE\t\t {self.nombre}\n" \ f"PVP\t\t {self.pvp}\n" \ f"DESCRIPCIÓN\t {self.descripcion}\n" \ f"ISBN\t\t {self.isbn}\n" \ f"AUTOR\t\t {self.autor}\n" """ adorno = Adorno(2034, "Vaso adornado", 15, "Vaso de porcelana") print(adorno)""" alimento = Alimento(2035, "Botella de Aceite de Oliva", 5, "250 ML") alimento.productor = "La Aceitera" alimento.distribuidor = "Distribuciones SA" print(alimento) libro = Libro(2036, "Cocina Mediterránea",9, "Recetas sanas y buenas") libro.isbn = "0-123456-78-9" libro.autor = "Doña Juana" print(libro)
b27aaab046856d166324e258136845cedff59446
dealvv/EGE
/Python/ЕГЭ2021/25/Решение заданий. Поляков/2873.py
583
3.953125
4
#(№ 2873) (Д.Ф. Муфаззалов) Число называется избыточным, если оно меньше суммы своих собственных делителей #(то есть всех положительных делителей, отличных от самого́ числа). #Определите количество избыточных чисел из диапазона [2; 20000]. def d(n): sum=0 for i in range(1,n): if (n%i==0): sum+=i return sum a=[x for x in range(2,20001) if (x<d(x))] print(len(a))
181f4ff45846bdea33b49e21794027e00e0ca23b
mahammadverdiyev/azresource
/Python/Kod nümunələri/4_fahrenheit_selsi_cevirici.py
753
3.875
4
""" Python dili üzrə kod nümunələri - müəllif Nurlan Aliyev, 26/07/2021 Kod №4 - Fahrenheit-Selsi çevirməsi Kopyalayıb kodu test edə bilərsiniz Və yaxud bu link vasitəsilə yoxlaya bilərsiniz https://replit.com/@NurlanAliyev/4FahrenheitSelsiCevirici """ # Aşağıdakı qiyməti istəyə uyğun dəyişə bilərsiniz # və yaxud altdakı sətri şərh blokunnan çıxarıb istifadəçidən temperatur göstəricisini ala bilər # fahrenheit = float(input('Temperatur göstəricisini (Fahrenheit şkalası ilə) daxil edin: ')) fahrenheit = 86 # S2lsiyə çevrilmə (selsi = (fahrenheit - 32) / 1.8 selsi = (fahrenheit - 32) / 1.8 #Nəticənin çap olunması print(f'{fahrenheit} dərəcə Fahrenheit, {selsi} dərəcə Selsiyə bərabərdir')
099dde66c9dc4df8afbabc56c3c11292653a06e3
my0614/python
/random_flower.py
263
3.78125
4
import turtle,random t = turtle.Turtle() t.pensize(2) t.speed(40) fcolor = ['red','purple','yellow'] t.color(random.choice(fcolor)) #랜덤색상고르기 radius = random.randint(100,150) t.circle(radius) for i in range(6): t.left(360/6) t.circle(radius)
4506653e91a04f4f4fb34eb452781e8bd47fbf24
nambroa/Algorithms-and-Data-Structures
/LEGACY/graphs/2_build_order.py
4,228
3.90625
4
""" CTCI - TREES AND GRAPHS: QUESTION 7 You are given a list of projects and a list of dependencies (which is a list of pairs of projects, where the second project is dependent on the first project). All of a project's dependencies must be built before the project is. Find a build order that will allow the projects to be built. If there is no valid build order, raise an error. (Topological sort problem) EXAMPLE: INPUT: Projects: a, b, c, d, e, f Dependencies: (a, d), (f, b), (b, d), (f, a), (d, c) OUTPUT: f, e, a, b, d, c """ def find_build_order(project_names, dependencies): """ :param project_names: list of strings :param dependencies: list of pair of strings :return: list of projects """ graph = build_graph(project_names, dependencies) return order_projects(graph.nodes()) def build_graph(project_names, dependencies): graph = TopologicalGraph() for project_name in project_names: graph.get_or_create_node(project_name) for dependency_pair in dependencies: first, second = dependency_pair[0], dependency_pair[1] graph.add_edge_between(first, second) # Second has a dependency to first return graph def order_projects(projects): order = [None] * len(projects) # First, we add the projects without dependencies. end_of_list_index = add_non_dependent_projects(projects, order, 0) to_be_processed = 0 while to_be_processed < len(order): current_project = order[to_be_processed] if not current_project: raise ValueError("Graph has a circular dependency. No build order is possible.") children = current_project.children() for child in children: child.remove_dependency() # Remove dependency between current_project and it's children # Add children projects that have no dependencies end_of_list_index = add_non_dependent_projects(children, order, end_of_list_index) to_be_processed += 1 return order def add_non_dependent_projects(projects, order, starting_index): starting_index = starting_index for project in projects: if project.amount_of_dependencies() == 0: order[starting_index] = project starting_index += 1 return starting_index class Project(object): # It's a graph node that also has a dependency count and a map. def __init__(self, name): self._amount_of_dependencies = 0 self._name = name self._children = [] self._children_map = {} # Maps a project name to it's project node, to find it faster def __str__(self): return str(self.name()) def children(self): return self._children def name(self): return self._name def amount_of_dependencies(self): return self._amount_of_dependencies def add_dependency(self): self._amount_of_dependencies += 1 def remove_dependency(self): self._amount_of_dependencies -= 1 def add_neighbor(self, project): # The project passed by parameter will have a dependency to self. if not(project.name() in self._children_map): self.children().append(project) self._children_map.update({project.name(): project}) project.add_dependency() class TopologicalGraph(object): def __init__(self): self._nodes = [] self._node_map = {} # Maps a project name to it's project node, to find it faster. def nodes(self): return self._nodes def get_or_create_node(self, name): if not (name in self._node_map): project = Project(name=name) self.nodes().append(project) self._node_map.update({name: project}) return self._node_map[name] def create_node(self, project): if not (project.name() in self._node_map): self._node_map.update({project.name(): project}) self.nodes().append(project) def add_edge_between(self, start_name, end_name): # End name will have a dependency to start name project_start = self.get_or_create_node(start_name) project_end = self.get_or_create_node(end_name) project_start.add_neighbor(project_end)
d1c699c964324b5cd17c8be5ad88b1f2c9edd9ad
muralee36/Project
/Tic_Tac_Toe.py
4,731
4.125
4
#!/usr/bin/env python # coding: utf-8 # In[9]: # my 6th project # TIC TAC TOE GAME from IPython.display import clear_output # function to display board def display_board(my_list): clear_output() print(' | | ') print(' '+my_list[7] +' | ' + my_list[8]+' | '+my_list[9]) print(' | | ') print('-'*19) print(' | | ') print(' '+my_list[4] +' | ' + my_list[5]+' | '+my_list[6]) print(' | | ') print('-'*19) print(' | | ') print(' '+my_list[1] +' | ' + my_list[2]+' | '+my_list[3]) print(' | | ') # function to choose x or y def player_choice(): x=False while not x: choice=input('PLAYER 1 : DO YOU WANT TO PLAY AS X or O : ') if choice.upper() in ['X','O']: x=True else: print('ENTER VALID CHOICE') if choice.upper()=='X': return ['X','O'] else: return ['O','X'] #function to get player location def player_input(): x=False while not x: no=input('ENTER YOUR LOCATION [1-9]: ') if no.isdigit() and no in ['1','2','3','4','5','6','7','8','9']: x=True else: print('ENTER VALID LOCATION ') return int(no) # function to check if location is vacant def position_vacant(board,position): return board[position]==' ' # function to mark position def player_marker(board,position,player): board[position]=player # function to check if player won def win_check(board,player): return ((board[1]==board[2]==board[3]==player) or (board[4]==board[5]==board[6]==player) or (board[7]==board[8]==board[9]==player) or (board[7]==board[5]==board[3]==player) or (board[9]==board[5]==board[1]==player) or (board[7]==board[4]==board[1]==player) or (board[8]==board[5]==board[2]==player) or (board[9]==board[6]==board[3]==player)) # function to check if board is empty def full_check(board): return not ' ' in board # function to check if player wants to replay def replay(): x=False while not x: choice=input('DO YOU WANT TO REPLAY [Y/N] : ') if choice.upper() in ['Y','N']: x=True else: print('ENTER VALID CHOICE !') if choice.upper()=='Y': return True else: return False #function to select who goes first import random def choose_first(): if random.randint(0, 1) == 0: return 'Player 2' else: return 'Player 1' print('WELCOME TO TIC TAC TOE ') while True: # board with empty strings from loc 1-9 board=['invalid',' ',' ',' ',' ',' ',' ',' ',' ',' '] #player selects his/her marker player1_mark,player2_mark=player_choice() #choose whose going first turn=choose_first() print(turn+' goes first') choice=input('ARE YOU READY ? : ') if choice.upper()[0]=='Y': game_on=True else: game_on=False #game starts while game_on: #player 1 gameplay if turn=='Player 1': display_board(board) x=False while not x: marker=player_input() if position_vacant(board,marker): player_marker(board,marker,player1_mark) x=True else: print('LOCATION NOT VACANT') if win_check(board,player1_mark): display_board(board) print('CONGRATULATIONS PLAYER 1 WINS !!!!!') game_on=False break elif full_check(board): display_board(board) print('OOH!! THE GAME IS DRAW') game_on=False break else: turn='Player 2' else: display_board(board) x=False while not x: marker=player_input() if position_vacant(board,marker): player_marker(board,marker,player2_mark) x=True else: print('LOCATION NOT VACANT') if win_check(board,player2_mark): display_board(board) print('CONGRATULATIONS PLAYER 2 WINS !!!!!') game_on=False break elif full_check(board): display_board(board) print('OOH!! THE GAME IS DRAW') game_on=False break else: turn='Player 1' if not replay(): break # In[ ]:
63c9ac34a707fb9fa3eb1d1c86cedf5b2ad59ae6
XiaoqingNLP/SwordOffer
/exp34.py
2,673
3.640625
4
# -*- coding:utf-8 -*- import copy class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # 返回二维列表,内部每个列表表示找到的路径 def __init__(self): self.res = [] def FindPath(self, root, expectNumber): if not root or not expectNumber: return None path = [] cur_sum = 0 self.find(root, expectNumber, path, cur_sum) return self.res def find(self, root, expectNumber, path, cur_sum): path.append(root.val) cur_sum += path[-1] is_leaf = root.left is None and root.right is None if is_leaf and cur_sum == expectNumber: # print path self.res.append(copy.deepcopy(path)) # print self.res if root.left != None: self.find(root.left, expectNumber, path, cur_sum) if root.right != None: self.find(root.right, expectNumber, path, cur_sum) cur_sum -= path[-1] path.pop() def listcreattree(root,llist,i):###用列表递归创建二叉树, # 它其实创建过程也是从根开始a开始,创左子树b,再创b的左子树,如果b的左子树为空,返回none。 # 再接着创建b的右子树, if i < len(llist): if llist[i] == '#': return None ###这里的return很重要 else: root = TreeNode(llist[i]) # print('列表序号:'+str(i)+' 二叉树的值:'+str(root.val)) # 往左递推 root.left = listcreattree(root.left, llist, 2 * i + 1) # 从根开始一直到最左,直至为空, # 往右回溯 root.right = listcreattree(root.right, llist, 2 * i + 2) # 再返回上一个根,回溯右, # 再返回根' # print('************返回根:',root.val) return root ###这里的return很重要 return root def PrintFromTopToBottom(root): print "PrintFromTopToBottom" if not root: return [] res = [] queue = [] queue.append(root) while (queue): res.append(queue[0].val) if queue[0].left: queue.append(queue[0].left) if queue[0].right: queue.append(queue[0].right) queue.pop(0) print res return res def main(): a = Solution() root = listcreattree(0, [10, 5, 12, 4, 7], 0) PrintFromTopToBottom(root) expect = 22 res = a.FindPath(root, expect) print(res) if __name__ == '__main__': main()
fcff959a659e746c4112ad0b97f3c1b0336709c9
TP-TD-Informatique/tp1_info_501
/multiplication-Traini-Martins-Gomes.py
3,694
3.515625
4
#!/usr/bin/env python3 # global variable last_aux = 0 VERBOSE = False def log(*args, **kwargs): if VERBOSE: print(*args, **kwargs) def new_aux(): global last_aux last_aux += 1 return f"x_{last_aux}" def equal(x, y): log(f"~ >>> {x} := {y}") print(f"~{x} {y}") print(f"~{y} {x}") log() def xor2(r, x, y): log(f"~ >>> {r} := {x} ⊕ {y}") print(f"~{x} {y} {r}") print(f"{x} ~{y} {r}") print(f"{x} {y} ~{r}") print(f"~{x} ~{y} ~{r}") log() def carry2(r, x, y): log(f"~ >>> {r} := {x} ∧ {y}") print(f"{x} ~{r}") print(f"{y} ~{r}") print(f"~{x} ~{y} {r}") log() and2 = carry2 def xor3(r, x, y, z): log(f"~ >>> {r} := {x} ⊕ {y} ⊕ {z}") print(f"~{x} {y} {z} {r}") print(f"{x} ~{y} {z} {r}") print(f"{x} {y} ~{z} {r}") print(f"{x} {y} {z} ~{r}") print(f"~{x} ~{y} ~{z} {r}") print(f"~{x} ~{y} {z} ~{r}") print(f"~{x} {y} ~{z} ~{r}") print(f"{x} ~{y} ~{z} ~{r}") log() def carry3(r, x, y, z): log(f"~ >>> {r} := ⟨{x} {y} {z}⟩") print(f"{x} {y} {z} ~{r}") print(f"{x} {y} ~{z} ~{r}") print(f"{x} ~{y} {z} ~{r}") print(f"~{x} {y} {z} ~{r}") print(f"~{x} ~{y} {z} {r}") print(f"~{x} {y} ~{z} {r}") print(f"{x} ~{y} ~{z} {r}") print(f"~{x} ~{y} ~{z} {r}") log() def multiplier(n1, n2): n = n1 + n2 Bin = [[] for _ in range(n+1)] for i in range(n1): for j in range(n2): q = f"q_{i}_{j}" and2(q, f"a_{i}", f"b_{j}") Bin[i+j].append(q) for k in range(n): assert Bin[k] log(f"~ >>>>>> Bin[{k}] = {Bin[k]}") while Bin[k]: if len(Bin[k]) == 1: equal(f"p_{k}", Bin[k].pop()) assert not Bin[k] break if len(Bin[k]) == 2: a = Bin[k].pop() b = Bin[k].pop() xor2(f"p_{k}", a, b) c = new_aux() carry2(c, a, b) Bin[k+1].append(c) assert not Bin[k] break r = new_aux() x = new_aux() a = Bin[k].pop() b = Bin[k].pop() c = Bin[k].pop() xor3(r, a, b, c) carry3(x, a, b, c) Bin[k].append(r) Bin[k+1].append(x) def help(exe): print(f"utilisation: {exe} n1 n2 [p]") print(""" - n1 est le nombre de bits pour a - n2 est le nombre de bits pour b - p est le produit, qui doit tenir sur n1+n2 bits""") if __name__ == "__main__": from sys import argv, exit, stderr try: n1 = int(argv[1]) n2 = int(argv[2]) except (ValueError, IndexError): help(argv[0]) exit(1) n = n1 + n2 try: p = int(argv[3]) except IndexError: from random import randrange p = randrange(0, randrange(0, 2**n)) print(f">>> no 'p' number given, using {p}", file=stderr) except ValueError: print(f"invalid 'p' number: {p}", file=stderr) exit(1) # entêtes print(f"~ n1 = {n1}, n2 = {n2}, n = {n}, p = {p}") print(f"~ les bits de a et b (facteurs de p) sont contenus dans les bits a_0 a_1 ... a_n1 et b_0 b_1 ... b_n2") # NOTE: # les nombres a et b sont contenus dans les bits a_0 ... a_n1 et b_0 ... b_n2 # le produit p est contenu dans les bits p_0 ... p_n # les autres variables (x_1, ...) sont des variables auxiliaires pour les résultats intermédiaires # clauses correspondant au circuit multiplicateur multiplier(n1, n2) # les bits p_0 ... p_n sont bien les bits de p # TODO ...
9d763864b426ed7226e45a285cd69505f20c38a9
wanghan79/2020_Python
/张缤予2018010982/平时作业1随机数生成与筛选/randomData(first).py
3,485
4.34375
4
##!/usr/bin/python3 """ Author: By.Zhang Purpose:Generate random data set. Created:3/5/2020 """ import random import string def dataSampling(datatype, datarange, num, strlen=8): ''' :Description:Generate a given condition random data set. :param datatype: the data type you want to sample including int, float,str. :param datarange: iterable data set :param num: the number of data you need :param strlen: the length of each string you want to generate :return: a data set ''' try: if num < 0: print("Please input correct num in dataSampling.") if strlen < 0: print("Please input correct strlen in dataSampling") result = set() if datatype is int: while len(result) < num: it = iter(datarange) item = random.randint(next(it), next(it)) result.add(item) elif datatype is float: while len(result) <num: it = iter(datarange) item = random.uniform(next(it), next(it)) result.add(item) elif datatype is str: while len(result) < num: item = ''.join(random.SystemRandom().choice(datarange) for _ in range(strlen)) result.add(item) except ValueError: print("Maybe num is not correct.") except NameError: print("Maybe your datatype is wrong.") except TypeError: print("Maybe your num is different with your datatype.") except MemoryError: print("Maybe memory is full.") except: raise else: return result finally: pass def dataScreening(data, *conditions): #*args ''' :Description: according the conditions to pick the correct data in dataSampling :param data: iterable data set :param conditions: the condition such as range or string you want to screen from a data set :return: a data set ''' result = set() # Screening try: for i in data: if type(i) is int: it = iter(conditions) if next(it) <= i and next(it) >= i: result.add(i) elif type(i) is float: it = iter(conditions) if next(it) <= i and next(it) >= i: result.add(i) elif type(i) is str: for teststr in conditions: if teststr in i: result.add(i) except Exception as e: print("Maybe your condition or data is not correct.") return result def apply(): # int类型例子 result_1 = dataSampling(int, [0, 280], 100) print('随机生成100个在0~280内的整数:') print(result_1) print('筛选其中在10~50之间的数:') print(dataScreening(result_1, 10, 50)) print('\n') # float类型例子 result_2 = dataSampling(float, [0, 200], 100) print('随机生成100个在0~200内的浮点数:') print(result_2) print('筛选其中在20~60之间的数:') print(dataScreening(result_2, 20, 60)) print('\n') # str类型例子 str_ex = string.ascii_letters + string.digits + string.punctuation result_3= dataSampling(str, str_ex, 1000, 20) print('随机生成1000个字符串长度为20的字符串:') print(result_3) print('筛选其中含有‘at’或者‘no’的字符串:') print(dataScreening(result_3, 'at', 'no')) apply()
be44d74c75ea7f7f16fbbd24a160929f1e631bf4
nininininini/sentiment_analysis
/test_vocab.py
1,073
3.71875
4
import os import string # build vocabulary def buildvocab(N): vocab = [] stopwords = open('stopwords.txt').read().lower().split() vocab1 = {} # TODO: Populate vocab list with N most frequent words in training data, minus stopwords root = os.getcwd() root += '/pos' for file in os.listdir(root): if file.endswith(".txt"): with open(root + '/' + file, 'r') as f: for line in f: words = line.lower().split(' ') for word in words: if word not in stopwords and word not in string.punctuation: if word not in vocab1: vocab1[word] = 0 else: vocab1[word] += 1 # need to cut vocab list down to N most frequent words vocab = [0 for i in range(N+1)] limiter = 0 while len(vocab) > N: vocab = [(k, v) for k, v in vocab1.items() if v > limiter] print len(vocab) limiter += 1 return vocab
506ec465fbfe5ed1f89caed4b389672ac2c996ba
kkxujq/leetcode
/answer/0004/4.linningmii.py
1,299
3.65625
4
# FIXME 这个不是正确解, 不满足时间复杂度 class Solution: def findMedianSortedArrays(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: float """ pointer1 = 0 pointer2 = 0 merged_list = [] while pointer1 < len(nums1) or pointer2 < len(nums2): if pointer1 >= len(nums1): merged_list.append(nums2[pointer2]) pointer2 += 1 continue if pointer2 >= len(nums2): merged_list.append(nums1[pointer1]) pointer1 += 1 continue if nums1[pointer1] <= nums2[pointer2]: merged_list.append(nums1[pointer1]) pointer1 += 1 else: merged_list.append(nums2[pointer2]) pointer2 += 1 merged_list_length = len(merged_list) if merged_list_length % 2 == 1: return merged_list[int(merged_list_length / 2)] else: return (merged_list[int(merged_list_length / 2) - 1] + merged_list[int(merged_list_length / 2)]) / 2 solution = Solution() print(solution.findMedianSortedArrays([1, 3], [2])) print(solution.findMedianSortedArrays([1, 2], [3, 4]))
eb8937fb9a4e5e4f33847661d94e8e956748f27c
realcundo/microbit-playground
/dice.py
3,181
3.96875
4
""" Simple die simulator. Shake and then leave for 2 seconds to see the result. Whilst shaking press either button to cheat! """ import microbit # all 6 dice faces dice_faces = [ " \n" " \n" " 9 \n" " \n" " \n", "9 \n" " \n" " \n" " \n" " 9\n", "9 \n" " \n" " 9 \n" " \n" " 9\n", "9 9\n" " \n" " \n" " \n" "9 9\n", "9 9\n" " \n" " 9 \n" " \n" "9 9\n", "9 9\n" " \n" "9 9\n" " \n" "9 9\n", ] # convert them to images so they can be displayed directly dice_faces = [microbit.Image(x) for x in dice_faces] result = 0 result_countdown = int(2000/50) # pretend we started with shaking last_accelerometer = microbit.accelerometer.get_values() cheating_enabled = False # not sure if this is needed, but pretend to seed the random generator for _ in range(last_accelerometer[0]): microbit.random(10) # main loop while True: microbit.sleep(50) # get accelerometer difference between now and last 50ms current_accelerometer = microbit.accelerometer.get_values() dx = last_accelerometer[0] - current_accelerometer[0] dy = last_accelerometer[1] - current_accelerometer[1] dz = last_accelerometer[2] - current_accelerometer[2] last_accelerometer = current_accelerometer # let's say we have shaken the board if diff >= 1000^2 is_shaking = (dx*dx + dy*dy + dz*dz) >= 1000*1000 # if we stopped shaking, count down to zero for the dice result # if we're still shaking, (re)initialise the counter if is_shaking: result_countdown = int(2000/50) # 2 seconds countdown # whilst shaking, check if either button is pressed. If so, enable cheating if microbit.button_a.is_pressed() or microbit.button_b.is_pressed(): cheating_enabled = True # choose random (temporary) result if we're still counting down if result_countdown > 0: result = microbit.random(6) result_countdown -= 1 # if we haven't reached countdown, display temporary result if result_countdown > 0: microbit.display.show(dice_faces[result]) # make the display look more random by adding some dots. # display fewer dots as we're getting closer to the result for _ in range(microbit.random(int(result_countdown/5))): microbit.display.set_pixel(microbit.random(5), microbit.random(5), microbit.random(10)) else: # we've reached the countdown, so display the result # show 6 if we're cheating if cheating_enabled: result = 5 microbit.display.show(dice_faces[result]) cheating_enabled = False
f48ec584163f4e63611c54741e2a4103d13eca7b
Deepti1289/python_codes
/string/search_substring.py
311
3.6875
4
#!/usr/bin/python import re my_str = raw_input("Input string :") sub_str = raw_input("Input string :") x = re.search(sub_str,my_str) i = 0 if not x: print(-1,-1) while x!= None: print((x.start()+i, x.end()-1+i)) i += x.start()+1 my_str = my_str[x.start()+1:] x = re.search(sub_str,my_str)
d1907163cdf154392f19e8c5fe2d9311441e7db4
Aasthaengg/IBMdataset
/Python_codes/p02379/s511972884.py
119
3.671875
4
import math x1,y1,x2,y2 = (float(x) for x in input().split()) d = math.sqrt((x2 - x1)**2 + (y2 - y1)**2.0) print (d)
12a21fdbe603f87a43456c0a3a98a1373eb3a2b0
nwthomas/code-challenges
/src/leetcode/medium/clone-graph/clone_graph.py
2,822
3.71875
4
""" https://leetcode.com/problems/clone-graph/ Given a reference of a node in a connected undirected graph. Return a deep copy (clone) of the graph. Each node in the graph contains a value (int) and a list (List[Node]) of its neighbors. class Node { public int val; public List<Node> neighbors; } Test case format: For simplicity, each node's value is the same as the node's index (1-indexed). For example, the first node with val == 1, the second node with val == 2, and so on. The graph is represented in the test case using an adjacency list. An adjacency list is a collection of unordered lists used to represent a finite graph. Each list describes the set of neighbors of a node in the graph. The given node will always be the first node with val = 1. You must return the copy of the given node as a reference to the cloned graph. Example 1: Input: adjList = [[2,4],[1,3],[2,4],[1,3]] Output: [[2,4],[1,3],[2,4],[1,3]] Explanation: There are 4 nodes in the graph. 1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4). 2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3). 3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4). 4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3). Example 2: Input: adjList = [[]] Output: [[]] Explanation: Note that the input contains one empty list. The graph consists of only one node with val = 1 and it does not have any neighbors. Example 3: Input: adjList = [] Output: [] Explanation: This an empty graph, it does not have any nodes. Constraints: The number of nodes in the graph is in the range [0, 100]. 1 <= Node.val <= 100 Node.val is unique for each node. There are no repeated edges and no self-loops in the graph. The Graph is connected and all nodes can be visited starting from the given node. """ class Node: def __init__(self, val = 0, neighbors = None): self.val = val self.neighbors = neighbors if neighbors is not None else [] def clone_graph(node: Node) -> Node: if not node: return None root = Node(node.val, []) cache = { node.val: root } stack = [[node.val, node.neighbors]] while len(stack) > 0: value, neighbors = stack.pop() new_node = Node(value, []) if value in cache: new_node = cache[value] for neighbor in neighbors: new_neighbor = Node(neighbor.val, []) if neighbor.val in cache: new_neighbor = cache[neighbor.val] else: cache[neighbor.val] = new_neighbor stack.append([neighbor.val, neighbor.neighbors]) new_node.neighbors.append(new_neighbor) return root
a5c58c161d0aeb526681645994780e2d9835bef5
tylerdegen/coding-practice
/10-28-2016/2.py
2,072
3.515625
4
class TreeNode: def __init__(self, data): self.data = data self.children = [] def shade(self): for child in children: print child.data x = TreeNode("woff") print(x.data) '''def solution (X): indent = 0 index_of_root = 0 index = 0 lines = X.split(str="\n") roots = [] for line in lines: #if line[indent] == " ": # indent += 1 # if a root dir if indent == 0 roots[index_of_root] = TreeNode(len(line)) index_of_root += 1 else: if line[indent] != " ": # else: # index += 1 ''' def createTree(parent, lines, index, indent): while index < len(lines): line = lines[index] #dir = "." not in line #if !dir: if "." not in line: #check to make sure in same directory samedirectory = indent == line.count(' ') if samedirectory: parent.children.append(line) index += 1 else: #done adding children to tree return index #this line IS a directory else: x = TreeNode(dirname) print("WOO RECURSION") index = createTree(x, lines, index, indent + 1) parent.children.append(x) with open("2input.txt") as f: lines = f.readlines() print lines rootNode = TreeNode("root") createTree(rootNode, lines, 0, 0) for child in rootNode.children: print child ''' def create_tree(dict): x = NodeTree() for a in d.keys(): if type( def solution(X, indent) #call solution on each new directory #find the longest string at that indentation row and return its length lines = X.split(str="\n") for line in lines if indent = 0 dirlevel = [] for line in lines: if line[indent] == " ": indent += 1 for line in X if line[X + indent] == " ": solution(line, indent+1) def dirDive(indent, index, lines) . return index dir = [] dir.append(line) if line[indent] != ' ': #it's at same level dir.append(line) if indent != 0: if line[indent - 1] != ' ': #that level is finished break #while index < lines.size() #if indent is == to current directory level x.append(len(line)) #if not x.append(size(line)) x.append(size(line, '''
a15aa2a5ac34b1d94f34d70a78749029e7553277
viviane-menezes/Calculadora--python
/calculadora.py
776
4.125
4
print("****************Python Calculator****************") print("Selecione o número da operação desejada:") print("1 - Soma") print("2 - Subtração") print("3 - Multiplicação") print("4 - Divisão") def soma(x,y): s =x+y print( "A soma é :",s) def subtracao(x,y): sub =x-y print("A subtração é :",sub) def multiplicacao(x,y): mult = x*y print("A multiplicação é :",mult) def divisao(x,y): div = x/y print(" A divisão é: ", div) opcao=int(input("Digite sua opção:")) num1= int(input("Digite o primeiro número:")) num2=int(input("Digite o segundo número:")) if opcao ==1: soma(num1,num2) elif opcao==2: subtracao(num1,num2) elif opcao==3: multiplicacao(num1,num2) elif opcao ==4: divisao(num1,num2) else: print("Opção inválida")
f73d3869e69b9b6ca21a4076413ad729b80ae140
fuyixuannnn/storeeee
/工行.py
8,306
3.8125
4
print("==============================================") print("|--------------青岛银行账户管理系统--------------|") print("|------------1、开户 ------------|") print("|------------2、取钱 ------------|") print("|------------3、存钱 ------------|") print("|------------4、转账 ------------|") print("|------------5、查询 ------------|") print("|------------6、退出 ------------|") print("==============================================") bank = {} # 创建随机账号 import random # 开户功能 bank_name = "青岛银行" # 第一个对应第一个 不是名称对应名称 def bank_adduser(account, username, password, country, province, street, door): if len(bank) > 100: return 3 if account in bank: return 2 bank[account] = { "username": username, "password": password, "country": country, "province": province, "street": street, "door": door, "balance": 0, "bank_name": bank_name } return 1 def adduser(): username = input("请输入您的用户名") account = random.randint(10000000, 99999999) print("账号为", account) password = input("请输入您的密码") print("请输入您的地址") country = input("\t\t请输入您的国家") province = input("\t\t请输入您的省份") street = input("\t\t请输入您的街道") door = input("\t\t请输入您的门牌号") stat = bank_adduser(account, username, password, country, province, street, door) if stat == 3: print("再等等吧~") elif stat == 2: print("用户已存在!") elif stat == 1: bank["account"] = account info = ''' ------------个人信息------------ 用户名:%s 账号:%s 密码:***** 国籍:%s 省份:%s 街道:%s 门牌号:%s 余额:%s元 开户行名称:%s ''' # 每个元素都可传入% print(info % (username, account, country, province, street, door, bank[account]["balance"], bank_name)) # 存钱功能 def saving(): account = int(input("请输入账号(返回请输入0):")) if account in bank: save_amount = float(input("请放入金额:¥")) bank[account]["balance"] += save_amount print("当前余额:¥", bank[account]["balance"]) switch = input("是否继续存钱?YES or NO") while True: if switch == "YES" or switch == "yes": save_amount = float(input("请放入金额:¥")) bank[account]["balance"] += save_amount print("当前余额:¥", bank[account]["balance"]) switch = input("是否继续存钱?YES or NO") elif switch == "NO" or switch == "no": print("当前余额:¥", bank[account]["balance"]) return False elif account == 0: print("当前余额:¥", bank[account]["balance"]) return False else: return False # def check_account(account): # if account not in bank: # return 1 # # # def check_password(account, password): # if account in bank and password != bank[account]["password"]: # return 2 # bank[account] = {"password": password} # # # def check_money(account): # if account in bank and bank[account]["balance"] < 0: # return 3 # 取钱功能 def withdrawing(): # account = int(input("请输入账号:")) # stat = check_account(account) # if stat == 1: # print("账号不存在") # else: # password = input("请输入密码:") # stat = check_password(account, password) # if stat == 2: # print("密码错误!") # return False # else: # money = float(input("请输入取出的金额:¥")) # bank[account]["balance"] -= money # stat = check_money(account) # while True: # if stat == 3: # print("余额不足!") # else: # print("当前余额:¥", bank[account]["balance"]) # switch = input("是否继续取钱?YES or NO") # if switch == "YES" or switch == "yes": # print("当前余额:¥", bank[account]["balance"]) # money = float(input("请输入取出的金额:¥")) # elif switch == "NO" or switch == "no": # return False account = int(input("请输入账号(返回请输入0):")) if account in bank: password = input("请输入密码:") if password == bank[account]["password"]: wd_amount = float(input("请取出金额:¥")) bank[account]["balance"] -= wd_amount if bank[account]["balance"] < 0: print("余额不足") else: print("当前余额:¥", bank[account]["balance"]) switch = input("是否继续取钱?YES or NO") while True: if switch == "YES" or switch == "yes": wd_amount = float(input("请取出金额:¥")) bank[account]["balance"] -= wd_amount if bank[account]["balance"] < 0: print("余额不足") else: print("当前余额:¥", bank[account]["balance"]) switch = input("是否继续取钱?YES or NO") elif switch == "NO" or switch == "no": print("当前余额:¥", bank[account]["balance"]) return False elif account == 0: print("当前余额:¥", bank[account]["balance"]) return False else: print("密码错误!") else: print("账号不存在!") return False # 转账 def transfer(): faccount = int(input("请输入转出账号")) taccount = int(input("请输入转入账号")) if faccount and taccount in bank: password = input("请输入转出账号密码") if password == bank[faccount]["password"]: print("当前余额为¥", bank[faccount]["balance"]) money = float(input("请输入转账金额:¥")) if money <= bank[faccount]["balance"]: bank[faccount]["balance"] -= money bank[taccount]["balance"] += money print("转账成功!") else: print("密码错误!") else: print("账号不存在!") # 查询功能 def query(): account_number = int(input("请输入想要查询的账号:")) if account_number in bank: pswd = input("请输入密码:") if pswd == bank[account_number]["password"]: print("密码正确!") info = ''' 用户名:%s 账号:%s 密码:%s 用户居住地址:%s 余额:%s元 开户行名称:%s ''' print(info % (bank[account_number]["username"], account_number, bank[account_number]["password"], bank[account_number]["country"] + bank[account_number]["province"] + bank[account_number][ "street"] + bank[account_number]["door"], bank[account_number]["balance"], bank[account_number]["bank_name"])) else: print("密码错误") else: print("该账号不存在!") while True: begin = input("请选择业务") if begin == "1": adduser() elif begin == "2": withdrawing() elif begin == "3": saving() elif begin == "4": transfer() elif begin == "5": query() else: print(6, "、退出") break
5c96b892cfb6aba24c9e783d31550f589b78fb33
amerc/TCP3
/chips2/chips/compiler/verilog_area.py
64,124
3.984375
4
#!/usr/bin/env python """Generate Verilog Implementation of Instructions The area optimized implementation uses a CPU like architecture. + Instructions are implemented in block RAM. + Registers are implemented in dual port RAM. + Only one instruction can be executed at a time. + The CPU uses a pipeline architecture, and will take 2 clocks to execute a taken branch. + A minimal instruction set is determined at compile time, and only those instructions are implemented. """ __author__ = "Jon Dawson" __copyright__ = "Copyright (C) 2013, Jonathan P Dawson" __version__ = "0.1" import fpu def unique(l): """In the absence of set in older python implementations, make list values unique""" return dict(zip(l, l)).keys() def log2(instructions): """Integer only algorithm to calculate the number of bits needed to store a number""" bits = 1 power = 2 while power < instructions: bits += 1 power *= 2 return bits def print_verilog_literal(size, value): """Print a verilog literal with expicilt size""" if(value >= 0): return "%s'd%s"%(size, value) else: return "-%s'd%s"%(size, abs(value)) def remove_register_hazards(instructions): """search through instructions, and remove register hazards""" wait_2_for = None wait_1_for = None new_instructions = [] for instruction in instructions: wait = 0 if "src" in instruction: if instruction["src"] == wait_1_for: wait = max(wait, 1) if instruction["src"] == wait_2_for: wait = max(wait, 2) if "srcb" in instruction: if instruction["srcb"] == wait_1_for: wait = max(wait, 1) if instruction["srcb"] == wait_2_for: wait = max(wait, 2) for i in range(wait): new_instructions.append({"op":"nop"}) new_instructions.append(instruction) if instruction["op"] != "label": wait_1_for = wait_2_for if "dest" in instruction: wait_2_for = instruction["dest"] else: wait_2_for = None return new_instructions def generate_instruction_set(instructions): """Calculate the required instruction set""" instruction_set = [] instruction_memory = [] for instruction in instructions: opcode = {} encoded_instruction = {} encoded_instruction["dest"] = 0 encoded_instruction["src"] = 0 encoded_instruction["srcb"] = 0 encoded_instruction["literal"] = 0 encoded_instruction["float"] = True opcode["op"] = instruction["op"] opcode["right"] = False opcode["unsigned"] = False opcode["literal"] = False opcode["float"] = False if "signed" in instruction: opcode["unsigned"] = not instruction["signed"] if "element_size" in instruction: opcode["element_size"] = instruction["element_size"] if "file_name" in instruction: opcode["file_name"] = instruction["file_name"] if "file" in instruction: opcode["file"] = instruction["file"] if "line" in instruction: opcode["line"] = instruction["line"] if "input" in instruction: opcode["input"] = instruction["input"] if "output" in instruction: opcode["output"] = instruction["output"] if "dest" in instruction: encoded_instruction["dest"] = instruction["dest"] if "src" in instruction: encoded_instruction["src"] = instruction["src"] if "srcb" in instruction: encoded_instruction["srcb"] = instruction["srcb"] if "left" in instruction: opcode["literal"] = True encoded_instruction["literal"] = instruction["left"] if "right" in instruction: opcode["literal"] = True opcode["right"] = True encoded_instruction["literal"] = instruction["right"] if "type" in instruction: if instruction["type"] == "float": opcode["float"] = True encoded_instruction["float"] = True if "literal" in instruction: opcode["literal"] = True encoded_instruction["literal"] = instruction["literal"] if "label" in instruction: opcode["literal"] = True encoded_instruction["literal"] = instruction["label"] if opcode not in instruction_set: instruction_set.append(opcode) for op, test_opcode in enumerate(instruction_set): if test_opcode == opcode: encoded_instruction["op"] = op encoded_instruction["comment"] = repr(instruction) instruction_memory.append(encoded_instruction) break return instruction_set, instruction_memory def calculate_jumps(instructions): """change symbolic labels into numeric addresses""" #calculate the values of jump locations location = 0 labels = {} new_instructions = [] for instruction in instructions: if instruction["op"] == "label": labels[instruction["label"]] = location else: new_instructions.append(instruction) location += 1 instructions = new_instructions #substitue real values for labeled jump locations for instruction in instructions: if "label" in instruction: instruction["label"]=labels[instruction["label"]] return instructions def generate_declarations(instructions, no_tb_mode, register_bits, opcode_bits): """Generate verilog declarations""" #list all inputs and outputs used in the program inputs = unique([i["input"] for i in instructions if "input" in i]) outputs = unique([i["output"] for i in instructions if "output" in i]) input_files = unique([i["file_name"] for i in instructions if "file_read" == i["op"]]) output_files = unique([i["file_name"] for i in instructions if "file_write" == i["op"]]) testbench = not inputs and not outputs and not no_tb_mode #Do not generate a port in testbench mode inports = [ ("input_" + i, 16) for i in inputs ] + [ ("input_" + i + "_stb", 1) for i in inputs ] + [ ("output_" + i + "_ack", 1) for i in outputs ] outports = [ ("output_" + i, 16) for i in outputs ] + [ ("output_" + i + "_stb", 1) for i in outputs ] + [ ("input_" + i + "_ack", 1) for i in inputs ] #create list of signals signals = [ ("timer", 16), ("timer_enable", 1), ("stage_0_enable", 1), ("stage_1_enable", 1), ("stage_2_enable", 1), ("program_counter", log2(len(instructions))), ("program_counter_0", log2(len(instructions))), ("instruction_0", 32 + register_bits*2 + opcode_bits), ("opcode_0", opcode_bits), ("dest_0", register_bits), ("src_0", register_bits), ("srcb_0", register_bits), ("literal_0", 32), ("program_counter_1", log2(len(instructions))), ("opcode_1", opcode_bits), ("dest_1", register_bits), ("register_1", 32), ("registerb_1", 32), ("literal_1", 32), ("dest_2", register_bits), ("result_2", 32), ("write_enable_2", 1), ("address_2", 16), ("data_out_2", 16), ("data_in_2", 16), ("memory_enable_2", 1), ("address_4", 16), ("data_out_4", 32), ("data_in_4", 32), ("memory_enable_4", 1), ] + [ ("s_output_" + i + "_stb", 16) for i in outputs ] + [ ("s_output_" + i, 16) for i in outputs ] + [ ("s_input_" + i + "_ack", 16) for i in inputs ] if testbench: signals.append(("clk", 1)) signals.append(("rst", 1)) else: inports.append(("clk", 1)) inports.append(("rst", 1)) return inputs, outputs, input_files, output_files, testbench, inports, outports, signals def floating_point_enables(instruction_set): enable_adder = False enable_multiplier = False enable_divider = False enable_int_to_float = False enable_float_to_int = False for i in instruction_set: if i["op"] == "+" and i["float"]: enable_adder = True if i["op"] == "-" and i["float"]: enable_adder = True if i["op"] == "*" and i["float"]: enable_multiplier = True if i["op"] == "/" and i["float"]: enable_divider = True if i["op"] == "int_to_float": enable_int_to_float = True if i["op"] == "float_to_int": enable_float_to_int = True return ( enable_adder, enable_multiplier, enable_divider, enable_int_to_float, enable_float_to_int) def generate_CHIP(input_file, name, instructions, output_file, registers, memory_size_2, memory_size_4, initialize_memory, memory_content_2, memory_content_4, no_tb_mode=False): """A big ugly function to crunch through all the instructions and generate the CHIP equivilent""" instructions = remove_register_hazards(instructions) instructions = calculate_jumps(instructions) instruction_set, instruction_memory = generate_instruction_set(instructions) register_bits = log2(len(registers)); opcode_bits = log2(len(instruction_set)); instruction_bits = 32 + register_bits*2 + opcode_bits declarations = generate_declarations(instructions, no_tb_mode, register_bits, opcode_bits) inputs, outputs, input_files, output_files, testbench, inports, outports, signals = declarations enable_adder, enable_multiplier, enable_divider, enable_int_to_float, enable_float_to_int = floating_point_enables(instruction_set) #output the code in verilog output_file.write("//////////////////////////////////////////////////////////////////////////////\n") output_file.write("//name : %s\n"%name) for i in inputs: output_file.write("//input : input_%s:16\n"%i) for i in outputs: output_file.write("//output : output_%s:16\n"%i) output_file.write("//source_file : %s\n"%input_file) output_file.write("///%s\n"%"".join(["=" for i in name])) output_file.write("///\n") output_file.write("///Created by C2CHIP\n\n") if enable_adder: output_file.write(fpu.adder) if enable_divider: output_file.write(fpu.divider) if enable_multiplier: output_file.write(fpu.multiplier) if enable_int_to_float: output_file.write(fpu.int_to_float) if enable_float_to_int: output_file.write(fpu.float_to_int) output_file.write("//////////////////////////////////////////////////////////////////////////////\n") output_file.write("// Register Allocation\n") output_file.write("// ===================\n") output_file.write("// %s %s %s \n"%("Register".center(20), "Name".center(20), "Size".center(20))) for register, definition in registers.iteritems(): register_name, size = definition output_file.write("// %s %s %s \n"%(str(register).center(20), register_name.center(20), str(size).center(20))) output_file.write("module %s"%name) all_ports = [name for name, size in inports + outports] if all_ports: output_file.write("(") output_file.write(",".join(all_ports)) output_file.write(");\n") else: output_file.write(";\n") output_file.write(" integer file_count;\n") if enable_adder: generate_adder_signals(output_file) if enable_multiplier: generate_multiplier_signals(output_file) if enable_divider: generate_divider_signals(output_file) if enable_int_to_float: generate_int_to_float_signals(output_file) if enable_float_to_int: generate_float_to_int_signals(output_file) output_file.write(" real fp_value;\n") if enable_adder or enable_multiplier or enable_divider or enable_int_to_float or enable_float_to_int: output_file.write(" parameter wait_go = 2'd0,\n") output_file.write(" write_a = 2'd1,\n") output_file.write(" write_b = 2'd2,\n") output_file.write(" read_z = 2'd3;\n") input_files = dict(zip(input_files, ["input_file_%s"%i for i, j in enumerate(input_files)])) for i in input_files.values(): output_file.write(" integer %s;\n"%i) output_files = dict(zip(output_files, ["output_file_%s"%i for i, j in enumerate(output_files)])) for i in output_files.values(): output_file.write(" integer %s;\n"%i) def write_declaration(object_type, name, size, value=None): if size == 1: output_file.write(object_type) output_file.write(name) if value is not None: output_file.write("= %s'd%s"%(size,value)) output_file.write(";\n") else: output_file.write(object_type) output_file.write("[%i:0]"%(size-1)) output_file.write(" ") output_file.write(name) if value is not None: output_file.write("= %s'd%s"%(size,value)) output_file.write(";\n") for name, size in inports: write_declaration(" input ", name, size) for name, size in outports: write_declaration(" output ", name, size) for name, size in signals: write_declaration(" reg ", name, size) memory_size_2 = int(memory_size_2) memory_size_4 = int(memory_size_4) if memory_size_2: output_file.write(" reg [15:0] memory_2 [%i:0];\n"%(memory_size_2-1)) if memory_size_4: output_file.write(" reg [31:0] memory_4 [%i:0];\n"%(memory_size_4-1)) output_file.write(" reg [%s:0] instructions [%i:0];\n"%(instruction_bits-1, len(instructions)-1)) output_file.write(" reg [31:0] registers [%i:0];\n"%(len(registers)-1)) #generate clock and reset in testbench mode if testbench: output_file.write("\n //////////////////////////////////////////////////////////////////////////////\n") output_file.write(" // CLOCK AND RESET GENERATION \n") output_file.write(" // \n") output_file.write(" // This file was generated in test bench mode. In this mode, the verilog \n") output_file.write(" // output file can be executed directly within a verilog simulator. \n") output_file.write(" // In test bench mode, a simulated clock and reset signal are generated within\n") output_file.write(" // the output file. \n") output_file.write(" // Verilog files generated in testbecnch mode are not suitable for synthesis, \n") output_file.write(" // or for instantiation within a larger design.\n") output_file.write(" \n initial\n") output_file.write(" begin\n") output_file.write(" rst <= 1'b1;\n") output_file.write(" #50 rst <= 1'b0;\n") output_file.write(" end\n\n") output_file.write(" \n initial\n") output_file.write(" begin\n") output_file.write(" clk <= 1'b0;\n") output_file.write(" while (1) begin\n") output_file.write(" #5 clk <= ~clk;\n") output_file.write(" end\n") output_file.write(" end\n\n") #Instance Floating Point Arithmetic if enable_adder or enable_multiplier or enable_divider or enable_int_to_float or enable_float_to_int: output_file.write("\n //////////////////////////////////////////////////////////////////////////////\n") output_file.write(" // Floating Point Arithmetic \n") output_file.write(" // \n") output_file.write(" // Generate IEEE 754 single precision divider, adder and multiplier \n") output_file.write(" // \n") if enable_divider: connect_divider(output_file) if enable_multiplier: connect_multiplier(output_file) if enable_adder: connect_adder(output_file) if enable_int_to_float: connect_int_to_float(output_file) if enable_float_to_int: connect_float_to_int(output_file) #Generate a state machine to execute the instructions binary_operators = ["+", "-", "*", "/", "|", "&", "^", "<<", ">>", "<",">", ">=", "<=", "==", "!="] if initialize_memory and (memory_content_2 or memory_content_4): output_file.write("\n //////////////////////////////////////////////////////////////////////////////\n") output_file.write(" // MEMORY INITIALIZATION \n") output_file.write(" // \n") output_file.write(" // In order to reduce program size, array contents have been stored into \n") output_file.write(" // memory at initialization. In an FPGA, this will result in the memory being \n") output_file.write(" // initialized when the FPGA configures. \n") output_file.write(" // Memory will not be re-initialized at reset. \n") output_file.write(" // Dissable this behaviour using the no_initialize_memory switch \n") output_file.write(" \n initial\n") output_file.write(" begin\n") for location, content in memory_content_2.iteritems(): output_file.write(" memory_2[%s] = %s;\n"%(location, content)) for location, content in memory_content_4.iteritems(): output_file.write(" memory_4[%s] = %s;\n"%(location, content)) output_file.write(" end\n\n") output_file.write("\n //////////////////////////////////////////////////////////////////////////////\n") output_file.write(" // INSTRUCTION INITIALIZATION \n") output_file.write(" // \n") output_file.write(" // Initialise the contents of the instruction memory \n") output_file.write(" //\n") output_file.write(" // Intruction Set\n") output_file.write(" // ==============\n") for num, opcode in enumerate(instruction_set): output_file.write(" // %s %s\n"%(num, opcode)) output_file.write(" // Intructions\n") output_file.write(" // ===========\n") output_file.write(" \n initial\n") output_file.write(" begin\n") for location, instruction in enumerate(instruction_memory): output_file.write(" instructions[%s] = {%s, %s, %s, %s};//%s\n"%( location, print_verilog_literal(opcode_bits, instruction["op"]), print_verilog_literal(register_bits, instruction["dest"]), print_verilog_literal(register_bits, instruction["src"]), print_verilog_literal(32, instruction["srcb"] | instruction["literal"]), instruction["comment"])) output_file.write(" end\n\n") if input_files or output_files: output_file.write("\n //////////////////////////////////////////////////////////////////////////////\n") output_file.write(" // OPEN FILES \n") output_file.write(" // \n") output_file.write(" // Open all files used at the start of the process \n") output_file.write(" \n initial\n") output_file.write(" begin\n") for file_name, file_ in input_files.iteritems(): output_file.write(" %s = $fopenr(\"%s\");\n"%(file_, file_name)) for file_name, file_ in output_files.iteritems(): output_file.write(" %s = $fopen(\"%s\");\n"%(file_, file_name)) output_file.write(" end\n\n") output_file.write("\n //////////////////////////////////////////////////////////////////////////////\n") output_file.write(" // CPU IMPLEMENTAION OF C PROCESS \n") output_file.write(" // \n") output_file.write(" // This section of the file contains a CPU implementing the C process. \n") output_file.write(" \n always @(posedge clk)\n") output_file.write(" begin\n\n") if memory_size_2: output_file.write(" //implement memory for 2 byte x n arrays\n") output_file.write(" if (memory_enable_2 == 1'b1) begin\n") output_file.write(" memory_2[address_2] <= data_in_2;\n") output_file.write(" end\n") output_file.write(" data_out_2 <= memory_2[address_2];\n") output_file.write(" memory_enable_2 <= 1'b0;\n\n") if memory_size_4: output_file.write(" //implement memory for 4 byte x n arrays\n") output_file.write(" if (memory_enable_4 == 1'b1) begin\n") output_file.write(" memory_4[address_4] <= data_in_4;\n") output_file.write(" end\n") output_file.write(" data_out_4 <= memory_4[address_4];\n") output_file.write(" memory_enable_4 <= 1'b0;\n\n") output_file.write(" write_enable_2 <= 0;\n") if enable_divider: output_file.write(" divider_go <= 0;\n") if enable_multiplier: output_file.write(" multiplier_go <= 0;\n") if enable_adder: output_file.write(" adder_go <= 0;\n") if enable_int_to_float: output_file.write(" int_to_float_go <= 0;\n") if enable_float_to_int: output_file.write(" float_to_int_go <= 0;\n") output_file.write(" //stage 0 instruction fetch\n") output_file.write(" if (stage_0_enable) begin\n") output_file.write(" stage_1_enable <= 1;\n") output_file.write(" instruction_0 <= instructions[program_counter];\n") output_file.write(" opcode_0 = instruction_0[%s:%s];\n"%( register_bits * 2 + opcode_bits + 31, register_bits * 2 + 32)) output_file.write(" dest_0 = instruction_0[%s:%s];\n"%( register_bits * 2 + 31, register_bits + 32)) output_file.write(" src_0 = instruction_0[%s:32];\n"%( register_bits + 31)) output_file.write(" srcb_0 = instruction_0[%s:0];\n"%(register_bits-1)) output_file.write(" literal_0 = instruction_0[31:0];\n") output_file.write(" if(write_enable_2) begin\n") output_file.write(" registers[dest_2] <= result_2;\n") output_file.write(" end\n") output_file.write(" program_counter_0 <= program_counter;\n") output_file.write(" program_counter <= program_counter + 1;\n") output_file.write(" end\n\n") output_file.write(" //stage 1 opcode fetch\n") output_file.write(" if (stage_1_enable) begin\n") output_file.write(" stage_2_enable <= 1;\n") output_file.write(" register_1 <= registers[src_0];\n") output_file.write(" registerb_1 <= registers[srcb_0];\n") output_file.write(" dest_1 <= dest_0;\n") output_file.write(" literal_1 <= literal_0;\n") output_file.write(" opcode_1 <= opcode_0;\n") output_file.write(" program_counter_1 <= program_counter_0;\n") output_file.write(" end\n\n") output_file.write(" //stage 2 opcode fetch\n") output_file.write(" if (stage_2_enable) begin\n") output_file.write(" dest_2 <= dest_1;\n") output_file.write(" case(opcode_1)\n\n") #A frame is executed in each state for opcode, instruction in enumerate(instruction_set): if instruction["op"] == "literal": output_file.write(" 16'd%s:\n"%(opcode)) output_file.write(" begin\n") output_file.write(" result_2 <= literal_1;\n") output_file.write(" write_enable_2 <= 1;\n") output_file.write(" end\n\n") elif instruction["op"] == "move": output_file.write(" 16'd%s:\n"%(opcode)) output_file.write(" begin\n") output_file.write(" result_2 <= register_1;\n") output_file.write(" write_enable_2 <= 1;\n") output_file.write(" end\n\n") elif instruction["op"] == "~": output_file.write(" 16'd%s:\n"%(opcode)) output_file.write(" begin\n") output_file.write(" result_2 <= ~register_1;\n") output_file.write(" write_enable_2 <= 1;\n") output_file.write(" end\n\n") elif instruction["op"] == "int_to_float": output_file.write(" 16'd%s:\n"%(opcode)) output_file.write(" begin\n") output_file.write(" int_to <= register_1;\n") output_file.write(" int_to_float_go <= 1;\n") output_file.write(" stage_0_enable <= 0;\n") output_file.write(" stage_1_enable <= 0;\n") output_file.write(" stage_2_enable <= 0;\n") output_file.write(" end\n\n") elif instruction["op"] == "float_to_int": output_file.write(" 16'd%s:\n"%(opcode)) output_file.write(" begin\n") output_file.write(" float_to <= register_1;\n") output_file.write(" float_to_int_go <= 1;\n") output_file.write(" stage_0_enable <= 0;\n") output_file.write(" stage_1_enable <= 0;\n") output_file.write(" stage_2_enable <= 0;\n") output_file.write(" end\n\n") elif instruction["op"] in binary_operators: if instruction["literal"]: if instruction["float"]: output_file.write(" 16'd%s:\n"%(opcode)) output_file.write(" begin\n") if instruction["op"] == "/": if instruction["right"]: output_file.write(" divider_a <= register_1;\n") output_file.write(" divider_b <= literal_1;\n") else: output_file.write(" divider_a <= literal_1;\n") output_file.write(" divider_b <= register_1;\n") output_file.write(" divider_go <= 1;\n") elif instruction["op"] == "*": if instruction["right"]: output_file.write(" multiplier_a <= register_1;\n") output_file.write(" multiplier_b <= literal_1;\n") else: output_file.write(" multiplier_a <= literal_1;\n") output_file.write(" multiplier_b <= register_1;\n") output_file.write(" multiplier_go <= 1;\n") elif instruction["op"] == "+": if instruction["right"]: output_file.write(" adder_a <= register_1;\n") output_file.write(" adder_b <= literal_1;\n") else: output_file.write(" adder_a <= literal_1;\n") output_file.write(" adder_b <= register_1;\n") output_file.write(" adder_go <= 1;\n") elif instruction["op"] == "-": if instruction["right"]: output_file.write(" adder_a <= register_1;\n") output_file.write(" adder_b <= {~literal_1[31], literal_1[30:0]};\n") else: output_file.write(" adder_a <= literal_1;\n") output_file.write(" adder_b <= {~register_1[31], register_1[30:0]};\n") output_file.write(" adder_go <= 1;\n") output_file.write(" stage_0_enable <= 0;\n") output_file.write(" stage_1_enable <= 0;\n") output_file.write(" stage_2_enable <= 0;\n") output_file.write(" end\n\n") elif instruction["unsigned"]: output_file.write(" 16'd%s:\n"%(opcode)) output_file.write(" begin\n") if instruction["right"]: output_file.write(" result_2 <= $unsigned(register_1) %s $unsigned(literal_1);\n"%(instruction["op"])) else: output_file.write(" result_2 <= $unsigned(literal_1) %s $unsigned(register_1);\n"%(instruction["op"])) output_file.write(" write_enable_2 <= 1;\n") output_file.write(" end\n\n") else: if instruction["op"] == ">>": instruction["op"] = ">>>" output_file.write(" 16'd%s:\n"%(opcode)) output_file.write(" begin\n") if instruction["right"]: output_file.write(" result_2 <= $signed(register_1) %s $signed(literal_1);\n"%(instruction["op"])) else: output_file.write(" result_2 <= $signed(literal_1) %s $signed(register_1);\n"%(instruction["op"])) output_file.write(" write_enable_2 <= 1;\n") output_file.write(" end\n\n") else: if instruction["float"]: output_file.write(" 16'd%s:\n"%(opcode)) output_file.write(" begin\n") if instruction["op"] == "/": output_file.write(" divider_a <= register_1;\n") output_file.write(" divider_b <= registerb_1;\n") output_file.write(" divider_go <= 1;\n") elif instruction["op"] == "*": output_file.write(" multiplier_a <= register_1;\n") output_file.write(" multiplier_b <= registerb_1;\n") output_file.write(" multiplier_go <= 1;\n") elif instruction["op"] == "+": output_file.write(" adder_a <= register_1;\n") output_file.write(" adder_b <= registerb_1;\n") output_file.write(" adder_go <= 1;\n") elif instruction["op"] == "-": output_file.write(" adder_a <= register_1;\n") output_file.write(" adder_b <= {~registerb_1[31], registerb_1[30:0]};\n") output_file.write(" adder_go <= 1;\n") output_file.write(" stage_0_enable <= 0;\n") output_file.write(" stage_1_enable <= 0;\n") output_file.write(" stage_2_enable <= 0;\n") output_file.write(" end\n\n") elif instruction["unsigned"]: output_file.write(" 16'd%s:\n"%(opcode)) output_file.write(" begin\n") output_file.write(" result_2 <= $unsigned(register_1) %s $unsigned(registerb_1);\n"%(instruction["op"])) output_file.write(" write_enable_2 <= 1;\n") output_file.write(" end\n\n") else: if instruction["op"] == ">>": instruction["op"] = ">>>" output_file.write(" 16'd%s:\n"%(opcode)) output_file.write(" begin\n") output_file.write(" result_2 <= $signed(register_1) %s $signed(registerb_1);\n"%(instruction["op"])) output_file.write(" write_enable_2 <= 1;\n") output_file.write(" end\n\n") elif instruction["op"] == "jmp_if_false": output_file.write(" 16'd%s:\n"%(opcode)) output_file.write(" begin\n") output_file.write(" if (register_1 == 0) begin\n"); output_file.write(" program_counter <= literal_1;\n") output_file.write(" stage_0_enable <= 1;\n") output_file.write(" stage_1_enable <= 0;\n") output_file.write(" stage_2_enable <= 0;\n") output_file.write(" end\n") output_file.write(" end\n\n") elif instruction["op"] == "jmp_if_true": output_file.write(" 16'd%s:\n"%(opcode)) output_file.write(" begin\n") output_file.write(" if (register_1 != 0) begin\n"); output_file.write(" program_counter <= literal_1;\n") output_file.write(" stage_0_enable <= 1;\n") output_file.write(" stage_1_enable <= 0;\n") output_file.write(" stage_2_enable <= 0;\n") output_file.write(" end\n") output_file.write(" end\n\n") elif instruction["op"] == "jmp_and_link": output_file.write(" 16'd%s:\n"%(opcode)) output_file.write(" begin\n") output_file.write(" program_counter <= literal_1;\n") output_file.write(" result_2 <= program_counter_1 + 1;\n") output_file.write(" write_enable_2 <= 1;\n") output_file.write(" stage_0_enable <= 1;\n") output_file.write(" stage_1_enable <= 0;\n") output_file.write(" stage_2_enable <= 0;\n") output_file.write(" end\n\n") elif instruction["op"] == "jmp_to_reg": output_file.write(" 16'd%s:\n"%(opcode)) output_file.write(" begin\n") output_file.write(" program_counter <= register_1;\n") output_file.write(" stage_0_enable <= 1;\n") output_file.write(" stage_1_enable <= 0;\n") output_file.write(" stage_2_enable <= 0;\n") output_file.write(" end\n\n") elif instruction["op"] == "goto": output_file.write(" 16'd%s:\n"%(opcode)) output_file.write(" begin\n") output_file.write(" program_counter <= literal_1;\n") output_file.write(" stage_0_enable <= 1;\n") output_file.write(" stage_1_enable <= 0;\n") output_file.write(" stage_2_enable <= 0;\n") output_file.write(" end\n\n") elif instruction["op"] == "file_read": output_file.write(" 16'd%s:\n"%(opcode)) output_file.write(" begin\n") output_file.write(" file_count = $fscanf(%s, \"%%d\\n\", result_2);\n"%( input_files[instruction["file_name"]])) output_file.write(" write_enable_2 <= 1;\n") output_file.write(" end\n\n") elif instruction["op"] == "file_write": output_file.write(" 16'd%s:\n"%(opcode)) output_file.write(" begin\n") if instruction["float"]: output_file.write(' fp_value = (register_1[31]?-1.0:1.0) *\n') output_file.write(' (2.0 ** (register_1[30:23]-127.0)) *\n') output_file.write(' ({1\'d1, register_1[22:0]} / (2.0**23));\n') output_file.write(' $fdisplay (%s, "%%f", fp_value);\n'%( output_files[instruction["file_name"]])) else: output_file.write(" $fdisplay(%s, \"%%d\", register_1);\n"%( output_files[instruction["file_name"]])) output_file.write(" end\n\n") elif instruction["op"] == "read": output_file.write(" 16'd%s:\n"%(opcode)) output_file.write(" begin\n") output_file.write(" stage_0_enable <= 0;\n") output_file.write(" stage_1_enable <= 0;\n") output_file.write(" stage_2_enable <= 0;\n") output_file.write(" s_input_%s_ack <= 1'b1;\n"%instruction["input"]) output_file.write(" end\n\n") elif instruction["op"] == "ready": output_file.write(" 16'd%s:\n"%(opcode)) output_file.write(" begin\n") output_file.write(" result_2 <= 0;\n") output_file.write(" result_2[0] <= input_%s_stb;\n"%( instruction["input"])) output_file.write(" write_enable_2 <= 1;\n") output_file.write(" end\n\n") elif instruction["op"] == "write": output_file.write(" 16'd%s:\n"%(opcode)) output_file.write(" begin\n") output_file.write(" stage_0_enable <= 0;\n") output_file.write(" stage_1_enable <= 0;\n") output_file.write(" stage_2_enable <= 0;\n") output_file.write(" s_output_%s_stb <= 1'b1;\n"%instruction["output"]) output_file.write(" s_output_%s <= register_1;\n"%instruction["output"]) output_file.write(" end\n\n") elif instruction["op"] == "memory_read_request": output_file.write(" 16'd%s:\n"%(opcode)) output_file.write(" begin\n") output_file.write(" address_%s <= register_1;\n"%( instruction["element_size"])) output_file.write(" end\n\n") elif instruction["op"] == "memory_read_wait": pass elif instruction["op"] == "memory_read": output_file.write(" 16'd%s:\n"%(opcode)) output_file.write(" begin\n") output_file.write(" result_2 <= data_out_%s;\n"%( instruction["element_size"])) output_file.write(" write_enable_2 <= 1;\n") output_file.write(" end\n\n") elif instruction["op"] == "memory_write": output_file.write(" 16'd%s:\n"%(opcode)) output_file.write(" begin\n") output_file.write(" address_%s <= register_1;\n"%( instruction["element_size"])) output_file.write(" data_in_%s <= registerb_1;\n"%( instruction["element_size"])) output_file.write(" memory_enable_%s <= 1'b1;\n"%( instruction["element_size"])) output_file.write(" end\n\n") elif instruction["op"] == "assert": output_file.write(" 16'd%s:\n"%(opcode)) output_file.write(" begin\n") output_file.write(" if (register_1 == 0) begin\n") output_file.write(" $display(\"Assertion failed at line: %s in file: %s\");\n"%( instruction["line"], instruction["file"])) output_file.write(" $finish_and_return(1);\n") output_file.write(" end\n") output_file.write(" end\n\n") elif instruction["op"] == "wait_clocks": output_file.write(" 16'd%s:\n"%(opcode)) output_file.write(" begin\n") output_file.write(" timer <= register_1;\n") output_file.write(" timer_enable <= 1;\n") output_file.write(" stage_0_enable <= 0;\n") output_file.write(" stage_1_enable <= 0;\n") output_file.write(" stage_2_enable <= 0;\n") output_file.write(" end\n\n") elif instruction["op"] == "report": output_file.write(" 16'd%s:\n"%(opcode)) output_file.write(" begin\n") if instruction["float"]: output_file.write(' fp_value = (register_1[31]?-1.0:1.0) *\n') output_file.write(' (2.0 ** (register_1[30:23]-127.0)) *\n') output_file.write(' ({1\'d1, register_1[22:0]} / (2.0**23));\n') output_file.write(' $display ("%%f (report at line: %s in file: %s)", fp_value);\n'%( instruction["line"], instruction["file"])) elif instruction["unsigned"]: output_file.write(' $display ("%%d (report at line: %s in file: %s)", $unsigned(register_1));\n'%( instruction["line"], instruction["file"])) else: output_file.write(' $display ("%%d (report at line: %s in file: %s)", $signed(register_1));\n'%( instruction["line"], instruction["file"],)) output_file.write(" end\n\n") elif instruction["op"] == "stop": #If we are in testbench mode stop the simulation #If we are part of a larger design, other C programs may still be running output_file.write(" 16'd%s:\n"%(opcode)) output_file.write(" begin\n") for file_ in input_files.values(): output_file.write(" $fclose(%s);\n"%file_) for file_ in output_files.values(): output_file.write(" $fclose(%s);\n"%file_) if testbench: output_file.write(' $finish;\n') output_file.write(" stage_0_enable <= 0;\n") output_file.write(" stage_1_enable <= 0;\n") output_file.write(" stage_2_enable <= 0;\n") output_file.write(" end\n\n") output_file.write(" endcase\n") output_file.write(" end\n") for instruction in instruction_set: if instruction["op"] == "read": output_file.write(" if (s_input_%s_ack == 1'b1 && input_%s_stb == 1'b1) begin\n"%( instruction["input"], instruction["input"])) output_file.write(" result_2 <= input_%s;\n"%(instruction["input"])) output_file.write(" write_enable_2 <= 1;\n") output_file.write(" s_input_%s_ack <= 1'b0;\n"%instruction["input"]) output_file.write(" stage_0_enable <= 1;\n") output_file.write(" stage_1_enable <= 1;\n") output_file.write(" stage_2_enable <= 1;\n") output_file.write(" end\n\n") elif instruction["op"] == "write": output_file.write(" if (s_output_%s_stb == 1'b1 && output_%s_ack == 1'b1) begin\n"%( instruction["output"], instruction["output"])) output_file.write(" s_output_%s_stb <= 1'b0;\n"%instruction["output"]) output_file.write(" stage_0_enable <= 1;\n") output_file.write(" stage_1_enable <= 1;\n") output_file.write(" stage_2_enable <= 1;\n") output_file.write(" end\n\n") output_file.write(" if (timer == 0) begin\n") output_file.write(" if (timer_enable) begin\n") output_file.write(" stage_0_enable <= 1;\n") output_file.write(" stage_1_enable <= 1;\n") output_file.write(" stage_2_enable <= 1;\n") output_file.write(" timer_enable <= 0;\n") output_file.write(" end\n") output_file.write(" end else begin\n") output_file.write(" timer <= timer - 1;\n") output_file.write(" end\n\n") if enable_adder: output_file.write(" if (adder_done) begin\n") output_file.write(" write_enable_2 <= 1;\n") output_file.write(" stage_0_enable <= 1;\n") output_file.write(" stage_1_enable <= 1;\n") output_file.write(" stage_2_enable <= 1;\n") output_file.write(" end\n\n") if enable_multiplier: output_file.write(" if (multiplier_done) begin\n") output_file.write(" write_enable_2 <= 1;\n") output_file.write(" stage_0_enable <= 1;\n") output_file.write(" stage_1_enable <= 1;\n") output_file.write(" stage_2_enable <= 1;\n") output_file.write(" end\n\n") if enable_divider: output_file.write(" if (divider_done) begin\n") output_file.write(" write_enable_2 <= 1;\n") output_file.write(" stage_0_enable <= 1;\n") output_file.write(" stage_1_enable <= 1;\n") output_file.write(" stage_2_enable <= 1;\n") output_file.write(" end\n\n") if enable_int_to_float: output_file.write(" if (int_to_float_done) begin\n") output_file.write(" write_enable_2 <= 1;\n") output_file.write(" stage_0_enable <= 1;\n") output_file.write(" stage_1_enable <= 1;\n") output_file.write(" stage_2_enable <= 1;\n") output_file.write(" end\n\n") if enable_float_to_int: output_file.write(" if (float_to_int_done) begin\n") output_file.write(" write_enable_2 <= 1;\n") output_file.write(" stage_0_enable <= 1;\n") output_file.write(" stage_1_enable <= 1;\n") output_file.write(" stage_2_enable <= 1;\n") output_file.write(" end\n\n") #Reset program counter and control signals output_file.write(" if (rst == 1'b1) begin\n") output_file.write(" stage_0_enable <= 1;\n") output_file.write(" stage_1_enable <= 0;\n") output_file.write(" stage_2_enable <= 0;\n") output_file.write(" timer <= 0;\n") output_file.write(" timer_enable <= 0;\n") output_file.write(" program_counter <= 0;\n") for i in inputs: output_file.write(" s_input_%s_ack <= 0;\n"%(i)) for i in outputs: output_file.write(" s_output_%s_stb <= 0;\n"%(i)) output_file.write(" end\n") output_file.write(" end\n") for i in inputs: output_file.write(" assign input_%s_ack = s_input_%s_ack;\n"%(i, i)) for i in outputs: output_file.write(" assign output_%s_stb = s_output_%s_stb;\n"%(i, i)) output_file.write(" assign output_%s = s_output_%s;\n"%(i, i)) output_file.write("\nendmodule\n") return inputs, outputs def connect_float_to_int(output_file): output_file.write(" \n float_to_int float_to_int_1(\n") output_file.write(" .clk(clk),\n") output_file.write(" .rst(rst),\n") output_file.write(" .input_a(float_to),\n") output_file.write(" .input_a_stb(float_to_stb),\n") output_file.write(" .input_a_ack(float_to_ack),\n") output_file.write(" .output_z(to_int),\n") output_file.write(" .output_z_stb(to_int_stb),\n") output_file.write(" .output_z_ack(to_int_ack)\n") output_file.write(" );\n\n") output_file.write(" \n always @(posedge clk)\n") output_file.write(" begin\n\n") output_file.write(" float_to_int_done <= 0;\n") output_file.write(" case(float_to_int_state)\n\n") output_file.write(" wait_go:\n") output_file.write(" begin\n") output_file.write(" if (float_to_int_go) begin\n") output_file.write(" float_to_int_state <= write_a;\n") output_file.write(" end\n") output_file.write(" end\n\n") output_file.write(" write_a:\n") output_file.write(" begin\n") output_file.write(" float_to_stb <= 1;\n") output_file.write(" if (float_to_stb && float_to_ack) begin\n") output_file.write(" float_to_stb <= 0;\n") output_file.write(" float_to_int_state <= read_z;\n") output_file.write(" end\n") output_file.write(" end\n\n") output_file.write(" read_z:\n") output_file.write(" begin\n") output_file.write(" to_int_ack <= 1;\n") output_file.write(" if (to_int_stb && to_int_ack) begin\n") output_file.write(" to_int_ack <= 0;\n") output_file.write(" result_2 <= to_int;\n") output_file.write(" float_to_int_state <= wait_go;\n") output_file.write(" float_to_int_done <= 1;\n") output_file.write(" end\n") output_file.write(" end\n") output_file.write(" endcase\n") output_file.write(" if (rst) begin\n") output_file.write(" float_to_int_state <= wait_go;\n") output_file.write(" float_to_stb <= 0;\n") output_file.write(" to_int_ack <= 0;\n") output_file.write(" end\n") output_file.write(" end\n\n") def connect_int_to_float(output_file): output_file.write(" \n int_to_float int_to_float_1(\n") output_file.write(" .clk(clk),\n") output_file.write(" .rst(rst),\n") output_file.write(" .input_a(int_to),\n") output_file.write(" .input_a_stb(int_to_stb),\n") output_file.write(" .input_a_ack(int_to_ack),\n") output_file.write(" .output_z(to_float),\n") output_file.write(" .output_z_stb(to_float_stb),\n") output_file.write(" .output_z_ack(to_float_ack)\n") output_file.write(" );\n\n") output_file.write(" \n always @(posedge clk)\n") output_file.write(" begin\n\n") output_file.write(" int_to_float_done <= 0;\n") output_file.write(" case(int_to_float_state)\n\n") output_file.write(" wait_go:\n") output_file.write(" begin\n") output_file.write(" if (int_to_float_go) begin\n") output_file.write(" int_to_float_state <= write_a;\n") output_file.write(" end\n") output_file.write(" end\n\n") output_file.write(" write_a:\n") output_file.write(" begin\n") output_file.write(" int_to_stb <= 1;\n") output_file.write(" if (int_to_stb && int_to_ack) begin\n") output_file.write(" int_to_stb <= 0;\n") output_file.write(" int_to_float_state <= read_z;\n") output_file.write(" end\n") output_file.write(" end\n\n") output_file.write(" read_z:\n") output_file.write(" begin\n") output_file.write(" to_float_ack <= 1;\n") output_file.write(" if (to_float_stb && to_float_ack) begin\n") output_file.write(" to_float_ack <= 0;\n") output_file.write(" result_2 <= to_float;\n") output_file.write(" int_to_float_state <= wait_go;\n") output_file.write(" int_to_float_done <= 1;\n") output_file.write(" end\n") output_file.write(" end\n") output_file.write(" endcase\n") output_file.write(" if (rst) begin\n") output_file.write(" int_to_float_state <= wait_go;\n") output_file.write(" int_to_stb <= 0;\n") output_file.write(" to_float_ack <= 0;\n") output_file.write(" end\n") output_file.write(" end\n\n") def connect_divider(output_file): output_file.write(" \n divider divider_1(\n") output_file.write(" .clk(clk),\n") output_file.write(" .rst(rst),\n") output_file.write(" .input_a(divider_a),\n") output_file.write(" .input_a_stb(divider_a_stb),\n") output_file.write(" .input_a_ack(divider_a_ack),\n") output_file.write(" .input_b(divider_b),\n") output_file.write(" .input_b_stb(divider_b_stb),\n") output_file.write(" .input_b_ack(divider_b_ack),\n") output_file.write(" .output_z(divider_z),\n") output_file.write(" .output_z_stb(divider_z_stb),\n") output_file.write(" .output_z_ack(divider_z_ack)\n") output_file.write(" );\n\n") output_file.write(" \n always @(posedge clk)\n") output_file.write(" begin\n\n") output_file.write(" divider_done <= 0;\n") output_file.write(" case(div_state)\n\n") output_file.write(" wait_go:\n") output_file.write(" begin\n") output_file.write(" if (divider_go) begin\n") output_file.write(" div_state <= write_a;\n") output_file.write(" end\n") output_file.write(" end\n\n") output_file.write(" write_a:\n") output_file.write(" begin\n") output_file.write(" divider_a_stb <= 1;\n") output_file.write(" if (divider_a_stb && divider_a_ack) begin\n") output_file.write(" divider_a_stb <= 0;\n") output_file.write(" div_state <= write_b;\n") output_file.write(" end\n") output_file.write(" end\n\n") output_file.write(" write_b:\n") output_file.write(" begin\n") output_file.write(" divider_b_stb <= 1;\n") output_file.write(" if (divider_b_stb && divider_b_ack) begin\n") output_file.write(" divider_b_stb <= 0;\n") output_file.write(" div_state <= read_z;\n") output_file.write(" end\n") output_file.write(" end\n\n") output_file.write(" read_z:\n") output_file.write(" begin\n") output_file.write(" divider_z_ack <= 1;\n") output_file.write(" if (divider_z_stb && divider_z_ack) begin\n") output_file.write(" divider_z_ack <= 0;\n") output_file.write(" result_2 <= divider_z;\n") output_file.write(" div_state <= wait_go;\n") output_file.write(" divider_done <= 1;\n") output_file.write(" end\n") output_file.write(" end\n") output_file.write(" endcase\n") output_file.write(" if (rst) begin\n") output_file.write(" div_state <= wait_go;\n") output_file.write(" divider_a_stb <= 0;\n") output_file.write(" divider_b_stb <= 0;\n") output_file.write(" divider_z_ack <= 0;\n") output_file.write(" end\n") output_file.write(" end\n\n") def connect_multiplier(output_file): output_file.write(" \n multiplier multiplier_1(\n") output_file.write(" .clk(clk),\n") output_file.write(" .rst(rst),\n") output_file.write(" .input_a(multiplier_a),\n") output_file.write(" .input_a_stb(multiplier_a_stb),\n") output_file.write(" .input_a_ack(multiplier_a_ack),\n") output_file.write(" .input_b(multiplier_b),\n") output_file.write(" .input_b_stb(multiplier_b_stb),\n") output_file.write(" .input_b_ack(multiplier_b_ack),\n") output_file.write(" .output_z(multiplier_z),\n") output_file.write(" .output_z_stb(multiplier_z_stb),\n") output_file.write(" .output_z_ack(multiplier_z_ack)\n") output_file.write(" );\n\n") output_file.write(" \n always @(posedge clk)\n") output_file.write(" begin\n\n") output_file.write(" multiplier_done <= 0;\n") output_file.write(" case(mul_state)\n\n") output_file.write(" wait_go:\n") output_file.write(" begin\n") output_file.write(" if (multiplier_go) begin\n") output_file.write(" mul_state <= write_a;\n") output_file.write(" end\n") output_file.write(" end\n\n") output_file.write(" write_a:\n") output_file.write(" begin\n") output_file.write(" multiplier_a_stb <= 1;\n") output_file.write(" if (multiplier_a_stb && multiplier_a_ack) begin\n") output_file.write(" multiplier_a_stb <= 0;\n") output_file.write(" mul_state <= write_b;\n") output_file.write(" end\n") output_file.write(" end\n\n") output_file.write(" write_b:\n") output_file.write(" begin\n") output_file.write(" multiplier_b_stb <= 1;\n") output_file.write(" if (multiplier_b_stb && multiplier_b_ack) begin\n") output_file.write(" multiplier_b_stb <= 0;\n") output_file.write(" mul_state <= read_z;\n") output_file.write(" end\n") output_file.write(" end\n\n") output_file.write(" read_z:\n") output_file.write(" begin\n") output_file.write(" multiplier_z_ack <= 1;\n") output_file.write(" if (multiplier_z_stb && multiplier_z_ack) begin\n") output_file.write(" multiplier_z_ack <= 0;\n") output_file.write(" result_2 <= multiplier_z;\n") output_file.write(" mul_state <= wait_go;\n") output_file.write(" multiplier_done <= 1;\n") output_file.write(" end\n") output_file.write(" end\n\n") output_file.write(" endcase\n\n") output_file.write(" if (rst) begin\n") output_file.write(" mul_state <= wait_go;\n") output_file.write(" multiplier_a_stb <= 0;\n") output_file.write(" multiplier_b_stb <= 0;\n") output_file.write(" multiplier_z_ack <= 0;\n") output_file.write(" end\n") output_file.write(" end\n\n") def connect_adder(output_file): output_file.write(" \n adder adder_1(\n") output_file.write(" .clk(clk),\n") output_file.write(" .rst(rst),\n") output_file.write(" .input_a(adder_a),\n") output_file.write(" .input_a_stb(adder_a_stb),\n") output_file.write(" .input_a_ack(adder_a_ack),\n") output_file.write(" .input_b(adder_b),\n") output_file.write(" .input_b_stb(adder_b_stb),\n") output_file.write(" .input_b_ack(adder_b_ack),\n") output_file.write(" .output_z(adder_z),\n") output_file.write(" .output_z_stb(adder_z_stb),\n") output_file.write(" .output_z_ack(adder_z_ack)\n") output_file.write(" );\n\n") output_file.write(" \n always @(posedge clk)\n") output_file.write(" begin\n\n") output_file.write(" adder_done <= 0;\n") output_file.write(" case(add_state)\n\n") output_file.write(" wait_go:\n") output_file.write(" begin\n") output_file.write(" if (adder_go) begin\n") output_file.write(" add_state <= write_a;\n") output_file.write(" end\n") output_file.write(" end\n\n") output_file.write(" write_a:\n") output_file.write(" begin\n") output_file.write(" adder_a_stb <= 1;\n") output_file.write(" if (adder_a_stb && adder_a_ack) begin\n") output_file.write(" adder_a_stb <= 0;\n") output_file.write(" add_state <= write_b;\n") output_file.write(" end\n") output_file.write(" end\n\n") output_file.write(" write_b:\n") output_file.write(" begin\n") output_file.write(" adder_b_stb <= 1;\n") output_file.write(" if (adder_b_stb && adder_b_ack) begin\n") output_file.write(" adder_b_stb <= 0;\n") output_file.write(" add_state <= read_z;\n") output_file.write(" end\n") output_file.write(" end\n\n") output_file.write(" read_z:\n") output_file.write(" begin\n") output_file.write(" adder_z_ack <= 1;\n") output_file.write(" if (adder_z_stb && adder_z_ack) begin\n") output_file.write(" adder_z_ack <= 0;\n") output_file.write(" result_2 <= adder_z;\n") output_file.write(" add_state <= wait_go;\n") output_file.write(" adder_done <= 1;\n") output_file.write(" end\n") output_file.write(" end\n") output_file.write(" endcase\n") output_file.write(" if (rst) begin\n") output_file.write(" add_state <= wait_go;\n") output_file.write(" adder_a_stb <= 0;\n") output_file.write(" adder_b_stb <= 0;\n") output_file.write(" adder_z_ack <= 0;\n") output_file.write(" end\n") output_file.write(" end\n\n") def generate_float_to_int_signals(output_file): output_file.write(" reg [31:0] float_to;\n") output_file.write(" reg float_to_stb;\n") output_file.write(" wire float_to_ack;\n") output_file.write(" wire [31:0] to_int;\n") output_file.write(" wire to_int_stb;\n") output_file.write(" reg to_int_ack;\n") output_file.write(" reg [1:0] float_to_int_state;\n") output_file.write(" reg float_to_int_go;\n") output_file.write(" reg float_to_int_done;\n") def generate_int_to_float_signals(output_file): output_file.write(" reg [31:0] int_to;\n") output_file.write(" reg int_to_stb;\n") output_file.write(" wire int_to_ack;\n") output_file.write(" wire [31:0] to_float;\n") output_file.write(" wire to_float_stb;\n") output_file.write(" reg to_float_ack;\n") output_file.write(" reg [1:0] int_to_float_state;\n") output_file.write(" reg int_to_float_go;\n") output_file.write(" reg int_to_float_done;\n") def generate_divider_signals(output_file): output_file.write(" reg [31:0] divider_a;\n") output_file.write(" reg divider_a_stb;\n") output_file.write(" wire divider_a_ack;\n") output_file.write(" reg [31:0] divider_b;\n") output_file.write(" reg divider_b_stb;\n") output_file.write(" wire divider_b_ack;\n") output_file.write(" wire [31:0] divider_z;\n") output_file.write(" wire divider_z_stb;\n") output_file.write(" reg divider_z_ack;\n") output_file.write(" reg [1:0] div_state;\n") output_file.write(" reg divider_go;\n") output_file.write(" reg divider_done;\n") def generate_multiplier_signals(output_file): output_file.write(" reg [31:0] multiplier_a;\n") output_file.write(" reg multiplier_a_stb;\n") output_file.write(" wire multiplier_a_ack;\n") output_file.write(" reg [31:0] multiplier_b;\n") output_file.write(" reg multiplier_b_stb;\n") output_file.write(" wire multiplier_b_ack;\n") output_file.write(" wire [31:0] multiplier_z;\n") output_file.write(" wire multiplier_z_stb;\n") output_file.write(" reg multiplier_z_ack;\n") output_file.write(" reg [1:0] mul_state;\n") output_file.write(" reg multiplier_go;\n") output_file.write(" reg multiplier_done;\n") def generate_adder_signals(output_file): output_file.write(" reg [31:0] adder_a;\n") output_file.write(" reg adder_a_stb;\n") output_file.write(" wire adder_a_ack;\n") output_file.write(" reg [31:0] adder_b;\n") output_file.write(" reg adder_b_stb;\n") output_file.write(" wire adder_b_ack;\n") output_file.write(" wire [31:0] adder_z;\n") output_file.write(" wire adder_z_stb;\n") output_file.write(" reg adder_z_ack;\n") output_file.write(" reg [1:0] add_state;\n") output_file.write(" reg adder_go;\n") output_file.write(" reg adder_done;\n")
37969a112cf14a667e6f7af94363f6fc041942e5
hyang012/leetcode-algorithms-questions
/059. Spiral Matrix II/Spiral_Matrix_II.py
560
4
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Leetcode 59. Spiral Matrix II Given a positive integer n, generate a square matrix filled with elements from 1 to n^2 in spiral order """ def generateMatrix(n): """ :type n: int :rtype: List[List[int]] """ res = [[0] * n for _ in range(n)] i, j, di, dj = 0, 0, 0, 1 for k in range(n**2): res[i][j] = k + 1 if res[(i+di)%n][(j+dj)%n] != 0: di, dj = dj, -di i += di j += dj return res print(generateMatrix(3))
233cf457bae17e581e6bf7e1ea2e6d06e9b0e828
Vish9454/nptel
/nptel_py/creating_list.py
468
3.8125
4
class Node: def __init__(self,initval=None): self.value=initval self.next=None def isempty(self): return self.value==None def append_i(self,v): if self.isempty(): self.value=v elif self.next==None: newnode=Node(v) self.next=newnode else: self.next.append_i(v) return () l1=Node(5);print(l1.isempty()) print(l1.append_i(3)) l1.append_i(4) l1.append_i(5)
a515e08de1f7846adf0c37116ba315234ed93b61
ibeketov/EnterpriseDataScientist
/support.py
3,807
3.671875
4
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from sklearn.linear_model import LinearRegression from sklearn.model_selection import train_test_split from sklearn.metrics import r2_score, mean_squared_error def col_check(df): """ Prints short info about columns :param df: takes into a dataframe """ columns = df.columns.tolist() for col in columns: print(df[col].head()) print('Missing (%):', df[col].isnull().mean()) print(10*'-') def show_missing(df, lower_thresh=0.0): """ Shows a barplot of the missing values of all columns. :param df: takes into a pandas dataframe. :param lower_thresh: Allows to threshold the count of missing columns to gain greater insight :return: """ plt.figure(figsize=(16,10)) na_count = df.isna().sum()/df.shape[0] na_count = na_count[na_count >= lower_thresh] plot = sns.barplot(na_count.index.values, na_count) plot.set_xticklabels(plot.get_xticklabels(), rotation=90) # a function from the file AllTogether.py from the Lesson 1 materials is applied to create subsets with different number of features to create a similar plot as in "Lesson 1 - Notebook + Quiz: Putting It All Together" def find_optimal_lm_mod(X, y, cutoffs, test_size = .30, random_state=42, plot=True): ''' INPUT X - pandas dataframe, X matrix y - pandas dataframe, response variable cutoffs - list of ints, cutoff for number of non-zero values in dummy categorical vars test_size - float between 0 and 1, default 0.3, determines the proportion of data as test data random_state - int, default 42, controls random state for train_test_split plot - boolean, default 0.3, True to plot result OUTPUT r2_scores_test - list of floats of r2 scores on the test data r2_scores_train - list of floats of r2 scores on the train data lm_model - model object from sklearn X_train, X_test, y_train, y_test - output from sklearn train test split used for optimal model ''' r2_scores_test, r2_scores_train, num_feats, results = [], [], [], dict() for cutoff in cutoffs: #reduce X matrix reduce_X = X.iloc[:, np.where((X.sum() > cutoff) == True)[0]] num_feats.append(reduce_X.shape[1]) #split the data into train and test X_train, X_test, y_train, y_test = train_test_split(reduce_X, y, test_size = test_size, random_state=random_state) #fit the model and obtain pred response lm_model = LinearRegression(normalize=True) lm_model.fit(X_train, y_train) y_test_preds = lm_model.predict(X_test) y_train_preds = lm_model.predict(X_train) #append the r2 value from the test set r2_scores_test.append(r2_score(y_test, y_test_preds)) r2_scores_train.append(r2_score(y_train, y_train_preds)) results[str(cutoff)] = r2_score(y_test, y_test_preds) if plot: plt.plot(num_feats, r2_scores_test, label="Test", alpha=.5) plt.plot(num_feats, r2_scores_train, label="Train", alpha=.5) plt.xlabel('Number of Features') plt.ylabel('Rsquared') plt.title('Rsquared by Number of Features') plt.legend(loc=1) plt.show() best_cutoff = max(results, key=results.get) #reduce X matrix reduce_X = X.iloc[:, np.where((X.sum() > int(best_cutoff)) == True)[0]] num_feats.append(reduce_X.shape[1]) #split the data into train and test X_train, X_test, y_train, y_test = train_test_split(reduce_X, y, test_size = test_size, random_state=random_state) #fit the model lm_model = LinearRegression(normalize=True) lm_model.fit(X_train, y_train) return r2_scores_test, r2_scores_train, lm_model, X_train, X_test, y_train, y_test
24ee196e3a2ab42bcfc717d293a56735baf2146f
almamuncsit/LeetCode
/random/Tree/404. Sum of Left Leaves.py
654
3.78125
4
# Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def __init__(self): self.total = 0 def sumation(self, node): if node.left: if not node.left.left and not node.left.right: self.total += node.left.val self.sumation(node.left) if node.right: self.sumation(node.right) def sumOfLeftLeaves(self, root: TreeNode) -> int: if not root: return 0 self.sumation(root) return self.total
75b67db327e63ad18c9c7a4cbecdd69df6b975ae
anderson-br-ti/python
/Projetos/mdc.py
365
3.828125
4
#mdc segundo o algoritmo de Euclides # a b a%b # 21 15 6 (15 % 21 = 15) # 15 6 3 menor maior resto # 6 3 0 #a lógica a, b = b, a%b #repito até que a%b seja 0 #quando a%b for zero mdc é o b a = int(input('a: ')) b = int(input('b: ')) while a%b != 0: a, b = b, a%b print (b)
33a5c8ae06443f19bd69fb824919b8056118aaba
vikash-india/DeveloperNotes2Myself
/languages/python/src/concepts/P018_Functions_DefaultArguments.py
1,447
4.25
4
# Description: Functions With Default Argument Values def functionWithDefaultArguments(number_1, string_1, number_2=3, string_2='Yes', list=[]): # Do something with the arguments! print(number_1, string_1, number_2, string_2, list) # Calling the function with default values functionWithDefaultArguments(1, "Test") functionWithDefaultArguments(1, "Test", 5) functionWithDefaultArguments(1, "Test", 5, "No") functionWithDefaultArguments(1, "Test", 5, "No", [1, 2, 3, 4]) # IMPORTANT # The default values are evaluated at the point of function definition in the defining scope. Hence arg will have value # 5 and not 6 i = 5 def functionArgumentEvaluation(arg=i): # i will have 5 and not 6 print(arg) i = 6 functionArgumentEvaluation() # IMPORTANT # The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, # dictionary, or instances of most classes. For example, the following function accumulates the arguments passed to it # on subsequent calls. def functionAccumulatesValues(a, L=[]): L.append(a) return L print(functionAccumulatesValues(1)) print(functionAccumulatesValues(2)) print(functionAccumulatesValues(3)) # IMPORTANT # If you don't want the default to be shared between subsequent calls, you can write the function like this instead. def functionWithoutAccumulatingValues(a, L=None): if L is None: L = [] L.append(a) return L
e8af6e101207a5e62f4b34fca74b221ca8dc1d9f
ShreyasAmbre/python_practice
/PythonPracticeQustions1.0/Patterns.py
407
3.890625
4
print("Patterns") # Patter 1 for a in range(4): print("*", end="") for b in range(3): print("*", end="") print() # pattern 2 i = 3 for a in range(4): print("a", end="") for b in range(i): print("b", end="") i = i - 1 print() # Patter 3 i = 0 for a in range(4): print("a", end="") for b in range(i): print("b", end="") i = i + 1 print()
dc5950857559d17ab2c9504a1ef1629a96113f69
BerkeleyPlatte/python_practice
/functions_practice.py
2,133
3.8125
4
running_kids = ["Pam", "Sam", "Andrea", "Will"] swinging_kids = ["Marybeth", "Jenna", "Kevin", "Courtney"] sliding_kids = ["Mike", "Jack", "Jennifer", "Earl"] hiding_kids = ["Henry", "Heather", "Hayley", "Hugh"] def run(names): for each in names: print(f"{each} ran") def swing(names): for each in names: print(f"{each} swung") def slide(names): for each in names: print(f"{each} slid") def hide_and_seek(names): for each in names: print(f"{each} hid") # run(running_kids) # swing(swinging_kids) # slide(sliding_kids) # hide_and_seek(hiding_kids) def chicken_monkey(): for num in range(1, 101): if num % 5 == 0 and num % 7 == 0: print("ChickenMonkey") elif num % 5 == 0: print("Chicken") elif num % 7 == 0: print("Monkey") else: print(num) # chicken_monkey() def calc_dollars(): piggyBank = { "pennies": 1, "nickels": 1, "dimes": 1, "quarters": 4 } for key, value in piggyBank.items(): if key == "pennies": pennies = value elif key == "nickels": nickels = value * 5 elif key == "dimes": dimes = value * 10 else: quarters = value * 25 dollarAmount = (pennies + nickels + dimes + quarters) / 100 print(f'${dollarAmount}') # calc_dollars() def calc_bank(amount): num = amount * 100 not_q = num % 25 quarters = round((num - not_q) / 25) not_q_or_d = not_q % 10 dimes = round((not_q - not_q_or_d) / 10) not_q_d_or_n = not_q_or_d % 5 nickels = round((not_q_or_d - not_q_d_or_n) / 5) pennies = round(num - ((quarters * 25) + (dimes * 10) + (nickels * 5))) piggy_bank = { "quarters": quarters, "dimes": dimes, "nickels": nickels, "pennies": pennies } print(piggy_bank) # calc_bank(5.78) nums = ["one", "two", "three", "four", "five"] def lightning_func(li, string="I can count to"): for each in li: print(string + " " + each) # lightning_func(nums, "I like")
e395683560e3de2781ac06b6ae719d9c84ef4211
AndrewMiranda/holbertonschool-machine_learning-1
/supervised_learning/0x05-regularization/1-l2_reg_gradient_descent.py
1,657
3.859375
4
#!/usr/bin/env python3 """File That contains the function l2_reg_gradient_descent""" import numpy as np def l2_reg_gradient_descent(Y, weights, cache, alpha, lambtha, L): """ Function that calculates updates the weights and biases of a neural network using gradient descent with L2 regularization: Args: Y is a one-hot numpy.ndarray of shape (classes, m) that contains the correct labels for the data classes is the number of classes m is the number of data points weights is a dictionary of the weights and biases of the neural network cache is a dictionary of the outputs of each layer of the neural network alpha is the learning rate lambtha is the L2 regularization parameter L is the number of layers of the network """ m = Y.shape[1] W_copy = weights.copy() Layers = range(L + 1)[1:L + 1] for i in reversed(Layers): A = cache["A" + str(i)] if i == L: dZ = cache["A" + str(i)] - Y dW = (np.matmul(cache["A" + str(i - 1)], dZ.T) / m).T dW_L2 = dW + (lambtha / m) * W_copy["W" + str(i)] db = np.sum(dZ, axis=1, keepdims=True) / m else: dW2 = np.matmul(W_copy["W" + str(i + 1)].T, dZ2) tanh = 1 - (A * A) dZ = dW2 * tanh dW = np.matmul(dZ, cache["A" + str(i - 1)].T) / m dW_L2 = dW + (lambtha / m) * W_copy["W" + str(i)] db = np.sum(dZ, axis=1, keepdims=True) / m weights["W" + str(i)] = (W_copy["W" + str(i)] - (alpha * dW_L2)) weights["b" + str(i)] = W_copy["b" + str(i)] - (alpha * db) dZ2 = dZ
ee7506f9767de3b04ffa3710ba15ea91d4d5645c
kanm4s/CP3-Kantapon-Thitinart
/Exercise5_1_Kantapon_T.py
276
3.953125
4
firstNo = int(input("First number: ")) secondNo = int(input("Second number: ")) print(firstNo,"+",secondNo,"=",firstNo+secondNo) print(firstNo,"-",secondNo,"=",firstNo-secondNo) print(firstNo,"*",secondNo,"=",firstNo*secondNo) print(firstNo,"/",secondNo,"=",firstNo/secondNo)
7f1f06800e1f72b5170a35f1df61dfee1c28d418
NicolaiRee/CP2K_Editor
/scr/Analyse_CDFT.py
2,191
3.59375
4
#Made by Andreas Vishart import sys #Python 3 if str(sys.version)[0]=="3": import tkinter as tk #Python 2 elif str(sys.version)[0]=="2": import Tkinter as tk #Function for extracting details from CDFT calculation def CDFT_details(filename): #Load the out file with open(filename) as thefile: content=thefile.readlines() #Parameters rotation=["-"];lowdin=["-"];target1=["-"];target2=["-"] #Get the elctronic couplings and target values for line in content: if "Diabatic electronic coupling (rotation, mHartree):" in line: con=list(filter(None,line.split(" ")))[5] rotation.append(str(con)) if "Diabatic electronic coupling (Lowdin, mHartree):" in line: con=list(filter(None,line.split(" ")))[5] lowdin.append(str(con)) if "Final value of constraint I:" in line: con=list(filter(None,line.split(" ")))[5] target1.append(str(con)) if "Final value of constraint J:" in line: con=list(filter(None,line.split(" ")))[5] target2.append(str(con)) return rotation[-1].replace("\n",""),lowdin[-1].replace("\n",""),target1[-1].replace("\n",""),target2[-1].replace("\n","") #CDFT popup window (Results) def CDFT_popup(cdft_file): rotation,lowdin,target1,target2=CDFT_details(cdft_file) popup_cdft=tk.Tk() popup_cdft.title("CDFT") tk.Label(popup_cdft, text="Rotation diabatic electronic coupling / [mHartree]:").grid(row=1,column=0,sticky=tk.W) tk.Label(popup_cdft, text=str(rotation)).grid(row=1,column=2) tk.Label(popup_cdft, text="Lowdin diabatic electronic coupling / [mHartree]:").grid(row=2,column=0,sticky=tk.W) tk.Label(popup_cdft, text=str(lowdin)).grid(row=2,column=2) tk.Label(popup_cdft, text="Final value of constraint 1:").grid(row=3,column=0,sticky=tk.W) tk.Label(popup_cdft, text=str(target1)).grid(row=3,column=2) tk.Label(popup_cdft, text="Final value of constraint 2:").grid(row=4,column=0,sticky=tk.W) tk.Label(popup_cdft, text=str(target2)).grid(row=4,column=2) tk.Button(popup_cdft, text="Close", command = popup_cdft.destroy).grid(row=5,column=1) return popup_cdft
c07fda89164d7cbdaed93eebc586cddddfca92da
erika-r/CA268_python
/week3/stacks/matching_brackets.py
277
3.796875
4
from Stack import Stack def match(s): stack = Stack() for letter in s: if letter == ")" and stack.is_empty(): return False elif letter == "(": stack.push("(") elif letter == ")" and not stack.is_empty(): stack.pop() return stack.is_empty()
39decaf8ef680d934aeeeabfb40cdcfa26c5a651
hugoleeney/leetcode_problems
/p1052_grumpy_bookstore_owner.py
1,883
3.59375
4
""" Today, the bookstore owner has a store open for customers.length minutes. Every minute, some number of customers (customers[i]) enter the store, and all those customers leave after the end of that minute. On some minutes, the bookstore owner is grumpy. If the bookstore owner is grumpy on the i-th minute, grumpy[i] = 1, otherwise grumpy[i] = 0. When the bookstore owner is grumpy, the customers of that minute are not satisfied, otherwise they are satisfied. The bookstore owner knows a secret technique to keep themselves not grumpy for X minutes straight, but can only use it once. Return the maximum number of customers that can be satisfied throughout the day. Example 1: Input: customers = [1,0,1,2,1,1,7,5], grumpy = [0,1,0,1,0,1,0,1], X = 3 Output: 16 Explanation: The bookstore owner keeps themselves not grumpy for the last 3 minutes. The maximum number of customers that can be satisfied = 1 + 1 + 1 + 1 + 7 + 5 = 16. Note: 1 <= X <= customers.length == grumpy.length <= 20000 0 <= customers[i] <= 1000 0 <= grumpy[i] <= 1 """ from typing import List class Solution: def maxSatisfied(self, customers: List[int], grumpy: List[int], X: int) -> int: max_cheat = sum((x for idx, x in enumerate(customers[0:X]) if grumpy[idx] == 1)) cheat = max_cheat max_cheat_idx = 0 for idx, c in enumerate(customers[1:len(customers) - X + 1]): prior_cheat = cheat cheat = cheat - (customers[idx] if grumpy[idx] else 0) + (customers[idx + X] if grumpy[idx + X] else 0) if cheat > max_cheat: max_cheat = cheat max_cheat_idx = idx + 1 satisfied = max_cheat + sum((x for idx, x in enumerate(customers) if grumpy[idx] == 0)) return satisfied if __name__ == "__main__": s = Solution() assert s.maxSatisfied([1,0,1,2,1,1,7,5], [0,1,0,1,0,1,0,1], 3)
148c0296cce6aa1d0514c60e6af20752d69dff37
Tiotao/CS3245HW2
/SkipList.py
2,861
3.875
4
import math class Node: def __init__(self, data=None): self.next = None # next node self.skip = None # the target node of the skip pointer (if has) self.data = int(data) def append_node(self, node): self.next = node def has_next(self): return self.next != None # if the node has a skip pointer def has_skip(self): return self.skip != None def __repr__(self): return "Node: " + str(self.data) class SkipList: def __init__(self, array=None): self.length = 0 self.skip = False if array == None: self.head = None # first node in the list self.tail = None # last node in the list else: array.sort() for i in array: node = Node(i) self.append(node) def __len__(self): return self.length # if skip pointers are created for this list def is_skipped(self): return self.skip # get a specific node according to its index def get_node(self, index): current = self.head while index > 0 : current = current.next index = index - 1 return current # append a node after the last node of the list def append(self, node): if len(self) == 0: self.head = node self.tail = node else: self.tail.append_node(node) self.tail = node self.length = self.length + 1 # calculate the skip distance of the list def skip_distance(self): list_length = len(self) skipDis = math.floor(math.sqrt(list_length)) return skipDis # connect two nodes by adding skip pointers from current node to target node. input: index! not node! def connect(self, current_index, target_index): current_node = self.get_node(current_index) target_node = self.get_node(target_index) current_node.skip = target_node # create skip pointes for the entire list def build_skips(self): if self.is_skipped(): self.clearSkips() else: distance = self.skip_distance() current = 0 target = 0 + distance while target < self.length: self.connect(current, target) current = target target = target + distance self.skip = True return self # clear skip pointers for the entire list def clear_skips(self): if self.skip == True: current = self.head while current.has_next(): if current.has_skip(): current.skip = None current = current.next self.skip = False return self def to_list(self): result = [] current = self.head while current.has_next(): result.append(current.data) current = current.next result.append(self.tail.data) return result # return two arrays. one with all nodes, another with skip pointers def display(self): first = [] second = [] current = self.head while current.has_next(): if current.has_skip(): second.append((current.data, current.skip.data)) first.append(current.data) current = current.next first.append(self.tail.data) return { "all_nodes": first, "skips": second }
4c2245c6d3df2432c9de6a70770af9aa7e007ce0
DanielDubonDR/LFP-Proyecto1_201901772
/Clases/Dt.py
1,509
3.859375
4
class Seccion: def __init__(self, id, seccion): self.id=id self.seccion=seccion def __str__(self): string=str(self.id)+str(" ")+str(self.seccion) return string class Opciones: def __init__(self, idseccion, identificador, nombre, precio, descripcion): self.idseccion=idseccion self.identificador=identificador self.nombre=nombre self.precio=precio self.descripcion=descripcion def setIdseccion(self, idseccion): self.idseccion=idseccion def setIdentificador(self, identificador): self.identificador=identificador def setNombre(self, nombre): self.nombre=nombre def setPrecio(self, precio): self.precio=precio def setDescripcion(self, descripcion): self.descripcion=descripcion def __str__(self): string=str(self.idseccion)+str(" ")+str(self.identificador)+str(" ")+str(self.nombre)+str(" ")+str(self.precio)+str(" ")+str(self.descripcion) return string def __gt__(self, lista): return float(self.precio)>float(lista.precio) ''' def __init__(self, idseccion, identificador, nombre, precio, descripcion): self.idseccion=idseccion self.identificador=identificador self.nombre=nombre self.precio=precio self.descripcion=descripcion ''' ''' a=Opciones() a.setIdseccion(1) a.setIdentificador(2) a.setNombre(3) a.setPrecio(4) a.setDescripcion(5) print(a) '''
7e1ff0471979074f6cdc7daeaa37a9e6e3055ca5
hyt0617/leetcode
/10-19/lc_19_removeNthFromEnd.py
640
3.703125
4
# !/usr/bin/env python # -*-coding: utf-8 -*- def removeNthFromEnd(head, n): """ :type head: ListNode :type n: int :rtype: ListNode """ length = 0 tmp = head while tmp: length += 1 tmp = tmp.next remove_index = length - n if remove_index == 0: return head.next else: tmp = head prev = None cur_idx = 0 while tmp: if cur_idx == remove_index: prev.next = tmp.next break else: prev = tmp tmp = tmp.next cur_idx += 1 return head
719b18fa50f010abc1c7e4e11fa91271bd601254
zehra-99/GlobalAIHubPythonHomework
/hw1_zehraevrensel.py
648
3.84375
4
#value = input("Please enter the first value:\n") #print(f'Entered value is {value}') name = input("Please enter your name: ") print(f'your name is {name}') print(type(name)) surname = input("Please enter your surname: ") print(f'your surname is {surname}') print(type(surname)) id = int(input("Please enter your id: ")) print("your id is :{}".format(id)) print(type(id)) birthday = input("Please enter your birthday: ") print(f'your birthday is {birthday}') print(type(birthday)) favourite_colour = input("Please enter your favourite colour: ") print(f'your favourite colour is {favourite_colour}') print(type(favourite_colour)) #zehra evrensel #zehra.evrensel2017@gtu.edu.tr
2b6108e6846759a02079feb92fedd1cc9557dd8b
rkuate/adventure_game
/adventure_game.py
6,411
3.796875
4
import time import random # List of potentials ennemies ennemies = ["pirate", "dragon", "wickie fairie", "troll", "wolf", "witch"] # Hand of the player ; items he is carrying hand = ["dagger"] # Variable name for the sword sword = "sword" # Print messages with delays def print_pause(message): print(message) # Delay the message by 2 seconds time.sleep(0) # Print the introduction when starting a new game def intro(ennemy): print_pause("You find yourself standing in an open field," " filled with grass and yellow wildflowers.") print_pause("Rumor has it that a " + ennemy + " is somewhere around here, and has been" " terryfying the nearby village.") print_pause("In front of you is a house.") print_pause("To your right is a dark cave.") print_pause("In your hand you hold your trusty (but not" " very effective) dagger.") # Make sure the player enters valid inputs # Valid inputs are the choices values def valid_input(prompt, choices): print_pause("\n") choice = input(prompt + "\n") for item in choices: if choice == item: return choice return valid_input(prompt, choices) # Path when the player decides to knock at the door def knock_door(ennemy): print_pause("You approach the door of the house.") print_pause("You are about to knock when the door " "opens and out steps a " + ennemy + ".") print_pause("Eep! This is the " + ennemy + "'s house!") print_pause("The " + ennemy + " attacks you!") # Path when the player decides to peer into the cave def peer_cave(): print_pause("You peer cautiously into the cave") # Path when the player peers into the cave without the sword def peer_cave_dagger(ennemy, ennemies, hand, sword): print_pause("It turns out to be only a very small cave.") print_pause("Your eye catches a glint of metal behind a rock.") print_pause("You have found the magical Sword of Ogoroth.") print_pause("You discard your silly old dagger and " "take the sword with you.") print_pause("You walk back out to the field.") play_game(ennemy, ennemies, hand, sword) # Path when the player peers into the cave with the sword def peer_cave_sword(ennemy, ennemies, hand, sword): print_pause("You've been here before, and gotten all the " "good stuff. It's just an empty cave now.") print_pause("You walk back out to the field.") play_game(ennemy, ennemies, hand, sword) # Path when the player attacks the ennemy with the sword def sword_attack(ennemy, ennemies, sword): print_pause("As the " + ennemy + " moves to attack, " "you unsheath your new sword.") print_pause("The Sword of Ogoroth shines brightly in your " "as you brace yourself for the attack.") print_pause("But the " + ennemy + " takes one look at your " "shiny new toy and runs away!") print_pause("You have rid the town of the " + ennemy + ". " "You are victorious!") print_pause("\nGAME OVER") play_again(ennemies, sword) # Path when the player attacks the ennemy without the sword def dagger_attack(ennemy, ennemies, sword): print_pause("You do your best...") print_pause("but your dagger is no match for the " + ennemy + ".") print_pause("You have been defeated!") print_pause("\nGAME OVER") play_again(ennemies, sword) # Path when the player decides to run away from the ennemy def run_away(ennemy, ennemies, hand, sword): print_pause("You ran back into the field. Luckily, you " "don't seem have been followed.") play_game(ennemy, ennemies, hand, sword) # Request the player to decide whether to restart the game again or not def play_again(ennemies, sword): hand = ["dagger"] # Collect the choice for the player # Whether to start a new game or exit choice_play = valid_input("Would you like to play again? (y/n)", ["y", "n"]) if (choice_play == "y"): print_pause("Excellent! Restarting the game...") adventure_game(ennemies, hand, sword) elif (choice_play != "n"): print_pause("Thanks for playing! See you next time.") play_again(ennemies, sword) # Continue a game ; from the point after the introduction def play_game(ennemy, ennemies, hand, sword): print_pause("Enter 1 to knock at the door of the house.") print_pause("Enter 2 to peer into the cave.") print_pause("What would you like to do?") # Collect the choice for the player # Whether to knock the door or peer into the cave choice_village = valid_input("(Please enter 1 or 2.)", ["1", "2"]) if choice_village == "1": knock_door(ennemy) if sword in hand: # Collect the choice for the player # Whether to fight or run away choice_door = valid_input("Would you like to (1) " "fight or (2) run away?", ["1", "2"]) if choice_door == "1": sword_attack(ennemy, ennemies, sword) elif choice_door == "2": run_away(ennemy, ennemies, hand, sword) elif sword not in hand: print_pause("You feel a bit under-prepared for this, " "what with only having a tiny dagger.") choice_door = valid_input("Would you like to (1) " "fight or (2) run away?", ["1", "2"]) if choice_door == "1": dagger_attack(ennemy, ennemies, sword) elif choice_door == "2": run_away(ennemy, ennemies, hand, sword) elif choice_village == "2": peer_cave() if sword in hand: peer_cave_sword(ennemy, ennemies, hand, sword) elif sword not in hand: # Assign the sword to the player hand.append(sword) peer_cave_dagger(ennemy, ennemies, hand, sword) # Main function of the game def adventure_game(ennemies, hand, sword): # Choose randomly a new ennemy each time a new game start ennemy = random.choice(ennemies) intro(ennemy) play_game(ennemy, ennemies, hand, sword) adventure_game(ennemies, hand, sword)
be25d408f582b7454a795fb81757bf9f3a57aec7
Eunsoogil/pythonStudy
/basic/oop.py
4,800
3.59375
4
# oop print('\n------------------------oop-----------------------\n') print(type(None)) print(type(True)) print(type(5)) # object임 class BigObject: # code pass print(type(BigObject)) objTest = BigObject() # instanciate print(objTest) # 주소 class PlayerCharacter: # Class Object Attribute # static, 바꿀 수 있음 membership = True # __ dunder method # name에 첫번째 파라미터가 들어감 def __init__(self, name='annoymous', age=0): if self.membership: if age > 18: self.name = name self.age = age def run(self): print('run') def shout(self): print(f'my name is {self.name}') # 일종의 전역 method @classmethod def adding_things(cls, num1, num2): return num1 + num2 # 이런식으로도 사용 가능 @classmethod def start(cls, num1, num2): return cls('default', num1 + num2) # 일종의 전역 method @staticmethod def adding_things2(num1, num2): return num1 + num2 player1 = PlayerCharacter('cindy', 44) # player1이 self가 된다 player2 = PlayerCharacter('tom', 22) print(player1) print(player1.name) print(player1.age) print(player2.name) print(player2.age) print(player1.run()) # function이 return이 없으면 none return print(player1.membership) print(player1.shout()) player3 = PlayerCharacter('jack', 10) # print(player3.shout()) # 생성자 제한으로 안됨 print(player1.adding_things(2, 3)) print(PlayerCharacter.adding_things(2, 3)) player4 = PlayerCharacter.start(10, 9) print(player4.age) player1.membership = False print(player1.membership) # Encapsulation : 1. data fields와 methods를 하나로 묶고, 2. 이를 외부에 감춘다 # Abstraction : 객체의 정보와 기능들을 담아 명명하여 쉽게 접근하기 위함 # public인 경우, player1.speak = 'booo' 같은 것이 가능하다 # Abstraction 기능을 위해 private이 이상적이지만 python에는 그런 기능이 없음 # 앞에 _를 붙어 있으면 private라는 의미, 하지만 접근은 가능(???) # Inheritance : 상속, 재사용성 class User: def sign_in(self): print('logged in') # __init__이 반드시 필요한 것은 아님 class Wizard(User): def __init__(self, name, power): self.name = name self.power = power def attack(self): print('fire ball') wizard1 = Wizard('merlin', 50) wizard1.attack() print(isinstance(wizard1, Wizard)) print(isinstance(wizard1, User)) print(isinstance(wizard1, object)) # Polymorphism : 다형성, 재사용성 # exercise print('\n------------------------exercise-----------------------\n') class Pets(): animals = [] def __init__(self, animals): self.animals = animals def walk(self): for animal in self.animals: print(animal.walk()) class Cat(): is_lazy = True def __init__(self, name, age): self.name = name self.age = age def walk(self): return f'{self.name} is just walking around' class Simon(Cat): def sing(self, sounds): return f'{sounds}' class Sally(Cat): def sing(self, sounds): return f'{sounds}' # 1 Add another Cat class John(Cat): def sing(self, sounds): return f'{sounds}' # 2 Create a list of all of the pets (create 3 cat instances from the above) my_cats = [Simon('simon', 2), Sally('sally', 1), John('john', 3)] print(my_cats) # 3 Instantiate the Pet class with all your cats use variable my_pets pets = Pets(my_cats) print(Pets) # 4 Output all of the cats walking using the my_pets instance pets.walk() # super print('\n------------------------super-----------------------\n') # 상속시 부모class.__init__.함수(self, *args) 식이였음 # 이젠 상속시 super.__init__.함수(self, *args) 가능(매우 불편..) # introspection print(dir(wizard1)) # 뭐 있는지 나옴 # 내부에 dunder method가 있음을 알 수 있음 # 당연히 수정 가능, class를 위한 기능들이 내장되어 있다 class SuperList(list): # 매개변수 형이 list가 됨 def __len__(self): return 1000 super_list1 = SuperList(); print(len(super_list1)) super_list1.append(5) print(super_list1) print(issubclass(SuperList, list)) # true나옴, 상속받음 # multiple inheritance : 그냥 매개변수를 넣으면 됨.. class HybridBorg(Simon, Sally, John): pass hb1 = HybridBorg('hb1', 50) print(hb1.sing('work?')) # MRO - Method Resolution Order class A: num = 10 class B(A): pass class C(A): num = 1 class D(B, C): pass # A -> B, C -> D, D는 multiple inheritance print(D.num) print(D.__mro__) # 상속 순서 보여줌 # 상속이 심하게 꼬이면 유지보수 불가
cd1e8b74c099df99c408e8681f9d48fd8c05a8f9
Mounitha-b/CS273A-MachineLearning
/hw2-part1.py
2,689
4.125
4
import numpy as np import matplotlib.pyplot as plt import mltools as ml # (a) Loading the data from the curve80.txt file, and splitting to # 75-25, training and test data data = np.genfromtxt("data/curve80.txt",delimiter=None) X = data[:, 0] # First column is feature X = X[:,np.newaxis] # code expects shape (M,N) so make sure it's 2-dimensional Y = data[:, 1] # Second column is the result Xtr,Xte,Ytr,Yte = ml.splitData(X,Y,0.75) # split data set 75/25 Ytr = Ytr[:, np.newaxis] Yte = Yte[:, np.newaxis] # (b) Plotting the linear regression prediction function, and training data, # finding the regression coefficients, finding MSE of train and test data lr = ml.linear.linearRegress(Xtr, Ytr) # create and train model xs = np.linspace(0, 10, 200) # densely sample possible x-values xs = xs[:, np.newaxis] # force "xs" to be an Mx1 matrix ys = lr.predict(xs) # make predictions at xs plt.scatter(Xtr, Ytr, c = 'red') # Plotting the training data points plt.plot(xs, ys, c= 'black') # Plotting the predictor line plt.title('Regression Function') plt.show() print 'Regression Coefficients\t=\t', lr.theta YTrainPred = lr.predict(Xtr) YTestPred = lr.predict(Xte) mseTrain = np.mean((YTrainPred - Ytr) ** 2) mseTest = np.mean((YTestPred - Yte) ** 2) print 'Mean Square Error on Training Data\t=\t', mseTrain print 'Mean Square Error on Test Data\t=\t', mseTest # (c) Fitting y = f(x) with polynomial functions of increasing order degrees = [1, 3, 5, 7, 10, 18] trainingError = [] testError = [] for degree in degrees: # Scaling and making polynomial features XtrP = ml.transforms.fpoly(Xtr, degree, bias=False) XtrP, params = ml.transforms.rescale( XtrP ) lr = ml.linear.linearRegress( XtrP, Ytr ) XteP,_ = ml.transforms.rescale( ml.transforms.fpoly(Xte, degree, False ), params ) xsP,_ = ml.transforms.rescale( ml.transforms.fpoly(xs, degree, False ), params ) # Predicting for xs, and plotting predictor function ys = lr.predict(xsP) # make predictions at xs plt.scatter(Xtr, Ytr, c = 'red') ax = plt.axis() plt.plot(xs, ys, c = 'black') # Plotting the predictor line plt.axis(ax) plt.title("Polynomial Function of Degree " + str(degree)) plt.show() # Calculating error in test and training data YTrainPredP = lr.predict(XtrP) YTestPredP = lr.predict(XteP) trainingError.append(np.mean((YTrainPredP - Ytr) ** 2)) testError.append(np.mean((YTestPredP - Yte) ** 2)) print trainingError print testError plt.semilogy(degrees, trainingError, c = 'red') plt.semilogy(degrees, testError, c = 'green') plt.xticks(degrees, degrees) plt.title("Training and Test Error vs Degree of Polynomial") plt.show()
da7a7a18169d8aab1234a10bb3a7656656255e61
musclecarlover07/Python
/Problem 1.py
3,997
4
4
# ===================================================================== # Course: CS219 -- Problem 1 -- Donor List # Filename: Problem 1_<Micheal Smith>_Problem 1.py # Author: <Micheal Smith> # Purpose: Program tht creates a multidimensional list of # donors and some information. Ability to edit and # print the data. # ===================================================================== donor_list = list() def main(): while True: print("Select an option:") print(" (A)dd a new donor") print(" (E)dit a record") print(" (L)ook up a record") print(" (Q)uit Program") user_input = input("> ") if user_input == "Q": break elif user_input == "A": add_data() elif user_input == "E": edit_info() elif user_input == "L": look_up() else: print("Invalid Selection. Try again\n") def add_data(): # Add Data print("\nADD INFORMATION") print("How many records would you like to input") num_records = int(input("> ")) while True: # Checks for a valid value. Must be an int greater than 0 if num_records >= 1: # Check to see if the is any records list_len = len(donor_list) # Creates empty lists in donor_list = num_records i = 0 while i < num_records: donor_list.append(list()) i += 1 j = 1 # Checks to see if there is an empty list before the records are created if list_len == 0: while j <= num_records: record_num = j - 1 print("\nRecord Number:", record_num + 1) donor_list[record_num].append(input("Name:")) donor_list[record_num].append(input("Address:")) donor_list[record_num].append(input("Contact:")) j += 1 else: while j <= num_records: record_num = list_len print("\nRecord Number:", j) donor_list[record_num].append(input("Name:")) donor_list[record_num].append(input("Address:")) donor_list[record_num].append(input("Contact:")) j += 1 list_len += 1 print("Created", i, "record(s)\n") break elif num_records < 1: print("Must input at least 1 record") else: print("Invalid value. Please Try again") def edit_info(): # Edit info print("EDIT INFORMATION") print("Enter the Record you wish to modify") look_up() record_num = int(input("Record: ")) - 1 print("Select which element of the record you wish to modify") print("'0' = Name") print("'1' = Address") print("'2' = Contact") element_num = int(input("Element: ")) while True: if element_num == 0: donor_list[record_num][element_num] = input("Name: ") break elif element_num == 1: donor_list[record_num][element_num] = input("Address: ") break elif element_num == 2: donor_list[record_num][element_num] = input("Contact: ") break else: print("Invalid Selection") def look_up(): print("\nINFO") print( "#", " " * (2 - len("#")), "Name", " " * (15 - len("Name")), "Address", " " * (20 - len("Address")), "Contact", " " * (10 - len("Contact")) ) j = 1 for i in donor_list: if j < 10: record = "0" + str(j) else: record = str(j) print( record, " " * (2 - len(i)), i[0], " " * (15 - len(i[0])), i[1], " " * (20 - len(i[1])), i[2], " " * (10 - len(i[2])), ) j += 1 print("\n") main()
6881510fa8ceae6121b5c9ecd8c1a563bfdf0379
darthlukan/pysys
/filescripts/oddnumbers.py
296
3.8125
4
# -*- coding: utf-8 -*- """ Created on Sun Mar 4 21:06:41 2012 @author: darthlukan """ odd = [] def odd_print(): for i in odd: print i def main(): for i in range(1, 100): if i % 2 != 0: odd.append(i) odd_print() if __name__ == '__main__': main()
5481385286e55db7037035fb3b982f4a7a669b3a
eunjin917/Summer-Algorithm-Merge
/chihun-jang/키패드 누르기.py
1,063
3.828125
4
def solution(numbers, hand): answer = '' cur_left = 10 cur_right= 12 change_zero = [11 if i == 0 else i for i in numbers] print(change_zero) for i in change_zero: if i % 3 == 1: cur_left = i answer += "L" elif i%3 == 0: cur_right = i answer += "R" else: if (abs(cur_right-i)%3+abs(cur_right-i)//3) < (abs(cur_left-i)%3+abs(cur_left-i)//3): cur_right = i answer += "R" elif (abs(cur_right-i)%3+abs(cur_right-i)//3) > (abs(cur_left-i)%3+abs(cur_left-i)//3): cur_left = i answer += "L" else: if hand =="left": cur_left = i answer += "L" else: cur_right = i answer += "R" print("cur_left : ",cur_left, "cur_right : ", cur_right) print(answer) return answer #지난주에 개인문제까지 push해서 다시 push합니당
51f81784fd7c0f47a3cfaa8195572fa81354773f
gsudarshan1990/PythonSampleProjects
/Python/ListExample3.py
544
4
4
my_list=['one', 'two', 'three'] print(my_list) another_list=['four', 'five', 'six'] print(another_list) new_list = my_list + another_list print(new_list) new_list[0]='ONE ALL CAPS' print(new_list) new_list.append('seven') new_list.append('eight') print(new_list) value1=new_list.pop() print(new_list) value2=new_list.pop() print(new_list) print(value1) print(value2) value3= new_list.pop(0) print(new_list) print(value3) my_new_list=['one', 'two','three', 'four'] my_new_list.sort() print(my_new_list) my_new_list.reverse() print(my_new_list)
18b3dc5150fd3d2cec2e74693f7492739634b775
chenxu0602/LeetCode
/1282.group-the-people-given-the-group-size-they-belong-to.py
1,522
3.71875
4
# # @lc app=leetcode id=1282 lang=python3 # # [1282] Group the People Given the Group Size They Belong To # # https://leetcode.com/problems/group-the-people-given-the-group-size-they-belong-to/description/ # # algorithms # Medium (83.78%) # Likes: 125 # Dislikes: 71 # Total Accepted: 14K # Total Submissions: 16.7K # Testcase Example: '[3,3,3,3,3,1,3]' # # There are n people whose IDs go from 0 to n - 1 and each person belongs # exactly to one group. Given the array groupSizes of length n telling the # group size each person belongs to, return the groups there are and the # people's IDs each group includes. # # You can return any solution in any order and the same applies for IDs. Also, # it is guaranteed that there exists at least one solution.  # # # Example 1: # # # Input: groupSizes = [3,3,3,3,3,1,3] # Output: [[5],[0,1,2],[3,4,6]] # Explanation: # Other possible solutions are [[2,1,6],[5],[0,4,3]] and # [[5],[0,6,2],[4,3,1]]. # # # Example 2: # # # Input: groupSizes = [2,1,3,3,3,2] # Output: [[1],[0,5],[2,3,4]] # # # # Constraints: # # # groupSizes.length == n # 1 <= n <= 500 # 1 <= groupSizes[i] <= n # # # # @lc code=start from collections import defaultdict class Solution: def groupThePeople(self, groupSizes: List[int]) -> List[List[int]]: count = defaultdict(list) for i, size in enumerate(groupSizes): count[size].append(i) return [l[i:i+s] for s, l in count.items() for i in range(0, len(l), s)] # @lc code=end
288baa7fe3457096b13c54be60788069295b5564
aitorlomu/SistemasGestores
/Python/Python/Ejercicios/12.py
298
3.875
4
num=int(input('Introduce un número para saber si es primo ')) contador=0 for i in range(1,int((num/2)+1)): if(num%i)==0: contador=contador+1 if contador>2: print('El número ',num,' no es primo') break if contador<=2: print('El número ',num,' es primo')
f19a26b4f0f26fc6b4d27e1b163944c89f48a20c
abhishpj/Sample_automation
/games/rolling_dice.py
667
3.734375
4
from __future__ import print_function import random class Dice(object): lower_boud = 1 upper_bound = 6 def __init__(self): self.input = '' self.roll_again = True def start_dice(self): while self.roll_again: print("Rolling the dice ") print(self.generate_random()) print(self.generate_random()) self.input =raw_input("Enter T to continue rolling ") if self.input != 'T':self.roll_again = False @classmethod def generate_random(cls): return random.randint(cls.lower_boud,cls.upper_bound) if __name__ == "__main__": x=Dice() x.start_dice()
c22074db98b0fbb9dbca8d5954f26cfcf1f7bd12
Prakruthy-Jayakumar/My_Files
/python/assignments/set 6/set6_3/2.py
252
3.5
4
import csv filename="mycsv.csv" fields=[] rows=[] with open('mycsv.csv','r') as f: reader=csv.reader(f) fields=reader.next() for row in reader: rows.append(row) for row in rows[:5]: for col in row: print("%10s"%col), print('\n')
fc61798b3da15e8a7e3d5cf9d5820843c3932172
SafonovMikhail/python_000577
/001146StepikPyBegin/Stepik001146PyBeginсh13p04st02_functions_THEORY02_202100301.py
2,206
4.5625
5
# ---------------------------- print('# Решение задач') print( '# Задача 1. Напишите функцию, которая возвращает длину гипотенузы прямоугольного треугольника по известным значениям его катетов.') def compute_hypotenuse(a, b): c = (a ** 2 + b ** 2) ** 0.5 return c print(compute_hypotenuse(3, 4)) print(compute_hypotenuse(5, 12)) print(compute_hypotenuse(1, 1)) print() # ---------------------------- print('# Задача 2. Напишите функцию, вычисляющую расстояние между двумя точками') def get_distance(x1, y1, x2, y2): return compute_hypotenuse(x1 - x2, y1 - y2) x1, y1 = float(input()), float(input()) # считываем координаты первой точки x2, y2 = float(input()), float(input()) # считываем координаты второй точки print(get_distance(x1, y1, x2, y2)) # вычисляем и выводим расстояние между точками print() # ---------------------------- print('# Задача 3. Напишите функцию, принимающую в качестве аргумента натуральное число и возвращающую сумму его цифр.') def sum_digits(n): result = 0 while n > 0: result += n % 10 n //= 10 return result n = int(input()) print(sum_digits(n)) # вычисляем и выводим сумму цифр считанного числа print() # ---------------------------- print( '# Задача 4. Напишите функцию, принимающую в качестве аргумента список чисел и возвращающую среднее значение элементов списка.') def compute_average(numbers): return sum(numbers) / len(numbers) numbers = [1, 3, 5, 1, 6, 8, 10, 2] print(numbers) print(compute_average(numbers)) # вычисляем и выводим среднее значение элементов списка print() # ---------------------------- print('# ') print()
80aee4c57ba414b9a24b0fcebc9302e71c75bd7f
J-Krisz/EDUBE-Labs
/PCAP/2.5.1.6 LAB: Improving the Caesar cipher.py
1,314
4.5
4
""" The original Caesar cipher shifts each character by one: a becomes b, z becomes a, and so on. Let's make it a bit harder, and allow the shifted value to come from the range 1..25 inclusive. Moreover, let the code preserve the letters' case (lower-case letters will remain lower-case) and all non-alphabetical characters should remain untouched. Your task is to write a program which: asks the user for one line of text to encrypt; asks the user for a shift value (an integer number from the range 1..25 - note: you should force the user to enter a valid shift value (don't give up and don't let bad data fool you!) prints out the encoded text. """ text = input("Enter text for encryption here : ") shift = 0 cipher = '' while not shift: try: shift = int(input("Enter a shift value between 1-25 : ")) if shift not in range(1, 26): raise ValueError except ValueError: shift = 0 if shift == 0: print("Wrong shift value") for char in text: if char.isalpha(): code = ord(char) + shift if char.isupper(): first = ord("A") else: first = ord("a") code -= first code %= 26 cipher += chr(first + code) else: cipher += char print(cipher)
e2d59eee17c0738b5a6414ef61ed510f5e1ed2ec
mrzepka/carinfowebcrawler
/sanitizer.py
2,895
3.875
4
''' Class to sanitize/reorder input given to us so that we can form a valid query to search for in the main python script ''' def create_makes_dict(): '''Creates mapping of makes -> what they should be for query''' makes = {} with open('makes.txt', 'r') as makesfile: for line in makesfile.readlines(): line_arr = line.split('/') makes[line_arr[0]] = line_arr[1].rstrip() #strip off \n from file line return makes def is_make(text, makes): '''returns true if text is defined in the makes dictionary''' if text.lower() in makes.keys(): return True return False def is_year(text): '''returns true if the text is a number to be used as a year''' try: int(text) return True except ValueError: return False def get_base_query(message): ''' Pulls out everything after /u/car_spec_bot in the message params: message is the comment/message body from reddit inbox ''' bodylist = message.split(' ') indexofquery = bodylist.index('/u/car_spec_bot') return bodylist[indexofquery + 1:] class Sanitizer: ''' Sanitizer class that takes in input and cleans it up to create a query. The query created will be used in the webcrawler to create the URL that we will be pulling data from. ''' def __init__(self): self.makes_dictionary = create_makes_dict() self.make_found = False self.make = '' self.model = '' self.year = '' def get_make_info(self, text): '''returns information about a make. Uses dictionary to match partial words, abbreviations, and a few misspellings into actual makes that can be used in the query ''' return self.makes_dictionary[text] def verify(self): '''Make sure everything is initialized''' return bool(self.make and self.model and self.year) def create_query(self): '''return the string that will be used in the query''' if self.verify(): return self.make + '-' + self.model.lstrip().replace(' ', '_')\ + '-' + self.year def sanitize_input(self, text): ''' essentially the "main" of this class. begins sanitation of input params: text given is comment body from reddit message/comment ''' list_of_input = get_base_query(text) for item in list_of_input: if is_make(item, self.makes_dictionary): if not self.make_found: self.make = self.get_make_info(item) self.make_found = True elif is_year(item): self.year = self.year + item # in case someone does something like 1 9 2 3... else: self.model = self.model + ' ' + item return self.create_query()
74efacbfeeb0b8a7ad1eb994993adc3429dc5005
idannos/send-emails-with-python
/code.py
1,430
3.625
4
import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart def send_email(message, email, password,send_to_email, subject): """ :param message: the message we want to send :param email: the email will send from this email address always :param password: the password for the email :param send_to_email: the email address we want to send to. :param subject: subject of the email message :exit: sent or an error message """ try: msg = MIMEMultipart() msg['From'] = email msg['To'] = send_to_email msg['Subject'] = subject msg.attach(MIMEText(message, 'plain')) server = smtplib.SMTP('smtp.gmail.com', 587) # may need to change the port server.starttls() server.login(email, password) text = msg.as_string() server.sendmail(email, send_to_email, text) server.quit() print "sent email" except Exception as e: print e message = "the message itself" email = "my_email@gmail.com" password = "my_email_password" send_to_email = ["ar12@gmail.com", "ts@gmail.com"] # add emails you want to send to to this list. subject = "mail's subject" for i in send_to_email: send_email(message, email, password, i, subject) # keep in mind that running this function takes about 2 seconds, # if you want to send to hundreds mails you need try with threads maybe or another methods
7e7cf8a96bd4a6ee3f290952c9b3ac01a9c706a5
hemxism96/clustering
/clustering/KMean.py
4,093
3.515625
4
import numpy as np import matplotlib.pyplot as plt from scipy.spatial import distance class KMean: def __init__(self,x,k,distance='euclidean'): self.x = x # Input Points self.k = k # Nb of Clusters self.dim = x.shape[-1] # Point Dimension self.n = x.shape[0] # Nb of Points self.distance = distance # Method to use for distance calculation self.belongs = None # n value array which contain for each point the id of the cluster # Generating random points for cluster's positions self.middles = np.random.randint(low=0,high=20,size=(k,self.dim))/2 self.code_color = ['red','green','blue','black','yellow','orange','purple','brown','grey'] self.colors = [] self.colormap = {} def _euclidean_distance(self): k = self.k n = self.n x = self.x l = self.dim middles = self.middles # (k,n,l) points = np.broadcast_to(x,(k,n,l)) c = np.zeros((k,n,l)) # Need to find a numpy way to do this to avoid loops # (k,n,l) for i in range(0,k): c[i] = np.broadcast_to(middles[i],(n,l)) # Euclidean Distance # (k,n) because distance is a scalar here d = np.linalg.norm(points-c,axis=2) # For each point get the argument of the minimum distance args = np.argmin(d,axis=0) return(args) def _manhattan_distance(self): k = self.k n = self.n x = self.x l = self.dim middles = self.middles # (k,n,l) points = np.broadcast_to(x,(k,n,l)) c = np.zeros((k,n,l)) # Need to find a numpy way to do this to avoid loops # (k,n,l) for i in range(0,k): c[i] = np.broadcast_to(middles[i],(n,l)) # Manhattan Distance # (k,n) because distance is a scalar here d = np.sum(abs(points-c),axis=2 ) # For each point get the argument of the minimum distance args = np.argmin(d,axis=0) return(args) def _cosine_distance(self): k = self.k n = self.n x = self.x l = self.dim middles = self.middles # (k,n,l) points = np.broadcast_to(x,(k,n,l)) c = np.zeros((k,n,l)) # Need to find a numpy way to do this to avoid loops # (k,n,l) for i in range(0,k): c[i] = np.broadcast_to(middles[i],(n,l)) # Cosine Distance # (k,n) because distance is a scalar here d = np.zeros((k,n)) for i in range(0,k): for j in range(0,n): d[i][j] = scipy.spatial.distance.cosine(points[i][j],c[i][j])# cosine distance # For each point get the argument of the minimum distance args = np.argmin(d,axis=0) return(args) def _scatter_plot(self): k = self.k n = self.n points = self.x l = self.dim middles = self.middles code_color = self.code_color colors = self.colors colormap = self.colormap for i in range(k): colormap[i] = code_color[i] colors.append(code_color[i]) plt.scatter(points[:,0],points[:,1],color='blue') plt.scatter(middles[:,0],middles[:,1],color= colors) for i in range(0,n): plt.scatter(points[i][0],points[i][1],color = colormap[self.belongs[i]]) plt.text(points[i][0], points[i][1], str(i), fontsize=15) for i in range(0,k): plt.text(middles[i,0],middles[i,1], chr(i+65), fontsize=15) def _new_middles(self): #Calcul of newer positions for clusters using the mean coordinates k = self.k n = self.n l = self.dim middles = self.middles new_middles = np.zeros((k,l)) for i in range(0,k): if i in self.belongs: new_middles[i] = np.mean(self.x[self.belongs ==i,:],axis=0) else: new_middles[i] = middles[i] return(new_middles) def run(self,n_iter=5): # Running the KMean algorithm if self.distance == 'euclidean': dist_function = self._euclidean_distance elif self.distance == 'manhattan': dist_function = self._manhattan_distance elif self.distance == 'cosine': dist_function = self._cosine_distance for i in range(n_iter): self.belongs = dist_function() self.middles = self._new_middles() self._scatter_plot() plt.show()
3de47ba2487419f5994621c851e4dcf89c2e3e26
ilkutkutlar/gene-grn-simulator
/src/models/reaction.py
2,043
3.546875
4
class Reaction: """ :param str name: :param List[str] left: :param List[str] right: :param Formula rate_fn: """ def __init__(self, name, left, right, rate_fn): self.name = name self.left = left self.right = right self.rate_function = rate_fn """ Return reaction rate in the given network state :param Dict[str, float] n: network state :returns float of reaction rate """ def rate(self, n): return self.rate_function.compute(n) """ Return change vector of reaction :param Dict[str, float] n: Network state :returns Dict[str, float] of change vector of reaction """ def change_vector(self, n): # How to obtain change vectors: # fpm + MmyR -> [k1] fpm:MmyR # --------------------------- # MmyR -= k1[MmyR][fpm] | General: if MmyR in left, then MmyR -= (k) * (left1) * (left2) # fpm -= k1[MmyR][fpm] # fpm:MmyR += k1[MmyR][fpm] | General: if fpm:MmyR in right, then fpm:MmyR += (k_) * (left1) * (left2) # fpm:MmyR -> [k_1] fpm + MmyR # --------------------------- # MmyR += k_1 [fpm:MmyR] # fpm += k_1 [fpm:MmyR] # fpm:MmyR -= k_1[fpm:MmyR] change = dict() for x in n: if x not in change: change[x] = 0 if x in self.left: change[x] -= self.rate(n) if x in self.right: change[x] += self.rate(n) return change def __str__(self): left = self.left[0] if self.left else "∅" right = self.right[0] if self.right else "∅" string = "Reaction: " + left + " ⟶ " + right + "\n" string += str(self.rate_function) return string def str_variables(self): str_vars = self.rate_function.str_variables() string = "" if len(str_vars) != 0: string = "----- " + self.name + " ----- \n" string += str_vars + "\n" return string
fc18a44eada9e25039962db2b55adaa53961f2ff
josh182014/Sorting
/src/iterative_sorting/iterative_sorting.py
1,214
4.1875
4
# TO-DO: Complete the selection_sort() function below def selection_sort(arr): # loop through n-1 elements for i in range(0, len(arr) - 1): cur_index = i smallest_index = cur_index # TO-DO: find next smallest element # (hint, can do in 3 loc) for j in range(i, len(arr)): if arr[smallest_index] > arr[j]: smallest_index = j # TO-DO: swap temp = arr[smallest_index] arr[smallest_index] = arr[i] arr[i] = temp return arr # TO-DO: implement the Bubble Sort function below def bubble_sort(arr): swaps_occurred = True while swaps_occurred: swaps_occurred = False for i in range(1, len(arr)): if arr[i] < arr[i - 1]: temp = arr[i] arr[i] = arr[i - 1] arr[i - 1] = temp swaps_occurred = True return arr # STRETCH: implement the Count Sort function below def count_sort(arr, maximum=-1): return arr if __name__ == "__main__": print(f"Selection Sort: [4, 2, 5, 1]") print(selection_sort([4, 2, 5, 1])) print(f"Bubble Sort: [4, 2, 5, 1]") print(bubble_sort([4, 2, 5, 1]))
73f7d52652b0e31e71dab7e2580af891b3003e85
ICS3U-Gallo/cpt-ethan
/main.py
44,816
4.1875
4
# MONOPOLY WITH A TWIST - By Ethan Lam from typing import List, Any import random from trivia import TRIVIA_QUESTIONS # Initializing constants NOBODY = -1 DISPLAY_PLAYER_ROLL_RESULTS = 1 DISPLAY_WHO_ROLLS_NEXT = 2 DAYS_IN_JAIL = 3 MAX_COMMUNITIES_ALLOWED = 5 VALID_TRIVIA_ANSWERS = "A B C D".split(" ") # Initializing global variables current_player = 0 starting_game = True debug_code = False game_over = False extra_roll = False passed_go = False def main(): display_title() start_menu_options() def display_title() -> None: """Displays the title. Done by: Ethan Lam """ game_title = "MONOPOLY WITH A TWIST!" coloured_game_title = "" i = 0 while i < len(game_title): if i % 3 == 0: coloured_game_title += add_colour(game_title[i], "red", True) elif i % 3 == 1: coloured_game_title += add_colour(game_title[i], "orange", True) else: coloured_game_title += add_colour(game_title[i], "cyan", True) i += 1 print(add_colour(" Welcome to", "none", True)) print(coloured_game_title) print() def start_menu_options() -> None: """Displays available menu options for the player and handles choice. Done by: Ethan Lam """ while True: print("[1] Start the game") print("[2] Read the rules") choice = input("> ") if choice == "1": play_game() if game_over: return elif choice == "2": print_rules() else: print("Invalid option!") print() def play_game() -> None: """Starts the game and continues until all players but one is bankrupt. Done by: Ethan Lam """ players = set_up_game() if players is None: return grids = set_up_grids() center_of_board_display = DISPLAY_WHO_ROLLS_NEXT display_board(players, grids, center_of_board_display) roll_dice(players) while True: clear_screen() center_of_board_display = DISPLAY_PLAYER_ROLL_RESULTS display_board(players, grids, center_of_board_display) if game_over: return follow_up_info = follow_up(players, grids) got_options = follow_up_info[0] if got_options: center_of_board_display = DISPLAY_WHO_ROLLS_NEXT clear_screen() sentence = add_colour(follow_up_info[1], "none", True) print(sentence) display_board(players, grids, center_of_board_display) roll_dice(players) def ask_trivia(questions: List[str]) -> bool: """Asks the current player a random trivia question. Args: Questions that can be asked along with the answers to verify. Returns: True if the player answered correctly. False otherwise. Done by: Ethan Lam """ selected_question_number = random.randint(0, len(questions) - 1) question_asked = questions[selected_question_number].split("\n") print() for i in range(5): print(question_asked[i]) correct_answer = question_asked[5] while True: choice = input("> ").upper() if choice == correct_answer: return True elif choice not in VALID_TRIVIA_ANSWERS: print("Invalid input. Please enter A, B, C, or D.") print() else: return False def set_up_grids() -> List[Any]: """A fixed initial set-up of the interactive grids on the board. Returns: The interactive grid set-up, each with unique properties. Done by: Ethan Lam """ grids = [] grid_names = ["GO", "Belleville", "North Bay", "Chance Card", "Grande Prairie", "Saint John", "Chance Card", "Sarnia", "Prince George", "Cell", "Peterborough", "Victoria", "Kamloops", "Chance Card", "pay $20", "Thunder Bay", "$25", "St. John's", "Free Parking", "$50", "Oshawa", "Kitchener", "Saskatoon", "Chance Card", "Vaughan", "Quebec City", "Mississauga", "JAIL", "Vancouver", "Ottawa", "$75", "Calgary", "an extra roll", "Montreal", "pay $50", "Toronto"] unpurchaseable_grids = [0, 3, 6, 9, 13, 14, 16, 18, 19, 23, 27, 30, 32, 34] grid_initial_costs = [-1, 50, 50, -1, 50, 75, -1, 75, 75, -1, 100, 100, 125, -1, -1, 125, -1, 150, -1, -1, 150, 175, 175, -1, 175, 200, 200, -1, 250, 250, -1, 275, -1, 300, -1, 350] grid_starting_worths = [-1, 10, 10, -1, 10, 20, -1, 20, 20, -1, 30, 30, 40, -1, -1, 40, -1, 50, -1, -1, 50, 60, 60, -1, 60, 75, 75, -1, 100, 100, -1, 125, -1, 130, -1, 150] # chr 0-7, 14-26, 28-31, 127-131, 134-154, 156, 157 <- These special characters are not printable # They are used purely for board string manipulation. grid_special_chars = [chr(5), chr(6), chr(7), chr(14), chr(15), chr(16), chr(17), chr(18), chr(19), chr(20), chr(21), chr(22), chr(23), chr(24), chr(25), chr(26), chr(28), chr(29), chr(30), chr(31), chr(127), chr(128), chr(129), chr(130), chr(131), chr(134), chr(135), chr(136), chr(137), chr(138), chr(139), chr(140), chr(141), chr(142), chr(143), chr(144)] placements = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 273, 386, 499, 612, 725, 838, 951, 1064, 1282, 1277, 1272, 1267, 1262, 1257, 1252, 1247, 1242, 1237, 1009, 896, 783, 670, 557, 444, 331, 218] i = 0 while i < 36: purchaseable = True if i in unpurchaseable_grids: purchaseable = False grid_name = grid_names[i] initial_cost = grid_initial_costs[i] starting_worth = grid_starting_worths[i] special_char = grid_special_chars[i] placement = placements[i] if 0 <= i <= 9: upgrade_cost = 50 elif 10 <= i <= 18: upgrade_cost = 100 elif 19 <= i <= 27: upgrade_cost = 150 else: upgrade_cost = 200 grid = { "name": grid_name, "belongs_to": NOBODY, "communities": 0, "purchaseable": purchaseable, "initial_cost": initial_cost, "upgrade_cost": upgrade_cost, "worth": starting_worth, "special_char": special_char, "placement": placement } grids.append(grid) i += 1 return grids def follow_up(player_info: List[Any], grid_info: List[Any]) -> List[Any]: """Changes information about the player based on their decisions of what to do after their roll. Args: player_info: Information about each player. grid_info: Information about each grid. Returns: A list of a boolean and a string. The boolean is True if the player was able to choose something. False otherwise. The string is the sentence returned based on the player's choice. Done by: Ethan Lam """ global current_player given_choice = False sentence = "" name = player_info[current_player]["name"] grid = player_info[current_player]["grid_pos"] grid_name = grid_info[grid]["name"] if grid_info[grid]["purchaseable"]: if grid_info[grid]["belongs_to"] == NOBODY and player_info[current_player]["money"] - grid_info[grid]["initial_cost"] >= 0: given_choice = True while True: print() print("[1] Yes") print("[2] No") choice = input("> ") if choice == "1": sentence = purchase_city(player_info, grid_info) break elif choice == "2": break else: print("Invalid option.") elif grid_info[grid]["belongs_to"] == current_player and player_info[current_player]["money"] - grid_info[grid]["upgrade_cost"] >= 0 and grid_info[grid]["communities"] < MAX_COMMUNITIES_ALLOWED: given_choice = True while True: print() print("[1] Yes") print("[2] No") choice = input("> ") if choice == "1": sentence = add_community(player_info, grid_info) break elif choice == "2": break else: print("Invalid option.") elif grid_name == "Chance Card": given_choice = True sentence = get_chance_card(player_info, grid_info) advance_to_next_player(player_info) return [given_choice, sentence] def advance_to_next_player(player_info: List[Any]) -> None: """Sets the current player to the next active player. Skipping the backrupt or in jail players. Args: player_info: Information about each player. Done by: Ethan Lam """ global current_player while True: # Goes to the next player, skipping those bankrupt or in jail current_player += 1 if current_player >= len(player_info): current_player -= len(player_info) if player_info[current_player]["jail_sentence"] > 0: player_info[current_player]["jail_sentence"] -= 1 if player_info[current_player]["bankrupt"] is False and player_info[current_player]["jail_sentence"] == 0: return def purchase_city(player_info: List[Any], grid_info: List[Any]) -> str: """The current player can purchase the city if the trivia question is successfully answered. Args: player_info: Information about each player. grid_info: Information about each grid. Returns: A sentence to be printed later about the result of the city purchase. Done by: Ethan Lam """ name = player_info[current_player]["name"] grid = player_info[current_player]["grid_pos"] grid_name = grid_info[grid]["name"] print("To purchase this city, you must first answer the following question correctly.") correct = ask_trivia(TRIVIA_QUESTIONS) if correct is False: return "Incorrect! - You do not get to buy this city." player_info[current_player]["money"] -= grid_info[grid]["initial_cost"] grid_info[grid]["belongs_to"] = current_player return f"{name} has successfully purchased {grid_name}!" def add_community(player_info: List[Any], grid_info: List[Any]) -> str: """Adds a community to the city if the trivia question is successfully answered. Args: player_info: Information about each player. grid_info: Information about each grid. Returns: A sentence to be printed later about the result of the community purchase. Done by: Ethan Lam """ name = player_info[current_player]["name"] grid = player_info[current_player]["grid_pos"] grid_name = grid_info[grid]["name"] print("To purchase a community, you must first answer the following question correctly.") correct = ask_trivia(TRIVIA_QUESTIONS) if correct is False: return "Incorrect! - You do not get to buy a community." player_info[current_player]["money"] -= grid_info[grid]["upgrade_cost"] grid_info[grid]["communities"] += 1 return f"{name} has added a community to {grid_name}!" def clear_screen() -> None: """Clears the entire screen. Done by: Ethan Lam """ print("\n" * 100) def set_current_player_to_previous_player(player_info: List[Any]) -> None: """Sets the current player to the previously active player. Args: player_info: Information about each player. Done by: Ethan Lam """ global current_player while True: current_player -= 1 if current_player < 0: current_player = len(player_info) - 1 if player_info[current_player]["bankrupt"] is False and player_info[current_player]["jail_sentence"] == 0: return def roll_dice(player_information: List[Any]) -> None: """Changes the grid position of the player based on their dice roll. Args: player_information: Information about each player. Done by: Ethan Lam """ global current_player global passed_go global extra_roll word = "now" if extra_roll: # Checks if the previous player landed on the extra roll grid. extra_roll = False set_current_player_to_previous_player(player_information) word = "still" print() print(f"It is {word} " + player_information[current_player]["visual"] + " " + player_information[current_player]["name"] + "'s turn.") print("You can choose to roll 1, 2, or 3 dice.") print("For every additional dice after 1, it costs $50 more.") while True: while True: try: number_of_rolls = int(input("Please enter the number of dice you want to roll: ")) if number_of_rolls < 1 or number_of_rolls > 3: raise ValueError break except ValueError: print("Invalid choice - you must roll at least 1 dice, maximum of 3.") print() if player_information[current_player]["money"] - 50 * (number_of_rolls - 1) >= 0: player_information[current_player]["money"] -= 50 * (number_of_rolls - 1) break else: print("Not enough money!") print() roll = 0 i = 0 while i < number_of_rolls: number = random.randint(1, 6) roll += number i += 1 if debug_code: roll = int(input("Type in the number you want rolled: ")) player_information[current_player]["previous_roll"] = player_information[current_player]["roll"] player_information[current_player]["roll"] = roll player_information[current_player]["grid_pos"] += roll if player_information[current_player]["grid_pos"] >= 36: player_information[current_player]["grid_pos"] -= 36 player_information[current_player]["money"] += 200 passed_go = True def set_up_game() -> List[Any]: """The initial set-up with features determined by the user. Returns: The player and game set-up. Done by: Ethan Lam """ number_of_players = 0 players = [] print() print("Enter 'b' to go back to the menu.") while True: choice = input("Please enter the number of players (2 to 4): ") if choice == "b": print() return try: number_of_players = int(choice) if number_of_players > 4 or number_of_players < 2: raise ValueError break except ValueError: print("Invalid option!") print() print() print("Please enter the amount of money each player starts with (recommended: 500)") starting_money = get_positive_integer_max_5000("> ") colour_list = ["blue", "green", "orange", "red"] used_names = [] i = 0 while i < number_of_players: print() player_name = "" while True: player_name = input(f"Please enter player {i + 1}'s name: ") if player_name in used_names: print("Name already used - please choose another name.") print() elif len(player_name) < 11: used_names.append(player_name) break else: print("MAX 10 characters.") print() print() while True: print(f"Which colour will {player_name} be using?") j = 0 while j < len(colour_list): print(f"[{j + 1}] {colour_list[j]}") j += 1 try: choice = int(input("> ")) if choice > len(colour_list) or choice < 1: raise ValueError break except ValueError: print("Invalid option.") print() player_colour = colour_list[choice - 1] colour_list.remove(player_colour) print() while True: print(f"Which gamepiece will {player_name} be using?") print("This must be a single character.") choice = input("> ") if len(choice) == 1: break else: print("Invalid choice - please enter just 1 character.") print() player_gamepiece = choice player_final = add_background(player_gamepiece, player_colour) # Associates each player with a special character to help with # displaying the character on the board. if i == 0: special_character = chr(0) elif i == 1: special_character = chr(1) elif i == 2: special_character = chr(2) else: special_character = chr(3) player = { "money": starting_money, "roll": None, "grid_pos": 0, "name": player_name, "colour": player_colour, "gamepiece": player_gamepiece, "visual": player_final, "char_representation": special_character, "bankrupt": False, "previous_roll": None, "jail_sentence": 0 } players.append(player) i += 1 print_player_settings(players) return players def print_player_settings(player_info: List[Any]) -> None: """Prints the settings set by the user. Args: player_info: A list of the players' settings. Done by: Ethan Lam """ spacing = 0 if len(player_info) == 2: spacing = " " * 7 elif len(player_info) == 3: spacing = " " * 17 else: spacing = " " * 29 title = add_colour(spacing + "PLAYER SETTINGS", "none", True) print() print(title) # Prints the player settings subtitles = "" names = "" player_colours = "" player_gamepieces = "" visuals_on_board = "" i = 0 while i < len(player_info): subtitle = add_colour(f"Player {i + 1}", "none", True) subtitles += subtitle + " " * 13 names += "Name: " + player_info[i]["name"] + " " * (15 - len(player_info[i]["name"])) player_colours += "Colour: " + player_info[i]["colour"] + " " * (13 - len(player_info[i]["colour"])) player_gamepieces += "Gamepiece: " + player_info[i]["gamepiece"] + " " * 9 visuals_on_board += "Visuals: " + player_info[i]["visual"] + " " * 11 i += 1 print(subtitles.strip(" ")) print(names.strip(" ")) print(player_colours.strip(" ")) print(player_gamepieces.strip(" ")) print(visuals_on_board.strip(" ")) print() def display_board(new_player_info: List[Any], grid_info: List[Any], center_of_board_display: int) -> None: """Displays the updated board. Args: new_player_info: Updated information about the players and the game. grid_info: Information about each grid. center_of_board_display: What to display in the center of the board (player's dice roll results / next player to roll) Done by: Ethan Lam """ global current_player global starting_game global game_over global passed_go global extra_roll name = new_player_info[current_player]["name"] roll = new_player_info[current_player]["roll"] current_visuals = new_player_info[current_player]["char_representation"] if starting_game: roll_str = center_board_text(f"{current_visuals} To begin, {name} must first roll.") # elif new_player_info[current_player]["jail_sentence"] > 0: # roll_str = center_board_text("") elif center_of_board_display == DISPLAY_WHO_ROLLS_NEXT: roll_str = center_board_text(f"{current_visuals} Now, {name} must roll.") else: roll_str = center_board_text(f"{current_visuals} {name} rolled a {roll}.") add_200 = center_board_text("") if passed_go and center_of_board_display == DISPLAY_PLAYER_ROLL_RESULTS: add_200 = center_board_text(f"{name} passed GO! You got $200!") passed_go = False grid = new_player_info[current_player]["grid_pos"] grid_name = grid_info[grid]["name"] belongs_to = grid_info[grid]["belongs_to"] worth = grid_info[grid]["worth"] starting_cost = grid_info[grid]["initial_cost"] upgrade_cost = grid_info[grid]["upgrade_cost"] number_of_communities = grid_info[grid]["communities"] landed_on = center_board_text("") question = center_board_text("") cost = int(grid_info[grid]["worth"] * (1 + number_of_communities * 3)) cost_amount = center_board_text("") bankrupt_text = center_board_text("") winner_text = center_board_text("") bankrupt = chr(157) + 7 * " " winner = chr(156) + 5 * " " if center_of_board_display == DISPLAY_PLAYER_ROLL_RESULTS: if grid_name == "Chance Card": landed_on = center_board_text(f"You landed on a {grid_name}.") elif grid_name == "pay $20" or grid_name == "pay $50": landed_on = center_board_text("You landed on a reserved area.") question = center_board_text(f"You must {grid_name} to the government.") amount = int(grid_name[-2:]) new_player_info[current_player]["money"] -= amount elif grid_name == "$25" or grid_name == "$50" or grid_name == "$75": landed_on = center_board_text(f"You get {grid_name}!") question = center_board_text(f"The government gives you {grid_name}.") amount = int(grid_name[-2:]) new_player_info[current_player]["money"] += amount elif grid_name == "an extra roll": landed_on = center_board_text(f"You get {grid_name}!") question = center_board_text("You may roll again.") extra_roll = True elif grid_name == "JAIL": landed_on = center_board_text(f"GO TO {grid_name}!") new_player_info[current_player]["jail_sentence"] = DAYS_IN_JAIL new_player_info[current_player]["grid_pos"] -= 18 elif grid_name == "Cell": if new_player_info[current_player]["jail_sentence"] == 0: landed_on = center_board_text(f"You are visiting the {grid_name}.") else: landed_on = center_board_text("YOU ARE IN JAIL") elif grid_name == "Free Parking" or grid_name == "GO": landed_on = center_board_text(f"You landed on {grid_name}.") else: # Landing on a purchaseable grid. landed_on = center_board_text(f"You landed on {grid_name}.") if belongs_to == NOBODY: if new_player_info[current_player]["money"] >= starting_cost: question = center_board_text("Do you want to buy this city?") cost_amount = center_board_text(f"This costs ${starting_cost}") else: question = center_board_text("You cannot afford this city.") elif belongs_to == current_player: if new_player_info[current_player]["money"] >= upgrade_cost and number_of_communities < MAX_COMMUNITIES_ALLOWED: question = center_board_text("Do you want to build a community?") cost_amount = center_board_text(f"This costs ${upgrade_cost}") elif number_of_communities == MAX_COMMUNITIES_ALLOWED: question = center_board_text("You have bought all the available") cost_amount = center_board_text("communities for this city.") else: question = center_board_text("You cannot afford a community.") else: # Already purchased by someone else owner = new_player_info[belongs_to]["name"] question = center_board_text(f"You paid {owner} ${cost}") new_player_info[current_player]["money"] -= cost new_player_info[belongs_to]["money"] += cost if new_player_info[current_player]["money"] < 0: # and new_player_info[current_player]["bankrupt"] == False bankrupt_text = center_board_text(f"{name} has gone {bankrupt}") new_player_info[current_player]["bankrupt"] = True remove_bankrupt_player_grids(grid_info, current_player) j = 0 players_remaining = 0 winner_name = "" while j < len(new_player_info): if new_player_info[j]["bankrupt"] is False: winner_name = new_player_info[j]["name"] players_remaining += 1 j += 1 if players_remaining == 1: winner_text = center_board_text(f"{winner_name} is the {winner}") game_over = True players_money = create_players_money_text(new_player_info) board = f""" GO NP NP CC NP NP CC NP NP CL --------------------------------------------------- | | | | | | | | | | | --------------------------------------------------- NP | | | | NP ------{roll_str}------ PM | |{add_200}| | NP ------{landed_on}------ NP | |{question}| | NP ------{cost_amount}------ ER | | | | CC ------{bankrupt_text}------ NP | |{winner_text}| | PM ------ ------ 75 | |{players_money[0]}| | NP ------{players_money[1]}------ NP | |{players_money[2]}| | 25 ------{players_money[3]}------ NP | | | | NP --------------------------------------------------- | | | | | | | | | | | --------------------------------------------------- JL NP NP NP CC NP NP NP 50 FP""" # Marking cities on the board to indicate that it is already owned by a player. i = 0 while i < len(grid_info): if grid_info[i]["belongs_to"] != NOBODY: board = board[:grid_info[i]["placement"]] + grid_info[i]["special_char"] * 2 + board[grid_info[i]["placement"] + 2:] i += 1 # Inserts players into the correct locations on the board. player_placements = grid_to_string_pos(new_player_info) i = 0 while i < len(player_placements): board = board[:player_placements[i]] + new_player_info[i]["char_representation"] + board[player_placements[i] + 1:] i += 1 # Makes the bankrupt player invisible for future board displays. if new_player_info[current_player]["bankrupt"]: new_player_info[current_player]["char_representation"] = " " board = finalize_board(grid_info, new_player_info, board) starting_game = False print() print(board) def finalize_board(grid_info: List[Any], player_info: List[Any], board: str) -> str: """Finalizes the board display. - Replaces players special characters with visible player pieces. - Replaces grids special characters with a string indicating the number of communities and the owner. - Replaces special fields with special character highlights (bankruptcy/winner text). Args: grid_info: Information about each grid. player_info: Information about each player. board: The board string being modified. Returns: The complete board string ready for display. Done by: Ethan Lam """ bankrupt = add_colour("BANKRUPT", "red", True) winner = add_colour("WINNER", "green", True) change = True while change is True: change = False i = 0 while i < len(board): if board[i] == chr(0): board = board[:i] + player_info[0]["visual"] + board[i + 1:] change = True break elif board[i] == chr(1): board = board[:i] + player_info[1]["visual"] + board[i + 1:] change = True break elif board[i] == chr(2): board = board[:i] + player_info[2]["visual"] + board[i + 1:] change = True break elif board[i] == chr(3): board = board[:i] + player_info[3]["visual"] + board[i + 1:] change = True break elif board[i] == chr(157): board = board[:i] + bankrupt + board[i + 8:] change = True elif board[i] == chr(156): board = board[:i] + winner + board[i + 6:] change = True j = 0 while j < len(grid_info): if board[i] == grid_info[j]["special_char"]: colour = player_info[grid_info[j]["belongs_to"]]["colour"] number = str(grid_info[j]["communities"]) string = add_background(f"{number}C", colour) board = board[:i] + string + board[i + 2:] change = True break j += 1 i += 1 return board def create_players_money_text(player_info: List[Any]) -> List[str]: """Builds the strings in the board related to each player's money. Args: player_info: Information about each player. Returns: [players_money[0], players_money[1], players_money[2], players_money[3]] Done by: Ethan Lam """ player_money_text = [] for i in range(4): player_money_text.append(center_board_text("")) i = 0 while i < len(player_info): # Creates strings for each player's money to display later temp_name = player_info[i]["name"] temp_money = player_info[i]["money"] temp_visuals = player_info[i]["char_representation"] if player_info[i]["bankrupt"] is False: player_money_text[i] = (center_board_text(f"{temp_visuals} {temp_name}'s money: ${temp_money}")) else: player_money_text[i] = (center_board_text(f"{temp_visuals} {temp_name}: BANKRUPT")) i += 1 return player_money_text def remove_bankrupt_player_grids(grid_info: List[Any], bankrupt_player: int) -> None: """Removes ownership of the cities related to the bankrupt player. This allows other players to purchase the cities now. Args: grid_info: Information about each grid. bankrupt_player: The player who went bankrupt. Done by: Ethan Lam """ i = 0 while i < len(grid_info): if grid_info[i]["belongs_to"] == bankrupt_player: grid_info[i]["belongs_to"] = NOBODY grid_info[i]["communities"] = 0 i += 1 def grid_to_string_pos(player_info: List[Any]) -> List[int]: """Converts the player's grid position to a string position on the board. Args: player_info: Information necessary to determine the positions of the players. Returns: Numbers indicating where to slice the string on the board to place each player. Done by: Ethan Lam """ new_list = [] i = 0 while i < len(player_info): if player_info[i]["grid_pos"] < 10: new_list.append(112 + player_info[i]["grid_pos"] * 5 + i) elif player_info[i]["grid_pos"] < 19: new_list.append(154 + (player_info[i]["grid_pos"] - 9) * 113 + i) elif player_info[i]["grid_pos"] < 28: new_list.append(1171 - (player_info[i]["grid_pos"] - 18) * 5 + i) elif player_info[i]["grid_pos"] < 36: new_list.append(1126 - (player_info[i]["grid_pos"] - 27) * 113 + i) i += 1 return new_list def center_board_text(text: str) -> str: """Centers a string between the two edges of the board. Args: text: The string being centered. Returns: The centered string with the appropriate number of spaces in front. Done by: Ethan Lam """ new_string = "" width = 39 - len(text) i = 0 while i < width // 2: new_string += " " i += 1 new_string += text + new_string if len(text) % 2 == 0: new_string += " " return new_string def get_positive_integer_max_5000(user_prompt: str) -> int: """Gets a positive integer between 0 and 5000 (inclusive). Args: user_prompt: The prompt used to get the user to input the integer. Returns: A positive integer between 0 and 5000. Done by: Ethan Lam """ while True: try: positive_integer = int(input(user_prompt)) if positive_integer < 0 or positive_integer > 5000: raise ValueError return positive_integer except ValueError: print("INVALID INPUT - enter a positive integer between 0 and 5000.") print() def print_rules() -> None: """Prints out the rules of the game Done by: Ethan Lam """ title = add_colour(" MONOPOLY WITH A TWIST ", "red", True) print() print(title) print("---------------------------------------------------") print("Number of players: 2 - 4") print() print("Legend:") print("GO -> Collect $200") print("NP -> City not yet purchased") print("CC -> Random chance card") print("FP -> Free Parking") print("PM -> Pay money to government") print("25 -> Recieve $25") print("50 -> Recieve $50") print("75 -> Recieve $75") print("JL -> GO TO JAIL") print("CL -> Jail cell") print("ER -> Extra roll") print() print("Gameplay: Similar to Monopoly.") print("""Monopoly With A Twist is a virtual yet visual board game similar to Monopoly where players try to obtain as many properties as possible. However, instead of claiming properties, the objective is to claim and build as many cities as possible all the while trying not to go bankrupt from having to pay too much tax to other players. Many features, including colours, gamepieces, and names are customizable. The challenge with this game is that there are puzzles and problems to solve before the player is allowed to purchase cities. Other additions such as a wide variety of luck cards and the ability to choose how many dice you want to roll all make this game very unique.""") print() def add_colour(text: str, colour: str, bold: bool) -> str: """Adds colour and bold to a specified text. Args: text: The text being modified. colour: The colour it is being changed to. bold: Whether the text is bolded or not. Returns: The original string with added colour and modifications. Done by: Ethan Lam """ colours = ["red", "green", "orange", "blue", "none", "cyan"] code_bold = "" default = "\033[0;0;0m" if bold: code_bold = "1" else: code_bold = "0" respective_codes = [f"\033[{code_bold};31;1m", f"\033[{code_bold};32;1m", f"\033[{code_bold};33;1m", f"\033[{code_bold};34;1m", f"\033[{code_bold};0;1m", f"\033[{code_bold};36;1m"] i = 0 while i < len(colours): if colour == colours[i]: break i += 1 return respective_codes[i] + text + default def add_background(text: str, colour: str) -> str: """Adds a background to a specified text. Args: text: The text being modified. colour: The colour the background is being changed to. Returns: The original string with added background colour. Done by: Ethan Lam """ colours = ["red", "green", "orange", "blue"] default = "\033[0;0;0m" respective_codes = ["\033[0;37;41m", "\033[0;30;42m", "\033[0;37;43m", "\033[0;37;44m"] i = 0 while i < len(colours): if colour == colours[i]: break i += 1 return respective_codes[i] + text + default def get_chance_card(player_info: List[Any], grid_info: List[Any]) -> str: """Randomly chooses a chance card for the current player. Args: player_info: Information about each player. grid_info: Information about each grid. Returns: A sentence to be printed with the next board display. Done by: Ethan Lam """ sentence = "" while True: random_choice = random.randint(1, 7) if random_choice == 1: if player_info[current_player]["previous_roll"] is not None: sentence = guess_previous_roll(player_info) break elif random_choice == 2: if player_info[current_player]["money"] >= 10: sentence = bet_trivia(player_info) break elif random_choice == 3: sentence = grant_50_dollars(player_info) break elif random_choice == 4: sentence = sorting_minigame(player_info) break elif random_choice == 5: sentence = password_minigame(player_info) break elif random_choice == 6: sentence = donate_money(player_info) break elif random_choice == 7: sentence = pay_city_taxes(player_info, grid_info) break return sentence def pay_city_taxes(player_info: List[Any], grid_info: List[Any]) -> str: """Takes money from the user based on the number of cities they own. Args: player_info: Information about each player. grid_info: Information about each grid. Returns: A sentence to be printed in the next board display. Done by: Ethan Lam """ number_of_cities_owned = 0 i = 0 while i < len(grid_info): if grid_info[i]["belongs_to"] == current_player: number_of_cities_owned += 1 i += 1 name = player_info[current_player]["name"] percentage = number_of_cities_owned * 0.02 player_info[current_player]["money"] = int(player_info[current_player]["money"] * (1 - percentage)) return f"{name}, You paid 2% taxes for every city you own." def donate_money(player_info: List[Any]) -> str: """Makes the user donate money. Args: player_info: Information about each player. Returns: A sentence to be printed in the next board display. Done by: Ethan Lam """ player_info[current_player]["money"] = int(player_info[current_player]["money"] * 0.95) name = player_info[current_player]["name"] return f"{name}, You donated 5% of your money to World Health Organization!" def password_minigame(player_info: List[Any]) -> str: """Prompts the user to decode a password; negative consequences otherwise. Args: player_info: Information about each player. Returns: A sentence to be printed in the next board display. Done by: Ethan Lam """ random_number = random.randint(0, 999999) decoded_number = password_decoder(random_number) print() print("You must decode a password immediately or you will lose 20% of your money.") print("You are given the following decoding table:") print("0 = a, 1 = b, 2 = c,... 9 = j") print(f"Your number is {random_number}") name = player_info[current_player]["name"] answer = input("> ") if answer == decoded_number: return f"{name}, good work! You have successfully decoded the password!" else: money_lost = int(player_info[current_player]["money"] * 0.2) player_info[current_player]["money"] -= money_lost return f"{name}, INCORRECT! You have lost ${money_lost}." def password_decoder(integer: int) -> str: """Converts numbers into an alpha-password. Args: integer: Any integer. Returns: The password. Done by: Ethan Lam """ new_string = "" integer_string = str(integer) decoding_table_strings = "a b c d e f g h i j".split(" ") i = 0 while i < len(integer_string): reference = int(integer_string[i]) new_string += decoding_table_strings[reference] i += 1 return new_string def bet_trivia(player_info: List[Any]) -> str: """Asks the user how much they want to bet on getting a trivia question correct. If the user is correct, they will double their bet amount. If not, they lose it. Args: player_info: Information about each player. Returns: A sentence to be printed in the next board display. Done by: Ethan Lam """ print() print("Chance Card: How much are you willing to bet that you will get") print("this next trivia questions correct? (Minimum $10)") print("If you get the question correct, you will double your bet amount.") print("If not, you will lose the amount you bet.") while True: while True: try: bet_amount = int(input("> ")) if bet_amount < 10: raise ValueError break except ValueError: print("Please enter greater than $10 (to the nearest dollar).") print() if player_info[current_player]["money"] - bet_amount >= 0: player_info[current_player]["money"] -= bet_amount break else: print("NOT ENOUGH MONEY!") print("Enter another amount.") print() correct = ask_trivia(TRIVIA_QUESTIONS) name = player_info[current_player]["name"] if correct: player_info[current_player]["money"] += bet_amount * 2 return f"{name}, YOU ARE CORRECT! YOU DOUBLED YOUR MONEY! Congratulations." else: return f"{name} YOU ARE INCORRECT! You have unfortunately lost your bet." def guess_previous_roll(player_info: List[Any]) -> str: """Prompts the player to guess their previous roll. If successful, they will recieve $100. Args: player_info: Information about each player. Returns: A sentence to be printed in the next board display. Done by: Ethan Lam """ print() print("Chance Card: If you are able to remember your previous roll,") print("you will get $100!") while True: try: guess = int(input("> ")) if guess < 1 or guess > 18: raise ValueError break except ValueError: print("The dice roll was between 1 and 18.") print() name = player_info[current_player]["name"] if guess == player_info[current_player]["previous_roll"]: player_info[current_player]["money"] += 100 return f"{name}, GOOD JOB! You are correct. You are rewarded with $100!" else: return f"{name}, YOUR ANSWER WAS INCORRECT! Better luck next time!" def sorting_minigame(player_info: List[Any]) -> str: """Generates a random number with a random number of digits. Random number is displayed to the user and the user is prompted to sort it numerically. If successful, user gets $100. Args: player_info: Information about each player. Returns: A sentence to be printed in the next board display. Done by: Ethan Lam """ digits = random.randint(10, 20) number_string = str(random.randint(10 ** digits, 10 ** (digits + 1) - 1)) sorted_string = sort_numerical_string(number_string) money = digits * 10 print() print(f"In order to get ${money}, you must sort the following number in numerical order.") print(f"Your number is {number_string}") answer = input("> ") name = player_info[current_player]["name"] if answer == sorted_string: player_info[current_player]["money"] += money return f"{name}, CONGRATULATIONS! That is correct. You get ${money}." else: return f"{name}, INCORRECT! Unfortunately, you do not get ${money}." def sort_numerical_string(string: str) -> str: """Sorts the numerical string into numerical order. Args: string: The string being sorted. Returns: The sorted string. Done by: Ethan Lam """ new_string = "" numerical_list = [] i = 0 while i < len(string): numerical_list.append(int(string[i])) i += 1 numerical_list.sort() i = 0 while i < len(numerical_list): new_string += str(numerical_list[i]) i += 1 return new_string def grant_50_dollars(player_info: List[Any]) -> str: """Gives the current player 50 dollars. Args: player_info: The player's information to be updated. Returns: A sentence to be printed in the next board display. Done by: Ethan Lam """ player_info[current_player]["money"] += 50 name = player_info[current_player]["name"] return f"{name}, You were rewarded with $50!" if __name__ == "__main__": main()
cad246a06e60ea9b350591cdefa09404f7c77709
wzbbbb/LeetCode-OJ
/Unique_PathsII.py
377
3.53125
4
m, n = 4, 3 A = [ [0,0,0], [0,1,0], [0,0,0], [0,0,0] ] def uniq_path(A, m,n, i=0, j=0, count=0): if i == m-1 and j == n-1: count += 1 else: if i< m -1: if A[i+1][j] != 1: count = uniq_path(A, m,n, i+1, j, count) if j < n-1: if A[i][j+1] != 1: count = uniq_path(A, m,n, i, j+1, count) return count print uniq_path(A, m,n)
8be2c48e788b95d5b6d42e8234440bc4860b6150
Shreyas77778/Projects
/Hotel Management (GI)/databasesample2.py
2,716
3.71875
4
from tkinter import * import sqlite3 from PIL import ImageTk,Image root=Tk() root.title('Database Sample') root.iconbitmap('icon.ico') root.geometry('400x400') #create a database or connect con=sqlite3.connect('address_book.db') #create cursor c=con.cursor() #create submit function def submit(): # Create a database or connect to one conn = sqlite3.connect('Hotel_mgmt.db') # Create cursor c = conn.cursor() # Insert Into Table c.execute("INSERT INTO stock VALUES (:double_bed_sheets, :single_bed_sheets, :double_duet_cover, :big_pillow, :small_pillow, :cushion_cover,:bed_runner,:towel,:bath_towel)", { 'double_bed_sheets':41, 'single_bed_sheets':13, 'double_duet_cover':44, 'big_pillow':66, 'small_pillow':42, 'cushion_cover':38, 'bed_runner':31, 'towel':35, 'bath_towel':48 }) #Commit Changes conn.commit() # Close Connection conn.close() # Clear The Text Boxes fname.delete(0, END) lname.delete(0, END) address.delete(0, END) city.delete(0, END) state.delete(0, END) zipcode.delete(0, END) #create query function def query(): con=sqlite3.connect('hotel_mgmt.db') #create cursor c=con.cursor() #query the Database c.execute("select *,oid from stock ") res=c.fetchall() print(res) print_records='' for record in res: print_records+=str(record)+'\n' query_label=Label(root,text=print_records) query_label.grid(row=8,column=0) #commit con.commit() #close connection con.close() #create text boxes fname=Entry(root, width=30) fname.grid(row=0,column=1) lname=Entry(root, width=30) lname.grid(row=1,column=1) address=Entry(root, width=30) address.grid(row=2,column=1) city=Entry(root, width=30) city.grid(row=3,column=1) state=Entry(root, width=30) state.grid(row=4,column=1) zipcode=Entry(root, width=30) zipcode.grid(row=5,column=1) #create box labels fname_label=Label(root, text='First Name') fname_label.grid(row=0,column=0) lname_label=Label(root,text='last Name') lname_label.grid(row=1,column=0) address_label=Label(root, text='address') address_label.grid(row=2,column=0) city_label=Label(root,text='city') city_label.grid(row=3,column=0) state_label=Label(root,text='state') state_label.grid(row=4,column=0) zipcode_label=Label(root,text='zipCode') zipcode_label.grid(row=5,column=0) #create submit Button btn=Button(root, text='add to db',command=submit) btn.grid(row=6,column=1,padx=10,pady=10,ipadx=100) #create a query Button q_btn=Button(root,text='show records', command=query) q_btn.grid(row=7,column=0,columnspan=2,padx=10,pady=10,ipadx=137) mainloop()
4b2f5257efe91a448aa497f4b667ef2e7eb92092
Team-Agility/text_summerization
/baseline/utils.py
1,096
3.59375
4
import codecs import re def strip_stopwords(tokenized_sentence, stopwords): """ Strip stopwords Consecutive stopwords at head and tail of tagged utterance are stripped """ ib = 0 ie = 0 for i in range(len(tokenized_sentence)): if tokenized_sentence[i].lower() in stopwords: ib += 1 else: break for j in range(1, len(tokenized_sentence) + 1): if tokenized_sentence[-j].lower() in stopwords: ie += 1 else: break return tokenized_sentence[ib:len(tokenized_sentence) - ie] def load_stopwords(path): """ This function loads a stopword list from the *path* file and returns a set of words. Lines begining by '#' are ignored. """ # Set of stopwords stopwords = set([]) # For each line in the file for line in codecs.open(path, 'r', 'utf-8'): if not re.search('^#', line) and len(line.strip()) > 0: stopwords.add(line.strip().lower()) # Return the set of stopwords return stopwords
e77074f62cbb0b3a21b93627dae97b1a889097ae
alierdogan7/Titanic
/titanic_logisticreg.py
3,835
3.625
4
import math import matplotlib.pyplot as plt import numpy as np def gradient_descent(alpha, x, y, ep=0.0001, max_iter=10000): converged = False iter = 0 m = x.shape[0] # number of samples # initial theta t0 = np.random.random(x.shape[1]) t1 = np.random.random(x.shape[1]) # total error, J(theta) J = sum([(t0 + t1*x[i] - y[i])**2 for i in range(m)]) # Iterate Loop while not converged: # for each training sample, compute the gradient (d/d_theta j(theta)) grad0 = 1.0/m * sum([(t0 + t1*x[i] - y[i]) for i in range(m)]) grad1 = 1.0/m * sum([(t0 + t1*x[i] - y[i])*x[i] for i in range(m)]) # update the theta_temp temp0 = t0 - alpha * grad0 temp1 = t1 - alpha * grad1 # update theta t0 = temp0 t1 = temp1 # mean squared error e = sum( [ (t0 + t1*x[i] - y[i])**2 for i in range(m)] ) if abs(J-e) <= ep: print 'Converged, iterations: ', iter, '!!!' converged = True J = e # update error iter += 1 # update iter if iter == max_iter: print 'Max interactions exceeded!' converged = True return t0,t1 def read_csv(filename): dataset = [] splitted_data = {'training': [], 'validation': [], 'test':[]} with open(filename) as csvfile: read_array = lambda line: line.strip('\r\n').split(',') attributes = read_array(csvfile.readline()) for row in csvfile: dataset.append({attr: float(value) if attr == 'Age' else int(value) for attr, value in zip(attributes, read_array(row))}) normalize_features(dataset) splitted_data['training'] = dataset[:401] splitted_data['validation'] = dataset[401:701] splitted_data['test'] = dataset[701:] return splitted_data def normalize_features(dataset): age_set = [data['Age'] for data in dataset] min_age, max_age = min(age_set), max(age_set) for index in range(len(dataset)): dataset[index]['Age'] = (dataset[index]['Age'] - min_age) / (max_age - min_age) # def sigmoid(z): # return 1 / (1 + math.exp(-z)) # assumıng that m = number of traınıng data, lınes ın the tıtanıc dataset. # ıts gonna be m by 3, plus m by 1 bıas term # ın terms of matrıx multıplıacatıon # x0 + X*W = Y # h_theta(y). # W ıs a 3 by 1 vector # yıeldıng m by 1 output predıctıon. def h_theta(**kwargs): sum = kwargs['theta0'] for theta, x in zip(kwargs['theta_set'], kwargs['param_set']): sum += theta * x return sum # def cost_function(theta_set, data_set): # m = len(data_set) # sum = 0 # for example in data_set: # y_i = example['Survived'] # param_set = [ example['Age'], example['Pclass'], example['Sex']] # h_theta = hypothesis(theta_set=theta_set, param_set=param_set) # # sum += ( (-y_i * math.log10(h_theta)) - ((1 - y_i) * math.log10(1 - h_theta)) ) # # return sum / m # # # ''' # theta_j_param_name: derivative of J(theta) is going to be taken according to that parameter # theta_set: current theta values # dataset: example rows # ''' # def gradient_function(theta_j_param_name, theta_set, data_set): # m = len(data_set) # sum = 0 # for example in data_set: # y_i = example['Survived'] # param_set = [ example['Age'], example['Pclass'], example['Sex']] # h_theta = hypothesis(theta_set=theta_set, param_set=param_set) #calculate h_theta of x # # sum += ( h_theta - y_i) * example[theta_j_param_name] # # return sum / m # # # def converge(): # theta_set = def test(): # x = np.arange(-20, 20, 0.1) # y = list(map(sigmoid, x)) # plt.plot(x, y) # plt.show() normalized_data = read_csv('titanicdata.csv') test()
b77fe8f1c5dd8c82cd5a1d56177c40653e35ee7a
cathuan/LeetCode-Questions
/python/q97.py
1,195
3.625
4
class Solution(object): def isInterleave(self, s1, s2, s3): """ :type s1: str :type s2: str :type s3: str :rtype: bool """ if len(s1) + len(s2) != len(s3): return False n, m = len(s1), len(s2) r = [] for _ in range(m+1): v = [] for _ in range(n+1): v.append(False) r.append(v) for i in range(m+1): for j in range(n+1): if j == 0: if i == 0: r[i][j] = True else: r[i][j] = (s2[:i] == s3[:i]) elif i == 0: r[i][j] = (s1[:j] == s3[:j]) else: if r[i-1][j] and s2[i-1] == s3[i+j-1]: r[i][j] = True elif r[i][j-1] and s1[j-1] == s3[i+j-1]: r[i][j] = True else: r[i][j] = False return r[m][n] if __name__ == "__main__": s1 = 'aabcc' s2 = 'dbbca' s3 = 'aadbbbaccc' print Solution().isInterleave(s1, s2, s3)
9e612e97572491ee117250d514fc4642c4a25580
Ismeetdhall/Python
/17BEC1039resturant.py
243
3.78125
4
bill= int(input("ENTER Your Restaurant Bill : ")) print ("Your Original Bill :\t",bill) print ("Your 20% Discounted Bill :\t",bill-(bill*20/100)) print ("Your 25% Discounted Bill :\t",bill-(bill*25/100)) input("\nPRESS ENTER KEY TO EXIT:)\n")
d10666cc339422c4ffc1ab0efd04d0cd7e9f37e0
widelec9/codewars
/kata/python/3kyu/binomial_expansion.py
744
3.578125
4
import re from math import factorial def expand(expr): tokens = re.search(r'^\((\-?\d*([a-z]))([\+\-]\d*)\)\^(\d*)$', expr) a = int(tokens.group(1)[:-1]) if tokens.group(1)[:-1] not in ['', '-'] else int(tokens.group(1)[:-1] + '1') varname = tokens.group(2) b = int(tokens.group(3).strip('+')) n = int(tokens.group(4)) if n == 0: return '1' else: coeffs = [str(int(factorial(n) / (factorial(n-i) * factorial(i)) * a**(n-i) * b**i)) for i in range(n+1)] out = '+'.join([val + varname + '^' + str(len(coeffs)-1-i) for i, val in enumerate(coeffs)]).replace('+-', '-').replace('^1', '') out = re.sub(r'^(.*)[a-z]\^0', r'\1', re.sub(r'^([\+\-])?1([a-z].*)', r'\1\2', out)) return out
c19655e3d76daded67c6e09208e67a38f96fc348
Gr1dlock/ComputationalAlgorithms
/LR5/input_data.py
969
3.59375
4
import re class Data: def __init__(self, t0, tw, m): self.t0 = t0 self.tw = tw self.m = m def check_float(text): match = re.fullmatch(r'[-+]?(?:\d+(?:\.\d*)?|\.\d+)', text) return bool(match) def check_int(text): match = re.fullmatch(r'[-+]?\d+', text) return bool(match) def get_data(): while True: t0 = input('\nВведите To:') if check_float(t0): t0 = float(t0) break else: print('\nНекорректный ввод') while True: tw = input('\nВведите Tw:') if check_float(tw): tw = float(tw) break else: print('\nНекорректный ввод') while True: m = input('\nВведите m:') if check_int(m): m = int(m) break else: print('\nНекорректный ввод') return Data(t0, tw, m)
409074b04bed2b9795ec231a9318af94470595f2
MaloTheBigmalo/BridgeToSuccess
/codebarre.py
548
3.90625
4
codebarre=input("Taper les douze premiers chiffres du code barre ") dernierchiffre=int(input("Taper le dernier chiffre du code ")) somme=0 counter=0 while counter < len(codebarre): if counter % 2 == 0 : somme=somme + int(codebarre[counter])*1 else: somme=somme + int(codebarre[counter])*3 counter = counter + 1 reste = somme%10 treizieme = 10 - reste if treizieme == 10: treizieme=0 elif treizieme == dernierchiffre: print("Le code barre est valide") else: print("Le code barre n n'est pas valide")
5e65957094248593dc6156b2726ebda12d7dad79
jashtags/ceaser-cipher-implementation
/ceasercipher.py
377
3.859375
4
alphastr='abcdefghijklmnopqrstuvwxyz' encryptedmsg="" curpos=0 msg=input("Enter your message that is to be encrypted :") key=int(input("Enter the key ")) key+=1 for char in msg: if char in msg: curpos=alphastr.find(char) addingele=(curpos+key)%len(alphastr) encryptedmsg+=alphastr[addingele] else: encryptedmsg+=char print(encryptedmsg)
1292b3cf45bb288ba57c2efd7b40f3f1a3c47764
jugu77/demo-repo
/test.py
79
3.546875
4
print("Hello World") lst =[] for i in range(10): lst.append(i) print(lst)
3834ff7c2cf4438acbe634d1a052fe0793c501e4
jke-zq/myleetcode.py
/Reverse Linked List II.py
1,311
3.96875
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def reverseBetween(self, head, m, n): """ :type head: ListNode :type m: int :type n: int :rtype: ListNode """ dummy = ListNode(0) dummy.next = head pre = dummy for i in range(m - 1): pre = pre.next tail = pre.next for i in range(n - m): ##work # pre.next, tail.next.next, tail.next = tail.next, pre.next, tail.next.next ##not work print tail.next, tail.next.next, pre.next tmp = tail.next tail.next, tmp.next, pre.next = tail.next.next, pre.next, tail.next # print tail.next, tail.next.next, pre.next # tail.next.next, pre.next, tail.next = pre.next, tail.next, tail.next.next # tmp = tail.next # tail.next, pre.next, tmp.next = tmp.next, tmp, pre.next return dummy.next ##import ##multi variables assigment: #ie: tail.next, tail.next.next = a, b. #when assigning the b to tail.next.next, the value of tail.next.next equals to a.next. #Because the tail.next hase assinged to a.
bb25e89891b086bb769ebd3d98b45709a9c0dc33
hungphat/hackerrank-30days
/day_23/BST_Level_Order_Traversal.py
857
3.796875
4
import sys class Node: def __init__(self, data): self.right=self.left=None self.data = data class Solution: def insert(self,root, data): if root==None: return Node(data) else: if data<=root.data: cur=self.insert(root.left, data) root.left=cur else: cur=self.insert(root.right, data) root.right=cur return root def levelOrder(self,root): queue = [root] for i in queue: print(i.data, end=" ") if i.left: queue.append(i.left) if i.right: queue.append(i.right) T=6 S=[3,5,4,7,2,1] myTree=Solution() root=None for i in range(T): for j in S: data=j root=myTree.insert(root, data) myTree.levelOrder(root)
65e022f819ee9ea89437f0705374adce8d2fae51
hua-x/LeetCode
/mergetwosortedlist.py
1,086
3.921875
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: if not l1: return l2 elif not l2: return l1 marker1 = l1 marker2 = l2 if marker1.val < marker2.val : result = marker1 marker1 = marker1.next else: result = marker2 marker2 = marker2.next return_value = result while marker1 and marker2: if marker1.val < marker2.val: result.next = marker1 marker1 = marker1.next else: result.next = marker2 marker2 = marker2.next result = result.next if marker1: result.next = marker1 else: result.next = marker2 return return_value