blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
db8928441267551ec01087e01bcde08756589c0c | davidadamojr/diary_of_programming_puzzles | /sorting_and_searching/binary_search_recursive.py | 564 | 3.96875 | 4 | def binary_search(sorted_list, left, right, key):
midpoint = (left + right) / 2
middle_element = sorted_list[midpoint]
if middle_element == key:
return "Key found at position: " + str(midpoint)
if right <= left:
return "Could not find element"
if key < middle_element:
return binary_search(sorted_list, left, midpoint - 1, key)
else:
return binary_search(sorted_list, midpoint + 1, right, key)
sorted_list = [1, 4, 5, 5, 6, 7, 8, 9, 22, 43]
print(binary_search(sorted_list, 0, len(sorted_list) - 1, 22))
|
43f837964e71bf191eb7d40d4092de41df411f04 | davidadamojr/diary_of_programming_puzzles | /arrays_and_strings/pascals_triangle_2.py | 632 | 4.03125 | 4 | """
Given an index k, return the kth row of the Pascal's triangle.
For example, given k = 3, return [1,3,3,1]
Leetcode question: https://leetcode.com/problems/pascals-triangle-ii/
"""
def get_pascal_row(row_index):
"""Optimized for O(k) space"""
row = [0 for i in range(0, row_index + 1)]
for row_num in range(0, row_index + 1):
for col_num in range(row_num, -1, -1):
if col_num == row_num or col_num == 0:
row[col_num] = 1
else:
row[col_num] = row[col_num - 1] + row[col_num]
return row
if __name__ == '__main__':
print(get_pascal_row(4))
|
a61877902f47e882fa5aabd0adbaa55f1ffe1d92 | davidadamojr/diary_of_programming_puzzles | /bit_manipulation/same_number_of_ones_bf.py | 1,446 | 3.75 | 4 | """
Given a positive integer, print the next smallest and the next largest number
that have the same number of 1 bits in their binary representation.
"""
# brute force solution that first counts the number of ones in the integer and
# then continuously increments or decrements until it finds an integer with the
# same number of ones
def get_next_smallest(integer_value):
next_smallest = None
number_of_ones = count_ones(integer_value)
while integer_value != 0:
integer_value = integer_value - 1
if count_ones(integer_value) == number_of_ones:
next_smallest = integer_value
break
return next_smallest
def get_next_largest(integer_value):
next_largest = None
number_of_ones = count_ones(integer_value)
while integer_value != 0:
integer_value = integer_value + 1
if count_ones(integer_value) == number_of_ones:
next_largest = integer_value
break
return next_largest
def count_ones(integer_value):
number_of_ones = 0
while integer_value != 0:
if integer_value & 1 == 1:
number_of_ones = number_of_ones + 1
integer_value = integer_value >> 1
return number_of_ones
if __name__ == '__main__':
assert count_ones(get_next_smallest(52)) == count_ones(52)
print(get_next_smallest(52))
assert count_ones(get_next_largest(52)) == count_ones(52)
print(get_next_largest(52))
|
f71d41af482269acd95a3e621f86682fb14a89ed | davidadamojr/diary_of_programming_puzzles | /bit_manipulation/counting_bits.py | 1,292 | 4.09375 | 4 | """
Given a non-negative integer number "num". For every numbers i in the range 0<=i<=num, calculate the number of 1's in
their binary representation and return them as an array.
Example:
For num = 5, you should return [0,1,1,2,1,2]
Follow up:
- It is very easy to come up with a solution with run time O(n*sizeof(integer)). But you can do it in linear time O(n),
possibly in a single pass?
- Space complexity should be O(n).
"""
def count_bits(num):
"""O(num*sizeof(int)) implementation"""
lst_ones = []
for i in range(0, num + 1):
num_of_ones = 0
while i > 0:
if i & 1 == 1:
num_of_ones += 1
i >>= 1
lst_ones.append(num_of_ones)
return lst_ones
def count_bits_linear_time(num):
"O(num) implementation"
lst_ones = [0 for i in range(0, num + 1)]
for i in range(1, num + 1):
lst_ones[i] = lst_ones[i >> 1] + (i & 1)
return lst_ones
if __name__ == "__main__":
assert count_bits(7) == [0, 1, 1, 2, 1, 2, 2, 3]
assert count_bits(12) == [0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2]
assert count_bits_linear_time(7) == [0, 1, 1, 2, 1, 2, 2, 3]
assert count_bits_linear_time(12) == [0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2]
print("All test cases passed successfully.")
|
b590a55877b09b5d7ad28b1d059988d6b6d18fbb | davidadamojr/diary_of_programming_puzzles | /recursion_and_dynamic_programming/pick_m_elements_tail_recursion.py | 965 | 4.0625 | 4 | """
Write a method to randomly generate a set of n integers from an array of size
n. Each element must have equal probability of being chosen.
"""
import random
# @param original_list list of n elements where m elements will be picked from
# @param number_of_elements list of elements to be picked
# @param m_index the index of the mth element in the array
def pick_elements(original_list, number_of_elements, current_index):
if current_index == len(original_list):
return original_list[:number_of_elements]
if current_index >= number_of_elements:
random_index = random.randint(0, current_index)
if random_index < number_of_elements:
original_list[random_index] = original_list[current_index]
return pick_elements(original_list, number_of_elements, current_index + 1)
if __name__ == '__main__':
original_list = [11, 2, 34, 5, 2, 23, 53, 2, 2, 3, 55, 24, 66]
print(pick_elements(original_list, 5, 0))
|
7056be4296ae099551ffab90ac66075025d906b0 | davidadamojr/diary_of_programming_puzzles | /recursion_and_dynamic_programming/all_subsets_recursive.py | 638 | 4.0625 | 4 | """
Write a method to return all subsets of a set
"""
all_subsets = [[]]
# @param original_set a list of integers
def get_all_subsets(original_set, n):
# recursive solution - O(2^n) where n is the size of the original set
if n >= len(original_set):
return
new_subsets = []
for subset in all_subsets:
new_subset = []
new_subset.extend(subset)
new_subset.append(original_set[n])
new_subsets.append(new_subset)
all_subsets.extend(new_subsets)
get_all_subsets(original_set, n + 1)
if __name__ == '__main__':
get_all_subsets([1, 2, 3, 4, 5], 0)
print(all_subsets)
|
77bde9fd4e70f7bb6b56df5aeda363b9642b6db9 | davidadamojr/diary_of_programming_puzzles | /misc/count_twos_bf.py | 522 | 3.96875 | 4 | """
Write a method to count the number of 2s between 0 and n
"""
# brute force solution
# sum up the number of twos in each digit from 0 to n
def number_of_twos(number):
count = 0
for i in range(2, number + 1):
count = count + get_number_of_twos(i)
return count
def get_number_of_twos(number):
count = 0
while number > 0:
if number % 10 == 2:
count = count + 1
number = number / 10
return count
if __name__ == '__main__':
print(number_of_twos(100))
|
f26151d672804487996c5e3f0633515146a92ab9 | davidadamojr/diary_of_programming_puzzles | /recursion_and_dynamic_programming/string_combinations.py | 960 | 4.09375 | 4 | """
Implement a function that prints all possible combinations of the characters
in a string. These combinations range in length from one to the length of the
string. Two combinations that differ only in ordering of their characters are
the same combination. In other words, "12" and "31" are different combinations
from the input string "123", but "21" is the same as "12".
"""
class Combinations:
def __init__(self, input_string):
# constructor
self.input_string = input_string
self.comb_string = ""
self.do_combinations(0)
def do_combinations(self, start):
i = start;
while i < len(self.input_string):
self.comb_string = self.comb_string + self.input_string[i]
print(self.comb_string)
self.do_combinations(i + 1)
self.comb_string = self.comb_string[:-1]
i = i + 1
if __name__ == '__main__':
combinations = Combinations("wxyz")
|
e114ca362bb69f5298c5137696ee4aaffec569ad | davidadamojr/diary_of_programming_puzzles | /mathematics_and_probability/intersect.py | 931 | 4.125 | 4 | """
Given two lines on a Cartesian plane, determine whether the two lines would
intersect.
"""
class Line:
def __init__(self, slope, yIntercept):
self.slope = slope
self.yIntercept = yIntercept
def intersect(line1, line2):
"""
If two different lines are not parallel, then they intersect.
To check if two lines intersect, we just need to check if the slopes are
different (or if the lines are identical)
Note: Due to the limitations of floating point representations, never check
for equality with ==. Instead, check if the difference is less than an
epsilon value.
"""
epsilon = 0.000001 # used for floating point comparisons
return abs(line1.slope - line2.slope) > epsilon \
or abs(line1.yIntercept - line2.yIntercept) < epsilon;
if __name__ == '__main__':
line1 = Line(0.5, 1)
line2 = Line(0.5, 2)
print(intersect(line1, line2))
|
3c964c3542a076dfd60282db1d6fbeeae0f88132 | davidadamojr/diary_of_programming_puzzles | /arrays_and_strings/excel_sheet_column_number.py | 851 | 4.03125 | 4 | """
Given a column title as appears in an Excel sheet, return its corresponding
column number.
For example:
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
Leetcode problem: https://leetcode.com/problems/excel-sheet-column-number/
"""
def title_to_number(column_title):
# this is pretty much a base 26 number system
# Horner's rule comes to mind
if column_title.strip() == '':
return 0
char_map = {}
characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
for i in range(0, len(characters)):
char_map[characters[i]] = i + 1
column_number = 0
for j in range(0, len(column_title)):
column_number = column_number * 26 + char_map[column_title[j]]
return column_number
if __name__ == '__main__':
print(title_to_number('AA'))
print(title_to_number('AAA'))
print(title_to_number('ZZZ'))
|
76e8af6b3ef66bce39724bd917d84150361c139e | davidadamojr/diary_of_programming_puzzles | /arrays_and_strings/excel_sheet_column_title.py | 662 | 4.15625 | 4 | """
Given a positive integer, return its corresponding column title as it appears
in an Excel sheet.
For example:
1 -> A
2 -> B
3 -> C
...
26 -> Z
27 -> AA
28 -> AB
"""
def convert_to_title(num):
integer_map = {}
characters = "ZABCDEFGHIJKLMNOPQRSTUVWXY"
for i in range(0, 26):
integer_map[i] = characters[i]
column_title = ""
while num != 0:
remainder = num % 26
num = num - 1
num = num / 26
column_title = integer_map[remainder] + column_title
return column_title
if __name__ == '__main__':
print(convert_to_title(703))
print(convert_to_title(27))
print(convert_to_title(26))
|
16cd5990109cf3465638230214e4dbedc66bbc54 | Zurol/UAD-IntroduccionProgramacion | /conjuntosInterseccionUnion.py | 1,068 | 3.859375 | 4 | # Generar la unión e intersección de 2 colecciones.
animalesTerrestres = ["Perro", "Gato", "Tortuga", "Liebre", "Pingüino"]
animalesMarinos = ["Tortuga", "Ballena", "Calamar", "Pingüino"]
# A Unión B
animales = []
for animalMarino in animalesMarinos :
for animalTerrestre in animalesTerrestres :
#print("A: {0} X B: {1} \n".format(animalMarino, animalTerrestre))
animales.append(animalTerrestre)
#if len(animales) > 0 :
# for animal in animales:
# print(animales)
# print(">", animal)
# #print("Ciclo interno")
# if animal != animalMarino :
# animales.append(animalMarino)
#else :
# animales.append(animalMarino)
print(animales)
# A Intersección B
animalesTerrestresMarinos = []
for animalMarino in animalesMarinos :
for animalTerrestre in animalesTerrestres :
if animalMarino == animalTerrestre :
animalesTerrestresMarinos.append(animalMarino)
print(animalesTerrestresMarinos)
|
a1adebf6a6f32f9139d65179988fe3220ce2e058 | Adria-Bonjorn/PersonalProjectsPython | /ComfredABCv2ENG.py | 5,363 | 3.90625 | 4 | #CODE FOR HVAC MACHINE SELECTION****By: Adrià Bonjorn Cervera - July 2021
#Import function "ceil" from library "math"
from math import ceil
print("\n----------------------------------------")
print("AIR CONDITIONING MACHINE SELECTION - Adrià Bonjorn")
print("----------------------------------------\n")
#---------------------------------------------------------------------------------
#This program is meant to be a practice project applied to a necessity in my current job.
#The main idea is to develop a simple set of algorithms that allows AC machine selection
#(based on some of my own empirical coeficients) for non technical staff in order to improve
#client atention and productivity in my current company, an AC distributor (Comfred Suministros)
#---------------------------------------------------------------------------------
#Initialize variables
ti=0 #Type of machine
ns=0 #Number of rooms to air-condition
tf=0 #Mode of use
cf=0 #Coeficient due to the mode of use
ta=0 #Type of insulation
ca=0 #Coeficient due to the type of insulation
st=0 #Total area to air-condition
ss=[] #Area of each room to air-condition. It's a list
ssa=0 #Auxiliar variable to check validity of entered areas.
#EVALUATION SETTING SECTION--------------------------------------------------------------------------------
#Evaluation functions and variables to check user inputs
#Main error message
nv="This value is not valid!"
#Defining the function "eval" that checks the validity of the integer values entered in the selection inputs
def eval(va,txt,nv):
ve=int(input(txt))
while ve not in va:
print(nv)
ve=int(input(txt))
return ve
#Setting the arguments that function "eval" is going to use to evaluate and ask for inputs
vati=(1,2)
txtti="Select type of machine Split(1) o Ceiling Duct(2):"
vatf=(1,2,3)
txttf="Select mode of use cooling(1), heating(2) o cooling+heating(3):"
vata=(1,2,3)
txtta="Select type of insulation Good(1), Standard(2) o Poor(3):"
#Defining the function "eval2" that checks if the integer entered is positive
def eval2(txt,nv):
ve=int(input(txt))
while ve <=0:
print(nv)
ve=int(input(txt))
return ve
#Defining the function "eval3" that checks if the float entered is positive
def eval3(txt,nv):
ve=float(input(txt))
while ve <=0:
print(nv)
ve=float(input(txt))
return ve
#Setting the arguments that functions "eval2" and "eval3" is going to use to evaluate and ask for inputs
txtns="Introduce the number of rooms to air-condition:"
txtq="Introduce air flow of the selected model of machine(m3/h):\n"
txth="Introduce maximum heigh of the grills (mm):\n"
txtv="Introduce exit air velocity at grills (m/s): \n"
txtst="Introduce area to air-condition:"
#Defining the function "eval4" that checks the validity of areas for each room
def eval4(txt,i,nv):
print(txt, i,":")
ve=int(input())
while ve <=0:
print(nv)
ve=int(input(txt, i, ":"))
return ve
#Setting the arguments that function "eval4" is going to use to evaluate and ask for inputs
txtssa="Introduce area to air-condition:"
#USER INTERACTION SECTION--------------------------------------------------------------------------------
#User interaction loop starts
while True:
#Selecting type of machine Split(1) o Ceiling Duct(2)
ti=eval(vati,txtti,nv)
#Selecting mode of use cooling(1), heating(2) o cooling+heating(3)
tf=eval(vatf,txttf,nv)
#Selecting type of insulation Good(1), Standard(2) o Poor(3)
ta=eval(vata,txtta,nv)
#Introducing area to air-condition. For Ceiling Duct(2) user should introduce various values
if ti==2:
ns=eval2(txtns,nv)
ss=[0]*ns
for i in range(ns):
ssa=eval4(txtssa,i+1,nv)
ss[i]=ssa
st=sum(ss)
else:
st=eval2(txtst,nv)
#CALCULUS AND OUTPUT SECTION--------------------------------------------------------------------------------
#Assigning coeficient due to the mode of use
if tf==1:
cf=1.1
else:
cf=1.2
#Assigning coeficient due to the type of insulation
if ta==1:
ca=1
elif ta==2:
ca=1.1
else:
ca=1.2
#Recommended machine power calculus
pr=st*cf*ca/10
print("The recommended cooling/heating power is:", pr, "kW\n")
#Grill sizeing
if ti==2:
#Introducing variables for grill sizeing calculus
q=eval2(txtq,nv)
v=eval3(txtv,nv)
h=eval2(txth,nv)
#Preparing grill sizeing variables for calculus
q=q/3600
rh=[h]*ns
rw=[0]*ns
qr=[0]*ns
#Grill sizeing calculus
for i in range(1,ns+1):
rh[i-1]=h
rw[i-1]=1000*q*(ss[i-1]/st)/v/(h/1000)
rw[i-1]=ceil(rw[i-1]/50)*50
qr[i-1]=q*(ss[i-1]/st)*3600
print("Grill for room", i, ":", rw[i-1], "x", rh[i-1],"--->", qr[i-1], "m3/h")
if input('Select another AC machine(1) /// Exit(2)') == '2':
break
|
8ec11e6432d5ab941bc2b38d119b38d01387cc67 | tborisova/homeworks | /7th-semester/ai/hw4.py | 1,497 | 3.703125 | 4 | import collections
import functools
class memoized(object):
'''Decorator. Caches a function's return value each time it is called.
If called later with the same arguments, the cached value is returned
(not reevaluated).
'''
def __init__(self, func):
self.func = func
self.cache = {}
def __call__(self, *args):
if not isinstance(args, collections.Hashable):
# uncacheable. a list, for instance.
# better to not cache than blow up.
return self.func(*args)
if args in self.cache:
return self.cache[args]
else:
value = self.func(*args)
self.cache[args] = value
return value
def __repr__(self):
'''Return the function's docstring.'''
return self.func.__doc__
def __get__(self, obj, objtype):
'''Support instance methods.'''
return functools.partial(self.__call__, obj)
def knapsack(items, max_weight):
@memoized
def best_value(i, j):
if i == 0: return 0
value, weight = items[i - 1]
if weight > j:
return best_value(i - 1, j)
else:
return max(best_value(i - 1, j),
best_value(i - 1, j - weight) + value)
j = max_weight
for i in range(len(items), 0, -1):
if best_value(i, j) != best_value(i - 1, j):
j -= items[i - 1][1]
return best_value(len(items), max_weight)
items = [(5, 3), (2, 3), (5, 1), (3, 2)]
res = knapsack(items, 6)
print(res) |
5d28c27cfcdfdcee291dac3178563271a81ef909 | Pokecris200/CNYT | /clasico_a_cuantico.py | 602 | 3.515625 | 4 | from matplotlib import pyplot
from Libreria1 import *
import math
def pot (matriz,exp):
for i in range (1,b):
res = multiMatrix(matriz,matriz)
return res
def experimentos(a, b, c):
r1 = pot(a,c)
r2 = Accion(r1,b)
return(res2)
def probabilidad (vector):
x,y = [],[]
for i in range (len(vector)):
a = vector[i]
y = y + [modulo(a[0],a[1])*100]
for i in range (len(vector)):
x = x + [i]
def dibujo():
pyplot.title("PROBABILIDAD")
pyplot.bar(x,height=y)
pyplot.savefig("experimento.png")
pyplot.show()
|
8fe3537b1aae05334e6137adfb355f936d7a1c99 | pareshh7/beautifulsoup | /14 Next Siblings & Previous Siblings.py | 530 | 3.828125 | 4 | from bs4 import BeautifulSoup #import beautiful soup library
def read_file(): #function to read file
file = open('three_sisters.html')
data = file.read()
file.close()
return data
soup = BeautifulSoup(read_file(),'lxml') #make soup
p = (soup.body.p)
# .next_siblings returns an iterator of next siblings
for sibling in p.next_siblings:
print(sibling, sibling.name)
# .previous_siblings returns an iterator of previous siblings
for sibling in p.previous_siblings:
print(sibling, sibling.name)
|
866d5d5c3cedd726a360e6c14fd079248b128ff6 | pareshh7/beautifulsoup | /15 Find All Function Parameters (1).py | 963 | 3.71875 | 4 | from bs4 import BeautifulSoup #import beautiful soup library
def read_file(): #function to read file
file = open('three_sisters.html')
data = file.read()
file.close()
return data
soup = BeautifulSoup(read_file(),'lxml') #make soup
#Signature: find_all(name, attrs, recursive, string, limit, **kwargs)
#name parameter
a_tags = soup.find_all('a')
#attrs parameter passed as a dictionary
attr = {'class':'story'}
first_a = soup.find_all(attrs=attr)
print(first_a)
#recursive paramter
title = soup.find_all('title',recursive=False)
print(title)
# string parameter
regex = re.compile('story')
tag = soup.find_all(string=regex)
#limit parameter limits the no of output given by find_all function
a_tags = soup.find_all('a',limit=2)
print(a_tags)
# **kwargs arguments
tags = soup.find_all(class_='story')
# to write the class attribute of a tag - use class_ since simple class is a keyword in Python
|
85c3c31a4e98c2951446401c6bc8994aba9eda08 | parthpatadiya/Incubyte_assessment_parth_patadiya | /data_cleaning.py | 2,389 | 3.703125 | 4 | import pandas as pd
import numpy as np
def data_cleaning(file_path):
#Name of each columns
column_name=["Customer Name","Customer ID","Customer Open Date","Last Consulted Date","Vaccination Type",
"Doctor Consulted","State","Country","Date of Birth","Active Customer"]
# Read pipe delimited data file
# sep - the separator of data "|"
# skiprows - it skips rows from beginning.1 used to skip header row.
# skipfooter - it skips rows from ending.0 used because there is not any footer row in the end. if footer is avaible then use 1.
# usecols - list of index of which columns needs to be added in dataframe. here first two columns ignored because first was empty and second defines |D|.
# names - set column names. gave list of column name respectively.
# parse_dates - used to convert date-time data from string to date time object. gave list of columns number
data=pd.read_csv(file_path,sep="|",skiprows=1,skipfooter=0,usecols=[2,3,4,5,6,7,8,9,10,11],names=column_name,parse_dates=[2,3,8])
# it is important converted all datatype to string for using it in insert query of table which is dynamically formed.
data=data.astype(str)
#replace empty or nan in non-mandatory Date fields to the default 00000000 which will be interpreted as None in date type object of sql
data["Last Consulted Date"]=data["Last Consulted Date"].replace("nan","00000000")
data["Date of Birth"]=data["Date of Birth"].replace("nan","00000000")
#coverting "nan" string to None object.
data[data.loc[:]=="nan"]=None
# "Customer Name","Customer ID","Customer Open Date" are mandatory fields
# so if any records have missing values in that columns then
# we have to remove that data or we can store somewhere else.
# here we extracted indexes of data where mandatory field containing "None" or "NaT"
bad_data_indx=np.concatenate((np.where(data[["Customer Name","Customer ID","Customer Open Date"]]=="NaT")[0],
np.where(data[["Customer Name","Customer ID","Customer Open Date"]].isna())[0]))
# storing bad-data into pipe delimited data file so we can recover missing data later
bad_data=data.loc[bad_data_indx,:]
#removing bad-data from our main data so we can procceed it further.
data.drop(index=bad_data_indx,inplace=True)
return data,bad_data |
bf0610b20d7800f7686f8a779546e16e98af2b13 | Annarien/Python-Getting-Started | /exceptional.py | 1,398 | 3.65625 | 4 | """ Follows the work done on exceptions in the course: Core Python: Getting Started @
https://app.pluralsight.com/course-player?clipId=a8b1ac0f-c305-4505-a0d8-b40f4f858fcf """
# imports
import sys
from math import log
# this is the DIGIT_MAP used throughout this file
DIGIT_MAP = {
'zero': '0',
'one': '1',
'two': '2',
'three': '3',
'four': '4',
'five': '5',
'six': '6',
'seven': '7',
'eight': '8',
'nine': '9',
}
# defining a function
def convert(s):
''' Convert sting to integer'''
# using try and except blocks to overcome KeyErrors when the token is not available in DIGIT_MAP
x = -1
try: # try raises exceptions
number = ''
for token in s:
number += DIGIT_MAP[token]
return int(number)
except(KeyError, TypeError) as e: # e is a keyword
print(f"Conversion error:{e!r}", file=sys.stderr) # print standard error message
raise # re-raise the exception
return -1
def string_log(s):
v = convert(s) # calls convert() function
return log(v) # computes natural log
# converting strings to logs
string_log1 = string_log("ouch!".split()) # this raises a ValueError: math domain error
string_log2 = string_log("cat dog".split()) # this raises a ValueError: math domain error
string_log3 = string_log(87452874561) # this raises a ValueError: math domain error
|
d94edb8bda80e920c6ffe3012c7d817b783265bd | Engy-Bakr/python | /ASSIG0/ass1.py | 264 | 3.921875 | 4 | def vowelsremover(word):
vowels = ('a', 'e', 'i', 'o', 'u')
for i in word:
if i in vowels:
word=word.replace(i,'')
return(word)
# word=input('input the word ')
# print(vowelsremover(word)) |
6394500e3e3f5d5d0864e34609b2e24c1118b1a0 | liangricky7/mathcircleproject2019 | /mathcircleproj.py | 820 | 4.03125 | 4 | from matplotlib import pyplot as plt
import random as rnd
import numpy as np
#starting amount of money
x = [0]
y = [50]
def flipping_fair(n_simulations = 50):
# amount of dollars
balance = 50
for i in range(n_simulations):
# marks bounds of gambling
while 100 > balance and balance > 0:
coin = rnd.randint(1, 100)
# checks for coin flip's result
if coin <= 50:
balance += 1
x.append(x[-1]+1)
y.append(balance + 1)
print(balance)
else:
balance -= 1
x.append(x[-1] +1 )
y.append(balance - 1)
print(balance)
print()
return balance
string = 'The end balance: '
print(string, (flipping_fair()))
plt.title("Gambler's Ruin: Fair")
# returns the last plotted point before termination
print(x[-1], y[-1])
plt.plot(x, y)
plt.show()
|
ad0077c9a88adf7c5b74afa0e53814d6bb84875b | aedillo15/RolePlayingGame | /modules/Game.py | 24,925 | 4.1875 | 4 | """This python file is going to serve as the implementation of game data and logic and the interactivity with the user."""
#Imported Modules including random, Warrior, Wizard
import random
import Warrior
import Wizard
#This GameMenu() method represents the introduction of the game, asking for users name and creating the Role object (Warrior and Wizard) accordingly to user input, in addition the outComes of the dice resulting in the attribute changes of Role
def GameMenu():
#Introduction is the welcome prompt for the RPG Game.
Introduction = 'Welcome to the World of Sheridan.' + '\n' + '\n' + 'The school has been infested with teachers that sleep,' + '\n' + 'when they teach and we want to get rid of them by the time the summer ends.' + '\n'
#Printing the Introduction to the user.
print(Introduction)
#Input asking user what their name is.
Name = input('Before we begin what is your name? ' + '\n')
#Capitalizing the first letter of the name
NameCap = Name.capitalize()
#Declaring AskRoleConfirmation as an empty string
AskRoleConfirmation = ''
#A new Introduction variable, welcoming the user based and their name.
Introduction = '\n' + f'Well {NameCap}, you have just entered the school property and you see this problem '
#Printing the introduction with the users Name.
print(Introduction)
#Loop until the user has confirmed their choice if they end up saying no keep asking them what their role may be.
while(AskRoleConfirmation.lower() != 'y' and AskRoleConfirmation.lower() != 'yes'):
#When user input equals the role create an object of Warrior or Wizard accordingly to the user input
AskRole = input('The dean gives you two options: ' + '\n' + 'Warrior or Wizard, in order to wake up these bad teachers. ')
#If the user input is the warrior then assign them the role of "Warrior" from the warrior module
if (AskRole.lower() == 'warrior'):
#Character variable assigned to the Warrior module dot Warrior object(capitalizedName)
Character = Warrior.Warrior(NameCap)
#Input for user confirming that they would like to choose this class being Warrior
AskRoleConfirmation = input('Are you sure you would like to choose ' + Character.__class__.__name__ + ' (Y/N)?')
#If the user input is the wizard then assign them the role of "Wizard" from the wizard module
elif(AskRole.lower() == 'wizard'):
#Character variable assigned to the Wizard module dot Wizard object(capitalizedName)
Character = Wizard.Wizard(NameCap)
#Input for user confirming that they would like to choose this class being Wizard
AskRoleConfirmation = input('Are you sure you would like to choose ' + Character.__class__.__name__ + ' (Y/N)?')
#Once the Character is assigned give the first challenge to the user and pass the Character through the FirstChallenge that returns a string either 'a','b','c','d' and this string will be equal to ResultFirstChallenge
ResultFirstChallenge = FirstChallenge(Character)
#The first challenge will give a string that will result whether or not the user has loss or won, then make, the object adjustments on the member variables
#Permuations of challenges shall report them to the next challenges
#If the user has critically lost the FirstChallenge
if(ResultFirstChallenge == 'a'):
#If the firstChallege output is a, then the user critically lost, -1 from stats and -1 vitality which decreases health
Loss = Character.criticalLoss()
#Print the string that is returned from Character.criticalLoss() method in the Warrior and Wizard modules
print(str(Loss))
#Even if the user critical loss then provide the user with the second challenge.
SecondResultOutcome = SecondChallenge(Character)
#If the user has critically lost the SecondChallenge.
if(SecondResultOutcome == 'a'):
#Give the user the third challenge
ThirdChallenge(Character)
#If the user has lost the SecondChallenge.
elif(SecondResultOutcome == 'b'):
#Give the user the third challenge
ThirdChallenge(Character)
#If the user has won the SecondChallenge.
elif(SecondResultOutcome == 'c'):
#Give the user the third challenge
ThirdChallenge(Character)
#If the user has critically won the SecondChallenge.
elif(SecondResultOutcome == 'd'):
#Give the user the third challenge
ThirdChallenge(Character)
#If the user has lost the FirstChallenge
elif(ResultFirstChallenge == 'b'):
#Even if the user critical loss then provide the user with the second challenge.
SecondResultOutcome = SecondChallenge(Character)
#If the user has critically lost the SecondChallenge.
if(SecondResultOutcome == 'a'):
#Give the user the third challenge
ThirdChallenge(Character)
#If the user has lost the SecondChallenge.
elif(SecondResultOutcome == 'b'):
#Give the user the third challenge
ThirdChallenge(Character)
#If the user has won the SecondChallenge.
elif(SecondResultOutcome == 'c'):
#Give the user the third challenge
ThirdChallenge(Character)
#If the user has critically won the SecondChallenge.
elif(SecondResultOutcome == 'd'):
#Give the user the third challenge
ThirdChallenge(Character)
#If the user has won the FirstChallenge
elif(ResultFirstChallenge == 'c'):
#Even if the user won then provide the user with the second challenge.
SecondResultOutcome = SecondChallenge(Character)
#If the user has critically lost the SecondChallenge.
if(SecondResultOutcome == 'a'):
#Give the user the third challenge
ThirdChallenge(Character)
#If the user has lost the SecondChallenge.
elif(SecondResultOutcome == 'b'):
#Give the user the third challenge
ThirdChallenge(Character)
#If the user has won the SecondChallenge.
elif(SecondResultOutcome == 'c'):
#Give the user the third challenge
ThirdChallenge(Character)
#If the user has critically won the SecondChallenge.
elif(SecondResultOutcome == 'd'):
#Give the user the third challenge
ThirdChallenge(Character)
#If the firstChallege output is d, then the user critically won, +1 from stats and +1 vitality which increases health
elif(ResultFirstChallenge == 'd'):
Win = Character.criticalWin()
print(str(Win))
ResultOutcome = SecondChallenge(Character)
if(ResultOutcome == 'd'):
ThirdChallenge(Character)
#This method will be the first challenge of entering a room into
def FirstChallenge(Role):
#Decision can be a bush (5 bandages), school directory(map), door(locked, unlock), Sheridan Sign (FirstKey)
TextLocation = ''
FirstKey = False
ResultOutcome = ''
LockUnlocked = False
TextQuestLine = '*****FIRST CHALLENGE*****' + '\n' + 'The dean has assigned you the ' + Role.__class__.__name__ + ' role and has given you the powers' + '\n' + 'to wake these teachers up.' + '\n' + '\n' + 'The dean has asked you to figure out a way to get inside of the campus because the teachers have lock the doors from the inside.' + '\n'
print(TextQuestLine)
QuestInput = input('Do you accept the quest?(Y/N)')
if(str(QuestInput) == 'y' or str(QuestInput) == 'yes'):
try:
while(LockUnlocked != True):
decision = input('\n' + 'There are four spots to check in the front of the school and are as listed (E to check bag, F for Character Statistics):' + '\n' +
'A: Stairs' + '\n' +
'B: School Directory' + '\n' +
'C: Door' + '\n' +
'D: Sheridan School Sign' + '\n' +
'Your choice: ')
if(decision.lower() == 'a' or decision.lower() == 'bush'):
#behind the bush is a note that says in order to enter the school, check the door
TextLocation = 'You find a note, you pick it up and read it reads:' +'\n' + 'Check the main entrance of the school(door)'
print(TextLocation)
elif(decision.lower() == 'b' or decision.lower() == 'directory'):
#you check the school directory and see where the different spots are in the school, you put the map in your backpack
Item = 'Map'
TextLocation = 'You find a map'
print(TextLocation)
PickUp = ''
while(PickUp.lower() != 'y' and PickUp.lower() != 'yes' and PickUp.lower() != 'n' and PickUp.lower() != 'no'):
PickUp = input('Would you like to pick up this ' + Item + ' up?(Y/N)')
#Figure out how to get out of the loop once the Map is equippe and appended to the ItemBackpack
if(PickUp.lower() == 'y' or PickUp.lower() == 'yes' and 'Map' not in Role.ItemBackpack):
Role.ItemBackpack.append(Item)
print("You have now equipped the map...")
elif(decision.lower() == 'y' or PickUp.lower() == 'yes' and 'Map' in Role.ItemBackpack):
print("There is nothing to found here anymore")
elif(PickUp.lower() == 'n' or PickUp.lower() == 'no'):
print("Back to the entrance")
elif(decision.lower() == 'c' or decision.lower() == 'door'):
if(FirstKey == False):
TextLocation = 'There is a lock on the door and you see that the door is locked' +'\n' + '...it seems like it can be locked by an Item in your backpack'
print(TextLocation)
elif(FirstKey == True):
TextLocation = 'There is a lock on the door and you see that the door is locked' + '\n' + 'it seems like your FirstKey fits it ' + '\n' + '...' + '\n' + 'Door is now unlocked!' + '\n' + '\n' + 'You have now entered the campus. ' + '\n'
#The result outcome is equal to the dice roll from GamePlay()
print(TextLocation)
ResultOutcome = GamePlay()
LockUnlocked = True
elif(decision.lower() == 'd' or decision.lower() == 'sign'):
Item = 'FirstKey'
TextLocation = 'You check the sign and notice a ' + Item
print(TextLocation)
PickUp = ''
while(PickUp.lower() != 'y' and PickUp.lower() != 'yes' and PickUp.lower() != 'n' and PickUp.lower() != 'no'):
PickUp = input('Would you like to pick up this ' + Item + ' up?(Y/N)')
if (PickUp.lower() == 'y' or PickUp.lower() == 'yes'):
Role.ItemBackpack.append(Item)
print("You have now equipped the FirstKey...")
FirstKey = True
elif PickUp.lower() == 'no' or PickUp.lower() == 'n':
print("Back to the entrance")
elif(decision.lower() == 'e' or decision.lower() == 'bag'):
if not (Role.ItemBackpack):
print ("Your bag is empty")
else:
print(*Role.ItemBackpack, sep = "\n")
#Find out why it gets here when the power is turned on, escape while loop before this vv
elif(decision.lower() == 'f' or 'stats'):
print(Role.Stats())
return ResultOutcome
except:
print('An error has occured')
def SecondChallenge(Role):
TextLocation = ''
MapChecked = False
PowerOn = False
ResultOutcome = ''
TextQuestLine = '\n' + '*****SECOND CHALLENGE*****' +'\n' + 'You are now inside of the campus and it is super dark, figure out a way to turn the power on.' + '\n'
print(TextQuestLine)
QuestInput = input('Do you accept this quest?(Y/N)' + '\n')
if(str(QuestInput) == 'y' or str(QuestInput) == 'yes'):
try:
while(PowerOn != True):
decision = input('There are three spots you can check in the school so far, it is dark: (E to check bag, F for Character Statistics)' + '\n' +
'A: Control Room' + '\n' +
'B: Check Map' + '\n'
'C: School Directory' + '\n'
'Your Choice: ')
if(decision.lower() == 'a' and MapChecked == True):
TextLocation = '\n' + 'After checking the map, you now know where the control room is.' + '\n' + 'You enter the Control Room and see a switch to turn the school power on' + '\n'
print(TextLocation)
turnOnPower = ''
while(turnOnPower.lower() != 'y' and turnOnPower.lower() != 'yes' and turnOnPower.lower() != 'n' and turnOnPower.lower() != 'no'):
turnOnPower = input('Would you like to turn the power on?(Y/N)')
if (turnOnPower.lower() == 'y' or turnOnPower.lower() == 'yes'):
PowerOn = True
print('\n' + "You have now turned the power on!")
ResultOutcome = GamePlay()
#Function that checks that the user health is not 0, if 0 then print (Game Over!) and break program
if(Role.Health == 0):
print('Game Over!')
break
elif(turnOnPower.lower() == 'n' or turnOnPower.lower() == 'no'):
print("Back to the Entrance" + '\n')
if(decision.lower() == 'a' and MapChecked == False):
TextLocation = '\n' + 'You do not know where the Control Room is, figure a way to know where the Control Room is' + '\n'
print(TextLocation)
#Give the user this option when they have a map in their bag
elif(decision.lower() == 'b' and 'Map' in Role.ItemBackpack):
TextLocation = '\n' + 'You check the Map. You see that the Control Room is not too far down the hall way where you see the blue light.' + '\n'
MapChecked = True
print(TextLocation)
#Give the user this option when they dont have a map in their bag
elif(decision.lower() == 'b' and 'Map' not in Role.ItemBackpack):
TextLocation = 'You check your backpack and there is nothing for you see' + '\n'
print(TextLocation)
#If the user already has a map in their backpack don't allow them to pick another Map up
elif(decision.lower() == 'c' or decision.lower() == 'directory' and 'Map' in Role.ItemBackpack):
TextLocation = 'You check the directory and see a map, you already have a map in your backpack. ' + '\n'
print(TextLocation)
#If the user hasn't picked up a map from the first school directory from FirstChallenge(Role) then allow them pick it up so they can find the control room
elif(decision.lower() == 'c' or decision.lower() == 'directory' and 'Map' not in Role.ItemBackpack):
Item = 'Map'
PickUp = ''
TextLocation = 'You find a map in the school directory' + '\n'
print(TextLocation)
while(PickUp.lower() != 'y' and PickUp.lower() != 'yes' and PickUp.lower() != 'n' and PickUp.lower() != 'no'):
PickUp = input('Would you like to pick up this ' + Item + ' up?(Y/N)')
if (PickUp.lower() == 'y' or PickUp.lower() == 'yes'):
Role.ItemBackpack.append(Item)
print("You have now equipped the map..." + '\n')
elif(PickUp.lower() == 'n' or PickUp.lower() == 'no'):
print("Back to the entrance" + '\n')
elif(decision.lower() == 'e' or decision.lower() == 'bag'):
if not (Role.ItemBackpack):
print ("Your bag is empty")
else:
print(*Role.ItemBackpack, sep = "\n")
elif(decision.lower() == 'f'):
print(Role.Stats())
return ResultOutcome
except:
print('An error has occured')
#The third challenge requires the user to use the PA system and find out there is teachers sleeping in the class room and then pick up a flashlight so the user knows how they see the coffee maker where user can pour coffee and put them in the bag
def ThirdChallenge(Role):
TextLocation = ''
ClassRoomUnlocked = False
flashLight = False
secondKey = False
microphoneUsed = False
ResultOutcome = ''
PickUp = ''
TextQuestLine = '*****THIRD CHALLENGE*****' + '\n' + 'You can now see more of the campus and but you dont hear any sounds or have a clue where these teachers are ' + '\n' + 'you have to look for where these teachers are sleeping' + '\n' + 'so you can wake them up!' + '\n'
print(TextQuestLine)
QuestInput = input('Do you accept this quest?(Y/N)' + '\n')
#If N, prompt user to confirm quitting the game
# The user can check broadcasting station (secondKey), library(flashlight), classroom(needs key) until
if(str(QuestInput) == 'y' or str(QuestInput) == 'yes'):
# Do this until flashLight is in the bag and microphone is used in the broadcasting station then give them the classroom option; if A: Broadcasting Station flashlight and microPhone used; You already seen this room
while(flashLight != True or microphoneUsed != True):
decision = input('\n' + 'There are two spots to check in the front of the school and are as listed (E to check bag, F for Character Statistics):' + '\n' +
'A: Broadcasting Station' + '\n' +
'B: Library' + '\n' +
'Your choice: ')
#Decision A: Broadcasting Station
if(decision.lower() == 'a' or decision.lower() == 'station'):
TextLocation = '\n' + 'You enter the broadcasting station and you can use the microphone and see a flashlight you might need.' + '\n'
print(TextLocation)
Item = 'Flashlight'
while(microphoneUsed != True or flashLight != True):
decision = input('\n' + 'There are two spots to check in the broadcasting station and (E to check bag, F for Character Statistics):' + '\n' +
'A: [Place] Microphone' + '\n' +
'B: [Item] Flashlight' + '\n'
'Your choice: ')
if(decision.lower() == 'a' and microphoneUsed == True):
TextLocation = '\n' + 'You already made an annoucement and hear snoring coming from class SCAET 420.'
print(TextLocation)
#The logic behind the microphone which gives a boolean access to the class room option
if(decision.lower() == 'a' and microphoneUsed == False):
TextLocation = '\n' + 'You try out the microphone and make an announcement asking if anyone is at the school,' + '\n' + 'you use the PA and hear that there is a ton of snoring going on in class SCAET 420'
print(TextLocation)
microphoneUsed = True
if(decision.lower() == 'b' or decision.lower() == 'flashlight'):
while(PickUp.lower() != 'y' and PickUp.lower() != 'yes' and PickUp.lower() != 'n' and PickUp.lower() != 'no'):
PickUp = input('Would you like to pick up this ' + Item + ' up?(Y/N)')
if (PickUp.lower() == 'y' or PickUp.lower() == 'yes'):
Role.ItemBackpack.append(Item)
print("You have now equipped the " + Item + "...")
flashLight = True
#flashLight = True
elif(PickUp.lower() == 'n' or PickUp.lower() == 'no'):
print("Back to the studio")
#Give the user this option when they have a map in their bag
elif(decision.lower() == 'b' or decision.lower() == 'library'):
Item = 'secondKey'
TextLocation = 'You check the library and find a key on the librarians table.' + '\n'
print(TextLocation)
while(PickUp.lower() != 'y' and PickUp.lower() != 'yes'):
PickUp = input('Would you like to pick up this ' + Item + ' up?(Y/N)')
if (PickUp.lower() == 'y' or PickUp.lower() == 'yes'):
Role.ItemBackpack.append(Item)
print("You have now equipped the " + Item + "...")
secondKey = True
elif(PickUp.lower() == 'n' or PickUp.lower() == 'no'):
print("Back to the school")
elif(decision.lower() == 'e' or decision.lower() == 'bag'):
if not (Role.ItemBackpack):
print ("Your bag is empty")
else:
print(*Role.ItemBackpack, sep = "\n")
elif(decision.lower() == 'f' or 'stats'):
print(Role.Stats())
#While Loop that gives the user options A-D: resulting in Broadcasting Room, Library, Coffee Shop, Classroom (Coffee and Secondkey) not until Flashlight is true, Microphone used is true, Coffee in the backpack and the classroom is unlocked with Secondkey
while(flashLight != True or microphoneUsed != True or 'Coffee' in Role.ItemBackpack or ClassRoomUnlocked == True):
decision = input('\n' + 'There are four spots to check in the front of the school and are as listed (E to check bag, F for Character Statistics):' + '\n' +
'A: Broadcasting Station' + '\n' +
'B: Library' + '\n' +
'C: Coffee Shop' + '\n' +
'B: Classroom' + '\n'
'Your choice: ')
if(decision.lower() == 'c' and secondKey == False):
TextLocation = 'You check the classroom and see that the class room is locked' + '\n'
print(TextLocation)
#TextLocation = 'You check the coffee shop and see that there is a fresh pot of coffee there' + '\n'
#print(TextLocation)
return ResultOutcome
#(A: Coffee Shop, B: Broadcasting Station, C: Library, D: Classroom)
def GamePlay():
result = ''
ResultOutcome = ''
DiceOne = random.randrange(1,7)
DiceTwo = random.randrange(1,7)
FinalDice = DiceOne + DiceTwo
#Critical Loss (e.g. 2 - 3): challenge is lost and the attribute that is based on is decreased
if (FinalDice == 1 or FinalDice == 2 or FinalDice == 3):
result = '\n' + 'You rolled a ' + str(FinalDice) + ' challenge is critically lost and your attributes have decreased' + '\n'
ResultOutcome = 'a'
#Loss (e.g. 4-7): challenge is lost, no change in the character’s attributes
elif (FinalDice == 4 or FinalDice == 5 or FinalDice == 6 or FinalDice == 7):
result = '\n' + 'You rolled a ' + str(FinalDice) + ' challenge is lost, no change in the character’s attributes' + '\n'
ResultOutcome = 'b'
#Win (e.g. 8-10): challenge is won, no change in the character’s attributes
elif (FinalDice == 8 or FinalDice == 9 or FinalDice == 10):
result = '\n' + 'You rolled a(n) ' + str(FinalDice) + ' challenge is won, no change in the character’s attributes' + '\n'
ResultOutcome = 'c'
#Critical Win (e.g. 11-12): challenge is won and the attribute that is based on increases
elif (FinalDice == 11 or FinalDice == 12):
result = '\n' + 'You rolled a(n)' + str(FinalDice) + ' challenge is critically won and the attribute that is based on increases' + '\n'
ResultOutcome = 'd'
else:
result = 'Something went wrong here...'
print(result)
return ResultOutcome
GameMenu()
|
f5bd29f7ef1a6e02b7260da959eaaf82fbf1e992 | thetravisw/Data-Structures-And-Algorithms2 | /Data_Structures/old_stuff/linked_list/ll_merge/ll_merge.py | 524 | 3.890625 | 4 | from Data_Structures.linked_list import Linked_List
def merge_lists (list_a, list_b):
results = Linked_List()
if list_a.head == None:
return list_b
if list_b.head == None:
return list_a
a = list_a.head
b = list_b.head
results.head = a
if a == None:
results.head = b
if a != None:
while a.next and b.next:
a.next, b.next, a, b = b, a.next, a.next, b.next
if a.next:
a.next, b.next = b, a.next
else:
if b.next:
a.next=b
return results
|
f929d0829121d98e1d799e18ad2b86cbe2f1992a | eoguzinci/KUL_Datathon_Laqua | /leuvenair/myutils/gmap_utils.py | 1,881 | 3.546875 | 4 | # do not forget to enable gmaps in jupyter notebook by executing the following command
# in ipython shell ``jupyter nbextension enable --py gmaps``
import gmaps
import numpy as np
def get_gmap_figure(LAT, LON, filename = 'apikey.txt'):
# Reference: https://jupyter-gmaps.readthedocs.io/en/latest/tutorial.html#basic-concepts
# read google maps API
with open(filename) as f:
my_api_key = f.readline()
f.close
# get the base map
gmaps.configure(api_key=my_api_key) # Fill in with your API key
# zoom the map around the center
center_of_all_sensors = (np.mean(LAT),np.mean(LON))
# set the figure properties
figure_layout = {
'width': '600px',
'height': '600px',
'border': '1px solid black',
'padding': '1px',
'margin': '0 auto 0 auto'
}
# plot the base map
fobj = gmaps.figure(center=center_of_all_sensors, layout=figure_layout, zoom_level=13, map_type='TERRAIN')
# Note:
#'ROADMAP' is the default Google Maps style,
#'SATELLITE' is a simple satellite view,
#'HYBRID' is a satellite view with common features, such as roads and cities, overlaid,
#'TERRAIN' is a map that emphasizes terrain features.
# add point locations on top of the base map
locations = list(zip(LAT,LON)) # provide the latitudes and longitudes
sensor_location_layer = gmaps.symbol_layer(locations, fill_color='red', stroke_color='red', scale=2)
fobj.add_layer(sensor_location_layer)
leuven_city_center_layer = gmaps.marker_layer(list(zip([50.879800], [4.700500])))
fobj.add_layer(leuven_city_center_layer)
return fobj
def get_closest_idx(LAT, LON, LAT_star=50.8798, LON_star=4.7005):
dists = (LAT-LAT_star)**2 + (LON-LON_star)**2
idx_star = np.argsort(dists)
return idx_star
|
9b3ddafe986acf4bbd79367e34b6d2eabcadb314 | gabrielelanaro/scripting | /scripting/textprocessing.py | 1,945 | 3.5625 | 4 | import re
from utils import partition
def grep(pattern, filename):
"""Given a regex *pattern* return the lines in the file *filename*
that contains the pattern.
"""
return greplines(pattern, open(filename))
def greplines(pattern, lines):
"""Given a list of strings *lines* return the lines that match
pattern.
"""
res = []
for line in lines:
match = re.search(pattern, line)
if match is not None:
res.append(line)
return res
def sections(start, end, text, line=True):
"""Given the *text* to analyze return the section the start and
end matchers. If line=True return the lines between the line that
matches *start* and the line that matches *end* regexps.
If line=False return the text between the matching start and end
The match is in the regexp lingo *ungreedy*.
"""
if not line:
return re.findall(start+"(.*?)"+end, text, re.DOTALL)
lines = text.splitlines()
# This is a state-machine with the states MATCHING = True/False
MATCHING = False
section_list = []
for line in lines:
if MATCHING == False:
if re.search(start, line):
# Start to take stuff
MATCHING = True
section = []
continue
if MATCHING == True:
if re.search(end, line):
MATCHING = False
section_list.append('\n'.join(section))
else:
section.append(line)
return section_list
def grep_split(pattern, text):
'''Take the lines in *text* and split them each time the pattern
matches a line.
'''
lines = text.splitlines()
indices = [i for i, line in enumerate(lines)
if re.search(pattern, line)]
return ['\n'.join(part) for part in partition(lines, indices)]
def between(text, start, end):
pass |
2e1878f64e8d2492350bd51fd13e41922d31dc97 | jeremy1111/bink | /helper_funcs.py | 573 | 3.5625 | 4 | from datetime import datetime, date
def organise_output(contents):
list_contents = list(contents)
for i, d in enumerate(list_contents):
line = '|'.join(str(item).ljust(80) for item in d)
if i == 0:
print('-' * len(line))
print(line)
def convert_to_date(date_string):
strip_hyphen = ' '.join(date_string.split('-'))
converted_date = datetime.strptime(strip_hyphen, "%d %b %y").date()
return converted_date
def format_date(date_object):
formatted_date = date_object.strftime('%d/%m/%Y')
return formatted_date |
72c326034ab55fd69ebfcfeaaa7403d7af9b79b7 | RKH333/BYC | /BYC.py | 2,431 | 4.03125 | 4 | # Juego Bulls&Cows/ Toros y Vacas
# Roberto Chen Zheng
from random import randint
def Reglas():
print("\nEl objetivo:\nAdivinar el número al azar de n dígitos")
print("Las cifras son todas diferentes")
print("Toro: Si una cifra está presente y se encuentra en el lugar correcto")
print("Vaca: Si una cifra está presente pero se encuentra en un lugar equivocado")
print("Al adivinarse el número se termina la partida")
print("Los números a utilizar son del 0-9\n")
return
# Generador de numeros aleatorios para cierta dificultad
# Falta verificar que no se repitan numeros
# Son retornados como una lista de numeros separados
def Generador(num):
if (num==1):
rando= randint(0,999)
lista= [int(i) for i in rando]
return (lista)
elif (num==2):
randint(0,9999)
lista= [int(i) for i in rando]
return (lista)
elif (num==3):
rando = randint(0,999)
lista= [int(i) for i in rando]
return (lista)
else:
return ([])
def Evaluacion(numero,var,respuesta):
toros=0
vacas=0
index=0
if (len(numero) == len(respuesta)):
for i in range(0,len(respuesta)):
if (respuesta[i] == numero[i]):
toros+= 1
elif (numero[i] in respuesta):
vacas+= 1
return(toros, vacas)
else:
print("Mensaje de Error en funcion Evaluacion: Listas diferente tamaño")
def Nivel_1():
print("Juego Fácil 3 dígitos")
contador=0
var=False
respuesta= Generador(1)
while (var!=False):
numero= input("Ingrese el numero: ")
lista= [int(i) for i in numero]
# El resultado es una tupla, el primer valor son toros, el segundo son vacas
resultado= Evaluacion(numero,var,respuesta)
def BYC():
print("*** Bulls & Cows ***")
print("1. Jugar \n2. Reglas \n3. Salir")
opcion= int(input("Seleccione una opción: "))
if (opcion == 1):
nivel= input("Ingrese la dificultad: ")
## if (nivel == 1):
## Nivel_1()
## elif (nivel == 2):
## Nivel_2
## elif (nivel ==3):
## Nivel_3
## else:
## print ("Elija de nuevo la dificultad: ")
elif (opcion == 2):
Reglas()
BYC()
elif (opcion == 3):
print("Bye Bye")
|
44f5fcd365a974b30ce7c120070e701b3b8f0efa | MichaelLegg/AdventOfCode2017 | /Day 4/Kane/adventofcode_day4.py | 1,586 | 3.734375 | 4 | def noDupes():
count = 0
with open('input.txt') as f:
for line in f:
line = map(str, line.split(" "))
bool = False
for i in range(len(line)):
for j in range(i+1,len(line)):
line[i] = line[i].rstrip('\n')
line[j] = line[j].rstrip('\n')
if(line[i] == line[j]):
bool = True
break
if(bool == False):
count += 1
print count
def anagram():
count = 0
with open('input.txt') as f:
for line in f:
line = map(str, line.split(" "))
bool = False
for i in range(len(line)):
for j in range(i + 1, len(line)):
line[i] = line[i].rstrip('\n')
line[j] = line[j].rstrip('\n')
wordi = []
wordj = []
for ch in line[i]:
wordi += ch
for ch in line[j]:
wordj += ch
wordi.sort()
wordj.sort()
isorted = ""
jsorted = ""
for ch in wordi:
isorted += ch
for ch in wordj:
jsorted += ch
if(isorted == jsorted):
bool = True
break
if (bool == False):
count += 1
print count
# noDupes()
anagram()
|
41bfd5f2166cc575d70d6f38f572530da07ae8bb | San221/Snake-game-using-python-turtle-module | /snake_game.py | 4,340 | 3.953125 | 4 | import turtle
import time
import random
delay =0.1
## Score
score=0
high_score=0
## Set up screen
wn= turtle.Screen()
wn.title("Snake Game by San")
wn.bgcolor("green")
wn.setup(width=600, height=600)
wn.tracer(0) # BY putting zero it turns off the screen animation
## Snake head
head= turtle.Turtle()
head.speed(0) # This is speed of animation not of paddle in game
head.shape("square")
head.color("black")
#head.shapesize(stretch_wid=1, stretch_len=1) # keeping length constanr and increasing the width by factor 5
head.penup()
head.goto(0,0)
#head.dx=0.5
#head.dy=head
head.direction= "stop"
## Snake food
food= turtle.Turtle()
food.speed(0) # This is speed of animation not of paddle in game
food.shape("circle")
food.color("red")
food.penup()
food.goto(0,0)
segment=[]
## Pen
pen= turtle.Turtle()
pen.speed(0) # This is speed of animation not of paddle in game
pen.shape("square")
pen.color("white")
pen.penup()
pen.hideturtle()
pen.goto(0,260)
pen.write("Score=0 High Score=0", align="center", font=("courier",24,"normal"))
## Functions
def go_up():
if head.direction!="down":
head.direction="up"
def go_down():
if head.direction!="up":
head.direction="down"
def go_right():
if head.direction!="left":
head.direction="right"
def go_left():
if head.direction!="right":
head.direction="left"
def move():
if head.direction=="up":
y= head.ycor()
head.sety(y+20)
if head.direction=="down":
y= head.ycor()
head.sety(y-20)
if head.direction=="right":
x= head.xcor()
head.setx(x+20)
if head.direction=="left":
x= head.xcor()
head.setx(x-20)
## keyboard bindings
wn.listen()
wn.onkeypress(go_up,"w")
wn.onkeypress(go_down,"s")
wn.onkeypress(go_right,"d")
wn.onkeypress(go_left,"a")
## Main game loop
while True:
wn.update()
## Check for collison with border
if head.xcor()>290 or head.xcor()<-290 or head.ycor()>290 or head.ycor()<-290:
time.sleep(1)
head.goto(0,0)
head.direction= "stop"
## Hide the segments
for seg in segment:
seg.goto(1000,1000) # Thare no tools in turtle to disappear or delete the segment hence it is better to move outside the window
score=0
pen.clear()
pen.write("Score: {} High Score: {}". format(score, high_score), align="center",font=("courier",24,"normal"))
## Clear the segment list
segment.clear()
## Check for collison with food
if head.distance(food)<20: # This is center distance between food and head which is nothing but collision
#move the food to the random position
x= random.randint(-290,290)
y= random.randint(-290,290)
food.goto(x,y)
# Add a segment
new_segment= turtle.Turtle()
new_segment.speed(0) # This is speed of animation not of paddle in game
new_segment.shape("square")
new_segment.color("grey")
new_segment.penup()
segment.append(new_segment)
## Increase the score
score +=10
if score>high_score:
high_score= score
pen.clear()
pen.write("Score: {} High Score: {}". format(score, high_score), align="center",font=("courier",24,"normal"))
## Move the end segment first in reverse order
for index in range(len(segment)-1,0,-1):
x=segment[index-1].xcor()
y=segment[index-1].ycor()
segment[index].goto(x,y)
## Move segement 0 to where the head is
if len(segment)>0:
x=head.xcor()
y=head.ycor()
segment[0].goto(x,y)
move()
## Check for collision with body segment
for seg in segment:
if seg.distance(head)<20:
time.sleep(1)
head.goto(0,0)
head.direction= "stop"
for seg in segment:
seg.goto(1000,1000)
segment.clear()
score=0
pen.clear()
pen.write("Score: {} High Score: {}". format(score, high_score), align="center",font=("courier",24,"normal"))
time.sleep(delay)
wn.mainloop()
|
91efd9412dab08e3f3735a4f909da79648c1b511 | Hchyeria/some-data-structure-and-algorithm | /1/SplayTree.py | 5,536 | 3.9375 | 4 | # -*- coding:utf-8 -*-
"""
Splay tree
Question 1
Author: Hchyeria
"""
# 定义一个 TreeNode 类 保存树的节点信息
# 包括自身的数值 和 左右孩子节点 父节点信息
class TreeNode:
def __init__(self, val: int):
self.val = val
self.left = self.right = self.parent = None
# 定义一个 BinarySearchTree 类
# 可以进行删除 插入 和 查找操作
# 其中都需要将目标节点旋转到根节点
class SplayTree:
def __init__(self, root=None):
self.root = root
# 查找函数
def find(self, value):
current = self.root
# 找到相同的或者到边缘 停止循环
if not current:
return
while True:
if current.val > value:
if not current.left:
break
current = current.left
elif current.val < value:
if not current.right:
break
current = current.right
else:
break
# 将该节点伸展到根节点
self.root = splay(self.root, current)
# 返回是否找到
return current.val == value
def insert(self, value: int):
self.root = insert(self.root, value)
def delete(self, value: int):
# 删除之前 先找一下是否存在 并且伸展该节点
if not self.find(value):
return
self.root = delete(self.root)
def merge(self, tree):
self.root = merge(self.root, tree)
return self
# 旋转函数 左旋和右旋
def rotate(root, node):
p = node.parent
if not p:
return root
# 如果节点是父节点的左孩子
# 右旋
if p.left == node:
p.left = temp = node.right
node.right = p
else:
# 否则 左旋
p.right = temp = node.left
node.left = p
# 改变父节点的指向
node.parent = p.parent
p.parent = node
temp.parent = p
# 改变父亲的父亲的孩子指向
if node.parent:
if node.parent.left == p:
node.parent.left = node
else:
node.parent.right = node
return root
# 伸展函数
# 把目标节点伸展到根节点
def splay(root, node):
# 如果不是根节点 继续伸展
while node.parent:
p = node.parent
g = p.parent
# 如果存在爷爷 需要进行两次旋转
if g:
# 如果 父亲和节点和同在一侧 即父亲是爷爷的左孩子 节点的父亲的左孩子
# 或者 父亲是爷爷的右孩子 节点的父亲的右孩子 则先旋转父亲再旋转节点
# 如果不是在同一侧
# 节点需要进行两次旋转
root = rotate(root, p if (p == g.left) == (node == p.left) else node)
root = rotate(root, node)
return root
# 插入函数
def insert(root, value):
current = root
node = None
# 如果还没有根节点 将新插入的节点作为根节点
if not current:
root = node
return root
# 循环找到合适的插入位置
while True:
# 值小于节点值 向左移 反之 向右移
if current.val > value:
# 如果左孩子已经为空了 找到位置 中断循环
if not current.left:
# 插入到左子树
node = TreeNode(value)
current.left = node
node.parent = current
# 伸展该节点
root = splay(root, node)
break
# 如果还存在左子树 再继续找位置
current = current.left
if current < value:
# 如果右孩子已经为空了 找到位置 中断循环
if not current.right:
# 插入到右子树
node = TreeNode(value)
current.right = node
node.parent = current
# 伸展该节点
root = splay(root, node)
break
# 如果还存在右子树 再继续找位置
current = current.right
return root
# 删除函数
def delete(root):
# 如果存在的前提下
# 该节点已经伸展到根节点了
ptr = root
# 如果同时有左孩子和右孩子
# 将左子树的根节点作为新的根节点
# 找到左子树最大的节点
if ptr.left and ptr.right:
left_node = ptr.left
root = left_node
while left_node.right:
left_node = left_node.right
# 将原来根节点的右子树 变成次节点的右子树
left_node.right = ptr.right
ptr.right.parent = left_node
else:
root = ptr.left if ptr.left else ptr.right
root.parent = None
return root
# 因为第二题会用到合并两个集合 所以增加了一个 merge 函数
def merge(root, tree):
if not root and not tree:
return
if not tree or root:
return root if root else tree.root
tree = tree.root
ptr = root
while True:
if tree.val < root.val:
if not ptr.left:
ptr.left = tree
tree.parent = ptr
root = splay(root, tree)
break
ptr = ptr.left
else:
if not ptr.right:
ptr.right = tree
tree.parent = ptr
root = splay(root, tree)
break
ptr = ptr.right
return root |
8d089b1da8015d9e4e9420e10d63b7a22ab11dbd | spacerunaway/world_recoder | /music/chord.py | 11,104 | 3.859375 | 4 | from scale import *
import copy
CHORD_TYPE={'M':major,'m':minor,'dim','aug'}
class Chord(Scale):
"""
A chord is any harmonic set of pitches consisting of two or more (usually three or more) notes
(also called "pitches") that are heard as if sounding simultaneously.
(For many practical and theoretical purposes, arpeggios and broken chords,
or sequences of chord tones, may also be considered as chords.)
"""
name = 'UnknowChord'
category = ['Unknow']
def __init__(self,roots=None):
Scale.__init__(self,self.interval_keys[:])
self.roots = roots
self.bases = roots
def __repr__(self):
str_name = '{0}: {1}'.format(self.name, self.intervals)
str_members = ''
if hasattr(self,'bass'):
str_members = '\n{0} on {1}'.format(self.members, self.bass)
return '{0}{1}'.format(str_name, str_members)
def __eq__(self,y):
if self.interval_keys != y.interval_keys:
return False
if self.roots != y.roots:
return False
return True
def addroots(self,roots):
self.roots = roots
if self.bases == None:
self.bases = roots
def add(self,intervals):
"""
An added tone chord is a triad chord with an added, non-tertian note,
such as the commonly added sixth as well as chords with an added
ninth(second) or eleventh (fourth) or a combination of the three.
>>> CM = Major_Triad(do)
>>> CM = CM.add(['M9'])
>>> CM
Major_Triad_add9: [0, 4, 7, 14]
>>> CM.default()
>>> CM = CM.add([])
>>> CM
Major_Triad: [0, 4, 7]
>>> CM = CM.add(['M6','M9'])
>>> CM = CM.add(['P11'])
>>> CM = CM.add(['M6','M9'])
>>> CM
Major_Triad_add6_add9_add11: [0, 4, 7, 9, 14, 17]
"""
if type(intervals) != list:
return print('argument must be list')
add_keys = [i for i in intervals if i not in self.interval_keys[:]]
new_name = self.name + ''.join(['_add' + i[1:] for i in add_keys])
self.rebuild_chord(self.interval_keys + add_keys, new_name)
def aug(self,keys):
"""
Augmented diatonic scale tone of chords, in broadest definition it will be an altered chord.
An altered chord is a chord with one or more notes from the diatonic scale
replaced by a neighboring pitch in the chromatic scale. Thus the note must be a nonchord tone.
>>> CM = Major_Triad(do)
>>> CM.aug(['P5'])
>>> CM
Major_Triad_aug5: [0, 4, 8]
>>> CM.default()
>>> CM.aug([])
>>> CM
Major_Triad: [0, 4, 7]
>>> CM.aug(['M9'])
>>> CM
Major_Triad: [0, 4, 7]
>>> CM = CM.add(['M9'])
>>> CM.aug(['P5','M9'])
>>> CM
Major_Triad_add9_aug5_aug9: [0, 4, 8, 15]
>>> CM.aug(['M9'])
>>> CM
Major_Triad_add9_aug5_aug9: [0, 4, 8, 15]
"""
if type(keys) != list:
return print('argument must be list')
for key in [k for k in keys if k in self.interval_keys[:]]:
distance = self.find_interval(key)
new_key = self.find_interval_keys(distance + 1,'aug')
self.interval_keys = [new_key if i == key else i for i in self.interval_keys[:]]
self.name = self.name + ''.join('_aug' + key[1:])
self.rebuild_chord(self.interval_keys, self.name)
def dim(self,keys):
"""
diminished diatonic scale tone of chords, refer to aug()
>>> CM = Major_Triad(do)
>>> CM.dim(['P5'])
>>> CM
Major_Triad_dim5: [0, 4, 6]
>>> CM.default()
>>> CM.dim([])
>>> CM
Major_Triad: [0, 4, 7]
>>> CM.dim(['M9'])
>>> CM
Major_Triad: [0, 4, 7]
>>> CM = CM.add(['M9'])
>>> CM.dim(['P5','M9'])
>>> CM
Major_Triad_add9_dim5_dim9: [0, 4, 6, 13]
>>> CM.dim(['M9'])
>>> CM
Major_Triad_add9_dim5_dim9: [0, 4, 6, 13]
"""
if type(keys) != list:
return print('argument must be list')
for key in [k for k in keys if k in self.interval_keys[:]]:
distance = self.find_interval(key)
new_key = self.find_interval_keys(distance - 1,'dim')
self.interval_keys = [new_key if i == key else i for i in self.interval_keys[:]]
self.name = self.name + ''.join('_dim' + key[1:])
self.rebuild_chord(self.interval_keys, self.name)
def invertion(self):
"""
There are inverted chords, inverted melodies, inverted intervals,and (in counterpoint) inverted voices.
The concept of inversion also plays a role in musical set theory.
An interval is inverted by raising or lowering either of the notes using displacement of
the octave (or octaves) so that both retain their names (pitch class).
For example, the inversion of an interval consisting of a C with an E above
it is an E with a C above it – to work this out, the C may be moved up,
the E may be lowered, or both may be moved.
Under inversion, perfect intervals remain perfect, major intervals become minor and vice versa,
augmented intervals become diminished and vice versa.
"""
""" add your code """
def on(self,bases):
"""
On chord is an inverted chords. For example C Major chord(C,E,G) on G means
its bass note is G called ConG(G,C,E) is the first invertion of C.
But there are some extra version like ConF(F,C,E,G)
We called it extra invertion different to normal invertion.
"""
self.bases = bases
def set_bass(self,note):
"""
Set the bass note, it must be the lowest tone in the chord
"""
if note in self.bases:
self.bass = note
""" add your code """
else:
print("bass must be the lowest tone")
def start_with(self,note,bass=None):
"""
make chord from any note.
(e.g. major triad start with C4 is [C4,E4,G4] are chord C,
major triad start with D4 is [D4,Fs4,A4] are chord D,
dominant seventh start with C4 and the bass is G3 means [G3,C4,E4,G4,As4] are chord C7onG.)
"""
Scale.start_with(self,note)
if bass == None:
self.set_bass(note)
else:
self.set_bass(bass)
def rebuild_chord(self,interval_keys,name):
self.name = name
self.interval_keys = interval_keys
self.intervals = self.find_intervals(self.interval_keys)
if self.members:
self.start_with(self.members[0],self.bass)
@property
def isdominant(self):
return 'Dominant' in self.category
class Major_Triad(Chord):
name = 'Major_Triad'
interval_keys = ['P1','M3','P5']
category = ['Major','Triad']
def default(self):
self.rebuild_chord(Major_Triad.interval_keys,Major_Triad.name)
def add(self,intervals):
new_chord = copy.copy(self)
Chord.add(new_chord,intervals)
return new_chord
def dominant_seventh(self):
new_chord = copy.copy(self)
interval_keys = Major_Triad.interval_keys+['m7']
new_chord.rebuild_chord(interval_keys,'Dominant_seventh')
new_chord.category = ['Dominant','Dominant7']
return new_chord
def major_seventh(self):
new_chord = copy.copy(self)
interval_keys = Major_Triad.interval_keys+['M7']
new_chord.rebuild_chord(interval_keys,'Major_seventh')
return new_chord
def sixth(self):
new_chord = copy.copy(self)
interval_keys = Major_Triad.interval_keys+['M6']
new_chord.rebuild_chord(interval_keys,'Major_sixth')
return new_chord
def dominant_ninth(self):
new_chord = self.dominant_seventh()
interval_keys = new_chord.interval_keys+['M9']
new_chord.rebuild_chord(interval_keys,'Dominant_ninth')
return new_chord
def dominant_eleventh(self):
new_chord = self.dominant_ninth()
interval_keys = new_chord.interval_keys+['P11']
new_chord.rebuild_chord(interval_keys,'Dominant_eleventh')
return new_chord
def dominant_thirteenth(self):
new_chord = self.dominant_eleventh()
interval_keys = new_chord.interval_keys+['M13']
new_chord.rebuild_chord(interval_keys,'Dominant_thirteenth')
return new_chord
def sus2(self):
new_chord = copy.copy(self)
self.interval_keys[1] = 'M2'
new_chord.rebuild_chord(self.interval_keys,'Suspended_second')
return new_chord
def sus4(self):
new_chord = copy.copy(self)
self.interval_keys[1] = 'P4'
new_chord.rebuild_chord(self.interval_keys,'Suspended_fourth')
return new_chord
class Minor_Triad(Chord):
name = 'minor_Triad'
interval_keys = ['P1','m3','P5']
def seventh(self):
new_chord = copy.copy(self)
interval_keys = Minor_Triad.interval_keys+['m7']
new_chord.rebuild_chord(interval_keys,'minor_seventh')
return new_chord
def major_seventh(self):
new_chord = copy.copy(self)
interval_keys = Minor_Triad.interval_keys+['M7']
new_chord.rebuild_chord(interval_keys,'minor_major_seventh')
return new_chord
def sixth(self):
new_chord = copy.copy(self)
interval_keys = Minor_Triad.interval_keys+['M6']
new_chord.rebuild_chord(interval_keys,'minor_sixth')
return new_chord
def b5(self):
new_chord = copy.copy(self)
interval_keys = ['P1','m3','d5']
new_chord.rebuild_chord(interval_keys,'minor_flat5')
new_chord.category = ['Dominant']
return new_chord
def seventh_b5(self):
new_chord = copy.copy(self)
interval_keys = ['P1','m3','d5','m7']
new_chord.rebuild_chord(interval_keys,'minor_seventh_flat5')
new_chord.category = ['Dominant','Dominant7']
return new_chord
class Aug_Triad(Chord):
name = 'Aug_Triad'
interval_keys = ['P1','M3','A5']
def seventh(self):
new_chord = copy.copy(self)
interval_keys = Aug_Triad.interval_keys+['m7']
new_chord.rebuild_chord(interval_keys,'Augmented_seventh')
return new_chord
def major_seventh(self):
new_chord = copy.copy(self)
interval_keys = Aug_Triad.interval_keys+['M7']
new_chord.rebuild_chord(interval_keys,'Augmented_major_seventh')
return new_chord
class Dim_Triad(Chord):
name = 'dim_Triad'
interval_keys = ['P1','m3','d5']
def seventh(self):
new_chord = copy.copy(self)
interval_keys = Dim_Triad.interval_keys+['d7']
new_chord.rebuild_chord(interval_keys,'diminished_seventh')
return new_chord
def half_seventh(self):
new_chord = copy.copy(self)
interval_keys = Dim_Triad.interval_keys+['m7']
new_chord.rebuild_chord(interval_keys,'diminished_seventh')
return new_chord
|
ea8f49b1df16ef031010fcf8629412362eccffe0 | CindyWei/Python | /ex18.py | 752 | 3.953125 | 4 | #coding=utf-8
'''
2014-2-9
习题18:命名、变量、代码、函数
'''
#this one is like your scripts with argv
def print_two(*args): #将函数的所有参数都接收进来
arg1, arg2 = args #将参数解包
print "arg1: %r, arg2: %r" %(arg1, arg2)
#ok, that *args is actually pointless, we can just do this
def print_two_again(arg1, arg2):
print "arg1: %r, arg2: %r" % (arg1, arg2)
#this just takes one argument
def print_one(arg1):
print "arg1: %r" % arg1
#this one takes no arguments
def print_none():
print "I got nothing"
print_two("Zed", "Shaw")
print_two_again("Zed", "Shaw")
print_one("First!")
print_none()
'''
学习总结:
def 定义函数,函数名后跟参数和冒号
第二个函数的传参形式用的更多
'''
|
e6d847fbca7e196b13b3da94080a760656626497 | CindyWei/Python | /ex41.py | 1,295 | 4.15625 | 4 | #coding=utf-8
'''
2014-2-11
习题41:类
'''
class TheThing(object):
def __init__(self):
self.number = 0
def some_function(self):
print "I got called"
def add_me_up(self, more):
self.number += more
return self.number
a = TheThing()
b = TheThing()
a.some_function()
b.some_function()
print a.add_me_up(20)
print b.add_me_up(30)
print a.number
print b.number
class TheMultiplier(object):
def __init__(self, base):
self.base = base
def do_it(self, m):
return m * self.base
x = TheMultiplier(a.number)
print x.base
print x.do_it(30)
class Dog(object):
def __init__(self, name):
self.name = name
class Person(object):
def __init__(self, name):
self.name = name
self.pet = None #定义了类的两变量 name 和pet
#类的继承
class Employee(Person):
def __init__(self, name, salary):
super(Employee, self).__init__(name)
self.salary = salary
class Fish(object):
pass
class Salmon(Fish):
pass
class Halibut(Fish):
pass
rover = Dog("Rover")
print rover.name
mary = Person("Mary")
print mary.name
print mary.pet
employee = Employee('Cindy', 5000)
print employee.name
print employee.salary
'''
学习总结:
创建的类都要加上(object)参数
类的继承,用父类super(Employee, self).__init__(name)来初始化
'''
|
ed1bd6b9eeb6d9dafad2bab38a3516836d0178c5 | elisemmc/EECS800 | /Lab2/NaiveBayes.py | 4,276 | 3.65625 | 4 |
# coding: utf-8
# In[6]:
from __future__ import division
from sklearn import datasets
import pandas as pd
import numpy as np
import math
import operator
#Please complete the following Naive Bayes code based on the given instructions
# Load the training and test dataset.
#Please handle the data with 'dataframe' type, remember to print/display the test and training datasets
train = pd.read_csv('NaiveBayesTrain.csv')
test = pd.read_csv('NaiveBayesTest.csv')
print 'Training Data'
print train
print ''
print 'Test Data'
print test
print ''
groundtruth = test['target']
# We can use a Gaussian function to estimate the probability of a given attribute value,
# given the known mean and standard deviation for the attribute estimated from the training data.
# Knowing that the attribute summaries where prepared for each attribute and class value,
# the result is the conditional probability of a the attribute value given a class value.
def probCalculator(x, mean, stdev):
exponent = math.exp(-(math.pow(x-mean,2)/(2*math.pow(stdev,2))))
return (1 / (math.sqrt(2*math.pi) * stdev)) * exponent
def calcConditionalProb(testset,df_temp):
'''
This function takes the test dataset and a dataframe given one class label.
The function returns the conditional probability given a column(feature).
'''
#hint: you can test.ix[:,i]
#prob = 1.0
d = {}
means = df_temp.mean()
stdevs = df_temp.std()
for index,row in testset.iterrows():
prob = 1.0
for i in testset:
# print probCalculator(row[i], means[i], stdevs[i])
prob *= probCalculator(row[i], means[i], stdevs[i])
# prob[i] = probCalculator(row[i], means[i], stdevs[i])
d[index] = prob
return d
# Follow intructions for the given code snippet:
# In[ ]:
prob_df = pd.DataFrame()
#define a variable probTarget which is equal to the probablity of a given class.(upto 4 decimal places)
# print len(test[test['target']==1])
test = test.drop('target', axis = 1)
rowCount = len(train.index)
probZero = len(train[train['target']==0])/rowCount
probOne = len(train[train['target']==1])/rowCount
probTarget = { 1 : probOne , 0 : probZero }
# print probTarget
# For each label in the training dataset, we compute the probability of the test instances.
condProbs = {}
for label in train['target'].unique():
df_temp = train[train['target']==label]
df_temp = df_temp.drop('target', axis = 1)
testset = test.copy(deep=True)
condProbs = calcConditionalProb(testset, df_temp)
condProbs.update((k, v * probTarget[label]) for k,v in condProbs.items())
prob_df[label] = condProbs.values()
print 'Probability DataFrame'
print prob_df.round(4)
print ''
# Define a list 'prediction' that stores the label of the class with highest probability for each test
# instance which are stored in prob_df dataframe.
prediction = []
for index,row in prob_df.iterrows():
prediction.append( 1 if (row[1] > row[0]) else 0 )
print 'Prediction'
print prediction
print ''
# Calculate the accuracy of your model. The function should take the prediction and groundTruth as inputs and return the
# confusion matrix. The confusion matrix is of 'dataframe' type.
def confusionMatrix(prediction, groundTruth):
'''
Return and print the confusion matrix.
'''
conf = pd.crosstab(groundTruth, prediction, rownames=['Actual'], colnames=['Predicted'])
print 'Confusion Matrix'
print conf
print ''
return conf
def accuracy(confusionMatrix):
'''
Calculates accuracy given the confusion matrix
'''
numerator = 0
denominator = 0
for index, row in confusionMatrix.iterrows():
for i in range(len(row)):
if(index == i):
numerator += row[i]
denominator += row[i]
return numerator / denominator
# Call the confusionMatrix function and print the confusion matrix as well as the accuracy of the model.
groundTruth = pd.Series(groundtruth)
prediction = pd.Series(prediction)
conf = confusionMatrix(prediction, groundTruth)
accuracy = accuracy(conf) #( conf[0][0] + conf[1][1] ) / ( conf[0][0] + conf[0][1] + conf[1][0] + conf[1][1] ) #define accuracy
print 'Accuracy = '+str(accuracy*100)+'%'
print ''
|
282c057e572159d08a607c0f382c0e53b27a45e1 | cfernandez005/Software-Testing-with-Python | /Shopping List Test/hw2.py | 3,173 | 3.5625 | 4 | #Chris Fernandez
#4/9/16
#Assignment #2: unittest module
import unittest #imports in the unittest class
from hw1 import * #imports all code from hw1.py
class shoppingListTest(unittest.TestCase): #class that defines code to be tested
def testIsComplete_onePositiveQuantity(self):
# is_complete function test case where one list item has a positive quantity: expected False
self.assertFalse( is_complete([['cheese', 0], ['milk', 0], ['eggs', 12]]) )
def testIsComplete_allQuantitiesZero(self):
# is_complete function test case where all list items have a zero quantity: expected True
self.assertTrue( is_complete([['bread', 0], ['pickles', 0], ['eggs', 0], ['radish', 0]]) )
def testIsComplete_oneNegaiveQuantity(self):
# is_complete test case where one list item has a negative quantity and the rest have a zero quantity: expected True
self.assertTrue( is_complete([['salami', 0], ['waffle', -10], ['noodles', 0]]) )
def testIsComplete_emptyList(self):
# is_complete test case of an empty list: expected True
self.assertTrue( is_complete([]) )
def testAddItem_notInList(self):
# add_item test case for adding an item to a list that was previously non-exsistent: expected new item appended to list
self.assertEqual( [['flour', 3], ['potatoe', 10], ['toothpaste', 1], ['chips', 101]],
add_item([['flour', 3], ['potatoe', 10], ['toothpaste', 1]], ['chips', 101]) )
def testAddItem_alreadyInList(self):
# add_item test case for adding a positive quantity item to a list where such item already exsists
# : expected item quantity addition to listed item qantity
self.assertEqual( [['apples', 22], ['mushroom', 17], ['chicken breast', 16]],
add_item([['apples', 22], ['mushroom', 17], ['chicken breast', 8]], ['chicken breast', 8]) )
def testUpdateItem_alreadyInList(self):
# updae_item test case for updating an already listed item with a positive quantity copy
# : expected item quantity subtraction from listed item qantity
self.assertEqual( [['bananas', 6], ['yogurt', 4], ['bagels', 8]],
update_item([['bananas', 6], ['yogurt', 12], ['bagels', 8]], ['yogurt', 8]) )
def testUpdateItem_notInList(self):
# update_item test case for updating an item that doesn't exsist on the list: expected list remain unchanged
self.assertEqual( [['provalone', 10], ['pepper jack', 3], ['mayonnaise', 1]],
update_item([['provalone', 10], ['pepper jack', 3], ['mayonnaise', 1]], ['cheddar', 13]) )
def testRemaining_emptyList(self):
# remaining test case where all listed items have quantities less than one: expected empty list
self.assertEqual( [], remaining([['kiwi', -5], ['prezels', 0], ['avacado', 0]]) )
def testRemainging_fullList(self):
# remaining test case where all listed items have quantities greater than zero: expected entire list
self.assertEqual( [['apricots', 27], ['chocolate', 17], ['ice', 2], ['sausage', 12]],
remaining([['apricots', 27], ['chocolate', 17], ['ice', 2], ['sausage', 12]]) )
if __name__ == "__main__":
unittest.main(verbosity = 2)
|
00e06879ec7de3ee1fc6e9927b5e7c8783047067 | m-hawke/codeeval | /moderate/170_guess_the_number.py | 338 | 3.625 | 4 | import sys
for line in open(sys.argv[1]):
l = line.split()
lower = 0
upper = int(l[0])
for answer in l[1:]:
guess = lower + ((upper - lower + 1) // 2)
if answer == 'Lower':
upper = guess - 1
elif answer == 'Higher':
lower = guess + 1
else:
print(guess)
|
065771d0f3f9d50fe8cdf1ec1fbe6c44ea3b2cb3 | m-hawke/codeeval | /easy/202_stepwise_word.py | 226 | 3.703125 | 4 | import sys
for line in open(sys.argv[1]):
longest = ''
for word in line.split():
if len(word) > len(longest):
longest = word
for i, c in enumerate(longest):
print '*' * i + c,
print
|
4688687e9a0f060339ab9aa968ce420d3a458e8f | m-hawke/codeeval | /easy/240_mersenne_prime.py | 894 | 3.671875 | 4 | import sys
def is_prime(n):
if n <= 1:
return False
if n <= 3:
return True
if n%2 == 0 or n%3 == 0:
return False
if n < 25:
return True
for i in range(3, int(n**0.5)+1, 2):
if n%i==0:
return False
return True
from itertools import count
def gen_mersennes():
c = count()
while True:
x = 2**next(c) - 1
if is_prime(x):
yield x
g = gen_mersennes()
mersennes = list(next(g) for i in range(5))
# Don't even need any of the above... the 5th mersenne number is 8191, well
# over the constraint of 3000 in the question.
# The following comprehension is not efficient as it always traverses the whole
# list, however, it's so short that it's not going to matter.
for line in open(sys.argv[1]):
print(', '.join(str(mersenne) for mersenne in mersennes if mersenne < int(line)))
|
a0670f05cc06bde04970f5325947af298724ff90 | m-hawke/codeeval | /easy/139_working_experience.py | 1,663 | 3.703125 | 4 | import sys
month_name_to_number = dict(Jan=1, Feb=2, Mar=3, Apr=4, May=5, Jun=6, Jul=7, Aug=8, Sep=9, Oct=10, Nov=11, Dec=12)
def to_months(s):
month, year = s.split()
return (int(year) * 12) + month_name_to_number[month]
for line in open(sys.argv[1]):
months = 0
previous_end = 0
for start, end in sorted((to_months(start), to_months(end))
for start, end in [pair.split('-')
for pair in line.strip().split('; ')]):
if start > previous_end:
months += end - start + 1
elif end > previous_end or start == previous_end:
months += end - previous_end
else:
continue
previous_end = end
print(months // 12)
## datetime is slower and uses more memory than the simple convert to months
## code above.
#import sys
#from datetime import datetime
#
#for line in open(sys.argv[1]):
# date_pairs = sorted([(datetime.strptime(start, '%b %Y'),
# datetime.strptime(end, '%b %Y'))
# for start, end in [pair.split('-')
# for pair in line.strip().split('; ')]])
#
# months = 0
# previous_end = None
# for start, end in date_pairs:
# if previous_end is None or start > previous_end:
# months += (end.year*12 + end.month) - (start.year*12 + start.month) + 1
# elif end > previous_end or start == previous_end:
# months += (end.year*12 + end.month) - (previous_end.year*12 + previous_end.month)
# else:
# continue
#
# previous_end = end
#
# print(months // 12)
|
0fe3ef67c5d137ae7ea4d3615800e98af00a1138 | m-hawke/codeeval | /easy/19_bit_positions.py | 168 | 3.5 | 4 | import sys
for line in open(sys.argv[1]):
n, p1, p2 = (int(x) for x in line.split(','))
print('true' if ((n >> (p1-1) & 1) == (n >> (p2-1) & 1)) else 'false')
|
5185d421330d59dc45577e6ed4e046a961461ae6 | m-hawke/codeeval | /moderate/17_sum_of_integers.py | 970 | 3.703125 | 4 | import sys
for line in open(sys.argv[1]):
numbers = [int(x) for x in line.strip().split(',')]
max_ = sum(numbers)
for length in range(1, len(numbers), 2): # N.B increment by 2
sum_ = sum(numbers[:length])
max_ = sum_ if sum_ > max_ else max_
for i in range(len(numbers)-length):
# N.B. the following sum is also a sum of contiguous numbers
# for length + 1. We need calculate this once only, and
# therefore the length loop (see above) is incremented by 2
# each time. */
sum_ += numbers[i+length]
max_ = sum_ if sum_ > max_ else max_
sum_ -= numbers[i]
max_ = sum_ if sum_ > max_ else max_
print(max_)
#for line in open(sys.argv[1]):
# numbers = [int(x) for x in line.strip().split(',')]
# print(max([sum(numbers[x:x+i])
# for i in range(1,len(numbers)+1)
# for x in range(len(numbers)-i+1)]))
|
332acd1b09be1ad4bdea876a5f3f82633319c7bc | cryojack/python-programs | /charword.py | 402 | 4.34375 | 4 | # program to count words, characters
def countWord():
c_str,c_char = "",""
c_str = raw_input("Enter a string : ")
c_char = c_str.split()
print "Word count : ", len(c_char)
def countChar():
c_str,c_char = "",""
charcount_int = 0
c_str = raw_input("Enter a string : ")
for c_char in c_str:
if c_char is not " " or "\t" or "\n":
charcount_int += 1
print "Character count : ", charcount_int |
97b52a2ae01df1847f043ac37a45c2d47e2cbb3f | cryojack/python-programs | /multiply.py | 298 | 4.0625 | 4 | #This program prints a multiplication table upto count_int
num1_int = 1
num2_int = 1
res_int = 0
count_int = 10
while num1_int <= count_int:
res_int = num1_int * num2_int
print num1_int , " x " , num2_int , " = " , res_int
num2_int += 1
if num2_int > count_int:
num2_int = 1
num1_int += 1 |
e8db5926f025fcd3547334aeb313c1a7c7012940 | akshatha-nayak/quiz-application | /quiz_application_akshatha.py | 7,733 | 3.734375 | 4 | import json
def edit_q(di,sub,level,ques):
print(di["quiz"][sub][level][ques]["question"])
question=input("Edit question: ")
di["quiz"][sub][level][ques]["question"]=question
return di
def edit_o(di,sub,level,ques):
c=1
for option in di['quiz'][sub][level][ques]['options']:
print(c,option)
c+=1
b=int(input("Which option wants to edit: "))
di['quiz'][sub][level][ques]['options'][b-1]=input("Enter option: ")
return di
def edit_a(di,sub,level,ques):
print(di["quiz"][sub][level][ques]["answer"])
answer=input("Edit answer: ")
di["quiz"][sub][level][ques]["answer"]=answer
return di
def show_topics(di):
print("Topics are : ")
quiz_data=di["quiz"]
c=1
l=[]
for type_of_sub in quiz_data:
print("{}) {}".format(c,type_of_sub) )
c+=1
l.append(type_of_sub)
return l
def show_quiz(di):
quiz_data = di['quiz']
for type_of_sub in quiz_data:
print(type_of_sub)
print('==============')
for level in quiz_data[type_of_sub]:
print(level)
print('==============')
question_counter = 1
for question_no in quiz_data[type_of_sub][level]:
print(str(question_counter)+')',quiz_data[type_of_sub][level][question_no]['question'])
question_counter+=1
option_counter = 97
for option in quiz_data[type_of_sub][level][question_no]['options']:
print(chr(option_counter)+'.',option)
option_counter+=1
print("Answer:",quiz_data[type_of_sub][level][question_no]['answer'])
print('\n')
def Admin(di):
T=True
while T:
print("1. View Quizzes\n2. Create Quiz \n3. Edit Quiz\n4. Delete Quiz\n5. View Topics\n6. Logout")
n=int(input("Choose what you want: "))
if(n==1):
show_quiz(di)
elif(n==2):
type_of_sub=input("Subject: ")
level=input("Level: ")
question_no=input("Ques_Id: ")
ques=input("question: ")
count=int(input("How many option: "))
option=list(input("option: ") for i in range(count))
answer=input("answer: ")
di["quiz"][type_of_sub]={level:{question_no:{"question":ques, "options": option,"answer":answer}}}
dump_data = json.dumps(di)
fp = open('quizdata.json','w+')
fp.write(dump_data)
fp.close()
elif(n==3):
show_topics(di)
sub=input("In which topic you want to edit: ")
for level in di['quiz'][sub]:
print(level)
print('==============')
question_counter = 1
for question_no in di['quiz'][sub][level]:
print(str(question_counter)+')',di['quiz'][sub][level][question_no]['question'])
question_counter+=1
option_counter = 97
for option in di['quiz'][sub][level][question_no]['options']:
print(chr(option_counter)+'.',option)
option_counter+=1
s=int(input("What you want to edit: \n1. Question \n2. Options\n3. Answer\n ---> " ))
level=input("In which level (Easy, Medium, Hard): ")
ques=input("which question id (eg: q1, q2) : ")
if(s==1):
edit_q(di,sub,level,ques)
elif(s==2):
edit_o(di,sub,level,ques)
elif(s==3):
edit_a(di,sub,level,ques)
dump_data = json.dumps(di)
fp = open('quizdata.json','w+')
fp.write(dump_data)
fp.close()
elif(n==4):
quiz_data=di["quiz"]
c=1
for type_of_sub in quiz_data:
print(c,type_of_sub)
c+=1
sub=input("which subject you want to delete: ")
del di["quiz"][sub]
print(sub, "quiz is deleted")
dump_data = json.dumps(di)
fp = open('quizdata.json','w+')
fp.write(dump_data)
fp.close()
elif(n==5):
show_topics(di)
elif(n==6):
return
def result(di,d,sub,level,user):
c=0
for i in d:
# print(di["quiz"][sub][level]['q'+str(i)]["answer"],di["quiz"][sub][level]['q'+str(i)]["options"][d[i]])
if(di["quiz"][sub][level]['q'+str(i)]["answer"]== di["quiz"][sub][level]['q'+str(i)]["options"][d[i]-1]):
c+=1
print("Q{0}) Your answer is {2}\n Correct Answer is {1}".format(i,di["quiz"][sub][level]['q'+str(i)]["answer"],di["quiz"][sub][level]['q'+str(i)]["options"][d[i]-1]))
print("Total percentage: {}%".format(round(c/len(d)*100),2))
def test_taker(di,user):
while True:
n=int(input("1. Take Quiz \n 2. Logout \n choose the option: "))
if(n==1):
t=show_topics(di)
s=int(input("Choose topic: "))
sub=t[s-1]
k=["Easy", "Medium", "Hard"]
print("1. Easy Level 2. Medium Level 3.Hard Level")
l=int(input("Select level: "))
level=k[l-1]
d={}
question_counter = 1
for question_no in di['quiz'][sub][level]:
print(str(question_counter)+')',di['quiz'][sub][level][question_no]['question'])
option_counter = 1
for option in di['quiz'][sub][level][question_no]['options']:
print(str(option_counter) +'] ',option)
option_counter+=1
ans=int(input("Answer: "))
d[question_counter]=ans
question_counter+=1
result(di,d,sub,level,user)
elif(n==2):
return
def Login(di):
while True:
print("Please Login: ")
user=input("user_id : ")
passw=input("password: ")
if(user in di["user"]):
if(di["user"][user]==passw):
if(user=="Admin"):
print("Login Succesful")
dump_data = json.dumps(di)
fp = open('quizdata.json','w+')
fp.write(dump_data)
fp.close()
Admin(di)
else:
test_taker(di,user)
break
else:
print("user does not exit Register please")
di=registeration(di)
return di
def registeration(di):
while True:
user=input("user_id : ")
passw=input("password: ")
if(user in di["user"]):
print("Username is exits, please choose other ")
continue
di["user"][user]=passw
print("Registration Successfull")
dump_data = json.dumps(di)
fp = open('quizdata.json','w+')
fp.write(dump_data)
fp.close()
break
return di
if __name__=="__main__":
fp = open('quizdata.json','r')
content = fp.read()
di = json.loads(content)
fp.close()
inu=input("Login or register: ")
if(inu=="Login"):
Login(di)
print("Logout!!!")
elif(inu=="Res"):
registeration(di)
|
7111f56b0b2682a68818482d802c98aa4b81e072 | dennis-wei/AdventCode2019 | /17/solution.py | 2,157 | 3.5 | 4 | from computer import Computer
import time
from collections import defaultdict
import math
def parse_input(filename):
with open(filename, 'r') as f:
return [int(n) for n in f.read().strip().split(',')]
def get_adjacent(x, y):
return [(x + 1, y), (x - 1, y), (x, y - 1), (x, y + 1)]
def print_grid(grid):
minx = min(t[0] for t in grid.keys())
maxx = max(t[0] for t in grid.keys())
miny = min(t[1] for t in grid.keys())
maxy = max(t[1] for t in grid.keys())
for y in range(miny, maxy + 1):
for x in range(minx, maxx + 1):
print(grid[(x, y)], end='')
print()
print()
def part1():
code = parse_input("input.txt")
computer = Computer(code)
output = computer.run_on_input([])
as_ascii = [chr(n) for n in output]
rows = "".join(as_ascii).split("\n")
grid = defaultdict(lambda: ".")
scaffolding = set()
for y, r in enumerate(rows):
for x, c in enumerate(r):
grid[(x, y)] = c
if c == '#':
scaffolding.add((x, y))
# print(c, end="")
# print()
intersections = set()
a1 = 0
for c in scaffolding:
if all(a in scaffolding for a in get_adjacent(*c)):
intersections.add(c)
grid[c] = "0"
a1 += c[0] * c[1]
print_grid(grid)
print("Answer to Part 1: ", a1)
def part2():
ascii_answer = "A,B,B,A,C,B,C,C,B,A\n" + \
"R,10,R,8,L,10,L,10\n" + \
"R,8,L,6,L,6\n" + \
"L,10,R,10,L,6\n" + \
"n\n"
raw_answer = [ord(c) for c in ascii_answer]
print(raw_answer)
code = parse_input("input.txt")
code[0] = 2
computer = Computer(code)
output = computer.run_on_input(raw_answer)
as_ascii = [chr(n) for n in output[:-1]]
rows = "".join(as_ascii).split("\n")
for y, r in enumerate(rows):
for x, c in enumerate(r):
print(c, end="")
print()
print("Answer to Part 2: ", output[-1])
start = time.time()
part1()
print(f"Took {time.time() - start} seconds for Part 1")
part2()
print(f"Took {time.time() - start} seconds for both parts") |
112b49adaf048b44ce9ef2cc25520fd5d85685be | Rekk-e/FoodForStudent | /main.py | 630 | 3.75 | 4 | # This is a sample Python script.
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
print('n=')
n = int(input())
k = 0
for a in range(1, n):
for b in range(a, n):
for c in range(b, n):
if (c < a + b) and (a < b + c) and (b < a + c) and (a + b + c == n):
k = k+1
print(str(k) + ' treugolnikov')
# See PyCharm help at https://www.jetbrains.com/help/pycharm/
|
a922e393c7f593a0f00bbe645c9dc344db6c173c | Daywison11/Python-exercicios- | /ex040.py | 587 | 3.84375 | 4 | #Crie um programa que leia duas notas de um aluno e calcule sua média, mostrando uma mensagem
# no final, de acordo com a média atingida:
#- Média abaixo de 5.0: REPROVADO
#- Média entre 5.0 e 6.9: RECUPERAÇÃO
#- Média 7.0 ou superior: APROVADO
n1 = float(input('Digite a primeira nota: '))
n2 = float(input('Digite a segunda nota: '))
media = (n1 + n2) / 2
if media >= 7:
print(f'Sua média é {media:.2f} e você foi aprovado')
elif media < 5:
print(f'Sua média é {media:.2f} e você foi reprovado')
else:
print(f'Sua média é {media:.2f} e você está de recuperação') |
28d38ddd8f5cf86011e785037ef891a338810b23 | Daywison11/Python-exercicios- | /ex014.py | 252 | 4.25 | 4 | # Escreva um programa que converta uma temperatura digitando
# em graus Celsius e converta para graus Fahrenheit.
gc = float(input('infoeme a temperatra em °C :'))
fr = ((9*gc)/5) + 32
print('a temeratura de {}°C conrresponde a {}° F'.format(gc,fr)) |
4da9c666be85e52340aab787a3111fa7da1a1e29 | Daywison11/Python-exercicios- | /ex013.py | 259 | 3.640625 | 4 | """faça um programa que leia o salario de um fncionario e calcule o novo salario com 15% de almento"""
sl = float(input('digite o seu salario atual :'))
s1 = (sl * 15)
s2 = (s1 / 100)
s3 = (s2 + sl)
print('o seu salrio com 15% de almento é {}'.format(s3))
|
09a9915bab7ba3d94aeb385f9500567d3f47f9ee | Daywison11/Python-exercicios- | /ex001.py | 214 | 3.625 | 4 | nm =input('input qual seu nome ?')
idd =input('quantos anos voce tem ? ')
cdd =input('qual sua cidade natal?')
print('então seu nome é',nm,'voce tem',idd,'anos e voce mora na cidade de',cdd)
print('estou certo?') |
a1694deb4ac7b9e21d5057dbba059274cfea5290 | Daywison11/Python-exercicios- | /ex006.py | 246 | 4.09375 | 4 | """#crie um algoritimo que mostre seu dobro, triplo e a raiz quadrada"""
n1 = int(input('digite um numero: '))
D = (n1 * 2)
t = (n1 * 3)
rq = (n1 **(1/2))
print('o dobro desse numero é {} o triplo é {} e a raiz quadrada é {}'.format(D,t,rq)) |
7a4e9d405f3eaf80368e7d8d64ffbcf79d806a36 | hunguyen1702/lpthw | /ex45_maze_runner/weapon.py | 726 | 3.546875 | 4 | class Weapon(object):
def __init__(self):
self.name = "Weapon"
self.damage = 0
self.stability = 0
def decrease_stability(self):
self.stability -= 1
def is_broken(self):
if self.stability < 1:
print "%r is broken" % self.name
return True
return False
class Sword(Weapon):
def __init__(self):
self.name = "Sword"
self.damage = 15
self.stability = 3
class Knife(Weapon):
def __init__(self):
self.name = "Knife"
self.damage = 5
self.stability = 1
class FireGun(Weapon):
def __init__(self):
self.name = "FireGun"
self.damage = 100
self.stability = 3
|
19310bbd5067e23a07056a18585c5d2ff328d72a | ecaoili24/holbertonschool-higher_level_programming | /0x0B-python-input_output/9-add_item.py | 505 | 3.6875 | 4 | #!/usr/bin/python3
"""Module 9-add_item
Adds all arguments to a Python list, and then save them to a file
"""
import sys
import json
save_to_json_file = __import__("7-save_to_json_file").save_to_json_file
load_from_json_file = __import__("8-load_from_json_file").load_from_json_file
filename = "add_item.json"
my_list = []
try:
my_list = load_from_json_file(filename)
except:
my_list = []
for x in range(1, len(sys.argv)):
my_list.append(sys.argv[x])
save_to_json_file(my_list, filename)
|
9f98c013d81e525f857fafffec8301a5f57b97ca | ecaoili24/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/9-multiply_by_2.py | 111 | 3.578125 | 4 | #!/usr/bin/python3
def multiply_by_2(a_dictionary):
return {key: x * 2 for key, x in a_dictionary.items()}
|
b3acfef8d2e2a8974b0c41b133bde3c2e7091030 | ecaoili24/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/2-matrix_divided.py | 1,283 | 4.0625 | 4 | #!/usr/bin/python3
"""
This module contains the matrix_divided function
"""
def matrix_divided(matrix, div):
"""
Divides all elements of a matrix. Returns a
new matrix (list of list). The result is
rounded to 2 decimal places.
"""
if not isinstance(matrix, list) or len(matrix) == 0 or not matrix[0]:
raise TypeError("matrix must be a matrix (list of lists) " +
"of integers/floats")
for row in matrix:
if len(row) is 0:
raise TypeError("matrix must be a matrix (list of lists) " +
"of integers/floats")
for i in row:
if type(i) != int and type(i) != float:
raise TypeError("matrix must be a matrix (list of lists) " +
"of integers/floats")
len_rows = []
for row in matrix:
len_rows.append(len(row))
if not all(elements == len_rows[0] for elements in len_rows):
raise TypeError("Each row of the matrix must have the same size")
if type(div) != int and type(div) != float:
raise TypeError("div must be a number")
if div is 0:
raise ZeroDivisionError("division by zero")
NEW_matrix = [[round(i / div, 2) for i in row] for row in matrix]
return NEW_matrix
|
5940b3f15cdea71a5c640d29579398334e0381b7 | sachin-goyal-github/python-dojos | /katas/data-munging/part-one.py | 762 | 3.984375 | 4 | """
# http://codekata.com/kata/kata04-data-munging/
Part One: Weather Data
In weather.dat you’ll find daily weather data for Morristown, NJ for June 2002.
Download this text file, then write a program to output the day number (column one)
with the smallest temperature spread (the maximum temperature is the second column,
the minimum the third column).
"""
spread_days = {}
with open('weather.dat', 'r') as f:
for line in f:
columns = [column.strip() for column in line.split(' ') if column != '']
if len(columns) >= 3 and columns[0].isnumeric():
day = columns[0]
spread = int(columns[1].strip("*")) - int(columns[2].strip("*"))
spread_days[spread] = day
print(spread_days[min(spread_days.keys())])
|
580abee3fc3b1aa466caa38d6e38e2b0e4fb3d50 | guard1000/Everyday-coding | /190319_[모의 SW 역량테스트]_벽돌 깨기.py | 3,840 | 3.5 | 4 | import itertools
def bomb(board2, pos):
nxt=[]
if len(pos) == 0: return board2
for p in pos: #다음 폭발
d = p[2]
board2[p[0]][p[1]] = 0 #펑
for r in range(1,d): #up
if p[0] - r < 0 or board2[p[0] - r][p[1]] == 0: break
elif board2[p[0]-r][p[1]] != 1 and [p[0]-r,p[1],board2[p[0]-r][p[1]]] not in nxt: nxt.append([p[0]-r,p[1],board2[p[0]-r][p[1]]])
board2[p[0] - r][p[1]] = 0
for r in range(1,d): #down
if p[0] + r >= len(board2) or board2[p[0] + r][p[1]] == 0: break
elif board2[p[0]+r][p[1]] != 1 and [p[0]+r,p[1],board2[p[0]+r][p[1]]] not in nxt: nxt.append([p[0]+r,p[1],board2[p[0]+r][p[1]]])
board2[p[0] + r][p[1]] = 0
for c in range(1,d): #left
if p[1] - c < 0: break
elif board2[p[0]][p[1]-c] != 1 and [p[0],p[1]-c,board2[p[0]][p[1]-c]] not in nxt: nxt.append([p[0],p[1]-c,board2[p[0]][p[1]-c]])
board[p[0]][p[1]-c] = 0
for c in range(1,d): #right
if p[1] + c >= len(board2[0]): break
elif board2[p[0]][p[1]+c] != 1 and [p[0],p[1]+c,board2[p[0]][p[1]+c]] not in nxt: nxt.append([p[0],p[1]+c,board2[p[0]][p[1]+c]])
board2[p[0]][p[1]+c] = 0
return bomb(board2,nxt)
def drop(board):
for col in range(len(board[0])):
p = len(board)-1
for row in range(len(board)-1,-1,-1):
if board[row][col] != 0:
temp = board[row][col]
board[row][col] = 0
board[p][col] = temp
p -= 1
return board
def cnt(board):
zero_sum=0
for b in board:
zero_sum += b.count(0)
return len(board)*len(board[0])-zero_sum
T = int(input())
for t in range(T):
N,W,H = map(int, input().split())
answer=N*H
board=[]
for h in range(H):
board.append(list(map(int,input().split())))
target = [i for i in range(W)]
mypermutation = itertools.product(target, repeat=N)
for permutation in mypermutation:
tmp = board[:]
print(tmp)
for col in permutation:
if tmp[H-1][col] == 0:
break
for row in range(H):
if tmp[row][col] != 0:
break
print([row,col])
tmp = bomb(tmp,[[row,col,tmp[row][col]]])
print('bb',board)
tmp = drop(tmp)
if cnt(tmp) < answer:
answer = cnt(tmp)
print(permutation, answer)
print('b',board)
print(answer)
'''
for n in range(N):
target=[0,0]
for col in range(W):
flag = 0
for row in range(H):
if row == H-1 and board[row][col]==0:
flag = 1
if board[row][col] != 0:
break
if flag == 1:
flag = 0
break
tmp = bomb(board,[[row,col,board[row][col]]])
if answer > cnt(tmp):
answer = cnt(tmp)
target = [row,col]
board = bomb(board,[[target[0],target[1],board[target[0]][target[1]]]])
board = drop(board)
answer = cnt(board)
print(answer, target)
print(answer)
'''
'''
tmp = bomb(board,[[2,2,board[2][2]]])
for t in tmp:
print(t)
print('222')
tmp = drop(board)
for t in tmp:
print(t)
print(cnt(tmp))
'''
'''
for n in range(N):
for i in range(W - 1, -1, -1): # 구슬 비었을 경우
if board[H - 1][i] == 0 and i in target: target.remove(i)
'''
'''
1
3 10 10
0 0 0 0 0 0 0 0 0 0
1 0 1 0 1 0 0 0 0 0
1 0 3 0 1 1 0 0 0 1
1 1 1 0 1 2 0 0 0 9
1 1 4 0 1 1 0 0 1 1
1 1 4 1 1 1 2 1 1 1
1 1 5 1 1 1 1 2 1 1
1 1 6 1 1 1 1 1 2 1
1 1 1 1 1 1 1 1 1 5
1 1 7 1 1 1 1 1 1 1
''' |
29d286f30d32b97138e37ae81ceb5bb38a63c4b5 | guard1000/Everyday-coding | /1013문알준비.py | 843 | 3.953125 | 4 | '''
print([num * 3 for num in range(3)])
print([num * 3 for num in range(10) if num % 2 == 0])
print([x * y for x in range(2, 10) for y in range(1, 10)])
'''
# 실습 1
for i in range(5): # 혹은 (1,6):
for j in range(5-i):
print('*', end='')
print("")
#실습 2번
print('1번')
num = [1,2,3,4,5,6,7,8,9,10]
result = [n*2 for n in num if n%2]
print(result, '\n')
print('2번')
vowels = 'aeiou'
sentence = 'Do not learn English, but learn Python.'
print(''.join([a for a in sentence if a not in vowels]))
#print(' '.join([a for a in sentence if a.lower() not in vowels]))
#과제 - f
score= [20,55,67,82,45,33,90,87,100,25]
total = 0
count = 0
while len(score) != 0:
mark = score.pop()
if mark >= 50:
total += mark
count += 1
print('총합: {0}, 평균 {1:0.2f}'.format(total, total/count))
|
e19a24fc954f816fea4cd614353d38e5cc5f1698 | guard1000/Everyday-coding | /14주차_문알준비_tkinter.py | 5,193 | 3.53125 | 4 | from turtle import*
penup()
금액 = numinput("지불액",'얼마를 받아야 합니까? ')
goto(0,260)
msg1 = str(int(금액))+'원 받아야 합니다!'
write(msg1,align = "left", font=('Arial', 15,"bole"))
낸돈 = numinput("받은돈",'얼마를 받았습니까? ')
goto(0,290)
msg2 = str(int(낸돈))+'원 받았습니다!'
write(msg2,align = "left", font=('Arial', 15,"bold"))
if 낸돈 < 금액:
goto(200,260)
write("돈이 충분하지 않습니다.", font=('Arial', 15,"italic", "underline"))
elif 낸돈 == 금액:
goto(200,260)
write("거스름돈 없습니다.", font=('Arial', 15,"italic", "underline"))
exitonclick()
else:
change =낸돈 - 금액
msg3 = str(int(change))+'원 거슬러 드리겠습니다!'
goto(0,2250)
write(msg3, align="left", font=('Arial', 15, "bold"))
def make_change(change):
c50000 = int(change/50000)
change = change%50000
c10000 = int(change / 10000)
change = change % 10000
c5000 = int(change / 5000)
change = change % 5000
c1000 = int(change / 1000)
change = change % 1000
c500 = int(change / 500)
change = change % 500
c100 = int(change / 100)
change = change % 100
c50 = int(change / 50)
change = change % 50
c10 = int(change / 10)
change = change % 10
'''
#6,7분반
from tkinter import *
def BMI():
h = float(h_value.get())
w = float(w_value.get())
bmi = w/((h/100)*(h/100))
if bmi < 18.5:
result_value='저체중'
elif bmi >= 18.5 and bmi < 23.0:
result_value = '정상체중'
elif bmi >= 23.0 and bmi < 25:
result_value = '과체중'
else:
result_value = '비만'
result.set(result_value)
window = Tk() #윈도우 창 생성
h_value = DoubleVar() #변수 지정
w_value = DoubleVar()
result = StringVar()
lbl = Label(window, text='BMI 프로그램: ') #윈도우에 표시할 레이블 설정
lbl.grid(row=0, column=0, columnspan=2) #레이블 위치 설정
h_lbl = Label(window, text='키를 입력하세요: ') #키 레이블 위젯 설정
h_lbl.grid(row=1, column=0) #키 레이블 위젯 위치 설정
h_entry = Entry(window, textvariable = h_value) #키 한줄 텍스트 위젯 속성 설정
h_entry.grid(row=1, column=1)
w_lbl = Label(window, text='몸무게를 입력하세요: ') #몸무게
w_lbl.grid(row=2, column=0)
w_entry = Entry(window, textvariable = w_value)
w_entry.grid(row=2, column=1)
result_value_lbl = Label(window, text='판단 결과: ')
result_value_lbl.grid(row=3, column=0)
result_value_lbl = Label(window, textvariable=result) #결과 한줄 텍스트 위젯 속성 설정
result_value_lbl.grid(row=3, column=1)
calc_btn = Button(window, text='계산!', command=BMI)
calc_btn.grid(row=4, column=1)
window.mainloop() #윈도우 창의 이벤트 메시지 처리 루프
'''
'''
#5분반-이진탐색
def binary_search(list, target):
first = 0
last = len(list)-1
found = -1
while(first <= last and found == -1):
mid = (first+last)//2
if target == list[mid]:
found = mid
else:
if list[mid] > target:
last = mid -1
else:
first = mid + 1
if found == -1:
print('이분탐색 실패: 찾고자 하는', target, '이 없네요!!')
return False
else:
print('이분탐색 성공:', mid, '인덱스에서', target, '을 찾았어요~!!')
return True
list = [6,13,14,25,33,43,51,53,64,72,84,93,95,96,97]
print(binary_search(list,33))
print(binary_search(list,90))
'''
'''
#5분반-이진탐색 with GUI
from tkinter import *
def binary_search(list, target):
first = 0
last = len(list)-1
found = -1
search_process_txt.delete(1.0, END) #멀티라인 텍스트 위젯의 첫줄 삭제
while(first <= last and found == -1):
mid = (first+last)//2
if target == list[mid]:
found = mid
else:
if list[mid] > target:
last = mid -1
else:
first = mid + 1
if found == -1:
not_find_print = str(mid) + ' 인덱스에 ' + str(target) + '가 없네요!!\n'
search_process_txt.insert(1.0, not_find_print)
else:
find_print = str(mid) + ' 인덱스에서 ' + str(target) + '를 찾았어요~!!\n'
search_process_txt.insert(1.0, find_print)
list = [6,13,25,33,43,53,64,72,84,97]
window =Tk()
window.title('이분탐색')
window.geometry('400x300+100+100')
lbl = Label(window, text='입력된 자료들')
lbl.grid(row='0', column='0', padx='10', pady='10', sticky='e')
list_print_txt = Label(window, text=list, width='35', relief='solid')
list_print_txt.grid(row='0', column='1', columnspan='2', padx='0')
target_txt = Entry(window, width='20')
target_txt.grid(row='1', column='1', pady=10)
btn = Button(window, text = '이분탐색 시작', command = lambda:binary_search(list, int(target_txt.get())))
btn.grid(row='1', column='2', padx='10', pady='10', sticky='w')
search_process_txt = Text(window, width='47', height='10', relief='solid')
search_process_txt.grid(row='2', columnspan='3', padx='10', pady='10')
window.mainloop()
''' |
8604f551595a8601f5b3085c2d7e2623af5e69e6 | guard1000/Everyday-coding | /algo0920.py | 761 | 3.5 | 4 | #선택 정렬
def SelectionSort(data):
for i in range(0, len(data)-1):
j=i+1
while(j < len(data)):
if data[i] > data[j]:
data[i],data[j] = data[j],data[i]
j = j+1
return data
All = [] #데이터 리스트입니다.
with open('data.txt') as f: #데이터를 READ하는 모듈
lines = f.read().split() #data.txt 파일에 들어있는 데이터들을 line별로 읽어와서
for line in lines: #All리스트에 append 시켜줍니다.
All.append(int(line))
print(All) #원래 파일상에 저장되어있는 500개의 데이터
print(SelectionSort(All)) #선택정렬을 통해 절렬된 이후의 데이터
|
f9840bccce9ab85dd3a92b646d80f5134f81ac5a | guard1000/Everyday-coding | /190118_타일 장식물.py | 234 | 3.546875 | 4 | def func(a,b,N):
c = a+b
N -= 1
if N == 0:
return 2*(c+b)+2*c
return func(b,c,N)
def solution(N):
if N == 1: return 4
if N == 2: return 6
return func(1,1,N-2)
print(solution(5))
print(solution(6)) |
8bee9637f999a7d2b935c2b334cb3e54b9525572 | guard1000/Everyday-coding | /190226_자동완성.py | 1,617 | 3.640625 | 4 | class Node(object):
def __init__(self, key, data=None):
self.key = key
self.data = data
self.cnt=0
self.children = {}
class Trie(object):
def __init__(self):
self.head = Node(None)
def insert(self, string):
curr_node = self.head
for char in string:
if char not in curr_node.children:
curr_node.children[char] = Node(char)
curr_node = curr_node.children[char]
curr_node.cnt +=1
curr_node.data = string
def count_trie(self, string):
curr_node = self.head
cnt=0
for char in string:
cnt +=1
curr_node = curr_node.children[char]
if curr_node.data == string or curr_node.cnt==1:
return cnt
def solution(words):
answer = 0
trie = Trie()
for word in words:
trie.insert(word)
for word in words:
answer += trie.count_trie(word)
return answer
'''
def solution(words):
answer = 0
for word in words:
l = len(word)
i=0
while i < l:
cnt=0
for w in words:
if w[:l-i] == word[:l-i]:
cnt += 1
if cnt > 1 and i != 0:
answer += (l-i+1)
break
elif cnt > 1 and i == 0:
answer += (l - i)
break
i += 1
if i == l:
answer += 1
return answer
'''
print(solution(['war','word','world','warrior']))
#print(solution(['go','gone','guild']))
#print(solution(['go','wone','euild'])) |
76137c57fb4ed3643916d81c75f2fc7b6047a95d | guard1000/Everyday-coding | /1006_H-Index.py | 391 | 3.6875 | 4 | #string = "this is test string"
#print (string.find("test"))
def solution(phone_book):
answer = True
pb= sorted(phone_book, key=lambda x: len(x))
for i in range(len(pb)-1):
for j in range(1, len(pb)-i):
if pb[i+j].find(pb[i]) == 0:
answer = False
break
return answer
a=['119', '97674223', '1195524421']
print(solution(a)) |
75754e6d155b309fe88826f1e31abf1f89b26f89 | guard1000/Everyday-coding | /quick_sort.py | 1,020 | 3.578125 | 4 | def quick_sorted(arr):
if len(arr) > 1: #그래도 일단 원소가 2개이상은 되어야 정렬을 할 것입니다.
pivot = arr[len(arr) - 1] #피봇을 잡음.
left, mid, right = [], [], [] #피봇보다 작은 녀석은 left, 큰건 right, 피봇과 같은 값이면 mid에
for i in range(len(arr)):
if arr[i] < pivot:
left.append(arr[i])
elif arr[i] > pivot:
right.append(arr[i])
else:
mid.append(arr[i])
return quick_sorted(left) + mid + quick_sorted(right) #left, right 녀석들은 재귀로 다시 정렬!
else:
return arr
arr = []
with open('data.txt') as f: #데이터를 READ하는 모듈
lines = f.read().split() #data.txt 파일에 들어있는 데이터들을 line별로 읽어와서
for line in lines: #All리스트에 append 시켜줍니다.
arr.append(int(line))
answer = quick_sorted(arr)
print(answer)
|
f459575bade7989019661f8cb804b67d89fa0059 | guard1000/Everyday-coding | /0902.py | 1,980 | 3.515625 | 4 | import re #입력받는 특수문자, 숫자를 없애기 위해 정규식 사용
str1 = input()
str2 = input()
str1 = re.sub('[^A-Za-z]+', '', str1) #정규식. A-Z나 a-z외엔 모두제거
str2 = re.sub('[^A-Za-z]+', '', str2)
str1 = list(str1) #정규화된 결과를 한글자씩 list로 넣음
str2 = list(str2)
len1 = len(str1) #각 리스트의 길이
len2 = len(str2)
s1 = [] # 2문자씩 끊어 들어갈 리스트
s2 = []
gyo = 0 #자카드유사도 계산을 위한 변수들
hap = 0
J = 0.0
def intersec(a, b):
intersec_extend = []
intersec_extend.extend(a)
intersec_extend.extend(b)
intersec_extend = list(set(intersec_extend))
answer=[]
cnta=0
cntb=0
for m in intersec_extend:
for n in range(len(a)):
if a[n] == m:
cnta += 1
for k in range(len(b)):
if b[k] == m:
cntb += 1
for o in range(min(cnta, cntb)):
answer.append(m)
cnta=0
cntb=0
return len(answer)
def union(a, b):
union_extend = []
union_extend.extend(a)
union_extend.extend(b)
union_extend = list(set(union_extend))
answer=[]
cnta=0
cntb=0
for m in union_extend:
for n in range(len(a)):
if a[n] == m:
cnta += 1
for k in range(len(b)):
if b[k] == m:
cntb += 1
for o in range(max(cnta, cntb)):
answer.append(m)
cnta = 0
cntb = 0
return len(answer)
for i in range(len1 - 1): # s1에 두글자씩 끊어 추가. 대소문자 구별X
s1.append(str1[i] + str1[i + 1])
s1[i] = s1[i].lower()
for i in range(len2 - 1): # s2에 두글자씩 끊어 추가. 대소문자 구별X
s2.append(str2[i] + str2[i+1])
s2[i] = s2[i].lower()
gyo = intersec(s1, s2)
hap = union(s1, s2)
J = gyo/hap
answer = int(J*65536)
print(answer) |
b05739c495c2fa16e7bcbc7ec804562ffead519c | sallybao29/Softdev-Spring | /hw09/qsort.py | 325 | 3.5 | 4 | import random
def qsort(l):
if len(l) <= 1:
return l
pivot = random.choice(l)
nl = l[0:pivot] + l[pivot+1:]
lh = [x for x in nl if x < pivot]
uh = [x for x in nl if x > pivot]
return qsort(lh) + [x for x in l if x == pivot] + qsort(uh)
l = [10, 5, 9, 10, 4, 256, 2, 2]
print qsort(l)
|
2fe0c11eec86719da7ff695feec54bc2a5aedead | Tohanos/randomPotGenerator | /main.py | 1,337 | 3.671875 | 4 | import random
import numpy as np
import matplotlib.pyplot as plt
class RandomPot:
def __init__(self, initval, maxspeed, mindif):
self.value = initval
self.maxSpeed = maxspeed
self.speed = 0
self.mindif = mindif
def calcnextval(self, target):
dif = target - self.value
sign = np.sign(dif)
absdif = np.abs(dif)
if absdif < self.mindif:
self.speed = 0
return target
if absdif < self.maxSpeed:
self.speed = absdif / 2
else:
self.speed += 1
if self.speed > self.maxSpeed:
self.speed = self.maxSpeed
self.value += self.speed * sign
return self.value
maxSpeed = 1000
mindif = 2
pot = RandomPot(512, maxSpeed, mindif)
rng = np.arange(1000)
rnd = np.random.randint(0, 1023, size=(1, rng.size))
time = rng
val = []
target = random.randint(0, 1023)
for vals in time:
print(target)
nextval = pot.calcnextval(target)
print(nextval)
val.append(nextval)
if nextval == target:
target = random.randint(0, 1023)
fig, ax = plt.subplots(figsize=(5, 3))
plt.plot(val)
ax.set_title('Pot value with random dispersion')
ax.legend(loc='upper left')
ax.set_ylabel('Value')
ax.set_xlim(xmin=time[0], xmax=time[-1])
fig.tight_layout()
plt.show()
|
97b03f37db8b4930824932c531d53d3140fe190b | sysravi/codechef_pr_beginner | /HEADBOB.py | 343 | 3.765625 | 4 | r=int(input())
for _ in range(r):
n=int(input())
x=input()
flag=False
for i in x:
if i!="N":
if i=="Y" :
ntn="NOT INDIAN"
if i=="I":
ntn="INDIAN"
flag=True
break
if (flag==False):
print("NOT SURE")
else:
print(ntn)
|
7e1a037b78764940af13e570c85594f6e9ff8752 | sysravi/codechef_pr_beginner | /TRISQ.py | 111 | 3.609375 | 4 | for i in range(int(input())):
x = int(input())
x -= 2
x = x//2
y = int(x*(x+1)/2)
print(y)
|
d2ba291623cfb50ca5845e2d668f0cabf51aaa53 | operationstratus/viper_chaos | /battleship_game/battleship_01.py | 1,659 | 3.703125 | 4 | n = 5
# n x n
b = 10
# boats
HITS = 0
BOOMS = 0
class Tile:
def __init__(self, boat=False):
self.__boat = boat
self.__character = " "
def shoot(self):
if self.__boat:
self.__character = "x"
return self.__boat # returns true if there indeed was a boat here, but false if there was none
def get_character(self):
return self.__character
def setup():
BattleMap = [] # list with all the Tiles
i = 0
for w in range(n):
for h in range(n):
print(str(i))
i += 1 # bara för att testa att for loopen funkar
if corresponding tile in the text file has ha boat on this tile number:
boat = True
else:
boat = False
BattleMap.append(Tile(boat))
return BattleMap
def update(BattleMap):
i = 0
for Tile in BattleMap:
here print the right amount of "|" and "-" and " " in some clever way
print(Tile.get_character())
if i % 5 == 0: # if we have just made a sixth tile, we should begin next row
print("\n") # begin a new row
def main():
BattleMap = setup()
while not wanting to quit:
some if statements to navigate between options
when you shoot:
print("What coordinates do you want to shoot at?")
x = input("x: ")
y = input("y: ")
tile_index = x + n*y
if BattleMap[tile_index].shoot() == True:
HITS += 1
else:
BOOMS += 0
update(BattleMap)
|
4b99c54daf8a88d2f1b7d612de255bd7900baeee | SuperN8er/MMM | /median.py | 689 | 4.03125 | 4 | """Module for working with median"""
from rand_data import get_rand_nums
def calc_median(nums):
"""Calculate the mean, given a list of numbers"""
sorted_nums = sorted(nums)
print(sorted_nums)
length = len(sorted_nums)
midpoint = length // 2
if (length % 2) == 1:
# odd
median = sorted_nums[midpoint]
else:
# even
lower_median = sorted_nums[midpoint-1]
upper_median = sorted_nums[midpoint]
median = (lower_median + upper_median) / 2
return median
def main():
# nums = get_rand_nums(9)
nums = get_rand_nums(10)
print(nums)
print(calc_median(nums))
if __name__ == "__main__":
main()
|
2ca54deca377673e4503cfff0a5a3859d3cdff28 | netraan/star-python | /star_turtleramdom.py | 738 | 3.765625 | 4 | import turtle
import time
import random
start = time.time()
#init
t=turtle.Turtle()
t.hideturtle()
# number of points
n = random.randrange(3,10) # number of points
RT = random.randrange(1,200) # deg right turn
L = random.randrange(10,100) # line length
dL = random.randrange(10,100)
LT = RT-360/n
#print parameters
print('n={}'.format(n))
print('RT={}'.format(RT))
print('L={}'.format(L))
print('DL={}'.format(dL))
print('LT={}'.format(LT))
#draw square
for i in range(n):
t.forward(L-dL/2)
t.right(RT)
t.forward(L+dL/2)
t.left(LT)
stop=time.time()
elapsed = stop-start
#print(elapsed)
time_obj = time.gmtime(elapsed)
date_str = time.strftime("%H:%M:%S", time_obj)
print(date_str)
#keep window open
turtle.done()
|
f36812817952c945fab0a069bef59c400a0f7abc | Bairdotr/Development | /auth.py | 4,843 | 3.875 | 4 |
# register
# - first name, last name, password, email
# - generate user account number
# login
# - account number & password
# bank operations
# Initializing the system
import random
import validation
import database
from getpass import getpass
def init():
print("Welcome to bankPHP")
have_account = int(input("Do you have account with us: 1 (yes) 2 (no) \n"))
if have_account == 1:
login()
elif have_account == 2:
register()
else:
print("You have selected invalid option")
init()
def login():
print("********* Login ***********")
account_number_from_user = input("What is your account number? \n")
is_valid_account_number = validation.account_number_validation(account_number_from_user)
if is_valid_account_number:
password = input("What is your password \n")
user = database.authenticated_user(account_number_from_user, password)
if user:
print(user)
print("in login")
database.create_auth_session_file(account_number_from_user, user)
bank_operation(account_number_from_user, user)
#database.create_auth_session_file(account_number_from_user, user)
#apparently putting this line of code never created the auth session file and never prints finish login
print("finish login")
print('Invalid account or password')
login()
else:
print("Account Number Invalid: check that you have up to 10 digits and only integers")
init()
def register():
print("****** Register *******")
email = input("What is your email address? \n")
first_name = input("What is your first name? \n")
last_name = input("What is your last name? \n")
password = input("Create a password for yourself \n")
account_number = generation_account_number()
is_user_created = database.create(account_number, first_name, last_name, email, password)
if is_user_created:
print("Your Account Has been created")
print(" == ==== ====== ===== ===")
print("Your account number is: %d" % account_number)
print("Make sure you keep it safe")
print(" == ==== ====== ===== ===")
login()
else:
print("Something went wrong, please try again")
register()
def bank_operation(account_number, user):
print("Welcome %s %s " % (user[0], user[1]))
#print(user)
selected_option = int(input("What would you like to do? (1) deposit (2) withdrawal (3) Logout (4) Exit \n"))
if selected_option == 1:
deposit_operation(account_number, user)
elif selected_option == 2:
withdrawal_operation(account_number, user)
elif selected_option == 3:
logout(account_number)
elif selected_option == 4:
exit()
else:
print("Invalid option selected")
bank_operation(account_number, user)
def withdrawal_operation(account_number, user):
print("Withdrawal, your current balance is " + get_current_balance(user))
withdrawl = int(input("How much would you like to withdraw? \n"))
if withdrawl > int(get_current_balance(user)):
print("Must withdrwawl an amount less than " + get_current_balance(user) + "\n")
withdrawal_operation(account_number, user)
else:
set_current_balance(user, str(int(get_current_balance(user))-withdrawl))
database.update(account_number, user)
print("Your current balance is " + get_current_balance(user))
bank_operation(account_number, user)
# get current balance
# get amount to withdraw
# check if current balance > withdraw balance
# deduct withdrawn amount form current balance
# display current balance
def deposit_operation(account_number, user):
print("Deposit Operations: You're current balance is " + get_current_balance(user))
deposit = int(input("How much would you like to deposit?\n"))
balance = int(get_current_balance(user))
balance += deposit
set_current_balance(user, str(balance))
print("Current balance is " + get_current_balance(user) + "\n")
print("***")
database.update(account_number,user)
bank_operation(account_number, user)
# get current balance
# get amount to deposit
# add deposited amount to current balance
# display current balance
def generation_account_number():
return random.randrange(1111111111, 9999999999)
def set_current_balance(user_details, balance):
user_details[4] = balance
def get_current_balance(user_details):
return user_details[4]
def logout(account_number):
database.delete_auth_session(account_number)
login()
init()
|
c08e6a357ee5cd58f4a171dc81b001df5a8f487a | rPuH4/pythonintask | /INBa/2015/Serdehnaya_A_M/task_5_25.py | 1,494 | 4.25 | 4 | # Задача 5. Вариант 28.
# Напишите программу, которая бы при запуске случайным образом отображала название одной из пятнадцати республик, входящих в состав СССР.
# Serdehnaya A.M.
# 25.04.2016
import random
print ("Программа случчайным образом отображает название одной из пятнадцати республик, входящих в состав СССР.")
x = int (random.randint(1,15))
print ('\nОдна из Республик - ', end = '')
if x == 1:
print ('РСФСР')
elif x == 2:
print ('Украинская ССР')
elif x == 3:
print ('Белорусская ССР')
elif x == 4:
print ('Узбекская ССР')
elif x == 5:
print ('Казахская ССР')
elif x == 6:
print ('Грузинская ССР')
elif x == 7:
print ('Азербайджанская ССР')
elif x == 8:
print ('Литовская ССР')
elif x == 9:
print ('Молдавская ССР')
elif x == 10:
print ('Латвийская ССР')
elif x == 11:
print ('Киргизская ССР')
elif x == 12:
print ('Таджикская ССР')
elif x == 13:
print ('Армянская ССР')
elif x == 14:
print ('Туркменская ССР')
else:
print ('Эстонская ССР')
input("\nДля выхода нажмите Enter.") |
7f6cb8a9c235dd399d270576726824353ed5af7e | ThomasBrouwer/project_euler | /problem_34.py | 336 | 4.03125 | 4 | def factorial(n):
result = 1
while n > 1:
result *= n
n -= 1
return result
def sum_factorial_of_digits(n):
digits = str(n)
return sum([factorial(long(char)) for char in digits])
curious_numbers = []
for i in xrange(3,factorial(9)*9):
if i == sum_factorial_of_digits(i):
curious_numbers.append(i)
print sum(curious_numbers) |
f63b7915ae8b9778ceeccc99e377065f609a8efe | ThomasBrouwer/project_euler | /problem_10.py | 524 | 3.546875 | 4 | def find_next_prime(values,start,length):
for v in range(start,length):
if values[v] != 0:
return v
return -1
# We mark values by 0 if they are marked off
max_value = 2000000
primes = [1] # little hack
values = range(0,max_value+1)
values[1] = 0
# Use sieve of Eratosthenes
while True:
next_prime = find_next_prime(values,primes[-1]+1,max_value)
if next_prime == -1:
break
primes.append(next_prime)
print next_prime
i = next_prime
while i <= max_value:
values[i] = 0
i += next_prime
print sum(primes)-1 |
1af2a3e8831f99c842cefccdfec0dad506020c94 | ThomasBrouwer/project_euler | /problem_18.py | 946 | 3.578125 | 4 | triangle = \
"""75
95 64
17 47 82
18 35 87 10
20 04 82 47 65
19 01 23 75 03 34
88 02 77 73 07 63 67
99 65 04 28 06 16 70 92
41 41 26 56 83 40 80 70 33
41 48 72 33 47 32 37 16 94 29
53 71 44 65 25 43 91 52 97 51 14
70 11 33 28 77 73 17 78 39 68 17 57
91 71 52 38 17 14 91 43 58 50 27 29 48
63 66 04 68 89 53 67 30 73 16 69 87 40 31
04 62 98 27 23 09 70 98 73 93 38 53 60 04 23"""
def higher_val(a,b):
return a if a > b else b
def find_max_path(layers):
# We go bottom up, adding the highest of each two values next
# to each other to the parent, until we reach the top
for i in reversed(range(0,len(layers)-1)):
layer = layers[i]
layer_below = layers[i+1]
for j in range(0,len(layer)):
layer[j] += higher_val(layer_below[j],layer_below[j+1])
return layers[0][0]
layers = triangle.split("\n")
layers = [values.split() for values in layers]
layers = [
[int(val) for val in layer]
for layer in layers
]
print find_max_path(layers) |
0f0d02cc5888cd6871a57557b9588e56031f37be | ThomasBrouwer/project_euler | /problem_50.py | 1,211 | 3.640625 | 4 | import math
from collections import deque
def is_prime(n):
for i in xrange(2,long(math.sqrt(n))+1):
if n % i == 0:
return False
return True
def find_no_consecutive_terms(value,primes,best_so_far):
selected_primes = deque([])
sum_selection = 0
length_selected = 0
for prime in primes:
selected_primes.append(prime)
sum_selection += prime
length_selected += 1
# If the selection is greater than value, and we already have less
# consecutive primes than the best so far, we can stop
if sum_selection > value and length_selected < best_so_far:
return -1
while sum_selection > value:
removed_prime = selected_primes.popleft()
sum_selection -= removed_prime
length_selected -= 1
if sum_selection == value:
return len(selected_primes)
return -1
max_prime = 1000000
longest_sum_prime = 0
no_terms_longest_sum_prime = 0
primes = []
for val in xrange(2,max_prime+1):
if is_prime(val):
no_prime_terms = find_no_consecutive_terms(val,primes,no_terms_longest_sum_prime)
if no_prime_terms > no_terms_longest_sum_prime:
no_terms_longest_sum_prime = no_prime_terms
longest_sum_prime = val
primes.append(val)
print no_terms_longest_sum_prime,longest_sum_prime |
ff91fe7350f4ffa0662b186a62708101dfb8e0a6 | ThomasBrouwer/project_euler | /problem_31.py | 703 | 3.890625 | 4 | def greedy_fill(coin,money_left,stack):
while coin <= money_left:
stack.append(coin)
money_left -= coin
return money_left
def coins_lower_than(coins,value):
return [coin for coin in coins if coin < value]
coins = [1,2,5,10,20,50,100,200]
coins_left = coins[:]
stack = []
money_left = 200
number_ways = 0
while True:
if money_left == 0:
number_ways += 1
coin_popped = stack.pop()
money_left += coin_popped
else:
if not coins_left:
if not stack:
break
else:
coin_popped = stack.pop()
money_left += coin_popped
coins_left = coins_lower_than(coins,coin_popped)
else:
coin = coins_left.pop()
money_left = greedy_fill(coin,money_left,stack)
print number_ways |
bbeda9d0c0021a86fffa083afebc231058a65596 | rixwoodling/betelnuts | /hsinchu.py | 531 | 3.671875 | 4 | #!/usr/bin/python3
from time import sleep
import piglow
import random
piglow.auto_update = True
piglow.all( 0 )
def colorful_raindrops():
count = 0
leds = list(range( 0,18 ))
random.shuffle( leds )
while ( count < 3 ):
for i in leds:
piglow.led( i, 100 )
sleep( 0.1 )
random.shuffle( leds )
for i in leds:
piglow.led( i, 0 )
sleep( 0.1 )
count += 1
if __name__ == '__main__':
while True:
colorful_raindrops()
#
|
fe090069d1ceb7fda31264a723f18bd67d48842a | jocarmp08/Tutoria-IC1802 | /Semana #7/2016106261_Examen01.py | 8,283 | 4.0625 | 4 | '''
Examen I de Introducción a la programación
Estudiante: José Carlos Montoya Pichardo
Carné: 2016106261
'''
# =========================Función sumatoria_pares=============================
'''
Esta función permite sumar los números que se encuentran dentro de un rango
definido, basado en su valor par o impar.
Entradas: Números enteros y positivos. Además de un booleano que determina
si se trabaja con pares o impares.
Salida: Sumatoria de los números definidos.
Limitaciones: No se puede utilizar datos de valor flotante o cadena de texto.
'''
# Sumatoria para valor de verdad True
def funcion_pares(inicio, final):
'''
Se realiza la sumatoria utilizando solamente los números pares que se
encuentran dentro del rango definido.
'''
if inicio > final:
return 0
else:
pares = inicio % 2
if pares == 0:
return inicio + funcion_pares(inicio + 2, final)
else:
return funcion_pares(inicio + 1, final)
# Sumatoria para valor de verdad False
def funcion_impares(inicio, final):
'''
Se realiza la sumatoria utilizando solamente los números impares que se
encuentran dentro del rango definido.
'''
if inicio > final:
return 0
else:
impar = inicio % 2
if impar == 0:
return funcion_impares(inicio + 1, final)
else:
return inicio + funcion_impares(inicio + 2, final)
# Decisión basada en valor de verdad
def funcion_sumatoriaaux(inicio, final, pares):
'''
El valor de verdad de pares determina la función a utilizar para terminar
el proceso solicitado.
'''
if pares == True:
return funcion_pares(inicio, final)
else:
return funcion_impares(inicio, final)
# Validación de argumentos
def sumatoria_pares(inicio, final, pares):
'''
Se comprueba que inicio y final sean argumentos positivos y enteros, que
inicio sea menor a final y que pares tenga valor booleano.
'''
if type(inicio) == int and type(final) == int:
if inicio < 0 or final < 0:
return "Error02"
else:
if inicio > final:
return "Error02"
else:
if pares == True or pares == False:
return funcion_sumatoriaaux(inicio, final, pares)
else:
return "Error03"
else:
return "Error01"
# Ejecución inicial
sumatoria_pares(inicio, final, pares)
# =============================================================================
# ===========================Función quita_ceros===============================
'''
Esta función permite remover los ceros adicionales de los números dados.
Entradas: Números enteros y positivos, de al menos 6 digitos.
Salida: Un número de 6 digitos que no contiene ceros.
Limitaciones: No se puede utilizar datos de valor flotante o cadena de texto.
Además, los números de entrada deben ser de 6 digitos o más.
'''
# Eliminación de ceros y composición del nuevo número
def funcion_nozero(numero, potencia):
'''
Se compone un nuevo número, basado en el número de entrada, que no contiene
ceros para ser retornado para su valoración.
'''
if numero == 0:
return 0
else:
lastdigit = numero % 10
if lastdigit == 0:
return funcion_nozero(numero // 10, potencia)
else:
return lastdigit * (10 ** potencia) + funcion_nozero(numero // 10,
potencia + 1)
# Validación del nuevo número (sin ceros)
def funcion_digiseis(numero):
'''
Se cuenta la cantidad de dígitos del nuevo número formado. Para ello, antes
se debe obtener ese número mediante el llamado a funcion_nozero(argumento)
'''
digitos = funcion_nozero(numero, 0)
if digitos < 100000:
return "Error03"
else:
return digitos
# Validación de argumentos
def quita_ceros(numero):
'''
Se comprueba que numero sea un número entero positivo y entero, de al menos
6 digitos.
'''
if type(numero) == int:
if numero == 0:
return "Error03"
elif numero > 99999:
return funcion_digiseis(numero)
else:
'''
Se acordó este error al inicio del examen, sin embargo el ejemplo
muestra "Error03"
'''
return "Error02"
else:
return "Error01"
# Ejecución inicial
'''
Si los números comienzan con 0, se trata de un octal, lo cual muestra error
al ejecutar.
'''
quita_ceros(numero)
# =============================================================================
# ===========================Función palindromo================================
'''
Esta función valora si un número posee propiedad de palindromo.
Entradas: Números enteros y positivos.
Salida: Un valor de verdad (True para palindromo, False para no palindromo)
Limitaciones: No se puede utilizar datos de valor flotante o cadena de texto.
Los números deben ser naturales incluyendo 0.
'''
# Función que retorna la cantidad de digitos de un número
def cuentadigitos(numero):
'''
Se cuentan los digitos de un número mediante división entera
'''
if numero == 0:
return 0
else:
return 1 + cuentadigitos(numero // 10)
# Recomponer el número
def palindromo_final(numero, potencia):
'''
Se recompone el número utilizando operaciones de base 10.
'''
if numero == 0:
return 0
else:
lastdigit = numero % 10
return lastdigit * (10 ** potencia) + palindromo_final(numero // 10,
potencia - 1)
# Se comprueba la existencia del palindromo
def palindromoaux(numero):
'''
Se compara al nuevo número con el número original. Esto devuelve un valor
de verdad
'''
potencia = cuentadigitos(numero) - 1
nuevonum = palindromo_final(numero, potencia)
if nuevonum == numero:
return True
else:
return False
# Validación de argumentos
def palindromo(numero):
'''
Se comprueba que número sea un número entero positivo
'''
if type(numero) == int:
if numero < 0:
return "Error01"
elif numero == 0:
return True
else:
return palindromoaux(numero)
else:
return "Error01"
# Ejecución inicial
palindromo(numero)
# =============================================================================
# =========================Modificación de código==============================
'''
Esta función devuelve el valor del digito que se encuentra en una posición
determinada
Entradas: Números enteros y positivos.
Salida: Número que representa al digito de la posición señalada
Limitaciones: No se puede utilizar datos de valor flotante o cadena de texto.
La posición debe ser menor a la cantidad de digitos de un número, comenzando a
contar desde 0, derecha a izquierda
'''
# Función que retorna la cantidad de digitos de un número
def cuentadigitos2(numero):
'''
Se cuentan los digitos de un número mediante división entera
'''
if numero == 0:
return 0
else:
return 1 + cuentadigitos2(numero // 10)
# Descomposición y retorno
def retornardigitoaux(posicion, numero):
'''
Se descompone el número original hasta obtener el valor del digito señalado
por el usuario (posicion)
'''
if posicion == 0:
return numero % 10
else:
return retornardigitoaux(posicion - 1, numero // 10)
# Valoración de argumentos
def retornardigito(posicion, numero):
'''
Se valida que los argumentos sean números enteros y positivos. Además,
posicion debe ser menor a la cantidad retornada por cuentadigitos2.
'''
if type(posicion) != int or type(numero) != int:
return "No son números enteros"
elif posicion > cuentadigitos2(numero):
return "La posición no existe en el número"
else:
return retornardigitoaux(posicion, numero)
# Ejecución inicial
retornardigito(posicion, numero)
# ============================================================================= |
ef43a75e51b3d92d10d3e67ad1db0549fce4afd1 | War10c3/AI_ML-Assignment | /assign7.py | 486 | 3.765625 | 4 | #ques 1
a=eval(input('enter dictionary'))
b=int(input('enter the value'))
for k,v in a.items():
if b==v:
break
print(k)
#ques 2
a={'sarthak':{'maths':30,'physics':30,'chem':90},'ronaldo':{'maths':90,'physics':50,'chem':10},'vipul':{'maths':78,'physics':30,'chem':60}}
b=str(input('enter name of student'))
for k,v in a.items():
if b==k:
print('maths=',a[k]['maths'])
print('physics=',a[k]['physics'])
print('chem=',a[k]['chem'])
|
9effe1afdc7532ae0535d09927626a6fdd586c28 | War10c3/AI_ML-Assignment | /assign9.py | 668 | 3.65625 | 4 | # ques 1
a=3
try:
if a<4:
a=a/(a-3)
except ZeroDivisionError:
print("this question has Zero division error")
print(a)
ques 2
l=[1,2,3]
try:
print(l[3])
except IndexError:
print("It shows index error\n")
print (l)
# ques 3
"""
OUTPUT = An Exception
NameError: Hi there
"""
# ques 4
"""
-5.0
a/b result in 0
"""
#ques 5
try:
a=int(input())
print(a)
except ValueError:
print("Enter desired input")
l=[1,2,3]
try:
print(l[3])
except IndexError:
print("It shows index error\n")
print (l)
try:
import abcdef
except ImportError as msg:
print(msg)
|
bbaf1dec6b370ba832181e6b33f6e0f18a8490fb | ElianEstrada/Cursos_Programacion | /Python/Ejercicios/ej-while/ej-14.py | 476 | 4.21875 | 4 | #continuar = input("Desea continuar? [S/N]: ")
continuar = "S"
while(continuar == "S"):
continuar = input("Desea continuar? [S/N]: ")
print("Gracias por usar mi sistema :)")
'''
con ciclo while
pedir al usuario una cantidad númerica a ahorrar
y luego que le pregunten a al usuario si desea agregar otra cantidad
si la respuesta es SI, pedir la cantidad y volver ha preguntar si quiere ingresar otra
y si la respuesta es NO mostrar el total ahorrado y salir.
''' |
ff9783b7f1e118bf72d8ee96b1dd858f67689337 | chipmunk360/hello_py | /number_guessing_game.py | 972 | 3.78125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Mar 25 22:29:02 2016
@author: pi
"""
import random
secret = random.randint ( 1, 20)
guess = 0
tries = 0
print "AHOY! i'm the Dread Pirate Roberts and I hae a secret!"
print " It is a number from 1 to 20. I'll give you 6 tries. "
while guess != secret and tries < 6:
guess = input ( 'whats yer guees')
#==============================================================================
# print "guess: %s secret: %s tries: %s" %(guess, secret, tries)
#==============================================================================
if guess < secret:
print" too low ye scurvy dog."
elif guess > secret:
print "too high landlubber!"
tries = tries + 1
if guess == secret:
'''they guessed correctly'''
print "Avast! Ye got it! Found my secret ye did!"
else:
print "No More guesses! Better luck next time, matey!"
print "The secret number was ", secret
|
f88b76619437517a26c8ab5510592227bd4f94a8 | chipmunk360/hello_py | /monkey_shakespeare.py | 4,087 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Mar 26 04:05:12 2016
@author: pi
"""
#===============================================================================
# Pyevolve version of the Infinite Monkey Theorem
# See: http://en.wikipedia.org/wiki/Infinite_monkey_theorem
# By Jelle Feringa
#===============================================================================
from pyevolve import G1DList
from pyevolve import GSimpleGA, Consts
from pyevolve import Selectors
from pyevolve import Initializators, Mutators, Crossovers
import math
sentence = """
'Just living is not enough,' said the butterfly,
'one must have sunshine, freedom, and a little flower.'
"""
#==============================================================================
# sentence = """
# 'To be or not to be, that is the question.'
# """
#
# sentence = """
# 'In this context, almost surely is a mathematical term with a precise meaning, and the monkey is not an actual monkey, but a metaphor for an abstract device that produces an endless random sequence of letters and symbols. One of the earliest instances of the use of the monkey metaphor is that of French mathematician Emile Borel in 1913,[1] but the first instance may be even earlier. The relevance of the theorem is questionable—the probability of a universe full of monkeys typing a complete work such as Shakespeare's Hamlet is so tiny that the chance of it occurring during a period of time hundreds of thousands of orders of magnitude longer than the age of the universe is extremely low (but technically not zero). It should also be noted that real monkeys do not produce uniformly random output, which means that an actual monkey hitting keys for an infinite amount of time has no statistical certainty of ever producing any given text.'
#==============================================================================
#"""
numeric_sentence = map(ord, sentence)
def evolve_callback(ga_engine):
generation = ga_engine.getCurrentGeneration()
if generation%50==0:
indiv = ga_engine.bestIndividual()
print ''.join(map(chr,indiv))
return False
def run_main():
genome = G1DList.G1DList(len(sentence))
genome.setParams(rangemin=min(numeric_sentence),
rangemax=max(numeric_sentence),
bestrawscore=0.00,
gauss_mu=1, gauss_sigma=4)
genome.initializator.set(Initializators.G1DListInitializatorInteger)
genome.mutator.set(Mutators.G1DListMutatorIntegerGaussian)
genome.evaluator.set(lambda genome: sum(
[abs(a-b) for a, b in zip(genome, numeric_sentence)]
))
ga = GSimpleGA.GSimpleGA(genome)
#ga.stepCallback.set(evolve_callback)
ga.setMinimax(Consts.minimaxType["minimize"])
ga.terminationCriteria.set(GSimpleGA.RawScoreCriteria)
ga.setPopulationSize(600)
ga.setMutationRate(0.02)
ga.setCrossoverRate(0.9)
ga.setGenerations(5000)
ga.evolve(freq_stats=1)
best = ga.bestIndividual()
print "Best individual score: %.2f" % (best.score,)
print ''.join(map(chr, best))
if __name__ == "__main__":
#run_main()
genome = G1DList.G1DList(len(sentence))
genome.setParams(rangemin=min(numeric_sentence),
rangemax=max(numeric_sentence),
bestrawscore=0.00,
gauss_mu=1, gauss_sigma=4)
genome.initializator.set(Initializators.G1DListInitializatorInteger)
genome.mutator.set(Mutators.G1DListMutatorIntegerGaussian)
genome.evaluator.set(lambda genome: sum(
[abs(a-b) for a, b in zip(genome, numeric_sentence)]
))
ga = GSimpleGA.GSimpleGA(genome)
#ga.stepCallback.set(evolve_callback)
ga.setMinimax(Consts.minimaxType["minimize"])
ga.terminationCriteria.set(GSimpleGA.RawScoreCriteria)
ga.setPopulationSize(60)
ga.setMutationRate(0.02)
ga.setCrossoverRate(0.9)
ga.setGenerations(5000)
ga.evolve(freq_stats=100)
best = ga.bestIndividual()
print "Best individual score: %.2f" % (best.score,)
print ''.join(map(chr, best)) |
2c12b700e72b2cd155a8dca90a3e2389106eed3f | koenigscode/python-introduction | /content/partials/comprehensions/list_comp_tern.py | 311 | 4.25 | 4 | # if the character is not a blank, add it to the list
# if it already is an uppercase character, leave it that way,
# otherwise make it one
l = [c if c.isupper() else c.upper()
for c in "This is some Text" if not c == " "]
print(l)
# join the list and put "" (nothing) between each item
print("".join(l))
|
d51b6c59a12f740e9c95f675a3d84fa98d608fb9 | koenigscode/python-introduction | /content/partials/basic_syntax/string_formatting_examples.py | 210 | 3.609375 | 4 | who = "I"
version = 3
print( who + " love Python " + str(version) )
print( "%s love Python %s" % (who, version) )
print( "{} love Python {}".format(who, version) )
print( f"{who} love Python {version}" ) |
d4cec66953d44684f1c17c6c76eaeb20c6d417ec | samgensburg/adventofcode | /2020/3b.py | 742 | 3.578125 | 4 | import re
def main(right, down):
with open('3.dat', 'r') as file:
y = 0
count = 0
fall = down - 1
for line in file:
fall += 1
if fall == down:
fall = 0
else:
continue
line = line.strip()
width = len(line)
if line[y] == '#':
count += 1
y = (y + right) % width
return count
print(main(1, 1))
print(main(3, 1))
print(main(5, 1))
print(main(7, 1))
print(main(1, 2))
|
0cdfc292b376b2666cf02479a3ee6224ef1bd7cc | samgensburg/adventofcode | /2021/02a.py | 331 | 3.53125 | 4 | def main():
with open('02.dat', 'r') as file:
x = 0
y = 0
for line in file:
parts = line.split()
value = int(parts[1])
if parts[0] == 'forward':
x += value
elif parts[0] == 'down':
y += value
elif parts[0] == 'up':
y -= value
else:
raise 'how did I get here?'
return x * y
print(main())
|
22e20f3364f8498766caf17e4dc8b967ef217f5b | BMariscal/MITx-6.00.1x | /MidtermExam/Problem_6.py | 815 | 4.28125 | 4 | # Problem 6
# 15.0/15.0 points (graded)
# Implement a function that meets the specifications below.
# def deep_reverse(L):
# """ assumes L is a list of lists whose elements are ints
# Mutates L such that it reverses its elements and also
# reverses the order of the int elements in every element of L.
# It does not return anything.
# """
# # Your code here
# For example, if L = [[1, 2], [3, 4], [5, 6, 7]] then deep_reverse(L) mutates L to be [[7, 6, 5], [4, 3], [2, 1]]
# Paste your entire function, including the definition, in the box below. Do not leave any debugging print statements.
def deep_reverse(L):
for i in L:
i.reverse()
L.reverse()
return L
# Test: run_code([[0, -1, 2, -3, 4, -5]])
# Output:
# [[-5, 4, -3, 2, -1, 0]]
# None
|
383473ada2e5332caee9ab02bd421b024fa1cf50 | OrmandyRony/initialPython | /PythonBasico/estructuras.py | 1,242 | 4.0625 | 4 | # -*- coding: utf-8 -*-
#Estructuras de control de flujo
#Asignación múltiple
a, b, c = 'string', 15, True
print (a)
print (b)
print (c)
# En una tupla
mi_tupla = ('Hello world', 2020)
texto, anio = mi_tupla
print (texto)
print (anio)
# En una lista
mi_lista = ['Argentina', 'Buenos Aires']
pais, provincia = mi_lista
print (pais)
print (provincia)
# Estructuras de control de flujo condicionales
compra = 99
if compra <= 100:
print("Pago en efectivo")
elif compra > 100 and compra < 300:
print ("Pago con tarjeta de debito")
else:
print ("Pago con tarjeta de crédito")
# Estructuras de control iterativas
#Bucle while
anio = 2001
while anio <= 2012:
print("Informes del Año", str(anio))
anio += 1
"""
while True:
nombre = input("Indique su nombre")
if nombre:
break
"""
# Bucle for
mi_lista = ['Juan', 'Antonio', 'Pedro', 'Dilan']
for nombre in mi_lista:
print (nombre)
print()
mi_tupla = ('rosa', 'verde', 'amarillo')
for color in mi_tupla:
print (color)
for anio in range(2001, 2013):
print (anio)
for number in range(1, 11):
print(number)
for i in [0, 1, 2]:
print("cough")
for i in range(3):
for j in range(3):
print("#", end="")
print() |
fd87f0b66dc286e83c64e7500d5d391a7d86677d | OrmandyRony/initialPython | /ExercisePython/degreeConverter.py | 349 | 4.09375 | 4 | """ Escribe un programa que le pida al usuario una temperatura
en grados Celsius, la convierta a grados Fahrenheit e imprima
por pantalla la temperatura convertida. """
print("Convertidor de grados celcius a fahrenheit")
celcius = float(input("Ingrese los grados celcius: "))
fahrenheit = (celcius * 9/5) + 32
print("Grados farenheit: ", fahrenheit) |
85af22591e1b052ff672eafa626d6b30fd716853 | kyj0101/python_coding_test | /codeup/기초100/6064.py | 120 | 3.859375 | 4 | a,b,c = input().split()
a = int(a)
b = int(b)
c = int(c)
print(a if a < b and a < c else (b if b < a and b < c else c)) |
9c7beb4090f3aad39d66c3fe54fd656c374f1af6 | kyj0101/python_coding_test | /codeup/기초100/6078.py | 82 | 3.6875 | 4 | char = input()
while char != 'q':
print(char)
char = input()
print(char) |
73e4c51440c5d6da38f297556843c0173f0153ee | alexhong33/PythonDemo | /PythonDemo/Day01/01print.py | 1,140 | 4.375 | 4 | #book ex1-3
print ('Hello World')
print ("Hello Again")
print ('I like typing this.')
print ('This is fun.')
print ('Yay! Printing.')
print ("I'd much rather you 'not'.")
print ('I "said" do not touch this.')
print ('你好!')
#print ('#1')
# A comment, this is so you can read your program later.
# Anything after this # is ignored by python
print("I could have code like this.") # and the comment after is ignored
# You can also use a comment to "disable" or comment out a piece of code:
# print "This won't run."
print("This will run.")
# this is the first Comment
spam = 1 # and this is the second Comment
# ... and now a third!
text = " # This is not a comment because it's inside quotes."
print (2 + 2)
print (50 - 5 * 6)
print ((50 - 5 * 6) / 4)
print (8/5) #division always returns a floating point number
print (8//5) #获得整数
print (8%5) #获得余数
print (5 * 3 + 2)
print (5 ** 2) #5 squared
print (2 ** 8)
print (2.5 * 4 / 5.0)
print(7.0/2) #python完全支持浮点数, 不同类型的操作数混在一起时, 操作符会把整型转化为浮点型
|
8fe5c8e513e65e92210c9b0cc3cb1ae38c4d6532 | yanuar-nc/python-lesson | /oop/vehicle/car.py | 642 | 3.546875 | 4 | from . import Vehicle
class Car(Vehicle):
brands = {
'BMW': {'price': '$40,000', 'speed': '1000cc'},
'LAMBO': {'price': '$50,000', 'speed': '1100cc'},
'CIVIC': {'price': '$60,000', 'speed': '400cc'},
'FERARI': {'price': '$80,000', 'speed': '2000cc'}
}
def get_price(self):
if self._check_brand(self.brands) is False:
return self.get_error_message()
brand = self.brands[self.brand]
if self.color not in brand['colors']:
return "Unfortunely, the color \"" + self.color + "\" is empty"
return brand['price']
def how_fast(self):
if self.__check_brand() is False:
return self.get_error_message()
|
50dfeab0a39678d5713d49e59c86079d2d16faa6 | Choewonyeong/FireSafery-Schedule | /method/dateList.py | 1,149 | 3.59375 | 4 | from datetime import datetime
from datetime import date
from pandas import Timedelta
def __returnDate__(year, month, day):
weekend = ['(월)', '(화)', '(수)', '(목)', '(금)', '(토)', '(일)']
idx = date(year, month, day).weekday()
return weekend[idx]
def __returnDayCount__(year, month):
if month == 12:
current_month = datetime(year, month, 1, 0, 0, 0)
next_month = datetime(year + 1, 1, 1, 0, 0, 0)
days = Timedelta(next_month - current_month).days
else:
current_month = datetime(year, month, 1, 0, 0, 0)
next_month = datetime(year, month + 1, 1, 0, 0, 0)
days = Timedelta(next_month - current_month).days
return days
def returnDateList(year):
year = int(year)
dateList = []
for month in range(1, 13):
days = __returnDayCount__(year, month) + 1
for day in range(1, days):
textMonth = f"0{month}" if month < 10 else f"{month}"
textDay = f"0{day}" if day < 10 else f"{day}"
textDate = __returnDate__(year, month, day)
dateList.append(f"{textMonth}/{textDay}{textDate}")
return dateList
|
e5bf45c4b1461958b53df754af879bd9b7aedef1 | johanarangel/variables_python | /ejercicios_practica.py | 7,607 | 4.3125 | 4 | #!/usr/bin/env python
'''
Tipos de variables [Python]
Ejercicios de práctica
---------------------------
Autor: Johana Rangel
Version: 1.3
Descripcion:
Programa creado para que practiquen los conocimietos
adquiridos durante la semana
'''
__author__ = "johana Rangel"
__email__ = "johanarang@hotmail.com"
__version__ = "1.3"
def ej1():
# Ejercicios de práctica con números
print('Nuestra primera calculadora')
'''
Realice un calculadora, se ingresará por línea de comando dos
números reales y se deberá calcular todas las operaciones entre ellos:
- Suma
- Resta
- Multiplicación
- División
- Exponente/Potencia
- Para todos los casos se debe imprimir en pantalla el resultado aclarando
la operación realizada en cada caso y con que números
se ha realizado la operación
ej: La suma entre 4.2 y 6.5 es 10.7
'''
numero_1= float(input('Ingrese el primer número real: '))
numero_2= float(input('Ingrese el segundo número real: '))
suma= numero_1 + numero_2
print('La suma entre %.2f y %.2f es %.2f' % (numero_1, numero_2, suma))
resta= numero_1 - numero_2
print('La resta entre %.2f y %.2f es %.2f' % (numero_1, numero_2, resta))
mutiplicacion= numero_1 * numero_2
print('La multiplicación entre %.2f y %.2f es %.2f' % (numero_1, numero_2, mutiplicacion))
division= numero_1 / numero_2
print('La division entre %.2f y %.2f es %.2f' % (numero_1, numero_2, division))
potencia= numero_1 ** numero_2
print('La potencia de %.2f y %.2f es %.2f' % (numero_1, numero_2, potencia))
def ej2():
print('Ejercicios de práctica numérica y cadenas')
'''
Realice un programa que consulte por consola:
- El nombre completo de la persona
- El DNI de la persona
- La edad de la persona
- La altura de la persona
Finalmente el programa debe imprimir dos líneas de texto por separado
- En una línea imprimir el nombre completo y el DNI, aclarando de que
campo se trata cada uno
Ej: Nombre Completo: Nombre Apellido , DNI:35205070,
- En la segunda línea se debe imprimir el nombre completo, edad y
altura de la persona
Nuevamente debe aclarar el campo de cada uno, para el que lo lea
entienda de que se está hablando.
'''
nombre_completo= str(input('Ingrese nombre y apellido completo: '))
dni= int(input('Ingrese su numero de DNI: '))
edad= int(input('Ingrese su edad: '))
altura= float(input('Ingrese su altura en metros, separado por punto: '))
print('Nombre Completo: %s, DNI: %d' %(nombre_completo, dni))
print('Nombre Completo: %s, Edad: %d, Altura: %.2f metros' %(nombre_completo, edad, altura))
def ej3():
print('Ejercicios de práctica con cadenas')
'''
Realice un programa que determine cual sería el apellido de una persona
si se ingresaran los dos nombres completos de sus padres.
Dicha persona deberá tener los apellidos de ambos padres
- Primero el programa debe consultar el nombre completo del padre_1
- Luego el programa debe consultar el nombre completo del padre_2
- Luego debe consultar el nombre del hijo/a
- Debe extraer los apellidos de los padres
- Luego formar el nombre completo del hijo/a utilizando los apellidos
de sus padres
y el nombre ingresado de dicha persona
- Imprimir en pantalla el resultado
NOTA: Para extraer el apellido del nombre completo recomendamos usar
el método "split"
Mostraremos un ejemplo:
direccion_completa = 'Monroe 2716'
calle, altura = direccion_completa.split(' ')
Les dejo por su cuenta a que busquen un poco más acerca de este método
que seguramente utilizarán mucho de acá en adelante.
Les dejamos un link con algunos ejemplos más:
https://www.pythonforbeginners.com/dictionary/python-split
Cualquier duda con el método split pueden consultarla por el campus
'''
nombre_completoPadre_1= str(input('Ingrese primer nombre y primer apellido del primer padre:'))
nombrePadre_1, apellidoPadre_1= nombre_completoPadre_1.split(' ')
nombre_completoPadre_2= str(input('Ingrese primer nombre y primer apellido del segundo padre:'))
nombrePadre_2, apellidoPadre_2= nombre_completoPadre_2.split(' ')
nombre_hijo= str(input('Ingrese nombre del hijo:'))
print('El nombre completo del hijo es: %s %s %s,' %(nombre_hijo, apellidoPadre_1, apellidoPadre_2))
def ej4():
# Ejercicios de práctica con cadenas
print('Comencemos a ponernos serios')
'''
Realice un programa que determine si una persona_2
es pariente de la persona_1
Para facilitar el ejercicio solo ingresar un nombre
y un apellido por persona
Ingresar dichos datos como Nombre Apellido, es decir,
primero el nombre y luego el apellido, separado por un espacio.
- El programa debe consultar primero el nombre completo de la persona_1
- Luego debe consultar el nombre completo de la persona_2
- Debe extraer el apellido de la persona_2
- Luego preguntar si apellido de la persona_2 está contenido
en el nombre completo de la persona_1
- En caso de contenerlo, son parientes
- Imprimir en pantalla el resultado
NOTA: Para extraer el apellido del nombre recomendamos
usar el método "split"
Mostraremos un ejemplo:
direccion_completa = 'Monroe 2716'
calle, altura = direccion_completa.split(' ')
Les dejo por su cuenta a que busquen un poco más acerca
de este método que seguramente utilizarán mucho de acá en adelante.
Les dejamos un link con algunos ejemplos más:
https://www.pythonforbeginners.com/dictionary/python-split
Cualquier duda con el método split pueden consultarla por el campus
'''
nombreCompleto_persona_1= str(input('Ingrese primer nombre y primer apellido de la persona 1:'))
nombreLista_persona_1= nombreCompleto_persona_1.split(' ')
nombreCompleto_persona_2= str(input('Ingrese primer nombre y primer apellido de la persona 2:'))
nomPersona_2, apePersona_2= nombreCompleto_persona_2.split(' ')
esPariente_persona_1= apePersona_2 in nombreLista_persona_1
print(nombreCompleto_persona_2, 'es pariente de', nombreCompleto_persona_1, esPariente_persona_1)
def ej5():
# Ejercicios de práctica con cadenas
print('Ahora si! buena suerte!')
'''
Realice un programa que reciba por consola su nombre completo
e imprima en pantalla su nombre en los siguientes formatos:
- Todas las letras en minúsculas
- Todas las letras en mayúsculas
- Solo la primera letra del nombre en mayúscula
NOTA: Para realizar este ejercicio deberá usar los siguientes métodos
de strings:
- lower
- upper
- capitalize
Puede buscar en internet como usar en Python estos métodos.
Les dejamos el siguiente link que posee casos de uso de algunos de ellos:
Link de referencia:
https://www.geeksforgeeks.org/isupper-islower-lower-upper-python-applications/
Cualquier duda con estos métodos pueden consultarla por el campus
'''
nombreCompleto= str(input('Ingrese su nombe completo:'))
print(nombreCompleto.lower())
print(nombreCompleto.upper())
print(nombreCompleto.capitalize())
if __name__ == '__main__':
print("Ejercicios de práctica")
ej1()
ej2()
ej3()
ej4()
ej5()
|
b0280148b992b2069dc7608da4f84df75ef91dcd | anvartdinovtimurlinux/ADPY-12 | /2.7/stack.py | 350 | 3.546875 | 4 | class Stack:
def __init__(self):
self._storage = []
def is_empty(self):
return bool(self._storage)
def push(self, item):
self._storage.append(item)
def pop(self):
return self._storage.pop()
def peek(self):
return self._storage[-1]
def size(self):
return len(self._storage)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.