blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
55d726da1f5c4d38db5efa9a3ca99a5f01fcc87a
clsulli/DataFaker
/Crime.py
2,024
3.6875
4
import random import time class Crime: def __init__(self, caseID): self.caseID = caseID self.date = None self.domestic = False self.crimeTypes = ['Arson', 'Assault', 'Blackmail', 'Bribery', 'Burglary', 'Embezzlement', 'Extortion', 'False pretenses', 'Larceny', 'Pickpocketing', 'Stealing', 'Robbery', 'Smuggling', 'Tax Evasion', 'Theft', 'Murder'] self.crimeType = None def getCaseID(self): return self.caseID def getDate(self): return self.date def getDomestic(self): return self.domestic def getFbiID(self): return self.fbiID def getDescription(self): return self.crimeType def getCrimeType(self): self.crimeType = random.choice(self.crimeTypes) choices = [True, False] if self.crimeType == 'Assault': choice = random.choice(choices) self.domestic = choice def strTimeProp(start, end, format, prop): """Get a time at a proportion of a range of two formatted times. start and end should be strings specifying times formated in the given format (strftime-style), giving an interval [start, end]. prop specifies how a proportion of the interval to be taken after start. The returned time will be in the specified format. """ stime = time.mktime(time.strptime(start, format)) etime = time.mktime(time.strptime(end, format)) ptime = stime + prop * (etime - stime) return time.strftime(format, time.localtime(ptime)) def randomDate(start, end, prop): return strTimeProp(start, end, '%m/%d/%Y %I:%M %p', prop) self.date = randomDate("1/1/2017 12:00 AM", "12/31/2017 11:59 PM", random.random()) def toString(self): return "CASE ID: " + str(self.caseID) + " DATE: " + str(self.date) + " DOMESTIC: " + str(self.domestic) + " CRIME: " + str(self.crimeType)
b5b4612ebb8c8bf09a5811b3ca00867d26c03d82
aikem26/test1
/urok19/ter.py
67
3.71875
4
a = [4, 2, 5, 6] b = [num if num > 3 else 10 for num in a] print(b)
18c0853d3337a6ec1abe08e1cc6518ead4b9d5e9
lxj0276/note-1
/algorithm/top_interview/grab2.py
546
3.90625
4
# you can write to stdout for debugging purposes, e.g. # print("this is a debug message") def solution(S): # write your code in Python 3.6 if not S: return S while 'AA' in S or 'BB' in S or 'CC' in S: S = S.replace('AA', '') S = S.replace('BB', '') S = S.replace('CC', '') print(S) return S def main(): S = 'ABCBBCBA' print(solution(S)) S = 'BABABA' print(solution(S)) # r = solution([1, 3, 6, 4, 1, 2, -1]) # print(r) if __name__ == '__main__': main()
668e7cd085d2d3d336f4284c16705bdfe61ac4f9
bwest619/Python-Crash-Course
/Ch 4 - Working With Lists/animals.py
308
3.828125
4
# try it yourself, page 60 cats = ['tiger', 'jaguar', 'cheetah'] for cat in cats: print(cat.title()) print("\n") cats = ['tiger', 'jaguar', 'cheetah'] for cat in cats: print("Oh, how I would love to own a " + cat.title() + "!") print("All of these animals are in the cat family. And can eat you.")
b7a7ce9379455e7047f5cfd5ace4b8eef4cbc29e
nav-commits/Python-code
/Practice.py
849
4.03125
4
import random # function name validation def nameexcution (fname, lname, names): # if check if its true if fname == 'gurveer' and lname == 'gill': print( fname + ' is his first name ' + 'and his lastname is ' + lname) else: print('name not found') for name in names: print( 'other names as well like ' + name) # here we have dicitonary for user user = {"name": "Moe" , "age":27 ,"email": "[email protected]"} print('Moes email is : '+ user['email']) nameexcution('Gurveer','Gill',['John','Joe', 'Moe']) # code to check if person can afford priceguess = random.randint(0,200) content = ' the price is {} $ for the table and you can afford this!' name = input("enter name:") # if checks if priceguess >= 120: print(content.format(priceguess) + name) else: print('you cant afford this')
39c6be0f830da1a60ea4f2c10a9e2a1ff30446a4
Aishee0810/HackerRank
/removecharanagram.py
571
3.6875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jun 19 17:09:04 2019 @author: aishee """ from collections import Counter def removechar(s1,s2): dict1=Counter(s1) dict2=Counter(s2) print(dict1) key1=dict1.keys() key2=dict2.keys() print(key1) count1=len(key1) count2=len(key2) print(count1) set1=set(key1) commonKeys = len(set1.intersection(key2)) if (commonKeys == 0): print(count1 + count2) else: print((max(count1, count2)-commonKeys)) s1='bcadeh' s2='heafg' removechar(s1,s2)
5f7954c6a643b9a41d89b5d530e51b66ef3924cd
codemunkee/examples
/fizzbuzz.py
250
3.703125
4
#!/usr/bin/env python for i in range(1, 101): msg = str() if (i % 3 == 0) and (i % 5 == 0): msg = 'FizzBuzz' elif i % 3 == 0: msg = 'Fizz' elif i % 5 == 0: msg = 'Buzz' else: msg = i print msg
429f3f342aa5c3268c8c1ee6e85b727d6a0b959b
marmarmar/dungeon_game
/cold_warm_hot_game.py
3,719
3.8125
4
import random import os import time from termcolor import colored, cprint def intro_graphic(): """Read graphic from file cold_intro.txt""" data = [line.strip() for line in open("cold_intro.txt", 'r')] print('\n\n') for i in range(len(data)): if i == 0: print(" ", end='') if i == 2: print(" ", end='') # if i > 6: # print(" ", end='') for j in range(len(data[i])): time.sleep(0.005) cprint("{}".format(data[i][j]), 'red', attrs=['bold'], end='') print() print() def rand_num(): i = 0 rand_list = [] while not i == 3: rand_list.append(random.randint(0, 9)) i = len(set(rand_list)) end_list = list(set(rand_list)) if end_list[0] == 0: buffor = end_list[0] end_list[0] = end_list[1] end_list[1] = buffor return end_list[0], end_list[1], end_list[2] def comparison_numbers(rand): """ Converts the random number to list Cheks length and type of input Prints the result of the comparison """ hot = 0 warm = 0 rand = list(rand) attempt = 0 print(rand) while attempt < 10: user_input = list(input('\t\tGuess #{}: \n\t\t'.format(attempt+1))) if len(user_input) != 3 or (user_input[0] in user_input[1:]) or user_input[1] == user_input[2]: print("\n\t\tYOU MUST INPUT 3 OTHERS DIGITS\n") continue try: int(user_input[0]) int(user_input[1]) int(user_input[2]) except ValueError: print("\n\t\tYOU MUST INPUT DIGITS\n") continue i = 0 while i != 3: user_input[i] = int(user_input[i]) i += 1 if user_input == rand: hot = 3 # return i = 0 if hot != 3: hot = 0 warm = 0 while not i == 3: compare_num = rand.count(user_input[i]) if compare_num > 0: # if rand.index(user_input[i]) == i: if rand[i] == user_input[i]: hot += 1 else: warm += 1 i += 1 print('\t\t', end='') if hot > 0: if hot == 3: print("HOT " * hot, end='') return 1 attempt = 10 else: print("HOT " * hot, end='') if warm > 0: print("WARM " * warm, end='') if hot == 0 and warm == 0: print('COLD', end=" ") print('\n') hot = 0 warm = 0 attempt += 1 return 0 def print_intro(): print("\n\nI am thinking of a ", end='') cprint("3", 'green', end='') print('-digit number. Try to guess what it is.\n') print("Here are some clues:\n") print('When I say: That means:\n') print(" Cold No digit is correct.\n\n" + " Warm One digit is correct but in the wrong position.\n\n" + " Hot One digit is correct and in the right position.\n") print("I have thought up a number. You have ", end='') cprint("10", 'green', end=' ') print("guesses to get it.\n") def run(): os.system('clear') # clear screen intro_graphic() time.sleep(2) print_intro() result = comparison_numbers(rand_num()) if result == 1: os.system('clear') print("\n\n\t\tYOU WIN!!!\n\n") time.sleep(2) return 1 if result == 0: os.system('clear') print("\n\n\t\tYOU LOSE...\n\n") time.sleep(2) return 0 # run() # main()
58d9cf515080f7d26f64e6525997e0d8ef296f9f
cinhori/LeetCode
/python_src/101.对称二叉树.py
2,918
3.953125
4
# # @lc app=leetcode.cn id=101 lang=python3 # # [101] 对称二叉树 # # https://leetcode-cn.com/problems/symmetric-tree/description/ # # algorithms # Easy (51.08%) # Likes: 766 # Dislikes: 0 # Total Accepted: 137.7K # Total Submissions: 269.6K # Testcase Example: '[1,2,2,3,4,4,3]' # # 给定一个二叉树,检查它是否是镜像对称的。 # # # # 例如,二叉树 [1,2,2,3,4,4,3] 是对称的。 # # ⁠ 1 # ⁠ / \ # ⁠ 2 2 # ⁠/ \ / \ # 3 4 4 3 # # # # # 但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的: # # ⁠ 1 # ⁠ / \ # ⁠ 2 2 # ⁠ \ \ # ⁠ 3 3 # # # # # 进阶: # # 你可以运用递归和迭代两种方法解决这个问题吗? # # # @lc code=start # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None from queue import Queue class Solution: #40ms, 84.76%; 13.8MB, 6.06% # 递归 # def isSymmetric(self, root: TreeNode) -> bool: # if root is None: return True # return self._isSymmetric(root.left, root.right) # def _isSymmetric(self, left: TreeNode, right: TreeNode): # if left is right: return True # if (left and right) is None: return False # if left.val == right.val: # return self._isSymmetric(left.left, right.right) and self._isSymmetric(left.right, right.left) # return False # 52ms, 29.96%; 14MB, 6.06% # def isSymmetric(self, root: TreeNode) -> bool: # if root is None: return True # left, right = Queue(), Queue() # left.put(root.left) # right.put(root.right) # while not left.empty() and not right.empty(): # left_node = left.get() # right_node = right.get() # if left_node is right_node: continue # if (left_node and right_node) is None: return False # if left_node.val != right_node.val: return False # else: # left.put(left_node.left) # left.put(left_node.right) # right.put(right_node.right) # right.put(right_node.left) # return True # 60ms, 16.82%; 14MB, 6.06%; def isSymmetric(self, root: TreeNode) -> bool: if root is None: return True nodes = Queue() nodes.put(root.left) nodes.put(root.right) while not nodes.empty(): left_node = nodes.get() right_node = nodes.get() if left_node is right_node: continue if (left_node and right_node) is None: return False if left_node.val != right_node.val: return False nodes.put(left_node.left) nodes.put(right_node.right) nodes.put(left_node.right) nodes.put(right_node.left) return True # @lc code=end
a2b24178b9a21a622c063a281b6ebd6f6ff9e5da
bfollek/twitter_easy_and_hard
/random_string.py
291
3.578125
4
import random import string class RandomString: """ From https://pythontips.com/2013/07/28/generating-a-random-string/ """ @staticmethod def make(size=32, chars=string.ascii_uppercase + string.digits): return "".join(random.choice(chars) for x in range(size))
bdfb754c2d114f7b62f33351f48a2eccefc830e8
DaniloBP/Python-3-Bootcamp
/max_and_min.py
1,548
4.34375
4
# max() returns the largest item in an iterable or between two elements. nums = (45,-555,36,95,88) # print(f"Max value in {nums}: {max(nums)}\n") # print(f"Min value in {nums}: {min(nums)}\n") expr = "Nice to meet you." # print(f"Max value in {expr}: {max(expr)}\n") # print(f"Min value in {expr}: {min(expr)}\n") names = ["Tim", "Ariana", "Rachel", "Edris", "Latifa", "Zendaya"] # print(f"Max value in {names}: {max(names)}\n") # print(f"Min value in {names}: {min(names)}\n") # print(f"The longest name in {names} is { max( names, key= lambda name: len(name) ).upper() }\n") # print(f"The shortest name in {names} is { min( names, key= lambda name: len(name) ).upper() }\n") users = [ { "username" : "Mchammer", "num_comments" : 14}, { "username" : "Paul_George", "num_comments" : 22}, { "username" : "KittyKat", "num_comments" : 88}, { "username" : "Rainbow_Killer", "num_comments" : 5}, { "username" : "GodsSlayer", "num_comments" : 11}, { "username" : "Tchala", "num_comments" : 154}, { "username" : "Sam", "num_comments" : 566} ] print(f"The MOST active user is { max( users, key= lambda u: u['num_comments'])['username'].upper() }\n") print(f"The LEAST active user is { min( users, key= lambda u: u['num_comments'])['username'].upper() }\n") # ----------- EXERCISE ------------ # Define extremes below: def extremes(collection): return ( min(collection), max(collection) ) print( extremes([1,2,3,4,5]) ) # (1,5) print( extremes((-11,542,-41,45,78,111)) ) # (-41,542) print( extremes("alcatraz")) # ('a', 'z')
dbeaf8c49b4a6eddb12f026856a82fbe1e5c4500
rakeshgowdan/Python_Basics
/Python_Basics/ex2_condition.py
485
4.0625
4
print("welcome to the bank application") print("enter name") name=input() print("enter the age") age=input() print("enter the address") address=input() print("enter the salary") salary=input() print("enter the empid") empid=int(input()) print("checking number of years in company") print("-----------------------") if empid >=1000: print("2years of expirence") else: print("more than 2 years of expirence") list=[name,age,address,salary,empid] for list in list: print(list)
e69f6720f77d9ba6eebea51f7fbd31f77f92744c
DayGitH/Python-Challenges
/DailyProgrammer/DP20120827B.py
2,493
4.09375
4
""" [8/27/2012] Challenge #92 [intermediate] (Rubik's cube simulator) https://www.reddit.com/r/dailyprogrammer/comments/ywm08/8272012_challenge_92_intermediate_rubiks_cube/ Your intermediate task today is to build a simple simulator of a [Rubik's Cube](http://en.wikipedia.org/wiki/Rubik%27s_Cube). The cube should be represented by some sort of structure, which you can give a list of moves which it will execute and show you how the cube will look as a result. A Rubik's Cube has six sides, which are traditionally known as Up, Down, Front, Back, Left and Right, abbreviated as U, D, F, B, L and R respectively. Color the sides of the cube as follows: Up <- white, Down <- yellow, Front <- green, Back <- blue, Left <- orange and Right <- red. Taking advantage of the style of [problem #85](http://www.reddit.com/r/dailyprogrammer/comments/xq2ao/832012_challenge_85_intermediate_3d_cuboid/), the basic solved cube should then look something like this: W W W / W W W / R W W W / R R G G G|R R R G G G|R R G G G|R Here showing the top side, the front side and the right side. To list moves you can make on a Rubik's Cube, you use something called [Singmaster's notation](http://en.wikipedia.org/wiki/Rubik%27s_Cube#Move_notation), which works like this: to indicate a clockwise turn of any one side, you use the abbreviation of the side. So "R" means to spin the right side clockwise 90 degrees. If there's a prime sympol (i.e. a ' ) after the letter, that means to spin it counter-clockwise 90 degrees. If there's a "2" after the letter, it means you should spin that side 180 degrees. There is an extended notation for advanced moves (such as spinning a middle slice, or spinning two slices), but we'll ignore those for this challenge. So, for instance, executed the sequence R U B' R B R2 U' R' F R F' on a totally solved cube, it should result in the following configuration: O O R / B W G / W R R O / W R W W G|W R R G G G|R R G G G|R [See here for a step by step demonstration](http://alg.garron.us/?alg=R_U_B-_R_B_R2_U-_R-_F_R_F-). Make a program that can execute a sequence of moves like these, and then print out what the cube looks like as a result, either in the cuboid form I've used here, or just print out the sides one by one. What is the result of executing the following series of moves on a solved cube? F' B L R' U' D F' B """ def main(): pass if __name__ == "__main__": main()
0fad69f1ec8bfc497cffac065df4e60a877e7363
Lennoard/ifpi-ads-algoritmos2020
/Fabio02_Parte02a/q20_quadrante.py
574
4.15625
4
#20. Leia a medida de um ângulo (entre 0 e 360°) e escreva o quadrante # (primeiro, segundo, terceiro ou quarto) em que o ângulo se localiza. def determinar_quadrante(a): if (a < 90): return '1º quadrante' elif (a < 180): return '2º quadrante' elif (a < 270): return '3º quadrante' else: return '4º quadrante' def main(): angulo = float(input('Insira a media de um ângulo: ')) if (angulo < 0 or angulo > 360): print('Ângulo inválido') else: print(determinar_quadrante(angulo)) main()
7fbabbc99481bbc482c1506f8ea77c77dd59dce7
lotka/conwaypear
/conway.py
1,417
3.90625
4
from pprint import pprint from copy import copy """ Conway Rules: 1. Any live cell with fewer than two live neighbours dies, as if caused by underpopulation. 2. Any live cell with two or three live neighbours lives on to the next generation. 3. Any live cell with more than three live neighbours dies, as if by overpopulation. 4. Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction. """ def generate_next_board_state(board): new_board = copy(board) for i in xrange(len(board)): for j in xrange(len(board)): count = count_alive_cells_near_cell(board, i, j) if board[i][j] == 1: if count < 2: new_board[i][j] = 0; # Rule 1 if count > 3: new_board[i][j] = 0; # Rule 3 if board[i][j] == 0: if count == 3: new_board[i][j] = 1; return new_board def count_alive_cells_near_cell(board,x,y): alive_cells = [] for i in [x-1,x+1]: for j in [y-1,y+1]: if(board[i % len(board)][j % len(board[0])] == 1): alive_cells.append([i,j]) return len(alive_cells) board = [] iteration = 0 size = 8 for i in range(size): board.append([0 for i in range(size)]) #Seed the first life-form board[5][5] = 1 board[4][5] = 1 while (iteration < 3): pprint(board) print('\n') board = generate_next_board_state(board) iteration += 1
7a964e4f20f4d907bbb55fb0c47f2465c0ec62e2
vnpavlukov/Study
/Stepik/2. Python_Basic_and_application/test_2.3.2.1_iterators.py
350
3.90625
4
from random import random class RandomIterator: def __init__(self, n): self.n = n self.i = 0 def __next__(self): if self.n > self.i: self.i += 1 return random() else: raise StopIteration x = RandomIterator(3) print(next(x)) print(next(x)) print(next(x)) print(next(x))
324606f5ef04a76512bbbb819df806e19166cb54
vmirisas/Python_Lessons
/lesson3/exercise11.py
188
4.0625
4
a = int(input("insert a number for a: ")) if a == 0: print("the equation has no solution") else: b = int(input("insert a number for b: ")) x = - b / a print("x = ", + x)
b3063f4cb40bd85ca0e31f9061b6a3fb11174eff
zhsheng26/PythonLesson
/基础语法/8_set.py
713
3.9375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2017/9/12 14:12 # @Author : zhangsheng # set 没有重复的元素 # 创建一个set a_set = {6, 3, 4, 2} print(isinstance(a_set, set)) # 将list转为set a_list = [5, 1, 3, 6, 5, 6] print(a_list) a_set = set(a_list) # 重复元素在set中自动被过滤 print(a_set) s1 = set([1, 1, 2, 2, 3, 3]) print(s1) s2 = set([2, 3, 4]) print(s1 & s2) # 交集 print(s1 | s2) # 并集 # set的原理和dict一样,所以,同样不可以放入可变对象,因为无法判断两个可变对象是否相等 # 字符串是不可变对象 a_str = 'abc' b_str = a_str.replace('a', 'A') # 创建了一个新字符串'Abc'并返回 print(a_str) print(b_str)
36bdcc19ca5b43570f345c5c2fa244c155d5a6f1
Web-Sniper/python
/captilization.py
449
3.703125
4
#!/bin/python3 import math import os import random import re import sys # Complete the solve function below. def solve(s): f,l = s.split() f = list(f) l = list(l) f[0]=f[0].upper() l[0]=l[0].upper() f= ''.join(f) l=''.join(l) s= f+' '+l return s if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') s = input() result = solve(s) fptr.write(result + '\n') fptr.close()
f6bfc3f6a2b71fc499e65818d68a786154f71fe2
mufraswid/julius
/classic/affine.py
1,465
3.65625
4
import math ALPHABET_SIZE = 26 def convert(c, m, b, mod=ALPHABET_SIZE): pos = ord(c) pos_A = ord('A') pos_Z = ord('Z') pos_a = ord('a') pos_z = ord('z') shift = pos_A if pos >= pos_a and pos <= pos_z: #Lowercase Letter shift = pos_a new_c = chr((((pos - shift) * m + b) % mod) + shift) return new_c def inverse(m, mod=ALPHABET_SIZE): ''' Find the inverse of m in modulo mod ''' if(math.gcd(m, mod) > 1): #can't find inverse return -1 m = m % mod if m == 1: return m return mod - inverse(mod, m)*mod//m def encrypt(plaintext, m, b): ''' For encrypting plaintext with Affine Cipher ''' ciphertext_characters = [] for char in plaintext: new_char = convert(char, m, b) ciphertext_characters.append(new_char) return ''.join(ciphertext_characters) def decrypt(ciphertext, m, b): ''' For decrypting plaintext with Affine Cipher ''' plaintext_characters = [] inv_m = inverse(m) for char in ciphertext: new_char = convert(char, inv_m, -b*inv_m) plaintext_characters.append(new_char) return ''.join(plaintext_characters) if __name__ == '__main__': plaintext = 'HaInaMasayAupIniniAdiksayaiPin' test = [[7, 10], [3, 200], [25, 4]] for i in test: ciphertext = encrypt(plaintext, i[0], i[1]) print(ciphertext) print(decrypt(ciphertext, i[0], i[1]))
843cae5f9b2fa2f02c519c5da8a8e9cecb5d02e9
sharmasourab93/CodeDaily
/DataStructures/Advanced/Trie/Tries_HandsOn.py
1,599
3.984375
4
class TrieNode: def __init__(self): self.children=[None]*26 # isLeaf is True if node represent the end of the word self.isLeaf=False class Trie: def __init__(self): self.root=self.getNode() def getNode(self): return TrieNode() def _charToIndex(self,ch): #prevate helper function #converts 'a' through 'z' and lower case return ord(ch)-ord('a') def insert(self,key): #if not present , inserts key into trie #If the key is prefix of trie node, #just marks leaf node pCrawl=self.root length=len(key) for level in range(length): index=self._charToIndex(key[level]) #if current character is not present if not pCrawl.children[index]: pCrawl.children[index]=self.getNode() pCrawl=pCrawl.children[index] #mark last node as leaf pCrawl.isLeaf=True def search(self,key): #search key in the trie #Returns true if key presents #in trie, else false pCrawl=self.root length=len(key) for level in range(length): index=self._chartoIndex(key[level]) if not pCrawl.children[index]: return False pCrawl!=None and pCrawl.isLeaf def main(): #inpyt keys (use only 'a' through 'z' and lower case) keys=["the","a","there","anaswe","any", "by","their"] output=["Not present in trie", "Present in tire"] #Trie Object t=Trie() for key in keys: t.insert(key)
1e90cf954612abe7a99fec4ce39cfead4178fb49
SafonovMikhail/python_000577
/000403StepPyThin/000403_01_12_07_HappyTiket_02_StepikSolvers_ifElse_20191110.py
140
3.546875
4
a, b, c, d, e, f = input() l = int(a)+int(b)+int(c) r = int(d)+int(e)+int(f) if l == r: "Cчастливый" else: "Обычный"
befa46694a9d93e03ff7b47130ac280bb7eff57a
psyde26/Homework2
/task2.py
2,244
3.796875
4
# Задание 1 # Необходимо вывести имена всех учеников из списка с новой строки names = ['Оля', 'Петя', 'Вася', 'Маша'] for each_name in names: print(each_name) # Задание 2 # Необходимо вывести имена всех учеников из списка, рядом с именем показать количество букв в нём. names = ['Оля', 'Петя', 'Вася', 'Маша'] for each_name in names: print(each_name, len(each_name)) # Задание 3 # Необходимо вывести имена всех учеников из списка, рядом с именем вывести пол ученика is_male = { 'Оля': False, # если True, то пол мужской 'Петя': True, 'Вася': True, 'Маша': False, } names = ['Оля', 'Петя', 'Вася', 'Маша'] for each_name in names: if each_name in is_male: if is_male[each_name] is True: print(each_name, 'м') else: print(each_name, 'ж') else: print('Данного имени нет в списке') # Задание 4 # Даны группу учеников. Нужно вывести количество групп и для каждой группы – количество учеников в ней # Пример вывода: # Всего 2 группы. # В группе 2 ученика. # В группе 3 ученика. groups = [ ['Вася', 'Маша'], ['Оля', 'Петя', 'Гриша'], ] print('Всего', len(groups), 'группы') for person in groups: print('В группе', len(person), 'ученика') # Задание 5 # Для каждой пары учеников нужно с новой строки перечислить учеников, которые в неё входят. # Пример: # Группа 1: Вася, Маша # Группа 2: Оля, Петя, Гриша groups = [ ['Вася', 'Маша'], ['Оля', 'Петя', 'Гриша'], ] x = 0 for list_of_students in groups: x = x + 1 new_list = ' '.join(list_of_students) print(f'Группа {x}: ', new_list)
d8c0998c2996b814b41e28323763ee6eccc57025
bhawnagurjar27/Programming-Practice
/Codechef/Beginner's Level/HS08TEST/HS08TEST.py
279
3.625
4
Assumed_withdrawal_money, initial_acco_balance = map(float, input().split()) if(Assumed_withdrawal_money % 5 == 0): if(Assumed_withdrawal_money + 0.5) <= initial_acco_balance: initial_acco_balance -= (Assumed_withdrawal_money + 0.5) print(initial_acco_balance)
21eaee9fe2843edbc8dab59fe3aab1144d8406d2
27Saidou/cours_python
/test.py
169
3.671875
4
vallet=5000 computer_price=5000 if computer_price<=vallet: print("l'achat est possible") vallet-=computer_price else: print("oui l'achat est possible")
68709f693e5a4285804472148a3c628fa205e940
kazenski-dev/01_ling_progr_cesusc
/exercicio_16.py
485
4.09375
4
""" 16 - Faça um algoritmo que leia os valores de COMPRIMENTO, LARGURA e ALTURA e apresente o valor do volume de uma caixa retangular. Utilize para o cálculo a fórmula VOLUME = COMPRIMENTO * LARGURA * ALTURA. """ #Variables comprimento = float(input("Insira o valor do comprimento:")) largura = float(input("Insira o valor do largura:")) altura = float(input("Insira o valor do altura:")) #Main Code print("O volume e: {0} metros cubicos.".format(comprimento * altura * largura))
bf92143ac3e9b3c6dbcb40b89795897d9d40c39d
Cloudplement/amiok
/amiok/app.py
416
3.78125
4
import urllib.request def get_status(url): """ This function gets the status code of a website. A response of 200 if the website is okay """ try: conn = urllib.request.urlopen(url) if conn.getcode() == 200: return "OK" except urllib.error.URLError: return "Not OK" print(get_status("http://google.com")) print(get_status("http://not-google-domain.com"))
9460de6ef4d90a392aab793b0e07bdd882dca7fd
codekacode/Exercisespython
/Zipfunction.py
921
4.4375
4
"""Función zip (Ambos iteradores se usarán en una construcción de bucle único): esta función es útil para combinar elementos de datos de iteradores de tipo similar (list-list o dict-dict, etc.) en la posición i-ésima. Utiliza la longitud más corta de estos iteradores de entrada. Se omiten otros elementos de iteradores de mayor longitud. En caso de iteradores vacíos, devuelve Sin salida. Por ejemplo, el uso de zip para dos listas (iteradores) ayudó a combinar un solo automóvil y su accesorio requerido""" titis = ["Audis","Toyota","Volkswagen","Mini"] accesorios = ["Timon", "Parabrisas" ,"Sonido", "Llantas", "GPS"] for t , a in zip(titis , accesorios): print ("titis: %s , accesorios: %s" % (t,a)) #El reverso de estos iteradores de la función zip se conoce como descomprimir usando el operador "*". titi , acceso = zip(*[("Audi", "GPS"),("Volvo","Timon")]) print (titi) print (acceso)
5b998d46676796a85f51230c2fa9da873cb4acb1
axieax/sort-algorithm-time
/clean.py
1,322
3.53125
4
# Open file data = open("extracted.txt", "r") # Saves the lines into a list lines = data.readlines() # Lines we want to edit edit = [3, 4, 5, 7, 8, 9] # List with edited lines formatted_output = [] for i in range(len(lines)): # The first mod specifies the section (different input sizes) # The second mod determines the lines to be edited if (i%62)%10 in edit: # Extracts the time value org_time = lines[i][5:-2] # Finds the index for minutes (character 'm') m_index = org_time.find('m') # Calculates the time in seconds based on seconds and minutes seconds = float(org_time[m_index+1:]) minutes = float(org_time[:m_index]) time = seconds + 60*minutes # Includes the edited line formatted_output.append("%.3f" % time + "\n") elif "Trial" in lines[i]: # Finds starting index for word "Trial" t_index = lines[i].find("Trial") # Removes the trial number information from lines formatted_output.append(lines[i][:t_index-1] + ":\n") else: # Include lines that don't require editing formatted_output.append(lines[i]) data.close() # Write the cleaned lines to a new file new_file = open("results.txt", "w") for line in formatted_output: new_file.write(line) new_file.close()
8fe2af950cee50f14d3c39d04b8fbeb4fdb717bd
ezequielhenrique/exercicios-python
/ExerciciosPython/ex052.py
355
4.03125
4
num = int(input('Digite um número inteiro: ')) div = 0 for c in range(1, num+1): if num % c == 0: # Conta a quantidade de divisores div += 1 if div == 2: print('{} possui {} divisores portanto é um número primo.'.format(num, div)) else: print('{} possui {} divisores portanto não é um número primo.'.format(num, div))
921869182cd8ccfd8b7c08d5e3b1a32e8789894e
swetakum/Algorithms
/Sorting/SelectionSort.py
590
4.1875
4
""" The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from unsorted part and putting it at the beginning. """ def selectionSort(arr): k = arr elem = arr[0] for i in range(0,len(arr)): elem = arr[i] for j in range(i+1, len(arr)): if(arr[j]<elem): elem = arr[j] index= j if elem is not arr[i]: arr[index] = arr[i] arr[i] = elem return arr arr = [9,8,4,5,6,7,0,1] sor = [64, 25, 12, 22, 11] print(selectionSort(sor))
811272fe768145971a1c4d68e10082b3fd18ba18
zkadam/PythonKurssi
/randrangetest.py
151
3.59375
4
import random randomNum = random.randrange(1,21) for x in range(50): randomNum = random.randrange(1,21) print("Random numero: ",randomNum)
4676d95dc1e000761253d6b079ee586892dd176f
dmmitrenko/traverse-a-tree
/Pre-order_traversal.py
593
3.796875
4
class Node: def __init__(self, val = 0,left = None, right = None): self.left = left self.right = right self.val = val def PreorderTraversal(self, root): arr = [] if root is not None: arr.append(root.data) arr += self.PreorderTraversal(root.left) arr += self.PreorderTraversal(root.right) return arr root = Node(1) root.left = Node(2) root.right = Node(5) root.left.left = Node(3) root.left.right = Node(4) root.right.left = Node(6) print(root.PreorderTraversal(root))
78b4f8ba47cbd2fa2f562965e5bb5af6faeebcd1
MrHamdulay/csc3-capstone
/examples/data/Assignment_6/swptas001/question1.py
476
3.84375
4
### Tashiv Sewpersad (SWPTAS001) ### Assignment 6 - Question 1 ### 2014 - 04 - 20 ## Live Code # Initialise Variables aNames = [] iMaxLen = 0 # Get input sName = input("Enter strings (end with DONE):\n") while sName.upper() != "DONE": iLen = len(sName) if iLen > iMaxLen: iMaxLen = iLen aNames.append(sName) sName = input("") # Generate Output Output = "{0:>" + str(iMaxLen) + "}" print("\nRight-aligned list:") for Name in aNames: print(Output.format(Name))
24d90e3e2ba7787eb6d120d6b2265a28e87d920c
rahulskumbhar1997/ML_projects
/regression/salary_data_example/linear_regression_using_sklearn.py
1,941
3.984375
4
#!/usr/bin/env python # coding: utf-8 # In[2]: import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns # ### Read the dataset # In[3]: df = pd.read_csv('dataset/Salary_Data.csv') # ### Get some insights # In[4]: print(df.head()) # In[5]: print(df.info()) # ### Plot the data to get some insights # In[6]: plt.scatter(df["YearsExperience"], df["Salary"]) plt.xlabel("Years of Experience") plt.ylabel("Salary") plt.show() # ### Prepare training and testing dataset # In[7]: from sklearn.model_selection import train_test_split x = df.drop("Salary", axis=1) y = df["Salary"] x_train, x_test, y_train, y_test = train_test_split(x, y, train_size=0.8) # ### Create a model # In[8]: from sklearn.linear_model import LinearRegression model = LinearRegression() # ### Train the model # In[9]: model.fit(x_train, y_train) # ### Predict the result for test dataset # In[10]: y_prediction = model.predict(x_test) # ### Check the accuracy of model # In[12]: from sklearn.metrics import mean_squared_error, mean_absolute_error mae = mean_absolute_error(y_test, y_prediction) mse = mean_squared_error(y_test, y_prediction) print("Mean Absolute error : ",mae) print("Mean squared error : ", mse) print("Root mean squared error : ", np.sqrt(mse)) # ### Plot the predicted result # In[20]: plt.scatter(x_test, y_test, label="Actual values") plt.scatter(x_test, y_prediction, c='red', label="Predicted values") plt.xlabel("Years of Experience") plt.ylabel("Salary") plt.legend() # In[29]: # Intercept value print("Intercept value : ",model.intercept_) # Coefficient value print("Coefficient value : ", model.coef_) # In[37]: y_predict_eq = x * model.coef_ + model.intercept_ plt.scatter(x, y, label="Actual data") plt.plot(x, y_predict_eq, c='red', label="Best fit line") plt.legend() plt.xlabel("Years of Experience") plt.ylabel("Salary") # In[ ]:
43c2cd41f4dcbf64bec301920896083e638563e5
tanvi355/Video-to-PDF
/script.py
4,361
3.53125
4
from tkinter import * from moviepy.editor import VideoFileClip from moviepy.editor import AudioFileClip from tkinter import filedialog from tkinter import messagebox from tkinter import ttk from fpdf import FPDF import threading import speech_recognition as sr import os #variables video_clip = '' audio_clip = '' #function to get video def get_video(): global video_filepath, video_clip try: video_filepath.set(filedialog.askopenfilename(title="Select your video file")) video_clip = VideoFileClip(str(video_filepath.get())) except: messagebox.showerror("Error", "No video selected") #function to convert audio to pdf def audio_to_pdf(): ''' Here, we first extract the audio from the selected video and store it into 'my_audio.wav'. Then, using the speech recognition module and Google speech API, we convert this audio to text and write it into a file named 'my_text.txt'. This text file is then passed to text_to_pdf function to convert it into a pdf and at the end the audio and text files are removed using the OS module as we don't need them anymore. ''' global audio_clip try : #extract audio audio_clip = video_clip.audio.write_audiofile(r"my_audio.wav") r = sr.Recognizer() #open the audio file with sr.AudioFile("my_audio.wav") as source: #listen for the data audio_data = r.record(source) #recognize text = r.recognize_google(audio_data) #write into a file write_file = open('my_text.txt', 'w') write_file.write(text) write_file.close() #convert to pdf text_to_pdf('my_text.txt') messagebox.showinfo("Message", "Conversion Successfull") except : messagebox.showerror( "Error", "Conversion not performed") #reset path video_filepath.set('') #reset progressbar progress_bar['value'] = 0 progress_bar.stop() #delete audio and text files os.remove("my_audio.wav") os.remove("my_text.txt") #function to convert text to pdf def text_to_pdf(file): ''' In this function, we create a pdf using the FPDF module and add a page to it and set the font. Effective page width is calculated so that Then, we open the text file in read mode and using multi_cell(for wrapping the text into multiple lines), insert the text from the text file into the pdf. At last, we save it as 'my_pdf.pdf'. ''' pdf = FPDF(format='letter', unit='in') pdf.add_page() pdf.set_font("Arial", size = 12) effective_page_width = pdf.w - 2*pdf.l_margin #open text file in read mode f = open(file, "r") #write the pdf for x in f: pdf.multi_cell(effective_page_width, 0.15, x) pdf.ln(0.5) #save the pdf pdf.output("../Video to PDF/my_pdf.pdf") #function to run the script def run(): global progress_bar t1 = threading.Thread(target = progress_bar.start) t2 = threading.Thread(target = audio_to_pdf) t2.start() t1.start() # GUI CODE starts # Intializing main program settings root = Tk() root.title("Video to PDF Converter") # Variables for file paths video_filepath = StringVar() # Creating UI Frame UI_frame = Frame(root, width=500, height=500, relief = "raised") UI_frame.grid(row=0, column=0) convert_frame = Frame(root, width=500, height=500, relief="raised") convert_frame.grid(row=1, column=0) # Labels and buttons select = Label(UI_frame, text="Select Video : ", font = ("Arial", 12)) select.grid(row=1, column=1, padx=5, pady=5, sticky=W) browse = Button(UI_frame, text="Browse", command = get_video, font = ("Arial", 12)) browse.grid(row=1, column=2, padx=5, pady=5) video_selected = Label(UI_frame, text = "Selected video : ", font = ("Arial", 12)) video_selected.grid(row = 2, column = 1, padx = 5, pady = 5, sticky = E) video_path = Label(UI_frame, textvariable=video_filepath) video_path.grid(row=2, column=2, padx=2, pady=5, sticky=W) convert = Button(convert_frame, text="Convert", command = run, font = ("Arial", 12)) convert.grid(row=3, column=1, pady=5) progress_bar = ttk.Progressbar(root, orient=HORIZONTAL, mode='indeterminate', length=500) progress_bar.grid(padx=25, pady=25) # Calling main program root.mainloop() # GUI CODE ends
356032368303e65817da01cb31f8e8b59b8dcfe1
tmantock/python
/random-simulation.py
5,406
3.796875
4
import random class Location(object): def __init__(self, x, y): """x and y are floats""" self.x = x self.y = y def move(self, deltaX, deltaY): """deltaX and deltaY are floats""" return Location(self.x + deltaX, self.y + deltaY) def getX(self): return self.x def getY(self): return self.y def distFrom(self, other): ox = other.x oy = other.y xDist = self.x - ox yDist = self.y - oy return (xDist**2 + yDist**2)**0.5 def __str__(self): return '<' + str(self.x) + ', ' + str(self.y) + '>' class Field(object): def __init__(self): self.drunks = {} def addDrunk(self, drunk, loc): if drunk in self.drunks: raise ValueError('Duplicate drunk') else: self.drunks[drunk] = loc def moveDrunk(self, drunk): if not drunk in self.drunks: raise ValueError('Drunk not in field') xDist, yDist = drunk.takeStep() self.drunks[drunk] = self.drunks[drunk].move(xDist, yDist) def getLoc(self, drunk): if not drunk in self.drunks: raise ValueError('Drunk not in field') return self.drunks[drunk] class Drunk(object): def __init__(self, name): self.name = name def takeStep(self): stepChoices = [(0,1), (0,-1), (1, 0), (-1, 0)] return random.choice(stepChoices) def __str__(self): return 'This drunk is named ' + self.name def walk(f, d, numSteps): start = f.getLoc(d) for s in range(numSteps): f.moveDrunk(d) return(start.distFrom(f.getLoc(d))) def simWalks(numSteps, numTrials): homer = Drunk('Homer') origin = Location(0, 0) distances = [] for t in range(numTrials): f = Field() f.addDrunk(homer, origin) distances.append(walk(f, homer, numSteps)) return distances def drunkTest(numTrials): #for numSteps in [0, 1]: for numSteps in [10, 100, 1000, 10000, 100000]: distances = simWalks(numSteps, numTrials) print 'Random walk of ' + str(numSteps) + ' steps' print ' Mean =', sum(distances)/len(distances) print ' Max =', max(distances), 'Min =', min(distances) # homer = Drunk('Homer Simpson') # origin = Location(0,0) # f = Field() # f.addDrunk(homer,origin) # print walk(f,homer,10) #drunkTest(10) def rollDie(): """returns a random int between 1 and 6""" return random.choice([1,2,3,4,5,6]) def testRoll(n = 10): result = '' for i in range(n): result = result + str(rollDie()) print result #testRoll() import pylab # pylab.plot([1,2,3,4], [1,2,3,4]) # pylab.plot([1,4,2,3], [5,6,7,8]) # pylab.show() # # pylab.figure(1) # pylab.plot([1,2,3,4], [1,2,3,4]) # pylab.figure(2) # pylab.plot([1,4,2,3], [5,6,7,8]) # pylab.savefig('firstSaved') # pylab.figure(1) # pylab.plot([5,6,7,10]) # pylab.savefig('secondSaved') # pylab.show() # principal = 10000 #initial investment # interestRate = 0.05 # years = 20 # values = [] # for i in range(years + 1): # values.append(principal) # principal += principal*interestRate # pylab.plot(values) # # pylab.title('5% Growth, Compounded Annually') # pylab.xlabel('Years of Compounding') # pylab.ylabel('Value of Principal ($)') # # pylab.show() def checkPascal(numTrials = 100000): yes = 0.0 for i in range(numTrials): for j in range(24): d1 = rollDie() d2 = rollDie() if d1 == 6 and d2 == 6: yes += 1 break print 'Probability of losing = ' + str(1.0 - yes/numTrials) #checkPascal() def flip(numFlips): heads = 0 for i in range(numFlips): if random.random() < 0.5: heads += 1 return heads/float(numFlips) #print flip(100) ##def flipSim(numFlipsPerTrial, numTrials): ## fracHeads = [] ## for i in range(numTrials): ## fracHeads.append(flip(numFlipsPerTrial)) ## mean = sum(fracHeads)/float(len(fracHeads)) ## return (mean) def flipPlot(minExp, maxExp): ratios = [] diffs = [] xAxis = [] for exp in range(minExp, maxExp + 1): xAxis.append(2**exp) for numFlips in xAxis: numHeads = 0 for n in range(numFlips): if random.random() < 0.5: numHeads += 1 numTails = numFlips - numHeads ratios.append(numHeads/float(numTails)) diffs.append(abs(numHeads - numTails)) pylab.title('Difference Between Heads and Tails') pylab.xlabel('Number of Flips') pylab.ylabel('Abs(#Heads - #Tails') pylab.plot(xAxis, diffs) pylab.figure() pylab.plot(xAxis, ratios) pylab.title('Heads/Tails Ratios') pylab.xlabel('Number of Flips') pylab.ylabel('Heads/Tails') pylab.figure() pylab.title('Difference Between Heads and Tails') pylab.xlabel('Number of Flips') pylab.ylabel('Abs(#Heads - #Tails') pylab.plot(xAxis, diffs, 'bo') pylab.semilogx() pylab.semilogy() pylab.figure() pylab.plot(xAxis, ratios, 'bo') pylab.title('Heads/Tails Ratios') pylab.xlabel('Number of Flips') pylab.ylabel('Heads/Tails') pylab.semilogx() flipPlot(4, 20) #pylab.show() import math def stdDev(X): mean = sum(X)/float(len(X)) tot = 0.0 for x in X: tot += (x - mean)**2 return math.sqrt(tot/len(X)) print stdDev([1,2,3,4,5,6,7,8,9,10])
5664f70b00b22276eb4c78ca10b401b2872e2cd8
S-Spencer/AoC19
/day1.py
1,021
4.09375
4
""" Open input file and store in list 'masses' """ masses = [] raw = open("input_1.txt","r") for line in raw: masses.append(int(line)) raw.close() """ Next step calculate the Fuel Total required as the puzzle answer for part one 'FT1' To calculate fuel for each mass in masses: Divide mass by 3 Take int of the result Subtract 2 Add result to FT """ FT1 = 0 for mass in masses: fuel = int(mass/3) FT1 += (fuel - 2) print("The answer to part 1 is " + str(FT1)) """ Now the Fuelt Total 'FT2' must take into account the addition mass created by adding fuel For each mass in masses, need to repeat the loop until the new fuel needed is <=0 Initially set fuel = mass as a dummy start Then so long as fuel > 0, the loop continues A check is made before adding fuel to the total in case it is negative on the last pass """ FT2 = 0 for mass in masses: fuel = mass while fuel > 0: fuel = (int(fuel/3)) - 2 if fuel > 0: FT2 += fuel print("The answer to part 2 is " + str(FT2))
36c8c4918b7975d07773afcc7e218a95d0d86168
diegommezp28/ExponentialMinimunSimulation
/DataStructures/prueba.py
326
3.71875
4
def prueba(): print('hola') yield 1 print('mundo') yield 2 print('soy ') yield 3 print('Diego') # for i in prueba(): # print(i) class Generator: def __iter__(self): list = range(3) for i in list: yield i*i clase = Generator() for i in clase: print(i)
67e8fd09e75ddb0e1028cde5a9c81a10513b3393
yfzhang3/UCSD-TritonHacks-2021
/convert.py
1,514
4.09375
4
import random import math """ PART 5 - Average Price [list of string prices (e.g. [$, $$]) ] => float """ def avg_price(prices): print("Prices input looks like the following", prices) # Replace the below code to calculate the average prices! # Keep in mind the type of our input (list of string) sum = 0 for i in range(len(prices)): sum += len(prices[i]) average = sum / len(prices) # <- TODO Replace this line average = round(average,2) return average """ PART 5 - Average Rating [list of numbers] => float """ def avg_rating(ratings): print("Ratings input looks like the following", ratings) # Replace the below code to return the average of the values of the input # Keep in mind that the input here is a list of numbers sum=0 for i in range(len(ratings)): sum+=ratings[i] average = sum / len(ratings) # <- TODO Replace this line #average = round(average,2) return average """ Don't change this method [int, int] => [String, float] """ # Calculates the type of emoji to display for current rating. def calculate_moons(score, multiplier): # 🌑🌘🌓🌖🌕 MOON_EMOJIS = ["&#x1F311","&#x1F318", "&#x1F317", "&#x1F316", "&#x1F315"] score = math.floor(float(score) * multiplier + 0.25) / multiplier score_copy = score display_string = "" for i in range (5): if(score> 1): display_string += MOON_EMOJIS[4] score -= 1 else: display_string += MOON_EMOJIS[int(score*4)] score = 0 return (display_string, score_copy)
a95534de752e9a509ae9d0a6dc46eddf5ab0ebbb
Cynnabarflower/vk-analyzer
/venv/Lib/graphs.py
12,676
3.53125
4
import matplotlib.pyplot as plt import numpy as np import pandas as pd def moustache(dframe, qual1, quant1, lat=12, long=7, show_axes=True): """ Maidzhe Alexandra Creates boxplots from two columns of a dataframe (qualitative - quantintative)using matplotlib.pyplot.boxplot. :param dframe: the dataframe; :param qual1: name of the column with the qualitative data; :param quant1: name of the column with the quantitative data; :param lat: width of the plot window; :param long: length of the plot window; :param show_axes: bool to allow axes' showing; :return: figure/None. """ # converting quantitative data to float and non-convertible elements to nan dframe[quant1] = dframe[quant1].apply(pd.to_numeric, errors='coerce') # deleting all rows with nan values dframe = dframe.dropna(subset=[qual1, quant1]) if not dframe.empty: dframe.rename(columns={quant1: 'rainbow'}, inplace=True) # creating lists' series of the quantitative data grouped by the qualitative data a = dframe.groupby(qual1).rainbow.apply(list) # creating a list of qualitative data for x-axis label b = list(a.keys()) # dimensions of figure: # figure instance fig = plt.figure(1, figsize=(lat, long)) # axes instance ax = fig.add_subplot(111) # finding maximum and minimum of qualitative data to personalize the y-thicklabel maxi = max([max(t) for t in a]) mini = min([min(t) for t in a]) plt.ylim(bottom=mini - 0.1 * (maxi - mini), top=maxi + 0.1 * (maxi - mini)) # creating and designing the boxplot: # to allow fill colour bp = ax.boxplot(a, patch_artist=True) for box in bp['boxes']: # outline colour of the boxes box.set(color='k', linewidth=2) # fill colour of the boxes box.set(facecolor='C0') # colour and linewidth of the whiskers for whisker in bp['whiskers']: whisker.set(color='k', linewidth=2) # colour and linewidth of the caps for cap in bp['caps']: cap.set(color='k', linewidth=2) # colour and linewidth of the medians for median in bp['medians']: median.set(color='k', linewidth=2) # style of fliers and their fill for flier in bp['fliers']: flier.set(marker='o', color='#e7298a', alpha=0.5) if not show_axes: plt.axis('off') # adding the qualitative data as x-axis labels ax.set_xticklabels(b, rotation=40) return fig # otherwise the function returns 'None' def klaster(dframe, qual1, qual2, quant, lat=12, long=7, show_axes=True): """ Maidzhe Alexandra Creates a grouped bar chart from three columns of a dataframe; (qualitative, qualitative, quantintative)using matplotlib.pyplot.bar. :param dframe: the dataframe; :param qual1: name of the column with the series; :param qual2: name of the column with the categories; :param quant: name of the column with the values; :param lat: width of the plot window; :param long: length of the plot window; :param show_axes: bool to allow axes' showing; :return: figure/None. """ # converting quantitative data to float and non-convertible elements to nan dframe[quant] = dframe[quant].apply(pd.to_numeric, errors='coerce') # deleting all rows with nan values dframe = dframe.dropna(subset=[qual1, qual2, quant]) if not dframe.empty: # get lists of qualitative data to legend (with a) and index (with b) the graph a = sorted(list(set(dframe[qual1]))) b = sorted(list(set(dframe[qual2]))) dframe = dframe.pivot_table(values=quant, index=qual1, columns=qual2).fillna(0) # get list of lists of the means lst = [] for i in range(len(a)): lst.append(list(dframe.T[a[i]])) # building the figure: # fig, ax = plt.subplots() fig = plt.figure(2, figsize=(lat, long)) ax = fig.add_subplot(111) # setting the width and positions for the bars bar_width = 0.95 / len(a) index = np.arange(len(b)) for i in range(len(a)): ax.bar(index + i * bar_width, lst[i], bar_width, label=a[i]) # adding indexes for x-axis label plt.xticks(index + (len(a) * bar_width - bar_width) / 2, b, rotation=40) if not show_axes: plt.axis('off') else: plt.legend() ax.set_ylabel(quant) return fig # otherwise the function returns 'None' def sweetie_pie(dframe, qual, size=5, show_labels=True): """ Maidzhe Alexandra Createsa Pie Chart :param dframe: the dataframe :param qual: qualitative data :param size: size of the plot window :param show_labels: bool to allow labels' showing :return: figure/None """ labels = sorted(list(set(dframe[qual]))) values = list(dframe.pivot_table(index=[qual], aggfunc='size')) fig = plt.figure(3, figsize=(size, size)) if show_labels: plt.pie(values, labels=labels, autopct='%.1f%%') else: plt.pie(values) return fig def show_graph(figure): """ Maidzhe Alexandra Closes all the other figures, to open just the passed one. :param figure: a graph """ n = figure.number # closing all figures but the one needed for i in range(1, 10): if i != n: plt.close(i) plt.show() def barh(dframe, qual1, qual2, lat=12, long=7, show_axes=True): """ Maidzhe Alexandra Creates a bar plot out of two columns from a data frame. (qualitative-qualitative data). :param dframe: the data frame; :param qual1: qualitative data for the x-axis label; :param qual2: qualitative data for the x-axis label; :param lat: width of the plot window; :param long: length of the plot window; :param show_axes: bool to allow axes' showing; :return: figure/None """ dframe = dframe.dropna(subset=[qual1, qual2]) if not dframe.empty: dframe.rename(columns={qual1: 'rainbow'}, inplace=True) # creating lists for axis labels a = sorted(list(set(dframe['rainbow']))) b = sorted(list(set(dframe[qual2]))) # creating array of arrays form cumulative sum sss = [] for d in dframe[qual2].unique(): ms = dframe[dframe[qual2] == d].rainbow.value_counts() sss.append(ms) d = pd.concat(sss, axis=1).fillna(0) fr = d.transpose().to_numpy().astype(int) print(fr) all_fr = fr.cumsum(axis=1) # creating the figure instance fig, ax = plt.subplots(figsize=(lat, long)) ax.invert_yaxis() ax.xaxis.set_visible(False) ax.set_xlim(0, np.sum(fr, axis=1).max()) # the desinging part category_colors = plt.get_cmap('RdYlGn')(np.linspace(0.15, 0.85, fr.shape[1])) for i, (colname, color) in enumerate(zip(a, category_colors)): widths = fr[:, i] starts = all_fr[:, i] - widths ax.barh(b, widths, left=starts, height=0.5, label=colname, color=color) xcenters = starts + widths / 2 for y, (x, c) in enumerate(zip(xcenters, widths)): ax.text(x, y, str(int(c)), ha='center', va='center') if not show_axes: plt.axis('off') else: ax.legend(ncol=len(a), bbox_to_anchor=(0, 1), loc='lower left', fontsize='small') return fig # otherwise the function returns 'None' def line(dframe, quant1, quant2, lat=12, long=7, show_axes=True): """ Maidzhe Alexandra Create a figure of a line graph. :param dframe: the data frame; :param quant1: quantitative data for x-axis label; :param quant2: quantitative data for y-axis label; :param lat: width of the plot window; :param long: length of the plot window; :param show_axes: bool to allow axes' showing; :return: figure/None """ import copy # create new dataframe with only the needed columns # make a deep copy so that we do not to operate with slices df = copy.deepcopy(dframe[[quant1, quant2]]) # sort by x-axis df.sort_values(by=[quant1], inplace=True) x = df[quant1].tolist() y = df[quant2].tolist() fig = plt.figure(9, figsize=(lat, long)) ax = fig.add_subplot(111) ax.plot(x, y, 'r') if not show_axes: plt.axis('off') return fig def save_graph(figure): figure.savefig('figure.png', bbox_inches='tight') # **************************************************************** # dframe is the data frame # qual is the qualitative data (kachestvenniye) # quant is the quantitative data (kolichestvenniye) # **************************************************************** # #dframe is the data frame # qual is the qualitative data (kachestvenniye) # quant is the quantitative data (kolichestvenniye) def dispersion_diagram(data, p1, p2, qual, lat, long, show_axes): """ Mosolov Alexandr. The function builds a scatter diagram for two quantitative and one qualitative attributes. :param data: :type data: pandas DataFrame :param quan1: :type quan1: string :param quan2: :type quan2: string :param qual: :type qual: string :param wid: :type wid: int :param long: :type long: int :param show_axes: :type show_axes: bool :return fig: """ u = data[qual].unique() fig, ax = plt.subplots(figsize=(lat, long)) for i in range(len(u)): x = data.loc[data[qual] == u[i]][p1] y = data.loc[data[qual] == u[i]][p2] ax.scatter(x, y) # ax.set_xlabel(p1) # ax.set_ylabel(p2) ax.axis(show_axes) # ax.legend(u) return fig def kat_hist(data, qual, par, lat, long, show_axes): """ Mosolov Alexander. Creates categorized histogram according to two qualitative parameters. :param data: user data frame :type data: pandas.core.frame.DataFrame :param par: column of data frame with first quality parameter, abscissa :type par: pandas.core.series.Series :param qual: column of data frame with second quality parameter, graphics :type qual: pandas.core.series.Series :param lat: width of the plot window :type lat: int :param long: length of the plot window; :type long: int :param show_axis: axis display :type show_axis: bool :return: fig :rtype: matplotlib.figure.Figure """ c = data[qual].unique() fig, ax = plt.subplots(figsize=(lat, long), nrows=1, ncols=len(c)) for i in range(len(c)): x = data.loc[data[qual] == c[i]][par] ax[i].hist(x) ax[i].set_xlabel(par) ax[i].set_title(c[i]) ax[i].axis(show_axes) return fig def stkach(dframe, qual): """ Maidzhe Alexandra Creates a new data frame with frequencies and percentage of each element of a given data frame column. :param dframe: data frame :param qual: name of the column with the qualitative data; :return: data frame """ # Creating new data frame with frequencies m = dframe[qual].value_counts().to_frame() m.columns = ['Частота'] # Adding a column with percentages m['Процент(%)'] = dframe[qual].value_counts(normalize=True)*100 return m def stkol(dframe): """ Maidzhe Alexandra Creates a data frame with quantitative data's statistics. :param dframe: data frame :return: data frame """ # dropping columns that are numeric but do not have quantitative data dframe = dframe.drop(columns=['sex', 'id', 'bdate']) # Selecting all columns with numeric values left if not dframe.select_dtypes(include='number').empty: # and creating a new data frame with the statistics m = dframe.describe().transpose() m.columns = ['Amount of data', 'Arithmetic mean', 'Standard deviation', 'Minimum', 'Quartile 1', 'Quartile 2', 'Quartile 3', 'Maximum'] return m def piv(dframe, qual1, qual2, aggname): """ Maidzhe Alexandra Creates pivot table of two data frame's columns(qualitative data) :param dframe: data frame :param qual1: name of the column with the qualitative data for index(str); :param qual2: name of the column with the qualitative data for columns(str); :param aggname: name of the aggregation function to apply(str); :return: data frame; """ return dframe.pivot_table(index=qual1, columns=qual2, fill_value=0, aggfunc=aggname)
cfa8d708d00f2227b7a7fd5ac2b7657da8052d98
rainfidelis/budget_class
/budget_app.py
2,724
4.09375
4
import budget budget_dict = { 'Food': budget.Budget("Food"), 'Clothing': budget.Budget("Clothing"), 'Entertainment': budget.Budget("Entertainment"), 'Health': budget.Budget("Health"), 'Transport': budget.Budget("Transport") } def operations(budget_category): while True: try: operation = int(input("\nWhat would you like to do today? " "Enter: \n1 - Deposit \n2 - Withdrawal \n3 - Transfer \n")) except TypeError: raise TypeError("\nInvalid command! Try again...") continue if operation == 1: budget_category.deposit() break elif operation == 2: budget_category.withdraw() break elif operation == 3: receiver_name = input("\nEnter name of receiving account: ").strip().capitalize() receiver = budget_dict[receiver_name] budget_category.transfer(receiver) break else: print("\nInvalid command! Try again...") continue def main(): print("-----"*5) print("Rain Wallet") print("-----"*5) while True: print("\nExisting budget categories: ") for category in budget_dict: print(category) budget_to_run = input("\nEnter the name of the budget you wish to run or enter 1 to create a new budget category: ").strip().capitalize() if budget_to_run == '1': budget_to_create = input("\nEnter name of budget to create: ").strip().capitalize() if budget_to_create not in budget_dict: budget_dict[budget_to_create] = budget.Budget(budget_to_create) print(f"\nNew budget category created: {budget_to_create}") else: print(f"\n{budget_to_create} Budget Category already exists.") budget_to_run = budget_to_create # Set the new budget category as budget_to_run so it runs immediately pass if budget_to_run not in budget_dict: print("\nYour selected category does not exist.") continue else: print(f"\n***{budget_to_run} Budget***") print(f"\n{budget_to_run} Balance: NGN {budget_dict[budget_to_run].balance}") operations(budget_dict[budget_to_run]) run_again = input("\nWould you like to carry out another operation? \n[y/n]: ").lower() if run_again == 'y': continue else: print("\nSee you later!") break if __name__ == '__main__': main()
f47ce0897b4b12681df869a808f653675f4612af
tarcomurilo/bDevBC1
/Third/32_datetime.py
203
4.09375
4
#Write a Python program to display the current date and time. #Sample Output : #Current date and time : #2014-07-05 14:34:14 import datetime print(format(datetime.datetime.now(),'%Y-%m-%d %H:%M:%S'))
10c85c75d324100249a6151b2a586bb336e5ea41
edcoyote16/python_data_structures_and_algorithms_challenges
/Palindrome index.py
769
3.65625
4
# from collections import Counter # #string='qmdpbsswvmqtyhkobqeijjieqbokhytqmvwssbdmq' # string='abdccba' # length=len(string) # odd_value=0 # counter1=Counter(string) # for n in counter1.values(): # if n%2==0: # pass # else: # odd_value+=1 # # counter=0 # results=[] # string1=string[:(length+1)//2] # string2=string[::-1] # # for index_a, a in enumerate(string): # # b=string2[counter] # if a == b: # # counter+=1 # else: # results += [counter] # if string2[counter+1]==a: # counter+=2 # # # # # # # print(a) # # string='qmdpbsswvmqtyhkobqeijjieqbokhytqmvwssbdmq' # half=string[:(len(string)+1)//2] # the_other_half=string[(len(string)+1)//2:][::-1] # for index_a, a in enumerate(half): # print('') # # # # print(half) string='qmdpbsswvmqtyhkobqeijjieqbokhytqmvwssbdmq' string2=[::-1]
ab9d9b29b21c89ad89c7d80b77b2d39486068cad
reaprman/Data-Struct-algo-nanodegree
/proj2/problem6.py
3,025
3.875
4
class Node: def __init__(self, value): self.value = value self.next = None def __repr__(self): return str(self.value) class LinkedList: def __init__(self): self.head = None def __str__(self): cur_head = self.head out_string = "" while cur_head: out_string += str(cur_head.value) + " -> " cur_head = cur_head.next return out_string def append(self, value): if self.head is None: self.head = Node(value) return node = self.head while node.next: node = node.next node.next = Node(value) def size(self): size = 0 node = self.head while node: size += 1 node = node.next return size def union(llist_1, llist_2): # Your Solution Here lhead1, lhead2 = llist_1.head, llist_2.head values = set() while lhead1: values.add(lhead1.value) lhead1 = lhead1.next while lhead2: values.add(lhead2.value) lhead2 = lhead2.next newList = LinkedList() for i in values: newList.append(i) return newList pass def intersection(llist_1, llist_2): # Your Solution Here lhead1, lhead2 = llist_1.head, llist_2.head values1, values2 = set(), set() while lhead1: values1.add(lhead1.value) lhead1 = lhead1.next while lhead2: values2.add(lhead2.value) lhead2 = lhead2.next newList = LinkedList() for i in values1: if i in values2: newList.append(i) return newList pass # Test case 1 print("Test case 1") linked_list_1 = LinkedList() linked_list_2 = LinkedList() element_1 = [3,2,4,35,6,65,6,4,3,21] element_2 = [6,32,4,9,6,1,11,21,1] for i in element_1: linked_list_1.append(i) for i in element_2: linked_list_2.append(i) print (union(linked_list_1,linked_list_2)) print (intersection(linked_list_1,linked_list_2)) # Test case 2 print("Test case 2") linked_list_3 = LinkedList() linked_list_4 = LinkedList() element_1 = [3,2,4,35,6,65,6,4,3,23] element_2 = [1,7,8,9,11,21,1] for i in element_1: linked_list_3.append(i) for i in element_2: linked_list_4.append(i) print (union(linked_list_3,linked_list_4)) print (intersection(linked_list_3,linked_list_4)) # Test case print("Test case 3") linked_list_5 = LinkedList() linked_list_6 = LinkedList() element_1 = [] element_2 = [1,7,8,9,11,21,1] for i in element_1: linked_list_5.append(i) for i in element_2: linked_list_6.append(i) print (union(linked_list_5,linked_list_6)) print (intersection(linked_list_5,linked_list_6)) # Test case print("Test case 4") linked_list_7 = LinkedList() linked_list_8 = LinkedList() element_1 = [] element_2 = [] for i in element_1: linked_list_7.append(i) for i in element_2: linked_list_8.append(i) print (union(linked_list_7,linked_list_8)) print (intersection(linked_list_7,linked_list_8))
d2552cdafb9934164e554e2fe1ab874c345e118c
seagull1089/random-code
/python/src/getChange.py
964
3.796875
4
#!/usr/bin/python from collections import deque ''' Given the number of quarters available, the number of dimes available, and number of 5 cent coins available, return the the change for a given value in the available denominations. change for less than 5 cents can be ignored. uses breadth first search to generate change. ''' def getSum(item): return item[0]*25 + item[1]*10 + item[2]*5; def getChange(cents,quarters,dimes,nickels): start = [0,0,0] queue = deque([ start ]) while(len(queue) > 0): item = queue.popleft() if getSum(item) > cents: continue if cents - getSum(item) < 5: return item if quarters - item[0] > 0 : x = item[:] x[0] += 1 queue.append(x) if dimes - item[1] >0: x = item[:] x[1] += 1 queue.append(x) if nickels - item[2] > 0: x = item[:] x[2] += 1 queue.append(x) raise Exception('no change','get lost') if __name__ =="__main__": print getChange(65,1,2,4)
f86bd1aa606e88e0fb53dc9799cfda1a84f9e0b1
meet-projects/Y2-2016-C3
/Nir Python Test.py
296
3.6875
4
def Checker(list1,list2): a = [] for x in list1: for y in list2: if(x == y): a.append(x) return a Checker(["hi", "hi there","random letter", "not random"], ["hello", "wassup", "all cool?", "hi"])
c80631bc946d501f02f5769ac8ac5114f5911c82
pkt97/projects
/rsa.py
1,024
3.78125
4
m=1 cipher=3 plain=2 a=1 b=1 c=1 d=1 n=1 e=2 d=1 i=0 f=1 phi=1 def prime(a): flag=0 for i in range(2,a): if(a%i==0): print(a,"is not a prime number") exit(0) #return 0 if(flag==0): return 1 return 1 def gcd(a,b): if(a%b==0): return b else: return gcd(b,a%b) a=int(input("Enter first number")) b=int(input("Enter second number")) c=prime(a) d=prime(b) n=a*b phi=(a-1)*(b-1) for e in range(2,phi): if(gcd(e,phi)==1): print(e) print("Above is/are the possible value/s of e") f=int(input("Select any value of e:")) for i in range(0,phi): d=i if((d*e)%phi==1): break print("Private key is",d) m=int(input("Enter any message:")) cipher=pow(m,e) cipher=cipher%n print("Cipher text is",cipher) plain=pow(cipher,d) plain=plain%n print("Plain text is",plain) Output: Enter first number 5 Enter second number 7 5 7 11 13 17 19 23 Above is/are the possible value/s of e Select any value of e: 13 Private key is 23 Enter any message: 23 Cipher text is 32 Plain text is 23
85f4a8ab66433bbf2a0770fcb27243fdf09c4e6a
muhdibee/holberton-School-higher_level_programming
/0x0B-python-input_output/8-load_from_json_file.py
1,074
4.09375
4
#!/usr/bin/python3 import json def load_from_json_file(filename): """Creates a Python object from JSON file Args: filename (str): string of path to file Returns: Python object """ data = None with open(filename, 'r', encoding='utf-8') as json_data: data = json.load(json_data) return data if __name__ == '__main__': filename = "my_list.json" my_list = load_from_json_file(filename) print(my_list) print(type(my_list)) filename = "my_dict.json" my_dict = load_from_json_file(filename) print(my_dict) print(type(my_dict)) try: filename = "my_set_doesnt_exist.json" my_set = load_from_json_file(filename) print(my_set) print(type(my_set)) except Exception as e: print("[{}] {}".format(e.__class__.__name__, e)) try: filename = "my_fake.json" my_fake = load_from_json_file(filename) print(my_fake) print(type(my_fake)) except Exception as e: print("[{}] {}".format(e.__class__.__name__, e))
61706c3ab9fafb5786d1ed4aa2f8bdfd77196441
dixit5sharma/Individual-Automations
/CodeChef_Event.py
644
3.515625
4
testcases = int(input()) answer=[] while testcases>0: days = ["monday","tuesday","wednesday","thursday","friday","saturday","sunday"] k = input().split() S_E_sub = days.index(k[1]) - days.index(k[0]) if S_E_sub>0: diff = S_E_sub+1 else: diff = len(days)+S_E_sub+1 counter=0 while(diff<=int(k[3])): if diff>=int(k[2]): counter += 1 diff+=7 if counter>1: answer.append("many") elif counter==1: answer.append(diff-7) else: answer.append("impossible") testcases=testcases-1 for each in answer: print(each)
10b19f08b3e288a8cdea6817453d3d13de0dbbe6
qlccks789/Web-Study
/17_python/part1-basic/test03_자료형_할당.py
320
4.28125
4
""" 파이썬에서는 변수의 자료형은 대입되는 값에 따라 자동으로 정해진다. 데이터의 자료형 : type(데이터) """ data = 10 print(data, type(data)) # 10 <class 'int'> data = '10' print(data, type(data)) # 10 <class 'str'> data = True print(data, type(data)) # True <class 'bool'>
6db0831aec0d2e382969b2c2218d19f4ede2be80
ibraheemalayan/Unbeatable_TicTacToe
/players/player.py
609
3.578125
4
class XOPlayer: ''' this class represnts the xobot, it has the basic functions for a bot to play tic tac toe Available functions are : NextStep() should be overridden according to difficultiy level Grid object ''' def __init__(self, sign): ''' Construct an XOBot object''' self.sign = sign def play(self, game): ''' This method is abstract (should be overridden) ''' pass def done(self, state): ''' This method is abstract (should be overridden) and is intended for cli players''' pass
8c567fc71ece90408819e49093fed138c0743e4f
zanariah8/Starting_Out_with_Python
/chapter_06/q06.py
1,089
4.09375
4
# this program calculates the average of numbers # stored in names.txt file def main(): try: # open the file infile = open("numbers.txt", "r") # initialize an accumulator total = 0.0 # initialize a variable to keep the count of the lines count = 0 for line in infile: line = float(line) print(line) # add 1 to the count variable count += 1 # calculate the sum of the numbers total += line # close the file infile.close() # calculate the average and display average_num = total / count print("The average of the numbers stored in the file is", average_num) # this is exception in case there is 0 number in the file except ZeroDivisionError: print("ERROR: There is no number in the file") except ValueError: print("ERROR: The file has non-numeric content") # call the main function main()
f7d41356e5ee236888604bab2d781ecaf970e460
Natnaelh/Algorithm-Problems
/Searching/Linear_Search.py
363
3.921875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Jan 2 10:43:46 2020 @author: natnem """ def linearSearch(lst , e): #returns the index of item if it exists , if not None for i in range(len(lst)): if lst[i]==e: return i return None mylist = [1,5,87,5,13,1,8,4,6,7,4,5,8,5,4,7,79,6,78] print(linearSearch(mylist,1))
c252632b77c6e471a93e4ab737d650cef44d53bf
thomry/191011_pandas
/string_proce.py
1,189
3.65625
4
multi_str = """Guard: What? Ridden on a horse? King Arthur: Yes! Guard: You're using coconuts! King Arthur: What? Guard: You've got ... coconut[s] and you're bangin' 'em together. """ # splitlines 매서드 multi_str_split = multi_str.splitlines() # 특정 문자열 가져오기 guard = multi_str_split[::2] # replace 매서드로 guard: 문자열 빼보기 # Guard: 이 ''로 대체됨 guard = multi_str.replace('Guard: ', "").splitlines()[::2] print(guard) # 문자열 formatting # {} = place holder var = 'flesh wound' s = "It's just a {}!" print(s.format(var)) # 홀더에 변수 지정해도 됨. place holder에 :,넣으면 숫자를 표현가능. print("In 2005, Lu Chao of China recited {:,} digits of pi".format(67890)) # .4는 소숫점 이하의 숫자를 4개 출력. %사용시 백분율로 환산해 표현 print("I remember {0:.4} or {0:.4%} of what Lu Chao recited".format(7/67890)) # 42의 두자리값을 5자리수로 표현하되, 빈칸은 0으로 채워넣는 예문 print("My ID number is {0:05d}".format(42)) # % formatting s = 'I only know %d digits of pi' % 7 print(s) # string %s print('Some digits of %(cont)s: %(value).2f' % {'cont':'e', 'value':2.718})
60094482987385bbd36814e90be6b1b641955777
sriramv95/Python-Programming
/Pandas.py
3,369
3.5
4
# -*- coding: utf-8 -*- """ Created on Wed Feb 5 09:11:09 2020 @author: Sriram """ # ============================================================================= # Pandas package - is used to general task such as storing data is in the form of # a table, sorting of data, by group calculation etc.ArithmeticError # # All sorts of basic exploration data analysis(EDA) will be performed by Pandas # package. In order to use pandas package, we need to install it first, then # import in every session. # ============================================================================= import pandas as pd # ============================================================================= # Pandas has 2 types: Series and Dataframe # # Series - is used to store similar types of values and it is one dimentional # array # # Dataframe - is used to store different types of values in a spreadsheet format, # it is a 2 dimentional array # ============================================================================= sr = pd.Series([1,2,3,4,5]) print(type(sr)) print(sr) data1 = pd.DataFrame({'x':[101,102,103,104], 'y':['a','b','c','d'], 'z':['M','F','M','F'] }) print(type(data1)) print(data1) # Note: Each column should have equal number of values data2 = pd.DataFrame({'x':[100,101,102,103], 'y':'blr', 'z':'India'}) print(data2) data3 = pd.DataFrame({'x1': [100,101,102,103], 'x2': ['blr','chn'] * 2, 'x3': ['India'] * 4}) print(data3) import numpy as np # For Data with missing values data4 = pd.DataFrame({'x':[100,101,102,103], 'y':['blr',np.nan,'chn','mum'], 'z':['India'] * 4}) print(data4) # Class Assignment data5 = pd.DataFrame({'id':['A101','A102','A103','A104','A105','A106','A107', 'A108','A109','A110'], 'Name':['Ravi','Mona','Rabina','Mohan','Ganesh','Raju', 'Roja','Ramesh','Himani','Manish'], 'Sex':['M','F','F','M','M','M','F','M','F','M'], 'Age':np.random.randint(20,40,10), 'Salary':[25000,35000] * 5}) print(data5) # Extraction data5['Name'] data5['Name'][0:5] data5[['Name','Age']] data5[0:5] # What is the salary for mohan data5[data5['Name'] == 'Mohan']['Salary'] # What is the salary for mohan and ganesh print(data5[data5['Name'] == 'Mohan']['Salary'] data5[data5['Name'] == 'Ganesh']['Salary']) # basic information about DataFrame print(data5.head()) print(data5.tail()) print(data5.shape) print(data5.columns) # dataframe manupilation # addind new column data5['HRA'] = data5['Salary'] * 0.3 print(data5) # dropping coloums data5.drop(['id'],axis = 1,inplace = True) # axis = 1 means column delete # inplace = True means same result to same data frame # Transpose the data data5.T # Sorting the data frame data5.sort_values(by = 'Salary') # Grouping by calculation # Find the average # Sum of HRA column data5.groupby(by = 'Sex')['Salary'].mean() data5.groupby(by = 'Sex')['HRA'].mean() data5['HRA'].sum()
703425e8fd98c3363919da60f487fb17f8ae88bf
GuptaAman08/CompetitiveCoding
/Other Company Coding Problem/Tree Practice/LCA_ver1.py
1,059
3.546875
4
class Node: def __init__(self, key): self.data = key self.left = None self.right = None def findPath(root, n1, p): if root is None: return False if root.data == n1: p.append(root.data) return True if findPath(root.left, n1, p): p.append(root.data) return True if findPath(root.right, n1, p): p.append(root.data) return True return False def LCA(root, n1, n2): p1 = [] p2 = [] if not findPath(root, n1, p1) or not findPath(root, n2, p2): return 'No Common Ancestor' p1.reverse() p2.reverse() i = 0 a = len(p1) b = len(p2) while i < a and i < b: if p1[i] != p2[i]: break i += 1 return p1[i-1] root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) root.right.left = Node(6) root.right.right = Node(7) n1, n2 = [int(x) for x in input().split()] print(f'LCA of {n1} and {n2} is {LCA(root, n1, n2)}')
38a1e97f5b202383373904a251019d12d8726ec6
keeny8/Python-DiceGame
/DiceCards.py
1,748
3.890625
4
import random #Game from when we were kids # We have 6 dice and we bet if we will match the card or not class Dice: @staticmethod def roll(): return (random.randint(0,5)+1) class Card: @staticmethod def getCard(): card = [0,0,0,0,0,0] i = 0 while i < len(card): card[i] = Dice.roll() i+=1 return card class DiceHolder: def __init__(self, diceCount=9): self.diceCount = diceCount self.shakeDice() def __str__(self): retStr = ""; for x in self.diceValues: retStr = retStr+str(x)+", " retStr = retStr+"\n" return retStr def setDiceCount(self, amount): self.diceCount = amount def getDice(self): return self.diceValues def shakeDice(self): self.diceValues = [] i = 0 while i < self.diceCount: self.diceValues.append(Dice.roll()) i += 1 class DiceCards: @staticmethod def playARound(): card = Card.getCard() card.sort() matches = card.copy() print("Card: ") print(card) i = 0 won = False diceholder = DiceHolder() while i < 3: diceholder.shakeDice() diceholder.getDice().sort() print("Dice Roll: ") print(diceholder.getDice()) #matches for dice in diceholder.getDice(): cardIndex = 0 while cardIndex < len(matches): if matches[cardIndex] == dice: #dice matches set matches to 0 matches[cardIndex] = 0 diceholder.setDiceCount(diceholder.diceCount-1) break cardIndex += 1 print("Matches: ") print(matches) if sum(matches) == 0: won = True break i += 1 if won: print("Game Won!") return 1 else: print("Round Lost") return 0 while True: win = DiceCards.playARound() print("Play again? y/n") input1 = input() if(input1!='y' != input1!='yes'): break
d630735f5374ba6027edfaed217eeb9bc65655fc
Xarct/Matematica-Financeira-
/taxa aparente real .py
450
3.5625
4
ir = float ( input ( " Digite a taxa de juros real anual : ")) i =float ( input ( " Digite o valor da inflação anual: ")) import math x =(( ir / 100 ) * ( (i /100 )+ 1) ) taxaaparente =(( x + ( i /100 + 1 )) - 1) taxamensal =((( 1 + taxaaparente )**0.08333) - 1) tp = taxaaparente * 100 tm =(( taxamensal ) ) * 100 print ( " O valor da taxa aparente anual é de :%.1f "% tp,"%") print ( " O valor da taxa aparente mensal é de : %.1f " % tm, "%")
3f28e87f38ca5b8929fde2b0f4602f8e6113e132
majabojarska/tadpole
/src/motor_controller.py
8,983
3.796875
4
import math import typing from . import motor class MotorController: """ Class for controlling front motors. Motor pins are defined as BCM GPIO indices. """ SQRT_OF_TWO = math.sqrt(2) LEFT_MOTOR_POSITIVE_GPIO = 13 LEFT_MOTOR_NEGATIVE_GPIO = 6 RIGHT_MOTOR_POSITIVE_GPIO = 26 RIGHT_MOTOR_NEGATIVE_GPIO = 19 MAX_ABS_AXIS_VALUE = 2 ** 15 def __init__( self, enable_throttle_curve: bool = False, throttle_gate_threshold: float = 0.1, throttle_scale: float = 1.0, throttle_limit: float = 1.0, ) -> None: """ Parameters ---------- enable_throttle_curve : bool If True, a throttle curve will be used. throttle_gate_threshold : float Threshold of the throttle gate. Throttle will be applied only if it exceeds this value. throttle_scale : float The value by which the throttle will be scaled. throttle_limit : float The maximum value throttle can achieve after applying all other modifiers. """ self.left_motor = motor.Motor( self.LEFT_MOTOR_POSITIVE_GPIO, self.LEFT_MOTOR_NEGATIVE_GPIO, is_reversed=True, ) self.right_motor = motor.Motor( self.RIGHT_MOTOR_POSITIVE_GPIO, self.RIGHT_MOTOR_NEGATIVE_GPIO ) self.enable_throttle_curve = enable_throttle_curve self.throttle_gate_threshold = throttle_gate_threshold self.throttle_scale = throttle_scale self.throttle_limit = throttle_limit def handle_vector_input(self, input_vector: typing.Tuple[int, int]) -> None: """ Calculates and sets the throttle of both motors based on the input vector. Input vector processing chain is as follows: IN--->[Scale]->[Gate]->[Limit]--->OUT Parameters ---------- input_vector : list A list of two integer values in the range of [0;65535]. """ angle = MotorController.calc_vector_angle(input_vector) left_motor_throttle_modifier = self.calc_left_throttle_mod(angle) right_motor_throttle_modifier = self.calc_right_throttle_mod(angle) throttle = self.throttle_scale * self.calc_normalized_vector_length( input_vector ) if self.enable_throttle_curve: throttle = self._apply_throttle_curve(throttle) if self.throttle_gate_threshold is not None: throttle = self._apply_throttle_gate(throttle) if self.throttle_limit is not None: throttle = self._apply_throttle_limiting(throttle) left_motor_throttle = throttle * left_motor_throttle_modifier right_motor_throttle = throttle * right_motor_throttle_modifier self.left_motor.change_throttle(left_motor_throttle) self.right_motor.change_throttle(right_motor_throttle) def stop(self): """ Stops both motors. :return: None """ self.left_motor.stop() self.right_motor.stop() @staticmethod def calc_left_throttle_mod(joystick_angle: float) -> float: """ Calculates left motor throttle modifier. Function visualization: https://www.desmos.com/calculator/rhvsokblhl Parameters ---------- joystick_angle : float The angle of the joystick with respect to the positive x axis. Returns ------- throttle_modifier : float Throttle modifier for the left motor. """ MotorController._assert_angle_within_range(joystick_angle) throttle_modifier = None if -180 < joystick_angle <= -90: throttle_modifier = -1.0 elif -90 < joystick_angle < 0: throttle_modifier = joystick_angle / 45 + 1 elif 0 <= joystick_angle <= 90: throttle_modifier = 1.0 elif 90 < joystick_angle <= 180: throttle_modifier = -joystick_angle / 45 + 3 return throttle_modifier @staticmethod def calc_right_throttle_mod(joystick_angle: float) -> float: """ Calculates right motor throttle modifier. Function visualization: https://www.desmos.com/calculator/xfo4g4fh4j Parameters ---------- joystick_angle : float The angle of the joystick with respect to the positive x axis. Returns ------- throttle_modifier : float Throttle modifier for the right motor. """ MotorController._assert_angle_within_range(joystick_angle) throttle_modifier = None if -180 < joystick_angle < -90: throttle_modifier = -joystick_angle / 45 - 3 elif -90 <= joystick_angle <= 0: throttle_modifier = -1.0 elif 0 < joystick_angle < 90: throttle_modifier = joystick_angle / 45 - 1 elif 90 <= joystick_angle <= 180: throttle_modifier = 1.0 return throttle_modifier def calc_normalized_vector_length( self, input_vector: typing.Tuple[int, int] ) -> float: """ Calculates a normalized Euclidean vector length. Parameters ---------- input_vector : tuple a tuple of two integer values representing a vector with initial point at (0,0) and a specified terminal point. Returns ------- normalized_length : float Length of the normalized input vector. """ assert type(input_vector) == tuple assert len(input_vector) == 2 length = math.sqrt(input_vector[0] ** 2 + input_vector[1] ** 2) normalized_length = length / self.MAX_ABS_AXIS_VALUE if normalized_length > 1: normalized_length = 1 return normalized_length @staticmethod def calc_vector_angle(input_vector: typing.Tuple[int, int]) -> float: """ Calculates the angle between the positive x axis and the input vector. Parameters ---------- input_vector : tuple a tuple of two integer values representing a vector with initial point at (0,0) and a specified terminal point. Returns ------- float vector angle as degrees in range (-180;180] """ radians = math.atan2(input_vector[1], input_vector[0]) return math.degrees(radians) @staticmethod def _assert_angle_within_range(angle: float) -> None: """ Asserts that the input angle is within a valid range of [-180;180) degrees. Parameters ---------- angle : float Input angle. Raises ------ ValueError If angle <= -180 or angle > 180. """ if angle <= -180 or angle > 180: raise ValueError("Input angle is out of permitted range (-180;180]") @staticmethod def _apply_throttle_curve(throttle_modifier: float) -> float: """ Applies a throttle curve to the input throttle modifier. As an effect, this modifies sensitivity of the target motor to the input vector. Parameters ---------- throttle_modifier : float Input throttle modifier. Returns ------- new_throttle_modifier : float Resulting throttle modifier after mapping to a 3rd order polynomial curve. """ a = 0 b = 0.1666667 c = 1.722222 d = 0.5555556 new_throttle_modifier = ( a - b * throttle_modifier + c * throttle_modifier ** 2 - d * throttle_modifier ** 3 ) if not 0 <= new_throttle_modifier <= 1: new_throttle_modifier = round(new_throttle_modifier) return new_throttle_modifier def _apply_throttle_gate(self, input_throttle: float): """ Calculates a gated throttle with respect to the gate threshold. Parameters ---------- input_throttle : float The input throttle value. Returns ------- float The gated throttle. Equals 0 for any value less than self.throttle_gate_threshold. """ if abs(input_throttle) < self.throttle_gate_threshold: return 0 return input_throttle def _apply_throttle_limiting(self, input_throttle: float): """ Calculates a limited throttle with respect to the set limit. Parameters ---------- input_throttle : float The input throttle value. Returns ------- float The limited throttle value. """ result_throttle = input_throttle if abs(input_throttle) > self.throttle_limit: result_throttle = self.throttle_limit result_throttle = math.copysign(result_throttle, input_throttle) return result_throttle
c50f65dd33c41d34de3154ba26897f27b6a054c1
galya-study/ji
/py/1. inout_and_arithmetic_operations/ex 1 aplusbplusc.py
308
3.859375
4
#Сумма трёх чисел #Напишите программу, которая считывает три числа и выводит их сумму. Каждое число записано в отдельной строке. a = int(input()) b = int(input()) c = int(input()) d = a + b + c print(d)
f14efaf8822ea077598b103efb39f152f4e42c6c
AbrarJahin/Tree-Implementation-In-Python
/HashTable.py
1,377
3.890625
4
class HashTable: # default constructor def __init__(self, maxNoOfElement = 100): self.currentSize = 0 self.maxSize = maxNoOfElement self.hashData = [None for _ in range(maxNoOfElement)] # a method for printing data members def __repr__(self) -> str: return "Size : " + str(self.currentSize) + "/" + str(self.maxSize) def __str__(self) -> str: return ', '.join(str(e) for e in self.hashData if e is not None) def getHashValue(self, keyString: str) -> int: currentVal = 0 for val in [ord(ch) for ch in keyString]: currentVal = currentVal*26 + val return currentVal % self.maxSize def isKeyExist(self, key: str) -> bool: return self.search(key) is not None def search(self, key: str) -> bool: return self.hashData[self.getHashValue(key)] def insert(self, key: str) -> str: if self.isKeyExist(key): #raise Exception("Sorry, Data Already Exists, Need overwrite") print("Key Already Exists") self.currentSize -= 1 self.hashData[self.getHashValue(key)] = key self.currentSize += 1 def delete(self, key: str) -> None: if not self.isKeyExist(key): #raise Exception("Sorry, Data Not Exists") print("Key Not Found") self.currentSize += 1 self.hashData[self.getHashValue(key)] = None self.currentSize -= 1 #def insert(data): #If dynamic size # hash_key = Hashing(keyvalue) # Hashtable[hash_key].append(value)
c46bc5c67f43aeeee467fd7a0077e264d8ab3673
Digvijay003/pythonbasics
/iteration.py
395
3.578125
4
"""iterators """ class Remotecontrol(): def __init__(self): self.channels = ['a','b','c','d','e'] self.index = -1 def __iter__(self): return self def __next__(self): self.index += 1 if self.index == len(self.channels): raise StopIteration return self.channels[self.index] r = Remotecontrol() iter = iter(r) print(iter)
5f295102ec7d2afa6b1ea36f381fe7f9b413e5dd
ulinka/tbcnn-attention
/scripts/test.py
222
3.921875
4
import itertools list_1 = [1,2,3,4] list_2 = [3,8,9,10] list_3 = [list_1, list_2] for element in itertools.product([list_1,list_2]): print(element) cart_prod = [(a,b) for a in list_1 for b in list_2] print(cart_prod)
f6e6b767fd6447ec0f0fc337f672100b68821012
BenMeehan/Data-Structures-and-Algorithms---Revision
/Recursion/sum.py
116
3.640625
4
li=[1,2,3,4,5] def summ(li): if len(li)==1: return li[0] return li[0]+summ(li[1:]) print(summ(li))
9295ce799c6ed507b6a3055c1e501f65f5bfaedb
amohant4/coding-practice
/search.py
2,107
4.34375
4
# Searching algorithms. import math def binarySearch(arr, start, end, key): """ Compare with mid element and decide if you want to look in upper/lower half of array. O(logn) complexity """ if start > end: return -1 mid = start + (end-start)/2 if arr[mid] == key: return mid elif arr[mid] < key: return binarySearch(arr, mid+1, end, key) else: return binarySearch(arr, start, mid-1, key) def jumpSearch(arr, key): """ Keep jumping with step size of sqrt(n) till the interval has the key in range Then do linear search. Its complexity is O(sqrt(n)). its between linear and binary search. In systems where jumping back is difficult, jump search is better than binary search. """ print '~~~ jump search ~~~' n = len(arr) step = int(math.sqrt(len(arr))) prev = 0 while (arr[math.min(step,n)] < key): prev = step step = step + step if prev >= n: return -1 # TODO def interpolationSearch(arr, start, end, key): """ Improvement over binary search. Instead of starting in the mid, it looks at the interpolated location. This method works if the array contains numbers uniformly distributed. """ if start > end: return -1 loc = start + int((end - start)*(key - arr[start])/(arr[end]-arr[start])) if arr[loc] == key: return loc elif arr[loc] < key: return interpolationSearch(arr, loc+1, end, key) else: return interpolationSearch(arr, start, loc-1, key) def exponentialSearch(arr, key): """ look at positios 1,2,4,8,16,... then do binary search in the interval This is good when trying to find something in an un-ending list of sorted elements. Ex. finding 0 crossing in an monotonic function. """ #TODO if __name__ == '__main__': arr = [1,2,3,4,7,9,9,10,12,18,24] key = 10 idx = interpolationSearch(arr, 0, len(arr)-1, key) if idx == -1: print 'element not found' else: print 'element found at {}'.format(idx)
511fc2b07773145048c8b3c2c6d90d5ad0aa2550
minji-o-j/Python
/컴퓨팅 사고와 문제해결/5강 연습문제/5-8.py
695
3.75
4
x1=int(input("큰 원의 중심좌표 x1: ")) y1=int(input("큰 원의 중심좌표 y1: ")) r1=int(input("큰 원의 반지름 r1: ")) x2=int(input("작은 원의 중심좌표 x2: ")) y2=int(input("작은 원의 중심좌표 y2: ")) r2=int(input("작은 원의 반지름 r2: ")) dis=((x1-x2)**2+(y1-y2)**2)**0.5 import turtle t=turtle.Turtle() t.shape("turtle") t.up() t.goto(x1,y1-r1) t.down() t.circle(r1) t.up() t.goto(x2,y2-r2) t.down() t.circle(r2) if(dis<=r1-r2): t.write(" 작은 원은 큰 원의 내부에 있습니다.") elif(dis<r1+r2): t.write(" 작은 원은 큰 원과 걸쳐있습니다.") else: t.write(" 작은 원은 큰 원의 외부에 있습니다.")
e5c61ee16c5cdb429116917f6407bed7d5a8bb4d
leomessiah10/textGame
/for_her.py
1,128
3.953125
4
from random import randint as rd rand_num = rd(1,10) tries = 1 condition = 1 #print(rand_num) user_name = input("Hey !! What's your good name\n:-") print('Hi',user_name + '.') ques = input('Do you wish to play a game\n[Y/N]\n') if ques == 'N' or ques == 'n' : print("Well..it's the best i can do\nGood Bye") exit elif ques == 'Y' or ques == 'y' : print('Alright...its start this way ') print('I will guess a number between 1 to 10\n') while condition == 1 or tries !=6: guess = int(input("Make a guess of the number\n")) if guess > rand_num : print('You guessed a big number...make it small') tries +=1 elif guess < rand_num : print('Nooooo....think of a greater number') tries +=1 else : #printguess == rand_num : condition = 0 print('Great ....You have guessed a right number') print('You have guessed the nunber in ',tries, 'chances') break else : print('You are something that the world wants to get rid off') exit
fed27214f2ab2a8e19edbb3159a4dbb28cb4ecb5
Serdiuk-Roman/for_lit
/L6/dz6/game.py
1,025
3.53125
4
from abc import ABCMeta class Unit(metaclass=ABCMeta): def __init__(self, health, recharge): self.health = health self.recharge = recharge @abstractmethod def attack(self, target): pass @abstractmethod def take_damage(self, dmg): pass @abstractmethod def is_active(self): pass # @property # @abstractmethod # is_alive # health # attack_power # если речардж достиг нуля то можна брать юнита и атаковать def recharge(self): pass def teek(self): pass class Clock: def __init__(self): self.i = 0 def tick(self): self.i += 1 def time(self): return self.i class Soldier(Unit): def __init__(self, health, recharge, experience): pass def attack(self): return 0.5 * (1 + self.health/100) * random(50 + self.experience, 100) / 100 def damage(self): return 0.05 + self.experience / 100
747a21750a6d70084cfdc09b28ec8a1fb83fbfe2
Joy1Feng/data-structure
/03-队列.py
384
3.53125
4
# coding:utf-8 class Queue(object): """队列的实现""" def __init__(self): self.__list = [] def enqueue(self,item): self.__list.append(item) def dequeue(self): return self.__list.pop(0) def is_empty(self): return not self.__list def size(self): return len(self.__list) if __name__ == "__main__": q = Queue()
afc60f25693a32c6760c52224ea97124216f4aa7
Mohan110594/Competitive_Coding-3
/k-diff_pairs_in_array.py
1,820
3.625
4
// Did this code successfully run on Leetcode : Yes // Any problem you faced while coding this : None // Your code here along with comments explaining your approach: we used two pointers low and high. 1)if nums[high]-nums[low]==k then we add it to the result. 2)If nums[high]-nums[low] is greater than k we have to increase low to make the difference near to k. 3)If the above does not satisfy then we increment the high pointer. #Time complexity --> o(n) #space complexity --> o(n) class Solution: def findPairs(self, nums: List[int], k: int) -> int: nums=sorted(nums) low=0 high=low+1 # count=0 res=set() while low<=high and low<len(nums) and high<len(nums): # print(low,high) #take the example [1,1,1,2,2] target=0 #we start low=0 and high=1 #we check the if nums[high]-nums[low]==target we add it to the set.we used set to prevent duplicates from occuring. #if the difference between these numbers is greater than target we need to decrease the value so we increment the low value else we increment high pointer. #when low and high are equal we might be considering these elements so we have to skip these values so we used the below. #for instance at index 3 low and high pointers will meet for the above example.inorder to get rid of the above values we took this into consideration. if low==high: high=high+1 continue if nums[high]-nums[low]==k: res.add((nums[low],nums[high])) low=low+1 high=high+1 elif nums[high]-nums[low]>k: low=low+1 else: high=high+1 print(res) return len(res)
6d9d6669e09c6c5e7d3e87305a3da8a5c006cdbd
james-claar/Python-Projects
/Pysweeper.py
15,915
4.03125
4
""" Minesweeper implementation in python. Played through command prompt. Note: Although this program has an auto-save feature, it lacks much normal user input error checking and therefore tends to crash upon unacceptable user input. """ import random ROWS = 7 COLUMNS = 7 MINES = 10 AUTOSAVE_BOOL = True # Whether or not the program should save to a file. SAVE_FILE = "autosave.txt" mine_grid = [] # 0 is empty, 1 is mine numerical_grid = [] # Numbers are how many mines are around the space visual_grid = [] # 0 means the user can see this space, 1 means unseen and unmarked, 2 means unseen flagged, and 3 means unseen question marked visible_grid = [] # This is the grid that will be put into the board for the user to see. Needs updated every move. def create_empty_grids(): global mine_grid global numerical_grid global visual_grid global visible_grid for row in range(ROWS): mine_grid.append([]) numerical_grid.append([]) visual_grid.append([]) visible_grid.append([]) for column in range(COLUMNS): mine_grid[row].append(0) numerical_grid[row].append(0) visual_grid[row].append(1) visible_grid[row].append(" ") def generate_mines(): for i in range(MINES): spawn_row = random.randint(0, ROWS - 1) # spawn the mine in a random location spawn_column = random.randint(0, COLUMNS - 1) while mine_grid[spawn_row][spawn_column] == 1: # if this location is already occupied by a mine, try another spawn_row = random.randint(0, ROWS - 1) spawn_column = random.randint(0, COLUMNS - 1) mine_grid[spawn_row][spawn_column] = 1 def generate_mine_numbers(): for row in range(ROWS): for column in range(COLUMNS): surrounding_squares = get_surrounding_squares(row, column) mine_count = 0 for square in range(len(surrounding_squares)): if mine_grid[surrounding_squares[square][0]][surrounding_squares[square][1]] == 1: # if this surrounding square is a mine mine_count += 1 # add it to the square's number numerical_grid[row][column] = mine_count def get_surrounding_squares(row, column): square_coords = (row, column) output = [] for i in range(3): # examine the 3*3 area with square_coords as the center for j in range(3): if 0 <= square_coords[0] + (i-1) <= ROWS - 1: # if the square's X axis is inside the grid if 0 <= square_coords[1] + (j-1) <= COLUMNS - 1: # if the square's Y axis is inside the grid if (square_coords[0] + (i-1), square_coords[1] + (j-1)) != square_coords: # if it isn't the input square output.append((square_coords[0] + (i-1), square_coords[1] + (j-1))) return output def update_visible_grid(): global mine_grid global numerical_grid global visual_grid global visible_grid text_key = { "clear":" ", "1":" 1 ", "2":" 2 ", "3":" 3 ", "4":" 4 ", "5":" 5 ", "6":" 6 ", "7":" 7 ", "8":" 8 ", "uncovered mine":"XXX", "hidden":"[ ]", "flag":"[X]", "question":"[?]" } for row in range(ROWS): for column in range(COLUMNS): if visual_grid[row][column] in [1,2,3]: # deal with all 3 hidden square types if visual_grid[row][column] == 1: visible_grid[row][column] = text_key["hidden"] elif visual_grid[row][column] == 2: visible_grid[row][column] = text_key["flag"] elif visual_grid[row][column] == 3: visible_grid[row][column] = text_key["question"] else: # if it's not one of the three hidden square types: if mine_grid[row][column] == 1: # deal with uncovered mines visible_grid[row][column] = text_key["uncovered mine"] else: # if it's not a mine hint number: if numerical_grid[row][column] in [1, 2, 3, 4, 5, 6, 7, 8]: # deal with mine hint numbers visible_grid[row][column] = text_key[str(numerical_grid[row][column])] else: # it's not any of these visible_grid[row][column] = text_key["clear"] def print_visible_grid(): """ example grid +---+---+---+---+---+---+---+ |PYSWEEP| 1 | 2 | 3 | 4 | 5 | + Mines + + + + + + | 3 | | | | | | +---+---+---+---+---+---+---+ | 1 | | 1 | 1 | 2 |[ ]| +---+---+---+---+---+---+---+ | 2 | * | 1 |[X]|[ ]|[ ]| +---+---+---+---+---+---+---+ | 3 | | 2 | 4 |[ ]|[ ]| +---+---+---+---+---+---+---+ | 4 | | 1 |[X]|[?]|[ ]| +---+---+---+---+---+---+---+ | 5 | | 1 |[ ]|[ ]|[ ]| +---+---+---+---+---+---+---+ star is coords (1,2) """ flag_count = 0 for row in range(ROWS): # Count how many unflagged mines there are on the grid for column in range(COLUMNS): if visual_grid[row][column] == 2: # this square is flagged flag_count += 1 separator_row = "+---+---" clear_separator_row = "+ Mines " clear_data_row = "| " + space_int(MINES - flag_count) + " " for i in range(COLUMNS): separator_row = separator_row + "+---" clear_separator_row = clear_separator_row + "+ " clear_data_row = clear_data_row + "| " separator_row = separator_row + "+" clear_separator_row = clear_separator_row + "+" clear_data_row = clear_data_row + "|" column_marker_row = "|PYSWEEP" for i in range(COLUMNS): column_marker_row = column_marker_row + "|" + space_int(i + 1) column_marker_row = column_marker_row + "|" print(separator_row) print(column_marker_row) print(clear_separator_row) print(clear_data_row) for row in range(ROWS): print(separator_row) data_row = "|" + space_int(row + 1) + " " for column in range(COLUMNS): data_row = data_row + "|" + visible_grid[row][column] data_row = data_row + "|" print(data_row) print(separator_row) def space_int(num): num = str(int(num)) # ensure that num comes out as a string, we wouldn't want to add spaces to an int! if len(num) == 1: output = " " + num + " " elif len(num) == 2: output = num + " " elif len(num) == 3: output = num else: output = "BIG" return output def receive_user_commands(): help_text = "open <coords>: Reveals a square.\n" \ "flag <coords>: Flags a square as a mine.\n" \ "clear <coords>: Removes flags or question marks in the square.\n" \ "chord/openaround <coords>: Opens all non-flagged squares around the square. Only works if the number of flags around it equals the number in the square.\n" \ "flags/flagaround <coords>: Flags all hidden spaces around a square, if the number of spaces equals the number in the square.\n" \ "help/?: Pulls up this help list.\n" \ "exit/stop/quit: Stops the game.\n" \ "\n" \ "Replace all <coords> with the square coordinates, in column,row format with no spaces, i.e. '2,4'.\n" \ "Example command:\n" \ "flag 2,3\n" \ "Will place a flag in the space at column 2 and row 3." valid_commands = [ "open", "flag", "clear", "chord", "openaround", "flags", "flagaround", "help", "?", "exit", "stop", "quit", "load" ] user_input = input("PYSWEEP >>>").split(" ") command = user_input[0].lower() if command not in valid_commands: print("'" + str(command) + "' is not a valid command. Try 'help' or '?' for a list of commands") return # end the function due to invalid command elif command in ["exit", "stop", "quit"]: exit(0) elif command in ["help", "?"]: print(help_text) return # end the function so we don't continue and get errors for not having args elif command == "load": load_save() return # end the function so we don't continue and get errors for not having args square = list(user_input[1].split(",")) if len(square) != 2: return # end the function due to bad coords square.reverse() # reverse list so that the first value in the tuple is the column, not the row square[0] = int(square[0]) - 1 square[1] = int(square[1]) - 1 if command == "open": open_square(square[0], square[1]) elif command == "flag": if visual_grid[square[0]][square[1]] != 0: # We are a hidden square visual_grid[square[0]][square[1]] = 2 elif command == "clear": if visual_grid[square[0]][square[1]] in [2,3]: # We are a flag or a question mark visual_grid[square[0]][square[1]] = 1 elif command in ["chord", "openaround"]: if visual_grid[square[0]][square[1]] == 0: # We can see this square if numerical_grid[square[0]][square[1]] in [1,2,3,4,5,6,7,8]: # It is a mine hint number surrounding_squares = get_surrounding_squares(square[0], square[1]) mine_count = 0 for adj_square in range(len(surrounding_squares)): if visual_grid[surrounding_squares[adj_square][0]][surrounding_squares[adj_square][1]] == 2: # this is a flag mine_count += 1 if numerical_grid[square[0]][square[1]] == mine_count: for adj_square in surrounding_squares: if visual_grid[adj_square[0]][adj_square[1]] == 1: # this square is unseen and unmarked open_square(adj_square[0], adj_square[1]) # open it elif command in ["flags", "flagaround"]: if visual_grid[square[0]][square[1]] == 0: # We can see this square if numerical_grid[square[0]][square[1]] in [1,2,3,4,5,6,7,8]: # It is a mine hint number surrounding_squares = get_surrounding_squares(square[0], square[1]) hidden_count = 0 for adj_square in range(len(surrounding_squares)): if visual_grid[surrounding_squares[adj_square][0]][surrounding_squares[adj_square][1]] != 0: # this is a hidden square hidden_count += 1 if numerical_grid[square[0]][square[1]] == hidden_count: for adj_square in range(len(surrounding_squares)): if visual_grid[surrounding_squares[adj_square][0]][surrounding_squares[adj_square][1]] != 0: # if this square is hidden: visual_grid[surrounding_squares[adj_square][0]][surrounding_squares[adj_square][1]] = 2 # flag this square def shift_mines_from_square(row, column): global mine_grid surrounding_squares = get_surrounding_squares(row, column) surrounding_squares.append((row, column)) mines_around_bool = True while mines_around_bool: for adj_square in surrounding_squares: if mine_grid[adj_square[0]][adj_square[1]] == 1: mine_grid[adj_square[0]][adj_square[1]] = 0 spawn_row = random.randint(0, ROWS - 1) # spawn the mine in a random location spawn_column = random.randint(0, COLUMNS - 1) while mine_grid[spawn_row][spawn_column] == 1: # if this location is already occupied by a mine, try another spawn_row = random.randint(0, ROWS - 1) spawn_column = random.randint(0, COLUMNS - 1) mine_grid[spawn_row][spawn_column] = 1 temp = False for adj_square in surrounding_squares: if mine_grid[adj_square[0]][adj_square[1]] == 1: temp = True mines_around_bool = temp generate_mine_numbers() # update the mine numbers def open_square(row, column): global first_square_opened if first_square_opened: shift_mines_from_square(row, column) first_square_opened = False if visual_grid[row][column] == 2: # this square is flagged visual_grid[row][column] = 3 # set it to a question mark elif visual_grid[row][column] == 3: # this square has a question mark visual_grid[row][column] = 1 # remove the question mark elif mine_grid[row][column] == 1: # we hit a non-flagged mine game_over() elif numerical_grid[row][column] in [1,2,3,4,5,6,7,8]: # we hit a mine hint number visual_grid[row][column] = 0 else: # we hit a blank space visual_grid[row][column] = 0 surrounding_squares = get_surrounding_squares(row, column) for square in range(len(surrounding_squares)): if visual_grid[surrounding_squares[square][0]][surrounding_squares[square][1]] != 0: open_square(surrounding_squares[square][0], surrounding_squares[square][1]) def check_win(): possible_win = True for row in range(ROWS): # If we can see every space that is not a mine, we win for column in range(COLUMNS): if visual_grid[row][column] != 0 and mine_grid[row][column] == 0: # If we cannot see this space but it is not a mine, we do not win possible_win = False if possible_win: print("You win! Yay!") exit(0) def game_over(): for row in range(ROWS): # reveal all of the spaces for column in range(COLUMNS): visual_grid[row][column] = 0 update_visible_grid() print_visible_grid() print("You have triggered a mine! Better luck next time!") exit(0) def auto_save(): with open(SAVE_FILE, "w+") as f: f.write(str(ROWS) + "\n") f.write(str(COLUMNS) + "\n") f.write(str(MINES) + "\n") for row in range(ROWS): # save the mine grid for column in range(COLUMNS): f.write(str(mine_grid[row][column]) + "/") f.write("\n") # we skip the numerical grid, because it can be generated from the mine grid for row in range(ROWS): # save the visual grid for column in range(COLUMNS): f.write(str(visual_grid[row][column]) + "/") def load_save(): global ROWS global COLUMNS global MINES global mine_grid global numerical_grid global visual_grid global first_square_opened first_square_opened = False # otherwise we will shift mines away from the first click with open("Pysweeper Saves\\autosave.txt", "r") as f: lines = f.readlines() ROWS = int(lines[0]) COLUMNS = int(lines[1]) MINES = int(lines[2]) temp = lines[3][:-2].split("/") # Load the mine grid for row in range(ROWS): for column in range(COLUMNS): mine_grid[row][column] = int(temp[(row * COLUMNS) + column]) generate_mine_numbers() temp = lines[4].split("/") # Load the visual grid for row in range(ROWS): for column in range(COLUMNS): visual_grid[row][column] = int(temp[(row * COLUMNS) + column]) first_square_opened = True create_empty_grids() generate_mines() generate_mine_numbers() update_visible_grid() print_visible_grid() while True: receive_user_commands() if AUTOSAVE_BOOL: auto_save() update_visible_grid() print_visible_grid() check_win()
734f66c70aba353e4248c2cfb7ff60a31907c260
marysiuniq/advent_of_code_2020
/25/puzzle_25.py
3,090
3.734375
4
# -*- coding: utf-8 -*- """ Created on Fri Dec 25 07:40:56 2020 @author: Piotr.Idzik and Maria Paszkiewicz Puzzle 25 from https://adventofcode.com/2020/day/25 The handshake used by the card and the door involves an operation that transforms a subject number. To transform a subject number, start with the value 1. Then, a number of times called the loop size, perform the following steps: Set the value to itself multiplied by the subject number. Set the value to the remainder after dividing the value by 20201227. The card always uses a specific, secret loop size when it transforms a subject number. The door always uses a different, secret loop size. The cryptographic handshake works like this: - The card transforms the subject number of 7 according to the card's secret loop size. The result is called the card's public key. - The door transforms the subject number of 7 according to the door's secret loop size. The result is called the door's public key. - The card and door use the wireless RFID signal to transmit the two public keys (your puzzle input) to the other device. Now, the card has the door's public key, and the door has the card's public key. Because you can eavesdrop on the signal, you have both public keys, but neither device's loop size. - The card transforms the subject number of the door's public key according to the card's loop size. The result is the encryption key. - The door transforms the subject number of the card's public key according to the door's loop size. The result is the same encryption key as the card calculated. At this point, you can use either device's loop size with the other device's public key to calculate the encryption key. Transforming the subject number of 17807724 (the door's public key) with a loop size of 8 (the card's loop size) produces the encryption key, 14897079. (Transforming the subject number of 5764801 (the card's public key) with a loop size of 11 (the door's loop size) produces the same encryption key: 14897079.) What encryption key is the handshake trying to establish? """ def find_loop_num(in_value): cur_value = 1 cur_loop_num = 0 while cur_value != in_value: cur_value *= 7 cur_value %= 20201227 cur_loop_num += 1 return cur_loop_num def produce_key(in_loop_num, in_subject_num): cur_value = 1 for _ in range(in_loop_num): cur_value *= in_subject_num cur_value %= 20201227 return cur_value def solve_1(key_a, key_b): loop_a = find_loop_num(key_a) loop_b = find_loop_num(key_b) res_a = produce_key(loop_a, key_b) res_b = produce_key(loop_b, key_a) assert res_a == res_b return res_a def get_data_p(): return 10943862, 12721030 def get_data_m(): return 5099500, 7648211 assert find_loop_num(5764801) == 8 assert find_loop_num(17807724) == 11 assert produce_key(find_loop_num(5764801), 17807724) == 14897079 assert produce_key(find_loop_num(17807724), 5764801) == 14897079 assert solve_1(*get_data_m()) == 11288669 assert solve_1(*get_data_p()) == 5025281 print(solve_1(*get_data_m()))
c2096d7af295f1e23f48d463ddb1f77b0033338c
jobafash/InterviewPrep
/educative.io/patterns/fast_and_slow_pointers/challenges/challenge3.py
4,349
4.0625
4
''' Cycle in a Circular Array (hard)# We are given an array containing positive and negative numbers. Suppose the array contains a number ‘M’ at a particular index. Now, if ‘M’ is positive we will move forward ‘M’ indices and if ‘M’ is negative move backwards ‘M’ indices. You should assume that the array is circular which means two things: If, while moving forward, we reach the end of the array, we will jump to the first element to continue the movement. If, while moving backward, we reach the beginning of the array, we will jump to the last element to continue the movement. Write a method to determine if the array has a cycle. The cycle should have more than one element and should follow one direction which means the cycle should not contain both forward and backward movements. Example 1: Input: [1, 2, -1, 2, 2] Output: true Explanation: The array has a cycle among indices: 0 -> 1 -> 3 -> 0 Example 2: Input: [2, 2, -1, 2] Output: true Explanation: The array has a cycle among indices: 1 -> 3 -> 1 Example 3: Input: [2, 1, -1, -2] Output: false Explanation: The array does not have any cycle. ''' def circular_array_loop_exists(arr): for i in range(len(arr)): is_forward = arr[i] >= 0 # if we are moving forward or not slow, fast = i, i # if slow or fast becomes '-1' this means we can't find cycle for this number while True: # move one step for slow pointer slow = find_next_index(arr, is_forward, slow) # move one step for fast pointer fast = find_next_index(arr, is_forward, fast) if (fast != -1): # move another step for fast pointer fast = find_next_index(arr, is_forward, fast) if slow == -1 or fast == -1 or slow == fast: break if slow != -1 and slow == fast: return True return False def find_next_index(arr, is_forward, current_index): direction = arr[current_index] >= 0 if is_forward != direction: return -1 # change in direction, return -1 next_index = (current_index + arr[current_index]) % len(arr) # one element cycle, return -1 if next_index == current_index: next_index = -1 return next_index def main(): print(circular_array_loop_exists([1, 2, -1, 2, 2])) print(circular_array_loop_exists([2, 2, -1, 2])) print(circular_array_loop_exists([2, 1, -1, -2])) main() ''' This problem involves finding a cycle in the array and, as we know, the Fast & Slow pointer method is an efficient way to do that. We can start from each index of the array to find the cycle. If a number does not have a cycle we will move forward to the next element. There are a couple of additional things we need to take care of: As mentioned in the problem, the cycle should have more than one element. This means that when we move a pointer forward, if the pointer points to the same element after the move, we have a one-element cycle. Therefore, we can finish our cycle search for the current element. The other requirement mentioned in the problem is that the cycle should not contain both forward and backward movements. We will handle this by remembering the direction of each element while searching for the cycle. If the number is positive, the direction will be forward and if the number is negative, the direction will be backward. So whenever we move a pointer forward, if there is a change in the direction, we will finish our cycle search right there for the current element. Time Complexity# The above algorithm will have a time complexity of O(N2)O(N^2)O(N​2​​) where ‘N’ is the number of elements in the array. This complexity is due to the fact that we are iterating all elements of the array and trying to find a cycle for each element. Space Complexity# The algorithm runs in constant space O(1)O(1)O(1). An Alternate Approach# In our algorithm, we don’t keep a record of all the numbers that have been evaluated for cycles. We know that all such numbers will not produce a cycle for any other instance as well. If we can remember all the numbers that have been visited, our algorithm will improve to O(N)O(N)O(N) as, then, each number will be evaluated for cycles only once. We can keep track of this by creating a separate array, however, in this case, the space complexity of our algorithm will increase to O(N).O(N).O(N). '''
fb7b3dd91636e46f3c81031f36a4ce5a774d6278
SachaReus/basictrack_2021_1a
/how_to_think/chapter_4/exercise_4_9_2.py
557
4.09375
4
import turtle def draw_square(animal, size): for _ in range(4): animal.forward(size) animal.left(90) window = turtle.Screen() window.bgcolor("light-green") raphael = turtle.Turtle() raphael.shape("arrow") raphael.color("hot-pink") raphael.pensize(5) size = 20 for _ in range(5): draw_square(raphael, size) size += 20 raphael.penup() raphael.left(225) raphael.forward(14) # 10 * wortel 2 = +/- 14 (Pythagoras) óf 10 naar beneden en 10 naar links raphael.left(135) raphael.pendown() window.mainloop()
54e36d09efc8b0f9d7f52b7c862cf77ef9ee50f6
Joana-Almeida/Projeto-3-Per-odo-ADS--Sistema-Para-Estudo
/assunto.py
3,303
3.5
4
import sqlite3 from sqlite3.dbapi2 import Error from conexao import Conexao class Assunto: def cadastrar(self,tema,descricao_assunto): try: conn = Conexao() conexao = conn.conectar() cursor = conexao.cursor() sql = 'INSERT INTO Assunto (tema,descricao_assunto) VALUES (?,?)' cursor.execute(sql,(tema,descricao_assunto)) conexao.commit() cursor.close() conexao.close() return True except sqlite3.OperationalError as e: print("Erro no cadastro de assuntos: {}".format(e)) return False except sqlite3.IntegrityError as e: print("Erro de integridade: {}".format(e)) return False def consultar(self): conn = Conexao() conexao = conn.conectar() cursor = conexao.cursor() try: resultset = cursor.execute('SELECT id_assunto,tema,descricao_assunto FROM Assunto').fetchall() except Error as e: print(f"O erro '{e}' ocorreu.") cursor.close() conexao.close() return resultset def consultar_detalhes(self, id_assunto): conn = Conexao() conexao = conn.conectar() cursor = conexao.cursor() try: resultset = cursor.execute('SELECT * FROM assunto WHERE id = ?', (id_assunto,)).fetchone() except Error as e: print(f"O erro '{e}' ocorreu.") cursor.close() conexao.close() return resultset def consultar_ultimo_id(self): conn = Conexao() conexao = conn.conectar() cursor = conexao.cursor() try: resultset = cursor.execute('SELECT MAX(id) FROM assunto').fetchone() except Error as e: print(f"O erro '{e}' ocorreu.") cursor.close() conexao.close() return resultset[0] def atualizar(self,id_assunto,tema,descricao_assunto): try: conn = Conexao() conexao = conn.conectar() cursor = conexao.cursor() sql = 'UPDATE assunto SET id_assunto = ? WHERE tema = (?)' cursor.execute(sql,(tema, id_assunto, descricao_assunto)) conexao.commit() cursor.close() conexao.close() return True except sqlite3.OperationalError as e: print("Erro na atualização de assuntos: {}".format(e)) return False except sqlite3.IntegrityError as e: print("Erro de integridade: {}".format(e)) return False def excluir(self,id_assunto): try: conn = Conexao() conexao = conn.conectar() cursor = conexao.cursor() sql = 'DELETE FROM assunto WHERE id_assunto = (?)' cursor.execute(sql,[id_assunto]) conexao.commit() cursor.close() conexao.close() return True except sqlite3.OperationalError as e: print("Erro na exclusão de assuntos: {}".format(e)) return False except sqlite3.IntegrityError as e: print("Erro de inegridade: {}".format(e)) return False
5ba0a234c27651064be4801494681ac95b273af6
B3WD/python_advanced
/Lists as Stacks and Queues - Exercise/08. Crossroads.py
1,094
3.53125
4
from collections import deque green_light_time = int(input()) grace_time_period = int(input()) car_queue = deque() passed_cars = 0 crash = False while True: if crash: break command = input() if command == "END": print("Everyone is safe.") print(f"{passed_cars} total cars passed the crossroads.") break elif command == "green": current_time = green_light_time while len(car_queue) and current_time > 0: current_car = car_queue[0] if current_time > 0: if current_time + grace_time_period - len(current_car) >= 0: #car passes safely car_queue.popleft() passed_cars += 1 current_time -= len(current_car) else: print("A crash happened!") print(f"{current_car} was hit at {current_car[current_time + grace_time_period]}.") crash = True break else: #add the car car_queue.append(command)
48413345f8b8e723c4ed9f918944fbbc5114b374
EgalYue/Head_First_Design_Pattern
/template/barista.py
1,149
3.78125
4
# -*- coding: utf-8 -*- # @FileName: barista.py # @Author : Yue Hu # @E-mail : [email protected] class CaffeineBeverage(object): """ abstract class """ def __init__(self): return def prepareRecipe(self): self.boilWater() self.brew() self.pourInCup() self.addCondiments() def brew(self): # abstract return def addCondiments(self): # abstract return def boilWater(self): print "Boiling water" def pourInCup(self): print "Pouring into cup" class Coffee(CaffeineBeverage): def __init__(self): super(Coffee, self).__init__() return def brew(self): print "Dripping Coffee through filter" def addCondiments(self): print "Adding Sugar and Milk" class Tea(CaffeineBeverage): def __init__(self): super(Tea, self).__init__() return def brew(self): print "Steeping the tea" def addCondiments(self): print "Adding Lemon" tea = Tea() coffee=Coffee() print "\nMaking tea..." tea.prepareRecipe() print "\nMaking coffee..." coffee.prepareRecipe()
3c709e1bba7456ada1246a0bdc388ca076e83f9e
Choojj/acmicpc
/단계별/08. 문자열/09. 크로아티아 알파벳.py
1,873
3.546875
4
import sys word = sys.stdin.readline().rstrip() list_num = 0 word_num = 0 while (list_num < len(word)): if (word[list_num] == "c" and len(word[list_num:]) >= 2): if (word[list_num + 1] == "="): word_num += 1 list_num += 2 elif (word[list_num + 1] == "-"): word_num += 1 list_num += 2 else: word_num += 1 list_num += 1 elif (word[list_num] == "d" and len(word[list_num:]) >= 2): if (word[list_num + 1] == "-"): word_num += 1 list_num += 2 elif (word[list_num + 1] == "z" and len(word[list_num:]) >= 3): if (word[list_num + 2] == "="): word_num += 1 list_num += 3 else: word_num += 1 list_num += 1 else: word_num += 1 list_num += 1 elif (word[list_num] == "l" and len(word[list_num:]) >= 2): if (word[list_num + 1] == "j"): word_num += 1 list_num += 2 else: word_num += 1 list_num += 1 elif (word[list_num] == "n" and len(word[list_num:]) >= 2): if (word[list_num + 1] == "j"): word_num += 1 list_num += 2 else: word_num += 1 list_num += 1 elif (word[list_num] == "s" and len(word[list_num:]) >= 2): if (word[list_num + 1] == "="): word_num += 1 list_num += 2 else: word_num += 1 list_num += 1 elif (word[list_num] == "z" and len(word[list_num:]) >= 2): if (word[list_num + 1] == "="): word_num += 1 list_num += 2 else: word_num += 1 list_num += 1 else: word_num += 1 list_num += 1 print(word_num)
1a746e33fbf3488e44bbad999a0985ad0c8b6c0c
LKWBrando/CP1404
/practical2/wordGenerator.py
644
4.0625
4
import random def errorCheck(): for letter in word_format: if letter == 'c' or letter == 'v': return True else: return False VOWELS = "aeiou" CONSONANTS = "bcdfghjklmnpqrstvwxyz" word_format = str(input("Please enter c for consonants or v or vowels.").lower()) while not errorCheck(): print("Error!") word_format = str(input("Please enter c for consonants or v or vowels.").lower()) word = "" for kind in word_format: if kind == "c": word += random.choice(CONSONANTS) elif kind == 'v': word += random.choice(VOWELS) else: print("error") print(word)
c7cfcde5a854a832c58791b087ddebe8e48f3b6b
adamandrz/Python-basics
/fibbonaci.py
290
3.921875
4
number = int(input("Podaj liczbe dodatnią: ")) def fibb(n): if n <= 0: print("Podaj liczbe dodatnia!") elif n == 1: print(0) elif n == 2: print(1) else: print(fibb(n-1) + fibb(n-2)) return fibb(n-1) + fibb(n-2) print(fibb(number))
51cd7804bb6e35d096e9ef617113a315454b6d0a
hhoangnguyen/mit_6.00.1x_python
/midterm/problem_2.py
222
3.921875
4
def f(): for i in range(3): print(i) break print('me') # f() L = [1,2,3] d = {'a': 'b'} def f(x): return 3 for i in range(10, -1, -2): print(f) # print(int('abc')) s = 'aaaa' s[3] = 3
a7ca6fc6d2b5f18568edebee3e421fd24c10a7cb
wookim789/baekjoon_algo_note
/인프런/memo/sec1/reverse_prime.py
592
3.703125
4
# 뒤집은 소수 ertos = [] def reverse(x): x = list(str(x)) x.reverse() return int(''.join(x)) def isPrime(x): global ertos if ertos[x] == 1: print(x, end =' ') n = int(input()) arr = list(map(int, input().split())) reverse_arr = [] for i in arr: reverse_arr.append(reverse(i)) max_val = max(reverse_arr) ertos = [0] * (max_val + 1) for i in range(2, max_val + 1): if ertos[i] == 0: ertos[i] = 1 for j in range(i, max_val + 1, i): if ertos[j] == 0: ertos[j] = 2 for r in reverse_arr: isPrime(r)
f660417ee4130b8e9a2838c482c46c702699ab24
stevb/project_euler_stuv
/proj_euler34.py
334
3.828125
4
import numpy as np alist = [] number = 3 while True: value = 0 for i in range(0,len(str(number))): value += np.math.factorial(int(str(number)[i])) if value == number: alist.append(number) print alist print sum(alist) number += 1 #There are two numbers total; 145 and 40585 summing 40730
abd4b6d5c23dd6b7ae15fc31021ae2a7c4f98ef2
myfairladywenwen/cs5001
/week03/10_cards.py
526
4.125
4
suit = input('input a card suit:') value = input ('input a card value:') if suit == "diamond" or suit == "heart": color = "red" else: color = "black" if value == "king" or value == "queen" or value =="jack": isFaceCard = True else: isFaceCard = False if color== "red": if isFaceCard: print("you chose a red face card") else: print("you chose a red pip card") else: if isFaceCard: print("you chose a black face card") else: print("you chose a black pip card")
c94fe6d8fd076e96892363260dadaa09ee08e0cc
rajkumarvishnu/PyLessons
/ex40.py
423
4.3125
4
cities ={'CA':'San Franssisco', 'MI':'Detroit', 'FL':'jacksonville'} cities ['NY'] = 'new york' cities ['OR'] = 'Portland' def find_city(themap, state): if state in themap: return themap[state] else: return "Not found" cities['_find'] = find_city while True: print "state ?" state= raw_input(">") if not state: break city_found = cities ['_find'] (cities,state) print cities['_find'] print city_found
a0838d7e3cca9e29e9c5b7cec3aaab356dadd5b1
Regnier96/EjerciciosPython3_Erick
/Ejercicios/E1/Modulos/añoBisiesto.py
343
3.796875
4
def comprobarAño(): anio = input("Ingrese un año para saber si es bisiesto\n") try: anio = int(anio) if anio % 4 == 0 or (anio % 100 == 0 and anio % 400 == 0): return f"{anio} es bisiesto" else: return f"{anio} no es bisiesto" except ValueError: return "Valor no valido"
de325c08336d81e52e5a4c0a5d98b7d89aaa0612
sharatvarma/python
/Image.py
1,554
3.84375
4
''' Created on Sep 1, 2016 @author: murthyraju ''' class Pixel(object): def __init__(self, red, green, blue, alpha): self.red = red self.green = green self.blue = blue self.alpha = alpha def reddify(self, red_increment): self.red = self.red + red_increment def __str__(self): #return str(self.red) + "-" + str(self.green) + "-" + str(self.blue) + "-" + str(self.alpha) return "%s-%s-%s-%s" % (self.red, self.green, self.blue, self.alpha) # formatting operator class Row(object): def __init__(self, pixels): self.pixels = pixels def __str__(self): row_string = "" for pixel in self.pixels: #print(type(pixel)) row_string += " " + pixel.__str__() return row_string class Image(object): def __init__(self, rows): self.rows = rows def __str__(self): image_string = "" for row in self.rows: image_string = image_string + "\n" + row.__str__() return image_string pixel1_1 = Pixel(0, 0, 0, 0) pixel1_2 = Pixel(0, 0, 0, 0) pixel1_3 = Pixel(0, 0, 0, 0) pixel1_4 = Pixel(0, 0, 0, 0) pixel1_5 = Pixel(0, 0, 0, 0) pixel2_1 = Pixel(0, 0, 0, 0) pixel2_2 = Pixel(0, 0, 0, 0) pixel2_3 = Pixel(0, 0, 0, 0) pixel2_4 = Pixel(0, 0, 0, 0) pixel2_5 = Pixel(0, 0, 0, 0) row1 = Row([pixel1_1, pixel1_2, pixel1_3, pixel1_4, pixel1_5]) row2 = Row([pixel2_1, pixel2_2, pixel2_3, pixel2_4, pixel2_5]) image1 = Image([row1, row2]) image1.rows[0].pixels[0].reddify(100) print image1
416d28eb1290aba9b79f5a24a5ce4c5c7d00cd56
jhwang73/datathon-2020
/data_analysis/data_linker.py
2,309
3.734375
4
import pandas as pd import csv """ Need to be able to take census number and determine what zipcodes lie in it. """ def censusToZip(censusDF, censusNum, rows): zipNum = [] for idx in range(rows): if censusNum == censusDF['TRACT'][idx]: zipNum.append(censusDF['ZIP'][idx]) return zipNum """ Obtain the census num from a zipcode """ def zipToCensusNum(censusDF, zipNum, rows): censusNum = [] for idx in range(rows): if zipNum == censusDF['ZIP'][idx]: censusNum.append(censusDF['TRACT'][idx]) return censusNum """ Obtain gentrif percentage from a zipcode """ def zipToGentrif(censusDF, gentrificationDF, gentrificationCensus, census_rows, zipcodes): averageGentrif = {} for zipcode in zipcodes: gentrifLevels = [] #print(gentrifLevels) for censusNum in zipToCensusNum(censusDF, zipcode, census_rows): if censusNum in gentrificationCensus.tolist(): gentrifLevels.append(gentrificationDF.loc[censusNum]['Prob16_00v']) if gentrifLevels: averageGentrif[zipcode] = round(sum(gentrifLevels)/len(gentrifLevels), 2) return averageGentrif # Store/Analyze census data zipToCensus_file = '/Users/alexanderxiong/Documents/GitHub/datathon-2020/data/ZIP_TRACT_032016.xlsx' zipToCensus = pd.read_excel(zipToCensus_file) zipToCensus_shape = zipToCensus.shape # Number of rows zipToCensus_rows = zipToCensus_shape[0] # Store/Analyze gentrification data gentrificationCensusNum_file = '/Users/alexanderxiong/Documents/GitHub/datathon-2020/data/gentrifData.xlsx' gentrification = pd.read_excel(gentrificationCensusNum_file) # Different census numbers gentrificationCensusNum = gentrification['FIPS'] gentrification.set_index("FIPS", inplace=True) # Store/Analyze crime data crime_file = '/Users/alexanderxiong/Documents/GitHub/datathon-2020/data/NIBRSPublicView.Jan1-Dec31-FINAL.xlsx' crime = pd.read_excel(crime_file) # Different zip codes from crime data crimeZips = crime['ZIP Code'] new_crime_file = '/Users/alexanderxiong/Documents/GitHub/datathon-2020/data/ZipcodeToCrimeCount.csv' new_crime = pd.read_csv(new_crime_file) zipToGentrif_dict = zipToGentrif(zipToCensus, gentrification, gentrificationCensusNum, zipToCensus_rows, new_crime['ZIP']) with open('zipToGentrif.csv', 'w') as f: for key in zipToGentrif_dict.keys(): f.write("%s,%s\n"%(key, zipToGentrif_dict[key]))
90dd381e97ffe2f0dc899408a3c7e3fda47db992
WhiskeyKoz/self.pythonCorssNave
/script/551.py
665
4.09375
4
def is_valid_input(letter_guessed): """ collected leter and check if the letter proper :param letter_guessed: guess letter :type letter_guessed: str :return: if letter proper return true if letter not proper return false :rtype: bool """ # letter_guessed = input("Guess a letter: ") len_letter = len(letter_guessed) if int(len_letter) > 1: return False elif not (letter_guessed.isalpha()): return False else: return True print(is_valid_input('a')) print(is_valid_input('A')) print(is_valid_input('$')) print(is_valid_input("ab")) print(is_valid_input("app$"))
55bd2fd27cabcab671253b4e1d2cb4546c6b729e
ator89/Python
/main.py
134
3.84375
4
# -*- coding: utf-8 -*- a = 14; b = 15; def swap(a,b): temp = a a = b b = temp #swap(a,b) a,b = b,a print(a) print(b)
fbbcb8a9efc8970e1cea5ceaac9b9278b64b5553
whdesigns/Python3
/1-basics/2-input/mock-exam/bot.py
621
4.5625
5
print("Please enter your name: ") # The above code uses the string datatype to ask the the user what his/her name is. name = input() # "name" is assigned as a variable, because of the "=" sign. The variable is equal to input, meaning that whatever the user types in will be stored in this variable. In other words, name is equal to the value of input. I closed the input function with parentheses so the value will be taken and stored correctly. print("Hello", name) #This displays the message "Hello" in string, followed by the variable, which will be the name the user typed and that was stored inside it earlier.
b4ed39ff6e56a4468ca18a7219943b603c4000db
jsillman/astr-119-hw-1
/operators.py
843
4.34375
4
x = 9 #initialize x as 9 y = 3 #initialize y as 3 #arithmetic operators print(x+y) #addition print(x-y) #subtraction print(x*y) #multiplication print(x/y) #division print(x%y) #modulus print(x**y) #exponent x = 9.191823 print(x//y) #floor division #assignment operators x = 9 #set x equal to 9 x +=3 #increase x by 3 print(x) x = 9 x -=3 #decrease x by 3 print(x) x *=3 #multiply x by 3 print(x) x /=3 #divide x by 3 print(x) x **= 3 #raise x to 3rd power print(x) #comparison operators x = 9 y = 3 print(x==y) #True if x equals y, False otherwise print(x!=y) #False if x equals y, True otherwise print(x>y) #True if x is greater than y, False otherwise print(x<y) #True if x is less than y, False otherwise print(x>=y) #True if x is greater than or equal to y print(x<=y) #True if x is less than or equal to y
f93ac43306742255ecb74f7237925d5f0bbfae7f
ahmedElsayes/my_projects
/python_assignments/tkinter_GUI/simple_calculator.py
1,884
3.984375
4
from tkinter import * root = Tk() root.title('Basic calculator') # creat an entry. specify width and border width e = Entry(root, width=30, borderwidth=5) # the grid is to make the size of all calculator elements consistent with each other e.grid(row=0, column=0, columnspan=3, padx=10, pady=10) def button_press(num): # new_num = str(num) new_num = e.get() + str(num) e.delete(0, END) e.insert(0, new_num) def button_clear(): e.delete(0, END) # To create the calculator buttons text, width, length, command button_1 = Button(root, text='1', padx=40, pady=20, command=lambda: button_press(1)) button_2 = Button(root, text='2', padx=40, pady=20, command=lambda: button_press(2)) button_3 = Button(root, text='3', padx=40, pady=20, command=lambda: button_press(3)) button_4 = Button(root, text='4', padx=40, pady=20, command=lambda: button_press(4)) button_5 = Button(root, text='5', padx=40, pady=20, command=lambda: button_press(5)) button_6 = Button(root, text='6', padx=40, pady=20, command=lambda: button_press(6)) button_7 = Button(root, text='7', padx=40, pady=20, command=lambda: button_press(7)) button_8 = Button(root, text='8', padx=40, pady=20, command=lambda: button_press(8)) button_9 = Button(root, text='9', padx=40, pady=20, command=lambda: button_press(9)) button_0 = Button(root, text='0', padx=40, pady=20, command=lambda: button_press(0)) button_CLEAR = Button(root, text='clear', padx=80, pady=20, command=button_clear) # now organizing the buttons into grid button_1.grid(row=3, column=0) button_2.grid(row=3, column=1) button_3.grid(row=3, column=2) button_4.grid(row=2, column=0) button_5.grid(row=2, column=1) button_6.grid(row=2, column=2) button_7.grid(row=1, column=0) button_8.grid(row=1, column=1) button_9.grid(row=1, column=2) button_0.grid(row=4, column=0) button_CLEAR.grid(row=4, column=1, columnspan=2) root.mainloop()
aad7241d4492d9f069ce84806e349f58286d795f
lsx0304good/mpc_ml
/MPC_ML/SigmoidFunction.py
1,333
3.5
4
from Option import * import numpy as np #这个地方采用麦克劳林公式来逼近正常的sigmod函数 class SigmoidFunction: def __init__(self): #使用麦克劳林公式逼近 # ONE = SecureRational.secure(1) # W0 = SecureRational.secure(1/2) # W1 = SecureRational.secure(1 / 4) # W3 = SecureRational.secure(-1 / 48) # W5 = SecureRational.secure(1 / 480) # self.sigmoid = np.vectorize(lambda x: W0 + (x * W1) + (x ** 3 * W3) + (x ** 5 * W5)) #逼近sigmoid # self.sigmoid_deriv = np.vectorize(lambda x: (ONE - x) * x) #sigmoid导数 # #使用改进的relu函数 def f(x): cc = reveal(x) if(cc<-0.5): return SecureRational.secure(0) elif (cc>0.5): return SecureRational.secure(1) else: return x def f2(x): cc = reveal(x) if(-0.5<=cc<=0.5): return SecureRational.secure(1) else: return SecureRational.secure(0) self.sigmoid = np.vectorize(lambda x: f(x)) self.sigmoid_deriv = np.vectorize(lambda x: f2(x)) # sigmoid导数 def evaluate(self, x): return self.sigmoid(x) def derive(self, x): return self.sigmoid_deriv(x)
9cc1b563b3944d16b68287acd9b886f578b20d68
jcottongin/git
/calorie2.py
1,238
4.03125
4
calories = int(input("How Many Calories? ")) carbs = int(input("How Many Carbs? ")) fats = int(input("How Much Fat? ")) protein = int(input("How Much Protein? ")) def carbvalu(calories): carbval = calories/4 # type: int return carbval carbval = carbvalu(calories) #gram of carb is 4 calories def carb(carbvalue, carbs): carb3 = carbs/carbvalue return carb3 carb3 = carb(carbval, carbs) carb3 = carb3 * 100 carb3 = float("%.2f" % (carb3)) #use 2 decimal places print("Percent of Carbs :", carb3) ##gram of fat is 9 calories def fatvalu(calories): fatval = calories / 9 return fatval fatval = fatvalu(calories) #define return fatval and call fatvalu function using calories def fatcal(fatval2,fats): fatval2 = fats/fatval #divide entered fats by calories per fat return fatval2 fatval2 = fatcal(fatval, fats) fatval2= fatval2 * 100 fatval2 = float("%.2f" % (fatval2)) print("Percent of Fats: ", fatval2) #gram of protein is 4 calories def pro(carbval, protein): proteinCal = protein/carbval proteinCal = proteinCal * 100 proteinCal = float("%.2f" %(proteinCal)) print("Percent of Protein:", proteinCal) return proteinCal pro(carbval, protein)
56b469cbbce8657b44a0da30568f620e2be3b6c0
bellc709191/01_Skill_Building
/02_input_math.py
404
4.1875
4
# get input # ask user for name name = input("What is your name? ") # ask user for two numbers num_1 = int(input("What is your favourite number? ")) num_2 = int(input("What is your second favourite number? ")) # add numbers together add = num_1 + num_2 # multiply numbers together # greet user and display math print ("Hello", name) print("{} + {} = {}".format(num_1, num_2, add) )
4a48324271d5279c4feb0e7b8a1152e2599100fc
rsedlr/Python
/month name.py
651
4.25
4
1 = "januarry" 2 = "Febuary" 3 = "March" 4 = "April" 5 = "May" 6 = "June" 7 = "July" 8 = "August" 9 = "September" 10 = "October" 11 = "November" 12 = "December" month = int(input("Enter a month (number) > ")) if number > 12 and number < 1: print("Between 1 and 12!") elif number == 1: print(1) elif number == 2: print(2) elif number == 3: print(3) elif number == 4: print(4) elif number == 5: print(5) elif number == 6: print(6) elif number == 7: print(7) elif number == 8: print(8) elif number == 9: print(9) elif number == 10: print(10) elif number == 11: print(11) elif number == 12: print(12)
4440603cd64b41a557caefb56044af743106855f
SantoshKumarSingh64/September-LeetCode-Monthly-Challenge
/Day3.py
1,555
3.984375
4
''' Question Description :- Repeated Substring Pattern Given a non-empty string check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. You may assume the given string consists of lowercase English letters only and its length will not exceed 10000. Example 1: Input: "abab" Output: True Explanation: It's the substring "ab" twice. Example 2: Input: "aba" Output: False Example 3: Input: "abcabcabcabc" Output: True Explanation: It's the substring "abc" four times. (And the substring "abcabc" twice.) ''' def repeatedSubstringPattern(s): substring_len = len(set(s)) if len(s)//2 < substring_len: return False def correct_substring(string,substr_length): for x in range(substr_length,len(string),substr_length): print(string[:substr_length],string[x:x+substr_length]) if string[:substr_length] != string[x:x+substr_length]: return False return True while True: if correct_substring(s,substring_len): print(substring_len) return True substring_len += 1 if len(s)//2 < substring_len: break return False print(repeatedSubstringPattern('ababab')) ''' Optimal Solution :- def repeatedSubstringPattern(s): ss = (s + s)[1:-1] print(ss) print(s) return ss.find(s) != -1 '''
6f9ccf62c17225f4fd0a80e21fec5b1fea6a8c5c
savitadevi/List
/Q.py
180
3.75
4
n=int(input("enter any number=")) i=1 sum=0 while i<n: if n%i==0: sum+=i i+=1 if sum==n: print("perfeect number",n) else: print("not perfect number",n)