blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
5a67d1ced1aca77c19592b81b79a8b2172d336cc
NovaStrikeexe/FtermLabs
/Cir lat.py
669
3.984375
4
#2.42 #Дана строка. Подсчитать общее количество содержащихся в ней СТРОЧНЫХ латинских и русских букв. print("Start program.....") a = (input("Input some line of Letters with Cyrillic and Latin:")) len(a) print("The entire length of the string:",len(a)) arr = str(a) lat = 0; cir = 0; for i in range(arr(a)): if ord(i) in range(97, 123): lat += 1 elif ord(i) in range(1072, 1104): cir += 1 print("Number of Latin:", lat) print("Number of Cirilic:", cir) print("====================") print("End of program") input("Press <Enter> to close program").
23c968a19ec7c68fac5908f3bc798542546dba42
Genvekt/akvelon_python_internship_3_Evgenia_Kivotova
/finance_site/finance_manager/utils.py
601
4.46875
4
from typing import Optional def fibonacci(n: int) -> Optional[int]: """ Function to calculate n'th fibonacci number. Examples: fibonacci(0) -> 0 fibonacci(7) -> 13 fibonacci(-1) -> None fibonacci(N) = fibonacci(N-1) + fibonacci(N-2) """ memory = [0, 1] # Case for n out of function input range if n < 0: return None # Perform summation of memory members to get n == 1 while n > 1: memory[0], memory[1] = memory[1], memory[0] + memory[1] n -= 1 # Case for n == 1 and n == 0 return memory[n]
ccd130469d587a19f5c887a8edf397ba3e039d03
YaraDeOliveira/CursoemVideo
/ex088.py
548
3.671875
4
from random import randint from time import sleep palpite = list() print('-'*40) print(f'{"PALPITE MEGA SENA":^40}') print('-'*40) jogos = int(input('Quantos jogos vc quer que eu sorteie? ')) print(f'-=-=-= SORTEANDO {jogos} JOGOS -=-=-=- ') for c in range(1, jogos+1): for n in range(0, 6): s = randint(1, 60) while s in palpite: s = randint(1, 60) if s not in palpite: palpite.append(s) print(f' Jogo {c}: {sorted(palpite)}') palpite.clear() sleep(0.5) print(f'{"BOA SORTE":=^35}')
4870826ea355a02e7d6fe6051f907d8f0f01c4a6
maheshgawande/tree-data-structure
/binary_search_tree.py
8,387
3.875
4
# -*- coding: utf-8 -*- """ Created on Sat May 2 18:59:39 2020 @author: mahesh """ class Node: def __init__(self, data): self.data = data self.left = None self.right = None self.parent = None class Binary_search_tree: def __init__(self): self.root = None def insert(self, data): new_node = Node(data) if self.root == None: self.root = new_node else: cur_node = self.root while True: if new_node.data > cur_node.data: if cur_node.right == None: cur_node.right = new_node cur_node.right.parent = cur_node print('Data added.') return else: cur_node = cur_node.right elif new_node.data < cur_node.data: if cur_node.left == None: cur_node.left = new_node cur_node.left.parent = cur_node print('Data added.') return else: cur_node = cur_node.left else: print('Duplicate data not allowed.') return def get_min(self, cur_node): while cur_node.left != None: cur_node = cur_node.left return cur_node def del_node(self, d_node): parent_node = d_node.parent if d_node.left == None and d_node.right == None: if d_node == self.root: self.root = d_node = None else: if parent_node.left == d_node: parent_node.left = d_node = None else: parent_node.right = d_node = None elif d_node.left == None: if d_node == self.root: self.root = d_node.right d_node = None else: if parent_node.left == d_node: parent_node.left = d_node.right else: parent_node.right = d_node.right elif d_node.right == None: if d_node == self.root: self.root = d_node.left d_node = None else: if parent_node.left == d_node: parent_node.left = d_node.left else: parent_node.right = d_node.left else: temp = self.get_min(d_node.right) d_node.data = temp.data self.del_node(temp) def delete(self, key): if self.root == None: print('Tree is empty.') return del_status = False cur_node = self.root key_node = None ht = self.height() while ht != 0: if cur_node.data == key: key_node = cur_node break if key > cur_node.data and cur_node.right != None: cur_node = cur_node.right elif key < cur_node.data and cur_node.left != None: cur_node = cur_node.left ht -= 1 if key_node: self.del_node(key_node) del_status = True return del_status def display(self): if self.root == None: print('Tree is empty.') return root = self.root tl = [] q = [] q.append(root) while len(q) != 0: temp = q.pop(0) tl.append(temp.data) if temp.left != None: q.append(temp.left) if temp.right != None: q.append(temp.right) print(tl) def inorder(self): if self.root == None: print('Tree is empty') return self._inorder(self.root) def _inorder(self, cur_node): if cur_node != None: self._inorder(cur_node.left) print(cur_node.data, end=' ') self._inorder(cur_node.right) def preorder(self): if self.root == None: print('Tree is empty') return self._preorder(self.root) def _preorder(self, cur_node): if cur_node != None: print(cur_node.data, end=' ') self._preorder(cur_node.left) self._preorder(cur_node.right) def postorder(self): if self.root == None: print('Tree is empty') return self._postorder(self.root) def _postorder(self, cur_node): if cur_node != None: self._postorder(cur_node.left) self._postorder(cur_node.right) print(cur_node.data, end=' ') def count(self): if self.root == None: return count = 0 root = self.root q = [] q.append(root) while len(q) != 0: temp = q.pop(0) count += 1 if temp.left != None: q.append(temp.left) if temp.right != None: q.append(temp.right) return count def height(self): if self.root == None: return 0 return self._height(self.root, 0) def _height(self, cur_node, ht): if cur_node == None: return ht left_ht = self._height(cur_node.left, ht+1) right_ht = self._height(cur_node.right, ht+1) return max(left_ht, right_ht) if __name__ == '__main__': def not_num(): print('\nOnly numbers are allowed.\n') bst = Binary_search_tree() while True: try: choice = int(input('''1. Insert into tree 2. Display tree 3. Delete from tree 4. Height of tree and nodes is tree 5. Exit Enter your choose: ''')) except ValueError: not_num() else: if choice == 1: print('\n----------------------------------------') try: data = int(input('Enter data to be inserted: ')) except ValueError: not_num() else: bst.insert(data) bst.display() print('----------------------------------------\n') elif choice == 2: print('\n----------------------------------------') try: traverse = int(input('''1. Inorder 2. preorder 3. postorder Enter your choose: ''')) except ValueError: not_num() else: if traverse == 1: bst.inorder() elif traverse == 2: bst.preorder() elif traverse == 3: bst.postorder() else: print('Wrong choice.') print('\n') print('----------------------------------------\n') elif choice == 3: print('\n----------------------------------------') bst.display() try: data = int(input('Enter data to be deleted: ')) except ValueError: not_num() else: data_deleted = bst.delete(data) if data_deleted: print('Data deleted.') bst.display() else: print(f'{data} is not in the tree.') print('----------------------------------------\n') elif choice == 4: print('\n----------------------------------------') print(f'Height of tree: {bst.height()}') print(f'Nodes in tree: {bst.count()}') print('----------------------------------------\n') elif choice == 5: break else: print('\nWrong choice. Try again.\n')
c3faf4729a8ce51cb1b22d5f8a286ce6f18b1de2
dyyzqz1015/Demo_keyboard_python-c-
/python_keyboard/keyboard_test.py
636
4.1875
4
from pynput.keyboard import Key, Controller keyboard = Controller() # Press and release space aAAHello World keyboard.press(Key.space) keyboard.press(Key.space) keyboard.release(Key.space) keyboard.release(Key.space) keyboard.release(Key.space) # Type a lower case A; this will work even if no key on the # physical keyboard is labelled 'A' keyboard.press('a') keyboard.release('a') # Type two upper case As keyboard.press('A') keyboard.release('A') with keyboard.pressed(Key.shift): keyboard.press('a') keyboard.release('a') # Typ aAAHello Worlde 'Hello World' using the shortcut type method keyboard.type('Hello World')
aa8f4d4762d677da0344a62fe387c97867f1716d
alifoliveira/rep-estudos
/python/Unimeta/lista_encadeada/revisao.py
2,991
3.8125
4
class No(): def __init__(self,valor,prox): self.valor = valor self.prox = prox def __str__(self): return str(f'({self.valor},{self.prox})') class ListaEncadeada(): def __init__(self): self.__primeiro = None self.__ultimo = None self.__maior = '' self.__menor = '' self.__count = 0 def primeiro(self): print(self.__primeiro) def ultimo(self): print(self.__ultimo) def mostrar_estrutura(self): print(f'{Cor.WARNING}Lista Encadeada: {self.__primeiro}{Cor.ENDC}') def mostrar_tamanho(self): print(f'{Cor.WARNING}Quantidade de Elementos: {self.__count}{Cor.ENDC}') def maior(self): print(f'{Cor.WARNING}Maior valor: {self.__maior}{Cor.ENDC}') def menor(self): print(f'{Cor.WARNING}Menor valor: {self.__menor}{Cor.ENDC}') def insere_inicio(self,valor): self.valor = valor self.__primeiro = No(self.valor, self.__primeiro) if self.__ultimo == None: self.__ultimo = self.__primeiro self.__count += 1 if len(self.valor) > len(self.__maior): self.__maior = self.valor if len(self.__menor) == 0: self.__menor = self.valor elif len(self.valor) != 0 and len(self.valor) <= len(self.__menor): self.__menor = self.valor def insere_final(self,valor): self.valor = valor p = No(self.valor, None) if self.__primeiro == None: self.__primeiro = p self.__ultimo = p else: self.__ultimo.prox = p self.__ultimo = p self.__count += 1 if len(self.valor) > len(self.__maior): self.__maior = self.valor if len(self.__menor) == 0: self.__menor = self.valor elif len(self.valor) != 0 and len(self.valor) <= len(self.__menor): self.__menor = self.valor def remover_inicio(self): self.__primeiro = self.__primeiro.prox if self.__primeiro == None: self.__ultimo = None self.__count -= 1 def remover_fim(self): if self.__primeiro.prox == None: self.__primeiro == None else: p = self.__primeiro while p.prox != self.__ultimo: p = p.prox p.prox = p.prox.prox if p.prox == None: self._ultimo = p self.__count -= 1 class Cor(): HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' le = ListaEncadeada() le.insere_inicio('encadeada') le.insere_inicio('lista') le.insere_inicio('parece que') le.insere_final('funcionando') le.insere_final('corretamente') le.insere_final('certo?') le.remover_inicio() le.remover_fim() le.mostrar_estrutura() le.mostrar_tamanho() le.maior() le.menor()
fa01a1c66d85a5f45fe354753f8a78acc544fb8e
itboke/python
/hellopython.py
236
4
4
print("please enter your name?") username = input("your name is :") if username == "hello python": print("亲爱的,你输正确了哦!") else: print("你这个不懂编程的家伙") print("好了,今天就到这吧!")
3dd44451cdd8872f19d72ce99168347aca58b677
zhengjiani/pyAlgorithm
/leetcodeDay/March/prac365.py
2,356
3.6875
4
# -*- encoding: utf-8 -*- """ @File : prac365.py @Time : 2020/3/21 8:52 AM @Author : zhengjiani @Email : 936089353@qq.com @Software: PyCharm 水壶问题:有两个容量分别为 x升 和 y升 的水壶以及无限多的水。请判断能否通过使用这两个水壶,从而可以得到恰好 z升 的水? 如果可以,最后请用以上水壶中的一或两个来盛放取得的 z升 水。 你允许: 装满任意一个水壶 清空任意一个水壶 从一个水壶向另外一个水壶倒水,直到装满或者倒空 """ import math class Solution: def canMeasureWater(self, x, y, z): # 深度优先搜索 stack = [(0,0)] self.seen = set() # remain_x表示x中现有的水量 while stack: remain_x,remain_y = stack.pop() if remain_x == z or remain_y == z or remain_x + remain_y == z: return True if (remain_x,remain_y) in self.seen: continue self.seen.add((remain_x,remain_y)) # 把x灌满 stack.append((x,remain_y)) # 把y灌满 stack.append((remain_x,y)) # 倒空x stack.append((0,remain_y)) # 倒空y stack.append((remain_x,0)) # 把x的水灌进y壶,直至灌满或倒空 stack.append((remain_x - min(remain_x,y-remain_y), remain_y + min(remain_x,y-remain_y))) # 把y的水灌进x壶,直至灌满或倒空 stack.append((remain_x + min(x-remain_x,remain_y), remain_y-min(x-remain_x,remain_y))) return False class Solution1: def canMeasureWater(self, x, y, z): # 裴蜀定理(或贝祖定理)说明了对任何整数a、b和它们的最大公约数d, # 关于未知数x和y的线性不定方程(称为裴蜀等式):若a,b是整数,且gcd(a,b)=d,那么对于任意的整数x,y,ax+by都一定是d的倍数, # 特别地,一定存在整数x,y,使ax+by=d成立。 # 它的一个重要推论是:a,b互质的充要条件是存在整数x,y使ax+by=1. if x + y < z: return False if x == 0 or y == 0: return z == 0 or x + y == z return z % math.gcd(x,y) == 0 if __name__ == '__main__': x,y,z = 3,5,4 s = Solution() print(s.canMeasureWater(x,y,z))
68796721188aa11f36f25c7037208fef15be6aeb
prabhu30/coding
/Hackerrank/15 _ Find a String/solution.py
261
3.671875
4
def count_substring(string, sub_string): c = 0 ls = len(sub_string) fs = string.find(sub_string) for i in range(0,len(string)): if string[i]==sub_string[0]: if string[i:i+ls]==sub_string: c += 1 return c
2fbea34cb50660d7e3560c2288bc910943995fa0
odegard-remarkable/adventofcode2020
/dayOne.py
398
3.546875
4
from itertools import combinations from math import prod with open ("input.txt", "r") as f: entries = [int(i) for i in f.read().strip().splitlines()] def findCombinations(numberOfEntries): for combination in combinations(entries, numberOfEntries): if sum(combination) == 2020: return prod(combination) print(findCombinations(2)) print(findCombinations(3))
d599b9bfc12b74bcc7e377ef6461da05073bd05d
Jeepmb/adventuresofpython
/matrix_test/matrix_test.py
535
3.984375
4
#!/usr/bin/python3 usr_choice = input("What bar would you like to know about?:\n") bars = [ ["Manito Taphouse","3","6","All",], ["Republic Pi","4","6","Monday"] ] end = "" for element in bars: for sub_element in element: if usr_choice in sub_element: print(sub_element) start = element[1] end = element[2] print("The happy hour for " + usr_choice + " is from " + start + " to " + end) if end == "": print("That bar is not yet listed in our database")
6459992fcded23cddaf3d0cd3f7ad14612b698c6
guptahardik17/Coding-Challanges
/Total Number of Binary Search Trees.py
528
3.765625
4
# from math import factorial import sys _FAC_TABLE = [1, 1] def factorial(n): if n < len(_FAC_TABLE): return _FAC_TABLE[n] last = len(_FAC_TABLE) - 1 total = _FAC_TABLE[last] for i in range(last + 1, n + 1): total *= i _FAC_TABLE.append(total) return total t = int(sys.stdin.readline()) for i in range(t): value = int(sys.stdin.readline()) if value<2: print(1) pass else: print(factorial(value*2)//(factorial(value) * factorial(value+1)))
8ddf0950442ebe563b1955e3fc2320ba63ee73e6
anicacio/learning_python
/list.py
712
3.9375
4
""" There are four collection data types in the Python programming language: List is a collection which is ordered and changeable. Allows duplicate members. Tuple is a collection which is ordered and unchangeable. Allows duplicate members. Set is a collection which is unordered and unindexed. No duplicate members. Dictionary is a collection which is unordered, changeable and indexed. No duplicate members. """ # List thislist = ["apple", "banana", "cherry"] print(thislist) # Tuples thistuple = ("apple", "banana", "cherry") print(thistuple) # Set thisset = {"apple", "banana", "cherry"} print(thisset) # Dictionary thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } print(thisdict)
3d7e3c049cdbafec01db8a4e7635198e8cb1effa
ksrntheja/08-Python-Core
/venv/list/28OrderingFunctionsReversedString.py
246
3.640625
4
s = 'theja' # s.reverse() # AttributeError: 'str' object has no attribute 'reverse' r = reversed(s) print(r) print(type(r)) print(s) for x in r: print(x) # <reversed object at 0x7f76cae99b38> # <class 'reversed'> # theja # a # j # e # h # t
9a6f5a048c94a6e4e263cb8989b44ac3434b3b9e
madebr/ncurses_programs
/python/basics/other_border.py
2,832
3.5
4
#!/usr/bin/env python import curses class Border(object): def __init__(self): self.ls = '|' self.rs = '|' self.ts = '-' self.bs = '-' self.tl = '+' self.tr = '+' self.bl = '+' self.br = '+' class Window(object): def __init__(self): self.width = 10 self.height = 3 self.startx = (curses.COLS - self.height) // 2 self.starty = (curses.LINES - self.height) // 2 self.border = Border() def create_box(self, window, flag): x = self.startx y = self.starty w = self.width h = self.height if flag: window.addch(y + 0, x + 0, self.border.tl) window.addch(y + 0, x + w, self.border.tr) window.addch(y + h, x + 0, self.border.bl) window.addch(y + h, x + w, self.border.br) window.hline(y + 0, x + 1, self.border.ts, w - 1) window.hline(y + h, x + 1, self.border.bs, w - 1) window.vline(y + 1, x + 0, self.border.ls, h - 1) window.vline(y + 1, x + w, self.border.rs, h - 1) else: pass # for j in range(y, y + h + 1): # for i in range(x, x + w + 1): # window.addch(j, i, ' ') def __repr__(self): return "<{}: {} {} {} {}>".format(type(self).__name__, self.startx, self.starty, self.width, self.height) def main(): # Start curses mode stdscr = curses.initscr() # Start the color functionality curses.start_color() # Line buffering disabled, Pass on verything to me curses.cbreak() # I need that nifty F1 stdscr.keypad(True) curses.noecho() curses.init_pair(1, curses.COLOR_CYAN, curses.COLOR_BLACK) # Initialize the window parameters win = Window() stdscr.insstr(25, 0, repr(win)) stdscr.refresh() stdscr.attron(curses.color_pair(1)) stdscr.addstr(0, 0, "Press F1 to exit") stdscr.refresh() stdscr.attroff(curses.color_pair(1)) win.create_box(stdscr, True) while True: ch = stdscr.getch() if ch == curses.KEY_F1: break if ch == curses.KEY_LEFT: win.create_box(stdscr, False) win.startx -= 1 win.create_box(stdscr, True) elif ch == curses.KEY_RIGHT: win.create_box(stdscr, False) win.startx += 1 win.create_box(stdscr, True) elif ch == curses.KEY_UP: win.create_box(stdscr, False) win.starty -= 1 win.create_box(stdscr, True) elif ch == curses.KEY_DOWN: win.create_box(stdscr, False) win.starty += 1 win.create_box(stdscr, True) # End curses mode curses.endwin() try: main() finally: curses.endwin()
1639aa63c066a89a72103c87e20e58d39ffa5c0d
joeyaj1302/Diabetes_predictor
/diabetes_pred.py
2,119
3.734375
4
import pandas as pd from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression import streamlit as st import numpy as np import urllib from PIL import Image urllib.request.urlretrieve("https://www.niddk.nih.gov/-/media/Images/Health-Information/Diabetes/diabetes-monitor-fruits-vegetables-small_597x347.png", "car_sample1.png") img = Image.open("car_sample1.png").convert('RGB') img = img.resize((700,400)) st.image(img) url = "https://raw.githubusercontent.com/joeyaj1302/datasets/master/diabetes.csv" data = pd.read_csv(url, error_bad_lines=False) st.title("Diabetes Predicton by machine learning") st.header("Choose the parameters like age , BMI, Glucose , etc") # Storing the default mean values in a dictionary: #defining the inputs and outputs x = data.iloc[:,:-1] y = data.iloc[:,-1] reg = LogisticRegression() reg.fit(x,y) #taking input data from users Pregnancies= 0 SkinThickness = 20 DiabetesPedigreeFunction = 0.47 Age = st.slider("select your age from the slider :", 25, 100) BloodPressure = st.slider("Select your diastolic blood pressure from the slider :" ,60, 122) BMI = st.slider("Select your BMI from the slider :" ,20, 50) Insulin = st.slider("Select your insulin level from the slider :" ,30, 800) Glucose = st.slider("Select your Blood glucose level from the slider :" ,80, 200) if st.checkbox("Do you want to input other related data like pregnancy,skin thickness and DiabetesPedigreeFunction ?"): Pregnancies = st.sidebar.selectbox("Select the number of Pregnancies you had from the drop down box :",[1,2,3,4,5,6]) SkinThickness = st.sidebar.slider("Select your skin thickness in mm :",1.5,9.9)*10 DiabetesPedigreeFunction = st.sidebar.slider("Select your tested DiabetesPedigreeFunction :",0.07,2.42) x1 = np.array([[Pregnancies,Glucose,BloodPressure,SkinThickness,Insulin,BMI,DiabetesPedigreeFunction,Age]]) #st.write(x1) #st.write(Age,BMI,Insulin,BloodPressure,Glucose) preds = reg.predict(x1) if preds == 1: st.header("You are more prone to diabetes") else: st.header("You are probably safe from diabetes")
3268f4e14b3ab94fa03a956267e6e6ca153051a0
abdul-hashim/Python-Projects
/PyPoll/main.py
3,225
3.6875
4
import os import csv csvpath = os.path.join('.', 'Resources', 'election_data.csv') with open(csvpath, newline= '') as csvfile: csvreader = csv.reader(csvfile, delimiter=',') #reads the first line of the file which is the header and we stored it in the csv_header variable. csv_header = next(csvreader) countTotal = 0 countKhan = 0 countCorrey = 0 countLi = 0 countOTooley = 0 currentMax = 0 for row in csvreader: #Checks if its Khan if row[2] == "Khan": #Adds Khan to a counter to track him countKhan = countKhan + 1 #Checks if Khan has the most votes and if he does then adds his name as the winner if currentMax < countKhan: currentMax = countKhan winner = "Khan" #Same as the above 3 steps but for Correy elif row[2] == "Correy": countCorrey = countCorrey + 1 if currentMax < countCorrey: currentMax = countCorrey winner = "Correy" elif row[2] == "Li": countLi = countLi + 1 if currentMax < countLi: currentMax = countLi winner = "Li" elif row[2] == "O'Tooley": countOTooley = countOTooley + 1 if currentMax < countOTooley: currentMax = countOTooley winner = "O'Tooley" #adds total count countTotal = countKhan + countCorrey + countLi + countOTooley #Print out the results print(f"Election Results") print(f"---------------------------") print(f"Total Votes: {countTotal}") print(f"---------------------------") print(f"Khan: {round(countKhan/countTotal * 100, 3)}% ({countKhan})") print(f"Correy: {round(countCorrey/countTotal *100, 3)}% ({countCorrey})") print(f"Li: {round(countLi/countTotal * 100, 3)}% ({countLi})") print(f"O'Tooley: {round(countOTooley/countTotal*100, 3)}% ({countOTooley})") print(f"---------------------------") print(f"The Winner is: {winner}!") print(f"---------------------------") # Specify the file to write to output_path = os.path.join(".", "output", "Results.csv") # Open the file using "write" mode. Specify the variable to hold the contents with open(output_path, 'w', newline='') as csvfile: # Initialize csv.writer csvwriter = csv.writer(csvfile, delimiter='\n') # Write the second row csvfile.writelines([f"Election Results \n"]) csvfile.writelines(["--------------------------- \n"]) csvfile.writelines([f"Total Votes: {countTotal} \n"]) csvfile.writelines([f"--------------------------- \n"]) csvfile.writelines([f"Khan: {round(countKhan/countTotal * 100, 3)}% ({countKhan}) \n"]) csvfile.writelines([f"Correy: {round(countCorrey/countTotal *100, 3)}% ({countCorrey}) \n"]) csvfile.writelines([f"Li: {round(countLi/countTotal * 100, 3)}% ({countLi}) \n"]) csvfile.writelines([f"O'Tooley: {round(countOTooley/countTotal*100, 3)}% ({countOTooley}) \n"]) csvfile.writelines([f"--------------------------- \n"]) csvfile.writelines([f"The Winner is: {winner}! \n"]) csvfile.writelines([f"--------------------------- \n"])
d6a9787cf8ec514d7a1fddd7428ca008939be0af
jerthompson/au-aist2120-19fa
/1130-A/0903-primeB.py
333
4.15625
4
for n in range(3,101): max_factor = n//2 is_prime = True # ASSUMKE prime for f in range(2, max_factor + 1): # INCLUDE max_factor by adding 1 if n % f == 0: print(n, "is not prime--it is divisible by", f) is_prime = False break if is_prime: print(n, "is prime")
8e299caf4f666b94f1fa4449d1adf9b195b56df2
Ana-Vi/Homework
/Pythons/l5q4.py
164
3.78125
4
n= int(input("Quantos alunos so? ")) soma= 0 for aux in range (n): nota= float(input("Qual a nota? ")) soma= soma+nota media= soma/n print("%.2f" %media)
4f917d9f412714d9492099432755205b67aa269b
TrungHieu97/IntershipW1
/T1_A_divided_by_B.py
354
3.875
4
from builtins import print def A_divided_by_B(A , B): print("{A} : {B}".format(A=A, B=B)) if (B == 0): print("No answer") a = abs(A) b = abs(B) count = 0 while(a >= b): a = a - b count += 1 if ((A < 0) ^ (B < 0)): count = -count print("The result : %2d"%count) A_divided_by_B(0,-10)
31198d46f82b5623187eba6e30698ca4de7d70aa
ongaaron96/kattis-solutions
/python3/9_5-tsp-bruteforce.py
1,625
3.578125
4
class Point: def __init__(self, x, y, index): self.x = x self.y = y self.index = index def dist_to(self, other): return ((self.x - other.x)**2 + (self.y - other.y)**2) ** 0.5 def calc_total_dist(points): total_dist = 0 for i in range(len(points)-1): total_dist += points[i].dist_to(points[i+1]) return total_dist def swap(arr, i, j): temp = arr[i] arr[i] = arr[j] arr[j] = temp def next_order(points): for i in range(len(points)-2, -1, -1): # 1. Find largest i such that P[i] < P[i+1] if points[i].index < points[i+1].index: # 2. Find largest j such that P[i] < P[j] for j in range(len(points)-1, -1, -1): if points[i].index < points[j].index: # 3. Swap P[i] and P[j] swap(points, i, j) # 4. Reverse P[i+1 .. n] right_arr = points[i+1:] right_arr.reverse() return points[:i+1] + right_arr return None num_points = int(input()) points = [] for i in range(num_points): x, y = map(float, input().split()) points.append(Point(x, y, i)) orders_done = set() best_dist = -1 best_order = [] while not points is None: reverse_order = ''.join([str(p.index) for p in points[::-1]]) if reverse_order not in orders_done: # print(' '.join([str(p.index) for p in points])) total_dist = calc_total_dist(points) if best_dist == -1 or total_dist < best_dist: best_dist = total_dist best_order = points.copy() # print(best_dist) orders_done.add(''.join([str(p.index) for p in points])) points = next_order(points) for point in best_order: print(point.index)
aebadf89388be358bf3cee95f37e93136985b802
usafwilson/Codewars
/Python/6Kyu/Sort_the_odd.py
552
3.71875
4
def sort_array(source_array): odds = [] return_array = [] for e in source_array: if e % 2 != 0: odds.append(e) sorted_odds = sorted(odds) indx = 0 for n in source_array: if n % 2 != 0: return_array.append(sorted_odds[indx]) indx += 1 else: return_array.append(n) return return_array # ### Community Solution ### # def sort_array(arr): # odds = sorted((x for x in arr if x%2 != 0), reverse=True) # return [x if x%2==0 else odds.pop() for x in arr]
b69bf0bdb9c09039b4eda331d4549b9eca20e1e2
nicholaswuu/Year_10_Design
/Project 3/stopwords.py
834
3.578125
4
import nltk from nltk.corpus import stopwords stop_words = stopwords.words('english') text = ['natural', 'language', 'processing', 'nlp', 'is', 'a', 'subset', 'of', 'artificial', 'intelligence', 'which', 'deals', 'with', 'how', 'computers', 'process', 'and', 'understand', 'natural', 'language', 'or', 'human', 'language', 'it', 'is', 'used', 'to', 'processes', 'human', 'language', 'in', 'the', 'form', 'of', 'speech', 'or', 'text', 'so', 'that', 'it', 'can', 'be', 'used', 'by', 'the', 'computer', 'and', 'analyzed', 'to', 'recognize', 'context', 'and', 'intent', 'it', 'is', 'far', 'from', 'perfect', 'and', 'there', 'is', 'still', 'much', 'to', 'be', 'explored', 'and', 'improved', 'in', 'this', 'field'] filtered_sentence = [] for w in text: if w not in stop_words: filtered_sentence.append(w) print(filtered_sentence)
df3e16db595acd6c89906a15ed67522159f6c51f
sachinboob/Python
/list_comprehension.py
1,943
3.6875
4
my_range = range(1, 11) # Format 1 # L = [<x> for <x> in <iterable>] L1 = [x for x in my_range] print("List Format 1 :- ", L1) # Format 2 # L = [<f(x)> for <x> in <iterable>] def list_comprehension_format_2(x): return x**2 L2 = [list_comprehension_format_2(x) for x in my_range] print("List Format 2 :- ", L2) # Format 3 # L = [<x> for <x> in <iterable> if <C(<x>)> == True] def list_comprehension_format_3(x): return x % 3 == 0 L3 = [x for x in my_range if list_comprehension_format_3(x) == True] print("List Format 3 :- ", L3) L3 = [x for x in my_range if x % 2 == 0] print("List Format 3 :- ", L3) # Format 4 # L = [f(x) for x in iterable if C(x) == True] def list_comprehension_format_4(x): return x**3 L4 = [list_comprehension_format_4(x) for x in my_range if x % 2 != 0] print("List Format 4 :- ", L4) # Format 5 # L = [(x1, x2,...xn) for x1 in iterable1 # for x2 in iterable2 # . # . # for xn in iterablen] L5 = [(x1, x2, x3) for x1 in range(1, 3) for x2 in range(3, 5) for x3 in range(5, 7)] print("List Format 5 :- ", L5) # Format 6 # L = [f1(x1), f2(x2), ... fn(xn) for x1 in iterable1 # for x2 in iterable2 # . # . # for xn in iterablen] L6 = [(x1**2, x2**3) for x1 in [1, 2, 3] for x2 in [4, 5, 6]] print("List Format 6 :- ", L6) # Format 6 # L = [f1(x1), f2(x2), ... fn(xn) for x1 in iterable1 if c1(x1) == True # for x2 in iterable2 if c2(x2) == True # . # . # for xn in iterablen] if cn(xn) == True L7 = [(x1**2, x2**3) for x1 in my_range if x1 % 2 == 0 for x2 in my_range if x2 % 2 != 0] print("List Format 7 :- ", L7)
c10e0db7786c894bb36023eaf0d531c68354e069
imvijith/Coding-Ninjas---Data-Structures-and-Algorithms-in-Python
/30 Recursion Assignment/09 stairCase.py
222
4.0625
4
def stair(n): if n == 0 or n == 1: return 1 elif n == 2: return 2 elif n == 3: return 4 else: return stair(n-3) + stair(n-2) + stair(n-1) n = int(input()) print(stair(n))
7888059595ab5a48ffecb723c85c233c1698a064
pzmrzy/LeetCode
/python/add_two_numbers_II.py
910
3.671875
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ s1 = [] s2 = [] while l1 is not None: s1.append(l1.val) l1 = l1.next while l2 is not None: s2.append(l2.val) l2 = l2.next tmp = 0 res = ListNode(0) while len(s1) != 0 or len(s2) != 0: if len(s1) != 0: tmp += s1.pop() if len(s2) != 0: tmp += s2.pop() res.val = tmp % 10 head = ListNode(tmp // 10) head.next = res res = head tmp //= 10 return res.next if res.val == 0 else res
e2c158e3f656f285c4a43b5659535cac960cdcc0
caozhengbo/Python-project
/GUI/text8.py
1,111
4.03125
4
import tkinter #使用Tkinter前需要先导入 # 实例化object,建立窗口window window = tkinter.Tk() # 给窗口的可视化起名字 window.title('My Window') # 设定窗口的大小(长 * 宽) window.geometry('500x300') # 这里的乘是小x # 在图形界面上创建一个标签label用以显示并放置 label = tkinter.Label(window, bg='green', fg='white', width=20, text='how much you like me?') label.pack() # 定义一个触发函数功能 def print_selection(v): label.config(text = '程度:' + v) scale = tkinter.Scale(window, label = '%', from_ = 0,#从0开始 to = 100,#到100结束 orient = tkinter.HORIZONTAL,#水平方向 length = 200,#长度200个字符 tickinterval = 10,#每10一个刻度 resolution = 1,#精度为1 command = print_selection) scale.pack() # 主窗口循环显示 window.mainloop()
c66a80f3a1876651f075def495287c7679a8244f
agilitee/2021_Pavlishina_infa
/pythonProject1/ex14.py
320
3.78125
4
import turtle as t import math def star(n, a): t.penup() t.goto(0, 0) r = a / (2 * math.sin(math.pi / n)) t.goto(r, 0) t.left(180/n + 90) t.pendown() for i in range(n): t.forward(a) t.left(180-180/n) t.right(180-180/n) t.shape("turtle") star(5,40) star(11, 40) input()
6ad30333606afa0a004ccee04eb0af98695f46f7
exponential-growth/Python-Helper
/Python-Study/07-file/03_os.py
1,171
3.625
4
import os import shutil # 文件重命名 def rename(oldname, newname): os.rename(oldname, newname) # 文件重命名super def renames(oldname, newname): os.renames(oldname, newname) # 文件删除 def delete(path): os.remove(path) # 创建文件夹 def mkdir(path): os.mkdir(path) # 删除文件夹 # os.rmdir(path) # 文件的拷贝 def copy(src, dest): # 复制文件 shutil.copyfile(src, dest) # 复制文件到文件或者目录 # shutil.copy(src, dest) # 文件夹移动或者删除 def move(src, dst): shutil.move(src, dst) def rmtree(path): shutil.rmtree(path) if __name__ == '__main__': # rename("test02_1.txt", "test01.txt") # 除了改名还可以移动文件夹,如果文件夹不存在自动帮我们创建 # renames("test01.txt", "test100/test01.txt") # delete("test100/test01.txt") # mkdir("test_02") # copy("test02_2.txt", "test02_1.txt") # 除了改名还可以移动文件夹,如果文件夹不存在则报错 # move("test02_2.txt", "test_02/test01.txt") # input = raw_input("请输入数据:") # print "有人输入了:",input rmtree("test_02")
6f974498a56e1642a17240d95d5e4792f74e8eaf
ankur990/pythonlab
/ankur.py18.py
221
3.5
4
for k in range(0, len(all_words)): if(len(small) > len(all_words[k])): small = all_words[k]; if(len(large) < len(all_words[k])): large = all_words[k]; return small,large;
5c9f83b2168051582fade0d1b44ed7496a79ad99
chadparry/homeauto
/autonumber.py
692
3.671875
4
import enum from enum import unique # This can't be a member because members in an enum are treated magically. _AutoNumber_last = {} class AutoNumber(enum.Enum): """Automatically numbers enum values sequentially This code is based on the recipe at https://docs.python.org/3/library/enum.html#autonumber. It requires either Python 3.4 or the enum34 package.""" def __new__(cls, *args): if args == (): if cls in _AutoNumber_last: value = _AutoNumber_last[cls] + 1 else: value = 0 elif len(args) == 1: value = args[0] else: value = args obj = object.__new__(cls) obj._value_ = value if isinstance(value, int): _AutoNumber_last[cls] = value return obj
5bd69c395e6bb3482c000738c864446afd1a2426
lihua8188/python-foundation
/investigate texts and calls/ZH/Task2.py
1,649
3.8125
4
""" 下面的文件将会从csv文件中读取读取短信与电话记录, 你将在以后的课程中了解更多有关读取文件的知识。 """ import csv with open('texts.csv', 'r') as f: reader = csv.reader(f) texts = list(reader) with open('calls.csv', 'r') as f: reader = csv.reader(f) calls = list(reader) """ 任务2: 哪个电话号码的通话总时间最长? 不要忘记,用于接听电话的时间也是通话时间的一部分。 输出信息: "<telephone number> spent the longest time, <total time> seconds, on the phone during September 2016.". 提示: 建立一个字典,并以电话号码为键,通话总时长为值。 这有利于你编写一个以键值对为输入,并修改字典的函数。 如果键已经存在于字典内,为键所对应的值加上对应数值; 如果键不存在于字典内,将此键加入字典,并将它的值设为给定值。 """ phone_dict = {} longest_time = 0 longest_phone_list = [] # creat a telephone dictionary with time spent for call in calls: for i in range(2): if call[i] in phone_dict: phone_dict[call[i]] += int(call[3]) else: phone_dict[call[i]] = int(call[3]) # get the longest time spend and phone list for phone in phone_dict: if phone_dict[phone] > longest_time: longest_time = phone_dict[phone] longest_phone_list = [] longest_phone_list.append(phone) elif phone_dict[phone] == longest_time: longest_phone_list.append(phone) print("{} spent the longest time, {} seconds, on the phone during September 2016.".format(longest_phone_list, longest_time))
991aac05aa698db145c130449966d3217293ac8e
kimjieun6307/itwill
/itwill/Python_1/chap02_Control/exams/exam03.py
1,698
3.703125
4
''' step3 관련 문제 문) word counter - 여러줄의 문장을 단어로 분류하고, 단어 수 출력하기 ''' multiline="""안녕하세요. Python 세계로 오신걸 환영합니다. 파이션은 비단뱀 처럼 매력적인 언어입니다.""" sents = multiline.split() print(sents) # ['안녕하세요.', 'Python', '세계로', '오신걸', '환영합니다.', '파이션은', '비단뱀', '처럼', '매력적인', '언어입니다.'] print('단어 수: ', len(sents)) # 단어 수: 10 # <<출력 결과>> ''' 안녕하세요. Python 세계로 오신걸 환영합니다. 파이션은 비단뱀 처럼 매력적인 언어입니다. 단어수 : 10 ''' #(1) for i in multiline.split(): print(i) print('단어수 : ', len(i)) # 단어수 : 6 ---마지막 단어 '언어입니다.' 의 글자수 6 #-------------------------------------- #(2) sents =[] for i in multiline.split('\n') : sents.append(i) for j in i.split(): print(j) print('단어수 : ', len(words)) # 단어수 : 10 print(sents) # ['안녕하세요. Python 세계로 오신걸', '환영합니다.', '파이션은 비단뱀 처럼 매력적인 언어입니다.'] #----------------------------------- #(3) sents =[] words=[] for i in multiline.split('.') : sents.append(i) for j in i.split(): words.append(j) print(words) #['안녕하세요', 'Python', '세계로', '오신걸', '환영합니다', '파이션은', '비단뱀', '처럼', '매력적인', '언어입니다'] print('단어수 : ', len(words)) # 단어수 : 10 print(sents) # ['안녕하세요', ' Python 세계로 오신걸\n환영합니다', '\n파이션은 비단뱀 처럼 매력적인 언어입니다', '']
2ff399c5a7041be4029a8e91e3a9f6d6b64717cd
robg128/book_python_crash_course
/book_python_crash_course/ch04/dimensions.py
800
4.3125
4
# (1) Use tuples to create an immutable (i.e. can not change list items) dimensions = (200, 50) print(dimensions[0]) print(dimensions[-1]) # (2) Try to change an element in the list # dimensions[0] = 250 # print('\nNew list item at position 1') # print(dimensions[0]) # (3) Writing over a Tuple dimensions = (400, 100) print(dimensions[0]) print(dimensions[-1]) # (4) Try it yourself # (4-13) Buffet -> 5 basic foods basic_foods = ('collard greens', 'tomato', 'apple', 'carrots', 'orange') # Print all foods in the tuple for food in basic_foods: print(food) # Create error and try to reassign a value within the tuple # basic_foods[0] = 'mushrooms' # Rewrite the Tuple basic_foods = ('green beans', 'tomato', 'apple', 'carrots', 'strawberries') for food in basic_foods: print(food)
436123f8962139d36504f015a04c60228c0b16d8
mmateusu/Exercicios-python-cursoemvideo
/Exercício 11.py
212
3.65625
4
#Exercício 11 A= int(input('Insira a altura da parede:')) B= int(input('Insira a largura da parede:')) C= A*B print('Para essa parede você vai precisar dessa quantidade de tinta: {}l'.format(C/2))
d83bd00a210b2422d84cbcd2594970b18725a99d
Caioseal/Python
/Exercícios/ex39.py
625
4.03125
4
from datetime import date atual = date.today().year nasc = int(input('Ano de nascimento: ')) idade = atual - nasc print(f'Quem nasceu em {nasc} tem {idade} anos em {atual}.') if idade == 18: print('Você tem que se alistar nesse ano!') elif idade < 18: saldo = 18 - idade ano = atual + saldo print(f'Você ainda não tem 18 anos. Ainda faltam {saldo} anos para o alistamento.') print(f'Você deveria ter se alistado em {ano}') else: saldo = idade - 18 ano = atual - saldo print(f'Você deveria ter se alistado há {saldo} anos.') print(f'Você deverá se alistar em {ano}')
053c2a46b3df16514fbcd074c2c64265ec3ca4ce
lundbird/LeetCode
/getting_different_number.py
540
3.6875
4
def different_number(arr) -> int: ''' [0,1,2,3] -> 4 [1,2,3,4] -> 0 [0,1,3,4] -> 2 ''' sorted_arr = sorted(arr) for i in range(len(sorted_arr)): if sorted_arr[i] != i: return i return len(sorted_arr) def different_number_2(arr) -> int: ''' [0,1,2,3] -> 4 [1,2,3,4] -> 0 [0,1,3,4] -> 2 ''' dummy_array = [0]*(len(arr)+1) for val in arr: dummy_array[val] = 1 return dummy_array.get(0) print(different_number([0,1,2,3])) print(different_number([1,2,3,4])) print(different_number([0,1,3,4]))
af1bea7ff82f789b044d21614e46a3c2f77e7fa1
ZR-Huang/AlgorithmsPractices
/Leetcode/每日打卡/March/912_SortArray.py
1,023
3.875
4
''' 给你一个整数数组 nums,请你将该数组升序排列。 示例 1: 输入:nums = [5,2,3,1] 输出:[1,2,3,5] 示例 2: 输入:nums = [5,1,1,2,0,0] 输出:[0,0,1,1,2,5] 提示: 1 <= nums.length <= 50000 -50000 <= nums[i] <= 50000 ''' from typing import List class Solution: def sortArray(self, nums: List[int]) -> List[int]: self.quickSort(nums, 0, len(nums)-1) return nums def quickSort(self, nums, start, end): if start >= end: return pivot = self.partition(nums, start, end) self.quickSort(nums, start, pivot-1) self.quickSort(nums, pivot+1, end) def partition(self, nums, start, end): l = r = start while r < end: if nums[r] <= nums[end]: # choose the last element as pivot nums[l], nums[r] = nums[r], nums[l] l += 1 r += 1 nums[l], nums[end] = nums[end], nums[l] return l print(Solution().sortArray([5,1,1,2,0,0]))
9bf2ff424dfcc2079178f0250e37f4eefbe58432
AlexSousa/Codigos-fontes-variados-em-python
/ykinter.py
858
3.90625
4
import random import os status = True print("Bem-Vindo ao jogo ") print("------------------") print("Escolha Um Nível") print("1-Facil") print("2-Medio") print("3-Dificil\n") print("4-Sair") print("------------------") nivel = input("Digite o Nível") ale = random.randrange(10) if nivel == "1": for numero in range(10, 10): jogada = input("Digite um numero de 1 a 30") if jogada != ale: if numero == 0: print("Desculpe voce nao conseguiu acertar o numero sorteado era ", jogada) break print("Voce errou") print("Agora Voce tem ", numero, " chances") if numero < ale: print("Dica o numero sorteado é maior que :", jogada) else: print("Dica o numero sorteado é menor que :", jogada) else: print("Parabens voce acertou")
6dc708f5d5fa72644a6f2400f60930f66c7e70d5
Aasthaengg/IBMdataset
/Python_codes/p02415/s332760789.py
154
3.921875
4
s = input() o = "" for w in s: if w.isupper(): o += w.lower() elif w.islower(): o += w.upper() else: o += w print(o)
6b4e8b29ab2cad791a5ce996088235416db2761a
Yi-Hua/HackerRank_practicing
/Python_HackerRank/Math/ModDivmod.py
337
3.953125
4
# Mod Divmod # For example: ''' >>> print divmod(177,10) (17, 7)''' # Here, the integer division is 177/10 => 17 and the modulo operator is 177%10 => 7. # Sample Input ''' 177 10 ''' # Sample Output ''' 17 7 (17, 7) ''' a = int(input()) b = int(input()) print(a//b) print(a%b) print(divmod(a,b))
2633c8aed05b3c0fbbe01bdbca85478e9c3c3ef8
xFelipe/Estudos-Python
/7-string4.py
293
3.734375
4
print ('Programa que leia uma palavra e troque as vogais por "*"') palavra = input("Palavra: ") cont=0 troca = "" while cont < len(palavra): if palavra[cont] in "aeiou": troca=troca+("*") else: troca=troca+palavra[cont] cont=cont+1 print ("Nova palavra:%s"%troca)
1172e02df2e1e4c7348db347181d996a1c5b4b1a
aisuluudb/Ch4-Task4
/Task4.py
1,210
3.875
4
# Создайте класс ContactList, который должен наследоваться от # встроенного класса list. В нем должен быть реализован метод # search_by_name, который должен принимать имя, и возвращать список # всех совпадений. Замените all_contacts = [ ] на all_contacts = # ContactList(). Создайте несколько контактов, используйте метод # search_by_name. class ContactList(): def __init__(self, names, contacts): self.names = names self.contacts = contacts class List(ContactList): def __init__(self): self.all_contacts = [] def search_by_name(self, *name): for i in name: self.all_contacts.append(i) matches_ = set([i for i in self.all_contacts if self.all_contacts.count(i) > 1]) for match in matches_: print("list of matches: ", match) class ContactList(List): def __init__(self): super().__init__() my_contacts = ContactList() my_contacts.search_by_name('lisa', 'kara', 'sarah', 'lisa', 'lyuda', 'sarah', 'larisa')
e2a17a0ac349f5bd0233e85ce9438887c9d94747
quangdbui9999/CS-171
/week5Python/Week5/convertToBinary.py
173
4.09375
4
''' Type your code here. ''' decimal = int(input()) binary = "" while decimal != 0: remainder = decimal % 2 decimal //= 2 binary += str(remainder) print(binary)
ba9be9c6c9eade4aa9ed8729c89f515b60b432df
itzelot/CYPItzelOT
/libro/ejemplo3_3.py
211
3.90625
4
CUECER=0 N= int(input("Dame un numero entero positivo:")) for I in range(0,N,1): NUM=int(input("Ingresa un entero:")) if NUM==0: CUECER += 1 print("El numero de ceros capturados fue:", CUECER)
327855b468e267a4d2f41bd8a6fda258b606a10e
kamoshin/python3_nyumon_note
/chapter12/car_class1.py
555
3.96875
4
#Carクラス class Car: def __init__(self, color = "white"): self.color = color #引数で受け取った値を代入 self.mileage = 0 #0からスタート car1 = Car() #インスタンスcar1の作成 car2 = Car("red") #インスタンスcar2の作成 #インスタンス変数にアクセスする #方法:インスタンス.変数名 print(car1.color) print(car1.mileage) print(car2.color) #インスタンス変数colorの値を更新する car1.color = "green" print(car1.color)
14cf92d2ed276946d696122dca84c259678501b4
tpunhani/NineMenMorrisGame
/MiniMaxGameBlack.py
4,893
3.578125
4
import sys import math from MorrisVariantUtil import MorrisVariantUtil class MiniMaxGameBlack: ''' Program plays a move for Black in the midgame/endgame phase of the game with alpha beta pruning. ''' def __init__(self): ''' Take 3 arguments: input file, output file and depth of the game tree. ''' self.inFile = sys.argv[1] self.outFile = sys.argv[2] self.depth = int(sys.argv[3]) self.positionsEvaluated = 0 self.minimax_estimate = 0 def generateMovesMidgameEndgame(self, boardPos): ''' Return a list of all possible moves from board position. ''' whiteCount = 0 blackCount = 0 for value in boardPos: if value == 'W': whiteCount += 1 elif value == 'B': blackCount += 1 if whiteCount == 3: return morrisVariantUtil.generateHopping(boardPos) else: return morrisVariantUtil.generateMove(boardPos) def maxMin(self, boardPos, depth): ''' Return the best move for the MAX player. ''' maxChoice : str if depth > 0: depth -= 1 v = -math.inf # find all possible moves possibleMovesList = self.generateMovesMidgameEndgame(boardPos) for move in possibleMovesList: minPos = self.minMax(move, depth) if v < self.staticEstimation(minPos): v = self.staticEstimation(minPos) if self.minimax_estimate != 10000 or self.minimax_estimate != -10000: self.minimax_estimate = v maxChoice = move return maxChoice elif depth==0: self.positionsEvaluated += 1 return boardPos def minMax(self, boardPos, depth): ''' Return the best move for the MIN player. ''' minChoice: str if depth > 0: depth -= 1 v = math.inf # find all possible moves possibleMovesList = self.generateMovesMidgameEndgame(boardPos) for move in possibleMovesList: maxPos = self.maxMin(move, depth) if v > self.staticEstimation(maxPos): v = self.staticEstimation(maxPos) minChoice = move return minChoice elif depth==0: self.positionsEvaluated += 1 return boardPos def staticEstimation(self, boardPos): ''' Calculate the static estimation of the position. ''' numWhitePieces = 0 numBlackPieces = 0 numBlackMoves = len(self.generateBlackMoves(boardPos)) for value in boardPos: if value=='W': numWhitePieces += 1 elif value=='B': numBlackPieces += 1 if numBlackPieces <= 2: return 10000 elif numWhitePieces <= 2: return -10000 elif numBlackPieces == 0: return 10000 else: return (1000*(numWhitePieces - numBlackPieces) - numBlackMoves) def generateBlackMoves(self, boardPos): ''' Generate all possible moves for black pieces. ''' copyBoardPos = list(boardPos) for location, value in enumerate(copyBoardPos): if value == 'W': copyBoardPos[location] = 'B' elif value == 'B': copyBoardPos[location] = 'W' blackMoves = self.generateMovesMidgameEndgame(''.join(copyBoardPos)) finalBlackMoves = [] for move in blackMoves: moveList = list(move) for loc, value in enumerate(moveList): if value == 'B': moveList[loc] = 'W' elif value == 'W': moveList[loc] = 'B' finalBlackMoves.append(''.join(moveList)) return finalBlackMoves def checkForWin(self): if self.minimax_estimate == 10000: print('Congratulations! WINNER WINNER CHICKEN DINNER') miniMaxGameBlack = MiniMaxGameBlack() morrisVariantUtil = MorrisVariantUtil() boardPosition = morrisVariantUtil.readInputFile(miniMaxGameBlack.inFile) swappedBoardPosition = morrisVariantUtil.swapWhiteAndBlack(boardPosition) generatedPosition = miniMaxGameBlack.maxMin(swappedBoardPosition, miniMaxGameBlack.depth) blackPosition = morrisVariantUtil.swapWhiteAndBlack(generatedPosition) print(f'Input position: {boardPosition} Output position: {blackPosition}') print(f'Position evaluated by static estimation: {miniMaxGameBlack.positionsEvaluated}') print(f'MINIMAX Estimate: {miniMaxGameBlack.minimax_estimate}') morrisVariantUtil.writeOutputFile(miniMaxGameBlack.outFile, blackPosition) miniMaxGameBlack.checkForWin()
903829614c956754ed01ac04660976cc4b93c900
gkqha/string-similarity-python
/string-similarity.py
2,602
3.640625
4
import re from typing import Dict def compare_two_strings(first: str, second: str) -> float: first = re.sub("\s", "", first) second = re.sub("\s", "", second) if len(first) == 0 and len(second) == 0: return 1 if len(first) == 0 or len(second) == 0: return 0 if first == second: return 1 if len(first) == 1 and len(second) == 1: return 0 if len(first) < 2 or len(second) < 2: return 0 first_bigrams: Dict[str, int] = {} for i in range(0, len(first) - 1): bigram = first[i : i + 2] count = first_bigrams[bigram] + 1 if bigram in first_bigrams.keys() else 1 first_bigrams[bigram] = count intersection_size = 0 for i in range(0, len(second) - 1): bigram = second[i : i + 2] count = first_bigrams[bigram] if bigram in first_bigrams.keys() else 0 if count > 0: first_bigrams[bigram] = count - 1 intersection_size += 1 print(first_bigrams) return (2.0 * intersection_size) / (len(first) + len(second) - 2) def find_best_match(main_string: str, target_strings: list): if are_args_valid(main_string, target_strings) != True: raise Exception( "Bad arguments: First argument should be a string, second should be an array of strings" ) ratings = [] best_match_index = 0 for i in range(len(target_strings)): current_target_string = target_strings[i] current_rating = compare_two_strings(main_string, current_target_string) ratings.append({"target": current_target_string, "rating": current_rating}) if current_rating > ratings[best_match_index]["rating"]: best_match_index = i best_match = ratings[best_match_index] return ratings, best_match, best_match_index def flatten_deep(arr: list): return ( [item for sublist in arr for item in sublist] if isinstance(arr, list) else [arr] ) def are_args_valid(main_string: str, target_strings: list) -> bool: if not isinstance(main_string, str): return False if not isinstance(target_strings, list): return False if len(target_strings) == 0: return False if [x for x in target_strings if not isinstance(x, str)] != []: return False return True def letter_pairs(str: str) -> list: pairs = [] for i in range(0, len(str) - 1): pairs.append(str[i : i + 2]) return pairs def word_letter_pairs(str: str): pairs = list(map(letter_pairs, str.upper().split(" "))) return flatten_deep(pairs)
db4acac2dc9940b957c6c612d2378a7ab9d928d2
jasongros619/Project-Euler
/21 - 30/Euler_029 Distinct powers.py
459
3.546875
4
import time start=time.clock() import math nums={} for a in range(2,101): for b in range(2,101): #find log( a^b ) rounded at the 10th decimal place #check if you have already calculated this number before log_base = int( math.log( a ) * b * 10**10 ) #check in constant time if nums.get(log_base,None)==None: nums[log_base]=True print("Answer",len(nums),"computed in",(time.clock()-start)*1000,"ms")
530e823fc12d6592f9572406f4332c53909a5086
padmajalanka/tutorials
/homework/relarningfunctions.py
1,373
4.09375
4
print("&&&&&&&&&&&&&&&&&&&Functions&&&&&&&&&&&&") # or topic = "functions" print(topic.center(55, '$')) def my_name(): print("Hello my name is Padmaja") my_name() #function with arguments def my_name(firstname): print(firstname + "lanka") my_name("Raju") my_name("Padmaja") my_name("Viswanath") my_name("Sriram") ##Python Builtin functions #absolute function :returns absolute value of the specified number. #SYNTAX is abs(n) x = abs(3+5j) print(x) x = abs(-7) print(x) x = abs(-10.5) print(x) ###all() # the all() function returns true if all items in an iterable are true # otherwise it returns false. #if iterable item is empty it returns true. mylist = [True,True,True] print(all(mylist)) #ascii() normaltext = 'Python is interesting' print(ascii(normaltext)) othertext = 'python is interesting' print(ascii(othertext)) ###enumerate() function takes a collection and returns enumerate object #Syntax = enumerate(iterable, start) x = ('apple','banana','cherry') print(type(enumerate(x))) print(list(enumerate(x))) print(list(enumerate(x,10))) grocery = ['flowers','vegetables','fruits'] enumerateGrocery = enumerate(grocery) print(type(enumerateGrocery)) print(list(enumerateGrocery)) enumerateGrocery = enumerate(grocery, 10) print(list(enumerateGrocery)) ##id() returns unique id for the specified object x = ('apple''banana','cherry') print(id(x)) ##
69e624a39593cbe0ebe0c046126d0dcf53f63984
HTaylor7486/projects
/projects/cam/GH/guesswho.py
3,027
3.59375
4
import picamera,time,json#imports moduals def getpic(name="null"):#defines function try:#trys to run code block with picamera.PiCamera() as camera:#runs code block with the pi cam q = "n"#sets q to n while q == "n":#starts loop camera.start_preview()#starts cam preview time.sleep(3)#pauses the program camera.capture("{0}.jpeg".format (name))#takes a pic with and sets it to name.jpeg camera.stop_preview()#stops cam preview q = input("is the image okay? (y/n) ")#sets q to user input filename = ("{0}.jepg".format (name))#sets file name to name.jepg print("Your file is called {0}.jpeg".format (name))#prints message return filename except picamera.exc.PicameraMMALError:#if code block gives this error run block beneath print("Your camera is not working please connect and restart the program")#prints message def getchar():#defines function name = "h"#sets name to nothing while name == "": #checks to see#checks if name is = to nothing name = input("what is your name?")#prints message hair = "blonde"#sets hair to nothing while not hair in ["blonde","brown","ginger","no hair"]:#checks to see if hair is = to something on a list hair = input ("what hair colour do you have? (blonde/brown/ginger/no hair)")#sets hair to user input hat = "y"#sets hat to nothing while not hat in ["y","n"]:#checks to see if hat is = to something on a list hat = input("do you have a hat? (y/n)")#sets hat to user input eye = "green"#sets eye to nothing while not eye in ["green","brown","blue"] :#checks to see if eye is = to something on a list eye = input("what is your eye colour")#sets eye to user input gender = "m"#sets gender to nothing while not gender in ["m","f"] :#checks to see if gender is = to something on a list gender = input("what is your gender?(m/f)")#sets gender to user input fhair = "n"#sets fhair to nothing while not fhair in ["y","n"]:#checks to see if fahir is = to something on a list fhair = input("do you have facial hair?(y/n)")#sets fhair to user input glass = "y"#sets glass to nothing while not glass in ["y","n"]:#checks to see if glass is = to something on a list glass = input("do you have glasses?(y/n)")#sets glass to user input charprof = [name,hair,hat,eye,gender,fhair,glass]#sets charprof to list of all chars getpic(name)#runs getpic wit name return charprof def save(x): prof = getchar() x.append(prof) with open("profiles.txt",mode = "w") as my_file: json.dump(charprof,my_file) def load(): try: with open("profiles.txt",mode = "r") as my_file: charprof = json.load(my_file) except IOError: print("No profiles found, making new") charprof = [] print(charprof) return charprof charprof = load() save(charprof)
75e9aef11f7bfb650fe27051f89a6d6e97b12f69
ToddDiFronzo/cs-module-project-recursive-sorting
/src/searching/searching.py
2,480
4.46875
4
# TO-DO: Implement a recursive implementation of binary search def binary_search(arr, target, start, end): # base case # we'll stop when we either find target, # i.e, when left > right and we did not find the target if start > end: return -1 # how do we move closer to a base case?or we search the whole array else: mid = (start + end) // 2 if arr[mid] == target: return mid elif arr[mid] < target: # rule out the left side return binary_search(arr, target, mid+1, end) else: # rule out the right side return binary_search(arr, target, start, mid-1) arr = [3, 4, 6, 16, 26, 28, 52, 55] print(binary_search(arr, 52, 0, len(arr)-1)) # STRETCH: implement an order-agnostic binary search # This version of binary search should correctly find # the target regardless of whether the input array is # sorted in ascending order or in descending order # You can implement this function either recursively # or iteratively # Descending binary search def descending_binary_search(arr, target, left, right): if left > right: return -1 else: mid = (left + right) // 2 if arr[mid] == target: return mid elif arr[mid] < target: # rule out the right side return descending_binary_search(arr, target, left, mid-1) else: # rule out the left side return descending_binary_search(arr, target, mid+1, right) # Test it out # arr = [101, 99, 87, 76, 66, 65] # print('Desc: ', descending_binary_search(arr, 101, 0, len(arr)-1)) def agnostic_binary_search(arr, target): # figure out whether the input array is sorted in ascending or descending order # keep a boolean to indicate the order of the array # compare arr[0] and arr[1] if arr[0] > arr[-1]: is_ascending = False else: is_ascending = True # if the input array is ascending, call our normal 'binary_search' with the array # and target if is_ascending: return binary_search(arr, target, 0, len(arr)-1) # otherwise, call 'descending_binary_search' with the array and target else: return descending_binary_search(arr, target, 0, len(arr)-1) # Test it print("Agnostic Ascending: ", agnostic_binary_search([1,3,5,6,8,21], 8)) print("Agnostic Descending: ", agnostic_binary_search([101, 99, 87, 76, 66, 65], 66))
00b2924949761fe875cd8cea8920d1663d92963d
Hachimaki/adventofcode2019
/src/day2/prompt_2.py
4,876
3.78125
4
# On the way to your gravity assist around the Moon, your ship computer beeps angrily about a "1202 program alarm". # On the radio, an Elf is already explaining how to handle the situation: "Don't worry, that's perfectly norma--" The # ship computer bursts into flames. # # You notify the Elves that the computer's magic smoke seems to have escaped. "That computer ran Intcode programs like # the gravity assist program it was working on; surely there are enough spare parts up there to build a new Intcode # computer!" # # An Intcode program is a list of integers separated by commas (like 1,0,0,3,99). To run one, start by looking at the # first integer (called position 0). Here, you will find an opcode - either 1, 2, or 99. The opcode indicates what to # do; for example, 99 means that the program is finished and should immediately halt. Encountering an unknown opcode # means something went wrong. # # Opcode 1 adds together numbers read from two positions and stores the result in a third position. The three integers # immediately after the opcode tell you these three positions - the first two indicate the positions from which you # should read the input values, and the third indicates the position at which the output should be stored. # # For example, if your Intcode computer encounters 1,10,20,30, it should read the values at positions 10 and 20, add # those values, and then overwrite the value at position 30 with their sum. # # Opcode 2 works exactly like opcode 1, except it multiplies the two inputs instead of adding them. Again, the three # integers after the opcode indicate where the inputs and outputs are, not their values. # # Once you're done processing an opcode, move to the next one by stepping forward 4 positions. # # For example, suppose you have the following program: # # 1,9,10,3,2,3,11,0,99,30,40,50 # # For the purposes of illustration, here is the same program split into multiple lines: # # 1,9,10,3, # 2,3,11,0, # 99, # 30,40,50 # # The first four integers, 1,9,10,3, are at positions 0, 1, 2, and 3. Together, they represent the first opcode (1, # addition), the positions of the two inputs (9 and 10), and the position of the output (3). To handle this opcode, you # first need to get the values at the input positions: position 9 contains 30, and position 10 contains 40. Add these # numbers together to get 70. Then, store this value at the output position; here, the output position (3) is at # position 3, so it overwrites itself. Afterward, the program looks like this: # # 1,9,10,70, # 2,3,11,0, # 99, # 30,40,50 # # Step forward 4 positions to reach the next opcode, 2. This opcode works just like the previous, but it multiplies # instead of adding. The inputs are at positions 3 and 11; these positions contain 70 and 50 respectively. Multiplying # these produces 3500; this is stored at position 0: # # 3500,9,10,70, # 2,3,11,0, # 99, # 30,40,50 # # Stepping forward 4 more positions arrives at opcode 99, halting the program. # # Here are the initial and final states of a few more small programs: # # 1,0,0,0,99 becomes 2,0,0,0,99 (1 + 1 = 2). # 2,3,0,3,99 becomes 2,3,0,6,99 (3 * 2 = 6). # 2,4,4,5,99,0 becomes 2,4,4,5,99,9801 (99 * 99 = 9801). # 1,1,1,4,99,5,6,0,99 becomes 30,1,1,4,2,5,6,0,99. # # Once you have a working computer, the first step is to restore the gravity assist program (your puzzle input) to the # "1202 program alarm" state it had just before the last computer caught fire. To do this, before running the program, # replace position 1 with the value 12 and replace position 2 with the value 2. What value is left at position 0 after # the program halts? def add(arg1, arg2): return arg1 + arg2 def multiply(arg1, arg2): return arg1 * arg2 # gets a list of operands and performs instructions on them def main(operands): pc = 0 # store current program counter operator = operands[pc] while operator is not 99: if operator == 1: input[input[pc + 3]] = add(input[pc + 1], input[pc + 2]) elif operator == 2: input[input[pc + 3]] = multiply(input[pc + 1], input[pc + 2]) else: print(f"Something went wrong at operator {pc}: {operator}") break # somehow we got a non-default operator (probably means something went wrong pc += 4 operator = operands[pc] return if __name__ == "__main__": with open('prompt_2_test_1.txt') as input_file: # get a list of ints as strings representing the operands for the intcode processor # each entry is one operand, delimited by comma (no whitespace) input = input_file.readline().split(',') input_file.close() # need to convert all string entries to ints to properly operate for i in range(0, len(input)): input[i] = int(input[i]) main(input) print(f"Final input: {input}")
db8b3efdc4ce31f8bd9789ecd094c1a89b2fd54a
stavitska/amis_python71
/km71/Pashchenko_Kateryna/4/task12.py
148
3.59375
4
n = int(input()) m = int(input()) k = int(input()) if ((k%n == 0) or(k%m == 0)): answer = 'YES' else: answer = 'NO' print(answer)
5ff4f907c799a8621c6c61a5652db638490ac0ce
Arkinee/BOJ
/백준(9020).py
423
3.53125
4
t = int(input()) primes = [] def is_prime(x): for i in range(2, x): if x % i == 0: return False return True for i in range(2, 10001): if is_prime(i): primes.append(i) #print(primes) for i in range(t): n = int(input()) for x in range(len(primes)): if primes[x] > n: break if n - primes[x] in primes:
f31dfbf7201e1d3b4c1f9f94ec72916ca8284a23
Aditya8821/Python
/Python/Mini Projects/Rolling_Dice.py
277
4.15625
4
import random roll_again="yes" while roll_again=="yes" or roll_again=="y": print("Rolling Dices......") print("The Values are.....") print("=>",random.randint(1,6)) print("=>",random.randint(1,6)) roll_again=input("Want to roll the Dices again? ")
9d6dabf17eaf1e4bc98ff3c8f450a8d51a853f74
sandovbarr/holberton-system_engineering-devops
/0x15-api/0-gather_data_from_an_API.py
1,786
3.703125
4
#!/usr/bin/python3 ''' Python script that, using this REST API, for a given employee ID, returns information about his/her TODO list progress. You must use urllib or requests module The script must accept an integer as a parameter, which is the employee ID The script must display on the standard output the employee TODO list progress in this exact format: First line: Employee EMPLOYEE_NAME is done with tasks (NUMBER_OF_DONE_TASKS/TOTAL_NUMBER_OF_TASKS): EMPLOYEE_NAME: name of the employee NUMBER_OF_DONE_TASKS: number of completed tasks TOTAL_NUMBER_OF_TASKS: total number of tasks, which is the sum of completed and non-completed tasks Second and N next lines: display the title of completed tasks: Tab TASK_TITLE (with 1 tabulation + 1 space before) ''' import requests from sys import argv try: int(argv[1]) id_user = argv[1] user_data = requests.get( 'https://jsonplaceholder.typicode.com/users/{}'.format(id_user)) user_tasks = requests.get( 'https://jsonplaceholder.typicode.com/todos', params={ 'userId': id_user}) username = user_data.json()['name'] user_tasks_json = user_tasks.json() tasks_completed = [] total_tasks = len(user_tasks_json) for task in user_tasks_json: if task['completed']: tasks_completed.append(task['title']) print('Employee {} is done with tasks({}/{}):'.format(username, len(tasks_completed), total_tasks)) for task in tasks_completed: print('\t {}'.format(task)) except Exception: print('Not a valid argument')
a2338bdb5c7c86410088557fb4fc699e565e4a6f
lacklust/coding-winter-session
/notes/week_3/adv_while_loops.py
1,857
4.40625
4
""" we have dealt with while loops so far, but note: there is always danger with while loops that the condition associated with the while loop will never terminate (aka evaluate to False) if that happens, the loop will continue running forever --> we call this an infinite loop if you do end up with an infinite loop, you can force python to break out of it by hitting ctrl-c on your keyboard or the little stop button on the run console while True: print("okok") """ """ there are two special commands (keywords) called --> break --> continue you can use inside of a while loop to further control the flow of repetition these commands can only be used inside of a loop; they won't work anywhere else inside of your program """ """ break command: this is used to immediately end the loop once a break statement is encountered, the loop immediately stops and python resumes execution on the line directly after the end of the loop """ # # create a counter variable # counter = 0 # # # enter an infinite loop # while True: # # add 1 to our counter variable # counter += 1 # print(f"counter is at {counter}") # if counter >= 5: # print("breaking the loop!!!") # break """ continue command: this is used to cause the loop to immediately cease its current iteration and re-evaluate its boolean-condition the continue command does not end the loop - it simply causes the loop to "jump" to the next iteration if the condition evaluates to True, the loop iterates again, but if it evaluates to False, it will not """ counter = 0 while counter < 100: # add 1 to our counter variable counter += 1 if counter % 2 == 0: print("even number!!!") continue # if counter >= 100: # print("breaking the loop") # break print(f"counter is {counter}")
af26901d2ef07d36e50ebfcdcc6fc46d036b8763
JIbitesh07/check_a_num_armstrong.py
/armstrong.py
261
3.75
4
n=int(input("enter a number")) sum=0 t=n c=0 while(t>0): c=c+1 t=t//10 t=n while(t>0): d=t%10 sum=sum+d**c t=t//10 print(sum) if(n==sum): print(n,"its a armstrong number") else: print(n,"Its not armstrong number")
1f3717dc30f96dcc84999567928657dc58d77978
archphy/numerical-methods-python
/matrix_operations.py
2,638
3.78125
4
# commonly required basic operations for matrices from numpy import array from numpy import dot from numpy import identity from numpy import zeros from numpy import arange # matrix multiplication def matrix_product(a, b): return a*b # matrix addition def matrix_sum(a,b): return a+b # matrix subtraction def matrix_diff(a,b): return a-b # matrix transpose def transpose(a): if not check_1D(a): return a.T else: pShape = [a.shape[0],1] p = zeros(pShape) for i in xrange(0,pShape[0]): p[i][0] = a[i] return p def check_symmetry(a): if a.shape[0] != a.shape[1]: return False elif matrix_equality(a, transpose(a)): return True else: return False def check_positive_definite(a): X = arange(a.shape[0]) Y = dot(dot(X,a),transpose(X)) > 0 return Y[0] # matrix check diagonally_dominant def matrix_check_diagonally_dominant(a): pass # matrix check orthogonal def matrix_check_orthogonal(a): pass # matrix check singular def matrix_check_singular(a): pass # matrix equality def matrix_equality(a,b): c = (a==b) for k in c: for j in k: if not j: return False return True # print matrix elements without '[' def matrix_print(a): for x in xrange(a.shape[0]): for y in xrange(a.shape[1]): print '%.4f' % a[x][y] # infinity norm of the matrix def infinity_norm(a): pass # euclidean norm of the matrix def euclidean_norm(a): pass # L1 norm of the matrix def l1_norm(a): pass # check if matrix is upper triangular def check_upper_triangular(a): pass # check if 1D array def check_1D(a): try: a.shape[1] return False except IndexError: return True # augmented matrix def augmented_matrix(a,b): pShape = [0,0] if a.shape[0] == b.shape[0]: pShape[0] = a.shape[0] pShape[1] = a.shape[1] + b.shape[1] p = zeros(pShape) for i in xrange(0,a.shape[0]): for j in xrange(0,a.shape[1]): p[i][j] = a[i][j] for i in xrange(0,a.shape[0]): for j in xrange(0,b.shape[1]): p[i][j+a.shape[1]] = b[i][j] return p else: print 'check dimensions of the input arrays' # swapping rows def swap_rows(a,i,j): n = a.shape[1] for k in xrange(n): temp = a[i][k] a[i][k] = a[j][k] a[j][k] = temp return a def testing_function(a,b): if a==b: print 'Passed _/' else: print 'Failed X' def test_all(): A = array([[1,2],[3,4]]) B = array([[1,3],[5,7]]) C = array([[11,17],[23,37]]) D = array([[1,2],[3,4],[5,6]]) E = array([1,2,3,4]) F = array([[1,2,3],[2,4,5],[3,5,6]]) P = array([[24,20,-12],[20,25,-16],[-12,-16,5]]) Q = array([[1.44,-0.36,5.52,0],[-0.36,10.33,-7.78,0],[5.52,-7.78,28.4,9],[0,0,9,61]]) print check_positive_definite(Q) test_all()
48d749151ff0c88365bef872e3d61f5d8c82874a
taylorchen78/To_Lower_Case
/main.py
243
3.96875
4
""" Implement function ToLowerCase() that has a string parameter str, and returns the same string in lowercase. """ def toLowerCase(str): return str.lower() print(toLowerCase("Hello")) print(toLowerCase("here")) print(toLowerCase("LOVELY"))
4e183023c0d1efb555734929671ae5c08df2ad50
ronliang6/A01199458_1510
/Lab02/base_conversion.py
1,935
4.4375
4
""" Convert a base 10 number to a number in a different base. """ def base_conversion(): """Convert a base 10 number to another base in the range [2, 9]. Given the number of bits and the destination base, the maximum base ten number is determined. Given a number no larger than the maximum number, the new number is calculated digit by digit and returned. :return: the converted number as a string """ destination_base = int(input("Please enter the base destination, a number between 2 and 9, inclusive")) maximum_base10_number = maximum_number(destination_base, 4) print("The maximum base 10 number that can be converted is " + str(maximum_base10_number)) number_to_convert = int(input("Please enter a number that is less than or equal to " + str(maximum_base10_number))) digit_first = number_to_convert % destination_base quotient_first = number_to_convert // destination_base digit_second = quotient_first % destination_base quotient_second = quotient_first // destination_base digit_third = quotient_second % destination_base quotient_third = quotient_second // destination_base digit_fourth = quotient_third % destination_base new_number = str(digit_fourth) + str(digit_third) + str(digit_second) + str(digit_first) return new_number def maximum_number(destination_base, bits): """ Calculate the maximum base 10 number that you can convert given the destination base and the number of bits. :param destination_base: the destination base that the answer will be in as a positive integer :param bits: the number of bits that the answer will be in as a positive integer :return: the maximum base 10 number possible to convert as an integer """ return pow(destination_base, bits) - 1 def main(): """Call and print the base_conversion function.""" print(base_conversion()) if __name__ == "__main__": main()
b679baf49d42c66d3e01fbee3191cb87a2211ad5
srinathsibi/NightwingAnalysis
/BackupFiles.py
1,508
3.78125
4
#Author : Srinath Sibi #Email : ssibi@stanford.edu #Purpose : This script is meant to copy files to the external hard drive or any other drive that the user choses. import csv, os, shutil, platform #Function to check if the folder already exists in the External Drive ProcessedData Folder def checkandcopy(folder): print "Checking for folder : ", folder if not os.path.exists(PATH+folder): #os.makedirs(PATH+folder)#Create the folder for the first time shutil.copytree(folder+'/ClippedData',PATH+folder)#Copying the Data from the processing folder else: shutil.rmtree(PATH+folder) shutil.copytree(folder+'/ClippedData',PATH+folder)#Copying the Data from the processing folder #Main Function if __name__=='__main__': print " Copying ClippedData Folders to the external Drive" if platform.system() == 'Linux': PATH = '/media/srinathsibi/Seagate Backup Plus Drive/ProcessedData/' elif platform.system() == 'Windows': PATH = 'E:/ProcessedData/' else: print "Unknown OS" raise SystemExit print "Path to backup folder: \n", PATH #NOTE: The ClippedData Folder in each participant will be copied to the External Drive under the ProcessedData folder. #Shifting to the Data Folder os.chdir('Data/') listoffolders = os.listdir('.') for folder in listoffolders: if int(folder[1:4]) <= 100 and int(folder[1:4])>=0:#Way to curtail the folders that are copied checkandcopy(folder) print "\n"
2c383e940e5ca2337e96a31b57005726349cc0f6
matheusfelipeog/uri-judge
/categorias/iniciante/uri1045.py
488
3.890625
4
# -*- coding: utf-8 -*- valores = list(map(float, input().split())) valores.sort(reverse=True) a, b, c = valores if a >= b + c: print('NAO FORMA TRIANGULO') elif (a ** 2) == (b ** 2 + c ** 2): print('TRIANGULO RETANGULO') elif (a ** 2) > (b ** 2 + c ** 2): print('TRIANGULO OBTUSANGULO') elif (a ** 2) < (b ** 2 + c ** 2): print('TRIANGULO ACUTANGULO') if a == b == c: print('TRIANGULO EQUILATERO') elif a == b or b == c or a == c: print('TRIANGULO ISOSCELES')
db70121ec4c26d8f6c0d31ad3adea4b1961b4cd5
SandeepKiran089/Data-science
/Basic_Python2.py
4,429
4.28125
4
# Data type : """ python is loosley typed language therefor no need to define the datatype of Variables no need to declare variables before using them in code. Datatypes: immutable and mutable immutable - 1 number 2 string 3 tuples mutable - 1 list 2 dictionaries 3 set """ x=11 y=11.26 # String : It is useful thing of a string as an ordered sequence string="Sandeep" print(x) print(y) print(string) # In python we can change the type of expresion in python this is called typecasting # We can convert them into float and vise versa print(float(x)) print(int(y)) print("================================\n") # len() command is used to obtain the lenght of string print(len(string)) name="Sandeep Kumar" # As string stored as sequesnce or in array form we can fetch each elements or each character from string using slicing methods # if we want to get each 2 character print(name[::2]) # to get the character from a certain position (starting from 0 till 5,each 2nd) print(name[0:5:2]) # string is immutable # name[0]='x' # we get an item assigment error # escape sequence character - escape sequence are strings that are difficutl to input print("for new line \n") print("for tab \t") print("for slace \\") print(name.upper()) print(name.lower()) print(name.replace("e","i",2)) print(name.split(" ")) # tuple # tuples are data struckture that store an ordered sequence of values # tuples are immutable, this means you can not change the values # tuples can be defined using parenthesis () print("===============================================") name=("Sandeep","Kumar",'Singh') # join function - it work with strings """Concatenate any number of strings. The string whose method is called is inserted in between each given string. The result is returned as a new string.""" print(".".join(name)) print("===========================") name="Sandeep" print(name.find('eep')) mytuple=(1,2,3,4,5,6) print(mytuple) ice_cream_flavor=('Chocolate', 'Vanilla', 'Mint', 'Strawberry', 'Choc-Chip',[10,20]) print(ice_cream_flavor[0]) print(ice_cream_flavor[5]) print(ice_cream_flavor[-3]) print(ice_cream_flavor[1:4]) print("===================Conditional Statement (if...elif....else)=====================") ss=" mY text {}" print("{0},{0},{1}".format("Test","Test1")) if ice_cream_flavor[2]=='Mint': print("I Like {0} falavor most....!".format(ice_cream_flavor[2])) else: print("I don't like any other flavor...!") if ice_cream_flavor[1]!='Vanilla': if ice_cream_flavor[2]=='Mint': print("We got the mint flavor") elif ice_cream_flavor[1]=='Vanilla': print("I would like to have Vanilla") else: print("No match found....!") for items in ice_cream_flavor: print(items) my_favrate_books=['You can win','7 habits','the alchemist',[300,200,100],(1,2,3)] print(my_favrate_books) print("My favorate books name is {} and the price is {}...".format(my_favrate_books[1],my_favrate_books[3][1])) print(my_favrate_books[4][2]) # Use sorted, pop, append and extend function print(sorted([1,6,9,55,32,3,27])) print(my_favrate_books.pop(3)) #my_favrate_books=my_favrate_books.pop(3) #my_favrate_books=sorted(my_favrate_books) print(my_favrate_books) my_favrate_books[3]='Meluha by Amish' print(my_favrate_books) lst=['M','F'] my_favrate_books.append(lst) print(my_favrate_books) lst=[21,'M','F',21] my_favrate_books.extend(lst) print(my_favrate_books) # List comprehension # Normal way is append new_lst=[2,3,4,5,6,7,8,9] res=[] for num in new_lst: if num%2==0: res.append(num) print(res) i=0 while i<len(new_lst): res.append(new_lst[i]**2) i+=1 print(res) a=list([x%2==0 for x in new_lst]) print([x**2 for x in new_lst]) print("+++++++++++++++++++++++++++++++++++++++++++++++++++++") numSequence=[1,2,3] mapval=tuple(map(lambda x:x*2, numSequence)) print(mapval) def mulby2(num): return num*2 newTuple=map(mulby2,numSequence) newTuple=tuple(newTuple) print(newTuple) def mapExmple(*string): var="" for i in string: var+=i*2 return var result=mapExmple("T","E","X","T") print(result) exm_tuple=("T","E","X","T") result=list(map(mapExmple,exm_tuple)) print(result) print("-----End-----")
6e5530b9167cad43a5be511ab84c2809a3b75bb0
shuyirt/Leetcode
/[00430-M]Flatten a Multilevel Doubly Linked List/dfs.py
1,086
3.890625
4
""" # Definition for a Node. class Node: def __init__(self, val, prev, next, child): self.val = val self.prev = prev self.next = next self.child = child """ class Solution: def flatten(self, head: 'Node') -> 'Node': if not head: return head queue = [head] pre = cur = None while len(queue): pre = cur cur = queue.pop() if pre and pre.child == cur: pre.next = cur cur.prev = pre pre.child = None elif cur.prev != pre: cur.prev = pre pre.next = cur if cur.next: queue.append(cur.next) if cur.child: queue.append(cur.child) return head # Runtime: 32 ms, faster than 79.41% of Python3 online submissions for Flatten a Multilevel Doubly Linked List. # Memory Usage: 14 MB, less than 100.00% of Python3 online submissions for Flatten a Multilevel Doubly Linked List. # method: dfs
532c64346cfe6d3b51a9df787f93d08fd2f96de3
manishhedau/Python-Projects
/Tkinter/Calculator.py
3,301
4
4
from tkinter import * root = Tk() # window name root.title("Calculator") # entry box entry = Entry(root,width=40,borderwidth=5) entry.grid(row=0,column=0,columnspan=3,padx=10,pady=30) def Button_click(number): # entry.delete(0,END) current = entry.get() entry.delete(0,END) entry.insert(0,str(current) + str(number)) def Button_clear(): entry.delete(0,END) def Button_add(): first_number = entry.get() global f_num global math math = "Addition" f_num = int(first_number) entry.delete(0,END) def Button_equal(): second_number = entry.get() entry.delete(0,END) if math == "Addition": entry.insert(0,f_num+int(second_number)) if math == "Subtaction": entry.insert(0,f_num-int(second_number)) if math == "Multiply": entry.insert(0,f_num*int(second_number)) if math == "Devide": entry.insert(0,f_num/int(second_number)) def Button_subtract(): first_number = entry.get() global f_num global math math = "Subtraction" f_num = int(first_number) entry.delete(0,END) def Button_multiply(): first_number = entry.get() global f_num global math math = "Multiply" f_num = int(first_number) entry.delete(0,END) def Button_devide(): first_number = entry.get() global f_num global math math = "Devide" f_num = int(first_number) entry.delete(0,END) button1 = Button(root,text="1",padx=40,pady=20,command=lambda:Button_click(1)) button2 = Button(root,text="2",padx=40,pady=20,command=lambda:Button_click(2)) button3 = Button(root,text="3",padx=40,pady=20,command=lambda:Button_click(3)) button4 = Button(root,text="4",padx=40,pady=20,command=lambda:Button_click(4)) button5 = Button(root,text="5",padx=40,pady=20,command=lambda:Button_click(5)) button6 = Button(root,text="6",padx=40,pady=20,command=lambda:Button_click(6)) button7 = Button(root,text="7",padx=40,pady=20,command=lambda:Button_click(7)) button8 = Button(root,text="8",padx=40,pady=20,command=lambda:Button_click(8)) button9 = Button(root,text="9",padx=40,pady=20,command=lambda:Button_click(9)) button0 = Button(root,text="0",padx=40,pady=20,command=lambda:Button_click(0)) button_add = Button(root,text="+",padx=39,pady=20,command=Button_add) button_equal = Button(root,text="=",padx=87,pady=20,command=Button_equal) button_clear = Button(root,text='Clear',padx=79,pady=20,command=Button_clear ) button_subtract = Button(root,text="-",padx=40,pady=20,command=Button_subtract) button_multiply = Button(root,text="*",padx=42,pady=20,command=Button_multiply) button_devide = Button(root,text='/',padx=42,pady=20,command=Button_devide) # puts button on the screen button1.grid(row=3,column=0) button2.grid(row=3,column=1) button3.grid(row=3,column=2) button4.grid(row=2,column=0) button5.grid(row=2,column=1) button6.grid(row=2,column=2) button7.grid(row=1,column=0) button8.grid(row=1,column=1) button9.grid(row=1,column=2) button0.grid(row=4,column=0,columnspan=1) # symbols grids button_add.grid(row=5,column=0,columnspan=1) button_equal.grid(row=5,column=1,columnspan=2) button_clear.grid(row=4,column=1,columnspan=2) button_subtract.grid(row=6,column=0,) button_multiply.grid(row=6,column=1) button_devide.grid(row=6,column=2) root.mainloop()
8f1bb8b1286f133b6dc049cb28ecee57fe89ce90
Nehasuryaprakash/PESU-IO-SUMMER
/lecture3e.py
185
3.921875
4
s=input("enter the string") l=[] j=[] for i in s: l.append(i) if(i.isdigit()==True): j.append(i) if(l==j): print("the string is numeric") else: print("the string is not numeric")
c23e081385cf9a58b4dba60cfb3086fb82d4d3c5
Vaishnav95/bridgelabz
/linked_list_stock.py
2,233
3.953125
4
class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None self.count = 0 def add_to_list(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node self.count += 1 def delete_node(self, key): temp = self.head if temp is not None: if temp.data == key: self.head = temp.next temp = None self.count -= 1 return while temp is not None: if temp.data == key: break prev = temp temp = temp.next if temp is None: return 1 self.count -= 1 prev.next = temp.next temp = None def list_sorting(self): temp1 = self.head while temp1 is not None: temp = self.head while temp.next is not None: if temp.data > temp.next.data: tempo = temp.data temp.data = temp.next.data temp.next.data = tempo temp = temp.next temp1 = temp1.next def print_list(self): temp = self.head while temp: print(temp.data) temp = temp.next def return_list(self): temp = self.head final_list = [] while temp: final_list.append(temp.data) temp = temp.next return final_list def search(self, x): current = self.head while current is not None: if current.data == x: return True # data found current = current.next return False # Data Not found if __name__ == "__main__": list_stock = LinkedList() list_stock.add_to_list(1) list_stock.add_to_list(2) list_stock.add_to_list(3) list_stock.add_to_list(4) list_stock.add_to_list(5) print("\n") list_stock.print_list() list_stock.list_sorting() print("\n") list_stock.print_list()
68c4517ec44adc8e72ba7eeecd5f29f83891668d
mari00008/Python_Study
/Python_study/9.ファイルとディレクトリの操作/4.クラスの継承.py
1,614
4.40625
4
#!/usr/bin/env python # coding: utf-8 # In[3]: #Rectanglesクラスの定義 class Rectangles: def __init__(self, a, b): self.width = a self.length = b def area(self): return self.width * self.length #Rectanglesクラスを継承してRectangles_2クラスを作成 class Rectangles_2(Rectangles): #新しいメソッドの追加 def perimeter(self): return self.width * 2 + self.length * 2 #Rectangles_2クラスのインスタンスを生成 rec = Rectangles_2(5,10) #スーパークラスRectangleのメソッドを使用 print("面積",rec.area()) #サブクラスRectangle_2で追加されたメソッド print("周長",rec.perimeter()) # In[4]: #Rectanglesクラスを継承してRectangles_3クラスを作成 class Rectangles_3(Rectangles): #スーパークラスのarea()メソッドを上書き。 #上書きされたメソッドを実装するメソッドのオーバーライド def area(self): return "面積は" + str(self.width * self.length)+ "です。" #Rectangles_3のインスタンスを作成 rec = Rectangles_3(5,10) #上書きされたメソッドの使用 print(rec.area()) # In[5]: #Rectanglesクラスを継承してSquaresクラスを作成 class Squares(Rectangles): #super()関数でスーパークラスを呼び出し #初期化メソッドの引数a,bにxを渡す def __init__(self,x): super().__init__(x,x) #Squaresクラスのインスタンス作成 sq =Squares(10) #正方形の面積の計算 print(sq.area()) # In[ ]:
45380811f46415a72b622163aa0556b625422c33
charvi-a/hangman
/hangman.py
4,856
3.90625
4
import pycountry import random def hangman(): li = [] li1 = [] won = False for i in range(len(pycountry.countries)): li1 = (list(pycountry.countries)[i].name).split() if len(li1) == 1: li.append(list(pycountry.countries)[i].name) word_to_guess = random.choice(li) word_to_lower = word_to_guess.lower() no_of_guesses = 8 count = 0 display = "?" * len(word_to_lower) guessed = False correct_guesses = [] incorrect_guesses = [] print("WELCOME TO HANGMAN") print("RULES: ") print("---> The user is required to guess the name of the country within 8 guesses.") print("---> The user must enter a letter.") print("---> If the letter guessed is incorrect that is, it does not exist in the word to be guessed, then the number of guesses decreases.") print("---> Otherwise, if the letter guessed is correct then the position of the correct letter in the word to be guessed is displayed.") print("---> Once the number of guesses are over, the game ends.") print("********************************************************************") print("The word is: "+ display) while no_of_guesses > 0 and not guessed: guessed = False print("You have "+ str(no_of_guesses)+ " guesses left") if count > 0: print('***********************************************************') letter = input("Enter a letter in lowercase: ") if letter.isalpha() and letter.islower() and len(letter) == 1: if letter in word_to_lower and letter not in correct_guesses: print("The letter guessed was correct.") correct_guesses.append(letter) displaylist = list(display) index = [i for i,letter1 in enumerate(word_to_lower) if letter==letter1] for ind in index: displaylist[ind] = letter display = "".join(displaylist) print(display) count += 1 if no_of_guesses < 8: print(hanged(no_of_guesses)) if word_to_lower == display.lower(): guessed = True break continue elif letter in correct_guesses or letter in incorrect_guesses: print("You have already guessed this letter before.") else: no_of_guesses -= 1 incorrect_guesses.append(letter) if no_of_guesses == 0: break elif len(letter) == len(word_to_lower): if letter == word_to_lower: guessed = True break else: print("Sorry the word you guessed is incorrect") no_of_guesses -= 1 else: print("Please enter a valid letter as a guess") count += 1 if no_of_guesses != 8: print(hanged(no_of_guesses)) print(display) print("The incorrect guesses are:" + str(incorrect_guesses)) if guessed: print("You WON! CONGRATULATIONS! You have guessed the word") play() else: print(hanged(0)) print("You have "+ str(no_of_guesses)+ " guesses left") print("Sorry, the correct word was " + word_to_lower) play() def hanged(no_of_guesses1): hang_string = [ """ ------ | | | 0 | \\|/ | | | / \\ - """, """ ------ | | | 0 | \\|/ | | | / - """, """ ------ | | | 0 | \\|/ | | | - """, """ ------ | | | 0 | \\| | | | - """, """ ------ | | | 0 | | | | | - """ , """ ------ | | | 0 | | | | - """, """ ------ | | | 0 | | - """, """ ------ | | | | | | - """ ] return hang_string[no_of_guesses1] def play(): play_again = False let = input("Enter Y to play again and N to exit ") if let == 'Y' or let == 'y': print('***********************************************************') hangman() else: exit()
c7d102a8e7c0875fad3be840be2b004d64cbe36c
w4n9H/mark
/mark04.py
4,401
3.640625
4
""" py回炉计划,用来学习class类的,使用类的一些高级特性实现一个ORM """ class Field(object): __slots__ = ('max_length',) def __init__(self, max_length): self.max_length = max_length def __str__(self): return '<%s>' % self.__class__.__name__ __repr__ = __str__ # 通过 print(Field()) 直接显示 class StringField(Field): def __init__(self, max_length=32): super(StringField, self).__init__(max_length) class IntegerField(Field): def __init__(self, max_length=32): super(IntegerField, self).__init__(max_length) class ModelMetaclass(type): """ metaclass的类名总是以Metaclass结尾,必须从 type 类型派生 """ def __new__(cls, name, bases, attrs): """ __new__ 的调用在 __init__ 之前, 至少需要传递一个参数cls, cls表示需要实例化的类 __new__ 必须要有返回值,返回实例化出来的实例 :param name: 类的名字 :param bases: 类集成的父类集合 :param attrs: 类的方法集合 :return: """ if name == 'Model': return type.__new__(cls, name, bases, attrs) mappings = dict() for k, v in attrs.items(): # name <StringField:username> if isinstance(v, Field): # 继承至Field,使用isinstance也是返回True # print('Found mapping: %s ==> %s' % (k, v)) mappings[k] = v for k in mappings.keys(): attrs.pop(k) attrs['__mappings__'] = mappings # 保存属性和列的映射关系 attrs['__table__'] = name.lower() # 假设表名和类名一致 """ 关于 type() 和 type.__new__() 通过type()函数创建的类和直接写class是完全一样的。 type.__new__() 则是直接创建出一个类的实例 """ return type.__new__(cls, name, bases, attrs) # type()动态创建class class Model(dict, metaclass=ModelMetaclass): """ metaclass指示Py解释器在创建Model时,要通过ModelMetaclass.__new__()来创建 """ def __init__(self, **kw): super(Model, self).__init__(**kw) def __getattr__(self, key): # 动态返回属性 try: return self[key] except KeyError: raise AttributeError(r"'Model' object has no attribute '%s'" % key) def __setattr__(self, key, value): self[key] = value def save(self): fields = [] params = [] args = [] for k, v in self.__mappings__.items(): # fields.append(v.name) fields.append(k) params.append('?') args.append(getattr(self, k, None)) sql = """insert into %s (%s) values (%s)""" % (self.__table__, ','.join(fields), ','.join(params)) print('SQL: %s' % sql) print('ARGS: %s' % str(args)) def query(self, sql): # 假设结果为 print(sql) return QueryDict([dict(id=1, name='wang1', email='xxx1@qq.com', password='123456'), dict(id=2, name='wang2', email='xxx2@qq.com', password='123456')]) class QueryDict: def __init__(self, result): self.index = 0 if isinstance(result, dict): self.result = [result] if isinstance(result, list): self.result = result def __getitem__(self, n): # 把对象和实例当作list if isinstance(n, int): # n是索引 return self.result[n] if isinstance(n, slice): # n是切片 return self.result[n.start: n.stop] def __iter__(self): # 让对象和实例可以被迭代 return self # 实例本身就是迭代对象,故返回自己 def __next__(self): # 这地方有点bug啊,不能显示第一个 self.index += 1 if self.index >= len(self.result): raise StopIteration() return self.result[self.index] class User(Model): # 定义类的属性到列的映射: id = IntegerField() name = StringField(max_length=16) email = StringField() password = StringField() if __name__ == '__main__': db = User() # db.id = 1 # db.name = 'wang' # db.email = 'xxx@qq.com' # db.password = '123' # db.save() r = db.query('select * from user') print(r[0]) print(r[1]) for i in r: print(i)
fa6f28f3eb6e0bb30ceae6914f49828d6830018a
TristanBo15/Tarea1BodraFallas
/métodos.py
2,809
3.9375
4
# TAREA 1 microprocesadores y microcontroladores # Profesor: Rodolfo Piedra Camacho # Estudiantes: Tristan B. J. y Jesús F. B. # Fecha: 02/27/2021 # Método "check_char" x = "A" # Se define el parámetro de entrada def check_char(x): '''Primero verificamos si la entrada es un string o se encontro un error #3''' if type(x) ! = str: return("Error #3") ''' Si es un string, se pasa a otro filtro, donde se define un contador "count" para la longitud de la cadena y un contador "Fuera_Rango" para saber si la cadena esta en el rango de A-Z o a-z''' else: cont = 0 Fuera_Rango = 0 ''' Luego, se recorre el string con un for y se asigna un ascii a cada caracter y se revisa que a esté en los rangos de las letras dadas''' for i in x: cont = cont + 1 a = ord(i) if((a >= 0) and (a < 65)) or ((a >= 91) and (a <= 96)) or ((a >= 123) and (a <= 127)): Fuera_Rango = Fuera_Rango + 1 ''' Una vez se tienen los valores de "Fuera_Rango" y "cont", se proceden a comparar según corresponde, para identificar los dos errores faltantes, Error #2 si el string no está en el rango solicitado, o Error #1 si el string posee más de 1 caracter, si no cumple con las condiciones de los errores, retorna un 0, que sería una entrada string de 1 caracter en el rango''' if Fuera_Rango >= 1: return("Error #2") elif cont > 1: return("Error #1") else: return 0 print(check_char(x)) '''Definimos el parametro de entrada del método caps_switch como un string''' y = "A" '''método caps_switch: si recibe un único caracter dentro de los rangos A-Z o a-z devuelve el caracter en minúscula si es mayúscula y viceversa''' def caps_switch(y): '''llamamos al método check_char asignandolo a la variable c y comprueba que la entrada sea un único caracter dentro de alguno de los rangos deseados''' c = check_char(y) if c == 0: '''si el caracter es minúscula retorna su equivalente en mayuscula''' if y.islower(): u = ord(y) u2 = u - 32 return(chr(u2)) '''si el caracter es mayúscula retorna su equivalente en minuscula''' elif y.isupper(): v = ord(y) v2 = v + 32 return(chr(v2)) '''si no se cumplen las condiciones descritas anteriormente, la función retorna un error según check_char''' else: return(c) print(caps_switch(y)) '''imprime el resultado del método caps_switch'''
7488518bd1c6ad6778022c0f70eec312be866d5b
AFranco92/pythoncourse
/controlstatements/homework.py
454
4.21875
4
maths = int(input("Enter maths marks: ")) physics = int(input("Enter physics marks: ")) chemistry = int(input("Enter chemistry marks: ")) if maths >= 35 and physics >= 35 and chemistry >= 35: print "You have passed the exam!" average = (maths+physics+chemistry)/3 if average <= 59: print "You got a C." elif average <= 69: print "You got a B." else: print "You got a A." else: print "You failed the exam."
23726e73b0294f5caedcff761b48cd4d4884431c
Mniharbanu/guvi
/codekata/wordnum.py
95
3.703125
4
num=input() m=any(char.isdigit() for char in num) if(m==1): print('Yes') else: print('No')
fdf366f11c136eeef5d907824f7dff53d9719e04
baiden00/blockChain
/hash.py
282
3.796875
4
from hashlib import sha256 # text to hash text = "I am excited to learn about blockchain" #created an object of sha256 and passed the encoded version of text to it hash_result = sha256(text.encode()) #prints the hexidecimal form of the hash_result print(hash_result.hexdigest())
43a6772173de4d17299a80dd9f504b042a4c687f
parfeniukir/parfeniuk
/Lesson 6/operators.py
259
3.96875
4
a = 10 b = 20 if a == 10 and b == 10: print('True') else: print('False') if a == 10 or b == 10: print('True') else: print('False') text = 'Some Text' if (a == 10 or b == 10) and text == ('Hello'): print('True') else: print('False')
0faf17aa213fcf3477946277f10569711eca9566
congfeng22/Leetcode
/Python/43. Multiply Strings.py
541
3.53125
4
class Solution(object): def multiply(self, num1, num2): """ :type num1: str :type num2: str :rtype: str """ totalsum = [0]*(len(num1)+len(num2)) for i in range(len(num1)): for j in range(len(num2)): pairmul = int(num2[~j])*int(num1[~i])+totalsum[~(i+j)] totalsum[~(i+j)-1] += pairmul//10 totalsum[~(i+j)] = pairmul%10 return str(int("".join(map(str,totalsum)))) test = Solution() print(test.multiply('123','456'))
377e09aa65eb32639393b49f17f000adcc178cfd
grazielags/cp12
/Reginei/Módulo 3/Aula 8 Python/Aula 4 vetor exercicios/exercicio2.py
540
3.78125
4
''' 2. Faça um programa que preencha por leitura um vetor de 10 posições e obtenha por leitura um número para verificar quantas vezes esse número existe no vetor. ''' vetor = [] contador = 0 for i in range(10): vetor.append(eval(input("Digite o valor: "))) numero = int(input("Digite o valor a ser procurado na lista: ")) for i in range(len(vetor)): if vetor[i] == numero: contador = contador + 1 print("Lista Completa",vetor) print("O número",numero,"aparece",contador,"vezes na Lista!")
edffaabb0c6af449a30a279bf103bc1e3a935bc9
wpy-111/python
/Tensorflow/day03/05_dataset.py
435
3.625
4
""" 数据集加载 """ import tensorflow as tf from tensorflow.keras import datasets def prepare_mnist(x,y): x = tf.cast(x,tf.int32) y = tf.cast(y,tf.float32) return x,y (train_x,train_y),(test_x,test_y) = datasets.fashion_mnist.load_data() train_y = tf.one_hot(train_y,depth=10) test_y = tf.one_hot(test_y,depth=10) #转化到一个数据集 ds = tf.data.Dataset.from_tensor_slices((train_x,train_y)) print(ds)
914a95ace848d5cfbf979985a48443b57fcaa0f6
CameronCooke123/prg105
/Ch04_1.py
443
4.1875
4
""" a program that utilizes loops to display the amount of calories burned for different amounts of times on a treadmill. """ CALORIES_PER_MINUTE = 4.2 minutes_on_treadmill = 10 while minutes_on_treadmill <= 30: calories_burned = str(minutes_on_treadmill * CALORIES_PER_MINUTE) print("The calories burned in " + str(minutes_on_treadmill) + " minutes are: " + calories_burned) minutes_on_treadmill += 5;
6402f0d53dadc89aa91cfda4c44b699fc653f84f
draju1980/Hello-World
/fun_list_avg.py
264
4.21875
4
#Write a function that accepts a list of integers and returns the average. #Assume that the input list contains only numbers. def list_avg(mylist): sum=0 for item in mylist: sum=sum+int(item) result=(sum/len(mylist)) return result
541786e8c19f6f5c27ef530bf07996b94f3fb32a
srijaniintm/Code-Combat
/Python/02-Buildings-of-New-York-City.py
696
4.125
4
def secondLargest(arr): # Function to find the second largest if len(arr) <= 1: return -1 largest, secondL = arr[0], -1 for i in range(1,len(arr)): if arr[i] > largest: secondL = largest largest = arr[i] elif arr[i] > secondL and arr[i] != largest: secondL = arr[i] return secondL n = int(input()) # Taking Input arr = list(map(int,input().split())) # Taking Input no = secondLargest(arr) # Storing the second largest if no == -1: # If there was no second largest number in the array print(-1) else: print(*[i+1 for i in range(len(arr)) if arr[i] == no]) # Print the result if there exist a second largest
b546dbce1f0eeb0b2060a8147030eb1cf47ac26f
katevitale/Birkbeck-LLB-Progression-Analysis
/LLB_custom_scripts_mac.py
85,184
3.625
4
import pandas as pd import numpy as np import xlrd import csv import uuid from sklearn.utils import shuffle import matplotlib.pyplot as plt from matplotlib.lines import Line2D def csv_from_xls(filename, output_path): ''' Converts excel xls sheets to csv. Adapted from 'https://stackoverflow.com/questions/20105 118/convert-xlsx-to-csv-correctly-using-python'. ''' wb = xlrd.open_workbook(filename) sh = wb.sheet_by_name('Sheet1') short_name = filename.split('/')[-1] shorter_name = short_name.split('.')[0] csv_file = open(output_path + f'{shorter_name}.csv', 'w') wr = csv.writer(csv_file, quoting=csv.QUOTE_ALL) for row_num in range(sh.nrows): wr.writerow(sh.row_values(row_num)) csv_file.close() def anonymize_module(csv_filepath, SPR_dict): ''' Takes in a path for csv file of a module table and a path for storing the dictionary of spr codes and unique ids assigned to each code. Returns an anonymized and restructured dataframe of the table and the complete spr code dictionary. DOES NOT HANDLE BLANK ROWS These need to be manually deleted prior to being entered into this function. ''' # put csv contents into dataframe module_df = pd.read_csv(csv_filepath) # get new column names for new dataframe with each row representing a single student columns_1 = module_df.columns.values.tolist() assignments_columns = module_df.iloc[0].values.tolist() # this is the main row with student number, etc row_inds_1 = module_df.index.values[module_df['Ocurr'] == 'AAA'] # get number of assessments num_assessments = row_inds_1[1] - row_inds_1[0] - 1 # loop through assessments # make dictionary column_titles = {} for assessment in range(1, num_assessments+1): column_titles[assessment] = [ f'Assessment {assessment} ' + str(x) for x in assignments_columns] # make column titles new_columns = [] new_columns = columns_1 for assessment in column_titles: new_columns.extend(column_titles[assessment]) # make parts of new dataframe # get indices of each type of row row_inds = {} for assessment in range(1, num_assessments+1): row_inds[assessment] = row_inds_1 + int(assessment) # get each type of dataframe as an array array_1 = module_df.iloc[row_inds_1].values # loop through assessments to make new arrays arrays = {} for assessment in range(1, num_assessments+1): arrays[assessment] = module_df.iloc[row_inds[assessment]].values # make new dataframe from horizontally stacked arrays new_array = array_1 for assessment in range(1, num_assessments+1): new_array = np.hstack((new_array, arrays[assessment])) new_df = pd.DataFrame(data=new_array, columns=new_columns) new_df = new_df.dropna(axis='columns', how='all') # drop columns that have all NaN values # take off the /number at the end of SPR Codes new_df['SPR Code'] = ( new_df['SPR Code'].astype(str).str.split('/', expand=True).iloc[:,0]) # go through each row and replace SPR code with another number. put mapping in dictionary. # loop through SPR Code column and make replacement in order to create new dataframe # and also to populate dictionary for (index, value) in new_df['SPR Code'].iteritems(): if value in SPR_dict: new_df.at[index, 'SPR Code'] = SPR_dict[value] else: new_value = str(uuid.uuid4()) new_dict_pair = {value: new_value} SPR_dict.update(new_dict_pair) new_df.at[index, 'SPR Code'] = new_value # shuffle rows for increased anonymity new_df = shuffle(new_df) # clean up dataframe to get rid of unnecessary columns new_df.drop(labels=['Ocurr', 'Student name'], axis=1, inplace=True) new_df.set_index('SPR Code', inplace=True) # return the SPR_dict and DataFrame return SPR_dict, new_df def anonymize_progression(csv_filepath, SPR_dict): ''' Takes in a path for csv file of progression table and a dictionary of spr codes and unique ids assigned to each spr code. Returns an anonymized of the table and the updated spr code dictionary. DOES NOT HANDLE BLANK ROWS These need to be manually deleted prior to being entered into this function. ''' prog_df = pd.read_csv(csv_filepath) prog_df['SPR Code'] = ( prog_df['SPR Code'].astype(str).str.split('/', expand=True).iloc[:,0]) # loop through SPR Code column and make replacement in order to create new dataframe # and also to populate dictionary for (index, value) in prog_df['SPR Code'].iteritems(): if value in SPR_dict: prog_df.at[index, 'SPR Code'] = SPR_dict[value] else: new_value = str(uuid.uuid4()) new_dict_pair = {value: new_value} SPR_dict.update(new_dict_pair) prog_df.at[index, 'SPR Code'] = new_value # shuffle rows for increased anonymity new_df = shuffle(prog_df) # clean up dataframe to get rid of unnecessary columns new_df = new_df.dropna(axis='columns', how='all') # drop columns that have all NaN values new_df.drop(labels=['Student name'], axis=1, inplace=True) new_df.set_index('SPR Code', inplace=True) # return the SPR_dict and DataFrame return SPR_dict, new_df def add_fr_and_dr_flags(df): ''' Adds Reassessment (FR and DR) flags to the module files to indicate that student reassessed with FR or DR that particular year.''' df['DR Flag'] = df.apply(lambda row: any(row.isin(['DR'])) and (row['Result'] != 'D'), axis=1) # bc final grade can also be 'DR' (then Final Result == 'D') df['FR Flag'] = df.apply(lambda row: any(row.isin(['FR'])), axis=1) return df def record_history(row): for record in row['Entire Record']: year, course, reassess_flag, dr_flag, attemptnum, mark, result = record.split() row[f'{course} History'].append(record) def get_last_attempt_year(list_of_attempts): ''' Returns year of student's last attempt given a list of attempts. ''' if any(list_of_attempts): last_record = list_of_attempts[-1] l_yr, l_rs, l_att = last_record l_yr = int(l_yr[0:2] + l_yr[-2:]) # will record the last year in a multi-year term return l_yr def get_last_year_on_record_from_attempts(row): ''' Returns year of student's last attempt given a row of STUDENTS dataframe. Computes last year from list of attempts in each (module) Attempts column in the STUDENTS df using function 'get_last_attempt_year'. ''' courses = ['CONAD','CONTRACT','LSM','TORT','EQUITY','LAND','CRIMINAL','EU','LT1','LT2'] ser = pd.Series([row[f'{course} Attempts'] for course in courses]).apply(get_last_attempt_year) if any(ser): return max(ser) def make_year_columns(row): list_years = ['201112','201213','201314','201415', '201516', '201617','201718'] list_courses = ['CONAD','CONTRACT','LSM','TORT','CRIMINAL', 'LAND','EQUITY','EU','LT1','LT2'] first_year = row['Year started'] if pd.isnull(row['Last year']): index = row.name print(index, 'error: last year is nan.') pass else: last_year = (str(row['Last year'])[:2] + str(int(row['Last year'] - 1))[-2:] + str(int(row['Last year']))[-2:]) if (last_year == '201819'): pass else: for i, year in enumerate(list_years[list_years.index(first_year): list_years.index(last_year)+1], start=1): # make a column and get courses and put them in the column for course in list_courses: for attempt in row[f'{course} Attempts']: att_yr, att_res, att_num = attempt if att_yr == year: row[f'Year {i} Courses'].append((course, att_res, att_num)) return row def make_progression_columns(row): programme = row['Programme'] for i in range(1,7,1): modules = [entry[0] if any(entry) else np.NaN for entry in row[f'Year {i} Courses']] if programme == 'PT': y1_courses_pt = ['CONAD','CONTRACT','LSM'] y2_courses_pt = ['TORT','CRIMINAL'] y3_courses_pt = ['LAND','EQUITY'] y4_courses_pt = ['EU','LT1','LT2'] if any(module for module in modules if module in y4_courses_pt): row[f'Year {i} Progression'] = 'Year 4' elif any(module for module in modules if module in y3_courses_pt): row[f'Year {i} Progression'] = 'Year 3' elif any(module for module in modules if module in y2_courses_pt): row[f'Year {i} Progression'] = 'Year 2' elif any(module for module in modules if module in y1_courses_pt): row[f'Year {i} Progression'] = 'Year 1' else: row[f'Year {i} Progression'] = np.NaN elif programme == 'FT': y1_courses_ft = ['CONAD','CONTRACT','LSM','TORT'] y2_courses_ft = ['CRIMINAL','EQUITY'] y3_courses_ft = ['EU','LT1','LT2'] if any(module for module in modules if module in y3_courses_ft): row[f'Year {i} Progression'] = 'Year 3' elif any(module for module in modules if module in y2_courses_ft): row[f'Year {i} Progression'] = 'Year 2' elif any(module for module in modules if module in y1_courses_ft): row[f'Year {i} Progression'] = 'Year 1' else: row[f'Year {i} Progression'] = np.NaN return row def get_final_prog_status(row): cols = [f'Year {i} Progression' for i in list(range(1,8,1))] ser = row[cols] if any(ser.notnull()): final_stat = ser[ser.notnull()][-1] else: final_stat = np.NaN return final_stat def make_students_dataframe(module_files): # create dataframes with SPRcode as index student_attempts = pd.DataFrame() student_grades = pd.DataFrame() student_reassess_flags = pd.DataFrame() student_dr_flags = pd.DataFrame() student_marks = pd.DataFrame() for dfname, df in module_files.items(): # Add reassess flags (fr and dr) module_files[dfname] = add_fr_and_dr_flags(df) year, module, tmp = dfname.split('_') student_attempts = student_attempts.join(df[['Attempt']], how='outer') student_attempts.rename(columns={'Attempt': f'{year} {module}'}, inplace=True) student_grades = student_grades.join(df[['Grade']], how='outer') student_grades.rename(columns={'Grade': f'{year} {module}'},inplace=True) if any(df.columns == 'Mark'): student_marks = student_marks.join(df[['Mark']], how='outer') student_marks.rename(columns={'Mark':f'{year} {module}'}, inplace=True) else: student_marks = student_marks.join(df[['Grade']], how='outer') student_marks.rename(columns={'Grade':f'{year} {module}'}, inplace=True) student_marks[f'{year} {module}'] = np.NaN student_reassess_flags = student_reassess_flags.join(df[['FR Flag']], how='outer') student_reassess_flags.rename(columns={'FR Flag': f'{year} {module}'},inplace=True) student_dr_flags = student_dr_flags.join(df[['DR Flag']], how='outer') student_dr_flags.rename(columns={'DR Flag': f'{year} {module}'},inplace=True) student_attempts = student_attempts.reindex(sorted(student_attempts.columns), axis=1)#sort by year student_zipped = pd.DataFrame(index = student_attempts.index, columns = student_attempts.columns) for index in student_attempts.index: for column in student_attempts.columns: if student_marks.at[index, column] == np.NaN: student_zipped.at[index, column] = str(student_reassess_flags.at[index, column]) \ + ' ' + str(student_dr_flags.at[index, column]) \ + ' ' + str(student_attempts.at[index,column]) \ + ' ' + 'nan' + ' ' + str(student_grades.at[index,column]) else: student_zipped.at[index, column] = str(student_reassess_flags.at[index, column]) \ + ' ' + str(student_dr_flags.at[index, column]) \ + ' ' + str(student_attempts.at[index,column]) \ + ' ' + str(student_marks.at[index,column]) \ + ' ' + str(student_grades.at[index,column]) student_zipped = student_zipped.replace('nan nan nan nan nan', np.NaN) records = {} for index, row in student_zipped.iterrows(): courses_on_record = row.dropna().index.tolist() results = row.dropna().values.tolist() records[index] = list(zip(courses_on_record,results)) RECORDS = {} for SPRcode, record in records.items(): new_list = [] for (course, result) in record: new_list.append(course + ' ' + result) RECORDS[SPRcode] = new_list # make dictionaries about student variables for inputting into a future 'STUDENTS' table (clean this up too) year_entered = {} graduated_year = {} status_now = {} left_year = {} STUDENTS = pd.DataFrame(columns=['Entire Record', 'CONAD History','CONTRACT History', 'LSM History', 'TORT History', 'LAND History', 'CRIMINAL History','EQUITY History', 'EU History', 'LT1 History', 'LT2 History', 'CONAD Attempts', 'CONTRACT Attempts', 'LSM Attempts', 'TORT Attempts', 'LAND Attempts', 'CRIMINAL Attempts', 'EQUITY Attempts', 'EU Attempts', 'LT1 Attempts', 'LT2 Attempts']) list_years = ['201112','201213','201314','201415','201516', '201617','201718'] for SPRcode, list_records in RECORDS.items(): # for all students... # try: first_year = list_records[0].split()[0] last_year = list_records[-1].split()[0] # fill in entire record column STUDENTS.at[SPRcode, 'Entire Record'] = list_records # if graduauted for students with enough of record in data set # does not include students that failed any previous courses but were allowed to progress... if (any([((record.split()[1] == 'LT2') & (record.split()[-1] == 'P')) for record in list_records]) & any([((record.split()[1] == 'LT1') & (record.split()[-1] == 'P')) for record in list_records]) & any([((record.split()[1] == 'EU') & (record.split()[-1] == 'P')) for record in list_records]) & any([((record.split()[1] == 'EQUITY') & (record.split()[-1] == 'P')) for record in list_records]) # & any([((record.split()[1] == 'LAND') & (record.split()[-1] == 'P')) for record in list_records]) & any([((record.split()[1] == 'CRIMINAL') & (record.split()[-1] == 'P')) for record in list_records]) & any([((record.split()[1] == 'TORT') & (record.split()[-1] == 'P')) for record in list_records]) & any([((record.split()[1] == 'CONAD') & (record.split()[-1] == 'P')) for record in list_records]) & any([((record.split()[1] == 'CONTRACT') & (record.split()[-1] == 'P')) for record in list_records])): graduated_year[SPRcode] = last_year status_now[SPRcode] = 'Graduated' # if left prematurely -> does not include any students that left after 2018 if not any([(record.split()[0] == '201718') for record in list_records]): # not still working on degree in 2018... if SPRcode not in status_now: # ...and did not graduate status_now[SPRcode] = 'Left prematurely - details unknown' left_year[SPRcode] = last_year if any([((record.split()[-3],record.split()[-1]) == ('3.0', 'F')) for record in list_records if (record.split()[0] == last_year)]): # student eligible for termination status_now[SPRcode] = 'Terminated' left_year[SPRcode] = last_year elif any([((record.split()[0] == last_year) & (record.split()[-1] == 'W')) for record in list_records]): # student withdrawn status_now[SPRcode] = 'Withdrawn' left_year[SPRcode] = last_year elif any([((record.split()[0] == last_year) & (record.split()[-1] == 'F')) for record in list_records]): status_now[SPRcode] = 'Left after failing' left_year[SPRcode] = last_year elif all([((record.split()[-1] == 'P')) for record in list_records if (record.split()[0] == last_year)]): status_now[SPRcode] = 'Left in good standing' left_year[SPRcode] = last_year # determine current status (progressing or not progressing) if not graduated or left if SPRcode not in status_now.keys(): # determine if all courses passed for 201718 if any([((record.split()[-3],record.split()[-1]) == ('3.0', 'F')) for record in list_records if (record.split()[0] == last_year)]): status_now[SPRcode] = 'Eligible for termination' left_year[SPRcode] = last_year if any([(record.split()[-1] in ['F','W']) for record in list_records if (record.split()[0] == last_year)]): status_now[SPRcode] = 'Not progressing' elif any([(record.split()[0] =='201718') for record in list_records]): status_now[SPRcode] = 'Progressing' # determine year entered if possible for year in list_years[1:]: if first_year == year: if any([f'{first_year} CONAD' in record for record in list_records]): if any([f'{first_year} CONTRACT' in record for record in list_records]): year_entered[SPRcode] = first_year # find the PT/FT status of each student student_pt_ft_statuses = pd.DataFrame() for dfname, df in module_files.items(): year, module, tmp = dfname.split('_') student_pt_ft_statuses = (student_pt_ft_statuses.join(df[['Programme']], how='outer')) student_pt_ft_statuses.rename(columns={'Programme': f'{year} {module}'}, inplace=True) student_pt_ft_statuses = student_pt_ft_statuses.reindex(sorted(student_pt_ft_statuses.columns), axis=1)#sorted by year records = {} for index, row in student_pt_ft_statuses.iterrows(): courses_on_record = row.dropna().index.tolist() programmes_listed = row.dropna().values.tolist() records[index] = list(zip(courses_on_record,programmes_listed)) changed_programme = {} programmes = {} for SPRcode, record in records.items(): first_programme = record[0][1] for (course, programme) in record: if programme != first_programme: changed_programme[SPRcode] = record if SPRcode in changed_programme: programmes[SPRcode] = 'Changed' else: if 'part' in first_programme: programmes[SPRcode] = 'PT' elif 'full' in first_programme: programmes[SPRcode] = 'FT' elif '6' in first_programme: programmes[SPRcode] = '6YR' # Make STUDENTS dataframe STUDENTS['Programme'] = pd.Series(programmes) STUDENTS['Year started'] = pd.Series(year_entered) STUDENTS['Current status'] = pd.Series(status_now) STUDENTS['Graduated year'] = pd.Series(graduated_year) STUDENTS['Left year from records'] = pd.Series(left_year) # STUDENTS['Year left prematurely'] = pd.Series(year_left_prematurely) # STUDENTS['Courses prior to leaving prematurely'] = pd.Series(courses_prior_to_leaving_prematurely) cols = ['Programme','Year started', 'Current status', 'Graduated year', 'Left year from records', 'Entire Record', 'LSM History', 'CONTRACT History', 'CONAD History','TORT History', 'CRIMINAL History', 'LAND History', 'EQUITY History', 'EU History', 'LT1 History', 'LT2 History', 'LSM Attempts', 'CONTRACT Attempts', 'CONAD Attempts', 'TORT Attempts', 'CRIMINAL Attempts', 'LAND Attempts', 'EQUITY Attempts', 'EU Attempts', 'LT1 Attempts', 'LT2 Attempts'] STUDENTS = STUDENTS[cols] # remove students where do not have entire record from when they started STUDENTS = STUDENTS[STUDENTS['Year started'].notnull()] # determine the last time that the course shows up, and the attempt number of that time for name in ['CONAD History','CONTRACT History', 'LSM History', 'TORT History', 'LAND History', 'CRIMINAL History','EQUITY History', 'EU History', 'LT1 History', 'LT2 History']: STUDENTS[name] = np.empty((len(STUDENTS),0)).tolist() STUDENTS.apply(record_history, axis=1); # Record attempts for name in ['LSM Attempts','CONTRACT Attempts','CONAD Attempts', 'TORT Attempts', 'CRIMINAL Attempts','LAND Attempts', 'EQUITY Attempts', 'EU Attempts', 'LT1 Attempts', 'LT2 Attempts']: STUDENTS[name] = np.empty((len(STUDENTS),0)).tolist() for course in ['CONAD','CONTRACT','LSM','TORT','EQUITY','LAND','CRIMINAL','EU','LT1','LT2']: for index, row in STUDENTS.iterrows(): for record in row[f'{course} History']: year, course, reassess_flag, dr_flag, attemptnum, mark, result = record.split() next_year = year.split('_')[0][:2] + \ str(int(year.split('_')[0][2:4]) + 1) + \ str(int(year.split('_')[0][4:]) + 1) previous_year = year.split('_')[0][:2] + \ str(int(year.split('_')[0][2:4]) - 1) + \ str(int(year.split('_')[0][4:]) - 1) attemptnum = int(float(attemptnum)) if any(row[f'{course} Attempts']): # any attempts already for this course and student id # (NEED TO UNDERSTAND HOW TO MANUALLY INCREMENT WHEN previous attempts and attempt diff < 1) # if type(row[f'{course} Attempts'][-1][-1]) == list: # if there were multiple previous attempts most_recent_previous_attempt = float(row[f'{course} Attempts'][-1][-1][-1]) else: # if there was a single previous attempt most_recent_previous_attempt = float(row[f'{course} Attempts'][-1][-1]) attempt_diff = int(float(attemptnum) - most_recent_previous_attempt) #subtract the most recent previous attempt if attempt_diff < 1: previous_year_name = previous_year + '_' + module + '_' + 'assessment' try: previous_year_result = module_files[previous_year_name].at[index,'Result'] except: previous_year_result = np.NaN if previous_year_result == 'D': if attemptnum == 1: attemptnum = int(most_recent_previous_attempt) elif (reassess_flag == 'True'): # could add 2 or 3 attempts here, depending whether there is a third assessment the following year print(f'manual attempt increment of {attemptnum}', index, course, year) attemptnum = int(most_recent_previous_attempt) + attemptnum else: # catch where attemptnum doesn't increment and increment manually if reassess_flag == 'True': print(f'manual attempt increment of {attemptnum}', index, course, year) attempt_diff = attemptnum attemptnum = int(most_recent_previous_attempt) + attemptnum else: print('manual attempt increment of 1', index, course, year) attempt_diff = attemptnum attemptnum = int(most_recent_previous_attempt) + 1 else: # if no previous attempts recorded attempt_diff = int(float(attemptnum)) ############################# if (reassess_flag == 'True'): # if attempt that year included an FR if (attempt_diff == 3): # if the difference between the previous attempt and this one is 3 # there is an attempt and a reassessment that year # and another reassessment the next year that isn't recorded there row[f'{course} Attempts'].append((year, ['', ''], [attemptnum-2, attemptnum-1])) row[f'{course} Attempts'].append((next_year, result, attemptnum)) elif (attempt_diff == 2): row[f'{course} Attempts'].append((year, ['', result], [attemptnum-1, attemptnum])) elif (attempt_diff == 1): # print('attempt_diff error', index, record, '*', row[f'{course} History']) row[f'{course} Attempts'].append((year, result, attemptnum+1)) elif dr_flag == 'True': if (attempt_diff == 3): row[f'{course} Attempts'].append((year, ['' ,''], [attemptnum-2, attemptnum-1])) row[f'{course} Attempts'].append((next_year, result, attemptnum)) elif (attempt_diff == 2): row[f'{course} Attempts'].append((year, ['', result], [attemptnum-1, attemptnum])) else: #the DR was not counted by admin but had an effect that should be recorded row[f'{course} Attempts'].append((year, ['', result], [attemptnum, attemptnum])) else: row[f'{course} Attempts'].append((year, result, attemptnum)) # Get last year on record STUDENTS['Last year'] = STUDENTS.apply(get_last_year_on_record_from_attempts, axis=1) # Get year by year courses and progression status, and final progression status for i in range(1,8): STUDENTS[f'Year {i} Courses'] = np.empty((len(STUDENTS),0)).tolist() for i in range(1,8): STUDENTS[f'Year {i} Progression'] = np.NaN STUDENTS = STUDENTS.apply(make_year_columns, axis=1) STUDENTS = STUDENTS.apply(make_progression_columns, axis=1) STUDENTS['Final progression status'] = STUDENTS.apply(get_final_prog_status, axis=1) return STUDENTS, module_files def make_attempts_dataframe(STUDENTS, module_files, n_assessments_module_dict): for dfname, df in module_files.items(): module_files[dfname]['Real Attempt Number(s)'] = np.empty((len(df),0)).tolist() module_files[dfname]['Final Real Attempt Number'] = np.empty((len(df),0)).tolist() for course in ['CONAD','CONTRACT','LSM','TORT','EQUITY','LAND','CRIMINAL','EU','LT1','LT2']: for index, row in STUDENTS.iterrows(): if any(row[f'{course} Attempts']): for record in row[f'{course} Attempts']: year = record[0] if year == '201819': pass else: attempts_that_year = record[-1] (module_files[f'{year}_{course}_assessment'] .at[index,'Real Attempt Number(s)']) = attempts_that_year if type(attempts_that_year) == list: if not any(attempts_that_year): print('error: no attempts that year') pass else: (module_files[f'{year}_{course}_assessment'] .at[index,'Final Real Attempt Number']) = attempts_that_year[-1] else: (module_files[f'{year}_{course}_assessment'] .at[index,'Final Real Attempt Number']) = attempts_that_year # real attempt number is either empty list, integer, or list # let's replace the empty lists with np.NaN for dfname, df in module_files.items(): for index, row in df.iterrows(): if type(row['Real Attempt Number(s)']) == list: if not any(row['Real Attempt Number(s)']): module_files[dfname].at[index, 'Real Attempt Number(s)'] = np.NaN if type(row['Final Real Attempt Number']) == list: if not any(row['Final Real Attempt Number']): module_files[dfname].at[index, 'Final Real Attempt Number'] = np.NaN ATTEMPTS = {} tuples = [] for index in STUDENTS.index: for course in ['CONAD', 'CONTRACT', 'LSM', 'TORT', 'LAND', 'CRIMINAL', 'EQUITY', 'EU', 'LT1', 'LT2']: tuples.append((index,course)) index = pd.MultiIndex.from_tuples(tuples, names=['SPRcode', 'Module']) for attempt in ['first', 'second', 'third', 'fourth', 'fifth']: ATTEMPTS[f'{attempt}'] = pd.DataFrame(index=index, columns = [ 'Student Programme','Student Final Status', 'Year of Attempt', 'Attempt Type', 'Module Mark', 'Module Grade', 'Module Result', 'Asst 1 Grade', 'Asst 1 Result', 'Asst 1 Submit', 'Asst 2 Grade', 'Asst 2 Result', 'Asst 2 Submit']) for dfname, df in module_files.items(): year, module, tmp = dfname.split('_') for index, row in df.iterrows(): if index in STUDENTS.index: previous_year_name = year.split('_')[0][:2] + \ str(int(year.split('_')[0][2:4]) - 1) + \ str(int(year.split('_')[0][4:]) - 1) + '_' + module + '_' + 'assessment' next_year_name = year.split('_')[0][:2] + \ str(int(year.split('_')[0][2:4]) + 1) + \ str(int(year.split('_')[0][4:]) + 1) + '_' + module + '_' + 'assessment' try: previous_year_result = module_files[previous_year_name].at[index,'Result'] except: previous_year_result = np.NaN try: if index in module_files[next_year_name].index: if type(module_files[next_year_name].at[index,'Result']) != str: # this year is a reassessment that was failed second_reassessment_flag = True else: second_reassessment_flag = False else: second_reassessment_flag = False except: second_reassessment_flag = False ######################################################### if (type(row['Result']) == str): # if this isn't the second reassessment (which is recorded independently) primary_row = pd.Series() primary_row['Student Programme'] = STUDENTS.at[index,'Programme'] primary_row['Student Final Status'] = STUDENTS.at[index, 'Current status'] primary_row['Year of Attempt'] = year primary_row['Asst 1 Grade'] = df.at[index,'Assessment 1 Grade'] primary_row['Asst 1 Result'] = df.at[index, 'Assessment 1 P or F'] if module != 'LSM': if pd.to_numeric(df.at[index, 'Assessment 1 Mark']) > 0: primary_row['Asst 1 Submit'] = True else: primary_row['Asst 1 Submit'] = False else: if df.at[index, 'Assessment 1 Grade'] in ['P', 'LP']: primary_row['Asst 1 Submit'] = True else: primary_row['Asst 1 Submit'] = False if int(n_assessments_module_dict[dfname]) == 2: primary_row['Asst 2 Grade'] = df.at[index, 'Assessment 2 Grade'] primary_row['Asst 2 Result'] = df.at[index, 'Assessment 2 P or F'] if module != 'LSM': if pd.to_numeric(df.at[index, 'Assessment 2 Mark']) > 0: primary_row['Asst 2 Submit'] = True else: primary_row['Asst 2 Submit'] = False else: if df.at[index, 'Assessment 2 Grade'] in ['P', 'LP']: primary_row['Asst 2 Submit'] = True else: primary_row['Asst 2 Submit'] = False else: primary_row['Asst 2 Grade'] = np.NaN primary_row['Asst 2 Result'] = np.NaN primary_row['Asst 2 Submit'] = np.NaN #################################################################### # if a reassessment #################################################################### if (row['FR Flag'] == True) | (row['DR Flag'] == True): # if the year includes a reassessment if second_reassessment_flag == False: reassessment_row = primary_row.copy() # otherwise will overwrite primary_row!!! reassessment_row['Module Grade'] = row['Grade'] reassessment_row['Module Result'] = row['Result'] if any(df.columns == 'Mark'): reassessment_row['Module Mark'] = row['Mark'] else: reassessment_row['Module Mark'] = np.NaN # set all reassessment asst cols to nan first, # then overwrite them where they can be deduced asst_cols = ['Asst 1 Grade', 'Asst 1 Result', 'Asst 1 Submit', 'Asst 2 Grade','Asst 2 Result', 'Asst 2 Submit'] reassessment_row[asst_cols] = np.NaN if int(n_assessments_module_dict[dfname]) == 1: reassessment_row['Asst 1 Mark'] = \ reassessment_row['Module Mark'] reassessment_row['Asst 1 Result'] = \ reassessment_row['Module Result'] + ' calc' if reassessment_row['Module Mark'] == 0.0: reassessment_row['Asst 1 Submit'] = False else: reassessment_row['Asst 1 Submit'] = True if (int(n_assessments_module_dict[dfname]) == 2): if reassessment_row['Module Mark'] == 0.0: reassessment_row['Asst 1 Submit'] = False reassessment_row['Asst 2 Submit'] = False reassessment_row['Asst 1 Result'] = 'F calc' reassessment_row['Asst 2 Result'] = 'F calc' # determine attempt type if row['DR Flag'] == True: reassessment_row['Attempt Type'] = 'DR Reassessment' else: reassessment_row['Attempt Type'] = 'FR Reassessment' try: # determine attempt number if type(row['Real Attempt Number(s)']) == list: reassessment_attempt_num = row['Real Attempt Number(s)'][-1] else: first_attempt_that_year = row['Real Attempt Number(s)'] # write row to appropriate ATTEMPTS table if reassessment_attempt_num == 1: # DR reassessment ATTEMPTS['second'].loc[(index, module)] = reassessment_row if reassessment_attempt_num == 2: ATTEMPTS['second'].loc[(index, module)] = reassessment_row if reassessment_attempt_num == 3: ATTEMPTS['third'].loc[(index,module)] = reassessment_row if reassessment_attempt_num == 4: ATTEMPTS['fourth'].loc[(index,module)] = reassessment_row if reassessment_attempt_num == 5: ATTEMPTS['fifth'].loc[(index,module)] = reassessment_row except: # if there is no attempt number (ie started before 2011), then we don't care to write it anyway if type(STUDENTS.at[index,'Year started']) == str: print(STUDENTS.at[index,'Year started'],'no attempt number', index, module, year) pass elif second_reassessment_flag == True: # will need to make a row each to put in first reassessment and second reassessment first_reassessment_row = primary_row.copy() # do not overwrite primary_row second_reassessment_row = primary_row.copy() # do not overwrite primary_row or first_assessment_row first_reassessment_row['Module Grade'] = np.NaN second_reassessment_row['Module Grade'] = row['Grade'] first_reassessment_row['Module Result'] = 'F calc' second_reassessment_row['Module Result'] = row['Result'] first_reassessment_row['Module Mark'] = np.NaN if any(df.columns == 'Mark'): second_reassessment_row['Module Mark'] = row['Mark'] else: second_reassessment_row['Module Mark'] = np.NaN asst_cols = ['Asst 1 Grade', 'Asst 1 Result', 'Asst 1 Submit', 'Asst 2 Grade','Asst 2 Result', 'Asst 2 Submit'] # set all reassessment asst cols to nan first # then overwrite them where they can be deduced first_reassessment_row[asst_cols] = np.NaN second_reassessment_row[asst_cols] = np.NaN if int(n_assessments_module_dict[dfname]) == 1: first_reassessment_row['Asst 1 Result'] = 'F calc' second_reassessment_row['Asst 1 Mark'] = \ second_reassessment_row['Module Mark'] second_reassessment_row['Asst 1 Result'] = \ second_reassessment_row['Module Result'] + ' calc' if second_reassessment_row['Module Mark'] == 0.0: second_reassessment_row['Asst 1 Submit'] = False else: second_reassessment_row['Asst 1 Submit'] = True if (int(n_assessments_module_dict[dfname]) == 2): if second_reassessment_row['Module Mark'] == 0.0: second_reassessment_row['Asst 1 Submit'] = False second_reassessment_row['Asst 2 Submit'] = False second_reassessment_row['Asst 1 Result'] = 'F calc' second_reassessment_row['Asst 2 Result'] = 'F calc' # determine type of attempt if (row['DR Flag'] == True): first_reassessment_row['Attempt Type'] = 'DR Reassessment' else: first_reassessment_row['Attempt Type'] = 'FR Reassessment' second_reassessment_row['Attempt Type'] = 'Reassessment Following Year' # determine attempt number if type(row['Real Attempt Number(s)']) == list: first_reassessment_attempt_num = row['Real Attempt Number(s)'][-1] else: first_reassessment_attempt_num = row['Real Attempt Number(s)'] # write rows to appropriate ATTEMPTS table if first_reassessment_attempt_num == 1: print('error with attemptnum = 1 after reassessment',index, module, year) if first_reassessment_attempt_num == 2: ATTEMPTS['second'].loc[(index, module)] = first_reassessment_row ATTEMPTS['third'].loc[(index, module)] = second_reassessment_row if first_reassessment_attempt_num == 3: ATTEMPTS['third'].loc[(index,module)] = first_reassessment_row ATTEMPTS['fourth'].loc[(index, module)] = second_reassessment_row if first_reassessment_attempt_num == 4: ATTEMPTS['fourth'].loc[(index,module)] = first_reassessment_row ATTEMPTS['fifth'].loc[(index, module)] = second_reassessment_row if first_reassessment_attempt_num == 5: ATTEMPTS['fifth'].loc[(index,module)] = first_reassessment_row #################################################################### # put primary rows in correct attempt dfs #################################################################### if not ((pd.to_numeric(year,errors='coerce') > 201314) & (module =='LSM')): #needs testing try: if (int(n_assessments_module_dict[dfname]) == 2): # num assignments primary_row['Module Mark'] = float((pd.to_numeric(row['Assessment 1 Weight']) * pd.to_numeric(row['Assessment 1 Mark'])) + (pd.to_numeric(row['Assessment 2 Weight']) * pd.to_numeric(row['Assessment 2 Mark']))) else: primary_row['Module Mark'] = row['Assessment 1 Mark'] if int(float(pd.to_numeric(primary_row['Module Mark']))) >= 40.0: primary_row['Module Grade'] = 'P calc' primary_row['Module Result'] = 'P calc' else: primary_row['Module Grade'] = 'F calc' primary_row['Module Result'] = 'F calc' except: print('error in calculating mark',index, module, year, row['Assessment 1 Mark']) # this is a reassessment that is taking the full year # perhaps is being recorded below else: # course is LSM and both assignments must be passed to pass primary_row['Module Mark'] = np.NaN if ((df.at[index,'Assessment 1 Grade'] in ['P','LP']) & ( df.at[index,'Assessment 2 Grade'] in ['P','LP'])): primary_row['Module Grade'] = 'P calc' primary_row['Module Result'] = 'P calc' else: primary_row['Module Grade'] = 'F calc' primary_row['Module Result'] = 'F calc' #################################################################### # if no reassessment #################################################################### else: # no reassessment that year primary_row['Module Grade'] = row['Grade'] primary_row['Module Result'] = row['Result'] if any(df.columns == 'Mark'): primary_row['Module Mark'] = row['Mark'] else: primary_row['Module Mark'] = np.NaN #################################################################### # store the first primary row #################################################################### if type(row['Real Attempt Number(s)']) == list: first_attempt_that_year = row['Real Attempt Number(s)'][0] else: first_attempt_that_year = row['Real Attempt Number(s)'] if (first_attempt_that_year == 1): # initial assessment if previous_year_result != 'D': primary_row['Attempt Type'] = 'Initial Assessment' ATTEMPTS['first'].loc[(index, module)] = primary_row else: primary_row['Attempt Type'] = 'DR Retake' ATTEMPTS['second'].loc[(index, module)] = primary_row else:# make retake retake_attempt_num = first_attempt_that_year primary_row['Attempt Type'] = 'Retake' if retake_attempt_num == 2: if previous_year_result != 'D': ATTEMPTS['second'].loc[(index, module)] = primary_row else: primary_row['Attempt Type'] = 'DR Retake' ATTEMPTS['third'].loc[(index, module)] = primary_row elif retake_attempt_num == 3: if previous_year_result != 'D': ATTEMPTS['third'].loc[(index,module)] = primary_row else: primary_row['Attempt Type'] = 'DR Retake' ATTEMPTS['fourth'].loc[(index, module)] = primary_row elif retake_attempt_num == 4: if previous_year_result != 'D': ATTEMPTS['fourth'].loc[(index,module)] = primary_row else: primary_row['Attempt Type'] = 'DR Retake' ATTEMPTS['fifth'].loc[(index, module)] = primary_row elif retake_attempt_num == 5: ATTEMPTS['fifth'].loc[(index,module)] = primary_row for attempt in ['first', 'second', 'third', 'fourth', 'fifth']: ATTEMPTS[f'{attempt}'].dropna(how='all', inplace = True) ATTEMPTS[f'{attempt}']['Module Mark'] = pd.to_numeric(ATTEMPTS[f'{attempt}']['Module Mark']) return ATTEMPTS, module_files def create_outcomes_series(df, year_entered): outcomes = pd.Index(['Graduated','Failed out','Left in good standing', 'Still in program']) left_badly = ['Terminated', 'Withdrawn', 'Left after failing', 'Left prematurely - details unknown'] still_in = ['Progressing', 'Not progressing'] outcomes_ser= pd.Series(index=outcomes) selection_total_students =(df['Year started'] .str.contains(year_entered)) selection_graduated_students = (selection_total_students & (df['Current status'] == 'Graduated')) selection_left_badly_students = (selection_total_students & df['Current status'] .isin(left_badly)) selection_left_in_good_standing_students = (selection_total_students & (df['Current status'] == 'Left in good standing')) selection_still_in_students = (selection_total_students & df['Current status'] .isin(still_in)) outcomes_ser['Graduated'] = (len(df[ selection_graduated_students])) outcomes_ser['Failed out'] = (len(df[ selection_left_badly_students])) outcomes_ser['Left in good standing'] = (len(df[ selection_left_in_good_standing_students])) outcomes_ser['Still in program'] = (len(df[ selection_still_in_students])) return outcomes_ser def get_each_year_distribution(df, cohort_ent_yr): years = [1,2,3] increments = [(year-1) for year in years] output_df = (pd.DataFrame(index=pd.Index([f'Year {y}' for y in years]), columns = [f'Year {y} Curriculum'for y in years])) for i in increments: cutoff = int(cohort_ent_yr[:4]) + i selection_total_students = (df['Year started']. str.contains(cohort_ent_yr)) year = i + 1 for y in years: output_df.at[f'Year {year}',f'Year {y} Curriculum'] = \ len(df[selection_total_students & (df[f'Year {year} Progression'] == f'Year {y}')])\ / len(df[selection_total_students]) return output_df def get_year2_distribution(df, cohort_ent_yrs): if type(cohort_ent_yrs) == list: output_df = pd.DataFrame(index=pd.Index(cohort_ent_yrs)) for year in cohort_ent_yrs: cutoff = int(year[:4]) + 1 selection_total_students = \ df['Year started'].str.contains(year) selection_still_in_students = \ selection_total_students \ & (df['Last year'] > cutoff) selection_repeating_yr_1 = \ selection_still_in_students \ & (df['Year 2 Progression'] == 'Year 1') selection_progressed_to_yr_2 = \ selection_still_in_students \ & (df['Year 2 Progression'] == 'Year 2') output_df.at[year, 'Repeating Year 1'] = \ (len(df[selection_repeating_yr_1]) / len(df[selection_total_students])) output_df.at[year, 'Progressed to Year 2'] = \ ((len(df[selection_progressed_to_yr_2]) / len(df[selection_total_students]))) return output_df else: output_ser = pd.Series(index=pd.Index(cohort_ent_yrs)) cutoff = int(cohort_ent_yrs[:4]) + 1 selection_total_students = df['Year started'].str.contains(cohort_ent_yr) selection_still_in_students = selection_total_students & (df['Last year'] > cutoff) selection_repeating_yr_1 = selection_still_in_students & (df['Year 2 Progression'] == 'Year 1') selection_progressed_to_yr_2 = selection_still_in_students & (df['Year 2 Progression'] == 'Year 2') output_ser['Repeating Year 1'] = len(df[selection_repeating_yr_1]) / len(df[selection_total_students]) output_ser['Progressed to Year 2'] = (len(df[selection_progressed_to_yr_2]) / len(df[selection_total_students])) return output_ser def get_year3_distribution(df, cohort_ent_yrs): output_df = pd.DataFrame(index=pd.Index(cohort_ent_yrs)) for year in cohort_ent_yrs: cutoff = int(year[:4]) + 2 selection_total_students = \ df['Year started'].str.contains(year) selection_still_in_students = \ selection_total_students \ & (df['Last year'] > cutoff) selection_repeating_yr_1 = \ selection_still_in_students \ & (df['Year 3 Progression'] == 'Year 1') selection_repeating_yr_2 = \ selection_still_in_students \ & (df['Year 3 Progression'] == 'Year 2') selection_progressed_to_yr_3 = \ selection_still_in_students \ & (df['Year 3 Progression'] == 'Year 3') output_df.at[year, 'Repeating Year 1'] = \ (len(df[selection_repeating_yr_1]) / len(df[selection_total_students])) output_df.at[year, 'Repeating Year 2'] = \ (len(df[selection_repeating_yr_2]) / len(df[selection_total_students])) output_df.at[year, 'Progressed to Year 3'] = \ ((len(df[selection_progressed_to_yr_3]) / len(df[selection_total_students]))) return output_df def plot_single_cohort_progression(df, year_entered): x = (get_each_year_distribution(df, year_entered) .index.tolist()) w = 0.4 distributions = {} plots = {} for year in [1,2,3]: distributions[year] = \ get_each_year_distribution(df, year_entered)[f'Year {year} Curriculum'] fig = plt.figure(figsize=(6,5)) plt.bar(x, distributions[3], width=w, color='0.5') plt.bar(x, distributions[2], width=w, bottom=distributions[3], color=['0','0.5', 'salmon']) plt.bar(x, distributions[1], width=w, bottom=distributions[2]+distributions[3], color=['0.5','maroon', 'maroon']) plt.title(f'{year_entered} Cohort',fontsize=16, fontweight='bold') plt.ylabel('Proportion of Entering Cohort', fontweight='bold', fontsize=12) plt.xticks(fontsize=12, fontweight='bold') plt.yticks(fontsize=12) custom_lines = [Line2D([0], [0], color='0.5', lw=8), Line2D([0], [0], color='maroon', lw=8), Line2D([0], [0], color='salmon', lw=8)] plt.legend(custom_lines, ['Progressing on Time', 'Repeating Year 1', 'Pursuing Year 2 of Program in Year 3 of Study'], fontsize=12,frameon=False, loc=(0.65,0.8)) ax = plt.gca() ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ttl = ax.title ttl.set_position([.55, 1.10]) plt.show() def plot_all_yrs_progression(df, years_of_interest): y = {} x = get_each_year_distribution(df, years_of_interest[0]).index.tolist() w = 0.4 for year in years_of_interest: for i in [1,2,3]: y[(year,i)] = get_each_year_distribution(df, year)[f'Year {i} Curriculum'] fig, axes = plt.subplots(2, 2, figsize=(8, 6), sharex=True, sharey=True) # Set the title for the figure fig.suptitle('LLB Progression across Years', fontsize=15) fig.text(0.05, 0.5, 'Proportion of entering cohort', fontsize=15, ha='center', va='center', rotation=90) # Top Left Subplot axes[0,0].bar(x, y[('201314',3)], color='0.5', width=w) axes[0,0].bar(x, y[('201314',2)], bottom=y[('201314',3)], color=['0.5','0.5', 'salmon'],width=w) axes[0,0].bar(x, y[('201314',1)], bottom=y[('201314',3)]+y[('201314',2)], color=['0.5','maroon', 'maroon'],width=w) axes[0,0].set_title("2013 Cohort", fontweight='bold') # Top Right Subplot axes[0,1].bar(x, y[('201415',3)], color='0.5', width=w) axes[0,1].bar(x, y[('201415',2)], bottom=y[('201415',3)], color=['0.5','0.5', 'salmon'],width=w) axes[0,1].bar(x, y[('201415',1)], bottom=y[('201415',3)]+y[('201415',2)], color=['0.5','maroon', 'maroon'],width=w) axes[0,1].set_title("2014 Cohort", fontweight='bold') # Bottom Left Subplot axes[1,0].bar(x, y[('201516',3)], color='0.5', width=w) axes[1,0].bar(x, y[('201516',2)], bottom=y[('201516',3)], color=['0.5','0.5', 'salmon'],width=w) axes[1,0].bar(x, y[('201516',1)], bottom=y[('201516',3)]+y[('201516',2)], color=['0.5','maroon', 'maroon'],width=w) axes[1,0].set_title("2015 Cohort", fontweight='bold') # Bottom Right Subplot axes[1,1].bar(x, y[('201617',3)], color='0.5', width=w) axes[1,1].bar(x, y[('201617',2)], bottom=y[('201617',3)], color=['0.5','0.5', 'salmon'],width=w) axes[1,1].bar(x, y[('201617',1)], bottom=y[('201617',3)]+y[('201617',2)], color=['0.5','maroon', 'maroon'],width=w) axes[1,1].set_title("2016 Cohort", fontweight='bold') custom_lines = [Line2D([0], [0], color='0.5', lw=8), Line2D([0], [0], color='maroon', lw=8), Line2D([0], [0], color='salmon', lw=8)] plt.legend(custom_lines, ['Progressing on Time', 'Repeating Year 1', 'Pursuing Year 2 of Program in Year 3 of Study'], fontsize=12,frameon=False, loc=(1.25,1.75)) plt.show() def get_prop_failures_yr_1_due_to_NS(first_attempts): sel_F_NS_FY_1_asst_crs_PT = ((first_attempts['Module'] == 'CONAD') & (first_attempts['Student Programme'] == 'PT') & first_attempts['Module Result'].isin(['F', 'F calc']) & (first_attempts['Asst 1 Submit'] == False)) sel_F_NS_FY_1_asst_crs_FT = (first_attempts['Module'].isin(['CONAD', 'TORT']) & (first_attempts['Student Programme'] == 'FT') & first_attempts['Module Result'].isin(['F', 'F calc']) & (first_attempts['Asst 1 Submit'] == False)) sel_F_NS_FY_2_asst_crs = (first_attempts['Module'].isin(['CONTRACT','LSM']) & first_attempts['Module Result'].isin(['F', 'F calc']) & ((first_attempts['Asst 1 Submit'] == False) | (first_attempts['Asst 2 Submit'] == False))) sel_F_NS_any_FY_crs = sel_F_NS_FY_1_asst_crs_PT | sel_F_NS_FY_1_asst_crs_FT | sel_F_NS_FY_2_asst_crs sel_F_FY_crs_FT = (first_attempts['Module'].isin(['CONAD', 'TORT', 'CONTRACT', 'LSM']) & (first_attempts['Student Programme'] == 'FT') & first_attempts['Module Result'].isin(['F', 'F calc'])) sel_F_FY_crs_PT = (first_attempts['Module'].isin(['CONAD', 'CONTRACT', 'LSM']) & (first_attempts['Student Programme'] == 'PT') & first_attempts['Module Result'].isin(['F', 'F calc'])) sel_F_any_FY_crs = sel_F_FY_crs_FT | sel_F_FY_crs_PT proportion_F_FYC_NS = len(first_attempts[sel_F_NS_any_FY_crs]) / len(first_attempts[sel_F_any_FY_crs]) return proportion_F_FYC_NS def get_prob_pass_FYC_if_submit(first_attempts): sel_S_FY_1_asst_crs_PT = ((first_attempts['Module'] == 'CONAD') & (first_attempts['Student Programme'] == 'PT') & (first_attempts['Asst 1 Submit'] == True)) sel_S_FY_1_asst_crs_FT = (first_attempts['Module'].isin(['CONAD', 'TORT']) & (first_attempts['Student Programme'] == 'FT') & (first_attempts['Asst 1 Submit'] == True)) sel_S_FY_2_asst_crs = (first_attempts['Module'].isin(['CONTRACT','LSM']) & ((first_attempts['Asst 1 Submit'] == True) & (first_attempts['Asst 2 Submit'] == True))) sel_S_all_asst_FY_crs = sel_S_FY_1_asst_crs_PT | sel_S_FY_1_asst_crs_FT | sel_S_FY_2_asst_crs sel_S_all_asst_and_P_FY_crs = sel_S_all_asst_FY_crs & first_attempts['Module Result'].isin(['P', 'LP', 'P calc']) proportion_P_FYC_if_submit_all_asst = len(first_attempts[sel_S_all_asst_and_P_FY_crs]) \ / len(first_attempts[sel_S_all_asst_FY_crs]) return proportion_P_FYC_if_submit_all_asst def make_module_summary(df,dfname,n_assessments): ''' Takes a pandas dataframe 'module file', its name and its number of assessments. The module file has been modified from its original form in excel in the following ways: Returns a pandas Series of calculated values to input into a module summary table. ''' year, module, tmp = dfname.split('_') n_total = len(df.index.unique()) n_attend = sum(df['Attempt type'].isin(['Assessment', 'DR Retake', 'Retake'])) # Make series for populating with calculated values ser = pd.Series() ##################################################################### # Calculate general passing stats ##################################################################### ser['N (total)'] = n_total ser['N (enrolled)'] = n_attend ser['% Pass (after reassessment same year)'] = (100 * sum((df['Result']=='P') & (df['Attempt type'] != 'FR reassessment from previous year')) / n_attend) ser['% Pass (first attempt that year)'] = (100 * sum(df['Attempt type'].isin(['Assessment', 'Retake', 'DR Retake']) & (df['Result'] == 'P')) / n_attend) ser['% Pass (first attempt ever)'] = (100 * sum((df['Attempt'] == 1.0) & (df['Attempt type'] == 'Assessment') & (df['Result'] == 'P')) / sum((df['Attempt'] == 1.0) & (df['Attempt type'] == 'Assessment'))) ser['% Pass (all assessed that year)'] = (100 * sum(df['Result']=='P') / n_total) ser['% Pass (after reassessment next year)'] = (100 * sum((df['Final Result on Worksheet']=='P') & df['Attempt type'].isin(['Assessment', 'DR Retake', 'Retake'])) / n_attend) ##################################################################### # Calculate retake stats ##################################################################### # All retakes if year != '201718': ser['% Retake Next Year'] = (100 * sum((df['Retake next year'] .str.startswith('Y') == True) & df['Assessment 1 Grade'].notnull()) / n_total) # If any students retook... if sum((df['Retake next year'].str.startswith('Y') == True) & df['Assessment 1 Grade'].notnull()) != 0: # Calculate the proportion that passed the retake ser['% of Retake that Pass'] = \ (100 * sum((df['Retake and pass'] == True) & df['Assessment 1 Grade'].notnull()) / sum((df['Retake next year'].str.startswith('Y') == True) & df['Assessment 1 Grade'].notnull())) else: # If no students retook ser['% of Retake that Pass'] = np.NaN else: # If the year is 2017/18, set all retake variables to nan, # because there is no information about retakes (no 2019 sheets) ser['% Retake Next Year'] = np.NaN ser['% of Retake that Pass'] = np.NaN ##################################################################### # Calculate general reassessment stats ##################################################################### ser['% Reassess (Either Asst FR or DR)'] = \ (100 * sum(df['Attempt type'] .isin(['FR reassessment', 'DR reassessment'])) / n_attend) ser['% Reassess (Either Asst FR or DR) that Pass'] = \ (100 * sum(df['Attempt type'] .isin(['FR reassessment', 'DR reassessment']) & (df['Result'] == 'P')) / sum(df['Attempt type'] .isin(['FR reassessment', 'DR reassessment']))) # Calculate FR reassessment stats ser['% FR Reassess'] = \ (100 * sum(df['Attempt type'] == 'FR reassessment') / n_attend) ser['% FR Reassess that Pass'] = \ (100 * sum((df['Attempt type'] == 'FR reassessment') & (df['Result'] == 'P')) / sum(df['Attempt type'] == 'FR reassessment')) # Calculate DR reassessment stats ser['% DR Reassess'] = \ (100 * sum(df['Attempt type'] == 'DR reassessment') / n_attend) ser['% DR Reassess that Pass'] = \ (100 * sum((df['Attempt type'] == 'DR reassessment') & (df['Result'] == 'P')) / sum(df['Attempt type'] == 'DR reassessment')) # Calculate second reassessment stats if sum(df['Reassess next year'] == True) != 0: ser['% Second Reassess'] = (100 * sum(df['Reassess next year'] == True)/ n_attend) ser['% Second Reassess that Pass'] = (100 * sum((df['Reassess next year'] == True) & (df['Reassess next year and pass'] == True)) / sum(df['Reassess next year'] == True)) ##################################################################### # Calculate general submission stats ##################################################################### # For modules with one assessment if float(n_assessments) == 1.0: ser['% Submit all assignments'] = (100 * sum(df['Attempt type'].isin( ['Assessment', 'Retake', 'DR Retake']) & (df['Assessment 1 Mark'] != 0.0)) / sum(df['Attempt type'].isin( ['Assessment', 'Retake', 'DR Retake']))) ser['% Submit all assignments that pass'] = (100 * sum(df['Attempt type'].isin( ['Assessment', 'Retake', 'DR Retake']) & (df['Assessment 1 Mark'] != 0.0) & (df['Result'] == 'P')) / sum(df['Attempt type'].isin( ['Assessment', 'Retake', 'DR Retake']) & (df['Assessment 1 Mark'] != 0.0))) ser['% Submit one of two assignments'] = np.nan ser['% Submit no assignments'] = (100 * sum(df['Attempt type'].isin( ['Assessment', 'Retake', 'DR Retake']) & (df['Assessment 1 Mark'] == 0.0)) / sum(df['Attempt type'].isin( ['Assessment', 'Retake', 'DR Retake']))) # For modules with two assessments elif float(n_assessments) == 2.0: if module != 'LSM': ser['% Submit all assignments'] = (100 * sum(df['Attempt type'].isin( ['Assessment', 'Retake', 'DR Retake']) & (df['Assessment 1 Mark'].astype('float') != 0.0) & (df['Assessment 2 Mark'].astype('float') != 0.0)) / sum(df['Attempt type'].isin( ['Assessment', 'Retake', 'DR Retake']))) ser['% Submit all assignments that pass'] = (100 * sum(df['Attempt type'].isin( ['Assessment', 'Retake', 'DR Retake']) & (df['Assessment 1 Mark'].astype('float') != 0.0) & (df['Assessment 2 Mark'].astype('float') != 0.0) & (df['Result'] == 'P')) / sum(df['Attempt type'].isin( ['Assessment', 'Retake', 'DR Retake']) & (df['Assessment 1 Mark'].astype('float') != 0.0) & (df['Assessment 2 Mark'].astype('float') != 0.0))) ser['% Submit one of two assignments'] = (100 * sum(df['Attempt type'].isin( ['Assessment', 'Retake', 'DR Retake']) & (((df['Assessment 1 Mark'].astype('float') != 0.0) & (df['Assessment 2 Mark'].astype('float') == 0.0)) | ((df['Assessment 1 Mark'].astype('float') == 0.0) & (df['Assessment 2 Mark'].astype('float') != 0.0)))) / sum(df['Attempt type'].isin( ['Assessment', 'Retake', 'DR Retake']))) ser['% Submit no assignments'] = (100 * sum(df['Attempt type'].isin( ['Assessment', 'Retake', 'DR Retake']) & (df['Assessment 1 Mark'].astype('float') == 0.0) & (df['Assessment 2 Mark'].astype('float') == 0.0)) / sum(df['Attempt type'].isin( ['Assessment', 'Retake', 'DR Retake']))) else: # module is LSM ser['% Submit all assignments'] = (100 * sum(df['Attempt type'].isin( ['Assessment', 'Retake', 'DR Retake']) & (df['Assessment 1 P or F'] == 'P') & (df['Assessment 2 P or F'] == 'P')) / sum(df['Attempt type'].isin( ['Assessment', 'Retake', 'DR Retake']))) ser['% Submit all assignments that pass'] = np.NaN ser['% Submit one of two assignments'] = (100 * sum(df['Attempt type'].isin( ['Assessment', 'Retake', 'DR Retake']) & (((df['Assessment 1 P or F'] == 'P') & (df['Assessment 2 P or F'] != 'P')) | ((df['Assessment 1 P or F'] != 'P') & (df['Assessment 2 P or F'] == 'P')))) / sum(df['Attempt type'].isin( ['Assessment', 'Retake', 'DR Retake']))) ser['% Submit no assignments'] = (100 * sum(df['Attempt type'].isin( ['Assessment', 'Retake', 'DR Retake']) & (df['Assessment 1 P or F'] != 'P') & (df['Assessment 2 P or F'] != 'P')) / sum(df['Attempt type'].isin( ['Assessment', 'Retake', 'DR Retake']))) ##################################################################### # Calculate failure submission stats ##################################################################### # if a student fails an attempt (result not P), how many assignments # did they submit? # For modules with one assessment if float(n_assessments) == 1.0: ser['% Fail that submit all assignments'] = ( 100 * sum(df['Attempt type'].isin( ['Assessment', 'Retake', 'DR Retake']) & (df['Result'] != 'P') & (df['Assessment 1 Mark'] != 0.0)) / sum(df['Attempt type'].isin( ['Assessment', 'Retake', 'DR Retake']) & (df['Result'] != 'P'))) ser['% Fail that submit one of two assignments'] = np.NaN ser['% Fail that submit no assignments'] = ( 100 * sum(df['Attempt type'].isin( ['Assessment', 'Retake', 'DR Retake']) & (df['Result'] != 'P') & (df['Assessment 1 Mark'] == 0.0)) / sum(df['Attempt type'].isin( ['Assessment', 'Retake', 'DR Retake']) & (df['Result'] != 'P'))) elif float(n_assessments) == 2.0: if module != 'LSM': ser['% Fail that submit all assignments'] = ( 100 * sum(df['Attempt type'].isin( ['Assessment', 'Retake', 'DR Retake']) & (df['Result'] != 'P') & (df['Assessment 1 Mark'] != 0.0) & (df['Assessment 2 Mark'] != 0.0)) / sum(df['Attempt type'].isin( ['Assessment', 'Retake', 'DR Retake']) & (df['Result'] != 'P'))) ser['% Fail that submit one of two assignments'] = ( 100 * sum(df['Attempt type'].isin( ['Assessment', 'Retake', 'DR Retake']) & (df['Result'] != 'P') & (((df['Assessment 1 Mark'] == 0.0) & (df['Assessment 2 Mark'] != 0.0)) | ((df['Assessment 1 Mark'] != 0.0) & (df['Assessment 2 Mark'] == 0.0)))) / sum(df['Attempt type'].isin( ['Assessment', 'Retake', 'DR Retake']) & (df['Result'] != 'P'))) ser['% Fail that submit no assignments'] = ( 100 * sum(df['Attempt type'].isin( ['Assessment', 'Retake', 'DR Retake']) & (df['Result'] != 'P') & (df['Assessment 1 Mark'] == 0.0) & (df['Assessment 2 Mark'] == 0.0)) / sum(df['Attempt type'].isin( ['Assessment', 'Retake', 'DR Retake']) & (df['Result'] != 'P'))) else: # module is LSM ser['% Fail that submit all assignments'] = ( 100 * sum(df['Attempt type'].isin( ['Assessment', 'Retake', 'DR Retake']) & (df['Result'] != 'P') & (df['Assessment 1 Grade'] == 'P') & (df['Assessment 2 Grade'] == 'P')) / sum(df['Attempt type'].isin( ['Assessment', 'Retake', 'DR Retake']) & (df['Result'] != 'P'))) ser['% Fail that submit one of two assignments'] = ( 100 * sum(df['Attempt type'].isin( ['Assessment', 'Retake', 'DR Retake']) & (df['Result'] != 'P') & (((df['Assessment 1 Grade'] != 'P') & (df['Assessment 2 Grade'] == 'P')) | ((df['Assessment 1 Grade'] == 'P') & (df['Assessment 2 Grade'] != 'P')))) / sum(df['Attempt type'].isin( ['Assessment', 'Retake', 'DR Retake']) & (df['Result'] != 'P'))) ser['% Fail that submit no assignments'] = ( 100 * sum(df['Attempt type'].isin( ['Assessment', 'Retake', 'DR Retake']) & (df['Result'] != 'P') & (df['Assessment 1 Grade'] != 'P') & (df['Assessment 2 Grade'] != 'P')) / sum(df['Attempt type'].isin( ['Assessment', 'Retake', 'DR Retake']) & (df['Result'] != 'P'))) ##################################################################### # Calculate Assessment stats - only possible for first attempt that yr ##################################################################### ser['Asst. 1: % Pass'] = (100 * (sum(df['Assessment 1 P or F'] == 'P')) / n_attend) ser['Asst. 1: % F (Not DR or FR)'] = \ (100 * sum(df['Assessment 1 Grade'] == 'F') / n_attend) ser['Asst. 1: % W'] = (100 * sum(df['Assessment 1 Grade'] == 'W') / n_attend) ser['Asst. 1: % FR'] = (100 * sum(df['Assessment 1 Grade'] == 'FR') / n_attend) ser['Asst. 1: % DR'] = (100 * sum(df['Assessment 1 Grade'] == 'DR') / n_attend) ser['Asst. 1: % Blank'] = (100 * sum(df['Assessment 1 Grade'].isnull()) / n_attend) ser['Asst. 1: % LF'] = (100 * sum(df['Assessment 1 Grade'] == 'LF') / n_attend) if module != 'LSM': ser['Asst. 1: % No Sub'] = (100 * sum(pd.to_numeric(df['Assessment 1 Mark'], errors='coerce') == 0.0 )/ n_attend) ser['Asst. 1: % Failed Sub'] = \ (100 * sum((pd.to_numeric(df['Assessment 1 Mark'], errors='coerce') > 0.0) & (pd.to_numeric(df['Assessment 1 Mark'], errors='coerce') < 40.0)) / n_attend) ser['Asst. 1 F: % No Sub'] = \ (100 * sum((pd.to_numeric(df['Assessment 1 Mark'], errors='coerce') == 0.0) & (df['Assessment 1 P or F'] == 'F')) / sum(df['Assessment 1 P or F'] == 'F')) ser['Asst. 1 F: % Failed Sub'] = \ (100 * sum((pd.to_numeric(df['Assessment 1 Mark'], errors='coerce') != 0.0) & (df['Assessment 1 P or F'] == 'F')) / sum(df['Assessment 1 P or F'] == 'F')) ser['Asst. 1: % Submit that Pass'] = \ (100 * sum((pd.to_numeric(df['Assessment 1 Mark'], errors='coerce') > 0.0) & (df['Assessment 1 P or F'] == 'P')) / sum(pd.to_numeric(df['Assessment 1 Mark'], errors='coerce') > 0.0)) else: ser['Asst. 1: % No Sub'] = np.NaN ser['Asst. 1: % Failed Sub'] = np.NaN ser['Asst. 1 F: % No Sub'] = np.NaN ser['Asst. 1 F: % Failed Sub'] = np.NaN ser['Asst. 1: % Submit that Pass'] = np.NaN ##################################################################### # Add stats for second assessment if applicable ##################################################################### if float(n_assessments) == 2.0: ser['Asst. 2: % Pass'] = (100 * (sum(df['Assessment 2 P or F'] == 'P')) / n_attend) ser['Asst. 2: % F (Not DR or FR)'] = (100 * sum(df['Assessment 2 Grade'] == 'F') / n_total) ser['Asst. 2: % W'] = (100 * sum(df['Assessment 2 Grade'] == 'W') / n_attend) ser['Asst. 2: % FR'] = (100 * sum(df['Assessment 2 Grade'] == 'FR') / n_attend) ser['Asst. 2: % DR'] = (100 * sum(df['Assessment 2 Grade'] == 'DR') / n_attend) ser['Asst. 2: % Blank'] = (100 * sum(df['Assessment 2 Grade'].isnull()) / n_attend) ser['Asst. 2: % LF'] = (100 * sum(df['Assessment 2 Grade'] == 'LF') / n_attend) if module != 'LSM': ser['Asst. 2: % No Sub'] = \ (100 * sum(pd.to_numeric(df['Assessment 2 Mark'], errors='coerce') == 0.0 ) / n_attend) ser['Asst. 2: % Failed Sub'] = \ (100 * sum((pd.to_numeric(df['Assessment 2 Mark'], errors='coerce') > 0.0) & (pd.to_numeric(df['Assessment 2 Mark'], errors='coerce') < 40.0)) / n_attend) ser['Asst. 2 F: % No Sub'] = \ (100 * sum((pd.to_numeric(df['Assessment 2 Mark'], errors='coerce') == 0.0) & (df['Assessment 2 P or F'] == 'F')) / sum(df['Assessment 2 P or F'] == 'F')) ser['Asst. 2 F: % Failed Sub'] = \ (100 * sum((pd.to_numeric(df['Assessment 2 Mark'], errors='coerce') != 0.0) & (df['Assessment 2 P or F'] == 'F')) / sum(df['Assessment 2 P or F'] == 'F')) ser['Asst. 2: % Submit that Pass'] = \ (100 * sum((pd.to_numeric(df['Assessment 2 Mark'], errors='coerce') > 0.0) & (df['Assessment 2 P or F'] == 'P')) / sum(pd.to_numeric(df['Assessment 2 Mark'], errors='coerce') > 0.0)) else: ser['Asst. 2: % No Sub'] = np.NaN ser['Asst. 2: % Failed Sub'] = np.NaN ser['Asst. 2 F: % No Sub'] = np.NaN ser['Asst. 2 F: % Failed Sub'] = np.NaN ser['Asst. 2: % Submit that Pass'] = np.NaN if sum(df['Assessment 2 Grade'] == 'FR') != 0: ser['Asst. 2: % FR that Pass'] = \ (100 * sum((df['Assessment 2 Grade'] == 'FR') & (pd.to_numeric( df['Assessment 1 Mark'],errors='coerce') + pd.to_numeric( df['Assessment 2 Mark'],errors='coerce') >= 80.0)) / sum(df['Assessment 2 Grade'] == 'FR')) try: ser['Asst. 2: % DR that Pass'] = \ (100 * sum((df['Assessment 2 Grade'] == 'DR') & (pd.to_numeric( df['Assessment 1 Mark'],errors='coerce') + pd.to_numeric( df['Assessment 2 Mark'],errors='coerce') >= 80.0)) / sum(df['Assessment 2 Grade'] == 'DR')) except: print(year, module + "ser['Asst. 2: % DR that Pass']") ##################################################################### # return the series ##################################################################### ser = ser.T return ser
274b7781d01fb920ecf63a0a250c5b2f298b25e1
nikhilcogni1986/Python-Selenium
/DataTypes/lists.py
338
4.34375
4
movies = ["Lion King", "Lagaan", "James Bond"] print(movies) # print each item by index print(movies[0]) print(movies[1]) print(movies[2]) # print the last item print(movies[-1]) # print the range of values print(movies[0:2]) # use of insert movies.insert(3, "Don") print(movies) # Append a value to list movies.append("Hero") print(movies)
d40f3ee2e7bda76b6d458f19afdbf6fe08e4a54d
the16thpythonist/JTShell
/util/error.py
933
3.625
4
__author__ = 'Jonas' from util.message import Message class Error(Exception): """ the base class for every following error to be defined, this has to be used instead of exceptions, as exceptions within the parser for example would terminate the whole program instead of just the progress """ def __init__(self): self.message = None class SyntaxError(Exception): """ the exception given, when dealing with syntax errors within the user input, which may be the error most often occuring within a shell program :var message: (Message) the message which should be printed when handling the error :parameter message: (Message) the message which should be printed when handling the error """ def __init__(self, message): self.message = Message("error", message) class ProcessError(Error): def __init__(self, string): self.message = Message("error", string)
c69fab52442b45dae38fc5696efc306ab9954fc8
annapastwa/leet30dayschallenge
/April30dayschallenge/day24lru_cache.py
2,373
3.578125
4
import collections class LRUCache(object): def __init__(self, capacity): """ :type capacity: int """ self.dic = collections.OrderedDict() self.remain = capacity def get(self, key): """ :type key: int :rtype: int """ if key not in self.dic: return -1 v = self.dic.pop(key) self.dic[key] = v # set key as the newest one return v def put(self, key, value): """ :type key: int :type value: int :rtype: None """ if key in self.dic: self.dic.pop(key) else: if self.remain > 0: self.remain -= 1 else: # self.dic is full self.dic.popitem(last=False) self.dic[key] = value # old code # Your LRUCache object will be instantiated and called as such: # obj = LRUCache(capacity) # param_1 = obj.get(key) # obj.put(key,value) # cache = LRUCache(2) # /* capacity */ # cache.put(1, 1) # cache.put(2, 2) # cache.get(1) # returns 1 # cache.put(3, 3) # evicts key 2 # cache.get(2) # returns -1 (not found) # cache.put(4, 4) # evicts key 1 # cache.get(1) # returns -1 (not found) # cache.get(3) # returns 3 # cache.get(4) # returns 4 # # print(cache.store) ##### # cache = LRUCache(1) # /* capacity */ # cache.get(0) # returns 1 # print(cache.store) # # ["LRUCache","get"] # # [[1],[0]] # # cache = LRUCache(2) # /* capacity */ # cache.put(2, 1) # cache.put(2, 2) # cache.get(2) # returns 1 # cache.put(1, 1) # cache.put(4, 1) # cache.get(2) # print(cache.store) # Input: # ["LRUCache","put","put","get","put","put","get"] # [[2],[2,1],[2,2],[2],[1,1],[4,1],[2]] # Output: # [null,null,null,1,null,null,-1] # Expected: # [null,null,null,2,null,null,-1] # cache = LRUCache(2) # /* capacity */ # cache.get(2) # returns 1 # cache.put(2, 1) # cache.put(1, 1) # cache.put(2, 3) # cache.put(4, 1) # cache.get(1) # cache.get(2) # print(cache.store) # Input: # ["LRUCache","get","put","get","put","put","get","get"] # [[2],[2],[2,6],[1],[1,5],[1,2],[1],[2]] # Output: # [null,-1,null,-1,null,null,2,-1] # Expected: # [null,-1,null,-1,null,null,2,6] cache = LRUCache(2) # /* capacity */ cache.put(2, 1) cache.put(1, 1) cache.put(2, 3) cache.put(4, 1) cache.get(1) # returns 1 cache.get(2) print(cache.get(2))
4888e92026c69100c2f4cb5aaa0d1b59a28f4646
raianmol172/data_structure_using_python
/delete_data_in_list.py
1,012
3.984375
4
class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def printList(self): temp = self.head while temp is not None: print(" %s" %(temp.data)) temp = temp.next def deleteNode(self, value): temp = self.head if temp.data == value: self.head = temp.next temp = None return while temp is not None: if temp.data == value: break prev = temp temp = temp.next if temp is None: return prev.next = temp.next temp = None l1 = LinkedList() l1.head = Node('A') l2 = Node('B') l3 = Node('C') l4 = Node('D') l5 = Node('E') l1.head.next = l2 l2.next = l3 l3.next = l4 l4.next = l5 print("before deletion: ") l1.printList() print("after deletion") l1.deleteNode('A') l1.deleteNode('C') l1.deleteNode('E') l1.printList()
ff1388b0feaf7e7920546d2437ac0bf8ddd66205
Vasilic-Maxim/LeetCode-Problems
/problems/1260. Shift 2D Grid/2 - In-place + Reverse.py
742
3.640625
4
from typing import List class Solution: """ Time: O(m * n) Space: O(1) """ def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]: rows, cols = len(grid), len(grid[0]) elements = rows * cols k %= elements if k: self.reverse(grid, 0, elements) self.reverse(grid, 0, k) self.reverse(grid, k, elements) return grid def reverse(self, grid: List[List[int]], start: int, end: int): rows, cols = len(grid), len(grid[0]) for i in range((end - start) // 2): sr, sc = divmod(start + i, cols) er, ec = divmod(end + ~i, cols) grid[sr][sc], grid[er][ec] = grid[er][ec], grid[sr][sc]
c15f6eb71068f927a060517ddd1859745664ebd9
Jithin0801/DS-and-Algorithms
/PerfectNumber/perfectnum.py
456
3.640625
4
l = [] def findDivisiors(n): for i in range(1, n): if n%i == 0: l.append(i) def isPerfect(n): findDivisiors(n) sum = 0 for i in range(0, len(l)): sum += l[i] if n == sum: return True else: return False def main(): n = int(input("Enter a number: ")) if isPerfect(n): print(f"{n} is a perfect number") else: print(f"{n} is not a perfect number") main()
5cdefda45a0672e2cc314fd8d66336a6c6a29b41
AkashPatel18/Basic
/video 6.3/py3let.py
213
3.921875
4
x= 10 y=6 z=8 max1 = max(x,y,z) if max1 == x: max2=y max3=z elif max1 == y: max2=z max3=x else: max2=x max3=y if max1**2 == max2**2 + max3**2: print("py tip") else: ("not")
f767be663523d8a2bfe5adb8eea29f4101a69611
hsono1/Python
/Python_Fundamentals/pyexample2.py
483
3.984375
4
str = "If monkeys like bananas, then I must be a monkey!" print str.find('monkey') var1 = str.find('monkey') + 1 print str.find('monkey',var1) str2 = str print str2.replace('monkey', 'alligator') x = [2,54,-2,7,12,98] print min(x) print max(x) x = ["hello",2,54,-2,7,12,98,"world"] print x[0] print x[len(x)-1] y = [x[0], x[len(x)-1]] print y x = [19,2,54,-2,7,12,98,32,10,-3,6] x.sort() print x y = [x[0], x[1]] print y x.remove(-2) x.remove(-3) x.insert(0, y) print x
8d103bd93679ea4fbc2eae40a8287ec5d1aa3aee
LovepreetSingh-09/Python_Basics
/Lists1.py
1,511
4
4
numbers=[5,23,13,4,7,3,15] print(range(len(numbers))) for i in range(len(numbers)): numbers[i]=numbers[i]*2 print(numbers[i]) print(numbers) for i in numbers: print(i) empty=[] for x in empty: print('This never happens') # the body will never executes in empty listo listo=['hlo',3,3.5,[9,'rutherford']] print(listo) a=[1,2,3] b=[4,5,6] print(a+b) print(a*3) print(listo[1:5]) print(listo[:]) listo[1:3]=['hi',5] print(listo) listo.append(a) # Append Make a nested listo in the listo itself and returns no value print(listo) print(listo[3]) listo.extend(b) # Extend makes new elements in the listo and returns no value print(listo) l=['b','d','a','b'] l.sort() # sort does'nt returns values print(l) x=listo.pop(3) # Deletes the 3rd index from listo print(listo,'\n',x) y=listo.pop() # Deletes the last index value print(listo,'\n',y) del listo[3] # Same as last but don't return the value print(listo) print(len(numbers)) print(max(numbers)) print(min(numbers)) print(sum(numbers)) print(sum(numbers)/len(numbers)) listo=[] while True: n=input("Enter a number.....") try: value=float(n) listo.append(value) except: if n=='done': break else: print("Wrong value") print(listo) print(sum(listo)/len(listo)) fh = open('romeo.txt') ist = list() for line in fh: word = line.rstrip() ele = line.split() for element in ele: if element not in ist: ist.append(element) ist.sort() print(ist)
2c88a71ed09fb2d255817a9ebf42f11c2a546c26
bradsbrown/battleship
/battleship.py
10,052
3.640625
4
#! /usr/bin/env python from collections import namedtuple from enum import Enum, auto import random import click '''Welcome to Battleship! Below you'll find settings to adjust to your liking. A few things to note while playing: Grid Key: 0 - a blank cell on the grid * - an unhit cell containing a piece of ship ! - a ship cell that has been hit X - a shot taken that did not hit a ship''' # Settings GRID_SIZE = 10 SHIP_MIN = 2 SHIP_MAX = 5 NUM_SHIPS = 3 NUM_TURNS = 10 class Result(Enum): RETRY = auto() MISS = auto() HIT = auto() ResultTuple = namedtuple('ResultTuple', ['result', 'message']) ResultTuple.__new__.__defaults__ = (None, '') class Game(object): def __init__( self, p1_name=None, p2_name='Computer', is_2p=False, debug=False ): self.ship_sizes = self.size_ships() self.is_2p = is_2p self.players = self.setup_players(p1_name, p2_name, debug=debug) self._active_player = 0 self._last_result = ResultTuple(Result.MISS) def setup_players(self, p1_name, p2_name, **kwargs): return [ Player(p1_name, self.ship_sizes, **kwargs), Player( p2_name, self.ship_sizes, is_computer=not self.is_2p, **kwargs ) ] # determine ship lengths def size_ships(self): return [random.randint(SHIP_MIN, SHIP_MAX) for _ in range(NUM_SHIPS)] @property def over(self): if self.is_2p: return any(x.board.is_finished for x in self.players) else: return any(x.out_of_turns for x in self.players) @property def player(self): return self.players[self._active_player] @property def opponent(self): return self.players[{0: 1, 1: 0}[self._active_player]] def switch_turns(self): self._active_player = {0: 1, 1: 0}[self._active_player] def fire_shot(self, guess_row, guess_col): resulttuple = self.opponent.board.fire_shot(guess_row, guess_col) if resulttuple.result is Result.RETRY: return resulttuple if self.is_2p: self.switch_turns() else: if resulttuple.result is Result.MISS: self.player.use_turn() return resulttuple def play(self): self.setup() while not self.over: self.do_turn() self.end_game() def setup(self): if self.is_2p: for player in self.players: player.do_board_setup() def do_turn(self): self._last_result = ResultTuple(Result.RETRY, self._last_result.message) while self._last_result.result is Result.RETRY: self.opponent.board.print_board(hide_ships=True) if self._last_result.message: click.echo(self._last_result.message) if not self.is_2p: click.echo( f'{self.player.name} has ' f'{self.player.turns_remaining} turns remaining.' ) click.echo('Your turn, {}'.format(self.player.name)) guess_col = get_valid_coordinate('col') guess_row = get_valid_coordinate('row') self._last_result = self.fire_shot(guess_row, guess_col) def end_game(self): click.secho('Game over!', bg='green', fg='red') if self.is_2p: opponent_done = self.opponent.board.is_finished winner = self.player if opponent_done else self.opponent click.secho('{} wins!'.format(winner.name), fg='green') else: status = self.opponent.board.is_finished result, color = { True: ('won', 'green'), False: ('lost', 'red') }[status] click.secho(f'You {result}!', fg=color) click.secho('Thanks for playing Battleship!', fg='blue') class Player(object): def __init__(self, name, ship_sizes, is_computer=False, debug=False): self.name = name self.board = BoardSet(ship_sizes, autofill=is_computer, debug=debug) self.turns_remaining = NUM_TURNS def use_turn(self): self.turns_remaining -= 1 @property def out_of_turns(self): return self.turns_remaining <= 0 def do_board_setup(self): click.secho(f"Time to set up {self.name}'s ships", fg='green') click.pause() for ship in self.board.ship_sizes: self.board.player_build_ship(ship) click.clear() click.secho('Great, all set!', fg='green') click.pause() class BoardSet(object): empty_cell = '0' ship_cell = click.style('*', fg='blue') hit_cell = click.style('!', fg='green') miss_cell = click.style('X', fg='red') horizontal = 'hor' vertical = 'vert' valid_orientations = [horizontal, vertical] untried = (empty_cell, ship_cell) def __init__(self, ship_sizes, autofill=True, debug=False): self.size = GRID_SIZE self.ship_board = self.generate_board() self.ship_sizes = ship_sizes self.debug = debug if autofill: for ship in self.ship_sizes: self.autofill_ship(ship) def generate_board(self): return [[self.empty_cell] * self.size for _ in range(self.size)] def _prep_row(self, row, hide_ships): if self.debug or not hide_ships: return row return self._hide_ships(row) def print_board(self, hide_ships=False, message=''): click.clear() for row in self.ship_board: click.echo(' '.join(self._prep_row(row, hide_ships))) if message: click.echo(message) def _hide_ships(self, row): return [x.replace(self.ship_cell, self.empty_cell) for x in row] def fire_shot(self, guess_row, guess_col): cell = self.get_cell(guess_row, guess_col) if cell in self.untried: self.mark_board( guess_row, guess_col, { self.empty_cell: self.miss_cell, self.ship_cell: self.hit_cell }[cell] ) resulttuple = { self.empty_cell: ResultTuple(Result.MISS, 'You missed!'), self.ship_cell: ResultTuple(Result.HIT, 'A hit!') }[cell] else: resulttuple = ResultTuple( Result.RETRY, 'You already guessed that one!' ) return resulttuple def mark_board(self, guess_row, guess_col, mark=None): mark = mark or self.miss_cell self.ship_board[guess_row][guess_col] = mark return self.ship_board def get_cell(self, row, col): return self.ship_board[row][col] @property def is_finished(self): return not any(self.ship_cell in row for row in self.ship_board) def player_build_ship(self, length): self.print_board() click.secho(f'This ship is {length} cells long.', fg='green') orientation = click.prompt( 'Should it be horizontal (hor) or vertical (vert)?', type=click.Choice(self.valid_orientations) ) row_max, col_max = self.get_maxes(orientation, length) is_inserted = False while not is_inserted: click.secho('What cell should it start on?', fg='green') start_col = get_valid_coordinate('col', col_max + 1) start_row = get_valid_coordinate('row', row_max + 1) is_inserted = self.insert_ship(orientation, length, start_row, start_col) if not is_inserted: click.secho('That overlaps another ship! Try again!', fg='red') def autofill_ship(self, length): orientation = random.choice(self.valid_orientations) row_max, col_max = self.get_maxes(orientation, length) is_inserted = False while not is_inserted: start_row = random.randint(0, row_max) start_col = random.randint(0, col_max) is_inserted = self.insert_ship(orientation, length, start_row, start_col) def _build_static_axis(self, start_coord, length): return [start_coord] * length def _build_dynamic_axis(self, start_coord, length): return [start_coord + x for x in range(length)] def insert_ship(self, orientation, length, start_row, start_col): row_builder, col_builder = { self.horizontal: ( self._build_static_axis, self._build_dynamic_axis ), self.vertical: (self._build_dynamic_axis, self._build_static_axis) }[orientation] coords = list(zip( row_builder(start_row, length), col_builder(start_col, length) )) if any(self.get_cell(*x) != self.empty_cell for x in coords): return False for coord in coords: self.mark_board(*coord, mark=self.ship_cell) return True def get_maxes(self, orientation, length): big_max = GRID_SIZE - 1 small_max = GRID_SIZE - length return { self.horizontal: (big_max, small_max), self.vertical: (small_max, big_max) }[orientation] def get_valid_coordinate(category, biggest=GRID_SIZE): msg = f'Enter {category} in range 1-{biggest}' return click.prompt(msg, type=click.IntRange(1, biggest)) - 1 def get_player_name(player_num): return click.prompt(f'Player {player_num} name?') # begin game @click.command() @click.option( '--number-of-players', '-n', type=click.IntRange(1, 2), prompt="How many players?" ) @click.option('--debug', is_flag=True) def start_game(number_of_players, debug): click.secho("Let's play Battleship!", fg='green') game = Game(p1_name=get_player_name(1), p2_name=get_player_name(2) if number_of_players == 2 else None, is_2p=(number_of_players == 2), debug=debug) game.play() if __name__ == "__main__": start_game()
dba3e8598d0b5eb0759fec7f081ed63c5bcd3f3e
emilyfaccin/python
/learning_exercises/python_para_zumbis/twp230.py
446
4.1875
4
# 01 ler um numero do usuario e imprimir os numeros impares de 1 até o numero # 02 imprimir os 10 primeiros multiplos de 3 # 03 calcular a média de 10 numeros inteiros # 01 num = int(input('Digite um numero: ')) x = 1 while x <= num: print(x) x += 2 # 02 cont = 1 while cont <= 10: print(cont * 3) cont += 1 # 03 cont = 0 soma = 0 while cont < 10: soma += int(input('Digite um numero: ')) cont += 1 print(soma/cont)
01f4f91f4ad4d83ead382f64392dc0b43c295621
TonyJenkins/python-workout
/18-final-line/get_final_line.py
299
3.84375
4
#!/usr/bin/env python3 """ Exercise 18: Final Line Display the final (last) line of a file. """ def get_final_line(filename): f = open(filename) line = f.readlines()[-1][:-1] f.close() return line if __name__ == '__main__': print(get_final_line('rev_eli.txt'))
4513863f560a83210f562681747bc7cbda31affe
uccser/codewof
/codewof/programming/content/en/rotate-words/solution.py
67
3.796875
4
words = input("Words please: ") for char in words: print(char)
4df32576bd926367b98a28dba9f1f4d2c9db7ad1
Mikhail713-xph/exp
/perim.py
991
3.796875
4
''' площадь круга = 2ПR, площадь прямоугльника = a*b, треуг =pow(p(p-a)(p - b)(p-c)). p =(a+b+c)/2. ''' operation = input() if operation == 'круг': r = float(input()) pi = float(3.14) print(float((r ** 2) * pi)) if operation == 'прямоугольник': a = float(input()) b = float(input()) print(a * b) if operation == 'треугольник': a = float(input()) b = float(input()) c = float(input()) p = float((a + b + c) / 2) s = float(p(p - a)(p - b)(p - c)) print(float(pow(s, 0.5))) ''' a = float(input()) b = float(input()) c = float(input()) r = float(input()) pi = float(3.14) p = float((a + b + c) / 2) s = float(p(p - a)(p - b)(p - c)) if operation == 'прямоугольник': print(a * b) if operation == 'треугольник': print(float(pow(s, 0.5))) if operation == 'круг': print(float((r ** 2) * pi)) else: print('ytdthyjt ltqcndbt')'''
9b63184edc5dc1b76737e9502f95cb42534ad1ad
Devil-Rick/Advance-Task---4
/Single Number.py
316
3.640625
4
""" Given a non-empty array of integers nums, every element appears twice except for one. Find that single one. You must implement a solution with a linear runtime complexity and use only constant extra space. """ n = list(map(int, input().split(','))) for i in n: if n.count(i) == 1: print(i)
29758d76160eebcb61a1d1a25f3bc5fd2ea3f1a9
Ankan-nath/DNA-analysis-for-plasma-donation-in-Covid-19-crisis
/DNA-analysis-of-Recovered-COVID-19-master/hackathon.py
3,510
3.65625
4
filename="MN908947.txt" f=open(filename,"r") fp=open("DNA.txt","w") ft=open("Patient.txt","w") # Dynamic Programming implementation of LCS problem def lcs(X , Y): # find the length of the strings m = len(X) n = len(Y) # declaring the array for storing the dp values L = [[None]*(n+1) for i in range(m+1)] # """Following steps build L[m+1][n+1] in bottom up fashion # Note: L[i][j] contains length of LCS of X[0..i-1] # and Y[0..j-1]""" for i in range(m+1): for j in range(n+1): if i == 0 or j == 0 : L[i][j] = 0 elif X[i-1] == Y[j-1]: L[i][j] = L[i-1][j-1]+1 else: L[i][j] = max(L[i-1][j] , L[i][j-1]) # L[m][n] contains the length of LCS of X[0..n-1] & Y[0..m-1] return L[m][n] #end of function lcs X = input("Enter the genetic Sequence of the patient : " ) a=[];b=[] lines=f.readlines() for Y in lines: k=lcs(X, Y) print ("Length of LCS is ",k,"Genetic Subsequence",Y) b.append(k) a.append(k) b=sorted(b,reverse=True) maximum=b[0] for i in range(len(b)): if(maximum==a[i]): fp.write(lines[i]) ft.write(X) fp.close() f.close() ft.close() inputfile ="DNA.txt" fp = open(inputfile, "r") ft=open("Patient.txt","r") lines= fp.readlines() pop=[];push=[] def translate(seq): table = { 'ATA':'I', 'ATC':'I', 'ATT':'I', 'ATG':'M', 'ACA':'T', 'ACC':'T', 'ACG':'T', 'ACT':'T', 'AAC':'N', 'AAT':'N', 'AAA':'K', 'AAG':'K', 'AGC':'S', 'AGT':'S', 'AGA':'R', 'AGG':'R', 'CTA':'L', 'CTC':'L', 'CTG':'L', 'CTT':'L', 'CCA':'P', 'CCC':'P', 'CCG':'P', 'CCT':'P', 'CAC':'H', 'CAT':'H', 'CAA':'Q', 'CAG':'Q', 'CGA':'R', 'CGC':'R', 'CGG':'R', 'CGT':'R', 'GTA':'V', 'GTC':'V', 'GTG':'V', 'GTT':'V', 'GCA':'A', 'GCC':'A', 'GCG':'A', 'GCT':'A', 'GAC':'D', 'GAT':'D', 'GAA':'E', 'GAG':'E', 'GGA':'G', 'GGC':'G', 'GGG':'G', 'GGT':'G', 'TCA':'S', 'TCC':'S', 'TCG':'S', 'TCT':'S', 'TTC':'F', 'TTT':'F', 'TTA':'L', 'TTG':'L', 'TAC':'Y', 'TAT':'Y', 'TAA':'_', 'TAG':'_', 'TGC':'C', 'TGT':'C', 'TGA':'_', 'TGG':'W', } protein ="" n=len(seq)-1 if n%3 == 0: for i in range(0, n, 3): codon = seq[i:i + 3] protein= protein+table[codon] return protein for line in lines: k=translate(line) pop.append(k) readl=ft.read() t=translate(readl) def lcs(X , Y): # find the length of the strings m = len(X) n = len(Y) # declaring the array for storing the dp values L = [[None]*(n+1) for i in range(m+1)] # """Following steps build L[m+1][n+1] in bottom up fashion # Note: L[i][j] contains length of LCS of X[0..i-1] # and Y[0..j-1]""" for i in range(m+1): for j in range(n+1): if i == 0 or j == 0 : L[i][j] = 0 elif X[i-1] == Y[j-1]: L[i][j] = L[i-1][j-1]+1 else: L[i][j] = max(L[i-1][j] , L[i][j-1]) # L[m][n] contains the length of LCS of X[0..n-1] & Y[0..m-1] return L[m][n] #end of function lcs percentage=[] for Y in pop: k=lcs(t, Y) percentage.append((k/len(t))*100) for i in range(len(percentage)): print("Genetic Sequence",lines[i],"percentage",percentage[i]) ft.close() fp.close()