blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
0e1f1a1014983d50fc7f5395cda3c1cc186ba429
silverfox516/play
/python/closer.py
503
3.59375
4
def outer_func(tag): tag = tag def inner_func(txt): print '<{0}>{1}<{0}>'.format(tag, txt) return inner_func my_func = outer_func('my') print my_func print print dir(my_func) print print type(my_func.__closure__) print print my_func.__closure__ print print my_func.__closure__[0] print print dir(my_func.__closure__[0]) print print my_func.__closure__[0].cell_contents print print '-' * 80 h1_func = outer_func('h1') p_func = outer_func('p') h1_func('hello') p_func('world')
5eee8ba7adc1dbd83cec993eb6ce5e44dc42f105
davesheils/Project
/project2018.py
4,995
3.734375
4
# import modules import numpy as np import statistics as stat import pandas as pd import matplotlib.pyplot as plt import seaborn as sns # code to clear screen. Use clear if Unix, cls if windows (plese note: tested on Linux only) def clearscreen(): import platform import os if platform.system() == "Windows": os.system('cls') else: os.system('clear') clearscreen() print("Welcome to project 2018") input("Press Enter to run the first section of code, i.e. using numpy to ouput stats about each column in the iris dataset.") # Part 1 - Numpy test # www.numpy.org iris = np.genfromtxt('iris.csv', delimiter =',') # create a list called header with the column names header = ["Sepal length (cm)","Sepal width (cm)","Petal length (cm)","Petal width (cm)","Class"] print("The following is the list of column headers in the iris dataset. Please note they are not in the original dataset") for item in header: print(f"\t {item}") print("This following code will test some of the features of numpy.") print("The code will loop through the first four columns which contain numberic data and calculate the mode, mean, median, maximum and minimum values and standard deviation.") print() print("The following sections list items of significance about each column containing numerical data to 2dp.") print() # Following loop will print the mean, median, mode and standard deviation of columns 0 - 3 for i in range (4): print(header[i]) print(f"\t The most common value is {stat.mode(iris[:,i])}.") print(f"\t The median is {round(np.median(iris[:,i]),2)}.") print(f"\t The average value is {round(np.mean(iris[:,i]),2)}.") print(f"\t The maximum value is {round(np.max(iris[:,i]),2)}.") print(f"\t The minimum value is {round(np.min(iris[:,i]),2)}.") print(f"\t The standard deviation is {round(np.std(iris[:,i]),2)}.") print() input("Press Enter to run the next section of code:") clearscreen() print("The next section uses the pandas data analysis modules to further investigate the iris dataset.") print("Note that this code uses the iris2.csv file, the iris dataset with a header row added.") print("The aim of this section is to explore the concept of a dataframe.") print() # Using Pandas to load contents of csv into data frame, # https://pandas.pydata.org # https://pandas.pydata.org/pandas-docs/stable/10min.html # loads the contents of iris2.csv ino a data frame called iris. iris = pd.read_csv('iris2.csv') # https://stackoverflow.com/questions/19482970/get-list-from-pandas-dataframe-column-headers?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa headerlist= iris.columns.values.tolist() print("The following uses the head and tail methods to show the top and bottom rows of the frame") print() print(iris.head()) print() print(iris.tail()) print() # Select contents of the frame that meet specific criteria print("The following is the first five records of subset of the dataset where class = 'Iris-versicolor:\n") print(iris[iris['Class'] == 'Iris-versicolor'].head()) # https://datascience.stackexchange.com/questions/22266/summary-statistics-by-category-using-python print("The following code will use the groupby method to group data by class and tell us facts of significance about each of the three classes of Iris") print("The following simply returns the number of records/observations by class") print() print(iris.groupby('Class').size()) print() print("The following returns the mean of each column grouped by class") print() print(iris.groupby('Class').agg({'Sepal length': np.mean, 'Sepal width': np.mean, 'Petal length': np.mean, 'Petal width':np.mean})) print() print("The following will use the 'describe' in conjunction with the groupby method to output summary statistics from each column, by class of iris") print() for i in range(0,4): # https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.describe.html# print(headerlist[i]) print(iris.groupby('Class')[headerlist[i]].describe()) print() input("Press Enter to run the next section of code, data visualization examples:") clearscreen() #Create scatter plot, x = petal length, y = petal width # iris = pd.read_csv('iris2.csv') x = iris['Petal length'] y = iris['Petal width'] plt.title("Iris data set: Petal length vs Petal width (all classes)") plt.xlabel("Petal length") plt.ylabel("Petal width") scatter = plt.scatter(x,y) plt.show(scatter) # bx = iris.boxplot(column = 'Sepal length', vert = False, by = 'Class') plt.show(bx) # The following closely follows the Seaborn example from # https://www.kaggle.com/vasanthreddy/data-visualisation-of-iris-dataset plt.subplot(2,2,1) sns.boxplot(x="Class", y="Sepal length", data=iris) plt.subplot(2,2,2) sns.boxplot(x="Class", y="Sepal width", data=iris) plt.subplot(2,2,3) sns.boxplot(x="Class", y="Petal length", data=iris) plt.subplot(2,2,4) sns.boxplot(x="Class", y="Petal width", data=iris) plt.show()
6c56497b596ce6c618e4133422e3d9d8f695a6c3
rcolina17/guessgame
/main.py
1,329
3.90625
4
import random def humanguess(): number=random.randrange(0,10) print(number) numero=-1 while numero!=number: numero=int(input("Dame un numero del 1 al 10 ")) if number==numero: print(f"Felicidades ganaste {number}") elif number > numero: print(f"El numero {number} es mayor") else: print(f"El numero {number} es menor") humanguess() def computerGuess(): #Escogi el 500 firstNumber=0 secondNumber=1000 number=random.randrange(firstNumber,secondNumber) bandera=False while(bandera==False): print (number) print ("Este es tu numero?") opc=input("si | no: ").lower() if (opc =="no"): print("Tu numero es mayor o menor al mio?") opc2=input("mayor | menor: ").lower() if(opc2=="menor"): secondNumber=number newNumber=random.randrange(firstNumber,secondNumber)#el de la computadora es mayor number = newNumber else:#en caso de que sea mayor firstNumber=number newNumber=random.randrange(firstNumber,secondNumber) number=newNumber else: bandera=True print('Ganaste') computerGuess()
752733c3adc2f467ccae8a91dce6d73e6b672101
tanjina-3ni/PythonCodes
/randomIntInaRange.py
272
3.765625
4
# -*- coding: utf-8 -*- """ Created on Sun Jan 19 09:13:49 2020 @author: Aspire """ import random x=[] y=[] for z in range(0,20): x.append(random.randrange(0, 15)) for z in range(0,20): y.append(random.randrange(0, 15)) print (x) print (y)
8513413b804dff72a09ab9efafafc55f2d5b5be1
paul0920/leetcode
/question_leetcode/1087_3.py
942
3.59375
4
def expand(s): """ :type s: str :rtype: List[str] """ if not s: return [] res = [] dfs(0, s, [], res) return sorted(res) def get_char_to_expand(index, s): stack = [] close_bracket_index = None for i in range(index, len(s)): char = s[i] if char == ",": continue elif char == "}": close_bracket_index = i return stack, close_bracket_index stack.append(char) def dfs(index, s, path, res): if index == len(s): res.append("".join(path)) elif s[index] == "{": stack, close_bracket_index = get_char_to_expand(index + 1, s) for char in stack: path.append(char) dfs(close_bracket_index + 1, s, path, res) path.pop() else: path.append(s[index]) dfs(index + 1, s, path, res) path.pop() s = "{a,b}c{d,e}f" print expand(s)
6fd40ca0afa28e7e94d5e837d1949ac71531c421
katryo/leetcode
/5-longest-palindromic-substring/solution.py
2,594
3.546875
4
class Solution(object): # def longestPalindrome(self, s): # """ # :type s: str # :rtype: str # """ # # if not s: # return "" # if len(s) == 1: # return s # # table = [[-1] * len(s) for _ in range(len(s))] # # def palindrome_length(left, right): # if left == right: # return 1 # if table[left][right] != -1: # return table[left][right] # if s[left] == s[right]: # if left + 1 == right: # ret = 2 # elif palindrome_length(left+1, right-1) == right-left-1: # ret = 2 + palindrome_length(left+1, right-1) # else: # ret = max(palindrome_length(left+1, right), # palindrome_length(left, right-1)) # else: # ret = max(palindrome_length(left+1, right), # palindrome_length(left, right-1)) # table[left][right] = ret # return ret # # max_length = palindrome_length(0, len(s)-1) # i = 0 # j = len(s)-1 # while i < j and palindrome_length(i+1, j) == max_length: # i += 1 # while i < j and palindrome_length(i, j-1) == max_length: # j -= 1 # # return s[i:j+1] def longestPalindrome(self, s): """ :type s: str :rtype: str """ if not s: return "" def expand(left, right): while left > 0 and right < len(s)-1 and s[left-1] == s[right+1]: left -= 1 right += 1 return s[left:right+1] def expand_odd(center): return expand(center, center) def expand_even(center_left): if s[center_left] == s[center_left+1]: return expand(center_left, center_left+1) else: return "" ans = s[0] for i in range(len(s)-1): candidate = expand_odd(i) if len(candidate) > len(ans): ans = candidate candidate_even = expand_even(i) if len(candidate_even) > len(ans): ans = candidate_even return ans s = Solution() print(s.longestPalindrome("abcda")) print(s.longestPalindrome("ac")) print(s.longestPalindrome("babad")) print(s.longestPalindrome("cbbd")) print(s.longestPalindrome("abcdbcbaw")) thousand = "z" * 1000 print(s.longestPalindrome(thousand))
3a391de27d17f6f24441b494e07f3f09995aa426
Jyldyzbek/T2Part22
/task-22.py
215
3.78125
4
tF = int(input('Vedite °F: ')) tC = int(input('Vedite °C: ')) TC = 5/9 * (tF - 32) TF = 9/5 * tC + 32 print('Celsius', round(TC, 2)) print('Farengate', round(TF, 2)) # a = (32 °F − 32) × 5/9 = 0 °C
ff6d4843be5d281eeef09d19185477348ff35a51
jrclayton/RosalindProblems
/Bioinformatics Stronghold/010_FIBD/FIBD.py
1,821
3.59375
4
#!/usr/bin/python # This approach will use a loop if else loop to split the relations # based on the input values of n and m #def fib(n, m): # if n < m: # # Use relation A # if n == 0: # return 0 # elif n == 1: # return 1 # elif n > 1: # return fib(n-1, m) + fib(n-2, m) # result from relation A # elif n == m or n == m+1: # # Use relation B # if n == 0: # return 0 # elif n == 1: # return 1 # elif n > 1: # return fib(n-1, m) + fib(n-2, m) - 1 # result from relation B # elif n > m + 1: # # Use relation C # if n == 0: # return 0 # elif n == 1: # return 1 # elif n > 1: # return fib(n-1, m) + fib(n-2, m) - fib(n-(m+1), m) # result from relation C ### THE ABOVE ALGORITHM HANGS, I THINK BECAUSE IT RELIES ON RECURSION AND MEMORY ALLOCATION ### IS NOT DONE PROPERLY. JUST A GUESS. #run for n months, rabbits die after m months. total = [1, 1] #Seed the sequence with the 1 pair, then in their reproductive month. def fib(n, m): count = 2 while count < n: if count < m: #recurrence relation before rabbits start dying (simply fib seq Fn = Fn-2 + Fn-1) total.append(total[-2] + total[-1]) elif count == m or count == m+1: #Base cases for subtracting rabbit deaths (1 death in first 2 death gens) total.append((total[-2] + total[-1]) - 1)#Fn = Fn-2 + Fn-1 - 1 else: #Our recurrence relation here is Fn-2 + Fn-1 - Fn-(j+1) total.append((total[-2] + total[-1]) - (total[-(m+1)])) count += 1 return (total[-1]) infile = open("rosalind_fibd.txt", "r") outfile = open("output.txt", "w") params = infile.read().strip() infile.close() n = int(params.split()[0]) m = int(params.split()[1]) final_number = fib(n, m) print final_number outfile.write(str(final_number)) outfile.close()
2097fb154f51b06df22b9ff0eccbe5b2564cf89e
SerikDanaaa/Python_
/TSIS9/paint.py
5,958
3.625
4
# Paint import pygame, random import os pygame.init() # (x1, y1), (x2, y2) # A = y2 - y1 # B = x1 - x2 # C = x2 * y1 - x1 * y2 # Ax + By + C = 0 # (x - x1) / (x2 - x1) = (y - y1) / (y2 - y1) def drawLine(screen, start, end, width, color): x1 = start[0] y1 = start[1] x2 = end[0] y2 = end[1] dx = abs(x1 - x2) dy = abs(y1 - y2) A = y2 - y1 B = x1 - x2 C = x2 * y1 - x1 * y2 if dx > dy: if x1 > x2: x1, x2 = x2, x1 y1, y2 = y2, y1 for x in range(x1, x2): y = (-C - A * x) / B pygame.draw.circle(screen, color, (x, y), width) else: if y1 > y2: x1, x2 = x2, x1 y1, y2 = y2, y1 for y in range(y1, y2): x = (-C - B * y) / A pygame.draw.circle(screen, color, (x, y), width) screen = pygame.display.set_mode((800, 600)) background = pygame.Surface((800,600)) background.fill((255,255,255)) screen.blit(background,(0,0)) def main(): mode = 'random' draw_on = False clear_on = False save = False last_pos = (0, 0) color = (255, 128, 0) radius = 10 font_big = pygame.font.Font(None , 20) font_small = pygame.font.Font(None , 16) colors = { 'red': (255, 0, 0), 'blue': (0, 0, 255), 'green': (0, 255, 0) } while True: rect_pos = pygame.Rect(20,10,40,30) for event in pygame.event.get(): if event.type == pygame.QUIT: return if event.type == pygame.KEYDOWN: # SAVE IMAGE if event.key == pygame.K_ESCAPE: save = True if event.key == pygame.K_y and save: pygame.image.save(background,os.path.join("images","saved_3.BMP")) return if event.key == pygame.K_n and save: return #CHANGE COLOR if event.key == pygame.K_r: mode = 'red' if event.key == pygame.K_b: mode = 'blue' if event.key == pygame.K_g: mode = 'green' if event.key == pygame.K_UP: radius += 1 if event.key == pygame.K_DOWN: radius -= 1 #RECTANGLE AND CIRCLE if event.key == pygame.K_1: rect() if event.key == pygame.K_2: circle() if event.type == pygame.MOUSEBUTTONDOWN: if event.button == 3: #RUBBER pygame.draw.circle(background,(255,255,255), event.pos, radius) clear_on = True if event.button == 1: if mode == 'random': color = (random.randrange(256), random.randrange(256), random.randrange(256)) else: color = colors[mode] pygame.draw.circle(background, color, event.pos, radius) draw_on = True if event.type == pygame.MOUSEBUTTONUP: draw_on = False clear_on = False if event.type == pygame.MOUSEMOTION: if draw_on: drawLine(background, last_pos, event.pos, radius, color) # pygame.draw.circle(screen, color, event.pos, radius) if clear_on: drawLine(background, last_pos, event.pos, radius,(255,255,255)) last_pos = event.pos screen.fill((49,51,53)) if save: pygame.draw.rect(screen,(255,255,255),(650,5,150,40)) text = font_big.render("Do you want to save ?", True,(0,0,0)) text_yes = font_small.render("press y if yes", True,(0,0,0)) text_no = font_small.render("press n if no", True,(0,0,0)) screen.blit(text,(655,10)) screen.blit(text_yes,(655,22)) screen.blit(text_no,(655,32)) pygame.draw.rect(screen,(255,255,255),rect_pos,2) pygame.draw.circle(screen,(255,255,255),(90,25),20,2) text = font_small.render(" 1 ", True, (255,255,255)) screen.blit(text,(21,15)) text = font_small.render(" 2 ", True, (255,255,255)) screen.blit(text,(70,15)) screen.blit(background,(0,50)) pygame.display.flip() pygame.quit() def rect(): # DRAW RECTANGLE run = True while run: rx, ry = pygame.mouse.get_pos() for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: run = False if event.type == pygame.MOUSEBUTTONDOWN: if event.button == 1: pygame.draw.rect(background, (0, 0, 0), (rx, ry, random.randint(5, 200), random.randint(5, 200)), 2) pygame.display.flip() return def circle(): # DRAW CIRCLE run = True while run: cx, cy = pygame.mouse.get_pos() for event in pygame.event.get(): if event.type == pygame.QUIT: run = False if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: run = False if event.type == pygame.MOUSEBUTTONDOWN: if event.button == 1: pygame.draw.circle(background, (0, 0, 0), (cx, cy), random.randint(5, 100), 2) pygame.display.flip() return main() # rect = pygame.Rect(10, 20, 30, 50) # print(rect.bottom) # print(rect.top) # print(rect.left) # print(rect.right) # print(rect.bottomleft) # print(rect.bottomright) # print(rect.center)
94b150c97723def2d0010b0ee6f959a22bd3240d
sidmadethis/files_exceptions
/file_reader.py
1,015
4.40625
4
# with open('pi_digits.txt') as file_object: # contents = file_object.read() # print(contents) # this opens the pi digits file, reads it, and then prints out the text to the screen. # you first need to open the file to access it. the open() function needs one argument, the name of the file. python looks for this file in the same directory that the python program is running in. # the with keyword will close the file once access to it is no longer needed. you could use close() but this can lead to easy mistakes # if this file wasn't in the same directory as the python program, you could give a relative file path. # with open('text_files/filename.txt') as file_object # Or use the full file path if needed # filename = 'pi_digits.txt' # # with open(filename) as file_object: # for line in file_object: # print(line.rstrip()) filename = 'pi_digits.txt' with open(filename) as file_object: lines = file_object.readlines() for line in lines: print(line.rstrip())
6405c37942bec9d8978455434b3f365edb1aea3a
harry4401/30DayOfPython
/Day-10/Day_10_Mohit.py
168
4.09375
4
#sum of the n natural numbers i =int(input("Enter the number : ")) sum = 0 for i in range(0,int(i)+1): sum = sum+i print(sum," is the sum of ",i," numbers.")
f9b085edb91f8408386f6f16b51512d76e5b6e97
ifpb-cz-ads/pw1-2021-2-ac-s4-team_denis
/questao_07.py
263
4.03125
4
#7. Faça um programa que peça dois números inteiros. Imprima a soma desses dois números na tela. numero1= int(input("Informe o 1ª numero:")) numero2= int(input("Informe o 2ª numero:")) print('A soma de',numero1,'+',numero2,'é igual a:',numero1+numero2)
1e6056ea938feb355802b29a10128a119a16f806
akshat-52/FallSem2
/act1.27/9.py
142
3.640625
4
my_tuple=('a','p','p','l','e') print(my_tuple.count('p')) print(my_tuple.count('e')) print(my_tuple.index('p')) print(my_tuple.index('e'))
87dead39db7e8e6bf6902ae72aa34ecbbefd3f29
whosedaddy/Learn_python_the_hard_way
/learn_python/recursive.py
130
3.640625
4
def re(n,f,t,s): if n==1: print "From %s to %s."%(f,t) else: re(n-1,f,s,t) re(1,f,t,s) re(n-1,s,t,f) re(10,'f','t','s')
18fe5bd8730a5749e445668c4b31b2fc30715f7e
phillipfranco55/The-Beginning
/strings_and_methods_excercises.py
599
3.6875
4
# Was asked to create a string, school with the name of my elementary school. # Examine the methods that are available on that string. Use the help function. # So I viewed the methods with the dir function, picked the first on the list and # .casefold() lists all the methods with there help() file. school = 'Jackson' print(dir(school)) print(help(''.casefold())) print() country = 'usa' correct_country = country.upper() print(correct_country) print() filename = 'hello.py' print(filename.endswith('.java')) print(filename.index('.py')) print(filename.endswith('world')) print(type(school))
7ce46401826d19c36c52b217095cfcd5088e3338
Crigerprogrammer/Algebra_Lineal
/suma_vectores_numpy.py
785
3.875
4
import numpy as np rojo = [255,0,0] verde = [0,255,0] azul = [0,0,255] negro = [0,0,0] # Numpy tiene una estructura de datos llamado numpy arrays y se pueden crear con la propiedad array # Los numpy array tienen las propiedades de un vector y su suma puede ser como los vectores algebraicos rojo = np.array(rojo) verde = np.array(verde) azul = np.array(azul) print('La suma de los numpy array rojo mas verde es: ', rojo+verde) # Ejercicio de clase #6 # vector a = [0,0,255] es el color azul # Color al sumar rojo verde y azul print('La suma de los vectores, rojo, verde y azul es: ', rojo+verde+azul) # Color sumando rojo y verde print('La suma de los vectores, rojo y verde es: ', rojo+verde) # Color sumando negro - azul es: print('La suma negro menos azul es: ', negro-(+azul))
6401c8f67b8a72fd50e7e492d3dd86411ca3e39d
raydot/coursera
/mathThinkingInCoSci/wk02more_puzzles.py
314
3.671875
4
# ∃ a six-digit number that starts with 100 and is divisible by 9,127 # x = 0 for y in range(0, 999): if (y < 10): candidate = '10000' + str(y) elif(y < 100): candidate = '1000' + str(y) else: candidate = '100' + str(y) # print(candidate) if (int(candidate) % 9127 == 0): print(candidate)
079275c5102d56c6eebd3a7a82a90c2cdb58fcf4
cczhong11/Leetcode-contest-code-downloader
/Questiondir/717.1-bit-and-2-bit-characters/717.1-bit-and-2-bit-characters_125771223.py
423
3.53125
4
class Solution(object): def isOneBitCharacter(self, bits): """ :type bits: List[int] :rtype: bool """ can = [False]*(len(bits)+1) can[0] = True for i in range(len(bits)-1): if can[i]: if bits[i] == 0: can[i+1] = True else: can[i+2] = True return can[len(bits)-1]
696492506f69be4e3d9aafd0ea042d3ade185acd
pointschan/pylearning
/listComprehension.py
784
4.28125
4
__author__ = 'pointschan' #to create a list of squares squares = [] for x in range(10): squares.append(x**2) print squares #create the same list of squares as above squares = [x**2 for x in range(10)] print squares #can also use built-in function map() and lambda expression #map(function, sequence) squares = map(lambda x: x**2, range(10)) print squares # A list comprehension consists of brackets containing an expression followed by a for clause, # then zero or more for or if clauses. The result will be a new list resulting from evaluating # the expression in the context of the for and if clauses which follow it. For example, this # listcomp combines the elements of two lists if they are not equal: li = [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y] print li
5aea24a1f0f564fc3d96667895c71401485770a2
Borlander5/PythonClass
/shep/city_functions.py
837
3.859375
4
#11-1. """A collection of functions for working with cities.""" def city_country(city, country): """Return a string like 'Santiago, Chile'.""" return f"{city.title()}, {country.title()}" #11-2. """A collection of functions for working with cities.""" def city_country(city, country, population): """Return a string like 'Santiago, Chile - population 5000000'.""" output_string = f"{city.title()}, {country.title()}" output_string += f" -population {population}" return output_string """A collection of functions for working with cities.""" def city_country(city, country, population=0): """Return a string representing a city-country pair.""" output_string = f"{city.title()}, {country.title()}" if population: output_string += f" - population {population}" return output_string
ac25e58d6056ef6082df4e2428fadbbf71420107
daikiante/python
/43_func_default.py
503
3.75
4
# functions with the default values def greet(name='lohit',age=20,country='India',work='spiceup'): print(f'my name is {name}, my age is {age}, from {country}, I working {work}') greet() greet('daiki',23,'Japan','student') print('--------------------------------') def calls(name='lohit'): print(name) calls(name='sei') print('--------------------------------') def get_sum(num_1=5,num_2=10): print(num_1 * num_2) num_1 = input('Enter num 1 :') num_2 = input('Enter num 2 :')
6294736f106dda0a0c1861794e66214c5e2816d3
carloseduardo1987/Python
/ex20_lista02.py
772
3.9375
4
print('### Calculadora de média escolar ###') n1 = float(input('\nInforme a primeira nota bimestral: ')) n2 = float(input('Informe a segundo nota bimestral: ')) n3 = float(input('Informe a terceira nota bimestral: ')) n4 = float(input('Informe a quarta nota bimestral: ')) md1 = (n1+n2+n3+n4)/4 print(f'\nO valor da média obtida pelo aluno foi { round(md1, 2) }') if md1 >= 7 : print('Aprovado') elif md1 < 7 : ne = float(input('\nInforme a quinta nota bimestral: ')) md2 = (ne + md1)/2 if md2 >= 5 : print('\nAPROVADO EM EXAME') print(f'\nO valor da média obtida pelo aluno foi { round(md2, 2) }') else : print('\nREPROVADO') print(f'\nO valor da média obtida pelo aluno foi { round(md2, 2) }')
6873610a83ba0ddd0648a8052650627f72c093eb
AndreiRStamate/snekkk
/salut.py
13,586
3.5
4
import pygame import random import time def pause(): paused = True gameDisplay.fill(white) message_to_center("Game paused", black, -100, "large") message_to_center("Press 'p' to unpause or q to quit.", black, 25) pygame.display.update() clock.tick(5) while paused: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_p: paused = False if event.key == pygame.K_q or event.key == pygame.K_ESCAPE: pygame.quit() quit() def randAppleGen(): randAppleX = round(random.randrange(0, width - applethikness)) randAppleY = round(random.randrange(0, height - applethikness)) return randAppleX, randAppleY def game_intro(): intro = True while intro: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_c: intro = False if event.key == pygame.K_v: intro = False if event.key == pygame.K_q: pygame.quit() quit() gameDisplay.fill(white) message_to_center("Welcome to my game", green, -200, 'large') message_to_center("Eat the red apples and dont crash into yourself", black, -110) message_to_center("Eat them all", black, -70) message_to_center("C to play, p to pause, q to quit", black, 20) pygame.display.update() clock.tick(24) def text_objects(text, c, size): if size == "small": textsurface = smallfont.render(text, True, c) elif size == "medium": textsurface = medfont.render(text, True, c) elif size == "large": textsurface = largefont.render(text, True, c) return textsurface, textsurface.get_rect() def message_to_center(msg, c, y_displace=0, size="small"): textsurf, textrect = text_objects(msg, c, size) textrect.center = (width / 2), (height / 2) + y_displace gameDisplay.blit(textsurf, textrect) def message_to_corner(msg, c): screen_text = smallfont.render(msg, True, c) gameDisplay.blit(screen_text, [5, 1]) def message_to_corner2(msg, c): screen_text = smallfont.render(msg, True, c) gameDisplay.blit(screen_text, [width-150, 1]) def snake(block_s, snakelist): if direction == 'right': head = pygame.transform.rotate(snekimg, 270) if direction == 'left': head = pygame.transform.rotate(snekimg, 90) if direction == 'up': head = snekimg if direction == 'down': head = pygame.transform.rotate(snekimg, 180) gameDisplay.blit(head, (snakelist[-1][0], snakelist[-1][1])) for XnY in snakelist[:-5]: pygame.draw.rect(gameDisplay, green, [XnY[0], XnY[1], block_s, block_s]) def snake2(block_s, snakelist): if direction2 == 'right': head = pygame.transform.rotate(snek2img, 270) if direction2 == 'left': head = pygame.transform.rotate(snek2img, 90) if direction2 == 'up': head = snek2img if direction2 == 'down': head = pygame.transform.rotate(snek2img, 180) gameDisplay.blit(head, (snakelist[-1][0], snakelist[-1][1])) for XnY in snakelist[:-5]: pygame.draw.rect(gameDisplay, blue, [XnY[0], XnY[1], block_s, block_s]) pygame.init() icon = pygame.image.load('icon.png') snekimg = pygame.image.load('snakeHead.png') snek2img = pygame.image.load('snake2Head.png') appleimg = pygame.image.load('apple.png') smallfont = pygame.font.SysFont("comicsansms", 25) medfont = pygame.font.SysFont("comicsansms", 30) largefont = pygame.font.SysFont("comicsansms", 40) white = (255, 255, 255) black = (0, 0, 0) red = (255, 0, 0) green = (0, 205, 0) blue = (0, 162, 232) fps = 60 direction = 'up' direction2 = 'up' width = 800 height = 600 gameDisplay = pygame.display.set_mode((width, height)) speed = 4 speed2 = 4 block_size = 20 applethikness = 30 clock = pygame.time.Clock() pygame.display.set_caption(r"Slytherino.exe") pygame.display.set_icon(icon) pygame.display.update() def gameloop(mode_set): while mode_set is False: mode_crash = False mode_points = False gameDisplay.fill(white) message_to_center("X for crash, V for points", black) pygame.display.update() for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_x: mode_crash = True mode_set = True break elif event.key == pygame.K_v: mode_points = True mode_set = True break elif event.key == pygame.K_q: pygame.quit() quit() elif event.key == pygame.K_ESCAPE: pygame.quit() quit() if event.type == pygame.QUIT: pygame.quit() quit() global direction global direction2 global speed global speed2 lead_x = 400 lead_y = 300 lead_x2 = 500 lead_y2 = 400 lead_x_change = 0 lead_y_change = 0 lead_x2_change = 0 lead_y2_change = 0 points = 0 points2 = 0 point = 1 point2 = 1 player1crashed = False player2crashed = False s = 0 s2 = 0 p = 0 p2 = 0 cd = 0 cd2 = 0 dc = 0 dc2 = 0 cooldown = False cooldown2 = False cooldown_speed = False cooldown_speed2 = False randAppleX, randAppleY = randAppleGen() snakelist = [] snakelist2 = [] snakelength = 1 snakelength2 = 1 gamedone = False done = True gameover = False while gamedone is not done: while gameover: gameDisplay.fill(white) message_to_center("Game over", red, y_displace=-40, size='large') message_to_center("Press c to play again or q to quit", black, y_displace=20, size='medium') text = "The green snek ate 50 apples first, the best apple eater in the world" text2 = "The blue snek ate 50 apples first, the best apple eater in the world" if points >= 50: message_to_center(text, green, y_displace=60) if points2 >= 50: message_to_center(text2, blue, y_displace=60) if player1crashed: message_to_center("Mr Blue WON!!!", blue, y_displace=80) if player2crashed: message_to_center("Mr Green WON!!!", green, y_displace=80) for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_c: gameloop(f) if event.key == pygame.K_q: gameover = False gamedone = True pygame.display.update() for event in pygame.event.get(): if event.type == pygame.QUIT: gamedone = True if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE or event.key == pygame.K_q: gamedone = True if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: lead_y_change = 0 lead_x_change = -speed direction = "left" elif event.key == pygame.K_RIGHT: lead_y_change = 0 lead_x_change = speed direction = "right" elif event.key == pygame.K_UP: lead_x_change = 0 lead_y_change = -speed direction = "up" elif event.key == pygame.K_DOWN: lead_x_change = 0 lead_y_change = speed direction = "down" elif event.key == pygame.K_a: lead_y2_change = 0 lead_x2_change = -speed2 direction2 = 'left' elif event.key == pygame.K_d: lead_y2_change = 0 lead_x2_change = speed2 direction2 = 'right' elif event.key == pygame.K_w: lead_x2_change = 0 lead_y2_change = -speed2 direction2 = 'up' elif event.key == pygame.K_s: lead_x2_change = 0 lead_y2_change = speed2 direction2 = 'down' elif event.key == pygame.K_KP0: if cooldown_speed is False and mode_points is True: speed = 6 cooldown_speed = True elif event.key == pygame.K_f: if cooldown_speed2 is False and mode_points is True: speed2 = 6 cooldown_speed2 = True elif event.key == pygame.K_KP1: if cooldown is False and mode_points is True: point = 3 cooldown = True elif event.key == pygame.K_r: if cooldown2 is False and mode_points is True: point2 = 3 cooldown2 = True elif event.key == pygame.K_p: pause() lead_x += lead_x_change lead_y += lead_y_change lead_x2 += lead_x2_change lead_y2 += lead_y2_change lead_x %= width lead_y %= height lead_x2 %= width lead_y2 %= height snakehead = [lead_x, lead_y] snakelist.append(snakehead) snakehead2 = [lead_x2, lead_y2] snakelist2.append(snakehead2) gameDisplay.fill(white) gameDisplay.blit(appleimg, (randAppleX, randAppleY)) if len(snakelist) > snakelength: del snakelist[0] if len(snakelist2) > snakelength2: del snakelist2[0] snake(block_size, snakelist) snake2(block_size, snakelist2) pygame.display.update() if mode_crash: if snakehead in snakelist2[:-1]: player1crashed = True gameover = True if snakehead2 in snakelist[:-1]: player2crashed = True gameover = True if randAppleX < lead_x < randAppleX + applethikness or randAppleX < lead_x + block_size < randAppleX + applethikness: if randAppleY < lead_y < randAppleY + applethikness or randAppleY < lead_y + block_size < randAppleY + applethikness: randAppleX, randAppleY = randAppleGen() snakelength += 5 points += point if randAppleX < lead_x2 < randAppleX + applethikness or randAppleX < lead_x2 + block_size < randAppleX + applethikness: if randAppleY < lead_y2 < randAppleY + applethikness or randAppleY < lead_y2 + block_size < randAppleY + applethikness: randAppleX, randAppleY = randAppleGen() snakelength2 += 5 points2 += point2 if points >= 50 or points2 >= 50: gameover = True if mode_points: if speed == 6: s += 1 if s >= fps*5: speed = 4 s = 0 cooldown_speed = True if speed2 == 6: s2 += 1 if s2 >= fps*5: speed2 = 4 s2 = 0 cooldown_speed2 = True if cooldown_speed: cd += 1 if cd >= fps*15: cooldown_speed = False cd = 0 if cooldown_speed2: cd2 += 1 if cd2 >= fps*15: cooldown_speed2 = False cd2 = 0 if point == 3: p += 1 if p >= fps*5: point = 1 p = 0 cooldown = True if point2 == 3: p2 += 1 if p2 >= fps*5: point2 = 1 p2 = 0 cooldown2 = True if cooldown: dc += 1 if dc >= fps*15: cooldown = False dc = 0 if cooldown2: dc2 += 1 if dc2 >= fps*15: cooldown2 = False dc2 = 0 message_to_corner("points: " + str(points), black) message_to_corner2("points: " + str(points2), black) pygame.display.update() clock.tick(fps) message_to_center("Developed by me", black, y_displace=0, size='small') pygame.display.update() time.sleep(0.35) pygame.quit() quit() f = False t = True game_intro() gameloop(f)
d5a979d02f31cf7c056ed274c95b5329ebc9908e
cortadocodes/machine-learning
/machine_learning/logistic_regression/logistic_regression.py
3,447
3.8125
4
import numpy as np class LogisticRegressionWithGradientDescent: """An adaptive linear neuron implementation of logistic regression; an improvement on the perceptron; uses gradient descent of the logistic cost function (log-likelihood) to arrive at the global cost minimum. Type: supervised - binary classification. Notes: * Uses a sigmoid activation function in calculating errors """ def __init__(self, learning_rate = 0.01, number_of_training_iterations = 50, random_state_seed = 1): """Initialise an adaptive linear neuron that uses gradient descent. Note that for the learning rate to have an effect on the classification outcome, the weights must be initialised to non-zero values. :param float learning_rate: should be between 0 and 1 :param int number_of_training_iterations: :param int random_state_seed: for random weight initialisation :var np.array weights: internal weights of the AdaptiveLinearNeuronWithGradientDescent :var list(int) errors_per_epoch: number of mis-classifications (updates) in each epoch """ self.learning_rate = learning_rate self.number_of_training_iterations = number_of_training_iterations self.random_state = random_state_seed self.weights = np.array([]) self.cost = [] def fit(self, samples, targets): """Fit the neuron to the training data. :param np.array samples: samples in a matrix of shape (n_samples, n_features) :param np.array targets: target values in a vector of shape (n_samples) :return AdaptiveLinearNeuronWithGradientDescent: """ random_number_generator = np.random.RandomState(self.random_state) self.weights = random_number_generator.normal(loc = 0.0, scale = 0.01, size = 1 + samples.shape[1]) self.cost = [] for i in range(self.number_of_training_iterations): net_input = self.net_input(samples) errors = targets - self.activation(net_input) self.weights[0] += self.learning_rate * errors.sum() self.weights[1:] += self.learning_rate * samples.T.dot(errors) self.cost.append(self.calculate_cost(net_input, targets)) return self def net_input(self, samples): """Calculate the net input of a sample into the neuron. :param np.array samples: shape (n_samples, n_features) :return float: """ return self.weights[0] + np.dot(samples, self.weights[1:]) def activation(self, net_input): """Calculate the sigmoid activation of the net input. :param np.array net_input: shape (n_samples) :return np.array: """ return 1 / (1 + np.exp(-np.clip(net_input, -250, 250))) def calculate_cost(self, net_input, targets): """Calculate the value of the cost function. :param np.array errors: shape (n_samples) :return float: """ return - ( targets.dot(np.log(self.activation(net_input))) + (1 - targets).dot(np.log(1 - self.activation(net_input))) ) def predict(self, samples): """Classify a sample according to the decision function (a Heaviside step function). :param np.array sample: shape (n_samples, n_features) :return np.array: """ return np.where(self.activation(self.net_input(samples)) >= 0, 1, 0)
74864c19ac096567aad04fe94f78ef43f7c67c3b
JosephLevinthal/Research-projects
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/226/users/4127/codes/1637_2447.py
181
3.796875
4
pc= float(input("qual o valor do produto?")) pgm= float(input("qual o valor do pagamento?")) if (pc>pgm): print("Falta",round(pc-pgm,2)) else: print("Troco de",round(pgm-pc,2))
fe7f84702f9469b466cd304ad7bfd5d80c081525
NanZhang715/AlgorithmCHUNZHAO
/Week_01/merge.py
1,662
4.125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ 给你两个有序整数数组 nums1 和 nums2,请你将 nums2 合并到 nums1 中,使 nums1 成为一个有序数组。 初始化 nums1 和 nums2 的元素数量分别为m 和 n 。你可以假设 nums1 有足够的空间(空间大小等于 m + n)来保存 nums2 中的元素。 例 1: 输入:nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3 输出:[1,2,2,3,5,6] 链接:https://leetcode-cn.com/problems/merge-sorted-array """ from typing import List class Solution: def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: """ Do not return anything, modify nums1 in-place instead. 思路:双指针 依次从后向前遍历,依次取最大的放入 nums1 中 """ left, right = m - 1, n - 1 p = len(nums1) - 1 while left >= 0 and right >= 0: if nums1[left] > nums2[right]: nums1[left], nums1[p] = nums1[p], nums1[left] left -= 1 else: nums2[right], nums1[p] = nums1[p], nums2[right] right -= 1 p -= 1 # 如果 right < 0, 说明 nums2 的元素已经全部放入 nums1 中,即任务终止 # 如果 right >=0 ,将 nums2 中任务元素 放入nums1相应位置即可 if right >= 0: nums1[:right + 1] = nums2[:right + 1] return if __name__ == '__main__': # nums1, m = [1, 2, 3, 0, 0, 0], 3 # nums2, n = [2, 5, 6], 3 nums1, m = [0], 0 nums2, n = [1], 1 Solution().merge(nums1, m, nums2, n) print("result is ", nums1)
1893c6d3402d7e8d599a59fe001b37973ab13d54
PavloBryliak/Lab_14
/fourth/game.py
1,099
3.609375
4
import random from fourth.board import Board, computer def determine(board, player): a = -2 choices = [] if len(board.available_moves()) == 9: return 4 for move in board.available_moves(): board.make_move(move, player) val = board.alphabeta(board, computer(player), -2, 2) board.make_move(move, None) if val > a: a = val choices = [move] elif val == a: choices.append(move) return random.choice(choices) if __name__ == "__main__": board = Board() board.show() while not board.complete(): player = 'X' player_move = int(input("Next Move: ")) - 1 if not player_move in board.available_moves(): continue board.make_move(player_move, player) board.show() if board.complete(): break player = computer(player) computer_move = determine(board, player) board.make_move(computer_move, player) board.show() print(board.winner(), "won!")
0297d733f593fa9bbddc0fb0ccd3ddb06c1a9b15
CircularWorld/Python_exercise
/month_01/day_06/homework_06/homework_04.py
225
3.90625
4
''' 4. 将列表中的数字累减 list02 = [5, 1, 4, 6, 7, 4, 6, 8, 5] 提示:初始为第一个元素 ''' list02 = [5, 1, 4, 6, 7, 4, 6, 8, 5] result = list02[0] for num in list02: result -= num print(result)
392a4ee2ce75643a600b866a499793af465ae835
adityachhajer/LeetCodeSolutions
/56MergeIntervals.py
624
3.65625
4
class Solution: def merge(self, intervals: List[List[int]]) -> List[List[int]]: if intervals == []: return [] intervals.sort() stack = [] stack.append(intervals[0]) for i in range(1, len(intervals)): if intervals[i][0] > stack[-1][1]: stack.append(intervals[i]) else: if intervals[i][0] >= stack[-1][0]: if intervals[i][1] <= stack[-1][1]: continue else: stack[-1][1] = intervals[i][1] return stack
984c16e14a8b86945f5a728163c10c515812e641
Vasilic-Maxim/LeetCode-Problems
/problems/13. Roman to Integer/1 - Two Pointers.py
518
3.625
4
class Solution: """ n - length of the string Time: O(n) Space: O(1) """ def romanToInt(self, s: str) -> int: vocab = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000} slow = fast = len(s) - 1 result = 0 while fast >= 0: s_val = vocab[s[slow]] f_val = vocab[s[fast]] result += -f_val if s_val > f_val else f_val slow = slow if s_val > f_val else fast fast -= 1 return result
476d0c4232eaef3a97c4d2c4d603c2529f940e6f
shaoye/algorithm
/jianzhioffer/顺时针打印矩阵.py
258
3.65625
4
class Solution: # matrix类型为二维列表,需要返回列表 def printMatrix(self, matrix): ret = [] while matrix: ret.extend(matrix.pop(0)) matrix = list(zip(*matrix))[::-1] return ret
8e0f12e981e9298065ac13fe81abd90f95edf2fc
aizhan00000/game
/lection19.py
2,273
3.78125
4
# class CLassName: # # a = 5 # # b = 5 # # # # def __init__(self, hp): # # self.hp = hp # # # # def __del__(self): # # print("IAS") # # # # def print_hp(self): # # print(self.hp) # # print(self.a) # # # # # # class ClassName2(CLassName): # # def print_hp(self): # # print(self.a) # # # # '' # # a = CLassName(10) # # print(a.hp) # # a.print_hp() # # del a # # # # b = ClassName2(90) # # print(b.b) # # b.print_hp() # # class A: # a = 10 # # def __init__(self, name, country, grade, age): # self.name = name # self.grade = grade # self.country = country # self.age = age # # # class B: # b = 15 # # class C: # a = 50 # c = 90 # # class D(C, B, A): # def __init__(self, surname, *args): # super().__init__(*args) # self.surname = surname # # # def some_method(self, some_arg): # print(some_arg) # # d = D('Name', "Surname", 1, 11, 'ojd') # print(d.name) # print(d.age) # # d.some_method(10) def sum_nums(a, b): return a + b def minus(a, b): return a - b def div(a, b): return a / b def multiply(a, b): return a * b def main(): counter = 0 file = open('resultd.csv', 'a') while answer == 'y': counter +=1 file = open('resultd.csv', 'a') try: a, b = input("enter 2 nums with ',' : ").split(',') a, b = int(a), int(b) user_choice = input("Choose * / + - : ") file.write(f'Result {counter},') if user_choice == '+': sum_num = (sum_nums(a, b)) file.write(str(sum_num)) if user_choice == '-': minus_num = (minus(a, b)) file.write(str(minus_num)) if user_choice == '*': multiply_num = (multiply(a, b)) file.write(str(multiply_num)) if user_choice == '/': div_num = (div(a, b)) file.write(str(div_num)) # file.write(',') except TypeError: print("There is a mistake in your code ") finally: file.write(',') file.close() answer = input("continue y/n: ").lower() main()
2cb2e456fbe8389d82009c8db7ca975d97d7f281
lobzison/python-stuff
/AT/clustering.py
6,765
4.03125
4
""" Student template code for Project 3 Student will implement five functions: slow_closest_pair(cluster_list) fast_closest_pair(cluster_list) closest_pair_strip(cluster_list, horiz_center, half_width) hierarchical_clustering(cluster_list, num_clusters) kmeans_clustering(cluster_list, num_clusters, num_iterations) where cluster_list is a 2D list of clusters in the plane """ import alg_cluster ###################################################### # Code for closest pairs of clusters def pair_distance(cluster_list, idx1, idx2): """ Helper function that computes Euclidean distance between two clusters in a list Input: cluster_list is list of clusters, idx1 and idx2 are integer indices for two clusters Output: tuple (dist, idx1, idx2) where dist is distance between cluster_list[idx1] and cluster_list[idx2] """ return (cluster_list[idx1].distance(cluster_list[idx2]), min(idx1, idx2), max(idx1, idx2)) def slow_closest_pair(cluster_list): """ Compute the distance between the closest pair of clusters in a list (slow) Input: cluster_list is the list of clusters Output: tuple of the form (dist, idx1, idx2) where the centers of the clusters cluster_list[idx1] and cluster_list[idx2] have minimum distance dist. """ result = (float("inf"), -1, -1) num_clusters = len(cluster_list) for cluster in range(num_clusters): for other_cluster in range(num_clusters): if cluster != other_cluster: dist_clust = pair_distance( cluster_list, cluster, other_cluster) result = min(result, dist_clust) return result def fast_closest_pair(cluster_list): """ Compute the distance between the closest pair of clusters in a list (fast) Input: cluster_list is list of clusters SORTED such that horizontal positions of their centers are in ascending order Output: tuple of the form (dist, idx1, idx2) where the centers of the clusters cluster_list[idx1] and cluster_list[idx2] have minimum distance dist. """ num_clusters = len(cluster_list) if num_clusters <= 3: return slow_closest_pair(cluster_list) middle = num_clusters // 2 left_part = cluster_list[:middle] right_part = cluster_list[middle:] result_left = fast_closest_pair(left_part) result_right = fast_closest_pair(right_part) result = min( result_left, (result_right[0], result_right[1] + middle, result_right[2] + middle)) mid = (cluster_list[middle - 1].horiz_center() + cluster_list[middle].horiz_center()) / 2 result = min(result, closest_pair_strip(cluster_list, mid, result[0])) return result def closest_pair_strip(cluster_list, horiz_center, half_width): """ Helper function to compute the closest pair of clusters in a vertical strip Input: cluster_list is a list of clusters produced by fast_closest_pair horiz_center is the horizontal position of the strip's vertical center line half_width is the half the width of the strip (i.e; the maximum horizontal distance that a cluster can lie from the center line) Output: tuple of the form (dist, idx1, idx2) where the centers of the clusters cluster_list[idx1] and cluster_list[idx2] lie in the strip and have minimum distance dist. """ center_area_indexes = [index for index in range(len(cluster_list)) if abs(cluster_list[index].horiz_center() - horiz_center) < half_width] center_area_indexes.sort(key=lambda x: cluster_list[x].vert_center()) size = len(center_area_indexes) result = (float("inf"), -1, -1) for cluster_idx1 in range(size - 1): for cluster_idx2 in range(cluster_idx1 + 1, min(cluster_idx1 + 4, size)): dist_clust = pair_distance(cluster_list, center_area_indexes[cluster_idx1], center_area_indexes[cluster_idx2]) result = min(result, dist_clust) return result ###################################################################### # Code for hierarchical clustering def hierarchical_clustering(cluster_list, num_clusters): """ Compute a hierarchical clustering of a set of clusters Note: the function may mutate cluster_list Input: List of clusters, integer number of clusters Output: List of clusters whose length is num_clusters """ clusters = [cluster.copy() for cluster in cluster_list] while len(clusters) > num_clusters: clusters.sort(key=lambda cluster: cluster.horiz_center()) closest = fast_closest_pair(clusters) clusters[closest[1]].merge_clusters(clusters[closest[2]]) clusters.pop(closest[2]) print len(clusters) return clusters ###################################################################### # Code for k-means clustering def kmeans_clustering(cluster_list, num_clusters, num_iterations): """ Compute the k-means clustering of a set of clusters Note: the function may not mutate cluster_list Input: List of clusters, integers number of clusters and number of iterations Output: List of clusters whose length is num_clusters """ cluster_list_copy = [cluster.copy() for cluster in cluster_list] cluster_list_copy.sort(key=lambda x: x.total_population()) cluster_centres = [(cluster.horiz_center(), cluster.vert_center()) for cluster in cluster_list_copy[len(cluster_list_copy) - num_clusters:]] for _ in range(num_iterations): new_clusters = [alg_cluster.Cluster(set([]), cent[0], cent[1], 0, 0) for cent in cluster_centres] clust_pair_list = [] for init_clust in cluster_list_copy: min_dist_pair = (float("inf"), -1, -1) # find pair of cluster with minimum distance between them for clust_pair in ((init_clust.distance(new_cluster), new_cluster, init_clust) for new_cluster in new_clusters): if clust_pair[0] < min_dist_pair[0]: min_dist_pair = clust_pair # build a list with all cluster pairs clust_pair_list.append(min_dist_pair) # merge all clusters into new_clusters for pair in clust_pair_list: pair[1].merge_clusters(pair[2]) cluster_centres = [(clust.horiz_center(), clust.vert_center()) for clust in new_clusters] return new_clusters
bfc46d879aa3f368f7920b2578c4413edb972d4d
glennsvel90/Hangman-Game
/hangman_game.py
2,356
4.03125
4
import os import random import sys #make a list of words words = ["guide", "ultimate", "delete", "slides","sunny", "repository", "request", "setting", "explore", "wisdom", "apple", "banana", "cobra", "tentacles", "waterfall"] def clear(): """ clear the terminal """ if os.name == 'nt': os.system('cls') else: os.system('clear') def draw(wrong_guesses,right_guesses,random_word): """ Make appear the strikes and blank word line spaces """ clear() print('Strikes: {}/7'.format(len(wrong_guesses))) print ('') for letter in wrong_guesses: print(letter,) print('\n\n') for letter in random_word: if letter in right_guesses: print (letter, end = '') else: print("_", end = '') print('') def get_guess(wrong_guesses,right_guesses): """ return the guess """ while True: guess= input("Guess a letter: ").lower() if len(guess) != 1: print ("You only can guess 1 letter at a time") elif guess in wrong_guesses or guess in right_guesses: print ("You guessed that letter already before") elif not guess.isalpha(): print ("You only can use letters") else: return guess def play(done): """ Start the game loop """ clear() random_word = random.choice(words) wrong_guesses = [] right_guesses = [] while True: draw(wrong_guesses, right_guesses, random_word) guess = get_guess(wrong_guesses, right_guesses) if guess in random_word: right_guesses.append(guess) found = True for letter in random_word: if letter not in right_guesses: found = False if found: print ("You Win!!! CONGRATULATIONS!!!") print("The secret word was {}".format(random_word)) done = True else: wrong_guesses.append(guess) if len(wrong_guesses) == 7: draw(wrong_guesses, right_guesses, random_word) print ("You Lost! T_T") print ("The secret word was {}".format(random_word)) done = True if done: play_again = input("Wanna Play Again? Y/n").lower() if play_again != "n": return play(done = False) else: sys.exit() def welcome(): """ Introduce the directions """ start = input("Press enter/return to start, or enter Q to quit ").lower() if start == "q": print ("Bye Bye! Hope you come back and play!") sys.exit() else: return True print("Welcome to the Hangman Game!! ") done = False while True: clear() welcome() play(done)
9c95296a2eb280019e461e4f3cf72bb33469f865
cbohara/think_stats
/ch5.py
2,477
3.53125
4
"""This file contains notes and code from Chapter 5.""" import scipy.stats import thinkstats2 import thinkplot import nsfg import analytic def eval_normal_cdf(x, mu=0, sigma=1): """Evaluate normal CDF and assume standard normal distribution as default.""" return scipy.stats.norm.cdf(x, loc=mu, scale=sigma) def make_normal_plot(weights, term_weights): """Generate normal probability plot from birthweight data.""" # calculate mean and standard deviation for weight series mean = weights.mean() std = weights.std() xs = [-4, 4] # FitLine takes a sequence of xs, an intercept, and slope # returns fxs and fys = represents a line with the given parameters, evaluated at xs fxs, fys = thinkstats2.FitLine(xs, mean, std) thinkplot.Plot(fxs, fys, linewidth=4, color='0.8') thinkplot.PrePlot(2) # NormalProbability generates data for normal probability plot # returns numpy arrays xs and ys xs, ys = thinkstats2.NormalProbability(weights) thinkplot.Plot(xs, ys, label='all live') xs, ys = thinkstats2.NormalProbability(term_weights) thinkplot.Plot(xs, ys, label='full term') thinkplot.Show(root='analytic_birthwgt_normal', title='Normal probability plot', xlabel='Standard deviations from mean', ylabel='Birth weight (lbs)') def main(script): # read in data about the births of 44 kids on the same day from babyboom.dat # df with columns for time, sex, weight_g, and minutes (since midnight) df = analytic.ReadBabyBoom() # exponential distribution # difference between consecutive birth times diffs = df.minutes.diff() # distribution of the interarrival times cdf = thinkstats2.Cdf(diffs, label='actual') thinkplot.Cdf(cdf) # thinkplot.Show(xlabel='minutes', ylabel='CDF') # plot CCDF (complementary CDF) to observe if distribution is exponential thinkplot.Cdf(cdf, complement=True) # not straight = exponential distribution is not perfect for this model # thinkplot.Show(xlabel='minutes', ylabel='CCDF', yscale='log') # standard normal distribution # test the distribution of birth weights for normality preg = nsfg.ReadFemPreg() full_term = preg[preg.prglngth >= 37] weights = preg.totalwgt_lb.dropna() term_weights = full_term.totalwgt_lb.dropna() make_normal_plot(weights, term_weights) if __name__ == '__main__': import sys main(*sys.argv)
e03163fc82b0a674d7550de2318d70997f0c5b84
Asupkay/SSW-567
/HW 01/classifyTriangle.py
2,131
3.75
4
import math from numbers import Number def classifyTriangle(a, b, c): if(not isinstance(a, Number) or not isinstance(b, Number) or not isinstance(c, Number) or a + b <= c or a + c <= b or b + c <= a): return 'NotATriangle' if(a == b and a == c): return 'Equilateral' if((a == b and a != c) or (a == c and a != b) or (b == c and b != a)): return 'Isoceles' aPow = math.pow(a, 2) bPow = math.pow(b, 2) cPow = math.pow(c, 2) if(aPow + bPow == cPow or aPow + cPow == bPow or bPow + cPow == aPow): return 'Right' if(a != b and b != c): return 'Scalene' def runClassifyTriangle(a, b, c): print('classifyTriangle(' + str(a) + ',' + str(b) + ',' + str(c) + ')=' + classifyTriangle(a,b,c)) class TestTriangles(object): def test_Right(self): assert classifyTriangle(3,4,5) == 'Right' assert classifyTriangle(6, 8, 10) == 'Right' assert classifyTriangle(24, 26, 10) == 'Right' def test_Equilateral(self): assert classifyTriangle(1,1,1) == 'Equilateral' assert classifyTriangle(100,100,100) == 'Equilateral' assert classifyTriangle(0,0,0) != 'Equilateral' def test_Isoceles(self): assert classifyTriangle(10,10,10) != 'Isoceles' assert classifyTriangle(5, 5, 3) == 'Isoceles' def test_Scalene(self): assert classifyTriangle(13,9,14) == 'Scalene' assert classifyTriangle(7.7, 5, 9) == 'Scalene' def test_NotATriangle(self): assert classifyTriangle(False, 1, 1) == 'NotATriangle' assert classifyTriangle(100, 1, 1) == 'NotATriangle' assert classifyTriangle(-1, -1, -1) == 'NotATriangle' assert classifyTriangle(0, 0, 0) == 'NotATriangle' runClassifyTriangle(3,4,5) runClassifyTriangle(6, 8, 10) runClassifyTriangle(24, 26, 10) runClassifyTriangle(1,1,1) runClassifyTriangle(100,100,100) runClassifyTriangle(0,0,0) runClassifyTriangle(10,10,10) runClassifyTriangle(5, 5, 3) runClassifyTriangle(13,9,14) runClassifyTriangle(7.7, 5, 9) runClassifyTriangle(100, 1, 1) runClassifyTriangle(-1, -1, -1) runClassifyTriangle(0, 0, 0)
d4a9f92211cd8515de94a2d5815e71bab92e1d1a
marcelodinamo/Exercicios_python_ALP
/5_Salario.py
140
3.578125
4
sal_b = float(input("Digite seu salario: ")) imp = sal_b * 0.1 sal_r = 50.00 + sal_b - imp print("Salario à receber: {:.2f}".format(sal_r))
eabaf262e99f892958a84077c9b5920e0988bdbd
Lucky-Dutch/password-generator
/pass_creator.py
1,561
4.34375
4
""" This program create random passwords. """ import random import string import datetime print("Hello in Password Creator 0.01\n\ Choose a right number: \n\ 1 - simple password with 6th letters\n\ 2 - password with letters (small and big) and numbers with your value of characters\n\ 3 - CRAZIEST passwords - try it yourself!\n\ 4 - I don't have idea of what I want to do") program_choice = input("What number you choose?: ") now = datetime.datetime.now() now = now.strftime("%d-%m-%Y %X") password = "" if program_choice == "1": for i in range(6): password += random.choice(string.ascii_lowercase) elif program_choice == "2": characters_value = input("Write how many characters your password need: ") for i in range(int(characters_value)): password += random.choice(string.ascii_letters + string.digits) if password.isalpha(): password = password[:-1] + random.choice(string.digits) elif program_choice == "3": characters_value = input("Write how many characters your password need: ") for i in range(int(characters_value)): password += random.choice(string.ascii_letters + string.digits + string.punctuation) elif program_choice == "4": print("Thank you, see you next time") else: print("Wrong key. Try it again.") with open("passwords.txt","a+") as file: file.write("password: {} website: {} datetime: {}\n".format(password,input("Write name of website or press enter: "), now)) print(password)
55c05975135cd06379862ee9ab647f24cd9fc6c7
13323106900/1python-diyigeyue
/19自主复习day/闰年.py
144
3.828125
4
year = int(input("请输入年份")) if year%4==0 and year%100!= 0 or year%400==0: print("%d是闰年"%year) else: print("%d是平年"%year)
5a91da07fce38eeaf61fde307dbe2ceadca3b7ae
qmnguyenw/python_py4e
/geeksforgeeks/algorithm/medium_algo/2_9.py
4,462
3.703125
4
Merge Sort vs. Insertion Sort **Pre-requisite:Merge Sort, Insertion Sort** ** _Merge Sort_ :** is an external algorithm and based on divide and conquer strategy. In this sorting: 1. The elements are split into two sub-arrays **(n/2)** again and again until only one element is left. 2. Merge sort uses additional storage for sorting the auxiliary array. 3. Merge sort uses three arrays where two are used for storing each half, and the third external one is used to store the final sorted list by merging the other two and each array is then sorted recursively. 4. At last, all sub-arrays are merged to make it ‘n’ element size of the array. Below is the image to illustrate **Merge Sort** : ![](https://media.geeksforgeeks.org/wp-content/uploads/20200601174332/Merge- Sort-Tutorial.png) ** _Insertion Sort_** is a sorting algorithm in which elements are taken from an unsorted item, inserting it in sorted order in front of the other items, and repeating until all items are in order. The algorithm is simple to implement and usually consists of two loops: an outer loop to pick items and an inner loop to iterate through the array. It works on the principle of the sorting playing cards in our hands. Below is the image to illustrate **Insertion Sort** : ![](https://media.geeksforgeeks.org/wp-content/uploads/insertionsort.png) ** _Difference between Merge sort and Insertion sort_ :** * **Time Complexity:** In Merge Sort the Worst Case: _O(N*log N)_ , Average Case: _O(N*log N)_ , and Best Case: _O(N*log N)_ , whereas In Insertion Sort the Worst Case: _O(N 2)_, Average Case: _O(N 2)_, and Best Case: _O(N)_. * **Space Complexity:** **Merge sort** being recursive takes up the auxiliary space complexity of _O(N)_ hence it cannot be preferred over the place where memory is a problem, whereas In **Insertion sort** only takes _O(1)_ auxiliary space complexity. It sorts the entire array just by using an extra variable. * **Datasets:** Merge Sort is preferred for huge data sets. It happens to compare all the elements present in the array hence is not much helpful for small datasets, whereas Insertion Sort is preferred for fewer elements. It becomes fast when data is already sorted or nearly sorted because it skips the sorted values. * **Efficiency:** Considering average time complexity of both algorithm we can say that Merge Sort is efficient in terms of time and Insertion Sort is efficient in terms of space. * **Sorting Method:** The merge sort is an external sorting method in which the data that is to be sorted cannot be accommodated in the memory and needed auxiliary memory for sorting, whereas Insertion sort is based on the idea that one element from the input elements is consumed in each iteration to find its correct position i.e., the position to which it belongs in a sorted array. * **Stability:** Merge sort is stable as two elements with equal value appear in the same order in sorted output as they were in the input unsorted array, whereas Insertion sort takes _O(N 2)_ time on both data structures(Array and Linked list). If the CPU has an efficient memory block move function then the array may be quicker. Otherwise, there probably isn’t that much of a time difference. **Tabular Representation:** Parameters| Merge Sort| Insertion Sort| Worst Case Complexity| O(N*log N)| O(N2)| Average Case Complexity| O(N*log N)| O(N2)| Best Case Complexity| O(N*log N)| O(N)| Auxiliary Space Complexity| O(N)| O(1)| Works well on| On huge dataset.| On small dataset.| Efficiency| Comparitively Efficient.| Comparitively Inefficient.| Inplace Sorting| No| Yes| Algorithm Paradigm| Divide and Conquer| Incremental Approach| Uses| It is used for sorting linked list in O(N*log N), for Inversion Count problem, External sorting, etc.| It is used when number of elements is small. It can also be useful when input array is almost sorted, only few elements are misplaced in complete big array. ---|---|--- Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the **DSA Self Paced Course** at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer **Complete Interview Preparation Course** **.** My Personal Notes _arrow_drop_up_ Save
898eb96dbec9b6b0717e97f0a7aa85fc34090fa4
JorrgeX/CMPSC132
/Hsieh_Program5.py
4,420
4.0625
4
#Hsieh_Program5 #Yuan-Chih Hsieh #CMPSC132 Program5 class Node: def __init__(self, data=None): self.data = data self.next = None self.prev = None def get_data(self): return self.data def get_next(self): return self.next def get_prev(self): return self.prev def set_next(self, new): #this function occurs whenever the next data changes self.next = new def set_prev(self, new): #this function occurs whenever the previous data changes self.prev = new class LinkedList: #every elements in this linked list would be a node def __init__(self): self.head = None self.tail = None def get_head(self): return self.head def get_tail(self): return self.tail def insert(self, CurNode, new): #this is an insert function rather than an insert-after newNode = Node(new) if self.get_length() == 0: #check if it is an empty list or not self.head = newNode self.tail = newNode elif self.head == CurNode: #the case if the current node is at the head position temp_prev = CurNode.get_prev() CurNode.set_prev(newNode) newNode.set_prev(temp_prev) newNode.set_next(CurNode) self.head = newNode else: temp_prev = CurNode.get_prev() temp_prev.set_next(newNode) newNode.set_prev(temp_prev) newNode.set_next(CurNode) CurNode.set_prev(newNode) def deleting(self, item): temp = self.head #search for the item for list head deleted = False temp_next = None temp_prev = None while deleted == False and temp != None: if temp.get_data() == item: temp_next = temp.get_next() temp_prev = temp.get_prev() temp_next.set_prev(temp_prev) temp_prev.set_next(temp_next) deleted = True else: temp = temp.get_next() if deleted == False: print('The item you want to delete is not in this list.') def searching(self, key): temp = self.head #search for the item for list head found = False while found == False and temp != None: #temp would be None if it is out of the list if temp.get_data() == key: found = True return temp #return the key node else: temp = temp.get_next() if found == False: print('The item you are searching for is not in this list.') return def append(self, new): #add the new value at the end of this list newNode = Node(new) if self.head == None: self.head = newNode self.tail = newNode else: newNode.set_prev(self.tail) self.tail.set_next(newNode) #no need to set newNode's next, because the default is None self.tail = newNode def get_length(self): #get the length of the list i = self.head cnt = 0 while i != None: cnt += 1 i = i.get_next() return cnt def main(): sample = LinkedList() grade = 0 i = 0 while i < 10: try: grade = int(input('Please enter a grade: ')) sample.append(grade) i += 1 except ValueError: print('Please enter an integer!') ''' x = sample.searching(10) #using the searching method sample.insert(x, 110) #using the insert method sample.deleting(20) #using the deleting method ''' #print all the grades in the following for loop temp = None total = 0 print('Grades: ', end='') for i in range(sample.get_length()): if temp == None: temp = sample.get_head() else: temp = temp.get_next() print(temp.get_data(), end=' ') total += temp.get_data() print('') print('Average:', '{:.2f}'.format(total/sample.get_length())) if __name__ == "__main__": main()
8a2260c1ad39715e3e78a9d75c42b53e4b8552c5
kalbury/DnD-Character-Creator
/Character_Creation.py
42,751
3.9375
4
### Character information up to date for DnD Next version 4/11/13 ### import random as r print "~~~~ Welome to DnD Next Simple Character Creator ~~~~" print print "This program will help you create a character quickly " \ "to the point where you will need to begin choosing " \ "choosing armor, items, skills, etc." print print "To create a character, simply create a race instance and follow " \ "the directions." print "To do so, type: CharacterName = Race(Level,Name)" print "For example: Tim = Dwarf(4,'Tim')" print "Note: leaving the arguments blank (e.g. Dwarf() ) will default to Level 1"\ " with a random name." print print "Races are: Dwarf, Elf, Halfling, Human" def abilityScores(): """ () -> list Randomly chooses six scores by adding top three d6 rolls per score and appending those scores to a list. Returns that list. """ scores_list = [] for i in range(6): temp_list = [] for j in range(4): temp_list.append(r.choice([1,2,3,4,5,6])) temp_list.sort() scores_list.append(temp_list[1]+temp_list[2]+temp_list[3]) scores_list.sort() return scores_list #Default names if no name is given when creating character randomNames = {"Dwarf":['Adrik', 'Alberich', 'Baer', 'Barendd', 'Brottor', 'Dain', 'Darrak', 'Eberk', 'Einkil', 'Fargrim', 'Gardain', 'Harbek', 'Kildrak', 'Morgran', 'Orsik', 'Oskar', 'Rangrim', 'Rurik', 'Taklinn', 'Thoradin', 'Thorin', 'Tordek', 'Traubon', 'Travok', 'Ulfgar', 'Veit', 'Vondal'], "Elf":['Adran', 'Aelar', 'Aramil', 'Arannis', 'Aust', 'Beiro', 'Berrian', 'Carric', 'Enialis', 'Erdan', 'Erevan', 'Galinndan', 'Hadarai', 'Heian', 'Himo', 'Immeral', 'Ivellios', 'Laucian', 'Mindartis', 'Paelias', 'Peren', 'Quarion', 'Riardon', 'Rolen', 'Soveliss', 'Thamior', 'Tharivol', 'Theren', 'Varis'], "Halfling":['Alton', 'Ander', 'Cade', 'Corrin', 'Eldon', 'Errich', 'Finnan', 'Garret', 'Lindal', 'Lyle', 'Merric', 'Milo', 'Osborn', 'Perrin', 'Reed', 'Roscoe', 'Wellby'], "Human":['Alton', 'Ander', 'Cade', 'Corrin', 'Eldon', 'Errich', 'Finnan', 'Garret', 'Lindal', 'Lyle', 'Merric', 'Milo', 'Osborn', 'Perrin', 'Reed', 'Roscoe', 'Wellby','Adran', 'Aelar', 'Aramil', 'Arannis', 'Aust', 'Beiro', 'Berrian', 'Carric', 'Enialis', 'Erdan', 'Erevan', 'Galinndan', 'Hadarai', 'Heian', 'Himo', 'Immeral', 'Ivellios', 'Laucian', 'Mindartis', 'Paelias', 'Peren', 'Quarion', 'Riardon', 'Rolen', 'Soveliss', 'Thamior', 'Tharivol', 'Theren', 'Varis','Adrik', 'Alberich', 'Baer', 'Barendd', 'Brottor', 'Dain', 'Darrak', 'Eberk', 'Einkil', 'Fargrim', 'Gardain', 'Harbek', 'Kildrak', 'Morgran', 'Orsik', 'Oskar', 'Rangrim', 'Rurik', 'Taklinn', 'Thoradin', 'Thorin', 'Tordek', 'Traubon', 'Travok', 'Ulfgar', 'Veit', 'Vondal']} #global list of skills skills = {'administer first aid': 'wis', 'balance':'dex', 'bluff':'cha', 'break an object':'str', 'climb':'str', 'conceal an object':'dex', 'drive':'dex', 'gather rumors':'cha', 'handle an animal':'wis', 'intimidate':'cha', 'jump':'str', 'listen':'wis', 'perform':'cha', 'persuade':'cha', 'recall lore':'int', 'ride':'dex', 'search':'int', 'sense motive':'wis', 'sneak':'dex', 'spot':'wis', 'swim':'str', 'tumble':'dex'} #global dict for specialties (is filled in the chooseSpecialty() method) specialties = {} #global dict for feats feats = {} class Character(object): def __init__(self,level): self.level = level print "You can use randomized ability scores: "+str(abilityScores()) print "Or simply use the standard array: [8, 10, 12, 13, 14, 15]" print self.str = int(raw_input("Please enter STRENGTH value: ")) self.dex = int(raw_input("Please enter DEXTERITY value: ")) self.con = int(raw_input("Please enter CONSTITUTION value: ")) self.int = int(raw_input("Please enter INTELLIGENCE value: ")) self.wis = int(raw_input("Please enter WISDOM value: ")) self.cha = int(raw_input("Please enter CHARISMA value: ")) self.hp = 0 self.classType = '' self.background = '' self.backgroundStory = '' self.backgroundProfession = '' self.skills = '' self.specialty = '' self.specialtyStory = '' self.feats = {} print #classMods for updating hp and other stats when leveling up, as determined by traits #or class specific characteristics #The list represents [str,dex,con,int,wis,cha,hp] self.classMods = [0,0,0,0,0,0,0] #Experience calculator xp_dict = {1: 0, 2: 250, 3: 950, 4: 2250, 5:4750, 6: 9500, 7:16000, 8:25000, 9: 38000, 10: 56000, 11: 77000, 12: 96000, 13: 120000, 14: 150000, 15: 190000, 16: 230000, 17: 280000, 18: 330000, 19: 390000, 20: 460000} self.xp = xp_dict[self.level] self.hit_dice = {"Barbarian": "d12", "Cleric": "d8", "Druid":"d8", "Fighter":"d10", "Monk":"d8", "Paladin":"d10", "Ranger":"d10", "Rogue":"d6", "Wizard":"d6"} def getAbilityScores(self): """ Prints the six ability scores for the character. """ mods = [(self.str -10)/2, (self.dex-10)/2, (self.con-10)/2, (self.int-10)/2, (self.wis-10)/2, (self.cha-10)/2] print "STR: {0} ({1}) \nDEX: {2} ({3})\nCON: {4} ({5})".format(self.str, mods[0], self.dex, mods[1], self.con, mods[2]) print "INT: {0} ({1})\nWIS: {2} ({3})\nCHA: {4} ({5})".format(self.int, mods[3], self.wis, mods[4], self.cha, mods[5]) def abilityScores(self): """ Function used in save() method to return Ability Scores """ mods = [(self.str -10)/2, (self.dex-10)/2, (self.con-10)/2, (self.int-10)/2, (self.wis-10)/2, (self.cha-10)/2] return "STR: {0} ({1}) \nDEX: {2} ({3})\nCON: {4} ({5})".format(self.str, mods[0], self.dex, mods[1], self.con, mods[2])+"\n" \ "INT: {0} ({1})\nWIS: {2} ({3})\nCHA: {4} ({5})".format(self.int, mods[3], self.wis, mods[4], self.cha, mods[5]) def updateScore(self,ability,amount): """ (str,int) -> Nonetype Use to update an ability score manually. """ abilities = {'str':'strength','dex':'dexterity', 'con':'constitution','int':'intelligence', 'wis':'wisdom','cha':'charisma', 'hp':'hit points'} if ability == 'str': self.str += amount print "You added {0} point(s) to the {1} stat.".format(amount,abilities[ability]) elif ability == 'dex': self.dex += amount print "You added {0} point(s) to the {1} stat.".format(amount,abilities[ability]) elif ability == 'con': self.con += amount print "You added {0} point(s) to the {1} stat.".format(amount,abilities[ability]) elif ability == 'int': self.int += amount print "You added {0} point(s) to the {1} stat.".format(amount,abilities[ability]) elif ability == 'wis': self.wis += amount print "You added {0} point(s) to the {1} stat.".format(amount,abilities[ability]) elif ability == 'cha': self.cha += amount print "You added {0} point(s) to the {1} stat.".format(amount,abilities[ability]) elif ability == 'hp': self.hp += amount print "You added {0} point(s) to the {1} stat.".format(amount,abilities[ability]) else: print "Please use 'str','dex','con','int','wis', or 'cha' as input." def stealthUpdate(self,ability,amount): """ Use when needing to stealthily update stats. """ if ability == 'str': self.str += amount elif ability == 'dex': self.dex += amount elif ability == 'con': self.con += amount elif ability == 'int': self.int += amount elif ability == 'wis': self.wis += amount elif ability == 'cha': self.cha += amount elif ability == 'hp': self.hp += amount def createTraits(self,fileName,startLine,stopLine): """ (str,str,str) -> dict returns a dictionary of traits for character. Populates the self.traits variable for the character class. fileName: The file to open startLine: The function looks for this line before running; its usage here looks for "Traits:" before executing further stopLine: The place to stop; its usage here looks for line "Stop:" in the opened file. """ traits_file = open(fileName,'r') read_file = '' temp_dict = {} temp_line = '' while read_file[:-2].lower() != startLine.lower(): read_file = traits_file.readline() for line in traits_file: if line == "\n": pass elif line[:-2] == stopLine or line[:-1] == stopLine: traits_file.close() return temp_dict elif len(line) > 0 and ":" in line: temp_line = line[:line.index(":")] temp_dict[line[:line.index(":")]] = '' elif len(line) > 0: if len(temp_dict) == 0: pass else: temp_dict[temp_line] = line[:-1] def chooseClass(self): """ Asks player to choose a class for his/her character. Called in each character class. """ #global dictionary of classes with 0 values in a list (ex. [str,dex,con,int,wis,cha,hp,suggested specialty]) classes = {'barbarian': [0,0,0,0,0,0,self.con+12,'reaper'], 'cleric':[0,0,0,0,0,0,self.con+8,'mystical healer'], 'druid':[0,0,0,0,0,0,self.con+8,'hedge magician'], 'fighter':[0,0,0,0,0,0,self.con+10,'reaper'], 'monk':[0,0,0,0,0,0,self.con+8,'skirmisher'], 'paladin':[0,0,0,0,0,0,self.con+10,'defender'], 'ranger':[0,0,0,0,0,0,self.con+10,'sharpshooter'], 'rogue':[0,0,0,0,0,0,self.con+6,'specialist'], 'wizard':[0,0,0,0,0,0,self.con+6,'hedge magician'] } #Ask which class he/she would like chosen_class = raw_input("Which class would you like? Please choose from:\nBarbarian, Cleric, Druid, Fighter, Monk, Paladin, Ranger, Rogue, Wizard " ).lower() while chosen_class not in ['barbarian','cleric','druid','fighter','monk','paladin','ranger','rogue','wizard']: chosen_class = raw_input("\nIncorrect input\n\nWhich class would you like? Please choose from:\nBarbarian, Cleric, Druid, Fighter, Monk, Paladin, Ranger, Rogue, Wizard " ).lower() print #Adds character class to Class object for use in print statements self.classType = chosen_class.title() #Class specific conditional statements. These update the various ability scores #in the classes variable if chosen_class == 'barbarian': barb_choice = raw_input('Would you like to boost (1) Strength or (2) Constitution? ') print while barb_choice not in ['1','2']: barb_choice = raw_input('Would you like to boost (1) Strength or (2) Constitution? ') print if barb_choice == '1': classes['barbarian'][0] = 1 elif barb_choice == '2': classes['barbarian'][2] = 1 elif chosen_class == 'cleric': clerc_choice = raw_input('Would you like to boost (1) Wisdom, (2) Strength, or (3) Constitution? ') print while clerc_choice not in ['1','2','3']: clerc_choice = raw_input('Would you like to boost (1) Wisdom, (2) Strength, or (3) Constitution? ') print if clerc_choice == '1': classes['cleric'][4] = 1 elif clerc_choice == '2': classes['cleric'][0] = 1 elif clerc_choice == '3': classes['cleric'][2] = 1 elif chosen_class == 'druid': druid_choice = raw_input('Would you like to boost (1) Wisdom or (2) Constitution? ') print while druid_choice not in ['1','2']: druid_choice = raw_input('Would you like to boost (1) Wisdom or (2) Constitution? ') print if druid_choice == '1': classes['druid'][4] = 1 elif druid_choice == '2': classes['druid'][2] = 1 elif chosen_class == 'fighter': fight_choice = raw_input('Would you like to boost (1) Strength, (2) Dexterity, or (3) Constitution? ') print while fight_choice not in ['1','2','3']: fight_choice = raw_input('Would you like to boost (1) Strength, (2) Dexterity, or (3) Constitution? ') print if fight_choice == '1': classes['fighter'][0] = 1 elif fight_choice == '2': classes['fighter'][1] = 1 elif fight_choice == '3': classes['fighter'][2] = 1 elif chosen_class == 'monk': monk_choice = raw_input("Would you like to boost (1) Wisdom or (2) Dexterity? ") print while monk_choice not in ['1','2']: monk_choice = raw_input("Would you like to boost (1) Wisdom or (2) Dexterity? ") print if monk_choice == '1': classes['monk'][4] = 1 elif monk_choice == '2': classes['monk'][1] = 1 elif chosen_class == 'paladin': pal_choice = raw_input('Would you like to boost (1) Strength, (2) Constitution, or (3) Charisma? ') print while pal_choice not in ['1','2','3']: pal_choice = raw_input('Would you like to boost (1) Strength, (2) Constitution, or (3) Charisma? ') print if pal_choice == '1': classes['paladin'][0] = 1 elif pal_choice == '2': classes['paladin'][2] = 1 elif pal_choice == '3': classes['paladin'][5] = 1 elif chosen_class == 'ranger': rang_choice = raw_input('Would you like to boost (1) Strength, (2) Dexterity, or (3) Constitution? ') print while rang_choice not in ['1','2','3']: rang_choice = raw_input('Would you like to boost (1) Strength, (2) Dexterity, or (3) Constitution? ') print if rang_choice == '1': classes['ranger'][0] = 1 elif rang_choice == '2': classes['ranger'][1] = 1 elif rang_choice == '3': classes['ranger'][2] = 1 elif chosen_class == 'rogue': rog_choice = raw_input('Would you like to boost (1) Strength, (2) Dexterity, or (3) Intelligence? ') print while rog_choice not in ['1','2','3']: rog_choice = raw_input('Would you like to boost (1) Strength, (2) Dexterity, or (3) Intelligence? ') print if rog_choice == '1': classes['rogue'][0] = 1 elif rog_choice == '2': classes['rogue'][1] = 1 elif rog_choice == '3': classes['rogue'][3] = 1 elif chosen_class == 'wizard': wiz_choice = raw_input('Would you like to boost (1) Intelligence or (2) Constitution? ') print while wiz_choice not in ['1','2']: wiz_choice = raw_input('Would you like to boost (1) Intelligence or (2) Constitution? ') print if wiz_choice == '1': classes['wizard'][3] = 1 elif wiz_choice == '2': classes['wizard'][2] = 1 #Update base stats #A basic list full of the types of ability scores stats_list = ['str','dex','con','int','wis','cha','hp'] #loops through the stats_list and adds all numbers to character's #starting stats for i in range(len(stats_list)): self.stealthUpdate(stats_list[i],classes[chosen_class][i]) #modify hp if character is starting out higher than level 1 def update_hp_for_higher_level(chosen_class,level): """ Helper function for chooseClass(). Updates character for levels greater than 1. """ #Checks to see if your character is level 4,8,12,etc. def upgradedAbilityAt4(level): if level % 4 == 0: upgraded_ability = raw_input("Level "+str(level)+"!\n Which two abilities would you like to upgrade? (Adds +1 to ability)\n Please input two from str/dex/con/int/wis/cha with a space in between.\n (ex: cha dex) ").split(' ') print #To write: #if either ability pushes ability score over 20, redo input for i in upgraded_ability: self.stealthUpdate(i,1) #class specific HP calculations if chosen_class == 'barbarian': for i in range(2,self.level+1): upgradedAbilityAt4(i) self.hp += r.randint(1,12) + self.con + self.classMods[6] elif chosen_class == 'cleric': for i in range(2,self.level+1): upgradedAbilityAt4(i) self.hp += r.randint(1,8) + self.con + self.classMods[6] elif chosen_class == 'druid': for i in range(2,self.level+1): upgradedAbilityAt4(i) self.hp += r.randint(1,8) + self.con + self.classMods[6] elif chosen_class == 'fighter': for i in range(2,self.level+1): upgradedAbilityAt4(i) self.hp += r.randint(1,10) + self.con + self.classMods[6] elif chosen_class == 'monk': for i in range(2,self.level+1): upgradedAbilityAt4(i) self.hp += r.randint(1,8) + self.con + self.classMods[6] elif chosen_class == 'paladin': for i in range(2,self.level+1): upgradedAbilityAt4(i) self.hp += r.randint(1,10) + self.con + self.classMods[6] elif chosen_class == 'ranger': for i in range(2,self.level+1): upgradedAbilityAt4(i) self.hp += r.randint(1,10) + self.con + self.classMods[6] elif chosen_class == 'rogue': for i in range(2,self.level+1): upgradedAbilityAt4(i) self.hp += r.randint(1,6) + self.con + self.classMods[6] elif chosen_class == 'wizard': for i in range(2,self.level+1): upgradedAbilityAt4(i) self.hp += r.randint(1,6) + self.con + self.classMods[6] if self.level > 1: update_hp_for_higher_level(chosen_class,self.level) def backgroundAndSkills(self): """ Helps user choose Background and Skills. """ backgrounds = {} def createBackgrounds(fileName): """ (str) -> None Opens a file with background information and populates the backgrounds dictionary with that information """ backgroundFile = open(fileName,'r') current_bg = '' for line in backgroundFile: #If there is no text, go to next line if line == "\n": pass #Else if the line starts with "~~", create new key in top level #dictionary with the remainder of that line and set its value #to an empty dictionary elif line[:2] == "~~": current_bg = line[2:-1] backgrounds[line[2:-1]] = {} #Go through the next few lines and set them to keys and values #in the nestled dictionary elif ":" in line: line_heading = line[:line.index(":")] after_heading = line[line.index(":")+2:-1] #create a key/value pair for the background regarding its profession if line_heading == "hasProfession": #Change the string to a bool if after_heading == "True": backgrounds[current_bg][line_heading] = True else: backgrounds[current_bg][line_heading] = False #Create professions list if current BG has professions if line_heading == "professions" and backgrounds[current_bg]['hasProfession']: backgrounds[current_bg]['professions'] = after_heading.split(', ') #Create a two item list to store the trait name and its description if line_heading == "trait": backgrounds[current_bg]['trait'] = [line[line.index(":")+2: line.index("-")-1],\ line[line.index("-")+2:-1]] #Create an entry for the story of a character's background if line_heading == "story": backgrounds[current_bg]['story'] = after_heading #Create a list for the recommended skills if line_heading == "recommended": backgrounds[current_bg]['recommended'] = after_heading.split(', ') backgroundFile.close() #Creat background now createBackgrounds('Backgrounds.txt') #Make a list of backgrounds background_list = [] for i in backgrounds: background_list.append(i) background_list.sort() #Ask user to choose a background and set that to self.background background_choice = raw_input('Enter a background from this list: '+str(background_list)+': ').title() print while background_choice not in background_list: background_choice = raw_input('Enter a background from this list: '+str(background_list)+': ').title() print self.background = background_choice self.backgroundStory = backgrounds[self.background]['story'] #Add the background's trait to self.traits self.traits[backgrounds[self.background]['trait'][0]] = backgrounds[self.background]['trait'][1] #If the background has a profession, add that now if backgrounds[self.background]['hasProfession'] == True: #Create a temp list to account for Commoner's multiple profession listing profession_holder = [] for i in backgrounds[self.background]['professions']: if i in profession_holder: pass else: profession_holder.append(i) #Ask user which profession they'd like or if they press Enter one is chosen randomly temp_choice = raw_input("Which profession would you like? "+str(profession_holder)+"\n"\ "Enter one from the list above or press Enter for random. ").title() print while temp_choice != '' and temp_choice not in backgrounds[self.background]['professions']: temp_choice = raw_input("Which profession would you like? "+str(profession_holder)+"\n"\ "Enter one from the list above or press Enter for random. ").title() print if temp_choice == '': temp_int = r.randint(0,len(backgrounds[self.background]['professions'])-1) self.backgroundProfession = backgrounds[self.background]['professions'][temp_int] else: self.backgroundProfession = temp_choice else: pass #Ask about skills. skill_choice = [] print "You'll now choose 4 skills from this list:" print for i in skills: print i.title() print print "Recommended skills for your "+self.background+" are: "+str(backgrounds[self.background]['recommended']) for i in range(4): skill_choice.append(raw_input("Which Skill would you like for skill "+str(i+1)+"? ").title()) print self.skills = skill_choice def chooseSpecialties(self): """ Helps user choose a specialty for their character. """ #specialties = {} def createSpecialties(fileName): """ (str) -> None Helper function to create specialties dict from file. """ specialtyFile = open(fileName,'r') current_specialty = '' for line in specialtyFile: #If there is no text, go to next line if line == "\n": pass #If line starts with "~~", set current_specialty to the specialty #on that line, and create a new key in the specialties dict and #set its value to an empty dict. Then input the first item in the #new dict as the specialty's decription elif line[:2] == "~~": current_specialty = line[2:line.index("-")-1] specialties[current_specialty] = {} specialties[current_specialty]['story'] = line[line.index("-")+1:-1] #If the line starts with "Level," creates entries for which feats #the character will get at levels 1,3,6,9 elif line[:5] == "Level": specialties[current_specialty][int(line[6:7])] = line[line.index(":")+2:-1] specialtyFile.close() #Create the specialties dict createSpecialties('Specialties.txt') #Make list of specialties specialties_list = [] for i in specialties: specialties_list.append(i) specialties_list.sort() #Ask user which specialty they'd like, give them recommended specialty for their class class_recommendation = {'Barbarian':'reaper', 'Cleric':'mystical healer', 'Druid':'hedge magician', 'Fighter':'reaper', 'Monk':'skirmisher', 'Paladin':'defender', 'Ranger':'sharpshooter', 'Rogue':'specialist', 'Wizard':'hedge magician' } spec_choice = raw_input("Which specialty would you like?\n"\ "Choose from: \n"+str(specialties_list)+"\n\n"\ "The recommended specialty for your "+self.classType+" is "+class_recommendation[self.classType].title()+": ").title() print while spec_choice not in specialties_list: spec_choice = raw_input("Which specialty would you like?\n"\ "Choose from: \n"+str(specialties_list)+"\n\n"\ "The recommended specialty for your "+self.classType+" is "+class_recommendation[self.classType].title()+": ").title() print self.specialty = spec_choice self.specialtyStory = specialties[self.specialty]['story'] def populateFeats(self): """ Populates the feats dict and adds correct feat to self.feats """ def createFeats(fileName): """ Populates feats dict """ featsFile = open('Feats.txt','r') current_feat = '' for line in featsFile: if line == "\n": pass elif line[:2] == "~~": current_feat = line[2:line.index("-")-1] feats[current_feat] = {} feats[current_feat]['description'] = line[line.index("-")+2:-1] elif line[:6] == "prereq": feats[current_feat]['prereq'] = line[line.index(":")+2:-1] elif line[:7] == "benefit": feats[current_feat]['benefit'] = line[line.index(":")+2:-1] elif line[:4] == "type": feats[current_feat]['type'] = line[line.index(":")+2:-1] elif line[:6] == "effect": feats[current_feat]['effect'] = line[line.index(":")+2:-1] featsFile.close() createFeats('Feats.txt') for i in range(1,self.level+1): if i == 1 or i%3 == 0: current_feat = specialties[self.specialty][i] self.feats[i] = {} self.feats[i]['name'] = current_feat self.feats[i]['description'] = feats[current_feat]['description'] self.feats[i]['type'] = feats[current_feat]['type'] if 'benefit' in feats[current_feat]: self.feats[i]['benefit'] = feats[current_feat]['benefit'] if 'effect' in feats[current_feat]: self.feats[i]['effect'] = feats[current_feat]['effect'] if 'prereq' in feats[current_feat]: self.feats[i]['prereq'] = feats[current_feat]['prereq'] def save(self): """ Saves a character to a .txt file in same directory as this file. """ fileName=self.characterName+"_"+self.race+"_"+self.classType+"_lvl_"+str(self.level) new_file = open(str(fileName)+".txt","w") new_file.write("~~~~~~~~~~~ "+self.characterName+" the "+self.race+" "+self.classType+" ~~~~~~~~~~~\n\n") new_file.write("Level: "+str(self.level)+" HP: "+str(self.hp)+" XP: "+str(self.xp)+" Hit Dice: "+str(self.level)+str(self.hit_dice[self.classType])+"\n") new_file.write(str(self.abilityScores())) new_file.write("\n\n~~~~~~~~~ Skills ~~~~~~~~~\n") for i in self.skills: new_file.write("\n"+i+" "+"("+skills[i.lower()].upper()+")") new_file.write("\n\n~~~~~~~~~ Traits ~~~~~~~~~\n") for i in self.traits: new_file.write("\n ~~"+i+"~~\n "+str(self.traits[i])+"\n") new_file.write("\n\n~~~~~~~~~ Specialty: "+self.specialty+" ~~~~~~~~\n") new_file.write("\n "+self.specialtyStory+"\n") new_file.write("\n ~~~~ Feats ~~~~\n") for i in range(1,self.level+1): if i == 1 or i%3 == 0: new_file.write("\n Level "+str(i)+": "+self.feats[i]['name']+' '\ "("+self.feats[i]['type']+")\n"\ ' "'+self.feats[i]['description']+'"\n\n') if 'prereq' in self.feats[i]: new_file.write(" Prerequisite: "+self.feats[i]['prereq']+"\n") if 'benefit' in self.feats[i]: new_file.write(" Benefit: "+self.feats[i]['benefit']+"\n") if 'effect' in self.feats[i]: new_file(" Effect: "+self.feats[i]['effect']+"\n") new_file.write("\n\n~~~~~~~~~ Background: "+self.background+" ~~~~~~~~\n") if self.backgroundProfession == '': pass else: new_file.write("Profession: "+self.backgroundProfession) new_file.write("\n "+self.backgroundStory) new_file.close() print "File "+str(fileName)+".txt saved." def __str__(self): characterInfo = "\n~~~~~~~~~~~~~~~~ "+self.characterName+" the "+self.race+" "+self.classType+" ~~~~~~~~~~~~~~~~"\ "\n\nLevel: "+str(self.level)+" HP: "+str(self.hp)+" XP: "+str(self.xp)+" Hit Dice: "+str(self.level)+str(self.hit_dice[self.classType])+""\ "\n"+self.abilityScores()+"\n\n"\ "~~~~~~~~~ Skills ~~~~~~~~~\n\n" for i in self.skills: characterInfo += i+" "+"("+skills[i.lower()].upper()+")\n" characterInfo += "\n\n~~~~~~~~~ Traits ~~~~~~~~~\n" for i in self.traits: characterInfo += "\n ~~"+i+"~~\n "+str(self.traits[i])+"\n" characterInfo += "\n~~~~~~~~~ Specialty: "+self.specialty+" ~~~~~~~~\n"\ "\n"+self.specialtyStory+"\n" characterInfo += "\n ~~~~ Feats ~~~~\n" for i in range(1,self.level+1): if i == 1 or i%3 ==0: characterInfo += '\n Level '+str(i)+': '+self.feats[i]['name']+' '\ '('+self.feats[i]['type']+')\n'\ ' "'+self.feats[i]['description']+'"\n\n' if 'prereq' in self.feats[i]: characterInfo += ' Prerequisite: '+self.feats[i]['prereq']+'\n' if 'benefit' in self.feats[i]: characterInfo += ' Benefit: '+self.feats[i]['benefit']+'\n' if 'effect' in self.feats[i]: characterInfo += ' Effect: '+self.feats[i]['effect']+'\n' characterInfo += "\n~~~~~~~~~ Background: "+self.background+" ~~~~~~~~\n" if self.backgroundProfession == '': pass else: characterInfo += "Profession: "+self.backgroundProfession characterInfo += "\n "+self.backgroundStory return characterInfo class Dwarf(Character): def __init__(self,level=1,characterName=randomNames["Dwarf"][r.randint(0,len(randomNames["Dwarf"])-1)]): Character.__init__(self,level) self.characterName = characterName self.race = "Dwarf" self.subrace = raw_input("Are you a (1) Hill Dwarf or (2) Mountain Dwarf? (input number) ") print while self.subrace not in ['1','2']: self.subrace = raw_input("Are you a (1) Hill Dwarf or (2) Mountain Dwarf? (input number) ") print self.traits = self.createTraits('Races/Dwarf_Traits.txt','Traits','Stop') #if Hill Dwarf if self.subrace == '1': self.str += 1 self.traits['Dwarven Toughness'] = 'Your hit point maximum increases by 1 and it increases by 1 every time you gain a level. Additionally, whenever you roll Hit Dice during a rest, you regain 1 extra hit point for each Hit Die you roll.' self.traits['Subrace'] = "Hill Dwarf" self.hp += 1 self.classMods[6] += 1 #if Mountain Dwarf elif self.subrace == '2': self.wis += 1 self.traits['Armor Mastery'] = 'You are proficient with light and medium armor. While wearing medium or heavy armor, you gain a +1 bonus to Armor Class.' self.traits['Subrace'] = 'Mountain Dwarf' #Choose a class,background,skills,specialty,feats self.chooseClass() self.backgroundAndSkills() self.chooseSpecialties() self.populateFeats() print self.__str__() class Elf(Character): def __init__(self,level=1,characterName=randomNames["Elf"][r.randint(0,len(randomNames["Elf"])-1)]): Character.__init__(self,level) self.characterName = characterName self.race = "Elf" self.subrace = raw_input("Are you a (1) High Elf or (2) Wood Elf? (input number) ") print while self.subrace not in ['1','2']: self.subrace = raw_input("Are you a (1) High Elf or (2) Wood Elf? (input number) ") print self.traits = self.createTraits('Races/Elf_Traits.txt','Traits','Stop') #Added dex due to trait self.dex += 1 #if High Elf if self.subrace == '1': self.int += 1 self.traits['Extra Language'] = "You can speak, read, and write one extra language of your choice." self.traits['Cantrip'] = "You know one cantrip of your choice from the wizard's cantrip list. Intelligence is your magic ability for it." self.traits['Subrace'] = 'High Elf' #if Wood Elf elif self.subrace == '2': self.wis += 1 self.traits['Speed'] = "35 Feet" self.traits['Fleet of Foot'] = "Your speed increases by 5 feet. (Already calculated)" self.traits['Mask of the Wild'] = 'You can attempt to hide even when you are only lightly obscured by foliage, heavy rain, falling snow, mist, and other natural phenomena.' self.traits['Subrace'] = "Wood Elf" #Choose a class,background,skills,specialty,feats self.chooseClass() self.backgroundAndSkills() self.chooseSpecialties() self.populateFeats() print self.__str__() class Halfling(Character): def __init__(self,level=1,characterName=randomNames["Halfling"][r.randint(0,len(randomNames["Halfling"])-1)]): Character.__init__(self,level) self.characterName = characterName self.race = "Halfling" self.subrace = raw_input("Are you (1) Lightfoot or (2) Stout? (input number) ") print while self.subrace not in ['1','2']: self.subrace = raw_input("Are you a (1) Lightfoot or (2) Stout? (input number) ") print self.traits = self.createTraits('Races/Halfling_Traits.txt','Traits','Stop') #Added dex due to trait self.dex += 1 #if Lightfoot if self.subrace == '1': self.cha += 1 self.traits['Naturally Stealthy'] = "You can attempt to hide even when you are obscurred only by a creature that is one size category larger than you." self.traits['Subrace'] = 'Lightfoot' #if Stout elif self.subrace == '2': self.con += 1 self.traits['Stout Resilience'] = 'You have advantage on saving throws against poison, and you have resistance against poison damage.' self.traits['Subrace'] = 'Stout' #Choose a class,background,skills,specialty,feats self.chooseClass() self.backgroundAndSkills() self.chooseSpecialties() self.populateFeats() print self.__str__() class Human(Character): ''' Input Level or leave blank for Level 1 ''' def __init__(self,level=1,characterName=randomNames["Human"][r.randint(0,len(randomNames["Human"])-1)]): Character.__init__(self,level) self.characterName = characterName self.race = "Human" self.traits = self.createTraits('Races/Human_Traits.txt','Traits','Stop') #A list of abilities abilities_list = ['str','dex','con','int','wis','cha'] #Add 1 to each ability score as guided by trait for i in abilities_list: self.stealthUpdate(i,1) #Choose a class,background,skills,specialty,feats() self.chooseClass() self.backgroundAndSkills() self.chooseSpecialties() self.populateFeats() print self.__str__()
9b19491c1d6dc59f2625f116470a1e147e2746f5
githubfun/LPTHW
/PythonTheHardWay/projects/lexicon_project/ex48/lexicon.py
1,252
4.25
4
# Created for Learning Python the Hard Way, Exercise 48 def scan(sentence_to_parse): directions = {'north', 'south', 'east', 'west', 'down', 'up', 'left', 'right', 'back'} verbs = {'go', 'kill', 'eat', 'stop', 'shoot'} stop_words = {'the', 'in', 'of', 'from', 'at', 'it', 'to'} nouns = {'bear', 'princess', 'door', 'cabinet'} new_sentence = [] words = sentence_to_parse.split() for word_to_test in words: try: num_as_int = int(word_to_test) word_tuple = ('number', num_as_int) new_sentence.append(word_tuple) except ValueError: if word_to_test in directions: word_tuple = ('direction', word_to_test) new_sentence.append(word_tuple) elif word_to_test in verbs: word_tuple = ('verb', word_to_test) new_sentence.append(word_tuple) elif word_to_test in stop_words: word_tuple = ('stop', word_to_test) new_sentence.append(word_tuple) elif word_to_test in nouns: word_tuple = ('noun', word_to_test) new_sentence.append(word_tuple) else: word_tuple = ('error', word_to_test) new_sentence.append(word_tuple) return new_sentence # input_sentence = raw_input("Give me a sentence: ") # output_sentence = scan(input_sentence) # print "word list is %r" % output_sentence
28be7aaf0233c6f98b89a0edd8ffd181be162299
Malakai13/chess-tree-explorer
/MoveCount.py
1,184
3.515625
4
class MoveCount: def __init__(self, move): self.move = move self.count = 1 self.white_wins = 0 self.black_wins = 0 def __init__(self, move, game_results): self.move = move self.count = 1 self.black_wins = 0 self.white_wins = 0 self.increment_by_game_results(game_results) def increment_count(self): self.count += 1 def increment_white(self): self.white_wins += 1 def increment_black(self): self.black_wins += 1 def increment_by_game_results(self, game_results): if game_results == "1-0": self.increment_white() elif game_results == "0-1": self.increment_black() def win_str(self): total = self.white_wins + self.black_wins if total == 0: return "N/A" white_win_percentage = 100.0 * self.white_wins / total black_win_percentage = 100.0 * self.black_wins / total return "{0:.2f}".format(white_win_percentage) + "|" + "{0:.2f}".format(black_win_percentage) def __str__(self): return str(self.move) + ":" + str(self.count) + " " + self.win_str() def __repr__(self): return self.__str__() def __eq__(self, other): if isinstance(other, self.__class__): return self.move == other.move else: return False
fd24b3900bc159123582a764faa95efbf5f54eef
SimonFans/LeetCode
/OA/MS/Numbers With Equal Digit Sum.py
442
3.796875
4
def find_digit_sum(num): val = 0 while num: val += num % 10 num //= 10 return val def num_digit_equal_sum(arr): digit_sum_map = {} max_val = -1 for num in arr: digit_sum = find_digit_sum(num) if digit_sum in digit_sum_map: other_val = digit_sum_map[digit_sum] max_val = max(max_val, other_val + num) digit_sum_map[digit_sum] = max(other_val, num) else: digit_sum_map[digit_sum] = num return max_val
7fa8b029ce0ece9eaec2ad5a68e68c003329aad6
yilmazelif97/librarymanagementsystem
/DataAccess.py
861
3.65625
4
import sqlite3 as sqlite connection = sqlite.connect('library.db') connection.row_factory = sqlite.Row # Enables accessing columns via names database = connection.cursor() def getLogin(userloginname, password): result = database.execute(''' SELECT * FROM user WHERE userloginname = ? AND password = ? ''',(userloginname, password)).fetchall() if(len(result) == 1): return result[0] return False def getBook(userID): query = "SELECT BOOKID, RETURNDATE FROM borrow WHERE USERID = %d" % userID result = database.execute(query).fetchall() if(len(result) == 1): return result[0] return False def username(userID): query = "SELECT USERNAME FROM user WHERE USERID=%d" % userID result = database.execute(query).fetchall() if len(result)==1: return result[0] return False
37af10df860fe06d3d3518481ee71aaa37833c87
prernaralh19/file
/que4.py
158
3.765625
4
def test_range(n): if n in range (10,100): print ("10 is in the range 100" (n)) else: print("the number is outside the given range") test_range(10)
b5974ffb1b7fcf00ffe5ba96953cedeb6df68bd8
Mahler7/zelle-python-exercises
/ch8/ch8-ex7.py
1,162
4.09375
4
def goldbach_values(primes, n): highValue = n / 2 for i in primes: if i <= highValue and n - i in primes: print("Prime values {0} + {1} = {2}".format(i, (n - i), n)) def get_primes(n): p = 2 primes = [] while p <= n: if is_prime(p): primes.append(p) p = p + 1 goldbach_values(primes, n) def is_prime(n): i = 2 isPrime = False while i < n: if n % i == 0: return False i = i + 1 return True def inputs(): validNumber = False while validNumber == False: try: n = eval(input("Enter a number: ")) if n <= 0: print("Please enter a value greater than 0") elif n % 2 != 0: print("Please enter an even number") elif n > 0: validNumber = True except NameError: print("Enter a valid number") return n def intro(): print("This program executes the Goldbach conjecture") print("by finding the two prime numbers that add up to the even value") def main(): intro() n = inputs() get_primes(n) main()
193f3f0ba4b3771d957df995d521b706363c07f2
AMBrown0/DataVizAss02
/Python/sigmoid.py
1,238
3.703125
4
# -*- coding: utf-8 -*- """ Created on Sun Feb 7 16:28:27 2021 @author: andy """ #import section from matplotlib import pylab import pylab as plt import numpy as np #sigmoid = lambda x: 1 / (1 + np.exp(-x)) def sigmoid(x): return (1 / (1 + np.exp(-x))) mySamples = [] mySigmoid = [] # generate an Array with value ??? # linespace generate an array from start and stop value # with requested number of elements. Example 10 elements or 100 elements. # x = plt.linspace(-10,10,10) y = plt.linspace(-10,10,100) # prepare the plot, associate the color r(ed) or b(lue) and the label plt.plot(x, sigmoid(x), 'r', label='linspace(-10,10,10)') plt.plot(y, sigmoid(y), 'b', label='linspace(-10,10,100)') # Draw the grid line in background. plt.grid() # Title & Subtitle plt.title('Sigmoid Function') plt.suptitle('Sigmoid') # place the legen boc in bottom right of the graph plt.legend(loc='lower right') # write the Sigmoid formula plt.text(4, 0.8, r'$\sigma(x)=\frac{1}{1+e^{-x}}$', fontsize=15) #resize the X and Y axes plt.gca().xaxis.set_major_locator(plt.MultipleLocator(1)) plt.gca().yaxis.set_major_locator(plt.MultipleLocator(0.1)) # plt.plot(x) plt.xlabel('X Axis') plt.ylabel('Y Axis') # create the graph plt.show()
f3b47758b43ba94dd3e47698b4aa69f8fa0c229d
harshiniravula/DSP_LAB
/lab1_prog2(matrix_inverse).py
1,200
4.1875
4
# python code to find transpose of a matrix def cofactor(a): b=len(a) cofactor=[] for i in range(b): m1=[] for j in range(b): m2=[] for k in range(b): m3=[] for l in range(b): if(i==k or j==l): continue m3.append(a[k][l]) if(e!=[]): m2.append(e) if((i+j)%2==0): m=1 else: m=-1 y=det(d) m1.append(y*m) cofactor.append(c) return cofac def det(a): b=len(a) if(b==1): f=a[0][0]*1.0 return f elif(b==2): f=(a[0][0]*a[1][1]-a[0][1]*a[1][0])*1.0 return f else: k=[] k=cofactor(a) f=0.0 for l in range(b): f=f+(a[0][1]*t[0][1]) return f def transpose(a): b=len(a) m2=[] for j in range(b): f=[] for i in range (b): f.append(a[i][j]) m2.append(f) return m2 print"enter the matrix format\n[[a11,a12,....a1n],[a21,a22,....,a2n],.....[an1,an2,.....,ann]]" a=input("enter the elements for matrix") b=len(a) f=det(a) if(f==0): print("inverse of the given matrix is not possible") elif(b==1): inv=[[1.0/a[0][0]]] print inv else: inverse=transpose(cofactor(a)) for i in range(b): for j in range(b): inv[i][j]=inv[i][j]/f print invs
4b6edb266a39f582b108de4e45cf5380bb9276cc
SimonSlominski/Pybites_Exercises
/Pybites/135/books.py
2,725
4.25
4
""" Bite 135. Sort a list of book objects In this Bite you are going to look at a list of Book namedtuples and sort them by various criteria. Complete the 4 functions below. Consider using lambda and/or one or more helper functions and/or attrgetter (operator module). """ from collections import namedtuple from datetime import datetime from operator import attrgetter Book = namedtuple('Book', 'title authors pages published') books = [ Book(title="Python Interviews", authors="Michael Driscoll", pages=366, published="2018-02-28"), Book(title="Python Cookbook", authors="David Beazley, Brian K. Jones", pages=706, published="2013-05-10"), Book(title="The Quick Python Book", authors="Naomi Ceder", pages=362, published="2010-01-15"), Book(title="Fluent Python", authors="Luciano Ramalho", pages=792, published="2015-07-30"), Book(title="Automate the Boring Stuff with Python", authors="Al Sweigart", pages=504, published="2015-04-14"), ] # all functions return books sorted in ascending order. def sort_books_by_len_of_title(books=books): """ Expected last book in list: Automate the Boring Stuff with Python """ return sorted(books, key=lambda x: len(x[0])) def sort_books_by_first_authors_last_name(books=books): """ Expected last book in list: Automate the Boring Stuff with Python """ return sorted(books, key=lambda x: x[1].split(" ")[1]) # def _get_first_authors_last_name(book): # return book.authors.split(',')[0].split()[-1] # # # def sort_books_by_first_authors_last_name(books=books): # """ # Expected last book in list: # Automate the Boring Stuff with Python # """ # # 2. complex lambda -> helper function # return sorted(books, key=_get_first_authors_last_name) def sort_books_by_number_of_page(books=books): """ Expected last book in list: Fluent Python """ return sorted(books, key=lambda x: x[2]) # def sort_books_by_number_of_page(books=books): # """ # Expected last book in list: # Fluent Python # """ # # 3. by attribute -> attrgetter # return sorted(books, key=attrgetter("pages")) def sort_books_by_published_date(books=books): """ Expected last book in list: Python Interviews """ return sorted(books, key=lambda x: x[3]) # def _date_str_to_dt(book): # return datetime.strptime(book.published, '%Y-%m-%d') # # def sort_books_by_published_date(books=books): # """ # Expected last book in list: # Python Interviews # """ # # 2b. again more readable using a helper function # return sorted(books, key=_date_str_to_dt)
4bc6c85d1990d48694e80eb365770f35a23903c7
Grillern/H20_project0_harrisms_Optional_Exercise
/calculator.py
1,219
3.9375
4
def add(x, y): return x + y def factorial(n): if type(n) is int and n >= 0: factorial = 1 for i in range(1, int(n)+1): factorial *= i return factorial else: raise Exception(f"Factorial cannot be {type(n)} or a negative number. Type a natural number") def sin(x, N): if type(x) is int: taylor_sin = 0 for n in range(N): taylor_sin += ((-1)**n) * (x**(2*n+1)) / factorial(2*n+1) return taylor_sin else: raise Exception(f"Sin cannot be {type(x)}. Type an integer") def divide(x, y): if type(x) and type(y) is int or float: return x/y else: raise Exception(f"Divide cannot be {type(x)} and {type(y)}. Type an integer or float") def cos(x, N): if type(x) is int: taylor_cos = 0 for n in range(N): taylor_cos += ((-1)**n) * (x**(2*n)) / factorial(2*n) return taylor_cos else: raise Exception(f"Cos cannot be {type(x)}. Type an integer") def power(x, y): if type(x) and type(y) is int or float: return x ** y else: raise Exception(f"Power of cannot be {type(x)} and {type(y)}. Type an integer or float")
499bc6dc2a5430049a5002fd54df3afb4fbbfc95
DemonsHacker/learntf
/python/mo_fan/01_python3/02_if_else.py
219
4.21875
4
x = 1 y = 2 z = 3 if x<y: print('x is less than y') else: print('y is less than x') if x<y and y<z: print('x is less than y,and y is less than z') x = 2 y = 2 z = 0 if x == y: print("x is equal to y")
663c582183d36b6d261be256775d3955bcffac83
cielavenir/codeiq_solutions
/tbpgr_colosseum_manager/q1027/death6_1.py
75
3.53125
4
print(':'.join(str(i)for i in range(2,999)if all(i%j for j in range(2,i))))
dd6630cb373ab75e4c772626accb30dbc85d2b5b
sshukla31/leetcode
/wiggle_sort.py
1,082
4.1875
4
''' 280. Wiggle Sort Medium 344 42 Favorite Share Given an unsorted array nums, reorder it in-place such that nums[0] <= nums[1] >= nums[2] <= nums[3].... Example: Input: nums = [3,5,2,1,6,4] Output: One possible answer is [3,5,1,6,2,4] ''' class Solution(object): def wiggleSort(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ if not nums or len(nums) == 0: return wave = True for i in range(len(nums)-1): if wave: if nums[i] > nums[i+1]: nums[i], nums[i+1] = nums[i+1], nums[i] # swap else: if nums[i] < nums[i+1]: nums[i], nums[i+1] = nums[i+1], nums[i] # swap wave = not wave # toggle value to create value return nums if __name__=='__main__': sol = Solution() nums = [3,5,2,1,6,4] actual_result = sol.wiggleSort(nums) expected_result = [3,5,1,6,2,4] assert actual_result == expected_result
36c7023ceb1afa8065832ab6b8af1edca8fe9697
arononeill/Python
/ClassAttributes.py
1,008
4.21875
4
# Built-In Class Attributes class Employee: 'Common base class for all employees' empCount = 0 def __init__(self, name, salary): self.name = name self.salary = salary Employee.empCount += 1 def displayCount(self): print "Total Employee %d" % Employee.empCount def displayEmployee(self): print "Name : ", self.name, ", Salary: ", self.salary print "Employee.__doc__:", Employee.__doc__ # Class Documentation String (the comment at the start of the class) print "Employee.__name__:", Employee.__name__ # Class name print "Employee.__module__:", Employee.__module__ # Module name in which the class is defined. The "_main_" in interactive mode print "Employee.__bases__:", Employee.__bases__ # A possibly empty tuple containing the base classes, in the order of their occurrence in the base class list print "Employee.__dict__:", Employee.__dict__ # A possibly empty tuple containing the base classes, in the order of their occurrence in the base class list
521fcd2ecf232bddf99b5c8a9fcba26b507b09da
colinsongf/6.00.1x_Python_course
/wordgame.py
3,601
3.9375
4
# Fisseha Berhane # MITx: 6.00.1x Introduction to Computer Science and Programming Using Python # Problem set 4 #dictionary = raw_input('Please give the word list file name\n\t') # This waits for the word list file name with appropriate extention #f = open(dictionary, "r") f = open('sowpods.txt', "r") print'' print 'Loading word list from file...' word_list =[] for line in f: line = line.strip() word_list.append(line) f.close() print str(len(word_list))+' words loaded.' print('') SCRABBLE_LETTER_VALUES = {"a": 1, "c": 3, "b": 3, "e": 1, "d": 2, "g": 2, "f": 4, "i": 1, "h": 4, "k": 5, "j": 8, "m": 3, "l": 1, "o": 1, "n": 1, "q": 10, "p": 3, "s": 1, "r": 1, "u": 1, "t": 1, "w": 4, "v": 4, "y": 4, "x": 8, "z": 10} option = raw_input('Enter n to deal a new hand, r to replay the last hand, or e to end game:\n\t') if option=='e': print '\t Ok, see you next time' elif option=='n' or option=='r': hand=raw_input('Current Hand: ') hand_letters = list(hand) word = raw_input('Enter word, or a "." to indicate that you are finished: ') if word!='.': word_letters=list(word) candidate =True for letter in word_letters: if letter not in hand_letters: candidate=False break # No need to keep checking letters. else: hand_letters.remove(letter) if candidate==True: if word in word_list: # Get the Scrabble SCRABBLE_LETTER_VALUES for each legal word total = 0 for letter in word: total=total+SCRABBLE_LETTER_VALUES[letter] if len(word)==7: total=total*len(word)+50 # 50 point bonus for using all letters). else: total=total*len(word) if len(word)==7: print '"%s"'%word + ' earned '+ str(total) +' points. Total: '+ str(total)+' points' print 'Run out of letters. Total score:'+str(total)+' points. Nice Job!!' exit # no nead to go any further else: print '"%s"'%word + ' earned '+ str(total) +' points. Total: '+ str(total)+' points' print 'Current Hand: '+''.join(hand_letters) else: print 'That is not a valid word. Please provide a legal word' print 'Current Hand: '+''.join(hand_letters) else: print 'please provde a word from the hand you have' while len(hand_letters)>=2: word = raw_input('Enter word, or a "." to indicate that you are finished: ') if word=='.': print 'Total score: '+str(total)+' points.' break elif word!='.': hand_letters2=hand_letters[:] word_letters=list(word) for letter in word_letters: if letter not in hand_letters: candidate=False break # No need to keep checking letters. else: hand_letters.remove(letter) if candidate==True: if word in word_list: # Get the Scrabble SCRABBLE_LETTER_VALUES for each legal word tot=0 for letter in word: tot=tot+SCRABBLE_LETTER_VALUES[letter] tot=tot*len(word) total = total+tot print '"%s"'%word + ' earned '+ str(tot) +' points. Total: '+ str(total)+' points' print 'Current Hand: '+''.join(hand_letters) else: print 'That is not a valid word. Please choose another word' print 'Current Hand: '+''.join(hand_letters2) else: print 'please provde a word from the hand you have'
f2ed8fc548ac55b2b2404e881a31bc2d5482addb
eebmagic/phy214_enterprise_online
/python_functions/optics/lenses.py
2,041
4
4
''' A collection of functions using formulas related to projections through lenses ''' def image_distance(object_distance, focal_distance): ''' Returns the distance (cm) to the projected image Given the: distance to the object being projected (cm), focal distance of the lens (cm) Formula: 1/f = 1/s + 1/s' s' = 1 / (1/f - 1/s) f: focal distance s: object distance s': projected image distance ''' denom = 1/focal_distance - 1/object_distance s_prime = 1 / denom return s_prime def image_height(object_height, object_distance, projection_distance): ''' Returns the height (cm) of the projection of the object Given the: height to object (cm), distance to object (cm), distance to projection (cm) Formula: y' / y = -s' / s y' = (-s' / s) * y y: height of object y': height of projection s: distance to object s': distance to projection ''' projection_height = (-projection_distance / object_distance) * object_height return projection_height def focal_point(curvature_radius): ''' Returns the focal distance (cm) Given the: radius of the curvature of the lens Formula: f = 1/2 * r f: focal distance (cm) r: radius of lens curvature (cm) ''' return (1/2) * curvature_radius def curve_radius(focal_dist): ''' Returns the radius (cm) of the lens curvature Given the: focal_dist Formula: f = 1/2 * r r = 2 * f f: focal distance (cm) r: radius of lens curvature (cm) ''' return 2 * focal_dist if __name__ == "__main__": obj_dist = 30 obj_height = 5 focal_point = -25 projection_dist = image_distance(obj_dist, focal_point) projection_height = image_height(obj_height, obj_dist, projection_dist) print(f"projection_dist: {projection_dist}") print(f"projection_height: {projection_height}")
58dc93bccbc91f856bb8d32f735b988c18fb3aca
momo1606/Takhteet
/takhteet/takhteet.py
2,288
3.75
4
import test import myiter import time print("*********************** WELCOME ***************************") print("USER GUIDELINES") print("\n1. The user has to feed-in the following details:\n\ta)Number of students.\n\tb) Total number of days\n\t and then for each student,\n\tc) Student's name.\n\td) Student's current surat/page number and ayat/line number.\n\te) Number of safahs/lines per day assigned to the student.") print("\n2. Takhteet can be made safah wise or line wise with the least entity of safah being 0.25.") print("\n3. All the takhteets of students will be generated in the excel file\n 'takhteet.xlsx' while the program is being\n executed.\n The excel file should be closed while the program is being executed,\n and both the program and the excel file saved in the same directory.") print("\n4. User can either select the tabular layout or grid layout of takhteet.") wait = input("\nPRESS ENTER TO CONTINUE.") print ("\n" * 4) studs=int(input("Enter number of students ")) year=int(input("Enter hijri year ")) yr=myiter.to_arab(year) mon=int(input("Enter hijri month no. ")) mont=myiter.month[mon-1] tno=int(input("Enter total no.of working days of this month ")) form=int(input("Enter 1 for tabular or 2 for grid display of takhteet form in excel ")) print("\n") z=1 while(studs>0): j=0 print("\n") print("For student ",z,":") name=input("Enter student name ") flag=int(input("Enter \n1. for line wise takhteet \n2. for page wise \n")) if(flag==2): n=float(input("Enter number of pages per day in multiples of 0.25 ")) sur=int(input("Enter current surat no. ")) x=int(input("Enter current ayat number ")) v=test.line_search2(x,sur,n,tno) myiter.to_excel1(v,tno,form,name,n,mont,yr) elif(flag==1): n=int(input("Enter number of lines per day ")) sur=int(input("Enter current page no.(1-604) ")) x=int(input("Enter current line number(1-15) ")) v=test.line_search1(x,sur,n,tno) myiter.to_excel2(v,tno,form,name,n,mont,yr) print("\nTakhteet added in excel sheet") studs-=1 z=z+1 print(" معهد الزهراء-الشارقة") print("\n") print(" 'السهولة في التخطيط' ") print("\n") print("\n\t Mohammed Kothaliya") time.sleep(5)
2c7f6a6bb0ab06e16b476ab5cb0df7d4ccfd011c
juliermili/seminario
/Historico/Ejer teoria 1.py
356
3.6875
4
def futuro(edad): edad = edad + 1 def pasado(): edad = edad - 1 edad = int(input('Ingresa tu edad: ')) resp = int(input("""Elige una opción: 1.- El año que viene tu edad será... 2.- El año pasado tu edad era.... """)) if resp == 1: futuro(edad) print (edad) else: pasado() print (edad)
640519a533c85d16321b70427e2b4ecc135dd2d4
jordano1/python
/python_education/regex/regex.py
1,136
4.3125
4
import re string = "search this inside of this text please!" # methods in re.search print('search' in string) a = re.search('this', string) print('tells you where the string is index: ', a.span()) # 17, 21 print('start tells you when the text starts:', a.start()) # 17 print('tells you where the text ends: ' , a.end()) # 21 print('gives you the string: ', a.group()) # this, good for multiple searches # re.search # just one search, a pattern we're trying to match a = re.search('this', string) # a = re.search('thas', string) if it doesn't exist it will return nontype print(a.group()) # recompile pattern = re.compile('search this inside of this text please!') string = "search this inside of this text please!" # b = pattern.search('thIs', string) don't need to pass a string, take thIs out because we are putting 'this' as the pattern var on line 18, and we're using pattern.search(string) b = pattern.search(string) c = pattern.findall(string) d = pattern.fullmatch(string) pattern = re.compile('search this inside of this text please!') string = "search this inside of this text please!" d = pattern.match(string) print(d)
c7c30b55093879b4af4a70d5274bd39a0326a837
letsbrewcode/python-coding-lab
/lab-9/fizzbuzz.py
557
4.21875
4
""" Problem: FizzBuzz Complete the function below. For a number N, print all the numbers starting from 1 to N, except 1. For numbers divisible by 3, print "Fizz" 2. For numbers divisible by 5, print "Buzz" 3. For numbers divisible by both 3 and 5, print "FizzBuzz" Example: N = 30 Output: 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 16 """ def fizzbuzz(n): # +++ Your code here +++ return if __name__ == "__main__": fizzbuzz(100)
b6eeefcea1b0eda6fb8964fa80fbdde214fbc893
v-glovatskiy/playground
/log1.py
275
3.515625
4
from sys import argv script, filename = argv name = 'COMPLETED after 1' txt = open(filename) print ('Содержимое файла %r' % filename) #print (txt.read()) for string in txt: if name in string: print(string)
986a00007a84702ef34c948faae02a176b0c92b6
DecadentOrMagic/XY_python3_lxf
/01_Python基础/02_使用list和tuple.py
3,721
4.40625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # List # Python内置的一种数据类型是列表:list。list是一种有序的集合,可以随时添加和删除其中的元素。 # 变量classmates就是一个list # ************************************* classmates = ['Michael','Bob','Tracy'] print(classmates) # 获取list元素的个数 print(len(classmates)) # 用索引来访问list中每一个位置的元素,记得索引是从0开始的 print(classmates[0]) print(classmates[1]) print(classmates[2]) # 如果要取最后一个元素,除了计算索引位置外,还可以用-1做索引,直接获取最后一个元素 print(classmates[-1]) # 以此类推,可以获取倒数第2个、倒数第3个 print(classmates[-2]) print(classmates[-3]) # list是一个可变的有序表,所以,可以往list中追加元素到末尾 # ************************************* classmates.append('Adam') print(classmates) # 也可以把元素插入到指定的位置,比如索引号为1的位置 classmates.insert(1,'Jack') print(classmates) # 要删除list末尾的元素,用pop()方法 # ************************************* classmates.pop() print(classmates) # 要删除指定位置的元素,用pop(i)方法,其中i是索引位置 classmates.pop(1) print(classmates) # 要把某个元素替换成别的元素,可以直接赋值给对应的索引位置 # ************************************* classmates[1] = 'Sarah' print(classmates) # list里面的元素的数据类型也可以不同 # ************************************* L = ['Apple',123,True] print(L) # list元素也可以是另一个list # ************************************* s = ['python','java',['asp','php'],'scheme'] print(s) print(len(s)) # 要注意s只有4个元素,其中s[2]又是一个list,如果拆开写就更容易理解了 p = ['asp','php'] s = ['python','java',p,'scheme'] print(s) # 要拿到'php'可以写p[1]或者s[2][1],因此s可以看成是一个二维数组,类似的还有三维、四维……数组,不过很少用到 # tuple # 另一种有序列表叫元组:tuple。tuple和list非常类似,但是tuple一旦初始化就不能修改 # ************************************* classmates = ('Michael','Bob','Tracy') # classmates这个tuple不能变了,它也没有append(),insert()这样的方法。其他获取元素的方法和list是一样的,你可以正常地使用classmates[0],classmates[-1],但不能赋值成另外的元素 # 不可变的tuple有什么意义?因为tuple不可变,所以代码更安全。如果可能,能用tuple代替list就尽量用tuple。 # tuple的陷阱:当你定义一个tuple时,在定义的时候,tuple的元素就必须被确定下来,比如 t = (1,2) print(t) # 如果要定义一个空的tuple,可以写成() t = () print(t) # ************************************* # t = (1) # 定义的不是tuple,是1这个数!这是因为括号()既可以表示tuple,又可以表示数学公式中的小括号,这就产生了歧义,因此,Python规定,这种情况下,按小括号进行计算,计算结果自然是1 # 只有1个元素的tuple定义时必须加一个逗号,,来消除歧义 t = (1,) print(t) # “可变的”tuple # ************************************* t = ('a','b',['A','B']) t[2][0] = 'X' t[2][1] = 'Y' print(t) # 表面上看,tuple的元素确实变了,但其实变的不是tuple的元素,而是list的元素。tuple一开始指向的list并没有改成别的list,所以,tuple所谓的“不变”是说,tuple的每个元素,指向永远不变。即指向'a',就不能改成指向'b',指向一个list,就不能改成指向其他对象,但指向的这个list本身是可变的!
bcd4f4b15e374d4bf32d0f13bcca4c64aead6a05
VaishnaviReddyGuddeti/Python_programs
/Python_Sets/getthelengthofaset.py
197
4.25
4
# To determine how many items a set has, use the len() method. #Get the number of items in a set: thisset = {"apple", "banana", "cherry"} print(len(thisset)) thisset = {" "} print(len(thisset))
bcc47559030863467b689d5a18b9490b19469f7b
ninjaboynaru/my-python-demo
/leetcode/94-binary-tree-inorder-traversal.py
554
3.5625
4
from utils import TreeNode, stringToTreeNode from typing import List class Solution: def inorderTraversal(self, root: TreeNode) -> List[int]: if root is None: return [] res = [root.val] left = self.inorderTraversal(root.left) right = self.inorderTraversal(root.right) res = left + res + right return res if __name__ == "__main__": t = stringToTreeNode("[1,null,2,3]") print(Solution().inorderTraversal(t)) t = stringToTreeNode("[]") print(Solution().inorderTraversal(t))
861389b28c0b685065defd0ae85d92a63e742079
JordanWauchope/Python
/Excercises/ExcercisesSep28/Sec10-String.py
785
3.671875
4
useInputs = False def sentence1(): sentence = "I like to go on holiday by the sea." for x in sentence: print(x) # sentence1() def sentence2(): sentence = "I like to go on holiday by the sea" print(len(sentence)) for x in sentence: if 7 <= x < 24: print(sentence[x]) # sentence2() def sentence3(s): y = 0 for x in s: if x == "a": y += 1 return y if useInputs: sentence = input("Please enter a sentence: ") else: sentence = "I like to eat icecream on a sunny day." print(sentence3(sentence)) def sentence4(s): if s[::-1].lower() == s.lower(): print("%s is a palindrome." % s) if useInputs: word = input("Please enter a word: ") else: word = "Noon" sentence4(word)
ecd3b4bb48ebbb254d361477ecd3894c0feb09c3
bgergovski/simple-webapp
/other/classes.py
202
3.609375
4
class Person: def __init__(self, name): self.name = name def talk(self): print(f"{self.name} is my name") person_1 = Person("Bobby") person_1.talk() x = "Hello"[0] print({x})
fbe0d6bc2ba6fe23a67c59119e5197acbb29c44d
thonathan/Ch.02_Algebra
/2.0_Jedi_Training.py
939
4.28125
4
''' Sign your name:______ethan januszewski__________ 1.) How do you enter a single line comment in a program? Give an example. 2.) Enter a=2 and b=5 in the Python Console window and then all of the following. What are the outputs? If the output is an error record the error and try to determine what the error is! b/a = 2.5 b//a = 2 b**a = 25 b%a = 1 a+B = ERROR type(42) = int type(42.0) = float type("C3PO") = str type(True) = bool 3.) What is the final outp ut of (a) and type(a) if you enter the following 5 lines into the Python Console Window? a=2 a*=10 a/=2 a+=12 a-=7 a = 15.0 type(a) = float 4.) What is the mistake in the following code. Fix it! x,y=(4,5) a=3*(x+y) a 5.) What is the mistake in the following code so it will calculate the average. Fix it! x,y,z=(3,4,5) ave=(x+y+z)/3 ave '''
ef319c8112b043034d165bf0dbec05ea969f3065
subaquatic-pierre/algorithmic-toolbox
/divide_algorithms/majority_element/majoity_element.py
619
3.6875
4
# Uses python3 import sys def get_majority_element(a, left, right): size = len(a) value_counts = {} for elem in a: if elem in value_counts.keys(): value_counts[elem] += 1 else: value_counts[elem] = 1 found = False for key, value in value_counts.items(): if value > size / 2: found = True return key if not found: return -1 if __name__ == "__main__": input = sys.stdin.read() n, *a = list(map(int, input.split())) if get_majority_element(a, 0, n) != -1: print(1) else: print(0)
d7af1d4eaadc8ec39427784cf1ec8f7aee0ff007
arnabs542/achked
/python3/company/lnkd_rpn_eval.py
862
3.75
4
#!/usr/bin/env python3 def evalRPN(self, tokens): stack = [] for t in tokens: if t not in ["+", "-", "*", "/"]: stack.append(int(t)) else: r, l = stack.pop(), stack.pop() if t == "+": stack.append(l+r) elif t == "-": stack.append(l-r) elif t == "*": stack.append(l*r) else: # here take care of the case like "1/-22", # in Python 2.x, it returns -1, while in # Leetcode it should return 0 # # This may not be needed for python3 if l*r < 0 and l % r != 0: stack.append(l/r+1) else: stack.append(l/r) return stack.pop() # 1 + 3 = 3 1 + # 1 + 2 * 3 = 1 2 + 3 *
42a46914a360a1dc4cc63a5a0ea0c035c4ee9e7d
Programmer-Admin/binarysearch-editorials
/Contiguous Intervals.py
598
3.515625
4
""" Contiguous Intervals We iterate over the sorted numbers, each time the present number isn't equal to the past number, we append the interval. Trick so you don't have to deal with edge cases: add big value at end, so you don't need to check if you reached the end, or if the list is at least length 2. """ class Solution: def solve(self, nums): nums.sort() nums.append(1e9) ans=[] l=nums[0] for i in range(1,len(nums)): if nums[i] != nums[i-1] + 1: ans.append([l, nums[i-1]]) l=nums[i] return ans
7e8a9217dc478c89305b533e62219703a5a0f61b
kammitama5/Wally_Scale_game
/_005.py
1,771
4.21875
4
# build a game where if something is on a scale, calculate how much weight # kg vs pounds # Prints Welcome to Wally the scale. # You can weigh things with me. # Would you like to work in kg or pounds. Choose option # Bilingual..which want me to speak (implement library # Please select an object to weigh from choices # a b c d e f g # Tells you what you chose def Menu(): raw_input("Welcome to Wally the scale.\n" "You can weigh things with me.\n"); print("I'm Bilingual. Should I speak in kg or pounds?"); choice = raw_input("Pick 1 for kg or 2 for lbs"); # if entered 1, choice = choice otherwise choice = 2.2 * choice choice1 = float(choice); if (choice == "1"): choice1; raw_input("You chose kg => pounds"); elif (choice == "2"): (choice1 * 2.2) raw_input("You choise lbs => pounds"); else: choice = raw_input("This is not an option. Please try again"); weighobject = raw_input("Please select an object to weigh from choices: " "a through j\n" "a)Cat\n" "b)Bear\n" "c)Truck\n" "d)Trinidad\n" "e)White House\n" "f)Sequoia Tree\n" "g)Toilet Paper\n" "h) Bag of Flour\n" "i)Space Shuttle\n" "j)Box of Cue Tips\n"); #weightobject = #Cat => 4.5 kg #Bear => 272 kg #Truck => 2000 kg #Trinidad => 5.8 x 10^9 kg #White House => 10 866 217 kg #Sequoia Tree => 1 200 000 kg #Toilet Paper => .227 kg #Bag of Flour => 1.5 kg #Space Shuttle => 28945 kg #Box of Cue Tips => 1 kg Menu();
d51f78adced21aa103b44ebd2e5e1836d86e662a
prachuryanath/DSA-Problems
/Easy/21. Merge Two Sorted Lists/ans.py
342
3.5625
4
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: head = ListNode() curr = head while l1 and l2: while l1 and l2 and l1.val <= l2.val: curr.next = l1 l1 = l1.next curr = curr.next while l1 and l2 and l2.val <= l1.val: curr.next = l2 l2 = l2.next curr = curr.next curr.next = l1 or l2 return head.next
0e99844753b33b66d6e5fe283c9a84f16bf4256f
CristianCuartas/Python-Course
/Ejercicios/24- Objetos.py
305
4.03125
4
print('Objeto qué almacena el número y su potencia cuadrada') objeto = {} condicion = True while condicion: numero = int(input('Introduzca un número: ')) cuadrado = (numero**2) if numero != 0: objeto[numero] = cuadrado elif numero == 0: condicion = False print(objeto)
9699811745c9d7495ff8c48413d4406f431b9141
Lonitch/hackerRank
/leetcode/599.minimum-index-sum-of-two-lists.py
2,187
3.765625
4
# # @lc app=leetcode id=599 lang=python3 # # [599] Minimum Index Sum of Two Lists # # https://leetcode.com/problems/minimum-index-sum-of-two-lists/description/ # # algorithms # Easy (49.06%) # Likes: 467 # Dislikes: 172 # Total Accepted: 74.5K # Total Submissions: 150.5K # Testcase Example: '["Shogun","Tapioca Express","Burger King","KFC"]\n' + '["Piatti","The Grill at Torrey Pines","Hungry Hunter Steakhouse","Shogun"]' # # # Suppose Andy and Doris want to choose a restaurant for dinner, and they both # have a list of favorite restaurants represented by strings. # # # You need to help them find out their common interest with the least list # index sum. If there is a choice tie between answers, output all of them with # no order requirement. You could assume there always exists an answer. # # # # Example 1: # # Input: # ["Shogun", "Tapioca Express", "Burger King", "KFC"] # ["Piatti", "The Grill at Torrey Pines", "Hungry Hunter Steakhouse", "Shogun"] # Output: ["Shogun"] # Explanation: The only restaurant they both like is "Shogun". # # # # Example 2: # # Input: # ["Shogun", "Tapioca Express", "Burger King", "KFC"] # ["KFC", "Shogun", "Burger King"] # Output: ["Shogun"] # Explanation: The restaurant they both like and have the least index sum is # "Shogun" with index sum 1 (0+1). # # # # # Note: # # The length of both lists will be in the range of [1, 1000]. # The length of strings in both lists will be in the range of [1, 30]. # The index is starting from 0 to the list length minus 1. # No duplicates in both lists. # # # # @lc code=start from collections import defaultdict class Solution: def findRestaurant(self, list1: List[str], list2: List[str]) -> List[str]: if not list1 or not list2: return [] ct = defaultdict(int) lids = 2**31 ans = [] for i,v in enumerate(list1): ct[v]=i+1 for i,v in enumerate(list2): if ct[v]>0: cs = i+ct[v]-1 if cs == lids: ans.append(v) if cs<lids: ans = [v] lids = cs return ans # @lc code=end
2920bb9e665cfe98e8be5a6067e88bb1196370fb
ml1976/tools
/remove_images_smaller_than/remove_images_smaller_than.py
478
3.546875
4
# put this file in the same folder as images, and set your height and width from PIL import Image import glob import os for filename in glob.glob('*.jpg'): #assuming jpg #print(filename) #file, ext = os.path.splitext(filename) image=Image.open(filename) width, height = image.size image.close() #close the file before removing, if not you get an error if (height<416 or width<416): #print(filename) os.remove(filename) # removes images smaller than size requested
60209ad440c3e568c665b4bcfb4106079499c62b
ayush7garg/RGB-Gray
/video.py
336
3.578125
4
import cv2 def gray(image): gray = cv2.cvtColor(image,cv2.COLOR_RGB2GRAY)#cvtColor converts an image from one color space to another return gray cap = cv2.VideoCapture("path of the video file") while(cap.isOpened()): _,frame = cap.read() gray_image = gray(frame) cv2.imshow('result',gray_image) cv2.waitKey(1)
41357bb12afc7cb165d872d10b1ceaa7f3636c4d
deartc/Fitnesspythonproject
/dancestepsthree.py
938
3.9375
4
import random ### Here you must define random for use. Otherwise, python3 will return as "radiant" not defined player = input("Player, choose your dance: ").lower() rand_num = random.randint(0,2) if rand_num == 0: computer = "bolero" elif rand_num == 1: computer = "hustle" else: computer = "samba" print(f"Computer chooses {computer}" ) if player == computer: print("Both instructor and dancer choose same dance!") elif player == "bolero": if computer == "samba": print("instructor chooses!") else: print("dancer chooses!") elif player == "hustle": if computer == "bolero": print("instructor chooses!") else: print("instructor chooses!") elif player == "samba": if computer == "hustle": print("instructor chooses!") else: print("dancer chooses!") else: print("Please enter a valid dance!")
a8374941d3c8ea5b4c9bf43a65ba16326f096c9d
karolinaewagorska/lesson2
/data.py
2,281
3.84375
4
# Задание 1 # Необходимо вывести имена всех учеников из списка с новой строки names = ['Оля', 'Петя', 'Вася', 'Маша'] for name in names: print(name) # Задание 2 # Необходимо вывести имена всех учеников из списка, рядом с именем показать количество букв в нём. names = ['Оля', 'Петя', 'Вася', 'Маша'] for name in names: print(name, len(name)) # Задание 3 # Необходимо вывести имена всех учеников из списка, рядом с именем вывести пол ученика is_male = { 'Оля': False, # если True, то пол мужской 'Петя': True, 'Вася': True, 'Маша': False, } names = ['Оля', 'Петя', 'Вася', 'Маша'] for name in is_male.keys(): if is_male[name]: print(name, "Man") else: print(name, "Woman") # Задание 4 # Даны группу учеников. Нужно вывести количество групп и для каждой группы – количество учеников в ней # Пример вывода: # Всего 2 группы. # В группе 2 ученика. # В группе 3 ученика. groups = [ ['Вася', 'Маша'], ['Оля', 'Петя', 'Гриша'], ] print("number_of_groups =", len(groups)) number1 = 0 for pupils in groups[0]: number1 = number1 + 1 print("pupils_class_1 =", number1) number2 = 0 for pupils in groups[1]: number2 = number2 + 1 print("pupils_class_2 =", number2) # Задание 5 # Для каждой пары учеников нужно с новой строки перечислить учеников, которые в неё входят. # Пример: # Группа 1: Вася, Маша # Группа 2: Оля, Петя, Гриша groups = [ ['Вася', 'Маша'], ['Оля', 'Петя', 'Гриша'], ] class_one = '' for pupil in groups[0]: class_one = class_one + ' ' + pupil print("pupils_class_1 =", class_one) class_two = '' for pupil in groups[1]: class_two = class_two + ' ' + pupil print("pupils_class_2 =", class_two)
ed465eb2bfb4ae99f828b704b0296cb2dc31f9b5
Goodusernamenotfound/c4t-nhatnam
/session7/districts.py
468
3.90625
4
name = ["ST", "BĐ", "BTL", "CG", "ĐĐ", "HBT"] population = [150300, 247100, 333300, 266800, 420900, 31800] # highest = 4 # lowest = 0 # print("District with highest population:", name[highest], "with", population[highest], "residents") # print("District with lowest population:", name[lowest], "with", population[lowest], "residents") index = int(input("Enter index: ")) print("The district with that index is", name[index], "with", population[index], "residents")
85b53898c2dada92118141c243070bd8447da15f
daviddumas/pmls05-demo
/samples/representation.py
624
3.578125
4
'''Demonstrate computing 2x2 matrix representation from strings''' # ---- BEGIN code from presentation slide ---- import numpy as np def representation(gen_matrices): def _rho(x): if len(x) == 0: # identity matrix return np.eye(2) elif len(x) == 1: # generator matrix return gen_matrices[x] else: N = len(x) return np.dot(_rho(x[:N//2]),_rho(x[N//2:])) return _rho rho = representation( {'a': np.array( [[0,1],[1,1]] )} ) # etc print(rho('aaaaa')) # -> [[3 5], [5 8]] # ---- END code from presentation slide ----
65885e96aca4b958d6ca03ffcfc6d2cb95a479ca
gsudarshan1990/Python_Sets
/Doc_Strings/example1.py
2,631
4.21875
4
def add(a,b): """Addition of two integers and returns the resulting integer""" return a+b help(add) print(add.__doc__) class Triangle: """ methods: find_area() provides information about the area of the trianlge find_perimeter() provides information about the perimeter of the triangle """ def find_area(self,base,height): """ :param base: base of the triangle :param height: height of the triangl;e :return: area of the triangle :raises: raises the valueerror if arguments are negative """ if base <0 or height <0: raise ValueError("value should be positive") else: return (base*height)/2 def find_perimeter(self,side1,side2,side3): """ :param side1: one of the three side of the triangle :param side2: second side of the triangle :param side3: third side of the triangle :return: returns the perimeter of the triangle :raises: raises the valueerror if the argument is negative """ if side1 <0 or side2 <0 or side3 <0: raise ValueError else: return side1+side2+side3 help(Triangle) t1=Triangle() print(t1.__doc__) class TissueSample: """ Arguments: Patient: Provides the name of the patient Code: Provides the code of the patient Diagnosis: Provides the diagnosis for the patient methods: show_data(): Displays information related to the patient """ def __init__(self,patient,code,diagnosis): """ Initializes the parameter :param patient: name of the patient :param code: type of the fever :param diagnosis: curing method """ self.patient = patient self.code = code self.diagnosis = diagnosis def show_data(self): """ displays the data :return: nothing """ print("========data==========") print("Patient name:"+self.patient) print("Code name:"+self.code) print("Diagnosis name:"+self.diagnosis) help(TissueSample) #Documenting the functions def freq_data(data): """calculates the frequency of letters from the given data :param data: list of numbers :return: dictionary of frequency of numbers :raises: raise the value error if no value in data """ if not data: raise ValueError("List is empty") freq={} for element in data: if element not in freq: freq[element]=1 else: freq[element]+=1 return freq help(freq_data)
aa63576d2224fae9538f04c76eb06657f1eb3eea
Atabekarapov/Week7_multiple_inheritence_Task
/multiple_inheritence.py
5,008
3.859375
4
# TASK1. WEEK7. ATABEK # 1) '''Будильник Создайте класс Clock, у которого будет метод показывающий текущее время и класс Alarm, с методами для включения и выключения будильника. Далее создайте класс AlarmClock, который наследуется от двух предыдущих классов. Добавьте к нему метод для установки будильника, при вызове которого должен включатся будильник.''' import datetime # class Clock: # def show_time(self): # print(datetime.datetime.now()) # class Alarm: # def clock_turn_on(self): # print("Thank you, alarm clock is turned on!") # def clock_turn_off(self): # print("Thank you, alarm clock is turned off!") # class AlarmClock(Clock, Alarm): # def put_alarm_clock(self): # print(datetime.time(int(input("Can you please put the AlarmClock: ")))) # ready = Clock() # ready.show_time() # Time = AlarmClock() # Time.put_alarm_clock() # Time.clock_turn_on() # 2) '''Напишите класс Coder с атрибутами experience, count_code_time = 0 и методами get_info и coding (возвращает ошибку возвращает ошибку NotImplementedError). Создайте классы Backend и Frontend, которые наследуют все атрибуты и методы от класса Coder. Класс Backend должен принимать дополнительно параметр languages_backend, а Frontend — languages_frontend соответственно. Переопределите в обоих классах методы get_info и coding (возвращает ошибку так, чтобы он принимал количество часов кодинга и при каждом вызове этого метода добавлял это значение к count_code_time). Так же бывают FullStack разработчики и поэтому создайте данный класс и чтобы у него были атрибуты и методы предыдущих классов. Создайте несколько экземпляров от классов Backend, Frontend, FullStack и вызовите их методы.''' # class Coder: # experience = '' # count_code_time = 0 # def get_info(self): # pass # def coding(self): # pass # class Backend(Coder): # """Класс для бэкенда""" # def init(self, languages_backend): # self.experience = languages_backend # def get_info(self): # print(f'Ваш язык {self.experience} ваше время кода {self.count_code_time} часов ') # def coding(self, time): # self.count_code_time += time # class Frontend(Coder): # """Класс для фронтенда""" # def init(self, languages_frontend): # self.experience = languages_frontend # def get_info(self): # print(f'Ваш язык {self.experience} ваше время кода {self.count_code_time} часов ') # def coding(self, time): # self.count_code_time += time # class FullStack(Frontend, Backend, Coder): # def init(self, languages_frontend): # self.experience = languages_frontend # backend1 = Backend() # backend1.coding(12) # backend1.get_info() # fronted1 = Frontend() # fronted1.coding(13) # fronted1.get_info() # full_stack = FullStack() # full_stack.coding(34) # full_stack.get_info() # 3) '''Колода карт Создайте класс для колоды карт. Внутри класса Deck должен использоваться другой класс - Card. Требования: • Класс колоды должен иметь метод deal для раздачи одной карты из колоды. • После раздачи карта удаляется из колоды. • Должен быть метод mix, который гарантирует, что в колоде есть все 52 карты, а затем перемешивает их случайным образом. • Класс карты должен иметь масть (возвращает ошибку червы, бубны, трефы, пики) и ценность (возвращает ошибку A, 2 , 3, 4, 5, 6, 7, 8, 9, 10, J, Q, K) ) Примечание: используйте random shuffle (возвращает ошибку from random import shuffle)''' # import random # class deck: # 4) # def hackerrankInString(s): # target = 'hackerrank' # n = len(target) # i = 0 # for char in s: # if char == target[i]: # i += 1 # if i == n: # return "YES" # return "NO"
b68fc9da284f54f00786e180c0e5817c52bcc0ad
acreel0/Creel-MATH361B
/NumberTheory/N1_Collatz_Creel.py
3,246
4.34375
4
# Defining Collatz Function def collatz(a0,N): # a0 = initial term # N = total number of terms to compute coll_list=[a0] for ii in range(N): if (coll_list[ii]%2 == 0): term = coll_list[-1]/2 else: term = 3*coll_list[-1]+1 coll_list.append(term) if (term == 1): return coll_list return coll_list # Input Variables a0 = 6**3 N = 200 seq = collatz(a0,N) print("The sequence is", seq) if len(seq)< N: print("It took", len(seq), "terms to reach 1.") else: print("After", N, "terms, we did not reach 1.") M = len(seq) even = [] odd = [] for kk in range(M): if seq[kk]%2 == 0: even.append(seq[kk]) else: odd.append(seq[kk]) percent_even = (len(even)/len(seq))*100 percent_odd = (len(odd)/len(seq))*100 print("There are ", len(even), "even terms in the sequence and", len(odd), "odd terms in the sequence. Even terms make up", percent_even, "percent of the sequence, and odd terms make up", percent_odd, "percent of the sequence.") # look at powers of three (even powers of three and odd powers of three) # start with 3 -- 8 terms # start with 6 -- 9 terms # start with 9 -- 20 terms # start with 12 -- 10 terms # start with 15 -- 18 terms # start with 21 -- 8 terms # start with 27 -- 112 terms # start with 33 -- 27 terms # start with 39 -- 35 terms # a power of 2 will eventually reach 2 # 2 took 2 terms # 4 took 3 terms # 8 took 4 terms # 16 took 5 terms # 32 took 6 terms # CONJECTURE NUMBER ONE: # 2 ^ n will have n+1 terms in the sequence after reaching one (converging) # e.g., 2^1 = 2 -- 2 terms # e.g., 2^2 = 4 -- 3 terms # prime numbers # 3 took 8 # 7 took 17 # 11 took 15 # 13 took 10 # 17 took 13 # 19 took 21 # 23 took 16 # powers of 10 # 10 took 7 # 100 took 26 # 1000 took 112 # 10000 took 30 # CONJECTURE NUMBER TWO: # powers of three will reach 16 and then start to converge because 16 is a power of 2 # 3 - 16 # 9 - 16 # 27 - 16 # 81 - 16 # CONJECTURE NUMBER TWO.5: # powers of 5 will reach 16 then start to converge because 16 is a power of 2 # powers of 2k+1 will reach 16 then converge because 16 is a power of 2 # 4 starts converging at 4 # 9 starts converging at 16 # 16 starts at 16 # 25 starts at 16 # CONJECTURE THREE: For powers of three, at least 60% of the terms will be even, and at most 40% of the terms will be odd. # powers of three: # 3 -- 62.5% even, 37.5% odd # 9 -- 65% even, 35% odd # 27 --62.5% even, 37.5% odd # 81 -- ~69.5% even, ~30.5% odd # 243 -- ~64% even, ~ 36% odd # powers of 3 -- about twice as many even numbers as odd numbers in the sequence # 729 -- ~ 70.6% even, ~ 29.4% odd # 2187 -- ~ 66% even, ~33% odd # look at prime powers vs. composite powers # powers of five: # 5 -- ~ 66.6% even, ~33.3% odd # 25 -- ~ 66.6% even, ~ 33.3% odd # 125 -- ~ 63.3% even, ~ 36.7% odd # powers of six: # 6 -- ~66.6% even, ~33.3% odd # 36 -- ~68% even, ~ 32% odd # excluding powers of two, starting the sequence with a power of any integer (ex. 3^ of something) # will give at least 60% evens
eb644b92348a0b2c2995b861b69740cc717de603
ArnasKundrotas/algos-python
/binary-search-rot-array.py
903
3.5
4
############## # UNSOLVED ############## # Binary search # Rotated arr # Sorted arr [2,3,6,7,9,15,19] was rotated (shifted) # arr: [6, 7, 9, 15, 19, 2, 3] # index: 0 1 2 3 4 5 6 # left mid right # mid right # ans # find smallest element index in rotated arr def find_sm_e(arr): left = 0 right = len(arr) - 1 # 6 ans = None while left <= right: mid = left + (right-left)//2 # 3 / 5 if arr[mid] > arr[left]: # 15 > 6 / 2 > 19 left = mid + 1 # 4 ans = left # 3 else: right = mid - 1 ans = right return ans print (find_sm_e([6,7,9,15,19,2,3])) # 5 print (find_sm_e([6,7,9,15,1,2,3])) # 4 print (find_sm_e([6,7,9,0,1,2,3])) # 3 print (find_sm_e([6,7,1,2,3,4,5])) # 2
6770d9342cf3def621c90e57439204e101e7594a
webdeziner/tools
/python/count-html-tags/search.py
586
3.5625
4
# -*- coding: UTF-8 -*- import requests from bs4 import BeautifulSoup from collections import defaultdict occurrences = defaultdict(int) __author__ = 'Webdeziner.se' searchUrl = raw_input('Which url to scan: '); def make_soup(url): response = requests.get(url) return BeautifulSoup(response.content, 'lxml') def search(url): soup = make_soup(url) tags = soup.find_all() for tag in tags: occurrences[tag.name] += 1 print len(tags) search(searchUrl) ### print occurrences for tag_count in occurrences: print tag_count, occurrences[tag_count]
851cf7a22e835b0408fca21c5ffeb8a3632bc3bb
AbdelhamidElKrem/Day4
/main.py
764
4.15625
4
import random; import check; Rock = ''' _______ ---' ____) (_____) (_____) (____) ---.__(___) ''' Paper = ''' _______ ---' ____)____ ______) _______) _______) ---.__________) ''' scissors = ''' _______ ---' ____)____ ______) __________) (____) ---.__(___) ''' list = [Rock,Paper,scissors]; a = ""; while a!= "you win": user_choice = int(input("what do you choose? Type 0 for Rock, 1 for Paper or 2 for scissors: ")); computer_choice = random.randint(0,2); if user_choice <= 3 and user_choice >= 0: print (list[user_choice]); print ("\n computer chose : \n"); print(list[computer_choice]); a =check.check(user_choice, computer_choice); print (a);
36c68c3326031651681648059c7e3fc983a04753
Naeel90/les2
/les5/__init__.py
192
3.5625
4
def convert(C ): F=C*1.8+32 return F def tabel(): print('{0:10}{1:9}'.format('F','C')) for i in range(-30,50,10): print('{:} '.format(convert(i)),(i)) tabel()
a04cc4d6808ebd8f956094692ceb3ba4cd280b7c
JyHu/PYStudy
/source/sublime/base/py02.py
845
4.09375
4
#coding:utf-8 #auther:jyhu # list tuple # # List # classmates = ['Michael', 'Bob', 'Tracy'] print(classmates) print(len(classmates)) for i in classmates: print('My name is %s ;' % i) for i in range(len(classmates)): print('NO. %d name is %s' % (i, classmates[i])) print(classmates[0]) print(classmates[-2]) classmates.insert(1, 'Jack') print(classmates) # 删除最后一个元素 print(classmates.pop()) #删除某个位置的元素 print(classmates.pop(1)) #list的元素可以不同 L = ['Apple', 123, True] #list中的元素还可以也是list s = ['python', 'Java', ['asp', 'php'],'scheme'] # # Tuple 元组 # # 跟list类似,不过,只要创建了就无法再修改 t = ('Michael', 'John', 'Tracy') print(t) #如果只有一个元素的话,则需要在后面加一个 ',' 来消除歧义 t = (1,) print(t)
f0d2d51f2721a672e44770dcf116dac96428dc94
Sree-vathsan/leetcode
/CheckIfItIsAStraightLine.py
1,190
3.765625
4
""" You are given an array coordinates, coordinates[i] = [x, y], where [x, y] represents the coordinate of a point. Check if these points make a straight line in the XY plane. Example 1: Input: coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]] Output: true Example 2: Input: coordinates = [[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]] Output: false Constraints: 2 <= coordinates.length <= 1000 coordinates[i].length == 2 -10^4 <= coordinates[i][0], coordinates[i][1] <= 10^4 coordinates contains no duplicate point. """ from math import inf class Solution: def checkStraightLine(self, coordinates: List[List[int]]) -> bool: def getSlope(point1, point2): if point2[1] == point1[1]: return 0 if point2[0] == point1[0]: return inf return (point2[1] - point1[1]) / (point2[0] - point1[0]) if not coordinates or len(coordinates) <= 2: return True slope: float = getSlope(coordinates[0], coordinates[1]) for i in range(2, len(coordinates)): if slope != getSlope(coordinates[i-1], coordinates[i]): return False return True
0b33e7c2a0ed9b0e3dfe8d35f82f52aea07dc9b9
gaolichuang/book-algorithm-datastruct
/solution/dynamicprogram/scrambelstring.py
1,740
3.640625
4
''' Scramble String My Submissions Question Given a string s1, we may represent it as a binary tree by partitioning it to two non-empty substrings recursively. Below is one possible representation of s1 = "great": great / \ gr eat / \ / \ g r e at / \ a t To scramble the string, we may choose any non-leaf node and swap its two children. For example, if we choose the node "gr" and swap its two children, it produces a scrambled string "rgeat". rgeat / \ rg eat / \ / \ r g e at / \ a t We say that "rgeat" is a scrambled string of "great". Similarly, if we continue to swap the children of nodes "eat" and "at", it produces a scrambled string "rgtae". rgtae / \ rg tae / \ / \ r g ta e / \ t a We say that "rgtae" is a scrambled string of "great". Given two strings s1 and s2 of the same length, determine if s2 is a scrambled string of s1. ''' class Solution(object): def isScramble(self, s1, s2): """ :type s1: str :type s2: str :rtype: bool """ return self.dfs(s1,s2) def dfs(self,s1,s2): if len(s1) != len(s2): return False if len(s1) == 1 and s1 != s2: return False if s1 == s2: return True for i in range(len(s1)): ret = self.dfs(s1[:i], s2[:i]) and self.dfs(s1[i+1:], s2[i+1:]) ss2 = ''.join(reversed(list(s2))) ret = ret or (self.dfs(s1[:i], ss2[:i+1]) and self.dfs(s1[:i], ss2[:i+1])) if ret == True: return True return False s = Solution() print s.isScramble('great','rgtae') print s.isScramble('great','retag') print s.isScramble('c','b')
5c76512702d032ff57060d9eec6c3b3ade15483f
gandresr/Numerical-Analysis
/Optimizacion.py
4,667
3.515625
4
# -*- coding: utf-8 -*- #Metodo para evaluar la funcion en un punto x #Recibe como parametros W0, L, E, I (Si no se ingresan se toman valores predeterminados) def f(x,W0=5400., L=700., E=20000., I = 1500.): return W0/(120*E*I*L)*(-(x**5)+2*(L**2)*(x**3)-(L**4)*x) #Metodo para evaluar la primera derivada de la funcion en un punto x #Recibe como parametros W0, L, E, I (Si no se ingresan se toman valores predeterminados) def d1f(x,W0=5400., L=700., E=20000., I = 1500.): return W0/(120*E*I*L)*(-5*(x**4)+6*(L**2)*(x**2)-(L**4)) #Metodo para evaluar la segunda derivada de la funcion en un punto x #Recibe como parametros W0, L, E, I (Si no se ingresan se toman valores predeterminados) def d2f(x,W0=5400., L=700., E=20000., I = 1500.): return W0/(120*E*I*L)*(-20*(x**3)+12*(L**2)*x) #Metodo de busqueda dorada def dorada(xl,xu,tol): #Se definen los parametros iniciales i = 1 #Numero de iteracion e = None #Error R = 0.6180339 #Razón dorada ans = 'I xl xu xopt error f(xopt)\n\n' #Tabla para archivo de texto #Ciclo principal #Se lleva a cabo hasta obtener un error menor a la tolerancia ingresada por el usuario while e>tol or e is None: #Se calculan variables para hallar el optimo d = R*(xu-xl) x1 = xl + d #Posible optimo entre intervalo [xl,xu] x2 = xu - d #Posible optimo entre intervalo [xl,xu] num = (1-R)*abs(xu-xl) #Numerador de la ecuacion del error absoluto #Se agrega información a la tabla ans += (str(i)+(4-len(str(i)))*' '+('%.4f' % xu)+(10-len(('%.4f' % xu)))*' '+('%.4f' % xl)+(10-len(('%.4f' % xl)))*' ') #Se escoge el mejor optimo entre x1 y x2 if f(x1) < f(x2): xopt = x1 xl = x2 x2 = x1 else: xopt = x2 xu = x1 x1 = x2 e = num/xopt i += 1 #Se registra la iteración #Se agrega información a la tabla ans +=(('%.4f' % xopt)+(10-len(('%.4f' % xopt)))*' '+('%.4f' % e)+(10-len(('%.4f' % e)))*' '+('%.4f' % f(xopt))+'\n') print 'Busqueda dorada\n','Optimo: ',xopt,'\n','Error', e, '\n' #Se imprime el resultado #Se crea un archivo donde de texto donde se guardan los datos de la tabla archivo = open('dorada.txt','w') archivo.write(ans) archivo.close() #Metodo Interpolación cuadrática def icuadratica(x0,x1,x2,tol): i = 0 e = None ans = 'I x1 x2 x3 xopt error f(xopt)\n\n' while e > tol or e == None: x3 = ((f(x0)*((x1**2)-(x2**2))+f(x1)*((x2**2)-(x0**2))+f(x2)*((x0**2)-(x1**2)))/ (2*f(x0)*(x1-x2)+2*f(x1)*(x2-x0)+2*f(x2)*(x0-x1))) x1a = x1 ans += (str(i)+(4-len(str(i)))*' '+('%.4f' % x0)+(10-len(('%.4f' % x0)))*' '+('%.4f' % x1)+(10-len(('%.4f' % x1)))*' ' +('%.4f' % x2)+(10-len(('%.4f' % x2)))*' '+('%.4f' % x3)+(10-len(('%.4f' % x3)))*' ') if x3>x1: if abs(f(x3)) > abs(f(x1)): x0 = x1 x1 = x3 else: x2 = x3 else: if abs(f(x3)) > abs(f(x1)): x2 = x1 x1 = x3 else: x0 = x3 e = abs((x1-x1a)/x1) i += 1 ans += ('%.4f' % e)+(10-len(('%.4f' % e)))*' '+('%.4f' % f(x1))+'\n' print 'Interpolacion Cuadratica\n','Optimo: ',x1,'\n','Error', e, '\n' #Se imprime el resultado archivo = open('cuadratica.txt','w') archivo.write(ans) archivo.close() #Metodo de Newton def newton(tol,L=700.): #Se definen los parametros iniciales i = 1 #Numero de la iteración x0 = 0.14*L #Distancia inicial e = None #Error ans = 'I x0 x error f(x)\n\n' #Tabla para archivo de texto #Ciclo principal #Se lleva a cabo hasta obtener un error menor a la tolerancia ingresada por el usuario while e > tol or e == None: x = (x0 - d1f(x0) / d2f(x0)) #Se calcula la aproximacion al optimo e = abs((x - x0) / x) #Se calcula el error de la iteración ans += (str(i)+(4-len(str(i)))*' '+('%.4f' % x0)+(10-len(('%.4f' % x0)))*' '+('%.4f' % x)+(10-len(('%.4f' % x)))*' ' +('%.4f' % e)+(10-len(('%.4f' % e)))*' '+('%.4f' % f(x))+'\n') #Se agregan datos a la tabla i += 1 #Se registra la iteración x0=x #Se cambia el valor inicial por el mejor optimo para continuar el calculo de la siguiente iteracion #Se imprime el resultado de l optimo y el error en pantalla print 'Metodo de Newton\n','Optimo: ',x,'\n','Error', e, '\n' #Se imprime el resultado #Se crea un archivo donde de texto donde se guardan los datos de la tabla archivo = open('newton.txt','w') archivo.write(ans) archivo.close() #Se corren los metodos dorada(0,700,0.00001) newton(0.00001) icuadratica(0.,420.,700.,0.00001) raw_input('Presionar enter para finalizar')
7a54aba27fc99a76788ecec08c7c92f5f9036463
lime2002/Test
/keskiarvo.py
225
3.796875
4
val1 = int(input('anna 1.luku\n')) val2 = int(input('anna 2.luku\n')) val3 = int(input('anna 3.luku\n')) sum = val1 + val2 +val3 avg = sum / 3 print("lukujen",val1,',',val2, "ja",val3, "keskiarvo on","{:.2f}".format(sum))
a05587b110c62223bd2bf54b4f1152761605bb79
hyunjun/practice
/Problems/hacker_rank/Algorithm/Arrays_and_Sorting/20141231_QuickSort_In_Place/solution2_1.py
814
3.734375
4
def print_ar(ar): print " ".join([str(a) for a in ar]) def partition(ar, l, r): pivot_item = ar[l] left = l right = r while left < right: while ar[left] <= pivot_item: left += 1 while ar[right] > pivot_item: right -= 1 if left < right: ar[left], ar[right] = ar[right], ar[left] ar[l] = ar[right] ar[right] = pivot_item return right def quick_sort(ar): data = [] data.append((ar, 0, len(ar) - 1)) while 0 < len(data): arr, l, r = data.pop(0) arr, m = partition(arr, l, r) print_ar(arr) if l < m - 1: data.append((ar, l, m - 1)) if m + 1 < r: data.append((ar, m + 1, r)) if __name__ == '__main__': n = int(raw_input()) ar = map(int, raw_input().split()) quick_sort(ar) # print partition([1, 2, 3, 5, 9, 7, 8], 4, 6)
23b7fd3bb1209db3e8ad0e2cec91807a401ce6ce
agerista/code-challenge-practice
/pramp/shortest_substring.py
1,041
4.0625
4
def smallest_substring(arr, s): """ >>> smallest_substring(['x','y','z'], 'xyyzyzyx') 'zyx' >>> smallest_substring(['a','c','e'], 'cceccaeceeacc') 'cae' >>> smallest_substring(['a','x','e'], 'cceccaeceeacc') '' """ head = 0 tail = len(arr) shortest = '' while head <= len(s): temp = set(s[head:tail]) if tail == len(s) and head < (len(s) - len(arr)): head += 1 if sorted(temp) != sorted(arr) and tail < len(s): tail += 1 elif sorted(temp) == sorted(arr): if shortest == '': shortest = s[head:tail] elif len(s[head:tail]) < len(shortest): shortest = s[head:tail] head += 1 else: break return shortest ################################################################################ if __name__ == '__main__': import doctest result = doctest.testmod() if not result.failed: print "\nALL TESTS PASSED. GOOD JOB!\n"
c48dcf77225c49cad5ea676fe0f64e54a928beda
yoshiaki-ki/python-basic-lesson
/network/create_json.py
439
3.515625
4
import json j = { "employee": [ {"id":111, "name":"Mike"}, {"id":222, "name":"Nancy"}, ] } print(j) print("#########") print(json.dumps(j)) # jsonは必ずダブルクオート(”)で値を囲むこと # jsonファイルへの書き込み with open('test.json', 'w') as f: json.dump(j,f) # jsonファイルの読み込み with open('test.json', 'r') as f: print(json.load(f))
4bf20bfc152b1594f2d3d3fe2eb30d0c47e80087
Adlaneb10/Python
/Class_notes/classs.py
531
3.953125
4
class Student(object): """Simple student class""" def __init__(self, first="", last="", id=0, grade=0): # initializer self.first_name_str = first self.last_name_str = last self.id_int = id self.grade = grade def __str__(self): return "{} {}, ID: {}".format(self.first_name_str, self.last_name_str, self.id_int) def print_grade(self): return "Grade is {}".format(self.grade) student1 = Student("Lucas", "Rizzo", 1, 100) print(student1.print_grade())
0667b4cbc247db7221a8887e217b4eb89e34757a
rentheroot/Learning-Pygame
/Following-Car-Game-Tutorial/Adding-Images.py
1,237
4.21875
4
#learning to use pygame #following this tutorial: https://pythonprogramming.net/displaying-images-pygame/?completed=/pygame-python-3-part-1-intro/ #imports import pygame #start pygame pygame.init() #store width and height vars display_width = 800 display_height = 600 #init display gameDisplay = pygame.display.set_mode((display_width,display_height)) #name window pygame.display.set_caption('A bit Racey') #define rgb colors black = (0,0,0) white = (255,255,255) #set the game's clock clock = pygame.time.Clock() #game not crashed crashed = False #load the car image carImg = pygame.image.load('racecar.png') #function to place car on display #blit draws car to screen def car(x,y): gameDisplay.blit(carImg, (x,y)) #define x and y for car x = (display_width * 0.45) y = (display_height * 0.8) #run until game crashes while not crashed: #log game events for event in pygame.event.get(): #if user exits window if event.type == pygame.QUIT: crashed = True #print out user actions print(event) #make everything currently in the game white gameDisplay.fill(white) #put car in postition car(x,y) #update display pygame.display.update() #run at 60 fps clock.tick(60) #quit game pygame.quit() quit()
7a28eb4876999c9babd1399a6e4661879cbd2bd2
yujieyen/ryPat2021_code
/Python-Data-Analysis-Third-Edition-master/Chapter04/.ipynb_checkpoints/ch4_ry-checkpoint.py
7,240
4.0625
4
#!/usr/bin/env python # coding: utf-8 # In[1]: # Import required libraries NumPy, polynomial and matplotlib import numpy as np import matplotlib.pyplot as plt # Generate two random vectors v1=np.random.rand(10) v2=np.random.rand(10) # Creates a sequence of equally separated values sequence = np.linspace(v1.min(),v1.max(), num=len(v1)*10) # Fit the data to polynomial fit data with 4 degree of polynomial coefs = np.polyfit(v1, v2, 3) # Evaluate polynomial on given sequence polynomial_sequence = np.polyval(coefs,sequence) # plot the polynomial curve plt.plot(sequence, polynomial_sequence) # Show plot plt.show() #%% # Generate two random vectors v1= np.random.rand(10) v2= np.random.rand(10) #%%ry # Creates a sequence of equally separated values sequence= np.linspace( v1.min(), v1.max(), num= len(v1)*10) # Fit the data to polynomial fit data with 4 degree of polynomial degree= 8 coefs= np.polyfit(v1, v2, degree) # Evaluate polynomial on given sequence polynomial_sequence= np.polyval(coefs, sequence) # plot the polynomial curve plt.plot(sequence, polynomial_sequence) plt.plot(v1,v2,'rx') plt.title(f'degree= {degree}') plt.grid() # Show plot plt.show() #%%ry for degree in range(0,10): coefs= np.polyfit(v1, v2, degree) # Evaluate polynomial on given sequence polynomial_sequence= np.polyval(coefs, sequence) # plot the polynomial curve plt.plot(sequence, polynomial_sequence) plt.plot(v1,v2,'rx') plt.title(f'degree= {degree}') plt.grid() # Show plot plt.show() # In[2]: # Import numpy import numpy as np # Create matrix using NumPy mat=np.mat([[2,4],[5,7]]) print("Matrix:\n",mat) # Calculate determinant print("Determinant:",np.linalg.det(mat)) # In[3]: # Import numpy import numpy as np # Create matrix using NumPy mat=np.mat([[2,4],[5,7]]) print("Matrix:\n",mat) # Find matrix inverse inverse = np.linalg.inv(mat) print("Inverse:\n",inverse) # In[4]: # Create matrix A and Vector B using NumPy A=np.mat([[1,1],[3,2]]) print("Matrix A:\n",A) B = np.array([200,450]) print("Vector B:", B) # In[5]: # Solve linear equations solution = np.linalg.solve(A, B) print("Solution vector x:", solution) # In[6]: # Check the solution print("Result:",np.dot(A,solution)) # In[ ]: # In[1]: # Import numpy import numpy as np # Create matrix using NumPy mat=np.mat([[2,4],[5,7]]) print("Matrix:\n",mat) # In[2]: # Calculate the eigenvalues and eigenvectors eigenvalues, eigenvectors = np.linalg.eig(mat) print("Eigenvalues:", eigenvalues) print("Eigenvectors:", eigenvectors) # In[3]: # Compute eigenvalues eigenvalues= np.linalg.eigvals(mat) print("Eigenvalues:", eigenvalues) # In[ ]: # In[35]: # import required libraries import numpy as np from scipy.linalg import svd # Create a matrix mat=np.array([[5, 3, 1],[5, 3, 0],[1, 0, 5]]) # Perform matrix decomposition using SVD U, Sigma, V_transpose = svd(mat) print("Left Singular Matrix:",U) print("Diagonal Matrix: ", Sigma) print("Right Singular Matrix:", V_transpose) # In[42]: # import required libraries import numpy as np from numpy.linalg import matrix_rank # Create a matrix mat=np.array([[5, 3, 1],[5, 3, 1],[1, 0, 5]]) # Compute rank of matrix print("Matrix: \n", mat) print("Rank:",matrix_rank(mat)) # In[ ]: # In[ ]: # In[11]: # Import numpy import numpy as np # Create an array with random values random_mat=np.random.random((3,3)) print("Random Matrix: \n",random_mat) # In[ ]: # In[4]: # Import required libraries import numpy as np import matplotlib.pyplot as plt # Create an numpy vector of size 5000 with value 0 cash_balance = np.zeros(5000) cash_balance[0] = 500 # Generate random numbers using Binomial samples = np.random.binomial(9, 0.5, size=len(cash_balance)) # Update the cash balance for i in range(1, len(cash_balance)): if samples[i] < 5: cash_balance[i] = cash_balance[i - 1] - 1 else: cash_balance[i] = cash_balance[i - 1] + 1 # Plot the updated cash balance plt.plot(np.arange(len(cash_balance)), cash_balance) plt.show() # In[7]: # Import required library import numpy as np import matplotlib.pyplot as plt sample_size=225000 # Generate random values sample using normal distriubtion sample = np.random.normal(size=sample_size) # Create Histogram n, bins, patch_list = plt.hist(sample, int(np.sqrt(sample_size)), density=True) # Set parameters mu, sigma=0,1 x= bins y= 1/(sigma * np.sqrt(2 * np.pi)) * np.exp( - (bins - mu)**2 / (2 * sigma**2) ) # Plot line plot(or bell curve) plt.plot(x,y,color='red',lw=2) plt.show() # In[9]: # create small, medium, and large samples for noymality test small_sample = np.random.normal(loc=10, scale=6, size=10) medium_sample = np.random.normal(loc=10, scale=6, size=100) large_sample = np.random.normal(loc=10, scale=6, size=1000) # In[10]: # Histogram for small import seaborn as sns import matplotlib.pyplot as plt # Create distribution plot sns.distplot(small_sample) plt.show() # In[11]: # Histogram for medium import seaborn as sns import matplotlib.pyplot as plt # Create distribution plot sns.distplot(medium_sample) plt.show() # In[12]: # Histogram for large import seaborn as sns import matplotlib.pyplot as plt # Create distribution plot sns.distplot(large_sample) plt.show() # In[13]: # Import shapiro funtion from scipy.stats import shapiro # Apply Shapiro-Wilk Test print("Shapiro-Wilk Test for Small Sample: ",shapiro(small_sample)) print("Shapiro-Wilk Test for Medium Sample: ",shapiro(medium_sample)) print("Shapiro-Wilk Test for Large Sample: ",shapiro(large_sample)) # In[14]: # Import anderson funtion from scipy.stats import anderson # Apply Anderson-Darling Test print("Anderson-Darling Test for Small Sample: ",anderson(small_sample)) print("Anderson-Darling Test for Medium Sample: ",anderson(medium_sample)) print("Anderson-Darling Test for Large Sample: ",anderson(large_sample)) # In[15]: # Import normaltest function from scipy.stats import normaltest # Apply D'Agostino-Pearson test print("D'Agostino-Pearson Test for Small Sample: ", normaltest(small_sample)) print("D'Agostino-Pearson Test for Medium Sample: ",normaltest(medium_sample)) print("D'Agostino-Pearson Test for Large Sample: ",normaltest(large_sample)) # In[16]: # Import required library import numpy as np from scipy.misc import face import matplotlib.pyplot as plt face_image = face() mask_random_array = np.random.randint(0, 3, size=face_image.shape) fig, ax = plt.subplots(nrows=2, ncols=2) # Display the Original Image plt.subplot(2,2,1) plt.imshow(face_image) plt.title("Original Image") plt.axis('off') # Display masked array masked_array = np.ma.array(face_image, mask=mask_random_array) plt.subplot(2,2,2) plt.title("Masked Array") plt.imshow(masked_array) plt.axis('off') # Log operation on original image plt.subplot(2,2,3) plt.title("Log Operation on Original") plt.imshow(np.ma.log(face_image).astype('uint8')) plt.axis('off') # Log operation on masked array plt.subplot(2,2,4) plt.title("Log Operation on Masked") plt.imshow(np.ma.log(masked_array).astype('uint8')) plt.axis('off') # Display the subplots plt.show()