blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
3cde074ae49a40fb3dae8cabbcb3c4d3a909191a
audiotech2017/Python_Code
/Pratise.py
703
3.921875
4
dictx = {'red':'1','blue':'2'} dict1 = {'Name' : 'John1', 'Age' : '22', 'Sex' : 'Male'} #dict = {'Name' : 'John2', 'Age' : '23', 'Sex' : 'Feale'} #dict = {'Name' : 'John3', 'Age' : '24', 'Sex' : 'Feale'} #TinyDict = {'Name' : 'John5', 'Age' : '24', 'Sex' : 'Feale'} while True: try: print (dict1.popitem()) except KeyError: print ('End of the Dictionary') break print ('print of dictx') for x in dictx: print(x, dictx[x]) print ('Add dict1') for x in dictx: try: dict1[x] = dictx[x] except KeyError: print ('key error') break print ('print of dict1') for x in dict1: print (x, dict1[x])
7febad1ce0b43fb85d203cd23507a8ace2fe10b0
jackschulz/Machine_Learning__Final_Project
/one_hot.py
3,283
3.578125
4
# -*- coding: utf-8 -*- """ Created on Sun May 19 13:31:46 2019 @author: lefty """ def one_hot_meat(meat_list, exclusion_list): file = open("ingredients_spaces_alt.csv", "r") l = file.readlines() file.close() recipes = [] for item in l: temp = item.strip('\n') temp = temp.split(',') recipes.append(temp) nb_recipes = len(recipes) nb_target_items = len(meat_list) #build ingredient dictionary one_hot_meat = [[0 for col in range(nb_target_items)] for row in range(nb_recipes)] d = {} for i in range(nb_target_items): d[meat_list[i]] = i print(d) for i in range(nb_recipes): temp = recipes[i] mini_n = len(temp) found = False found_meat = False for j in range(mini_n): for meat in meat_list: if meat in temp[j]: found = True break ignore = False if (found): for exclude in exclusion_list: if temp[j] == exclude: ignore = True found = False break if (found == True and ignore == False): # if no meat is found set Non val to 1 one_hot_meat[i][d[meat]] = 1 found_meat = True found = False if (found_meat == False): one_hot_meat[i][-1] = 1 #print(one_hot_meat[i]) #if sum(one_hot_meat[i]) > 2: #print("check this index:", i) file = open("one_hot_meat.csv", "w+") for i in range(nb_recipes): temp= str(one_hot_meat[i][0]) for j in range(1, nb_target_items): temp+= "," + str(one_hot_meat[i][j]) temp += '\n' file.write(temp) file.close() def sort_data(file): # run this check to see the distrubtion in the database of meat and no meat f = open(file, "r") l = f.readlines() f.close() one_hot = [] for item in l: temp = item.strip('\n') temp = temp.split(',') one_hot.append(temp) nb_meat = 0 nb_no_meat = 0 n = len(one_hot) for i in range(2500,3000): row = one_hot[i] if nb_meat < 10: print(row) if row[-1] == "1": nb_no_meat += 1 else: nb_meat += 1 print("There are", nb_no_meat, "recpies without meat") print("There are", nb_meat, "recpies with some meat") def main(): run_meat = False #run_veg = if (run_meat): meat_exclusion_list = ['beef consomme', 'beef stock', 'beef tomato', 'chicken soup', 'chicken stock', 'fish sauce', 'lamb stock', 'oyster mushroom', 'oyster sauce', 'sirlion', 'steak'] meat_list = ['beef', 'chicken', 'crab','eel', 'fish', 'lamb', 'oyster', 'pork', 'salmon', 'turkey', 'veal', "No Meat"] one_hot_meat(meat_list, meat_exclusion_list) #ohmf = one_hot_meat_file ohmf = "one_hot_meat.csv" sort_data(ohmf) main()
878c2e35b401cb7eddd93d775508230058a37084
Nitin-patil2209/Snake-Game
/snake.py
1,258
3.703125
4
from turtle import Turtle LIST_POS = [(0,0), (-20,0), (-40,0)] UP = 90 RIGHT = 0 LEFT = 180 DOWN = 270 class Snake: def __init__(self): self.turtles = [] self.Create() self.head = self.turtles[0] def Create(self): for i in LIST_POS: self.Createbody(i) def Createbody(self,position): tim = Turtle(shape="square") tim.color("white") tim.penup() tim.goto(position) self.turtles.append(tim) def Addnew(self): self.Createbody(self.turtles[-1].position()) def Move(self): for i in range(len(self.turtles) - 1, 0, -1): txcor = self.turtles[i - 1].xcor() tycor = self.turtles[i - 1].ycor() self.turtles[i].goto(txcor, tycor) self.head.forward(20) def Up(self): if self.head.heading() != DOWN: self.head.setheading(UP) def Down(self): if self.head.heading() != UP: self.head.setheading(DOWN) def Right(self): if self.head.heading() != LEFT: self.head.setheading(RIGHT) def Left(self): if self.head.heading() != RIGHT: self.head.setheading(LEFT)
78a7f72237ff8b26257391f793243a5bda6cc773
jchristy40/projecteulersolutions
/recurse.py
276
3.578125
4
def fact(prod,x): while x > 1: prod = prod*x return fact(prod,x-1) else: return prod def splitsum(x): x=str(x) n=1 sum=0 splitter=[x[i:i+n] for i in range(0,len(x), n)] for y in splitter: y=int(y) sum = sum + y return sum print(splitsum(fact(1,1000)))
02effe468f1ab388b75fc30556b69f996e57b0b4
charlievweiss/mastermind
/mastermind.py
2,056
3.59375
4
import numpy as np Colors = ['r', 'o', 'y', 'g', 'b', 'w'] # red, orange, yellow, green, blue, white def generate_code(length = 4): # Generates code to break code = [] for i in range(0, length): index = np.random.randint(0, len(Colors)) color = Colors[index] code.append(color) return code def compare_codes(code, guess): red = 0 white = 0 # Check possible colors for color in Colors: # get indeces of color in code and guess code_indeces = [i for i, value in enumerate(code) if value == color] guess_indeces = [i for i, value in enumerate(guess) if value == color] # If the color exists, check for whites and reds if len(code_indeces) > 0 and len(guess_indeces) > 0: white += min(len(code_indeces), len(guess_indeces)) # check for reds for index in guess_indeces: if index in code_indeces: white -= 1 red += 1 return [red, white] def test(): code = generate_code() guess = generate_code() print("Code: {}\nGuess: {}".format(code, guess)) result = compare_codes(code, guess) print(result) def play_game(length = 4): code = generate_code(length=length) print("Code generated. Make a guess!\n") # Testing # print("Code is: {}".format(code)) guess = '' quit_commands = ['quit', 'X'] turns = 1 while not code == guess: guess = input() if guess in quit_commands: break print("You guessed: "+guess) # Convert to array guess = [i for i in guess] # Win condition if code == guess: print("You win!\n") break # Compare the codes comparison = compare_codes(code, guess) print("Turn {}: {} Red, {} White".format(turns, comparison[0], comparison[1])) print("Guess again!\n") turns += 1 print("game ended") return if __name__ == '__main__': play_game() # test()
454fe9f3fdd991b682badef4526cb79813598761
HariPrasad-N/datastructure
/utils/Node.py
2,914
3.75
4
class Node: def __init__(self,data=None): """ attributes: -> data - data in the node """ self.data=data self.next=None self.prev=None def __str__(self): return str(self.data) def __repr__(self): return str(self.data) def __neg__(self): """ returns negation(a.data) for a Node Raises TypeError if type of data attribute does not support negation """ return self.data*-1 def __add__(self,rnode): """ returns a.data+b.data for a and b Nodes Raises TypeError if type of data attribute does not support addition """ return self.data+rnode.data def __sub__(self,rnode): """ returns a.data-b.data for a and b Nodes Raises TypeError if type of data attribute does not support substraction """ return self.data-rnode.data def __mul__(self,rnode): """ returns a.data*b.data for a and b Nodes Raises TypeError if type of data attribute does not support multiplication """ return self.data*rnode.data def __floordiv__(self,rnode): """ returns a.data//b.data for a and b Nodes Raises TypeError if type of data attribute does not support floor division """ return self.data//rnode.data def __truediv__(self,rnode): """ returns a.data/b.data for a and b Nodes Raises TypeError if type of data attribute does not support division """ return self.data/rnode.data def __lt__(self,rnode): """ returns a.data<b.data for a and b Nodes Raises TypeError if type of data attribute does not support logical operations """ return self.data < rnode.data def __le__(self,rnode): """ returns a.data<=b.data for a and b Nodes Raises TypeError if type of data attribute does not support logical operations """ return self.data <= rnode.data # def __eq__(self,rnode): # """ # returns a.data==b.data for a and b Nodes # Raises TypeError if type of data attribute does not support logical operations # """ # if rnode is not None: # return self.data == rnode.data # else: # return False # def __ne__(self,rnode): # """ # returns a.data!=b.data for a and b Nodes # Raises TypeError if type of data attribute does not support logical operations # """ # return self.data != rnode.data def __ge__(self,rnode): """ returns a.data>=b.data for a and b Nodes Raises TypeError if type of data attribute does not support logical operations """ return self.data >= rnode.data def __gt__(self,rnode): """ returns a.data>b.data for a and b Nodes Raises TypeError if type of data attribute does not support logical operations """ return self.data > rnode.data if __name__ == '__main__': node1 = Node(1) node2 = Node(2) # print(-node1) # print(node1+node2) # print(node1-node2) # print(node1*node2) # print(node1//node2) # print(node1/node2) # print(node1<node2) # print(node1<=node2) # print(node1==node2) # print(node1!=node2) # print(node1>=node2) # print(node1>node2)
584081d5c3b0a621194e72d1ab7429e8df7bef23
Matheus73/DB-Fixes
/tuple_generator.py
2,935
3.828125
4
import functions menu = """ Opções de atributos: +---------------+-------------------------------------------------------+ | opcoes | definicao | +---------------+-------------------------------------------------------+ | cpf | Gera um cpf aleatorio | | nome | Gera um nome de pessoa aleatorio | | cnpj | Gera um CNPJ aleatorio | | data | Gera uma data aleatoria de 1980 a 2015 | | estado-cidade | Gera dois atributos sendo eles um estado e uma cidade | | random(n) | Gera um inteiro com N algarismos | | placa | Gera uma placa de veiculo aleatoriamente | | chassi | Gera um chassi de um veiculo aleatoriamente | | cor | Gera uma cor | | telefone | Gera um numero de telefone com area e DDD | | cep | Gera um CEP aleatorio | +---------------+-------------------------------------------------------+ """ if __name__ == '__main__': table = input("Qual o nome da tabela? ") n = int(input("Quantas tuplas gostaria de adicionar na tabela? ")) print(menu) atributes = input("Quais atributos gostaria de add? (separados por espaco) ").split() s = f"INSERT INTO {table}( " for i in atributes: if i == atributes[-1]: s = s + i else: s = s + i + ', ' s += ') VALUES' print(s) lines = [] for i in range(n): tmp = [] for atr in atributes: if atr == 'cpf': tmp.append(functions.generate_cpf()) elif atr == 'nome': tmp.append(functions.generate_name()) elif atr == 'cnpj': tmp.append(functions.generate_cnpj()) elif atr == 'data': tmp.append(functions.generate_date()) elif atr == 'estado-cidade': b = functions.generate_city() tmp.append(b[0]) tmp.append(b[1]) elif 'random' in atr: num = int(atr[-3:-1]) tmp.append(functions.generate_random_value(num)) elif atr == 'placa': tmp.append(functions.generate_car_license()) elif atr == 'chassi': tmp.append(functions.generate_chassi()) elif atr == 'cor': tmp.append(functions.generate_color()) elif atr == 'telefone': tmp.append(functions.generate_phone()) elif atr == 'cep': tmp.append(functions.generate_cep()) lines.append(tmp) for i in lines: if i == lines[-1]: print(tuple(i),';') else: print(tuple(i),',')
2cc818f209631711cb243f06de2229de30c97f2d
lilblue2225/encryption-program
/fileEncrypt.py
3,273
4.5625
5
from cryptography.fernet import Fernet #this function takes a file of your choice and encrypts it's contents then #outputs it to a file, with the option of saving the key to a file as well. def encryptFile(): print ('Enter file name: ') fileName = input() #user enters name of file to be encrypted file = open(fileName, 'r') #file is opened in "read mode" contents = file.read() #contents of file is saved to variable for use key = Fernet.generate_key() #this generates an encryption key. DO NOT LOSE THIS AS IT'S #NEEDED TO DECRYPT THE FILE LATER f = Fernet(key) #create a fernet object with the key in it token = f.encrypt(contents.encode()) #encrypts the contents of the file and saves to a variable print ('\nEncrypted contents: \n' + token.decode()) #this is the output of the encrypted text print ('\nEncryption key (keep this somewhere safe!) \n' + key.decode()) #prints the key for user to writr down print('\nName of output file: ') file2Name = input() #name of the file that will have encrypted data saved to it file2 = open(file2Name, 'w') #opens the output file in "write mode" file2.write(token.decode()) #writes encrypted data to the file print('\nOutput encryption key to .txt file (y/n)') keyToText = input() if keyToText == 'y': #key gets saved to a text file "key.txt" keyFile = open('key.txt', 'w') #open the key file in "write mode" keyFile.write(key.decode()) #writes the key to the file keyFile.close() #always close your files when done! file2.close() file.close() main() #return to main function #this unction take a file of users choice along with a key and decrypts said #file with the key, then outputs it in the console def decryptFile(): #enter the key to be used to decrypt the file print('Enter key: ') key = input() byteKey = key.encode() #typecasting. encryption keys need to be bytes to be used, user enters #it as a bunch of chars f = Fernet(byteKey) #create the fernet object with the key in byte form print('Enter file name:') fileName = input() #user chooses a file to decrypt #file is opened in "read mode" and it's contents are saved to variable file = open(fileName, 'r') contents = file.read() decryptedContents = f.decrypt(contents.encode()) #decrypts the contents and saves it in variable print('\n File contents: \n' + decryptedContents.decode()+ '\n') #outputs the decrypted contents file.close() #always close these things!!! main() #the main function of the code. kicks things off def main(): print('Do you want to encrypt or decrypt a file?') option = input() #triggers the encrypt, decrypt or exit commands if option == 'encrypt': encryptFile() #calls the encrypt function elif option == 'decrypt': decryptFile() #calls the decrypt function elif option == 'exit': exit() #exits the program #exception handling else: print("Incorrect input! Choose from encrypt, decrypt or exit.") main() main()
f257a1bec6d73043ec66085e41d6b1f811fcee58
Sujay2611/Coding
/circuit20april2.py
245
3.546875
4
def josephus(n): p = 1 while p <= n: p *= 2 # Return 2n - 2^(1 + floor(Logn)) + 1 return (2 * n) - p + 1 t=int(input()) for _ in range(t): n,k=[int(x) for x in input().split()] print((josephus(n)+2*k)%n)
78a15f0f29117be6423d7cb040f1a70a0524f019
attia7/AttiaGit
/coretabs ATM py/withdraw.py
1,400
3.546875
4
balance = 700 papers=[100, 50, 10, 5,4,3,2,1] def withdraw(balance, request): if balance < request : print('Sorry, you are try withdraw: {0}, but Your balance just : {1}'.format(request, balance)) else: print ('your balance >>', balance) orgnal_request = request while request > 0: for i in papers: while request >= i: print('give', i) request-=i balance -= orgnal_request return balance def withdraw1(balance, request): give = 0 if balance < request : print('Sorry, you are try withdraw: {0}, but Your balance just : {1}'.format(request, balance)) else: print ('your balance >>', balance) balance -= request while request > 0: if request >= 100: give = 100 elif request >= 50: give = 50 elif request >= 10: give = 10 elif request >= 5: give = 5 else : give = request print('give',give) request -= give return balance balance = withdraw(balance, 777) balance = withdraw(balance, 276) balance = withdraw1(balance, 276) balance = withdraw(balance, 34) balance = withdraw1(balance, 5) balance = withdraw1(balance, 500)
2a5e9c7be1fd772b693b90ea4cb50c4df5ad8bd5
naistangz/codewars_challenges
/8kyu/helloNameWorld.py
189
3.9375
4
def hello(name=None): if name == "" or name is None: return "Hello, World!" else: return f"Hello, {name.lower().capitalize()}!" print(hello("ALIce")) print(hello())
cb6c4b8004fdd8e69756c743e148878513d44678
jinkerry/PyStudy
/pythonclub/equality.py
456
3.734375
4
#encoding=utf-8 __author__ = 'jinfeng' import re def equality(): f = file('equality.txt', 'r') text = '' for line in f: text += line #找出两边都是三个连续大写字母的小写字母 #One small letter, surrounded by EXACTLY three big bodyguards on each of its sides pattern = '[a-z][A-Z]{3}([a-z])[A-Z]{3}[a-z]' all = re.findall(pattern, text) print ''.join(all) if __name__ == '__main__': equality()
5d0a13c2d6c528273a23cbcf01b42d04d5f19c79
rupindermonga/word2SubWords
/final_word2sub.py
3,380
3.625
4
import wordninja, os, re from math import log import math import json from heapq import nsmallest import pandas as pd with open("wordninja_words_final.txt") as f: words = f.read().split() def smallest(numbers): min_list = [] for eachTuple in numbers: min_list.append(eachTuple[0]) small_numbers = nsmallest(3, min_list) try: second_min = small_numbers[1] except: second_min = small_numbers[0] try: third_min = small_numbers[2] except: try: third_min = small_numbers[1] except: third_min = small_numbers[0] position1 = min_list.index(second_min) position2 = min_list.index(third_min) return numbers[position1], numbers[position2] # Build a cost dictionary, assuming Zipf's law and cost = -math.log(probability). # words = open("words-by-frequency.txt").read().split() wordcost = dict((k, log((i+1)*log(len(words)))) for i,k in enumerate(words)) maxword = max(len(x) for x in words) def infer_spaces(s): """Uses dynamic programming to infer the location of spaces in a string without spaces.""" # Find the best match for the i first characters, assuming cost has # been built for the i-1 first characters. # Returns a pair (match_cost, match_length). def best_match(i): candidates0 = enumerate(reversed(cost0[max(0, i-maxword):i])) candidates1 = enumerate(reversed(cost1[max(0, i-maxword):i])) candidates2 = enumerate(reversed(cost2[max(0, i-maxword):i])) final0 = min((c0 + wordcost.get(s[i-k0-1:i], 9e999), k0+1) for k0,c0 in candidates0) numbered1 = [] for k1, c1 in candidates1: numbered1.append((c1 + wordcost.get(s[i-k1-1:i],9e999), k1+1)) count1 = sum(1 if x[0] < 9e999 else 0 for x in numbered1) if count1 == 1: final1 = min(numbered1) else: final1 = smallest(numbered1)[0] numbered2 = [] for k2, c2 in candidates2: numbered2.append((c2 + wordcost.get(s[i-k2-1:i],9e999), k2+1)) count2 = sum(1 if x[0] < 9e999 else 0 for x in numbered2) if count2 > 2: final2 = smallest(numbered2)[1] elif count2 == 2: final2 = smallest(numbered2)[0] else: final2 = min(numbered2) return final0, final1, final2 # Build the cost array. cost0 = [0] cost1 = [0] cost2 = [0] for i in range(1,len(s)+1): c0,k0 = best_match(i)[0] c1,k1 = best_match(i)[1] c2, k2 = best_match(i)[2] cost0.append(c0) cost1.append(c1) cost2.append(c2) # Backtrack to recover the minimal-cost string. out0 = [] i = len(s) while i>0: c0,k0 = best_match(i)[0] assert c0 == cost0[i] out0.append(s[i-k0:i]) i -= k0 out1 = [] i = len(s) while i>0: c1,k1 = best_match(i)[1] assert c1 == cost1[i] out1.append(s[i-k1:i]) i -= k1 out2 = [] i = len(s) while i>0: c2,k2 = best_match(i)[2] assert c2 == cost2[i] out2.append(s[i-k2:i]) i -= k2 return s, " ".join(reversed(out0)), " ".join(reversed(out1)), " ".join(reversed(out2)) # s ="photostick" s = "aftereffect" print(infer_spaces(s))
abf632954ff9e8dc4f475c11c313c191e6321b3f
bhumika0311/Bootcamp-1
/Assessment05/pangram.py
670
3.9375
4
alphabets = [' ', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] frequency = [0, 0, 0, 0, 0, 0, 0, 0, 0 ,0 ,0, 0, 0, 0, 0, 0 ,0 , 0 , 0 , 0 ,0 , 0, 0, 0, 0 ,0, 0] def isPangram(Sentence): Sentence = Sentence.upper() for x in Sentence: i = 0 while i < 27: if alphabets[i] == x: frequency[i] += 1 i += 1 print(frequency) for x in frequency: if x == 0: return False return True print(isPangram("The quick brown x jumps over the lazy dog"))
81eb15e38d305ea16483abd3a67293d07b40561e
Sametcelikk/Edabit-Solutions-Python
/Easy/20-) Shuffle the Name.py
412
4.125
4
""" Create a function that takes a string (will be a person's first and last name) and returns a string with the first and last name swapped. Examples name_shuffle("Donald Trump") ➞ "Trump Donald" name_shuffle("Rosie O'Donnell") ➞ "O'Donnell Rosie" name_shuffle("Seymour Butts") ➞ "Butts Seymour" """ def name_shuffle(txt): list1 = txt.split() return list1[-1] + " " + list1[0] print(name_shuffle("Donald Trump")) print(name_shuffle("Rosie O'Donnell"))
bd8b77b3f281c7078af941d856c011490f28b666
suprit08/PythonAssignments
/Tuples/TupleExample4.py
524
4.09375
4
#TupleExample4.py -------- tuple1 = (1,2,3) print("Tuple1 = ", tuple1) # For Repetition tuple2 = () tuple2 = tuple1*2 print("tuple1*2 = ",tuple2) # For Concatenation use '+' tuple3 = () tuple3 = tuple1+tuple2 print("tuple1+tuple2 = ",tuple3) # For Membership use 'in' print("is 2 in tuple1 =",(2 in tuple1)) print("is 4 in tuple1 = ",(4 in tuple1)) # for length user 'len()' print("length of tuple1 = ",len(tuple1)) print("length of tuple2 = ",len(tuple2)) print("length of tuple3 = ",len(tuple3))
2b7e18b89e29b29f0f68a6818cda4a320a77e5da
Deepak-AISD/first-project
/main.py
2,251
3.984375
4
# Python script to scrape an article given the url of the article and store the extracted text in a file # Url: https://medium.com/@subashgandyer/papa-what-is-a-neural-network-c5e5cc427c7 import os import requests import re import sys # Code here - Import BeautifulSoup library from bs4 import BeautifulSoup # Code ends here # function to get the html source text of the medium article def get_page(): global url # Code here - Ask the user to input "Enter url of a medium article: " and collect it in url url = input('Please enter url of a valid medium article: ') # Code ends here # handling possible error if not re.match(r'https?://medium.com/', url): print('Please enter a valid website, or make sure it is a medium article') sys.exit(1) # Code here - Call get method in requests object, pass url and collect it in res res = requests.get(url) # Code ends here res.raise_for_status() soup = BeautifulSoup(res.text, 'html.parser') return soup # function to remove all the html tags and replace some with specific strings def clean(text): rep = {"<br>": "\n", "<br/>": "\n", "<li>": "\n"} rep = dict((re.escape(k), v) for k, v in rep.items()) pattern = re.compile("|".join(rep.keys())) text = pattern.sub(lambda m: rep[re.escape(m.group(0))], text) text = re.sub('\<(.*?)\>', '', text) return text def collect_text(soup): text = f'url: {url}\n\n' para_text = soup.find_all('p') print(f"paragraphs text = \n {para_text}") for para in para_text: text += f"{para.text}\n\n" return text # function to save file in the current directory def save_file(text): if not os.path.exists('./scraped_articles'): os.mkdir('./scraped_articles') name = url.split("/")[-1] print(name) fname = f'scraped_articles/{name}.txt' # Code here - write a file using with (2 lines) with open(fname, "w") as f: f.write(text) # Code ends here print(f'File saved in directory {fname}') if __name__ == '__main__': text = collect_text(get_page()) save_file(text) # Instructions to Run this python code # Give url as https://medium.com/@subashgandyer/papa-what-is-a-neural-network-c5e5cc427c7
94ec7761a59d87b1421ab86e3b7e2dd9db1b8bdc
estineali/Python-Programming
/decipher_this.py
1,676
4.21875
4
''' You are given a secret message you need to decipher. Here are the things you need to know to decipher it: For each word: the second and the last letter is switched (e.g. Hello becomes Holle) the first letter is replaced by its character code (e.g. H becomes 72) Note: there are no special characters used, only letters and spaces Examples decipherThis('72olle 103doo 100ya'); // 'Hello good day' decipherThis('82yade 115te 103o'); // 'Ready set go' Source: Codewars. ''' def decipher_this(string): #Decipher a string of words. return " ".join([decipher_word(i) for i in string.split()]) def decipher_word(word): #Decipher a single word. numeric_segment = "" if word[0:3].isnumeric(): numeric_segment = chr(int(word[0:3])) word = word[3:] elif word[0:2].isnumeric(): numeric_segment = chr(int(word[0:2])) word = word[2:] if len(word) <= 1: return numeric_segment + word return numeric_segment + word[-1] + word[1:-1] + word[0] # Test.assert_equals(decipher_this("65 119esi 111dl 111lw 108dvei 105n 97n 111ka"), "A wise old owl lived in an oak") # Test.assert_equals(decipher_this("84eh 109ero 104e 115wa 116eh 108sse 104e 115eokp"), "The more he saw the less he spoke") # Test.assert_equals(decipher_this("84eh 108sse 104e 115eokp 116eh 109ero 104e 104dare"), "The less he spoke the more he heard") # Test.assert_equals(decipher_this("87yh 99na 119e 110to 97ll 98e 108eki 116tah 119esi 111dl 98dri"), "Why can we not all be like that wise old bird") # Test.assert_equals(decipher_this("84kanh 121uo 80roti 102ro 97ll 121ruo 104ple"), "Thank you Piotr for all your help")
b094a8a8b0c17fb5714adff16583c7adac8c2cd6
lauradp21/OOP
/Complejo.py
1,291
4.28125
4
class Complejo(): def __init__(self,x,y,u,v): self.x = x self.y = y self.u = u self.v = v print("El primer numero complejo tiene la forma:", x, "+", y,"i") print("El segundo numero complejo tiene la forma:", u, "+", v,"i") def sumar(self): parte1 = x + u parte2 = y + v return (print("El resultado de sumar estos numeros complejos es:", parte1, "+", parte2,"i")) def restar(self): parte1 = x - u parte2 = y - v return (print("El resultado de restar estos numeros complejos es:", parte1, "+", parte2,"i")) def multiplicar(self): parte_real = (x*u) - (y*v) parte_compleja = (x*v) + (y*u) return (print("El resultado de multiplicar estos numeros complejos es:", parte_real, "+", parte_imaginaria,"i")) def dividir(self): parte_real1 = (x*u) + (y*v) parte_compleja1 = -(x*v) + (y*u) parte_real2 = (u*u) + (v*v) parte_compleja2 = -(u*v) + (v*u) total = (parte_real1 + parte_compleja1)/(parte_real2 + parte_compleja2) return (print("El resultado de dividir estos numeros complejos es:", total)) c = Complejo(3,4,5,6) print(c.sumar()) print(c.restar()) print(c.multiplicar()) print(c.dividir())
a9e1798e4219bc9f532f3c3306ab3f4c793ba6fa
lukereed/PythonTraining
/Homework/HW02/review_session_20160203.py
1,884
3.609375
4
# first import libraries import math import sys import csv # imports the csv module # define script inputs #script, fname = sys.argv # define shear calcualtion function def shear_calc(MH1, WS1, MH2, WS2, DH): # first make sure all variables are floats not integers/strings MH1 = float(MH1) WS1 = float(WS1) MH2 = float(MH2) WS2 = float(WS2) DH = float(DH) # now we can determine our shear exponent and wind speed # ln = math.log and log_{10} = math.log10 shear_exp = math.log(WS1 / WS2) / math.log(MH1 / MH2) wind_speed = WS2 * (DH / MH2) ** shear_exp # return the wind speed value return wind_speed # now read in the .csv infile = open('wind_sites.csv','rb') # opens the csv file # save the results of the .csv to a variable reader = csv.reader(infile) # initialize variables that will change within the loop WS80 = -9999 WS80_temp = -9999 ID80 = -9999 # initialize for additional heights firstRow = True # read each row of code for row in reader: if firstRow: firstRow = False else: # read in and save each element siteID = row[0] # continue for the rest of the variables MH1 = row[1] # ... # call shear_calc function WS80_temp = shear_calc(MH1,WS1,MH2,WS2,80) WS100_temp = shear_calc(MH1,WS1,MH2,WS2,100) # call function for additional heights # ... # check if it is the fastest windspeed # if so, save it # if not, continue to next row if WS80_temp > WS80: WS80 = WS80_temp # save out the windspeed ID80 = siteID # save out the siteID # check additioanl heights # ... # now create the file that we will write to outfile = csv.writer(open('wind_summary.csv', 'wb')) outfile.writerow(['DesiredHeight','windiestSiteNumber','windSpeed']) outfile.writerow([80,ID80,WS80]) # keep doing this for other hub heights # save and close the infile # if you have time try to imbed the repeated processes within loops
f416e14e5bc3afcc5d2da27e31473929fa858ba5
MrHamdulay/csc3-capstone
/examples/data/Assignment_7/hwxada001/question1.py
274
3.75
4
a = False print("Enter strings (end with DONE):\n") list = [] while a == False: temp = input() if temp == 'DONE': break if list.count(temp) == 0: list.append(temp) print("Unique list:") for i in range(len(list)): print(list[i])
346eaff5603e6816efb8017eb9c5e16eb2609b2a
yossibaruch/learn_python
/learn_python_the_hard_way/ex25.py
956
4.375
4
def break_words(stuff): """This function will break up words for us.""" return stuff.split(' ') def sort_words(words): """Sorts the words""" return sorted(words) def print_first_word(words): """prints the first word after popping it off.""" print(words.pop(0)) def print_last_word(words): """prints the last word after popping it off.""" print(words.pop(-1)) def sort_sentence(sentence): """Takes in full sentence and returns the sorted words.""" return sort_words(break_words(sentence)) def print_first_and_last(sentence): """Prints the first and last words of the sentence.""" print_first_word(break_words(sentence)) print_last_word(break_words(sentence)) def print_first_and_last_sorted(sentence): """Prints the first and last words of the sentence.""" print_first_word(sort_sentence(sentence)) print_last_word(sort_sentence(sentence))
2fde7b705c657e11dcd5048ad921ecdea9d7399c
leandrotominay/pythonaprendizado
/aula0/funcoes.py
377
3.953125
4
#Funções são blocos de códigos que só serão executados quando forem chamados # OBS: def's devem ser declaradas no começo do código para o funcionamento dos outros que chamarem o mesmo! def soma(x, y): print(x ,"+" ,end=" ") print(y, end=" = ") return x + y s = soma(2, 3) print(s) def multiplicacao(x, y): return x*y m = multiplicacao(3, 4) print(m)
2e01ec6df6e5eb1588a65f10fa4773c9fe5b4739
Jbranson85/Python
/Caesar_cipher-Jonathan Branson.py
2,219
4.21875
4
''' Jonthan Branson-Caesar_cipher Adapted from a programs written by Dr. Melissa Stange(simplecipher.py, string2.py) In this program allows the user to enter in a message, and will then be asked how many shifts they would like. The message will then be encoded and returned to the user. At this point in time only letters can be used in the message, however the message can contain lower case and upper case letters. ''' ##This funtion takes the imput of the message and shirt number calculates and returns encoded message def caesar(plain_Text, num_Shift): ##Empty string for future encoded message plain_Text2 = "" ##Loops though the message(plain_Text), loop will run for every chr or space in the message for ch in plain_Text: ##Condition 1, by uses the ord function which will change the ch into its unicode number and add it to the shift amount if ch in "abcdefghijklmnopqrstuvwxyz": num_1 = (ord(ch) + num_Shift) if num_1 > ord("z"): num_1 -= 26 elif num_1 < ord("a"): num_1 += 26 plain_Text2 = plain_Text2 + chr(num_1) ##Condition 2, by uses the ord function which will change the ch into its unicode number and add it to the shift amount elif ch in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": num_1 = (ord(ch) + num_Shift) if num_1 > ord("Z"): num_1 -= 26 elif num_1 < ord("A"): num_1 += 26 plain_Text2 = plain_Text2 + chr(num_1) ##Condition 3, used for anything that does not meet the requirements for Condition 1 and Condition 2 else: plain_Text2 = plain_Text2 + ch ##Returns encoded message return plain_Text2 ##Main function def main(): ##Inputs plain_Text = input("What is you plaintext?") num_Shift = int(input("What shift do you want to use?")) ##Call function caesar using the message and shift amount and returning encoded message plain_Text2 = caesar(plain_Text,num_Shift) ##Print encoded message print("Your ciphertext is: ", plain_Text2) main()
016f8af9d6a42298c76e7249a111952e8673ab4d
romu42/aoc2019
/day4/get_password.py
1,393
3.703125
4
from collections import deque def get_password_count(input: str) -> int: count = 0 start, stop = input.split('-') print(start, stop) for password in range(int(start), int(stop)): if check_increase(str(password)) and check_adjacent(str(password)): count += 1 return count def get_password_count_limited(input: str) -> int: count = 0 start, stop = input.split('-') print(start, stop) for password in range(int(start), int(stop)): if check_increase(str(password)) and check_adjacent_limited(str(password)): count += 1 return count def check_length(password: str) -> bool: if len(str(password)) == 6: return True else: return False def check_adjacent(password: str) -> bool: for i in range(len(password)-1): if password[i] == password[i + 1] and password[i + 1]: return True return False def check_adjacent_limited(password: str) -> bool: d = deque(password) for item in set(password): if d.count(item) == 2: return True return False def check_increase(password: str) -> bool: if ''.join(sorted(password)) == password: return True else: return False if __name__ == '__main__': print(get_password_count('172851-675869')) print(get_password_count_limited('172851-675869'))
8285d8e8d1af18b1225db7dbb79c1226eddf2ab6
sbhackerspace/sbhx-projecteuler
/001/euler001.py
185
3.796875
4
#!/usr/bin/python # 2009.04.02 (terrible version) # 2010.??.?? (one-liner) print sum([x for x in range(1000) if x%3 == 0 or x%5 == 0]) #print sum([x for x in range(1000) if x%5 == 0])
426676e1a04840023066776d5161c5f92e12fe11
niksite/PyTagCloud
/src/pytagcloud/lang/counter.py
592
3.671875
4
# -*- coding: utf-8 -*- import re from pytagcloud.lang.stopwords import get_stop_words from operator import itemgetter def get_tag_counts(text): """ Search tags in a given text. """ words = map(lambda x: x.lower(), re.findall(r'[\w-]+', text, re.UNICODE)) stop_words = get_stop_words() counted = {} for word in words: if len(word) > 1 and word not in stop_words: if word in counted: counted[word] += 1 else: counted[word] = 1 return sorted(counted.iteritems(), key=itemgetter(1), reverse=True)
fd5cdc0d0d88a2a2265e7495c6233a0fe42290d6
Lanlanshi/hello_coding
/month_1/hour_minute_second.py
190
3.828125
4
seconds=int(input('请输入秒数')) second=seconds%60 minutes=seconds//60 hour=minutes//60 minute=minutes%60 print('转化以后的结果是:',hour,'小时',minute,'分钟',second,'秒')
7dae0e66dd6c1ada222534ccd9393b86e9f989e7
dkurchigin/gb_algorythm
/lesson8/task1.py
1,151
3.546875
4
# 1) Определение количества различных подстрок с использованием хеш-функции. Пусть на вход функции дана строка. # Требуется вернуть количество различных подстрок в этой строке. # Примечание: в сумму не включаем пустую строку и строку целиком. # Пример работы функции: # # func("papa") # 6 # func("sova") # 9 import hashlib def subs_count(string_): subs_set = set() shift = len(string_) for i in range(len(string_)): for j in range(shift): if i < j: hash_ = hashlib.sha1(string_[i:j].encode('utf-8')).hexdigest() if hash_ not in subs_set: subs_set.add(hash_) # print(f'{string_[i:j]}: {hash_}') shift = len(string_) + 1 return len(subs_set) string_ = str(input('Введите строку: ')) print(f'Количество различных подстрок в этой строке: {subs_count(string_)}')
433823d76e8fb8ecfcc99ca47d9c1c1b55145903
liarazhang/aimooc_ori
/实例1读心术/guess.py
1,715
3.734375
4
import random import getopt import sys def human_guess(): # 从 0 - 1000 中,产生一个随机数 num = random.randint(0,1000) i = 0 while 1: # 异常处理 - 输入非int型数据的时候 try: # guess 接收 - 从键盘输入的数字的值 guess = int(input('请输入数字 0~1000:')) except ValueError: print('请输入正确的数字 0~1000') continue i += 1 # 如果 输入的猜测的数,比随机产生是随机数 num 大 if guess > num: # 提示 猜大了 print("猜大了:",guess) elif guess < num: print("猜小了:",guess) else: print("你猜对了!共猜了",i,'次') sys.exit(0) def computer_guess(): print('请在心里想一个0~1000范围内的数字') small = 0 big = 1000 guess = 500 i = 0 while 1: guess = int((big+small)/2) i += 1 print('是这个数吗:'+str(guess)+'(B:大了,S:小了,C:正确)') char = input() if char == 'B': big = guess elif char == 'S': small = guess elif char == 'C': print('共猜了{0}次,得到正确结果{1}'.format(i,guess)) sys.exit(0) else: print('请正确输入回答:(B:大了,S:小了,C:正确)') def main(): who_guess = input('请决定谁来猜数(C:电脑,H:玩家):') if who_guess in 'Hh': human_guess() elif who_guess in 'Cc': computer_guess() if __name__ == '__main__': try: main() except KeyboardInterrupt: print() sys.exit(1)
d758ddc25ae50d9d4dc69907d0595d296392f508
mariereed/minesweeper-flask-app
/minesweeper.py
4,908
4.03125
4
import random def create_true_false_matrix(height, width, mine_count): """ creates a {width}x{height} matrix with {mine_count} true randomly placed, the rest false """ # use a list comprehension to initialize a 2d array of "false" matrix = [[False for x in range(width)] for y in range(height)] while mine_count > 0: # generate a random height and width rand_height = random.randint(0, height-1) rand_width = random.randint(0, width-1 ) # verify not already a mine, place and decrease counter if matrix[rand_height][rand_width] is not True: matrix[rand_height][rand_width] = True mine_count -= 1 return matrix def is_valid_tile(matrix, x, y): """ validates that x and y are within grid """ if x >= 0 and x < len(matrix) and y >= 0 and y < len(matrix[0]): return True return False def change_if_valid(matrix, x, y): """ validates that x and y are within grid and not a bomb """ if is_valid_tile(matrix, x, y) and matrix[x][y] != '!': matrix[x][y] += 1 return True return False def reveal_if_valid(answer_matrix, current_board, x, y): """ checks that x,y is a valid tile, not a bomb, not yet selected and reveals the tile """ if is_valid_tile(current_board, x, y) and answer_matrix[x][y] != '!' and current_board[x][y] == '?': if answer_matrix[x][y] == 0: current_board[x][y] = ' ' reveal_neighbors(answer_matrix, current_board, x, y) else: current_board[x][y] = answer_matrix[x][y] return True return False def number_fill(matrix): """ generates bomb neighbor counters for each tile """ # fetch matrix of zeros new_matrix = create_new_zero_matrix(matrix) # increase counter for neighbors of bombs for i in range(len(matrix)): for j in range(len(matrix[0])): if matrix[i][j] is True: new_matrix[i][j] = '!' change_if_valid(new_matrix, i , j-1) change_if_valid(new_matrix, i , j+1) change_if_valid(new_matrix, i+1, j ) change_if_valid(new_matrix, i+1, j-1) change_if_valid(new_matrix, i+1, j+1) change_if_valid(new_matrix, i-1, j ) change_if_valid(new_matrix, i-1, j-1) change_if_valid(new_matrix, i-1, j+1) return new_matrix def create_new_zero_matrix(matrix): """ creates a matrix of zeros """ return [[0 for x in y] for y in matrix] def create_new_blank_matrix(matrix): """ generates '?' matrix, this is the matrix visible to the user """ return [['?' for x in y] for y in matrix] def reveal_click(x, y, answer_matrix, current_board): """ processes the user input to reveal a tile """ if is_valid_tile(answer_matrix, x, y): if answer_matrix[x][y] == '!': return False, reveal_end_board(current_board, answer_matrix) elif answer_matrix[x][y] == 0: current_board[x][y] = ' ' reveal_neighbors(answer_matrix, current_board, x, y) else: current_board[x][y] = answer_matrix[x][y] return True, current_board else: return False, current_board def reveal_neighbors(answer_matrix, current_board, x, y): """ selects the neighbors of a selection for revealing """ reveal_if_valid(answer_matrix, current_board, x , y-1) reveal_if_valid(answer_matrix, current_board, x , y+1) reveal_if_valid(answer_matrix, current_board, x+1, y ) reveal_if_valid(answer_matrix, current_board, x+1, y-1) reveal_if_valid(answer_matrix, current_board, x+1, y+1) reveal_if_valid(answer_matrix, current_board, x-1, y ) reveal_if_valid(answer_matrix, current_board, x-1, y-1) reveal_if_valid(answer_matrix, current_board, x-1, y+1) def reveal_winning_board(matrix): """ provides the winning board with same formatting as the current_board """ with_blanks_board = [[' ' if x == 0 else x for x in y] for y in matrix] with_questions_board = [['?' if x == '!' else x for x in y] for y in with_blanks_board] return with_questions_board def reveal_end_board(current_board, answer_matrix): """ provides the current_board with all mines revealed """ copy_current_board = current_board for i in range(len(answer_matrix)): for j in range(len(answer_matrix[i])): if answer_matrix[i][j] == '!': copy_current_board[i][j] = '*' return copy_current_board def game_over(current_board, answer_matrix): """ determines whether game is won or not """ winning_board = reveal_winning_board(answer_matrix) for i in range(len(answer_matrix)): for j in range(len(answer_matrix[i])): if winning_board[i][j] != current_board[i][j]: return False return True
0a608b9d0e03c2c64daac7598fea4c44a9f2c323
PeterL64/UCDDataAnalytics
/3_Intro_To_Importing_Data_Python/3_Working_With_Relational_Databases_In_Python/10_Advanced_Querying_INNER_JOIN_Relational_Tables.py
1,028
4.03125
4
# SQL Relational Tables and INNER JOINS # - Assign to "rs" the results from the following query: select all the records, extracting the "Title" of # the record and "Name" of the artist of each record from the "Album" table and the "Artist" # table, respectively. To do so, "INNER JOIN" these two tables on the "ArtistID" column of both. # - In a call to pd.DataFrame(), apply the method fetchall() to rs in order to fetch all records in rs. # Store them in the DataFrame df. # - Set the DataFrame's column names to the corresponding names of the table columns. # Import Packages and Create Engine to query file import pandas as pd from sqlalchemy import create_engine engine = create_engine('sqlite:///Chinook.sqlite') # Perform query and save results to DataFrame: df with engine.connect() as con: rs = con.execute("SELECT Title, Name FROM Album INNER JOIN Artist on Album.ArtistID = Artist.ArtistID") df = pd.DataFrame(rs.fetchall()) df.columns = rs.keys() # Print head of DataFrame df print(df.head())
9719d893d01766d5d2795364334afcc86bf16b04
udemy-course/python3-oop-new
/ch7-object-oriented/property.py
542
3.9375
4
class People: def __init__(self, name, age): self.__name = name self.__age = age @property def name(self): # 格式的规范 return self.__name.upper() @property def age(self): return self.__age @name.setter def name(self, name): # 做一些合法性的检查 self.__name = name def set_age(self, age): self.__age = age someone = People(name='Jack', age=20) print(someone.name) print(someone.age) someone.name = 'Test' print(someone.name)
d44827e05d82c3b4c5621a53819edf7ad1a080c2
kar97k/programming-exercises
/single_char_appear.py
471
4.21875
4
#!/usr/bin/env python3 #Реализуйте алгоритм, определяющий, все ли символы в строке встречаются #только один раз a = '1231' char_repeated = False for i in a: if char_repeated: break char_count = 0 for j in a: if i == j: char_count += 1 if char_count == 2: char_repeated = True if char_repeated: print ("Equal chars in string!") else: print ("Unique chars in string!")
a9396eedae06e46544736eca114f715741ce618c
front440/PYTHON
/Primer_Trimestre/Programas_Alternativas/Ejercicio01_MayorQue.py
756
4.03125
4
# Programa: Ejercicio01_MayorQue.py # Proposito: Algoritmo que pida dos números e indique si el primero es # mayor que el segundo o no. # # Autor: Francisco Javier Campos Gutiérrez # # Fecha : 16/10/2019 # # # Variables a usar # * a <-- Almacenaremos el primer numero # * b <-- Almacenaremos el segundo numero # # Algoritmo: # a > b <-- A es mayor # a < b <-- B es mayor # a == b <-- Iguales # Leer datos a = float(input("Inserta el primer número: ")) b = float(input("Inserta el segundo número: ")) # Algoritmo if a > b: print("El primer número: ",a, ",es mayor") # Mostramos Cual es mayor if a < b: print("El segundo número: ",b, ",es mayor")# Mostramos Cual es menor elif a == b: print("Son iguales.") # En caso de que sean iguales, lo mostramos
07cb0e177fc6851379dd319658deea9224df809e
roastbeeef/100daysofcode
/days_1-3/datetime_exploration.py
767
4.4375
4
from datetime import datetime from datetime import date # returns todays date datetime.today() today = datetime.today() # datetime object- important because you cant mix these objects type(today) todaydate = date.today() todaydate # note that when using date, the object type is a date and note a datetime type(todaydate) todaydate.month todaydate.year todaydate.day # assigning the date to a variable christmas = date(2022, 12, 5) # can see that the type is automatically a timedelta christmas - todaydate # using the days attribute of the datetime class returns an integer (christmas - todaydate).days if christmas != today: print(f'its not christmas yet! there are still {(christmas - todaydate).days} days left') else: print('yay its christmas')
0b7548688867b452d6f5b5ca602c3500efc3d552
mpettersson/PythonReview
/questions/list_and_recursion/num_ways_to_decode.py
1,931
4.03125
4
""" NUM WAYS TO DECODE Given a string of digits that represents an encoded message (data), write a method to count the number of ways to decode the message. You can assume that the message (data) only contains the characters zero through nine [0-9]. The encoding function is: 'a' --> 1 'b' --> 2 . . . 'y' --> 25 'z' --> 26 Example: Input = "12" Output = 2 ("12" can represent "ab" OR "l") """ # Recursive Approach: O(2**n) time, O(1) space. def num_ways_to_decode_recursive(data): def _num_ways_to_decode_recursive(data, k): if k == 0: return 1 start = len(data) - k if data[start] == '0': return 0 result = _num_ways_to_decode_recursive(data, k - 1) if k >= 2 and int(data[start:start+2]) <= 26: result += _num_ways_to_decode_recursive(data, k - 2) return result return _num_ways_to_decode_recursive(data, len(data)) # Top Down Dynamic Programming Approach: O(n) time, O(n) space. def num_ways_to_decode_tddp(data): memo = [None] * (len(data) + 1) def _num_ways_to_decode_tddp(data, k, l): if k == 0: return 1 start = len(data) - k if data[start] == '0': return 0 if l[k]: return l[k] l[k] = _num_ways_to_decode_tddp(data, k - 1, l) if k >= 2 and int(data[start:start+2]) <= 26: l[k] += _num_ways_to_decode_tddp(data, k - 2, l) return l[k] return _num_ways_to_decode_tddp(data, len(data), memo) inputs = ["3", "", "12345", "111111", "27345", "101", "011"] # NOTE: "101" is valid, "011" is NOT valid. for i in inputs: print(f"num_ways_to_decode_recursive({i}):", num_ways_to_decode_recursive(i)) print() for i in inputs: print(f"num_ways_to_decode_tddp({i}):", num_ways_to_decode_tddp(i))
24493e3d9697b5084bfca680912392a79a15d215
PdxCodeGuild/class_platypus
/Code/Colton/Python/Lab_19.py
1,052
3.828125
4
deck_worth = {'A': 1, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '10': 10, 'J': 10, 'Q': 10, 'K': 10} f_card = input(f"What's your first card? ") f_card = deck_worth[f_card] s_card = input(f"What's your second card? ") s_card = deck_worth[s_card] while True: if f_card + s_card < 17: print(f"{f_card + s_card} Hit") t_card = input(f"What's your third card? ") t_card = deck_worth[t_card] if f_card + s_card + t_card < 17: print(f"{f_card + s_card + t_card} Hit") break elif f_card + s_card >= 17 and f_card + s_card < 21: print(f"{f_card + s_card + t_card} 'Stay'") elif f_card + s_card + t_card == 21: print("BLACKJACK!") break elif f_card + s_card + t_card > 21: print("BUSTED!") break elif f_card + s_card >= 17 and f_card + s_card < 21: print(f"{f_card + s_card} 'Stay'") break elif f_card + s_card == 21: print("BLACKJACK!") break
ef45d4501123d4ee21a7a9012c128bedde602660
lifeloverxg/principlescomputing-1
/Tic-Tac-Toe .py
3,463
3.65625
4
""" Monte Carlo Tic-Tac-Toe Player """ import random import poc_ttt_gui import poc_ttt_provided as provided #import user34_Uc9ea2tRiN_0 as test_ttt #import user35_PIk21NjpAa_0 as tests #import user35_UuNOhyrtdu_2 as tests # Constants for Monte Carlo simulator # Change as desired NTRIALS = 10 # Number of trials to run MCMATCH = 1.0 # Score for squares played by the machine player MCOTHER = 1.0 # Score for squares played by the other player # Add your functions here. def mc_trial(board,player): """ play the game,change the player """ while board.check_win() is None: gamelist = board.get_empty_squares() [row,col] = random.choice(gamelist) board.move(row,col,player) player = provided.switch_player(player) def mc_update_scores(scores,board,player): """ update scores rely on board """ current_board = board.clone() dim = board.get_dim() if board.check_win() == provided.DRAW or board.check_win() == None: return player1 = current_board.check_win() for row in range(dim): for col in range(dim): if current_board.square(row,col) == player1: scores[row][col] += MCMATCH elif current_board.square(row,col) == provided.EMPTY: scores[row][col] += 0 else: scores[row][col] -= MCOTHER def get_best_move(board, scores): """ get best move """ current = board.clone() gamelist = current.get_empty_squares() if len(gamelist) == 0: return dim = current.get_dim() best_score = float("-inf") tmp = [] scores_list = [] return_list = [] for [row,col] in gamelist: tmp.append(scores[row][col]) best_score = max(tmp) for row in range(dim): for col in range(dim): if scores[row][col] == best_score: scores_list.append((row,col)) for scr_index in scores_list: for bor_index in gamelist: if scr_index == bor_index: return_list.append(scr_index) return random.choice(return_list) def mc_move(board, player, trials): """ move """ dim = board.get_dim() scores = [[0 for dummy_row in range(dim)] for dummy_col in range(dim)] for dummy in range(trials): current = board.clone() mc_trial(current,player) mc_update_scores(scores,current,player) best_move = get_best_move(board, scores) return best_move #test_ttt.test_trial(mc_trial) #print #test_ttt.test_update_scores(mc_update_scores, MCMATCH, MCOTHER) # print #test_ttt.test_best_move(get_best_move) # Test game with the console or the GUI. # Uncomment whichever you prefer. # Both should be commented out when you submit for # testing to save time. # provided.play_game(mc_move, NTRIALS, False) # poc_ttt_gui.run_gui(3, provided.PLAYERX, mc_move, NTRIALS, False) #tests.test_mc_trial(mc_trial) # tests for mc_trial #tests.test_mc_update_scores(mc_update_scores, MCMATCH, MCOTHER) # tests for mc_update_scores #tests.test_get_best_move(get_best_move) # tests for get_best_move #tests.test_mc_move(mc_move, NTRIALS)
99297528050c5ce812cdd8a3fc49eca01fef5796
freakraj/python_projects
/string_indexing.py
361
3.75
4
# string indexing language="python" # position (index number) # starting position dekhne ke liye ,end se postion dekhne ke liye # p= 0 ,-6 # y =1 ,-5 # t =2 ,-4 # h =3 ,-3 # o =4 ,-2 # n= 5 ,-1 # string postion indexing see print(language[1]) print(language[5]) # ending posion se print(language[-1]) print(language[-4]) print(language[-6])
9eb03fe79f966d16dea5d68014f51e74e9420510
sheetal101/loop
/fac.py
152
3.609375
4
n=int(input("enter a number: ")) while n>0: j=1 fac=1 rem=n%10 while j<=rem: fac=fac*j j=j+1 n=n//10 print(fac)
a71f5c84eef908abff4a9d8eedf21501a0cfaad7
Dragon-God/PythonRepo
/collatzSequence.py
413
4.34375
4
#This is a function to simulate the collatz sequence. def collatz(number): return (number//2) if (number % 2 == 0) else ((3*number)+1) while True: try: print("Input the number: ", end="") num = int(input()) i = num break except ValueError: print("Error: Invalid input.\n Please input a whole number.") continue while True: pass i = collatz(i) print(i) if(i == 1): break
80cd7cc638351ee3b976a4f308d72e2314c165e8
takushi-m/atcoder-work
/work/arc068_c.py
218
3.71875
4
# -*- coding: utf-8 -*- x = int(input()) if x<=6: print(1) exit() if x<=11: print(2) exit() r = x%11 ret = x//11 if r==0: print(2*ret) elif r<=6: print(2*ret+1) elif r<=11: print(2*ret+2)
fc3cbb645609e6b555f121e01f4c82bf17f2a627
seung-lab/torchfields
/torchfields/utils.py
5,868
3.84375
4
from functools import wraps ############################################# # Decorators for enforcing return value types ############################################# def return_subclass_type(cls): """Class decorator for a subclass to encourage it to return its own subclass type whenever its inherited functions would otherwise return the superclass type. This works by attempting to convert any return values of the superclass type to the subclass type, and then defaulting back to the original return value on any errors during conversion. If running the subclass constructor has undesired side effects, the class can define a `_from_superclass()` function that casts to the subclass type more directly. This function should raise an exception if the type is not compatible. If `_from_superclass` is not defined, the class constructor is called by default. """ def decorator(f): @wraps(f) def f_decorated(*args, **kwargs): out = f(*args, **kwargs) try: if not isinstance(out, cls) and isinstance(out, cls.__bases__): return cls._from_superclass(out) except Exception: pass # Result cannot be returned as subclass type return out return f_decorated # fall back to constructor if _from_superclass not defined try: cls._from_superclass except AttributeError: cls._from_superclass = cls for name in dir(cls): attr = getattr(cls, name) if name not in dir(object) and callable(attr): try: # check if this attribute is flagged to keep its return type if attr._keep_type: continue except AttributeError: pass setattr(cls, name, decorator(attr)) return cls def dec_keep_type(keep=True): """Function decorator that adds a flag to tell `return_subclass_type()` to leave the function's return type as is. This is useful for functions that intentionally return a value of superclass type. If a boolean argument is passed to the decorator as @dec_keep_type(True) def func(): pass then that agument determines whether to enable the flag. If no argument is passed, the flag is enabled as if `True` were passed. @dec_keep_type def func(): pass """ def _dec_keep_type(keep_type): def _set_flag(f): f._keep_type = keep_type return f return _set_flag if isinstance(keep, bool): # boolean argument passed return _dec_keep_type(keep) else: # the argument is actually the function itself func = keep return _dec_keep_type(True)(func) ########################################################################### # Decorators to convert the inputs and outputs of DisplacementField methods ########################################################################### def permute_input(f): """Function decorator to permute the input dimensions from the DisplacementField convention `(N, 2, H, W)` to the standard PyTorch field convention `(N, H, W, 2)` before passing it into the function. """ @wraps(f) def f_new(self, *args, **kwargs): ndims = self.ndimension() perm = self.permute(*range(ndims-3), -2, -1, -3) return f(perm, *args, **kwargs) return f_new def permute_output(f): """Function decorator to permute the dimensions of the function output from the standard PyTorch field convention `(N, H, W, 2)` to the DisplacementField convention `(N, 2, H, W)` before returning it. """ @wraps(f) def f_new(self, *args, **kwargs): out = f(self, *args, **kwargs) ndims = out.ndimension() return out.permute(*range(ndims-3), -1, -3, -2) return f_new def ensure_dimensions(ndimensions=4, arg_indices=(0,), reverse=False): """Function decorator to ensure that the the input has the approprate number of dimensions If it has too few dimensions, it pads the input with dummy dimensions. Args: ndimensions (int): number of dimensions to pad to arg_indices (int or List[int]): the indices of inputs to pad Note: Currently, this only works on arguments passed by position. Those inputs must be a torch.Tensor or DisplacementField. reverse (bool): if `True`, it then also removes the added dummy dimensions from the output, down to the number of dimensions of arg[arg_indices[0]] """ if callable(ndimensions): # it was called directly on a function func = ndimensions ndimensions = 4 else: func = None if isinstance(arg_indices, int): arg_indices = (arg_indices,) assert(len(arg_indices) > 0) def decorator(f): @wraps(f) def f_decorated(*args, **kwargs): args = list(args) original_ndims = len(args[arg_indices[0]].shape) for i in arg_indices: if i >= len(args): continue while args[i].ndimension() < ndimensions: args[i] = args[i].unsqueeze(0) out = f(*args, **kwargs) while reverse and out.ndimension() > original_ndims: new_out = out.squeeze(0) if new_out.ndimension() == out.ndimension(): break # no progress made; nothing left to squeeze out = new_out return out return f_decorated if func is None: # parameters were passed to the decorator return decorator else: # the function itself was passed to the decorator return decorator(func)
25f3b5c78c99e743484d1fb84e2c306cee92b2ad
Nutsanee28/workshop2_str
/string_format.py
351
3.625
4
age = 20 txt = "myname is nutsanee, and i am {}" result = txt.format(age) # ส่งageไปแทนที่{}กี่อันก็ได้โดยเรียงลำดับ{} print("result : ", result) # formatเป็นการต่อสตริงประเภทหนึ่งโดยนำตัวฝน()มาต่อ
1dfad4f3963f05b4aca663757d96d36211cd5bef
RobertoFigueroa/Lab2-TP
/Lab2.py
1,467
3.765625
4
#Maria Jose Castro 181202 #Roberto Figueroa 18306 #Diana de Leon 18607 #Ejercicio 1 #paquetes necesarios import math import itertools def genElements(n): return list(range(n)) mensaje = "1.Orden-Sin reemplazo\n2.Orden-Con remplazo\n3.Sin orden-sin remplazo\n4.Sin orden-con remplazo\n5.Salir" opcion = 0 opcion= int(input("\nMenu \n"+ mensaje + "\n" + "Ingrese una opcion del menu: ")) while opcion != 5: n = int(input("\nIngrese el numero de elementos: ")) r = int(input("\nIngrese el numero de elementos de la muestra: ")) resultado = 0 perm = [] if opcion == 1: resultado = math.factorial(n) / math.factorial((n-r)) perm = itertools.permutations(genElements(n),r) elif opcion == 2: resultado = n ** r perm = itertools.product(genElements(n),genElements(n)) elif opcion == 3: resultado = math.factorial(n) / (math.factorial(r)* math.factorial((n-r))) perm = itertools.combinations(genElements(n),r) elif opcion == 4: resultado = math.factorial((r+n-1)) / (math.factorial(r)* math.factorial((n-1))) perm = itertools.combinations_with_replacement(genElements(n),r) else: print("Opcion no valida") print("La cantidad es : " + str(int(resultado))) print("Las combinaciones/permutaciones son: ") print(list(perm)) opcion= int(input("\nMenu \n"+ mensaje + "\n" + "Ingrese una opcion del menu: "))
ac61975148af4d21cd552bcd31750fc74beaf17c
gustavors22/shortest-path
/dijkstra/dijkstra.py
1,625
4.21875
4
class Dijkstra: def __init__(self, graph, origin, destiny) -> None: self.graph = graph self.origin = origin self.destiny = destiny def dijkstra_algorithm(self) -> dict and dict: """this function will apply the dijkstra algorithm to the graph to return the shortest path""" nodes = [] for node in self.graph: nodes.append(node) nodes += [n[0] for n in self.graph[node]] queue = set(nodes) nodes = list(queue) distances = dict() previous = dict() for node in nodes: distances[node] = float("inf") previous[node] = None distances[self.origin] = 0 while len(queue) > 0: next_node = min(queue, key=distances.get) queue.remove(next_node) if next_node == self.destiny: return distances[self.destiny], previous for vertex, distance in self.graph.get(next_node, ()): alt = int(distances[next_node]) + int(distance) if alt < distances[vertex]: distances[vertex] = alt previous[vertex] = next_node return distances, previous def generate_shortest_path(self) -> str and list: """this function will generate the path taken by the algorithm""" distance, prev = self.dijkstra_algorithm() node = self.destiny parents = [] while node != None: parents.append(node) node = prev[node] return distance, parents[::-1]
7ea3bc03da8c1eeeb8ca6fab9d3f53a5fb545f1c
kent-recuca/AtCoder
/AtCoder/ABC128/A-Apple-Pie.py
157
3.671875
4
# -*- coding: utf-8 -*- def main(): A,P = map(int,input().split()) A = A*3 pi = int((A+P)/2) print(pi) if __name__ == '__main__': main()
429ad8cad55b1f7ffc53f953811e03823baf1dba
Karsten1987/code_snippets
/python/list_comprehension.py
430
3.9375
4
# your code goes here def list_comprehension(): vec = [0, 10, 1, 10, 2, 10, 3, 10, 4, 10, 5, 10] vec_filter = [x for x in vec if x != 10] print vec_filter def reverse_vector(): vec = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] vec_reverse = [vec[len(vec)-i-1] for i in range(len(vec))] print vec_reverse if __name__ == "__main__": list_comprehension() reverse_vector()
c4132f53e1292b06d2653304f1c6850f6e08485e
HenryChen1/my-practice-code
/Craps Game.py
749
3.75
4
print('Craps Game') import random craps_1 = int(random.randint(1,6)) craps_2 = int(random.randint(1,6)) n = 1 sum = craps_1 + craps_2 # print('first round sum is %d' % (sum)) if sum == 7 or sum == 11: print('you win!') print('%d' % (sum)) n = 0 if sum == 2 | 3 | 11: print('you lose!') print('%d' % (sum)) i = 1 while n : craps_a = int(random.randint(1, 6)) craps_b = int(random.randint(1, 6)) # print('%d and %d ' % (craps_a , craps_b)) summary = craps_a + craps_b if summary == sum: print('you win!!') # print('%d in the %d times'%(summary,i)) break if summary == 7: print('you lose!!') # print('%d in the %d times'%(summary,i)) break i = i + 1
3ab11cdc3bdb94fed9a5bd5ab8090e3f02e76014
danglh1910elmk/K-Means
/kmeans-3_library.py
440
3.796875
4
import numpy as np import matplotlib.pyplot as plt from sklearn.cluster import KMeans clusters = [] points = np.array([[1,1],[1,1.3],[1.3,1],[4,4.8],[4.2,4.8],[4.1,4.5],[8,4.8],[8,5.2],[8.1,5],[8,5.4]]) # draw points x, y = zip(*points) plt.plot(x, y, 'ro') # use library kmeans = KMeans(n_clusters=3).fit(points) clusters = kmeans.cluster_centers_ print(clusters) # draw clusters x, y = zip(*clusters) plt.plot(x, y, 'b*') plt.show()
098840b21382da879ac168b9ac549ecbefecb329
blockchain99/pythonlecture
/test111list2.py
2,258
3.984375
4
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] print(nested_list[0][1]) # 2 print(nested_list[1][-1]) # 6 nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] print("++=====very important====++") print("-----option1----") for l in nested_list: for val in l: print(val) print("-----option2----") [[print(val) for val in l] for l in nested_list] print("=============flat list from nested list===========****") b_nested = [[2, 4, 6, 8], [1, 3, 5, 7, 9]] print([element for alist in b_nested for element in alist]) print("---- [n for n in range(1,4)] for val in range(1,4)---") board = [[num for num in range(1,4)] for val in range(1,4)] print(board) # [[1, 2, 3], [1, 2, 3], [1, 2, 3]] print([["X" if num % 2 != 0 else "O" for num in range(1,4)] for val in range(1,4)]) # [['X', 'O', 'X'], ['X', 'O', 'X'], ['X', 'O', 'X']] print("==== np.array only!!====") print("-----for a_element, b_element cond in zip(A,B,condition)---") import numpy as np # numpy where A = np.array([1,2,3,4]) B = np.array([100,200,300,400]) condition = np.array([True,True, False, False]) # slow way zip(A,B,condition) #[(1, 100, True), (2, 200, True), (3, 300, False), (4, 400, False)] answer1 = [a_elem if cond else b_elem for a_elem, b_elem, cond in zip(A,B,condition)] print(answer1) [1, 2, 300, 400] ## fast way. np.where(condition,A,B) print(np.where(condition, A,B)) print("---------nested list------------") # nested_list = [[value for value in range(0, 10)] for l in range(0,10)] nested_list= [[num for num in range(0,10)] for val in range(0,10)] print(nested_list) for l in nested_list: for v in l: print(v) print("---------intersection of two lists----") print([val2 for val2 in [1,2,3,4] if val2 in [3,4,5,6]]) print("======= list comprehension: even number from list=====") print([v for v in range(1, 10) if v % 2 ==0 ]) print("---option2 --") answer = [] for x in [1,2,3,4]: if x in [3,4,5,6]: answer.append(x) print(f"answer: {answer}") answer2 = [] print("]]]]]]]") print([ name[::-1].lower() for name in ["Elie", "Tim", "Matt"]]) for name in ["Elie", "Tim", "Matt"]: answer2.append(name[::-1].lower()) print("==============") answer = [char for char in "amazing" if char not in ["a", "e","i","o","u"]] print(answer)
6b5b944b9f31f14c7ada8141edfbb6a023792f8a
RunningShoes/python_lianxice
/RandomWalker.py
1,574
3.546875
4
#!/usr/local/bin/python3 #-*-coding:utf-8-*- import matplotlib.pyplot as plot import random class ranWakler(): ''' 随机漫步 ''' def __init__(self,num_points=5000): ''' 初始化函数 ''' self.num_points=num_points self.x_step=[0] self.y_step=[0] def stepDirectionstep(self): while(len(self.x_step)<self.num_points): direction_x=random.choice([-1,1]) step_x=random.choice([1,2,3,4,5]) direction_y=random.choice([-1,1]) step_y=random.choice([1,2,3,4,5]) next_x=self.x_step[-1]+direction_x*step_x next_y=self.y_step[-1]+direction_y*step_y if (next_x == 0 and next_y == 0): continue self.x_step.append(next_x) self.y_step.append(next_y) for i in range(0,10): rw=ranWakler(5000*i) rw.stepDirectionstep() plot.grid('-') plot.xlabel("Random Walk Number--y",fontsize=14) plot.ylabel("Random Walk Number--x",fontsize=14) plot.title("Random Walker",fontsize=20) plot.scatter(rw.x_step,rw.y_step,c=rw.y_step,edgecolors='none',s=2) # plot.show() plot.savefig("Randomwalker{}.png".format(i)) # rw=ranWakler(5000) # plot.figure() # rw.stepDirectionstep() # plot.grid('-') # plot.xlabel("Random Walk Number--y",fontsize=14) # plot.ylabel("Random Walk Number--x",fontsize=14) # plot.title("Random Walker",fontsize=20) # plot.scatter(rw.x_step,rw.y_step,c=rw.y_step,edgecolors='none',s=2) # # plot.show() # plot.savefig("Randomwalker{}.png")
23913bb4f73c234ab61aed87e58b0b1bc392f3d1
ndwei97/python_project
/Week 7 lab/Krenn_Cho_Fei_LabWk7c_Skrenn.py
7,619
4.28125
4
# Steven Krenn # Sangmin Cho # Eric Mingfei # Date created: 5/2/17 # Data modified: 5/2/17 # gets gallons of gasoline from the user, and converts it # to liters, barrels, co2, energy, and USD. # Has a main menu function that lets the user pick # if they want to convert 1 at a time, or a list of gas values at once. # The one value function converts the gasoline one value at a time. # the list values function converts the gasoline at a # list of values at one time. # function to convert to liters def convert_to_liters(gallon): return round(float(gallon) * 3.7854, 3) # function to convert to barrels def convert_to_barrels(gallon): return round(float(gallon) / 19.5, 3) # function to convert to CO2 def convert_to_CO2(gallon): return round(float(gallon)*20, 3) # function to convert to energy def convert_to_energy(gallon): energy = float(gallon) * 115000 / 75700 return round(energy, 2) # function to convert to USD def convert_to_USD(gallon): return round(float(gallon) * 4, 2) # a function that converts the gas from a list of values def list_values(): # list taking all the input values value_list = [] # input the number of values num_input = input("Please enter the number of values to input\n") num = 0 while int(num) < int(num_input): try: # enter each of the values value = input("Enter value " + str(num + 1)+"\n") # convert it to float float_value = float(value) # ignore the negative values # add the value to the list if float_value > 0: num += 1 value_list.append(value) else: print("please input a positive number!") except: print("Not a valid, please re-enter!") while True: try: # print out the menu print("1. Number of liters") print("2. Number of barrels of oil required to produce the gallons of gasoline specified") print("3. Number of pounds of CO2 produced") print("4. Equivalent energy amount of ethanol gallons") print("5. Price of the gasoline in US dollars") # ask the user to choose from the menu choice = int(input("Please choose the type of convert\n")) # call each of the methods on each of the choices if choice == 1: print("Results are: ") for value in value_list: result = convert_to_liters(value) print(round(result, 4), end=", ") print() elif choice == 2: print("Results are: ") for value in value_list: result = convert_to_barrels(value) print(round(result, 4)) print() elif choice == 3: print("Results are: ") for value in value_list: result = convert_to_CO2(value) print(round(result, 4)) print() elif choice == 4: print("Results are: ") for value in value_list: result = convert_to_energy(value) print(round(result, 4)) print() elif choice == 5: print("Results are: ") for value in value_list: result = convert_to_USD(value) print(round(result, 4)) print() else: print('Not a valid choice!') # check to see if the user wants to repeat the calculations repeat = str(input("Do you want to have another conversion? Type 'n' for no \n")) # if the user inputs n, then break the while loop if repeat == 'n': break except ValueError: print("Not a valid option, try again!") # function that gets user input and does the gas conversion on 1 value # at a time def one_value(): while True: # try to do the calculations on valid inputs try: # gets the gallons of gasoline from the user gallons = float(input("Input gallons of gas: ")) # check to see if the number of gallons is positive if gallons < 0: raise ValueError # prints the menu to the screen print('Chose an option below: \n') # gets the user's choice from the menu choice = int(input("1. Convert to liters\n2. Convert to barrels\n3. Convert to pounds of C02\n4. Convert to energy amount of ethanol gallons\n5. Convert USD\n")) # if the user's choice is 1, then convert to liters if choice == 1: print('converted to liters:') print(str(convert_to_liters(gallons)) + '\n') # if the user's choice is 2, then convert to barrels elif choice == 2: print('converted to barrels:') print(str(convert_to_barrels(gallons)) + '\n') # if the user's choice is 3, then convert to CO2 elif choice == 3: print('converted to CO2:') print(str(convert_to_CO2(gallons)) + '\n') # if the user's choice is 4, then convert to energy elif choice == 4: print('converted to energy:') print(str(convert_to_energy(gallons)) + '\n') # if the user's choice is 5, then convert to USD elif choice == 5: print('convert to USD:') print(str(convert_to_USD(gallons)) + '\n') # if the user did not choose a valid choice else: print("It is not a valid choice!") # check to see if the user wants to repeat the calculations repeat = str(input("Do you want to have another conversion? Type 'n' for no \n")) # if the user inputs n, then break the while loop if repeat == 'n': break # if the user does not input a valid input gallon number, # then run this exception except ValueError: print("Not a valid number, try again!") # main function def main(): print("Hello! \n") # main loop if user does not enter a valid option while True: # try to have the user enter valid input, if not loop again try: # main menu question print("Would you like to convert one value, or a list of values?") # get user's menu reponse menu = int(input('1 for 1 value, 2 for list of values \n')) # if it's 1 then convert 1 value at a time if menu == 1: # call the one value function one_value() # leave the main loop break # if it's 2 then convert a list of values at a time if menu == 2: # call the list values function list_values() # leave the main loop break # if they didn't choose 1 or 2. else: print('Not a valid option.') # if they entered an option that wasn't a number except ValueError: print('Not a valid number, try again!') # calls the main function main()
2f3db3b00605efb5a19ef37eb9d37da2e00b45a7
lusan/Seismic-activity-monitor--SAM-
/PlottingEarthquakeFinalRelease.py
1,954
3.609375
4
#After all the mods, its time for the final release version #This powerful code is capable parsing a giant text and converting it to an #informative map representing seismic activity all over the globe! import csv #Open the earthquake data file filename = 'C:\Python27\Py Pro\SAM\dataset.csv' #Create empty lists for the data we are interested in lats, lons = [], [] magnitudes = [] timestrings = [] #Read through the entire file, skip the first line, #and pull out just the lats and lons with open(filename) as f: #Create a csv reader object reader = csv.reader(f) #Ignore the header row next(reader) #Store the latitudes and longitudes in the appropriate lists. for row in reader: lats.append(float(row[1])) lons.append(float(row[2])) magnitudes.append(float(row[4])) timestrings.append(row[0]) #-----Build Map---- from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt import numpy as np def get_marker_color(magnitude): #Returns green for small earthquakes, yellow for moderate earthquakes #red for significant earthquakes if magnitude < 3.0: return ('go') elif magnitude < 5.0: return ('yo') else: return ('ro') map = Basemap(projection = 'robin', resolution = 'l', area_thresh = 1000.0, lat_0 = 0, lon_0 = -130) map.drawcoastlines() map.drawcountries() map.fillcontinents(color = 'gray') map.drawmapboundary() map.drawmeridians(np.arange(0, 360, 30)) map.drawparallels(np.arange(-90, 90, 30)) min_marker_size = 2.25 for lon, lat, mag in zip(lons, lats, magnitudes): #zip function takes a number of lists, and pulls the one item from each list. x, y = map(lons, lats) msize = mag * min_marker_size marker_string = get_marker_color(mag) map.plot(x,y ,marker_string, markersize = msize) title_string = "Earthquake of Magnitude 1.0 or greater \n" title_string += "%s through %s" % (timestrings[-1][:10], timestrings[0][:10]) plt.title(title_string) plt.show() #The result is a success
10095aa8bf05be7d94e373b8a0b897daeb50bb02
hasnain40247/PythonPong
/Score.py
634
3.59375
4
from turtle import Turtle class Score(Turtle): def __init__(self): super().__init__() self.lscore=0 self.rscore=0 self.hideturtle() self.color("white") self.penup() self.updateScore() def updateScore(self): self.clear() self.goto(-200,330) self.write(f"{self.lscore}",font=("Arial", 42, "bold")) self.goto(200, 330) self.write(f"{self.rscore}", font=("Arial", 42, "bold")) def updateLeft(self): self.lscore+=1 self.updateScore() def updateRight(self): self.rscore+=1 self.updateScore()
a989104d7790bbd62b71e893637bfd8e6a1bf0ab
MonicaCat/Cat-Food
/22.py
688
3.65625
4
import math a = 12+13 print(a) b = 78-66 print(b) c = 11*22 print(c) d = 52/2 print(d) e = 6**2 print(e) a = 5 b = 2 c = a*b print("面积为:", c) a = 12*5 print(a) b = "有没有人告诉你." print(b) a = input() b = input() if float(a) == 0.0: print("0") else: print("结果为:", float(b) / float(a)) a = float(input(1)) b = float(input(2)) c = float(input(1)) delta = b ** 2 - 4 * a * c if delta < 0: print("无实数根") elif delta == 0: x12 = b /(2 * a) print("有两个相等的实数根:", x12) else: x1 = (b - math.sqrt(delta)) / (2 * a) x2 = (b - math.sqrt(delta)) / (2 * a) print("有两个不相等的实数根为:", x1, x2)
4fcd361e3baf5265e5397953986c4f34e0521b99
agoncecelia/datasciencebootcamp
/modules/app.py
501
3.546875
4
from utils.math_utils import max_average from classes.student import Student agoni = Student("Agon", "Cecelia", "agonn.c@gmail.com", "127488", 7.89) bislimi = Student("Bislim", "Bislimi", "bislimi.b@gmail.com", "127388", 6.78) ahmeti = Student("Ahmet", "Ahmeti", "a.ahmeti@gmail.com", "127332", 7.12) lista = [] lista.append(agoni) lista.append(bislimi) lista.append(ahmeti) max_avg_student = max_average(lista) print("{} {} me mesataren: {}".format(max_avg_student.first_name, max_avg_student.last_name, max_avg_student.average))
7b4e229d0202c05f3640ae467003a2b023a82eac
k-schmidt/Coding_Problems
/code_rust/merge_two_sorted_linked_lists.py
989
4.21875
4
""" Merge Two Sorted Linked Lists """ def merge_sorted(head1, head2): # if both lists are empty then merged list is also empty # if one of the lists is empty then other is the merged list if head1 is None: return head2 elif head2 is None: return head1 merged_head = None if head1.data <= head2.data: merged_head = head1 head1 = head1.next else: merged_head = head2 head2 = head2.next merged_tail = merged_head while head1 is not None and head2 is not None: temp = None if head1.data <= head2.data: temp = head1 head1 = head1.next else: temp = head2 head2 = head2.next merged_tail.next = temp merged_tail = temp if head1 is not None: merged_tail.next = head1 merged_tail = head1 elif head2 is not None: merged_tail.next = head2 merged_tail = head2 return merged_head
b3afe1777807a1e590cd250eebf572fb750b4c74
Sitwon/Pentago
/pentago.py
8,357
3.609375
4
#!/usr/bin/python import sys DEBUG = 0 class Place: EMPTY = 0 WHITE = 1 BLACK = 2 def __init__(self): self.state = self.EMPTY def CheckPlace(self): return self.state def SetPlace(self, value): assert((value == self.EMPTY) or (value == self.WHITE) or (value == self.BLACK)) self.state = value def Print(self): sys.stdout.write("[") if self.state == self.EMPTY: sys.stdout.write(" ") elif self.state == self.WHITE: sys.stdout.write("W") else: sys.stdout.write("B") sys.stdout.write("] ") class Quad: CW = 0 CCW = 1 def __init__(self): self.places = [[Place(), Place(), Place()], [Place(), Place(), Place()], [Place(), Place(), Place()]] def Rotate(self, direction): assert((direction == self.CW) or (direction == self.CCW)) tempPlaces = Quad() pos = [0, 0] if direction == self.CW: row = 2 while row >= 0: col = 0 while col <= 2: tempPlaces.places[pos[0]][pos[1]].SetPlace(self.places[row][col].CheckPlace()) #print "tempPlaces[", pos[0], ",", pos[1], "] = places[", row, ",", col,"] = ", self.places[row][col].CheckPlace() col += 1 pos[0] += 1 row -= 1 pos[0] = 0 pos[1] += 1 else: row = 0 while row <= 2: col = 2 while col >= 0: tempPlaces.places[pos[0]][pos[1]].SetPlace(self.places[row][col].CheckPlace()) col -= 1 pos[0] += 1 row += 1 pos[0] = 0 pos[1] += 1 self.places = tempPlaces.places def PrintLine(self, line): assert ((line >= 0) and (line <= 2)) for p in self.places[line]: p.Print() def CheckPlace(self, row, col): assert (((row >= 0) and (row <= 2)) and ((col >= 0) and (col <= 2))) return self.places[row][col].CheckPlace() def SetPlace(self, row, col, value): assert (((row >= 0) and (row <= 2)) and ((col >= 0) and (col <= 2))) self.places[row][col].SetPlace(value) class Board: def __init__(self): self.quads = [[Quad(), Quad()], [Quad(), Quad()]] def Print(self): print "* 1 2 3 | 4 5 6" print "" row = 0 while row <= 1: line = 0 while line <= 2: L = (row * 3) + line + 1 L = str(L) sys.stdout.write(L + " ") self.quads[row][0].PrintLine(line) sys.stdout.write("| ") self.quads[row][1].PrintLine(line) sys.stdout.write("\n") if line != 6: print " |" line += 1 if row == 0: print " -----------+-----------" print " |" row += 1 def CheckPlace(self, row, col): assert (((row >= 0) and (row <= 5)) and ((col >= 0) and (col <= 5))) return self.quads[row / 3][col / 3].CheckPlace(row % 3, col % 3) def SetPlace(self, row, col, value): assert (((row >= 0) and (row <= 5)) and ((col >= 0) and (col <= 5))) self.quads[row / 3][col / 3].SetPlace(row % 3, col % 3, value) def SetPlace2(self, qrow, qcol, row, col, value): assert (((qrow >= 0) and (qrow <= 2)) and ((qcol >= 0) and (qcol <= 2))) self.quads[qrow][qcol].SetPlace(row, col, value) def Rotate(self, quadrant, direction): direction -= 1 assert ((quadrant >= 1) and (quadrant <= 4)) assert ((direction == Quad.CW) or (direction == Quad.CCW)) if quadrant == 1: self.quads[0][1].Rotate(direction) elif quadrant == 2: self.quads[0][0].Rotate(direction) elif quadrant == 3: self.quads[1][0].Rotate(direction) else: self.quads[1][1].Rotate(direction) def FindFive (self, row, col, direction, color, num): winner = 0 isWon = [] if (direction == 0): if DEBUG > 10: print "Beginning..." color = self.CheckPlace(0, 0) if DEBUG > 10: print "Color:", color num = 1 # search horiz if DEBUG > 10: print "Start Horiz" isWon += self.FindFive(0, 1, 1, color, num) if DEBUG > 10: print "End Horiz" # search vert if DEBUG > 10: print "Start Vert" isWon += self.FindFive(1, 0, 2, color, num) if DEBUG > 10: print "End Vert" else: if DEBUG > 10: print "Continuing..." if DEBUG > 7: print "Row:", row, "\tCol", col, "\tColor:", self.CheckPlace(row, col) if self.CheckPlace(row, col) == color: num += 1 if num == 5: winner = color else: color = self.CheckPlace(row, col) num = 1 if ((row == 0) or (col == 0)): # search horiz if col < 5: if DEBUG > 10: print "start horiz" if direction == 1: isWon += self.FindFive(row, col + 1, 1, color, num) else: isWon += self.FindFive(row, col + 1, 1, color, 1) if DEBUG > 10: print "end horiz" # search vert if row < 5: if DEBUG > 10: print "start vert" if direction == 2: isWon += self.FindFive(row + 1, col, 2, color, num) else: isWon += self.FindFive(row + 1, col, 2, color, 1) if DEBUG > 10: print "end vert" elif direction == 1: if col < 5: if DEBUG > 10: print "cont horiz" isWon += self.FindFive(row, col + 1, direction, color, num) if DEBUG > 10: print "stop horiz" else: pass if DEBUG > 10: print "end of horiz" else: if row < 5: if DEBUG > 10: print "cont vert" isWon += self.FindFive(row + 1, col, direction, color, num) if DEBUG > 10: print "stop vert" else: pass if DEBUG > 10: print "end of vert" if DEBUG > 5: print "Row:", row, "\tCol:", col, "\tNum:", num,"\tColor:", color if winner != 0: isWon.append(winner) return isWon def FindDiag(self, row, col, direction, color, num): isWon = [] winner = 0 if direction == 0: color = self.CheckPlace(0, 0) num = 1 # Search criss... isWon += self.FindDiag(0, 0, 1, color, num) # Search cross... isWon += self.FindDiag(0, 5, 2, color, num) else: if self.CheckPlace(row, col) == color: num += 1 if num == 5: winner = color else: color = self.CheckPlace(row, col) num = 1 if direction == 1: if (row < 5) and (col < 5): isWon += self.FindDiag(row + 1, col + 1, direction, color, num) else: if (row < 5) and (col > 0): isWon += self.FindDiag(row + 1, col - 1, direction, color, num) if (row == 0) and (col == 0): isWon += self.FindDiag(0, 1, direction, color, 0) isWon += self.FindDiag(1, 0, direction, color, 0) elif (row == 0) and (col == 5): isWon += self.FindDiag(0, 4, direction, color, 0) isWon += self.FindDiag(1, 5, direction, color, 0) if winner != 0: isWon.append(winner) return isWon def CheckForWinner(self): winners = [] winners += self.FindFive(0, 0, 0, 0, 0) winners += self.FindDiag(0, 0, 0, 0, 0) if len(winners) > 0: if len(winners) == 1: return "Won" else: return "Possible Tie" else: return "Not Won" testBoard = Board() def PlayTest(): gameBoard = Board() turn = 1 #gameBoard.Print() keepPlaying = True while (keepPlaying): gameWon = "" if turn % 2 == 1: player = "White [W]" else: player = "Black [B]" print "Turn #" + str(turn) + " Player: " + player turnDone = False while not turnDone: gameBoard.Print() playDone = False while not playDone: row = 0 col = 0 try: row = input("What row? (1-6): ") col = input("What column? (1-6): ") except: pass #if (row == 0) or (col == 0): # sys.exit() if (row != 0) and (col != 0): if not (((row < 1) or (row > 6)) or ((col < 1) or (col > 6))): if gameBoard.CheckPlace(row - 1, col - 1) == Place.EMPTY: if (turn % 2) == 1: gameBoard.SetPlace(row - 1, col - 1, Place.WHITE) else: gameBoard.SetPlace(row - 1, col - 1, Place.BLACK) playDone = True rotateDone = False gameBoard.Print() gameWon = gameBoard.CheckForWinner() if gameWon != "Not Won": print gameWon else: while not rotateDone: quad = 0 direction = 0 try: quad = input("Which quadrant? (1-4): ") direction = input("Which direction? (CW:1 CCW:2): ") except: pass if (quad != 0) and (direction != 0): if (((quad >= 1) and (quad <= 4)) and ((direction >= 1) and (direction <= 2))): gameBoard.Rotate(quad, direction) rotateDone = True gameBoard.Print() gameWon = gameBoard.CheckForWinner() if gameWon != "Not Won": print gameWon turnDone = True turn += 1 #answer = raw_input("Continue game? (Y/n): ") #if (answer == 'n') or (answer == 'N'): # keepPlaying = False if gameWon != "Not Won": keepPlaying = False if __name__=="__main__": PlayTest()
a2573aed665d4ec84c3a3a988bbfc2e97bbc1c92
iamrishap/PythonBits
/InterviewBits/arrays/first-missing-positive.py
827
3.78125
4
""" Given an unsorted integer array, find the first missing positive integer. Example: Given [1,2,0] return 3, [3,4,-1,1] return 2, [-8, -7, -6] returns 1 Your algorithm should run in O(n) time and use constant space. """ class Solution: # @param A : list of integers # @return an integer def firstMissingPositive(self, A): A = list(filter(lambda x: x > 0, A)) # print(A) A = [len(A) + 2] + A # Add the next number. This is for proper indexing (zero based). # print(A) for i, num in enumerate(A): num = abs(num) if num < len(A): A[num] = - abs(A[num]) # print(A) for i in range(1, len(A)): if A[i] > 0: return i return len(A) s = Solution() s.firstMissingPositive([3, 5, 2, 1])
aa91e89e186998f1497a9bb6ade9a11511523732
smohsensh/smart-xo
/xo/game.py
1,920
3.734375
4
import random from xo.calc import get_next_turn, get_best_move_score from xo.model import Board class Game: def __init__(self): self.board = Board() self.play_for = None self.starter = None def initialize(self): print('Playing a Game of X/O') print('-' * 50) print('Please note that you should tell me your moves by a number between 1-9') print('Consider the board is number pad of your phone and tell the number of key you want') print('-' * 50) op = input('Which symbol you want to play for? X or O? ') self.play_for = 2 if op.lower() == 'x' else 1 print('Flipping a coin to see who starts') self.starter = random.randint(1, 2) # self.starter = self.play_for if self.play_for == self.starter: print('Computer will start') else: print('You start First') def play(self): self.initialize() turn = self.starter while not (self.board.get_winner_if_any() or self.board.is_full()): m = self.get_next_move(turn) self.board.b[m] = turn print(self.board) turn = get_next_turn(turn) if self.board.get_winner_if_any() == self.play_for: print('Hooray! I win') elif self.board.get_winner_if_any() != 0: print('Oh you got me') else: print("That's a tie") def get_next_move(self, turn): if turn == self.play_for: print('Thinking...') m, _ = get_best_move_score(self.board, turn, self.play_for) return m else: m = int(input('Please Enter Your Move ')) m = self.convert_user_move(m) assert self.board.b[m] == 0, 'The cell is already full' return m @staticmethod def convert_user_move(m): return (m - 1) // 3, (m - 1) % 3
99b57520f8b907241971f3b801615527f795308e
mxxu/leetcodeOJ
/minstack.py
739
3.703125
4
class MinStack: # @param x, an integer # @return an integer def push(self, x): self.elements.append(x) self.size = self.size + 1 if len(self.elements) == 1 or self.getMin() > x: self.min_eles.append(self.size - 1) # @return nothing def pop(self): if self.min_eles and self.min_eles[-1] == self.size - 1: self.min_eles.pop() self.elements.pop() self.size = self.size - 1 # @return an integer def top(self): return self.elements[-1] # @return an integer def getMin(self): return self.elements[self.min_eles[-1]] def __init__(self): self.elements = [] self.min_eles = [] self.size = 0
e7b3806d0f498eb98f9da503b4892fb7f132cfb7
eliffyildirim1/Wtech-Homeworks
/Homework-5/04_04_PlottingBasicChartsWithMatplotlib.py
3,995
4.21875
4
#!/usr/bin/env python # coding: utf-8 # <font color=blue>Assignments for \"Plotting Basic Charts With Matplotlib\"</font> # In this assignment, you will continue work with the [Coronavirus Source Data](https://ourworldindata.org/coronavirus-source-data). You will plot different chart types. Don't forget to set titles and axis labels. # 1. Plot a bar chart for total cases of the 20 countries that have biggest numbers. # In[2]: import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import numpy as np import datetime # In[50]: covid=pd.read_csv('covid_data.csv',index_col=0) total_case=covid.groupby(by='location')['new_cases'].sum() tc=(total_case.sort_values(ascending=False)).head(20) country = tc.drop("World", axis=0) locations= [] for location in country.index[0:21]: locations.append(location) plt.figure(figsize=(12,7)) plt.xlabel('Total Cases') plt.ylabel('Countries') plt.title('Total cases of the highest 20 countries') plt.barh(locations,country,color="#FF914D") # 2. Plot a histogram for daily deaths for any country you choose. Make three subplots for different bins. # In[60]: import warnings warnings.filterwarnings('ignore') covid = pd.read_csv("covid_data.csv", index_col=0) title_style_small = {'family': 'Century Gothic', 'color': 'green', 'size': 10 } axis_style_small = {'family': 'Century Gothic', 'color': 'blue', 'size': 10 } plt.figure(figsize=(15, 5)) plt.subplot(1,3,1) plt.title("New deaths", fontdict = title_style_small ) for city in ["Turkey"]: plt.hist(covid[covid.location == city].new_deaths,color = "green",bins = 50) plt.xlabel("Daily deaths", fontdict = axis_style_small) plt.subplot(1,3,2) plt.title("New deaths", fontdict = title_style_small ) for city in ["Turkey"]: plt.hist(covid[covid.location == city].new_deaths,color = "yellow",bins = 20) plt.xlabel("Daily deaths", fontdict = axis_style_small) plt.subplot(1,3,3) plt.title("New deaths", fontdict = title_style_small ) for city in ["Turkey"]: plt.hist(covid[covid.location == city].new_deaths,color = "blue",bins = 60) plt.xlabel("Daily deaths", fontdict = axis_style_small) # 3. Plot a scatter plot of new cases and new death for Germany and France. # # In[63]: import warnings warnings.filterwarnings('ignore') covid = pd.read_csv("covid_data.csv", index_col=0) title_style_small = {'family': 'Century Gothic', 'color': 'green', 'size': 10 } axis_style_small = {'family': 'Century Gothic', 'color': 'blue', 'size': 10 } plt.figure(figsize=(15, 5)) plt.subplot(1,3,1) plt.title("New death for Germany and France", fontdict = title_style_small ) for city in ["Germany", "France"]: plt.scatter(covid[covid.location == city].new_deaths, covid[covid.location == city].new_cases, color = "green") plt.xlabel("Daily deaths", fontdict = axis_style_small) # 4. Plot a boxplot for daily deaths for any country you choose. # In[66]: import warnings warnings.filterwarnings('ignore') covid = pd.read_csv("covid_data.csv", index_col=0) title_style_small = {'family': 'Century Gothic', 'color': 'green', 'size': 10 } axis_style_small = {'family': 'Century Gothic', 'color': 'blue', 'size': 10 } plt.figure(figsize=(15, 5)) plt.subplot(1,3,1) plt.title("New deaths", fontdict = title_style_small ) for city in ["Turkey"]: plt.boxplot(covid[covid.location == city].new_deaths) plt.xlabel("Daily deaths", fontdict = axis_style_small) # 5. Calculate the total case for each continent and plot a pie chart # In[67]: covid = pd.read_csv("covid_data.csv",index_col=0) total_cases = covid.groupby(by="continent")["new_cases"].sum() continents = [] for continent in total_cases.index: continents.append(continent) plt.figure(figsize=(15, 5)) plt.title('Total case for each Continent', fontdict = title_style) plt.pie(total_cases,labels=continents, autopct='%1.2f%%', shadow=True, startangle=90) plt.show() # In[ ]:
a978a47284e96bde4d3aca3a0d4322c6535f630a
hanbingo/friendly-disco
/project4.py
151
4.03125
4
counter = 0 while counter < 42: if counter % 2 == 0: print("HO HO HO") else: print("Happy new year") counter = counter + 1
dd48ceb1c423c560e5a6ba989bb3335df141979c
fifthlight/test
/date01/homework5.py
977
3.9375
4
#九九乘法表 # for i in range(1,10): # for j in range(1,10): # print('%d*%d=%2d '%(j,i,i*j),end='') # print() #while里面的这个条件判断就在for形式的括号里面体现了 # i=1 # while i <10: # j=1 # while j<=9: # print('%d*%d=%2d '%(j,i,i*j),end='') # j+=1 # print() # i+=1 #左下三角 # for i in range(1,10): # for j in range(1,i+1): # print('%d*%d=%2d '%(j,i,i*j),end=' ') # print() #左上三角 # for i in range(1,10): # for j in range(i,10): # print('%d*%d=%2d '%(j,i,i*j),end='') # print() #右下三角 # for i in range(1,10): # for k in range(1,10-i): # print(end=' ') # for j in range(1,i+1): # print('%d*%d=%2d '%(j,i,i*j),end=' ') # print() #右上三角 # for i in range(1,10): # for k in range(1,i): # print(end='') # for j in range(i,10): # print('%d*%d=%2d '%(j,i,i*j),end=' ') # print()
c7d4837df914029e8595e16fdab3589c2bbc2a5f
furkanbakkal/Machine-Learning-with-Tensorflow
/draw.py
1,064
4.1875
4
# draw square in Python Turtle from os import name import turtle import time def boxing(start_point_x, start_point_y,length,label): t = turtle.Turtle() turtle.title("Squid Game Challange") wn = turtle.Screen() wn.setup(1200, 800) wn.bgpic("test.gif") t.hideturtle() t.penup() #don't d_raw when turtle moves t.goto(start_point_x-600, start_point_y-400) t.showturtle() #make the turtle visible t.pendown() # drawing first side t.forward(length) # Forward turtle by s units t.right(90) # Turn turtle by 90 degree # drawing second side t.forward(length) # Forward turtle by s units t.right(90) # Turn turtle by 90 degree # drawing third side t.forward(length) # Forward turtle by s units t.right(90) # Turn turtle by 90 degree # drawing fourth side t.forward(length) # Forward turtle by s units t.right(90) # Turn turtle by 90 degree t.write(label,font=("Verdana",10)) time.sleep(3)
8ee4973a81b68fd6695f741b0b95f94bea2ce268
HelenaOliveira1/Exerciciosprova2bim
/Questão 24.py
350
3.96875
4
print("Questão 24") print("") N = int(input("Qual a quantidade de notas? ")) print("") nota = float(input("Digite a nota: ")) i = 0 aux = 0 for media in range (1,N+1): soma = nota + i i = nota aux +=1 if (aux < N): nota = float(input("Digite a nota: ")) media = soma/N print("") print("A média das notas é", media)
9a9df3e1aed9c2f985d794eda194a766b5f8a474
jjassonnlee/elements-of-programming-interviews
/arrays/compute_the_next_permutation.py
192
3.78125
4
""" Given a permutation A, return the next permutation under dicitonary ordering. If input is [1,0,3,2], return [1,2,0,3] If input is [3,2,1,0], return [] """ def next_permutation(A): ...
864c13c137d4e62364c9e1192872956fcc8d8c4c
srikanthpragada/PYTHON_10_JULY_2020
/demo/basics/table.py
100
3.921875
4
num = int(input("Enter number :")) for i in range(1,21): print(f"{num} * {i:2} = {num * i:4}")
03c26e56cece6de276fcf0b38072323172a250f3
matthijsvk/Battleship
/battleship.py
12,298
4.25
4
# -*- coding: cp1252 -*- from random import randint import re import copy """ This is the game of Battleship, where the computer puts some ships somewhere in the ocean. You can then shoot and try to hit the ships. If you hit all parts of a ship, it is sunk! Try to sink all the enemy ships before you run out of ammo :) First, you can choose a level (the size of the ocean) Then, the ocean (='board') is created, as a 2D list (a list of lists) The computer generates some random ships in the ocean, making sure they fit on the board and don't overlap with each other. Then, the game starts! You choose a coordinate to shoot, the game checks if it's a legal shot, and in case you hit a ship, the board is updated. If you hit a ship part, but the ship is not completely destroyed, a 'H' is shown (for 'hit') If a ship is completely sunk, an 'S' is shown at all its coordinates (for 'sunk') This continues until you run out of turns, or all the ships are sunk :) """ def main(): print("Hello! Welcome to the game of Battleship!!") play = True while play: play_Battleship() play = ask_new_game() print("Goodbye! Thanks for playing Battleship!!") def ask_new_game(): # ask for another game yn = input("Do you want to play some more? \n") yn = yn.lower() yn = re.sub(r'([^\s\w]|_)+', '', yn) # keep only alphabetical characters (thanks google :D) yesses = ["y", "yes", "ye", "yeah", "yea", "sure", "of course"] if yn in yesses: keep_playing = True else: keep_playing = False return keep_playing def play_Battleship(): # define the ships in the game # -> list of names # -> list of sizes (lengths) of those ships ship_names_list = ["this ship doesn't exist", "this ship doesn't exist", "Destroyer", "Cruiser", "Aircraft Carrier", "Battleship"] # used to tell the player what kind of ship they sunk. ship_sizes_list = [2, 2, 3, 3, 4, 5] # list of the shipsizes to use # I only tested the game till lvl 3, but it's perfectly expandable. You might have to change the number of tries/ships print( 'Welcome to Battleship! There are three sizes of the game: one, two or three. Higher level ships are bigger too!') lvl = -1 while lvl > 3 or lvl < 1: lvl = int(input("Not an existing lvl. Which lvl do you choose? 1,2 or 3?\n")) # set difficulty based on level chosen nb_ships = lvl + 1 size_x = lvl + 4 size_y = lvl + 4 maxturns = int(8 + 4 * lvl ** 1.5) # formula determined through testing # create the board board = create_board(size_y, size_x) # 2D list (= matrix) board_height = len(board) # number of rows board_width = len(board[0]) # number of columns # create the ships # how it works: list of ships. Each ship is a list of coordinates. # If you fire, search through the ship_list and if the fired coorindate is in ships_left, remove it (so that part of the ship is destroyed). # If all coordinates of a ship are gone (its list is empty), the ship is destroyed! # ships_left keeps track of which parts of which ships have already been hit. ships_left = [] for i in range(0, nb_ships): # we need to pass ships_left, to make sure we don't put ships in places where there's already another ship! # also the board, because a ship has to completely fit inside the board ship = create_ship(ship_sizes_list[i], board, ships_left) ships_left.append(ship) nb_ships_left = len(ships_left) # make a copy so even after all ships are destroyed, we still know where they started (eg so we can display the not found ships) ships_original_location = copy.deepcopy(ships_left) ############################ ####### LET'S PLAY! ######## ############################ print("Let's play Battleship!") turn = 0 while turn < maxturns and nb_ships_left > 0: # 1. Graphics & info for player print('----------------------------------------') print_board(board) if nb_ships_left == 1: print("There is ", nb_ships_left, "ship left") else: print("There are ", nb_ships_left, "ships left") print("This is shot number ", turn + 1) # +1 to show the 'logical' number (so "turn 1" instead of "turn 0") # show how many shots are left if maxturns - turn == 1: print("You have ", maxturns - turn, " shot left") else: print("You have ", maxturns - turn, " shots left") # enter target coordinates for the new shot # coordinates are a bit annoying to work with. For users, starting at '1' is logical. But the computer starts at '0'. So we need to do some conversion. # for X: we have to do -1 to use the 'logical', not 'computer' number as input (so '1' instead of '0'). We want the axis to start at 1, not at 0 # for Y: board_height - y. Y-axis is downward because of how we contstructed the board 2D list... This feels weird to the player, we want to have a Y-axis pointing upward! guess_x = int(input("Enter X-coordinates to hit:")) - 1 guess_y = board_height - int(input("Enter Y-coordinates to hit:")) print("\n") # 2. Process the input # options: a) shot not inside the board -> tell user and give another shot (:D) # b) shot same as previous shot -> tell user and give another shot (:D) # c) shot hits a ship -> process shot, update board, check if ship completely destroyed, tell user # d) shot was a miss -> update board, tell user # first y, then x because the height is the y-th sublist of 'board' # 2.a) check if shot is out of bounds if (guess_y < 0 or guess_y >= board_height) or (guess_x < 0 or guess_x >= board_width): print("Oops, that's not even in the ocean. Try again.\n") continue # continue goes back to where the while started -> start new turn # 2.b) if already guessed, hit or sunk elif board[guess_y][guess_x] != 'O': # or board[guess_y][guess_x] == "H" or board[guess_y][guess_x] == "S"): print("You guessed that one already. Try again\n") continue # 2.c) check if shot hits a ship elif (occupied_by_other_ship([guess_y, guess_x], ships_left)): print("Congratulations! You hit a ship!\n") board[guess_y][guess_x] = "H" # show a 'H' to the player, because it was a hit # find out which ship was hit, sink its coordinate (=remove from ships_left list), and see if whole ship is destroyed now i = 0 while i < nb_ships: # is the i'th ship damaged? if [guess_y, guess_x] in ships_left[i]: # delete this ship coordinate from the list of this ship's intact parts ships_left[i].remove([guess_y, guess_x]) # if the ship has no intact parts left, it is completely sunk if len(ships_left[i]) == 0: print("You sunk my ship of class ", ship_names_list[ship_sizes_list[i]], "!!!\n") nb_ships_left -= 1 for sunken_shippart in ships_original_location[i]: board[sunken_shippart[0]][ sunken_shippart[1]] = "S" # show 'S' at all coordinates of the sunken ship break # the ship has been found, so we don't need to search further. exit the while loop i += 1 # 2.d) not outside board, not already guessed, and not hit -> this is a miss else: print("You missed my battleship!" "\n") board[guess_y][guess_x] = "X" # we've processed the shot, so this turn is over turn += 1 # all turns are used up or nb_ships_left==0, so the game ended if nb_ships_left <= 0: print("\n Congratulations!! You destroyed all of my ships!") else: print("Oooh, you lost!!") # print ships that were not found print("The ships that are left(M) were at the following positions: ") for ship in ships_left: for shippart in ship: board[shippart[0]][shippart[1]] = "M" # print final state of the ocean print("\n") print_board(board) print("\n") # CREATING THE BOARD # first y because the height is the y-th sublist of board. x is the position in that sublist. def create_board(size_y, size_x): board = [] for y in range(size_y): board.append(["O"] * size_x) return board def print_board(board): # print all rows, add spaces in between the coordinates (looks nicer) for row in board: print(" ".join(row)) print("\n") # CREATING THE SHIPS -> generate random (integer) numbers for the coordinates def random_y(board): return randint(0, len(board) - 1) def random_x(board): return randint(0, len(board[0]) - 1) def check_next_to_shippart(pos, shipparts): # shipparts is the list of coordinates of this ship is_next_to_ship = False for part in shipparts: # check if any any of the neighbouring squares to pos is part of a ship if (((part[0] + 1 == pos[0] or part[0] - 1 == pos[0]) and (part[1] == pos[1])) or ( (part[0] == pos[0]) and (part[1] + 1 == pos[1] or part[1] - 1 == pos[1]))): is_next_to_ship = True return is_next_to_ship def in_line_with_ship(pos, shipparts): # asserts if the part is on a straight line with the other shipparts if len(shipparts) > 1: if shipparts[0][0] == shipparts[1][0] and pos[0] == shipparts[0][0]: # in line horizontally in_line = 1 elif shipparts[0][1] == shipparts[1][1] and pos[1] == shipparts[0][1]: # in line vertically in_line = 1 else: in_line = 0 else: if pos[0] == shipparts[0][0] or pos[1] == shipparts[0][1]: # same x or y as the first shippart in_line = 1 if check_next_to_shippart(pos, shipparts) and in_line == 1: return 1 else: return 0 def occupied_by_other_ship(pos, ships_left): # asserts if the space has already been taken by a part of another ship occupied = 0 for i in range(len(ships_left)): if pos in ships_left[i]: occupied = 1 return occupied def create_ship(size, board, ships_left): tries = 0 board_height = len(board) board_width = len(board[1]) ship_coordinates = [] ship_coordinates.append([random_y(board), random_x(board)]) while (occupied_by_other_ship(ship_coordinates[-1], ships_left)): # make sure the first part of the ship is well positioned ship_coordinates[0] = [random_y(board), random_x(board)] i = 1 while i < size: # make sure all of the other shipparts are in line with the previous ones and not already occupied ship_coordinates.append([random_y(board), random_x(board)]) while (occupied_by_other_ship(ship_coordinates[-1], ships_left)) \ or (ship_coordinates[-1] in ship_coordinates[:-1]) \ or (not in_line_with_ship(ship_coordinates[-1], ship_coordinates)): ship_coordinates[-1] = [random_y(board), random_x(board)] tries += 1 if tries > 100: # if too many tries, there is no good position left for the part. try with a new first coordinate (see 'if' underneath) break if tries >= 100: # infinite loop due to bad positioning of the first ship section, try to start this ship at another place. (Very rarely, an infinite loop still occurs when the positioning of all the previous ships just doesn't allow the placement of the new ship.) tries = 0 i = 0 ship_coordinates = [] ship_coordinates.append([random_y(board), random_x(board)]) while (occupied_by_other_ship(ship_coordinates[-1], ships_left)): ship_coordinates[0] = [random_y(board), random_x(board)] i += 1 return ship_coordinates if __name__ == "__main__": main()
668d238dafe1d88006a537460769a7385cdab714
Sanchita210507/Class-111-Single-Sample-z-tests-
/school.py
4,198
3.515625
4
import plotly.figure_factory as ff import plotly.graph_objects as go import statistics import random import pandas as pd import csv df = pd.read_csv("school2.csv") data = df["Math_score"].tolist() fig = ff.create_distplot([data],["Math Scores"], show_hist= False) #fig.show() mean = statistics.mean(data) std_deviation = statistics.stdev(data) print("mean of popultion : ",mean) print("Standard deviation of popultion : ",std_deviation) def randomSetOfMeans(counter): dataset = [] for i in range(0, counter): random_index= random.randint(0,len(data)-1) value = data[random_index] dataset.append(value) mean = statistics.mean(dataset) return mean mean_list = [] for i in range(0,1000): set_of_means= randomSetOfMeans(100) mean_list.append(set_of_means) std = statistics.stdev(mean_list) mean = statistics.mean(mean_list) print("\n") print("mean of sampling distribution : ",mean) print("Standard deviation of sampling distribution : ", std) first_std_start, first_std_end = mean - std, mean + std second_std_start, second_std_end = mean - (2*std), mean + (2*std) third_std_start, third_std_end = mean -(3*std), mean + (3*std) fig = ff.create_distplot([mean_list], ["Student Marks"], show_hist=False) fig.add_trace(go.Scatter(x=[mean,mean],y=[0,0.17],mode="lines+markers",name="Mean")) #fig.show() # finding the mean of THE STUDENTS WHO GAVE EXTRA TIME TO MATH LAB and plotting on graph df = pd.read_csv("School_1_Sample.csv") data = df["Math_score"].tolist() meanOfSample1 = statistics.mean(data) fig = ff.create_distplot([mean_list],["Student Marks"], show_hist=False) fig.add_trace(go.Scatter(x=[mean,mean],y=[0,0.17],mode="lines+markers",name="Mean")) fig.add_trace(go.Scatter(x=[meanOfSample1,meanOfSample1],y=[0,0.17],mode="lines+markers",name="Mean of student had math lab")) fig.add_trace(go.Scatter(x=[first_std_end,first_std_end],y=[0,0.17],mode="lines+markers",name="First std end")) fig.add_trace(go.Scatter(x=[second_std_end,second_std_end],y=[0,0.17],mode="lines+markers",name="Second std end")) fig.add_trace(go.Scatter(x=[third_std_end,third_std_end],y=[0,0.17],mode="lines+markers",name="Third std end")) #fig.show() #finding the mean of the STUDENTS WHO USED MATH PRACTISE APP and plotting it on the plot. df = pd.read_csv("School_2_Sample.csv") data = df["Math_score"].tolist() meanOfSample2 = statistics.mean(data) fig = ff.create_distplot([mean_list],["Student Marks"], show_hist=False) fig.add_trace(go.Scatter(x=[mean,mean],y=[0,0.17],mode="lines+markers",name="Mean")) fig.add_trace(go.Scatter(x=[meanOfSample2,meanOfSample2],y=[0,0.17],mode="lines+markers",name="Mean of student had math app")) fig.add_trace(go.Scatter(x=[first_std_end,first_std_end],y=[0,0.17],mode="lines+markers",name="First std end")) fig.add_trace(go.Scatter(x=[second_std_end,second_std_end],y=[0,0.17],mode="lines+markers",name="Second std end")) fig.add_trace(go.Scatter(x=[third_std_end,third_std_end],y=[0,0.17],mode="lines+markers",name="Third std end")) #fig.show() # finding the mean of the STUDENTS WHO WERE ENFORCED WITH REGISTERS and plotting it on the plot. df = pd.read_csv("School_3_Sample.csv") data = df["Math_score"].tolist() meanOfSample3 = statistics.mean(data) fig = ff.create_distplot([mean_list],["Student Marks"], show_hist=False) fig.add_trace(go.Scatter(x=[mean,mean],y=[0,0.17],mode="lines+markers",name="Mean")) fig.add_trace(go.Scatter(x=[meanOfSample3,meanOfSample3],y=[0,0.17],mode="lines+markers",name="Mean of student had enforced with registers")) fig.add_trace(go.Scatter(x=[first_std_end,first_std_end],y=[0,0.17],mode="lines+markers",name="First std end")) fig.add_trace(go.Scatter(x=[second_std_end,second_std_end],y=[0,0.17],mode="lines+markers",name="Second std end")) fig.add_trace(go.Scatter(x=[third_std_end,third_std_end],y=[0,0.17],mode="lines+markers",name="Third std end")) #fig.show() zscore1 = (meanOfSample1 - mean) / std print("Z score for the first group:", zscore1) zscore2 = (meanOfSample2 - mean) / std print("Z score for the second group:", zscore2) zscore3 = (meanOfSample3 - mean) / std print("Z score for the third group:", zscore3) # The third group had the most impact.
2f2928e1b7d3a02c0870c5105a62ab23cb970f1b
joe-antognini/exercises
/praxis/ex200/brute_countprimes.py
708
3.90625
4
#! /usr/bin/env python if __name__ == '__main__': from segmented_sieve import * else: from ..ex108.segmented_sieve import segmented_sieve def brute_countprimes(n): '''Count the number of primes up to n using a segmented sieve of Eratosthenes.''' blocksize = int(1e8) nprimes = 1 if blocksize > n: primes = sieve_erato(n) nprimes += sum(primes) else: primes = sieve_erato(2*blocksize) nprimes += sum(primes) for primes in segmented_sieve(2*blocksize, n + 2*blocksize - (n%(2*blocksize)), blocksize): nprimes += sum(primes) nprimes -= sum(primes[(n%(2*blocksize)+1)/2:]) return nprimes if __name__ == '__main__': print brute_countprimes(2038074745)
5bdf0a15a7a433c8cea5ee0ba53b9000d5a8e296
ranjana980/Python
/loop files/even.py
107
3.609375
4
counter=1 while counter<=100: if counter%2==0: print(counter) counter=counter=counter+1
5749dd2702cb129c8e31fc837b7065cd86a0bc27
rsamit26/AlgorithmsAndDatastructure
/EulerProject/Largest palindrome product.py
1,116
4.15625
4
""" A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers. """ class Solution: def largestPallindrome(self, k): n = 10**k-1 l = [] for i in range(n,10**(k-1), -1): for j in range(n, i-1,-1): if str(i*j) == str(i*j)[::-1]: l.append(i*j) break return max(l) def method_02(self, k): a = 10**k - 1 largest_palindrome = 0 while a > 10**(k-1): if a%11==0: b = 10**k - 1 db = 1 else: b = 10**k + 1 -11 db = 11 while b>=a: if a*b <= largest_palindrome: break if str(a*b) == str(a*b)[::-1]: largest_palindrome = a*b b = b-db a -= 1 return largest_palindrome s = Solution() print(s.largestPallindrome(3)) print(s.method_02(3))
96c70910bfa5e01a432c424c913630d6a155133d
MatheusFilipe21/exercicios-python-3
/exercicio14.py
195
3.78125
4
temp = float(input('Escreva a temperatura em °C: ')) novatemp = (temp * 1.8) + 32 print('A temperatura de \033[34m{:.2f}\033[m em °C equivale a \033[31m{:.1f}\033[m°F'.format(temp, novatemp))
856758bf9651910a1b5602f7358e69c6657c1406
gohdong/algorithm
/leetcode/1379.py
794
3.578125
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode: # print(original) # print(cloned) # print() answer = TreeNode() def dfs(node): if node.val == target.val: nonlocal answer answer = node return if node.right: dfs(node.right) if node.left: dfs(node.left) dfs(cloned) # a = target.val return answer
812776057a2ac72df135a5234cf4afce3c416cc1
castle-bravo/diamond_square
/diamond_square.py
2,944
3.578125
4
''' file: diamond_square.py title: Diamond-square algorithm author: Alexander Gosselin e-mail: alexandergosselin@gmail.com alexander.gosselin@alumni.ubc.ca date: August 19, 2015 license: GPLv3 <http://www.gnu.org/licenses/gpl-3.0.en.html> ''' import numpy as np import numpy.random as rnd def diamond_square(shape, roughness=0.5, seed=None): """ Return a new array of given shape, filled with randomly generated, normalized diamond-square heightmap. Parameters ---------- shape : int or sequence of ints Shape of the new array, e.g., ``(2, 3)`` or ``2``. roughness : float, optional The roughness of the heightmap. Each iteration i adds noise by scaled by a factor of roughness**i. seed : int, optional Random seed used to generate the heightmap. Returns ------- out : ndarray Heightmap with the given shape. Examples -------- >>> diamond_square((3,3)) array([[ 0.27224058, 0.13612029, 0. ], [ 0.25652526, 0.01390666, 0.5 ], [ 0.24080993, 0.62040496, 1. ]]) """ if type(shape) is tuple: n, m = shape elif type(shape) is int: n = shape m = shape # determine the number of iterations from the shape b = [bin(n - 1)[2:], bin(m - 1)[2:]] if len(b[0]) != len(b[1]): if len(b[0]) < len(b[1]): b[0] = '0'*(len(b[1]) - len(b[0])) + b[0] else: b[1] = '0'*(len(b[0]) - len(b[1])) + b[1] rnd.seed(seed) u = np.mat(rnd.random()) # expand matrix u if it needs to be expanded if b[0][0] == '1': u = np.row_stack((u, rnd.random((1, u.shape[1])))) if b[1][0] == '1': u = np.column_stack((u, rnd.random((u.shape[0], 1)))) r = roughness for k in range(1, len(b[0])): # perform iteration nk, mk = u.shape A = np.mat(np.empty((2*nk - 1, nk))) A[0::2] = np.eye(nk) A[1::2] = (np.diag([0.5]*nk, 0) \ + np.diag([0.5]*(nk - 1), 1))[0:-1] if nk == mk: B = A.T else: B = np.mat(np.empty((2*mk - 1, mk))) B[0::2] = np.eye(mk) B[1::2] = (np.diag([0.5]*mk, 0) \ + np.diag([0.5]*(mk - 1), 1))[0:-1] B = B.T R = np.zeros((2*nk - 1, 2*mk - 1)) R[1::2, 1::2] = r*(rnd.random((nk - 1, mk - 1)) - 0.5) u = A*u*B + R # expand matrix u if it needs to be expanded if b[0][k] == '1': u = np.row_stack( (u, u[-1,:] + r*(rnd.random((1, u.shape[1])) - 0.5))) if b[1][k] == '1': u = np.column_stack( (u, u[:,-1] + r*(rnd.random((u.shape[0], 1)) - 0.5))) r *= roughness # normalize u u -= u.min() u /= u.max() return np.array(u)
36399b0d59d727648d3be1887f85ad07e6f62bb1
deepu14d/Decrypto
/decrypto/src/vigenere_cipher.py
1,525
3.828125
4
class VigenereCipher: def __init__(self) -> None: """This is a python implementation of Vigenere Cipher""" def modify_key(self, msg: str, key: str) -> str: '''Generates the key in a cyclic manner until it's length equal to the length of text''' if len(msg) > len(key): for i in range(len(msg) - len(key)): key += key[i % len(key)] return key def encrypt(self, msg: str, key: str) -> str: msg, key = msg.upper(), key.upper() key = self.modify_key(msg, key) encrypted_words = [] curr_key_index = 0 for text in msg.split(): result = '' for i in range(len(text)): x = (ord(text[i]) + ord(key[curr_key_index])) % 26 x += ord('A') result += chr(x) curr_key_index += 1 encrypted_words.append(result) return ' '.join(encrypted_words).lower() def decrypt(self, msg: str, key: str) -> str: msg, key = msg.upper(), key.upper() key = self.modify_key(msg, key) decrypted_words = [] curr_key_index = 0 for word in msg.split(): result = '' for i in range(len(word)): x = (ord(word[i]) - ord(key[curr_key_index]) + 26) % 26 x += ord('A') result += chr(x) curr_key_index += 1 decrypted_words.append(result) return ' '.join(decrypted_words).lower()
d99872ecb47e18b5460a4ef5267fa0d10cfd3d45
yaalyy/Fruit_Machine
/slot machine.py
1,208
3.765625
4
import random credit = 1 fruit = ['Cherry','Bell','Lemon','Orange','Star','Skull'] def roll(): global credit credit=credit-0.2 results = [] bell_num = 0 skull_num = 0 same_num = 0 for i in range(3): m = random.randint(0,5) k = fruit[m] results.append(k) if results[i]=="Bell": bell_num+=1 if results[i]=="Skull": skull_num+=1 print("Results:",end="") for i in results: print(i,end=" ") print() if results[0]==results[1]: same_num+=1 if results[0]==results[2]: same_num+=1 if results[2]==results[1]: same_num+=1 if skull_num>=2: if skull_num==3: credit=0; elif skull_num==2: credit-=1 elif bell_num==3: credit+=5 elif same_num==3: credit+=1 elif same_num==2: credit=credit+0.5 if credit<0: credit=0 while credit>=0.2: print("You have ",round(credit,1)," credits") print("Would you like to continue or quiz?") q=input() if q=="quiz": break roll() print("In the end, you have ",credit," credits")
8c95d7d310e2b2fb1e026732a719559d18079cb2
xiaotiankeyi/PythonBase
/python_oo/oo_advanced/class_decorator_two.py
423
3.78125
4
# 实现类装饰器,为函数增加新的功能 class Family(object): def __init__(self, func): self.__func = func def __call__(self, *args, **kwargs): self.new() result = self.__func() print(result) def new(self): print('所要执行的新的功能!!!') @Family def daughter(): return '需要被装饰得类.....' if __name__ == "__main__": daughter()
09978538015c35f4750dac07cdb5eb860889d2ae
MrDrewShep/Python_fundamentals
/error_handling.py
880
3.75
4
# TRY EXCEPT def proclaim_user_birthday(name, age): try: new_age = age + 1 message = f"{name} is now {new_age} years old!" print(message) except Exception as e: print(e) print("ONLY WHEN MY PROGRAM CONTINUES") proclaim_user_birthday("Drew", "45") print("I'm after proclaim.") # Anytime you're deailing with user-input data, use error handling. # When dealing with data that only we control, might be safe enough to disregard error handling. def find_user(user_id): if not isinstance(user_id, int): try: user_id = int(user_id) except Exception as e: print(e) raise TypeError("User_id must be a number.") return "A user" # Rest of code block here find_user("test") """ def example_fn(PARAMETER): code block here code block here example_fun(ARGUMENT) """
8d645f82835576b1e219ab5aeccaf0347b29dc0a
anderalex803/nuwara-online-courses
/datacamp/statistical-simulation-python/02_poker_two_of_a_kind.py
557
3.53125
4
# Shuffle deck & count card occurrences in the hand n_sims, two_kind = 10000, 0 for i in range(n_sims): np.random.shuffle(deck_of_cards) hand, cards_in_hand = deck_of_cards[0:5], {} for card in hand: # Use .get() method on cards_in_hand cards_in_hand[card[1]] = cards_in_hand.get(card[1], 0) + 1 # Condition for getting at least 2 of a kind highest_card = max(cards_in_hand.values()) if highest_card>=2: two_kind += 1 print("Probability of seeing at least two of a kind = {} ".format(two_kind/n_sims))
907db787f072f64abb134ff67f457a36d359bb29
ThomasHartmannDev/CursoPython
/Programas/01 - Fundamentos/10 - Tuplas/exemplo.py
910
4.125
4
''' Diferente da lista que pode ser mudada, a Tupla è imutavel. ''' tupla_unica = ('um',) # Caso queremos apenas um item na tupla devemos deixar essa (,) no final. tupla_cores = ('Verde','Amarelo','Azul','Branco')# não precisamos colocar a (,) no final pois o python ja entendeu que se trata de uma tupla. print(tupla_cores[-1]) print(tupla_cores[1]) print(tupla_cores[1:]) print(tupla_cores[:4]) # funciona igual as listas. print(tupla_cores.index('Amarelo')) #Mostra o index do amarelo print(tupla_cores.count('Azul')) #Mostra quantas vezes o azul aparece na tupla. tupla_repetida = ('Verde','Amarelo','Azul','Branco','Azul','Azul','Azul','Azul','Azul','Azul') print(tupla_repetida.count('Azul'))# neste caso temos 7 'Azul' na tupla #Caso não tenha oque foi pedido para contar na lista ele retorna 0 #Vamos ver quantos itens tem em cada lista. print(len(tupla_cores)) print(len(tupla_repetida))
d90d7b2636edf74d2698bfd42acd852883f8297e
InahoKai/algorithms-1
/easy/isPowerOfFour.py
297
3.8125
4
# Runtime: 28 ms, faster than 90.26% of Python3 online submissions for Power of Four. def isPowerOfFour(num: int) -> bool: if num == 0: return False while num != 1: if num % 4 != 0: return False num = num // 4 return True print(isPowerOfFour(16))
01f1c86b72c530f95b8dff7c5a22970f294c69a8
kanikashridhar/Elevator
/utils/elevator_helper.py
774
4.125
4
import typing from typing import List, Tuple def calculate_service_in_directions(requested_floors: List[int], current_floor: int) -> Tuple[List[int], List[int]]: """ Creates two list from a input requested_floors list. floors_in_up_direction - contains all the floor number which are above the current_floor floors_in_down_direction - all floor which are below which are below the current_floor """ requested_list = sorted(requested_floors) floors_in_up_direction = [val for val in requested_list if val >= current_floor] floors_in_down_direction = [val for val in requested_list if val < current_floor] floors_in_down_direction = floors_in_down_direction[::-1] return floors_in_up_direction, floors_in_down_direction
f5c5a2910c1b2d9aec42a7424a8f6aa265c0bd79
Pigiel/udemy-python-for-algorithms-data-structures-and-interviews
/Stacks, Queues and Deques/Stacks, Queues, and Deques Interview Problems/Stacks, Queues, Deques Interview Questions /Balanced-Parentheses-Check.py
1,109
4
4
#!/usr/bin/env python3 def balance_check(s): # Check if even number of brackets if len(s) % 2 != 0: return False # Set of opening brackets opening = set('([{') # Matching pairs matches = set([('(',')'), ('[',']'), ('{','}')]) # Use a list as a "Stack" stack = [] # Check every parenthesis in string for paren in s: # If its an opening, append it to list if paren in opening: stack.append(paren) else: # Check that there are parentheses in Stack if len(stack) == 0: return False # Check the last open parentheses last_open = stack.pop() # Check if it has a closing match if (last_open, paren) not in matches: return False return len(stack) == 0 balance_check('[]') balance_check('[](){([[[]]])}') balance_check('()(){]}') """ SOLUTION TESTING """ import unittest class TestBalanceCheck(unittest.TestCase): def test(self, sol): self.assertEqual(sol('[](){([[[]]])}('),False) self.assertEqual(sol('[{{{(())}}}]((()))'),True) self.assertEqual(sol('[[[]])]'),False) print('ALL TEST CASES PASSED') t = TestBalanceCheck() t.test(balance_check)
b05b908d77aa8237e4cdd2e7263d20fef9055d2f
Rakeshyakkundi/DSA
/stack.py
659
3.703125
4
ls = [] rev = [] max = 5 while True: num = int(input("1.insert 2.pop 3.display 4.exit 5 reverse\n")) if num ==1 and len(ls)<max: n = int(input("Data :")) ls.append(n) continue if num == 2 and len(ls)>0: ls.pop() continue if num == 3: print("Stack Top-Down :") for i in range(len(ls)-1,-1,-1): print(ls[i]) continue if num == 4: print("bye") exit() if num == 5: for i in range(len(ls)): rev.append(ls.pop()) ls = rev print("Stack Top-Down :") for i in range(len(ls)-1,-1,-1): print(ls[i])
8140b0c7897420d4773610c6cae2088b7d9059dd
haron68/CSCI-1133
/arama006_3A.py
997
3.546875
4
# CSci 1133-20 HW 3 # Haron Arama # HW 3, Problem 3A inputType = input("Are input components int or float (i/f)? ") if inputType == "f": red = float(input("Red component: ")) * 255 green = float(input("Green component: ")) * 255 blue = float(input("Blue component: ")) * 255 rint = int(red) gint = int(green) bint = int(blue) if (red - rint) == 0.5: rint = rint + 1 if (blue - bint) == 0.5: bint = bint + 1 if (green - gint) == 0.5: gint = gint + 1 print("Int representation: ", rint, gint, bint) elif inputType == "i": red = int(input("Red component: ")) / 255 green = int(input("Green component: ")) / 255 blue = int(input("Blue component: ")) / 255 red = float("{0:.2f}".format(red)) green = float("{0:.2f}".format(green)) blue = float("{0:.2f}".format(blue)) print("Float representation: ", red, green, blue) else: print("Invalid option.")
06ed801583d1ba7c3912cf838e63acc795ec3cb0
mvxdipro/old-projects
/filters.py
3,249
3.65625
4
#tyutyunnykd_mohamedm2 #Import function to get red, green, blue values from cImage import * import sys def grayscale(image): #Function converts to grayscale by averaging the three color values grayscaleIM = image.copy() numP = image.getNumPixels() for i in range (numP): apixel = image.getPixel1D(i) apixel.red = int((apixel.red + apixel.blue + apixel.green)/3) apixel.blue = int((apixel.red + apixel.blue + apixel.green)/3) apixel.green = int((apixel.red + apixel.blue + apixel.green)/3) grayscaleIM.setPixel1D(i, apixel) return grayscaleIM def negate(image): #Function converts to negate by subtracting each color from 255, which turns dark to light and vice versa negateIM = image.copy() numP = image.getNumPixels() for i in range (numP): apixel = image.getPixel1D(i) apixel.red = int(255-apixel.red) apixel.blue = int(255-apixel.blue) apixel.green = int(255-apixel.green) negateIM.setPixel1D(i, apixel) return negateIM def saturatedRGB(r,g,b,k):#Function created by Sherri to adjust color values to saturated """ takes the red, green, and blue values for the color of a pixel as well as a k value that represents how much to saturate the color, then returns a list containing the saturated red, green, and blue values of the color""" vals = [.3*(1-k), .6*(1-k), .1+.9*k] newr = scale((.3+.7*k)*r + .6*(1-k)*g + .1*(1-k)*b) newg = scale(.3*(1-k)*r + (.6+.4*k)*g + .1*(1-k)*b) newb = scale(.3*(1-k)*r + .6*(1-k)*g + (.1+.9*k)*b) return [int(newr),int(newg),int(newb)] def scale(val):#Function created by Sherri to return k values """ scales a value to be in the allowable color range for a pixel 0-255 """ if val < 0: val = 0 elif val > 255: val = 255 return val def saturate(image, k):#Function converts to saturate by using the saturatedRGB function saturateIM = image.copy() numP = image.getNumPixels() for i in range (numP): apixel = image.getPixel1D(i) satValue = saturatedRGB(apixel.red, apixel.green, apixel.blue, k) apixel.red = satValue[0] apixel.green = satValue[1] apixel.blue = satValue[2] saturateIM.setPixel1D( i, apixel) return saturateIM def main (): oIm = FileImage(sys.argv[1]) #Assigns a variable to the image inputed from the command line win = ImageWin("image", oIm.getWidth()*2, oIm.getHeight()*2)# Creates a window twice the height and width to accommodate all four images oIm.draw(win) imGrayscale = grayscale(oIm) #Runs original image through gray scale imGrayscale.setPosition(oIm.getWidth()+1,0) #Places image top right imGrayscale.draw(win) imNegate = negate(oIm) #Runs original image through negate function imNegate.setPosition(0,oIm.getHeight()+1) #Places image bottom left imNegate.draw(win) imSaturate = saturate(oIm, scale(int(sys.argv[2]) )) #Runs original image through saturate function imSaturate.setPosition(oIm.getWidth()+1 , oIm.getHeight()+1) #Places image bottom right imSaturate.draw(win) input("enter to quit") main()
0fbad9f2170e2b70b5aa59f3d9fdbe546b4931bd
hrantm/ML-AndrewNg
/ex1/warmup.py
147
3.609375
4
# -*- coding: utf-8 -*- import numpy as np num = int(input("Enter num:" )) def warmup(x): return np.identity(x) print(warmup(num))
5f072aa28d29058c32a8ca2a2ae21f534f520a81
abiryusuf/pyhton_3
/lists/removeList.py
193
3.65625
4
thisList = ["red", "black", "blue", "white"] # remove # thisList.remove("red") # print(thisList) x = thisList.pop(1) print(x) print(thisList) print(2**10) p = 26 total = p**6 print(total)
26f0ae622d691d417146f8620717eebbd7de9cd2
dafedo/long-range_word_dependency
/correlation_function.py
5,209
3.53125
4
import re from collections import Counter import pandas as pd import matplotlib.pyplot as plt import numpy as np def tokenize(sentence): ''' List all the word tokens (consecutive letters) in a text. Normalize to lowercase. ''' return re.findall('[a-z]+', sentence.lower()) def frequency(corpus): ''' Generates a dictionary with word types and their counts. :param corpus: list of tokens, corpus represented as a sequence of tokens. :return freq: dict, word types and their frequencies ''' freq = Counter(corpus) return freq def unigram_prob(word_type, corpus): ''' Calculates the probability of a certain unigram. ''' word_type_prob = unigram_counts[word_type] / len(corpus) return word_type_prob def occurrence_counts(word_1, word_2, corpus, d): ''' Calculates the total number of times word_2 is observed after word_1 at distance d. ''' count = 0 for index, word in enumerate(corpus): if word == word_1 and (index + d) < len(corpus): if corpus[index + d] == word_2: count +=1 return count def correlation(word_1, word_2, corpus): ''' Computes the correlation between the two words with distance d in range from 1 to 101. ''' corr_list = [] for d in range(1, 101): prob_dis = occurrence_counts(word_1, word_2, corpus, d) / (len(corpus) - d) prob_corr = prob_dis / (unigram_prob(word_1, corpus) * unigram_prob(word_2, corpus)) corr_list.append(prob_corr) return corr_list if __name__ == '__main__': with open('continuous.corpus.en', encoding="utf8", errors='ignore') as f: # Initialize an empty list to represent the corpus as a sequence of tokens. tokenized_text = [] for sentence in f: sentence = sentence.rstrip('\n') tokenized_text.extend(tokenize(sentence)) # Generate a dictionary with word types and their counts unigram_counts = frequency(tokenized_text) # Compute the correlation between the word pairs for each D in range from 1 to 101. # Word pair 'you' and 'your' correlation_you_your = correlation('you', 'your', tokenized_text) # Word pair 'she' and 'her' correlation_she_her = correlation('she', 'her', tokenized_text) # Word pair 'he' and 'his' correlation_he_his = correlation('he', 'his', tokenized_text) # Word pair 'they' and 'their' correlation_they_their = correlation('they', 'their', tokenized_text) # Word pair 'he' and 'her' correlation_he_her = correlation('he', 'her', tokenized_text) # Word pair 'she' and 'his' correlation_she_his = correlation('she', 'his', tokenized_text) # Apply moving average with window size 5 on the data points in the corellation list for every word pair. df_you_your = pd.DataFrame(correlation_you_your) df_you_your_smooth = df_you_your.rolling(window=5).mean() df_she_her = pd.DataFrame(correlation_she_her) df_she_her_smooth = df_she_her.rolling(window=5).mean() df_he_his = pd.DataFrame(correlation_he_his) df_he_his_smooth = df_he_his.rolling(window=5).mean() df_they_their = pd.DataFrame(correlation_they_their) df_they_their_smooth = df_they_their.rolling(window=5).mean() df_he_her = pd.DataFrame(correlation_he_her) df_he_her_smooth = df_he_her.rolling(window=5).mean() df_she_his = pd.DataFrame(correlation_she_his) df_she_his_smooth = df_she_his.rolling(window=5).mean() # Generate a linear curve where the x-axis represents the distance D # and the y-axis represents the value of the correlation. A legend identifies each word pair on the graph. distance = list(range(1, 101)) plt.title('Running mean') plt.plot(distance, df_you_your_smooth, label='you, your') plt.plot(distance, df_she_her_smooth, label='she, her') plt.plot(distance, df_he_his_smooth, label='he, his') plt.plot(distance, df_they_their_smooth, label='they_their') plt.plot(distance, df_he_her_smooth, label='he, her') plt.plot(distance, df_she_his_smooth, label='she, his') plt.xticks(np.arange(0, 101, step=10)) plt.yticks(np.arange(0, 10, step=1)) plt.ylim(bottom=0) plt.xlim(left=0, right=100) plt.legend(loc='upper right') plt.title("Correlation Value by Distance") plt.xlabel('Distance') plt.ylabel('Correlation value') plt.legend() plt.show() # Generates a curve where the x-axis represents the distance d in logarithmic scale and # the y-axis represents the value of the correlation in linear scale. distance = list(range(1, 101)) plt.title('Running mean') plt.loglog(distance, df_you_your_smooth, label='you, your') plt.loglog(distance, df_she_her_smooth, label='she, her') plt.loglog(distance, df_he_his_smooth, label='he, his') plt.loglog(distance, df_they_their_smooth, label='they_their') plt.loglog(distance, df_he_her_smooth, label='he, her') plt.loglog(distance, df_she_his_smooth, label='she, his') plt.legend(loc='upper right') plt.title("Correlation Value by Distance") plt.xlabel('Distance') plt.ylabel('Correlation value') plt.legend() plt.show()
6fc03e029814d1e7f48e0c65921d19a276c15b06
CHilke1/Tasks-11-3-2015
/Fibonacci2.py
586
4.125
4
class Fibonacci(object): def __init__(self, start, max): self.start = start self.max = max def fibonacci(self, max): if max == 0 or max == 1: return max else: return self.fibonacci(max - 1) + self.fibonacci(max - 2) def printfib(self, start, max): for i in range(start, max): print("Fibonacci of %d %d: " % (i, self.fibonacci(i))) while True: start = int(input("enter start : ")) max = int(input("Enter maximum: ")) myfib = Fibonacci(start, max) myfib.printfib(start, max) quit = input("Run again?Y/N: ") if quit == "N" or quit == "n": break
dc0df8c65f2da598e1696c763cbcfa3254426612
santoshmano/pybricks
/trees/flip_tree.py
907
3.984375
4
class Node: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right def inorder_traversal(root): if root == None: return inorder_traversal(root.left) print(root.val, end=' ') inorder_traversal(root.right) def flip_tree(root): if root == None: return root flip_tree(root.left) flip_tree(root.right) temp = root.left root.left = root.right root.right = temp return root def create_bin_tree1(): root = Node(25) root.left = Node(15) root.left.left = Node(10) root.left.right = Node(20) root.right = Node(35) root.right.left = Node(30) root.right.right = Node(40) return root root = create_bin_tree1() path = [] inorder_traversal(root) print(":tree inorder") root = flip_tree(root) inorder_traversal(root) print(":flipped tree inorder")
6836cb34074d73fa92713f8a1fbef73a993d95e2
Corinyi/ML_Python
/svmexercise.py
535
3.84375
4
# 2만명 데이터 작성(csv) import random def bmi_func(height, weight): bmi = weight/(height/100)**2 if bmi < 18.5: return "low" if bmi < 25: return "ok" return "high" fp =open('bmi.csv',"w",encoding="utf-8") fp.write("height,weight,label\r\n") # 데이터 생성 cnt = {'low' : 0,'ok' : 0,'high' : 0} for i in range(10000): h = random.randint(120,200) w = random.randint(35,100) label= bmi_func(h,w) cnt[label] += 1 fp.write("{0},{1},{2}\r\n".format(h,w,label)) fp.close() print("ok, ",cnt)
5c225df9a4df6c34712cafdeaebfdeed45e6e7f1
sadatrafsanjani/MIT-6.0001
/Lec04/in.py
214
3.953125
4
def isIn(s1, s2): if (s1 in s2) or (s2 in s1): return True else: return False if isIn("Dragunov", "Dragunov is a sniper rifle"): print("Yes") else: print("No")
282da6a82acb1c87d385af3595cdb30616d65391
nabo715/LearningPython
/File_processing.py
215
4.1875
4
# Use words.txt as the file name fname = raw_input("Enter file name:") try: fh = open(fname) except: print("Incorrect file name") exit() for line in fh: line = line.rstrip() print line.upper()
ee8e82e51d4cdcad46024a25266da13f92308800
yentingw/lexical-normalization-twitter-text
/main.py
1,105
3.515625
4
from bestMatch import * # Read in the txt files and make them into lists def getToken(): with open('misspell.txt', 'r') as token: tokenLs = [item.strip() for item in token] return tokenLs tokenLs = getToken() def getDict(): with open('dict.txt', 'r') as dictTxt: dictLs = [item.strip() for item in dictTxt] return dictLs dictLs = getDict() def getAnswer(): with open('correct.txt', 'r') as ans: ansLs = [item.strip() for item in ans] return ansLs ansLs = getAnswer() # Convert misspelled tokens and dictionary with soundex, respectively (in bestMatch.py) # For each token, find the best match within the converted dictionary (also in bestMatch.py). # Compare the best match to the canonical form in correct.txt # And use accuracy to evaluate the model points = 0 for i in range(len(tokenLs)): match = bestMatch(tokenLs[i]) # If best match is the canonical form, get 1 point if match == ansLs[i]: points += 1 # Calculate the final accuracy accuracy = round(points / len(tokenLs), 2) print("Accuracy: " + str(accuracy))
9c14aa03df9430a990dd88c23f0d2dac3c91c7c3
DataEngDev/CS_basics
/leetcode_python/Tree/implement-trie-prefix-tree.py
5,195
3.90625
4
# V0 # V1 # https://blog.csdn.net/fuxuemingzhu/article/details/79388432 class Node(object): def __init__(self): self.children = collections.defaultdict(Node) self.isword = False class Trie(object): def __init__(self): """ Initialize your data structure here. """ self.root = Node() def insert(self, word): """ Inserts a word into the trie. :type word: str :rtype: void """ current = self.root for w in word: current = current.children[w] current.isword = True def search(self, word): """ Returns if the word is in the trie. :type word: str :rtype: bool """ current = self.root for w in word: current = current.children.get(w) if current == None: return False return current.isword def startsWith(self, prefix): """ Returns if there is any word in the trie that starts with the given prefix. :type prefix: str :rtype: bool """ current = self.root for w in prefix: current = current.children.get(w) if current == None: return False return True # Your Trie object will be instantiated and called as such: # obj = Trie() # obj.insert(word) # param_2 = obj.search(word) # param_3 = obj.startsWith(prefix) # V1' # https://www.jiuzhang.com/solution/implement-trie-prefix-tree/#tag-highlight-lang-python class TrieNode: def __init__(self): self.children = {} self.is_word = False class Trie: def __init__(self): self.root = TrieNode() """ @param: word: a word @return: nothing """ def insert(self, word): node = self.root for c in word: if c not in node.children: node.children[c] = TrieNode() node = node.children[c] node.is_word = True """ return the node in the trie if exists """ def find(self, word): node = self.root for c in word: node = node.children.get(c) if node is None: return None return node """ @param: word: A string @return: if the word is in the trie. """ def search(self, word): node = self.find(word) return node is not None and node.is_word """ @param: prefix: A string @return: if there is any word in the trie that starts with the given prefix. """ def startsWith(self, prefix): return self.find(prefix) is not None # V1'' # https://www.jiuzhang.com/solution/implement-trie-prefix-tree/#tag-highlight-lang-python class TrieNode: def __init__(self): self.children = {} self.is_word = False class Trie: def __init__(self): self.root = TrieNode() """ @param: word: a word @return: nothing """ def insert(self, word): node = self.root for c in word: if c not in node.children: node.children[c] = TrieNode() node = node.children[c] node.is_word = True """ return the node in the trie if exists """ def find(self, word): node = self.root for c in word: node = node.children.get(c) if node is None: return None return node """ @param: word: A string @return: if the word is in the trie. """ def search(self, word): node = self.find(word) return node is not None and node.is_word """ @param: prefix: A string @return: if there is any word in the trie that starts with the given prefix. """ def startsWith(self, prefix): return self.find(prefix) is not None # V2 # Time: O(n), per operation # Space: O(1) class TrieNode(object): # Initialize your data structure here. def __init__(self): self.is_string = False self.leaves = {} class Trie(object): def __init__(self): self.root = TrieNode() # @param {string} word # @return {void} # Inserts a word into the trie. def insert(self, word): cur = self.root for c in word: if not c in cur.leaves: cur.leaves[c] = TrieNode() cur = cur.leaves[c] cur.is_string = True # @param {string} word # @return {boolean} # Returns if the word is in the trie. def search(self, word): node = self.childSearch(word) if node: return node.is_string return False # @param {string} prefix # @return {boolean} # Returns if there is any word in the trie # that starts with the given prefix. def startsWith(self, prefix): return self.childSearch(prefix) is not None def childSearch(self, word): cur = self.root for c in word: if c in cur.leaves: cur = cur.leaves[c] else: return None return cur