blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
b3732c55bf3cc794fda7811b88558f7e6672b6f8 | anthonyndunguwanja/Anthony-Ndungu-bootcamp-17 | /Day 2/Data_Types_Lab .py | 396 | 3.984375 | 4 | def data_type(x):
if type(x) is int:
if x < 100:
print('less than 100')
elif x == 100:
print('equal to 100')
else:
print('more than 100')
elif type(x) is None:
print('no value')
elif type(x) is bool:
print(bool(x))
elif type(x) is str:
print(len(x))
elif type(x) is list:
if not x:
print("None")
else:
print(x[2])
|
5a60dade00c99a357b0f5982e3d8703abd349b11 | Colin0523/Ruby | /Ruby/ExamStatistics.py | 909 | 4 | 4 | grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5]
def print_grades(grades):
for grade in grades:
print grade
print_grades(grades)
grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5]
o = [6,5]
def grades_sum(scores):
total = sum(scores)
return total
print grades_sum(grades)
def grades_average(grades):
total = grades_sum(grades)
aver = total/float(len(grades))
return aver
print grades_average(grades)
def grades_variance(scores):
average = grades_average(scores)
print 'average = ',average
variance = 0
for score in scores:
variance += float((average - score) ** 2)
total_variance = variance / float(len(scores))
return total_variance
print grades_variance(o)
def grades_std_deviation(variance):
return variance ** 0.5
variance = grades_variance(grades)
print grades_std_deviation(variance) |
8226c9d6879b166b22974e187a931bc2014df449 | MCVitzz/AED | /Deque.py | 415 | 3.5 | 4 | class Deque:
def __init__(self):
self.items = []
def add_front(self, item):
self.items.insert(0, item)
def add_rear(self, item):
self.items.append(item)
def pop_front(self):
return self.items.pop(0)
def pop_rear(self):
return self.items.pop()
def is_empty(self):
return self.size() == 0
def size(self):
return len(self.items) |
9b3b287203c988e80248808faa68a0cdcc41f67d | Sandeep-Ravula/code-22April2021-SandeepRavula | /BMI_analysis.py | 4,307 | 4.40625 | 4 | ## This is a Python code to give analysis results of BMI on the given JSON sample data-sets
from pprint import pprint
import json
#Below is the function to calculate and return the BMI of the sample based on the given height, weight along with the BMI category and Health-Risks
def bmi(gender,height,weight):
"""
This function will calculates the BMI rate of each sample and returns the output data
:param gender: indicates gender of the person to be BMI analysed
:param height: indicates height in metres
:param weight: indicates weight in kgs
:return: a tuple of gender,height,weight,bmi,bmi_category,health_risk
"""
bmi_index_limits = [18.4, 24.9, 29.9, 34.9, 39.9, 40.0]
bmi_categories = ["Underweight", "Normal weight", "Overweight", "Moderately obese", "Severely obese", "Very severely obese"]
health_risk = ["Malnutrition risk", "Low risk", "Enhanced risk", "Medium risk", "High risk", "Very high risk"]
#Below is the mathematical formula for calculating BMI value
bmi_value = round(weight/(height**2), 2) ## BMI formula : BMI(kg/m**2) = mass(kg) / height(m**2)
bmi_in_units = str(bmi_value) + " kg/m2" ## concatenating the bmi value with units "kg/m**2"
height_in_units = str(height) + " m" ## concatenating the height value with units "m"
weight_in_units = str(weight) + " kg" ## concatenating the weight value with units "kg"
# Conditional loops for returning the respective output based on respective BMI value range limits
if bmi_value <= bmi_index_limits[0]:
return (gender, height_in_units, weight_in_units, bmi_in_units, bmi_categories[0], health_risk[0])
elif bmi_index_limits[0] < bmi_value <= bmi_index_limits[1]:
return (gender, height_in_units, weight_in_units, bmi_in_units, bmi_categories[1], health_risk[1])
elif bmi_index_limits[1] < bmi_value <= bmi_index_limits[2]:
return (gender, height_in_units, weight_in_units, bmi_in_units, bmi_categories[2], health_risk[2])
elif bmi_index_limits[2] < bmi_value <= bmi_index_limits[3]:
return (gender, height_in_units, weight_in_units, bmi_in_units, bmi_categories[3], health_risk[3])
elif bmi_index_limits[3] < bmi_value <= bmi_index_limits[4]:
return (gender, height_in_units, weight_in_units, bmi_in_units, bmi_categories[4], health_risk[4])
elif bmi_value >= bmi_index_limits[5]:
return (gender, height_in_units, weight_in_units, bmi_in_units, bmi_categories[5], health_risk[5])
## Below is the function to get the count of number of overweighted people among the given input samples
def get_Count_of_overWeight_ppl(consolidated_data):
"""
It will return the count of number of overweighted people among the given input samples
:param consolidated_data: (list)
:return: count_overweight (int)
"""
count_overweight = 0
for data in consolidated_data:
if data[4] == 'Overweight':
count_overweight += 1
return count_overweight
#Below is the main function of this entire code
def main(input_file):
"""
This is the main function to execute everthing
:param input_file: Input file containing given JSON data
"""
output_list = []
data_file = open(input_file, 'r')
json_data = json.load(data_file)
for bmi_data in json_data:
## Below we are calling the bmi function to get the required output
response = bmi(bmi_data['Gender'], bmi_data['HeightCm']/100, bmi_data['WeightKg'])
output_list.append(response)
print('\nBelow output are the data-sets in the format of [Gender, Height_in_metres. Weight, BMI value, BMI category, health-risks]:')
pprint(output_list)
count_overweight_ppl = get_Count_of_overWeight_ppl(output_list) ## Calling the get_Count_of_overWeight_ppl function
overweight_percent = count_overweight_ppl / len(output_list)*100
print('\nNOTE: In the above output, BMI values are rounded to 2 decimal places')
print('\ncount of overweight people is:', count_overweight_ppl)
print(f'\nMy observation: out of total BMI samples, {round(overweight_percent, 2)} % are overweighted\n')
## Below we are calling the main function
if __name__ == '__main__':
main('BMI_analysis_JSON_data.json')
|
19569f831e6fa6486f4df73d025801433cabfcba | anirudhpillai16/Python-Excercises | /Challenges/Excercise12.py | 352 | 4.21875 | 4 | # Write a program (function!) that takes a list and returns a new list that contains all the
# elements of the first list minus all the duplicates.
a = [1,2,6,7,1,4,3,1,8,2,8]
b = []
def remdup(a,b):
for i in a:
if i not in b:
b.append(i)
print "List after removing duplicate values is --> " + str(b)
remdup(a,b) |
62343b696e9aef4f8f92f57fb7bb3c096dca2292 | liudahuan0218/train-code | /6.py | 307 | 3.53125 | 4 | class A:
def __init__(self,a,b):
self.__a=a
self.__b=b
print('init')
def mydefault(self,*args):
print('default:',str(args[0]))
def __getattr__(self,name):
print('other fn:',name)
return self.mydefault
a=A(10,20)
a.fn1(33)
a.fn2('hello')
a.fn3(10)
|
156f877d6a54962cf50b4c9a09b59da628210901 | WenhaoChen0907/Python_Demo | /01_hellopython/hn_25_tuple02.py | 307 | 3.875 | 4 | # 格式字符串,格式化字符串后面的 () 本质上就是一个元组
info_tuple = ("小明", 18, 1.75)
print("%s 的年龄是 %d 身高是 %.2f" % info_tuple)
# 拓展:格式字符串可以拼接生成新的字符串
info_str = "%s 的年龄是 %d 身高是 %.2f" % info_tuple
print(info_str) |
2e8e9ede3967144e86b94da0a50bc5ff2c7a12eb | JCGilPose/Intro_Computing_David_Joyner | /exam_practice_6.py | 1,784 | 4.25 | 4 | #Write a function called are_anagrams. The function should
#have two parameters, a pair of strings. The function should
#return True if the strings are anagrams of one another,
#False if they are not.
#
#Two strings are considered anagrams if they have only the
#same letters, as well as the same count of each letter. For
#this problem, you should ignore spaces and capitalization.
#
#So, for us: "Elvis" and "Lives" would be considered
#anagrams. So would "Eleven plus two" and "Twelve plus one".
#
#Note that if one string can be made only out of the letters
#of another, but with duplicates, we do NOT consider them
#anagrams. For example, "Elvis" and "Live Viles" would not
#be anagrams.
#Write your function here!
def are_anagrams(string_1, string_2):
lower_1 = string_1.lower()
lower_2 = string_2.lower()
words_1 = lower_1.split(' ')
words_2 = lower_2.split(' ')
chars_1 = []
chars_2 = []
for word in words_1:
for i in range(len(word)):
chars_1.append(word[i])
for word in words_2:
for i in range(len(word)):
chars_2.append(word[i])
for i in chars_1:
if i in chars_2:
chars_2.remove(i)
if len(chars_2) == 0:
return True
return False
#Below are some lines of code that will test your function.
#You can change the value of the variable(s) to test your
#function with different inputs.
#
#If your function works correctly, this will originally
#print: True, False, True, False, each on their own line.
print(are_anagrams("Elvis", "Lives"))
print(are_anagrams("Elvis", "Live Viles"))
print(are_anagrams("Eleven plus two", "Twelve plus one"))
print(are_anagrams("Nine minus seven", "Five minus three"))
|
cae8cecb66010b90e237f87c1721061f0954e7c2 | Romario12c/COMP3608-2020 | /assignments/assignment1/solution.py | 1,775 | 3.546875 | 4 | import json
def check_valid(current_pairs):
taken_men = set()
for _, m in current_pairs:
if m in taken_men:
return False
taken_men.add(m)
return True
def solve_helper(preferences, current_pairs, current_index, num_women):
# see if we can progress (i.e. not at a deadend)
if not check_valid(current_pairs):
return False
# we hit a solution!
if current_index == num_women:
return True
current_preferences = preferences[current_index]
# iterate over possible actions
for possible_husband in current_preferences:
# take an action
current_pairs.append((current_index, possible_husband))
# see if this action takes us to a solution
if solve_helper(preferences, current_pairs, current_index + 1, num_women):
return True
# reach here only if we hit a deadend because of this action, so we undo it
current_pairs.pop(-1)
# we made a mistake higher up, we need to undo it
return False
def solve(preferences, num_women):
current_pairs = []
current_index = 0
solve_helper(preferences, current_pairs, current_index, num_women)
return current_pairs
def fix_preferences(preferences):
p1 = {}
for k, v in preferences.items():
p1[int(k)] = list(map(int, v))
return p1
def main():
with open('prefs.json') as fp:
content = json.load(fp)
preferences = fix_preferences(content['preferences'])
num_women = int(content['num_women'])
pairs = solve(preferences, num_women)
if not pairs:
print('No solution!')
else:
print('Solution found!')
print(pairs)
if __name__ == "__main__":
main()
|
792d13f5516577c8974a93fd856b45d2d6c4d0d2 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/224/users/4351/codes/1596_2049.py | 270 | 3.90625 | 4 | #colocamos a variavel dos numeros inteiros
x=int(input("valor de x"))
y=int(input("valor de y"))
#agora colocamos a variavel do que e pedido
dividendo=x
divisor=y
quociente=x//y
resto=x%y
#basta imprimir tudo
print(dividendo)
print(divisor)
print(quociente)
print(resto) |
1e90804e6b31310b1f4154201f05a827bcda6d85 | jearnest88/python | /multiply.py | 128 | 3.53125 | 4 | def multiply(a):
x = a * 5
return x
y = [2,4,10,16]
g = 0
while g < 4:
b = y[g]
result = multiply(b)
print result
g +=1
|
0c60fb2bc9325f01df7e6dbacaf081e8b0d413c9 | ntc-Felix/toolbox | /coding/writing_functions/dry.py | 1,467 | 3.78125 | 4 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from sklearn.model_selection import train_test_split
# Dont Repeat Yourself (DRY)
# At the first moment we have a function like this:
def load_and_plot(path):
"""
Load a data set and plot the first two principal components.
Args:
path (str): The location of a csv file.
Returns:
tuple of ndarray: (features, labels)
"""
# load the data
data = pd.read_csv(path)
y = data['label'].values
X = data[col for col in train.columns if col != 'label'].values
pca = PCA(n_components = 2).fit_transform(X)
plt.scatter(pca[:,0], pca[:,1])
return X,y
# Here we want to split this function
def load_data(path):
"""
Load a data set.
Args:
path(str): The location of a CSV file.
Returns:
tuple of ndarray: (features, labels)
"""
data = pd.read_csv(path)
y = data['labels'].values
X = data[col for col in data.columns if col!= 'labels'].values
return X,y
def plot_data(path):
"""
Plot the first two principal components of a matrix.
Args:
X (numpy.ndarray): The data to plot
"""
pca = PCA(n_components=2).fit_transform()
plt.scatter(pca[:,0], pca[:,1])
"""
Applying the steps to our code it becomes:
-More flexible
-More easily understood
-Simpler to test
-Simpler to debug
""" |
05f86c2229bdfec330de2e07b63502587aeea88d | dhk1349/Algorithm | /Algorithm Practice/leetcode_59.py | 1,490 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat May 8 23:33:06 2021
@author: dhk1349
"""
class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
condition=["right", "down", "left", "up"]# or left up down
mode=0
out=[]
cursor=[0, 0] # r, c
# though inefficient, make null matrix first.
for _ in range(n):
row=[]
for _ in range(n):
row.append(0)
out.append(row)
for i in range(n**2):
# print(f"{mode}: {cursor[0]}, {cursor[1]}-> {i+1}")
out[cursor[0]][cursor[1]] = i+1
if mode==0:
cursor[1]+=1
elif mode==1:
cursor[0]+=1
elif mode==2:
cursor[1]-=1
elif mode==3:
cursor[0]-=1
if -1>=cursor[0] or cursor[0] == n or -1>=cursor[1] or cursor[1] == n or out[cursor[0]][cursor[1]]!=0:
if mode==0:
cursor[1]-=1
cursor[0]+=1
elif mode==1:
cursor[0]-=1
cursor[1]-=1
elif mode==2:
cursor[1]+=1
cursor[0]-=1
elif mode==3:
cursor[0]+=1
cursor[1]+=1
mode+=1
mode%=4
# print(out)
return out
|
8b77d7564ecaf44693439b8958b57f193ceb6203 | tejasree0328/assignment5 | /qu1.py | 267 | 3.734375 | 4 | Python 3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:20:19) [MSC v.1925 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> import math
r=float(input("enter radius:"))
area=math.pi*r*r
print("area of circle:",area) |
787c196f86c764025fbeec81d9656ef82ba3ef85 | bobrayEden/python-katas | /fizzbuzz.py | 830 | 4.03125 | 4 | """
TIY-fizzbuzz
7 kyu fizzbuzz
"""
# Ma solution
def tiy_fizz_buzz(string):
result = ''
vowels = {'a', 'e', 'i', 'o', 'u'}
for c in string:
if (not c.isalpha() or
(c not in vowels and not c.isupper())
):
result += c
elif c.lower() in vowels and c.isupper():
result+= 'Iron Yard'
elif c in vowels:
result += 'Yard'
else:
result += 'Iron'
return result
# Solutions upvote
def tiy_fizz_buzz(string):
return ''.join(
'Iron Yard' if c in 'AEIOU' else
'Yard' if c in 'aeiou' else
'Iron' if c.isupper() else c
for c in string
)
def tiy_fizz_buzz(s):
return "".join(("Iron "*c.isupper() + "Yard"*(c.lower() in "aeiou")).strip() or c for c in s) |
d003f81f050b60be5fdd4543821aa7453c5a61d3 | ygorvieira/exerciciosPython | /ex013.py | 138 | 3.6875 | 4 | #Cálculo de acréscimo (15%)
s = float(input('Informe o salário: R$'))
print('O salário com aumento é R${:.2f}'.format(s + (s*0.15)))
|
2da37a3b82e945f06b77121618e264c12493430c | crocodile033/content | /labs/lab8/anagrams.py | 695 | 4.03125 | 4 | from mrjob.job import MRJob
class MRAnagram(MRJob):
def mapper(self, _, line):
# Convert word into a list of characters, sort them, and convert
# back to a string.
letters = list(line)
letters.sort()
# Key is the sorted word, value is the regular word.
yield letters, line
def reducer(self, _, words):
# Get the list of words containing these letters.
anagrams = [w for w in words]
# Only yield results if there are at least two words which are
# anagrams of each other.
if len(anagrams) > 1:
yield len(anagrams), anagrams
if __name__ == "__main__":
MRAnagram.run()
|
e1ed53516c721d388ef69b09477552d6a92ea22e | rdsteed/RasWik | /Python/Examples/02Receive.py | 1,285 | 3.625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Wireless Inventors Kit Python Example 02Receive.py
Copyright (c) 2013 Ciseco Ltd.
This basic Python example just open a serial port and send one LLAP message
and receive a reply and prints it to the console
Author: Matt Lloyd
This code is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
"""
#import the PySerial library and sleep from the time library
import serial
from time import sleep
# declare to variables, holding the com port we wish to talk to and the speed
port = '/dev/ttyAMA0'
baud = 9600
# open a serial connection using the variables above
ser = serial.Serial(port=port, baudrate=baud)
# wait for a moment before doing anything else
sleep(0.2)
# write a--D13HIGH-- out to the serial port
# this should turn the XinoRF LED on
# changing this to a--D13LOW--- will turn the LED off
ser.write('a--D13HIGH--')
# wait for a moment before doing anything else
sleep(0.2)
# read 12 characters from the serial port
reply = ser.read(12)
# print the replay
print(reply)
# close the serial port
ser.close()
# at the end of the script python automatically exits |
9cfec44bedba0aeabc70bd7a873a565a9b3fa403 | kolleshirisha/alarm-clock | /myminiproject-alarm.py | 1,033 | 3.546875 | 4 | from tkinter import *
import datetime
from tkinter import messagebox
from tkinter.ttk import *
import winsound
obj=Tk()
def alarm():
if(c1.get()=="AM"):
x=int(e1.get())
y=int(e2.get())
if(c1.get()=="PM"):
x=int(e1.get())+12
y=int(e2.get())
messagebox.showinfo("notification","alarm has been set")
while(True):
if(x==datetime.datetime.now().hour and y==datetime.datetime.now().minute):
for i in range(0,100):
winsound.Beep(1000,100)
messagebox.showinfo("notification","WAKE UP")
break
obj.geometry("400x200")
l1=Label(obj,text="HOURS:")
l2=Label(obj,text="MINUTES:")
l1.grid(row=0,column=0)
l2.grid(row=1,column=0)
e1=Entry(obj)
e2=Entry(obj)
e1.grid(row=0,column=1)
e2.grid(row=1,column=1)
b1=Button(obj,text="SET ALARM",command=alarm)
b1.grid(row=2,column=1)
c1=Combobox(obj,values=["AM","PM"])
c1.grid(row=0,column=2)
l3=Label(obj,text="AM OR PM")
l3.grid(row=0,column=3)
obj.mainloop()
|
3cc25068551ef4d261783dc462b248b8492341f7 | andriitugai/10_python_apps_udemy | /Other/hello.py | 160 | 3.78125 | 4 |
print("Hello!")
import os
dir = os.listdir()
print(dir)
a = ['a', 'b', 'c']
b = [1, 2, 3]
for i,j in zip(a,b):
print("%s is %s" % (i, j))
|
c6e62ee8ba73a87d375a2aa80c03a5b8655ae222 | pa20abhay/Swaping | /swap2.py | 48 | 3.578125 | 4 | x=5
y=6
print(x,y)
x=x*y
y=x/y
x=x/y
print(x,y)
|
f4aab33db74d16614b93051e06a2536230ab1b65 | UWPCE-PythonCert/Py100-2017q1 | /jingdai/stringformat.py | 300 | 3.53125 | 4 |
#
# Write a format string that will take:
#
# ( 2, 123.4567, 10000)
#
# and produce:
#
# 'file_002 : 123.46, 1.00e+04'
print("file_{:0>3d}: {:.2f}, {:.2e}".format(2, 123.4567, 10000))
t=(1,2,3)
print("the 3 numbers are: {:d}, {:d}, {:d}".format(*t))
|
41ad546fa8e24fba19c5fefc437ad9972e7be39b | sanderheieren/in1000 | /oblig6/dato.py | 1,408 | 3.859375 | 4 | # Program om datoer
# 1, 2, 3
class Dato:
def __init__(self, nyDag, nyMaanded, nyttAar):
self._nyDag = nyDag
self._nyMaanded = nyMaanded
self._nyttAar = nyttAar
def hentAar(self):
return self._nyttAar
def printDato(self):
return f"{self._nyDag}/{self._nyMaanded}/{self._nyttAar}"
def sjekkDato(self):
if self._nyDag == 15:
return "Loenningsdag!"
elif self._nyDag == 1:
return "Ny maaned, nye muligheter"
else:
return "Stå på"
# 2d
def lesInnDato(self):
nyDato = input("Oppgi ny dato (DD/MM/YYYY):\n>>>")
datoListe = nyDato.split("/")
dag = int(datoListe[0])
mnd = int(datoListe[1])
aar = int(datoListe[2])
if(aar < self._nyttAar):
print("Den nye oppgitte datoen kommer før dato-objektet")
return
if(aar > self._nyttAar):
print("Den nye oppgitte datoen kommer etter dato-objektet")
return
if aar == self._nyttAar:
if mnd < self._nyMaanded or (mnd == self._nyMaanded and dag < self._nyDag):
print("Den nye oppgitte datoen kommer før dato-objektet")
elif mnd == self._nyMaanded and dag == self._nyDag:
print('Lik dato')
else:
print("Den nye oppgitte datoen kommer etter dato-objektet")
|
0ee4deaac8683cf7c85338813f2827dd034ef750 | ibianco91/curso_em_video | /exercicios/desafio 5.py | 171 | 4.03125 | 4 | v = int(input('Digite um valor'))
print('o numero antecessor é {} e o numero sucessor é {}'.format((v-1),(v+1)))
print('o numero somado a 10 é igual a {}'.format(v+10)) |
bf321e3fbfb736597146195c98833e8fb13d36f8 | SterlingJosh/sat-sudoku | /display_solution.py | 710 | 3.578125 | 4 | #!/usr/bin/env python3
# encoding: UTF-8
"""A pretty-printer to display the solution."""
__author__ = "David Oniani"
__email__ = "onianidavid@gmail.com"
__license__ = "GPLv3"
def main() -> None:
def p(x, y, z):
return (((x - 1) * 9) + (y - 1)) * 9 + z
line = input()
if line.strip() == "SAT":
print("\n S O L U T I O N\n- - - - - - - - -")
solution = input().split()
for i in range(1, 10):
for j in range(1, 10):
for k in range(1, 10):
if str(p(i, j, k)) in solution:
print(k, end=" ")
print()
else:
print("\nGiven puzzle has no solutions.")
if __name__ == "__main__":
main()
|
1c690ea62fa138507183ba1c65ae6888f0336c19 | rajchauhan28/learn_with_raj | /tic_tac_toe_ex.py | 1,886 | 3.859375 | 4 | board=[0,1,2,3,4,5,6,7,8]
x=[1,3,5,9]
y=[2,4,6,8]
print("Enter name of user playing as 'x' player")
usrx = input()
print("Enter name of user playing as 'y' player")
usry = input()
def boards():
print(board[0]," l ",board[1]," l ",board[2])
print("-------------------")
print(board[3]," l ",board[4]," l ",board[5])
print("-------------------")
print(board[6]," l ",board[7]," l ",board[8])
boards()
print("The first move will be of",usrx," 'x'(cross) move and next will be of",usry," '0'(zero) ")
print("Every box contains a number so enter the number of the box which you want to make your move.")
try:
for moves in range(15):
print("enter the number")
num=int(input())
if board[num] != 'x' or board[num] != 'o':
if moves in x:
board[num]='x'
boards()
if moves in y:
board[num]='o'
boards()
elif board[num] == 'x' or board[number] == 'o':
print("this is already taken")
elif board[0,4,8]=='x' or board[2,4,6]=='x' or board[0,3,6]=='x' or board[1,4,7]=='x' or board[2,5,8]=='x' :
print('The',usrx,'is the winner')
elif board[0,4,8]=='o' or board[2,4,6]=='o' or board[0,3,6]=='o' or board[1,4,7]=='o' or board[2,5,8]=='o':
print('The',usry,'is the winner')
except ValueError:
print('Invalid please try again')
try:
for moves in range(15):
print("enter the number")
num=int(input())
if board[num] != 'x' or board[num] != 'o':
if moves in x:
board[num]='x'
boards()
if moves in y:
board[num]='o'
boards()
elif board[num] == 'x' or board[number] == 'o':
print("this is already taken")
elif board[0,4,8]=='x' or board[2,4,6]=='x' or board[0,3,6]=='x' or board[1,4,7]=='x' or board[2,5,8]=='x' :
print('The',usrx,'is the winner')
elif board[0,4,8]=='o' or board[2,4,6]=='o' or board[0,3,6]=='o' or board[1,4,7]=='o' or board[2,5,8]=='o':
print('The',usry,'is the winner')
|
45cc5c2855dda5563feccb699f78ceb7ea5e501f | yyHaker/PythonStudy | /algorithms/常见面试编程题(剑指offer&leetcode)/双指针&快慢指针&滑动窗口/8.无重复字符的最长子串.py | 1,863 | 3.578125 | 4 | #!/usr/bin/python
# coding:utf-8
"""
@author: yyhaker
@contact: 572176750@qq.com
@file: 10.无重复字符的最长子串.py
@time: 2019/7/25 10:13
"""
"""
leetcode3: 无重复字符的最长子串
思路:滑动窗口
"""
class Solution1(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
# 思路:滑动窗口, 维护一个窗口为[i,j)的字符串,并使用hashset存储出现的字符,
# 若s[j]不在hashset,j后移,更新不重复字符串的最大长度;若s[j]在hashset,i后移,继续维护下一个窗口。
# 时间复杂度为O(2n)=O(n), 空间复杂度为O(min(m,n))
res = 0
chars = set()
i, j = 0, 0
while i < len(s) and j < len(s):
if s[j] not in chars:
chars.add(s[j])
j += 1
res = max(res, j - i)
else:
chars.remove(s[i])
i += 1
return res
class Solution2(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
# 思路:优化的滑动窗口, 维护一个窗口为[i,j]的字符串,并使用hashset存储出现的字符到索引的一个映射。
# 如果s[j]在hashset中,i直接跳到该重复字符的下一个位置;每轮均会更新当前最大无重复字符串的最大长度,并添加字符到hashset
# 时间复杂度为O(n), 空间复杂度为O(min(m,n))
res = 0
chars = {}
i, j = 0, 0
for j in range(len(s)):
if s[j] in chars:
i = max(chars[s[j]] + 1, i)
res = max(res, j - i + 1)
chars[s[j]] = j
return res
s = "abcabcbb"
solution = Solution1()
res = solution.lengthOfLongestSubstring(s)
print(res) |
84cafbe66bb746b876bd011a6f9552e33396a61a | mstgrant/Interview_Prep | /Selection_sort.py | 446 | 3.75 | 4 | #Time Complexity O(n^2)
#Space Complextiy O(1)
def selection_sort(list_a):
index_a = range(0,len(list_a)-1)
for i in index_a:
min_value = i
for j in range(i+1,len(list_a)):
if list_a[j] < list_a[min_value]:
min_value = j
if min_value != i:
list_a[min_value], list_a[i] = list_a[i], list_a[min_value]
return list_a
print(selection_sort([7,85,9,5,2,1,2,0,5,785]))
|
f9b6ccdc394c40c55e894c5449411f52c6a8d7c2 | GodMadoka/LeetCode | /array/566. Reshape the Matrix/R1.py | 684 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
def matrixReshape(nums, r, c):
"""
:type nums: List[List[int]]
:type r: int
:type c: int
:rtype: List[List[int]]
"""
if len(nums)*len(nums[0]) != r*c:
return nums
res = []
for i in xrange(r):
res.append([])
col = 0
for i in xrange(len(nums)):
for j in xrange(len(nums[0])):
res[col].append(nums[i][j])
if (i*len(nums[0])+j+1)%c == 0:
col += 1
return res
a = [[1,2],[3,4]]
print matrixReshape(a, 1, 4) |
f11a12484eb394803ae46f4fee9cbaf03ee845fd | Derin-Wilson/Numerical-Methods | /poly_reg.py | 3,221 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 15 18:48:45 2020
@author: esha
"""
import matplotlib.pyplot as plt
import numpy as np
import sympy as sym
"""This is a program to perform polynomial interpolation"""
#Enter the data
x=np.array([0,1,2,3,4,5])
y=np.array([2.1,7.7,13.6,27.2,40.9,61.1])
print("The x matrix is :\n",x)
print("\n")
print("The y matrix is :\n",y)
print("\n")
plt.scatter(x,y,color='red')
plt.title("Actual data")
plt.xlabel('x-axis')
plt.ylabel('y-axis')
plt.show()
#This is a module to perform Polynomial-Interpolation
def pol_int(x,y):
n=len(x)
m=eval(input("Enter the degree of the polynomial to be fitted : "))
print("\n")
z=z_mat(x,n,m)
zt=Transpose(z)
A=np.dot(zt,z)
B=np.dot(zt,y)
a=Gauss_Elim(A,B,len(A))
return (z,zt,A,B,a)#Returns a tuple
#This is a module to find the z matrix for any polynomial-interpolation
def z_mat(x,n,m):
z=np.zeros(shape=(n,m+1))
for i in range(0,n):
for j in range(0,m+1):
d=np.copy(x[i])
z[i][j]=pow(d,j)
return(z)
#This is a module for Transpose of any n x m matrix
def Transpose(z):
no_r=len(z)
no_c=len(z[0])
zt=np.zeros(shape=(no_c,no_r))
for i in range(0,len(zt)):
for j in range(0,len(zt[0])):
d=np.copy(z[j][i])
zt[i][j]=d
return(zt)
#This is a module for Gauss-Elimination
def Gauss_Elim(A,B,n):
RR_A,RR_B=Forward_Elim(A,B,n)#Function call for forward elimination
sol=Back_Sub(RR_A,RR_B,n)#Function call for back substitution
return sol
#Module to perform Forward Elimination
def Forward_Elim(A,B,n):
for i in range(0,n-1):
for j in range(i+1,n):
factor=A[j][i]/A[i][i]
for k in range(i,n):
A[j][k]=A[j][k]-(factor*A[i][k])
B[j]=B[j]-factor*B[i]
return(A,B)#Returns a tuple contating row-reduced forms of A and B
#Module to perform Back-Substitution
def Back_Sub(A,B,n):
x=np.zeros(n)
s=0
x[n-1]=B[n-1]/A[n-1][n-1]
for i in range(n-2,-1,-1):
for j in range(i+1,n):
s=s+A[i][j]*x[j]
x[i]=(B[i]-s)/A[i][i]
s=0
return(x)#Returns the solution matrix
sol=pol_int(x,y)#Interpolation
print("The z matrix is :\n",sol[0])
print("\n")
print("The transpose of matrix is :\n",sol[1])
print("\n")
print("The zt*z matrix is :\n",sol[2])
print("\n")
print("The zt*y vector is :\n",sol[3])
print("\n")
print("The coeff vector is :\n",sol[4])
print("\n")
#Module to find the polynomial given the coeff-matrix and also the fitted y-values
def func(k,x):
l=len(x)
x_f=np.copy(x)
y_f=np.zeros(l)
x=sym.Symbol('x')
m=len(k)
s=0
for j in range(m-1,-1,-1):
s=k[j]+s*x
for j in range(0,l):
y_f[j]=s.subs(x,x_f[j])
return (s,y_f)
k=sol[4]#This is the coeff matrix
f,y_f=func(k,x)#f is the polynomial and y_f is as calculated by f
print("The polynomial which is to be fitted is :\n",f)
#Plotting
plt.scatter(x,y,label='actual data',color='red')
plt.plot(x,y_f,label='fitted data',color='green')
plt.legend(loc='best')
plt.xlabel('x-axis')
plt.ylabel('y-axis')
plt.title('The actual and fitted data')
plt.show()
|
48db56f8f8182bc630790959eeeabf484e534405 | teohongwei898/python | /divisbleby10.py | 225 | 3.90625 | 4 | #Write your function here
def divisible_by_ten(nums):
x = 0
for y in nums:
if (y % 10 == 0):
x += 1
return x
#Uncomment the line below when your function is done
print(divisible_by_ten([20, 25, 30, 35, 40]))
|
833f01cbb75a4275754c1b4b932ede4d7213d9b6 | takecian/ProgrammingStudyLog | /hackerrank/30-days-of-code/day29.py | 643 | 3.515625 | 4 | # https://www.hackerrank.com/challenges/30-bitwise-and/problem
#!/bin/python3
import math
import os
import random
import re
import sys
if __name__ == '__main__':
t = int(input())
for t_itr in range(t):
nk = input().split()
n = int(nk[0])
k = int(nk[1])
a = k - 1 # 答えの候補
expected = a | (a + 1) # a の 1 の桁が全て1の数字で一番小さい数字
if expected <= n: # expected が使えるなら、 a の値が & で作れる a & expected
print(a)
else: # expected が使えないなら a & a - 1 が最大値
print(a - 1)
|
8cb75263cee39e95232dd5dca4d4c7d46867c4c1 | Codechef-SRM-NCR-Chapter/30-DaysOfCode-March-2021 | /answers/justshivam/Day 27/question2.py | 129 | 3.890625 | 4 | string, num = input(), int(input())
while len(string) < num:
string += string
string = string[:num]
print(string.count('a'))
|
899d5c0dfeccdb3146e2480474aefd8b723334cc | anoirtrabelsi/Path-Finder | /Main.py | 4,583 | 3.828125 | 4 | from collections import deque
import pygame
import Graph as graph
import math
#This class represents the GUI
#Select start then end vertex then draw obstacles with the mouse
#Hit the Enter key
pygame.init()
class grid(object):
def __init__(self, w, h, rows):
self.w = w
self.h = h
self.rows = rows
self.s = self.h // rows
self.cols = self.w // self.s
self.graph = self.generate_graph()
def draw_grid(self, surface):
w = self.h // self.rows
# horizontal:
for i in range(self.rows + 1):
pygame.draw.line(surface, (105, 105, 105),
(0, i*w), (self.w, i*w), 1)
# vertical:
i = 0
while (i*w < self.w):
pygame.draw.line(surface, (105, 105, 105),
(i*w, 0), (i*w, self.h), 2)
i += 1
def generate_graph(self):
# geneates a graph object representing the grid.
g = graph.Graph()
num_cells = self.rows * self.cols
for i in range(num_cells):
g.add_vertex(str(i))
for i in range(num_cells):
if i // self.cols == (i+1) // self.cols:
g.add_edge(str(i), str(i+1))
if i-1 >= 0 and i // self.cols == (i-1) // self.w:
g.add_edge(str(i), str(i-1))
if i + self.cols < num_cells:
g.add_edge(str(i), str(i + self.cols))
if i - self.cols >= 0:
g.add_edge(str(i), str(i - self.cols))
return g
def draw_vertex(self, window, vertex, color):
(r, c) = (int(vertex) // self.cols, int(vertex) % self.cols)
pygame.draw.rect(window, color, (c*self.s, r *
self.s, self.s-0.5, self.s-0.5))
def manhattanDistance(self, v1, v2):
(r1, c1) = (int(v1) // self.cols, int(v1) % self.cols)
(r2, c2) = (int(v2) // self.cols, int(v2) % self.cols)
return abs(r1-r2) + abs(c1-c2)
def computeDistances(self, goal):
vertices = self.graph.get_vertices()
map = dict()
for v in vertices:
map[v] = self.manhattanDistance(v, goal)
return map
running = True
# window dimensions:
w = 1200
h = 900
num_rows = 30
window = pygame.display.set_mode((w, h))
window.fill((255, 255, 255))
pygame.display.set_caption("Path Finder")
grid = grid(w, h, num_rows)
grph = grid.graph
finished = False
config = False
start = -1
end = -1
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
grid.draw_grid(window)
pygame.display.update()
mouse = pygame.mouse.get_pressed()
keys = pygame.key.get_pressed()
if not config:
if start == -1 or end == -1:
if mouse[0]:
(x, y) = pygame.mouse.get_pos()
if x >= 0 and x < grid.w and y >= 0 and y < grid.h:
vertex = str((y // grid.s) * grid.cols + (x // grid.s))
grid.draw_vertex(window, vertex, (255, 0, 0))
pygame.display.update()
if start == -1:
start = vertex
elif vertex != start:
end = vertex
else:
if mouse[0]:
(x, y) = pygame.mouse.get_pos()
if x >= 0 and x < grid.w and y >= 0 and y < grid.h:
vertex = str((y // grid.s) * grid.cols + (x // grid.s))
if vertex != start and vertex != end:
grid.draw_vertex(window, vertex, (100, 100, 100))
grph.remove_vertex(vertex)
if keys[pygame.K_RETURN]:
config = True
if config and not finished:
distances = grid.computeDistances(end)
#path = grph.a_star(start,end, distances)
path, order = grph.greedy_BFS(start, end, distances)
if path:
for vertex in order:
if vertex != start and vertex != end:
grid.draw_vertex(window, vertex, (247, 247, 89))
pygame.time.delay(20)
pygame.display.update()
for vertex in path:
if vertex != start and vertex != end:
grid.draw_vertex(window, vertex, (115, 194, 4))
pygame.time.delay(50)
pygame.display.update()
print("The cost of the shortest path is " + str(len(path)-1))
else:
print("No path has been found!")
finished = True
|
a6b64b703d685bcb8885b96dae69c382193f0a70 | qcq/WeChatCopyer | /src/listener/mouselistener.py | 220 | 3.53125 | 4 | # -*- coding:utf-8 -*-
#!/usr/bin/env python3
from pynput import mouse
mouseController = mouse.Controller()
def on_scroll(x, y, dx, dy):
print(x, y, dx, dy)
listener = mouse.Listener(
on_scroll=on_scroll
)
|
5c75f93b0b896566e451949a375a3999537708c2 | mfarzamalam/Snake_Charmer | /numpy/one_dimension/user_input.py | 492 | 3.609375 | 4 | from numpy import *
### Using For loop
# user = int(input("How many user do you have?\n:"))
# rollno = zeros(user, dtype=int)
# print("Enter their Roll Number's\n")
# for i in range(user):
# ids = int(input(":"))
# rollno[i] = ids
# print(rollno)
### Using While Loop
user = int(input("How many user do you have?\n:"))
rollno = zeros(user, dtype=int)
print("Enter their Roll Number's\n")
i=0
while i < user:
ids = int(input(":"))
rollno[i] = ids
i+=1
print(rollno) |
2c9c1ea44c545e4d0cdb74f6234012bc604142e2 | amitdshetty/PycharmProjects | /PracticePythonOrg/Solutions/23_File_Overlap.py | 1,717 | 4.1875 | 4 | """
Problem Statement:
Given two .txt files that have lists of numbers in them, find the numbers that are overlapping. One .txt file has a list of all prime numbers under 1000,
and the other .txt file has a list of happy numbers up to 1000.
(If you forgot, prime numbers are numbers that can’t be divided by any other number. And yes, happy numbers are a real thing in mathematics -
you can look it up on Wikipedia. The explanation is easier with an example, which I will describe below.)
"""
def main():
prime_number_file_location = '/Users/amitshetty/Desktop/primenumbers.txt'
happy_numbers_file_location = '/Users/amitshetty/Desktop/happynumbers.txt'
prime_numbers_list = read_and_add_to_list(prime_number_file_location)
happy_numbers_list = read_and_add_to_list(happy_numbers_file_location)
print('File Stats -> \nPrime Numbers: {}, Happy Numbers: {}'.format(len(prime_numbers_list), len(happy_numbers_list)))
if len(prime_numbers_list) < len(happy_numbers_list):
calculate_file_overlap(prime_numbers_list, happy_numbers_list)
else:
calculate_file_overlap(happy_numbers_list, prime_numbers_list)
def calculate_file_overlap(smallest_list, largest_list):
file_overlap_list = [int(number) for number in smallest_list if number in largest_list]
print('Numbers common to both lists ==>\n{}'.format(file_overlap_list))
def read_and_add_to_list(file_location):
numbers_list = []
with open(file_location) as open_file:
line_in_file = open_file.readline()
while line_in_file:
numbers_list.append(line_in_file)
line_in_file = open_file.readline()
return numbers_list
if __name__ == '__main__':
main() |
e9bfd9657352b3f8aff32cd943d82663d08d2566 | ricarcon/programming_exercises | /2021/implementQueueWithStack.py | 1,588 | 4.25 | 4 | class Queue:
def __init__(self):
self.s1 = []
self.s2 = []
self.flag = True #when we move elements from one stack to the other, the new stack will now have the last element at the top vs the bottom, so we can just pop from the top if even
def enQueue(self, val):
self.s1.append(val)
def deQueue(self):
if self.flag:
#in this case we'll pop everything until we have the last element and return the last element
#s2 will then have the elements in order that we can just pop to dequeue
while len(self.s1) > 0:
#transfer everything from stack 1 to stack 2
self.s2.append(self.s1.pop())
self.flag = False
#return the top of stack 2
return self.s2.pop()
else:
element = None
if len(self.s2) > 0:
#reset the flag if we have no more elements in s2
element = self.s2.pop()
#if after popping the element we have nothing else, let's pull from the first stack by setting the flag accordingly
if len(self.s2) == 0:
self.flag = True
return element
# Driver code
if __name__ == "__main__":
q = Queue()
q.enQueue(1)
q.enQueue(2)
q.enQueue(3)
print(q.deQueue())
print(q.deQueue())
q.enQueue(4)
print(q.deQueue())
print(q.deQueue()) |
97e7251535e3656d9dad93c48ca3fb9e3c15b1eb | jereneal20/Basic_Python_Study | /week4/gugudan.py | 182 | 3.78125 | 4 |
number = 0
while number < 10:
number2 = 0
number = number + 1
while number2 < 10:
number2 = number2 + 1
print(number,"단!! ",number2," * ",number," = ", number * number2)
|
815ff83f3e238d6a603163152ef6239b0587007b | southpawgeek/perlweeklychallenge-club | /challenge-188/vamsi-meenavilli/python/ch-1.py | 1,103 | 4.15625 | 4 | #!/usr/bin/env python3
'''
Week 188:
https://theweeklychallenge.org/blog/perl-weekly-challenge-188
Task #1: Divisible Pairs
You are given list of integers @list of size $n and divisor $k.
Write a script to find out count of pairs in the given list that
satisfies the following rules.
The pair (i, j) is eligible if and only if
a) 0 <= i < j < len(list)
b) list[i] + list[j] is divisible by k
'''
def count_divisibles(list, k):
divisibles_count = 0
list_size = len(list)
for i in range(list_size):
for j in range(i+1, list_size):
if ((list[i] + list[j]) %k == 0):
divisibles_count += 1
return divisibles_count
def test_count_divisibles():
assert count_divisibles([4, 5, 1, 6], 2) == 2, 'Example 1 Failed'
assert count_divisibles([1, 2, 3, 4], 2) == 2, 'Example 2 Failed'
assert count_divisibles([1, 3, 4, 5], 3) == 2, 'Example 3 Failed'
assert count_divisibles([5, 1, 2, 3], 4) == 2, 'Example 4 Failed'
assert count_divisibles([7, 2, 4, 5], 4) == 1, 'Example 5 Failed'
test_count_divisibles()
|
a2eff41cb79724f0b86f6cbc6a63b9053dc7fe12 | AyaElAshry/Mancala_Game | /Mancala_Project.py | 5,580 | 3.6875 | 4 | import time
import sys
from pytimedinput import timedInput
def print_board(board):
print("| |" , board[12], "|" , board[11], "|" , board[10], "|" , board[9], "|" , board[8], "|" , board[7], "| |" )
# print("-----------------------------")
print("|{}| \t\t\t\t\t |{}|" .format(board[13], board[6]))
# print("-----------------------------")
print("| |", board[0], "|" , board[1], "|" , board[2], "|" , board[3], "|" , board[4], "|" , board[5], "| |" )
def ToString(String):
List_2 = []
String = str(String)[1:-2]
String = String.replace(" ", "")
List = list(String.split(","))
for i in List:
List_2.append(int(i))
return List_2
def Center_Drawing_List(List ):
for i in range(len(List)):
txt = List[i]
x = txt.center(80, 'X')
print(x)
def Center_Drawing_String(String):
x = String.center(80, 'X')
print(x)
def Center_Drawing_String_Circles(String):
x = String.center(80, 'O')
print(x)
def Center_Drawing_String_Null(String):
x = String.center(80)
print(x)
def getWinner(board):
board = board.copy()
for i in range(6):
board[6]+=board[i]
board[i]=0
for i in range(7,13):
board[13]+=board[i]
board[i]=0
score = board[6] - board[13]
return score, board
def NewGame():
board =[4,4,4,4,4,4,0,
4,4,4,4,4,4,0]
print_board(board)
print("\n")
print("Ai already won the name Player_1, You are now Player_2\n")
print('''You may choose to Start first or Let your rival start first, You may select 1 or 2:
1. Show me your best move Ai!!!
2. I will show you my move first''')
player=int(input())
print('''Plaese Choose:
0.No Stealing Mode
1.Stealing Mode''')
stealing= int(input())
print(''' Choose the game difficulty:
1- Easy
2- Intermediate
3- Hard
''')
depth_limit = int(input())
# print("Enter the time you required to play ")
# time_out=int(input())
return (board, player, stealing, depth_limit)
def SaveGame(next_board,next_player, stealing, depth_limit):
with open("LastGame.txt", "w") as output:
output.write(str(next_board))
output.write('\n')
output.write(str(next_player))
output.write('\n')
output.write(str(stealing))
output.write('\n')
output.write(str(depth_limit))
output.write('\n')
def RestoreGame():
f = open("LastGame.txt", "r")
Game = []
for x in f:
Game.append(x)
return Game
def gameover(board):
count=0
count1=0
for i in range(len(board)):
if (i >= 0 and i < 6 ):
if board[i] ==0:
count = count + 1
# print(count)
elif ( i> 6 and i <13 ):
if board[i]==0:
count1 =count1 +1
if count == 6 or count1 == 6:
return 1
else:
return 0
# result= gameover(board)
# print(result)
def move(board, idx, stealing = True):
player_1 = 0
player_2 = 0
next_player = 0
inc = 0
final_idx = 0
valid_stealing_flag = True
board = board.copy()
if idx < 6:
player_1 = 1
next_player = 2
else:
player_2 = 2
next_player =1
pocket_val = board[idx]
if pocket_val == 0 :
# print("Pocket is empty")
return board , -1
board[idx] = 0
for i in range(idx + 1 , pocket_val + idx + 1):
i = i%14
final_idx = i
if ((player_1 == 1 and i == 13) or (player_2 == 2 and i == 6)):
inc +=1
continue
else:
board[i] += 1
for i in range(inc):
# TODO: Add a condition if the final_idx == 0, but dont increment the opponent mancala
board[((final_idx + i + 1)%14)] += 1
# Final position (Final pocket)
final_pos = (final_idx + inc) % 14
'''
Valid stealing
'''
if (player_1 and final_pos > 6):
valid_stealing_flag = False
elif (player_2 and final_pos < 6):
valid_stealing_flag = False
'''
Stealing technique
'''
if (final_pos != 6):
if (final_pos != 13):
if (board[final_pos] == 1) and stealing == True and valid_stealing_flag == True:
# will steal from 14 - ((final_idx + inc)%14) - 2
board[final_pos] += board[14 - final_pos - 2]
board[14 - final_pos - 2] = 0
if player_1:
board[6] += board[final_pos]
board[final_pos] = 0
if player_2:
board[13] += board[final_pos]
board[final_pos] = 0
if(player_1 and (final_pos) == 6) :
next_player = 1
elif (player_2 and (final_pos == 13)) : # Final play
next_player = 2
return board , next_player
# # [0,1,2,3,4 ,5,6,7,8,9,10,11,12,13]
#board=[0,0,0,0,2,1, 1, 1,0,0,0,0,0, 0]
#b, next_player = move(board, 7)
#print_board(b)
#print(b)
#print("Next player is: {}".format(int(next_player)))
# w = NewGame()
# print(w[0])
# w = RestoreGame()
# print(w[2])
# List = "[4, 4, 0, 5, 5, 5, 1, 4, 4, 4, 4, 4, 4, 0]"
# print(ToString(List))
|
58e5e631c2c7471a86087fc88a14436846e8106a | django-group/python-itvdn | /домашка/starter/lesson 7/Dmytro Marianchenko/t_2.py | 769 | 4.09375 | 4 | def fib(max):
"""
Функция выводит число Фибоначчи, согласно порядковому номеру списка.
для работы функции, передайте число равное порядковому номеру чила Фибонначи
"""
num1 = 0
num2 = num1 + 1
numbers.append(num1)
numbers.append(num2)
for i in range(max):
numbers.append(numbers[-1] + numbers[-2])
max -= 1
del numbers[-1]
del numbers[-2]
return numbers
numbers = []
while True:
max = int(input("Input a number (if you want to quit, input '00'): "))
if max > 0:
fib(max)
print(f"Your Fibonacci number: {numbers[-1]}")
elif max == 00:
break
|
40044c7ebb51620e5cfb338d4a7393965e4b5675 | rdhakal098/RichterScale | /proj01.py | 289 | 3.828125 | 4 | print("How many Richters are you converting")
richter = float(input())
print("Richter scale Value:", richter)
def Conversions():
joules = 10**((1.5*richter)+4.8)
print("Amount of Joules:", joules)
tnt = joules / (4.184*10**9)
print("Amount of TNT:", tnt)
Conversions()
|
7d30529d3e4db547e23297db14f8b8d786e2e005 | Allaman/pckt | /pckt/db.py | 1,222 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
db implements functionality to create a local sqlite3 database
containing Pocket items from the fetch module
"""
import os
import sqlite3
from sqlite3 import Error
from fetch import get_tags
def create_db_con(path):
"""Returns a sqlite3 connection object
Args:
path (str): path to database
Returns:
sqlite3 connection object
"""
try:
return sqlite3.connect(path)
except Error as e:
print(e)
def clear_db(path):
"""Removes existing database file
Args:
path (str): path to database
"""
if os.path.exists(path):
os.remove(path)
def update_db(path, data):
"""Create and fill a sqlite3 database
Args:
path (str): path to database
data (dict): inserts data dictionary into db
"""
con = create_db_con(path)
con.execute('''CREATE VIRTUAL TABLE entries
USING FTS5(title, url, tags, created, note)''')
sql = '''INSERT INTO entries(title, url, tags, created, note) VALUES(?,?,?,?,?)'''
cur = con.cursor()
for _, v in data.items():
vals = (v[0], v[1], get_tags(v), v[3], v[4])
cur.execute(sql, vals)
con.commit()
con.close()
|
0c9307e508116e65603363c1a355ef46c0a38812 | branko-malaver-vojvodic/Python | /values_dict.py | 177 | 3.828125 | 4 | #Function that prints the assigned value of a key
animals_count = {'Lion':1, 'Tiger':2, 'Shark':3, 'Dog':4, 'Cat':5}
print (animals_count['Tiger'])
print (animals_count['Dog'])
|
b604953bc6662432589bf9d32c7090f2b383c243 | CodeHemP/CAREER-TRACK-Data-Scientist-with-Python | /19_Writing Functions in Python/04_More On Decorators/06_Run_n_times().py | 1,564 | 4.28125 | 4 | '''
06 - Run_n_times()
In the video exercise, I showed you an example of a decorator that takes
an argument: run_n_times(). The code for that decorator is repeated below
to remind you how it works. Practice different ways of applying the decorator
to the function print_sum(). Then I'll show you a funny prank you can play
on your co-workers.
'''
def run_n_times(n):
"""Define and return a decorator"""
def decorator(func):
def wrapper(*args, **kwargs):
for i in range(n):
func(*args, **kwargs)
return wrapper
return decorator
'''
Instructions 1/3
- Add the run_n_times() decorator to print_sum() using decorator syntax so that
print_sum() runs 10 times.
'''
# Make print_sum() run 10 times with the run_n_times() decorator
@run_n_times(10)
def print_sum(a, b):
print(a + b)
print_sum(15, 20)
'''
Instructions 2/3
- Use run_n_times() to create a decorator run_five_times() that will run any
function five times.
'''
# Use run_n_times() to create the run_five_times() decorator
run_five_times = run_n_times(5)
@run_five_times
def print_sum(a, b):
print(a + b)
print_sum(4, 100)
'''
Instructions 3/3
- Here's the prank: use run_n_times() to modify the built-in print() function so
that it always prints 20 times!
'''
# Modify the print() function to always run 20 times
print = run_n_times(20)(print)
print('What is happening?!?!')
'''
- Warning: overwriting commonly used functions is probably not a great idea, so think
twice before using these powers for evil.
'''
|
c218f564293dc03f627eba8e79c4f7072f5f7d05 | dombroks/Daily-Coding-Problems | /Google_Problems/Google_Problem_38.py | 903 | 3.859375 | 4 | """
This problem was asked by Google.
Given the root of a binary search tree, and a target K, return two nodes in the tree whose sum equals K.
For example, given the following tree and K of 20
10
/ \
5 15
/ \
11 15
Return the nodes 5 and 15.
"""
class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
nodes = []
def get_nodes(root):
if not root:
return
nodes.append(root.val)
get_nodes(root.left)
get_nodes(root.right)
def nodes_sum(root, k):
get_nodes(root)
for i in range(len(nodes)):
node = nodes[i]
for j in range(i + 1, len(nodes)):
if node + nodes[j] == k:
return node, nodes[j]
return None
# Driver code
ROOT = Node(10, Node(5), Node(15, Node(11), Node(15)))
print(nodes_sum(ROOT, 20))
|
bca3c67594e37453908f1d0f417c2ec438740e69 | gutovesco/Introduction-to-Python- | /funcoes.py | 342 | 4.15625 | 4 | # -*- coding: utf-8 -*-
def divisao(x, y):
return x/y
divisao = divisao(10, 2)
def quadrado(m, n):
return m**n
quadrado = quadrado(3, 3)
print("O valor da divisao é:")
print(divisao)
print("\nO valor do quadrado é:")
print(quadrado)
print("\nO valor do quadrado menos o da divisão é:")
print(quadrado - divisao)
|
74f4ba52c88c312f1a51774fb300e08106ec683b | atriekak/LeetCode | /solutions/78. Subsets.py | 2,181 | 3.703125 | 4 | class Solution:
#Solution 1
def subsets(self, nums: List[int]) -> List[List[int]]:
#Approach: Recursion with backtracking
#Time Complexity: O(n * 2^n)
#Space Complexity: O(n)
#where, n is the length of nums
self.result = []
self.backtracking(nums, 0, [])
return self.result
def backtracking(self, nums, pivot, path):
#base
self.result.append(path.copy())
#logic
for i in range(pivot, len(nums)):
#action
path.append(nums[i])
#recursion
self.backtracking(nums, i + 1, path)
#backtracking
path.pop()
#Solution 2
"""
def subsets(self, nums: List[int]) -> List[List[int]]:
#Approach: Recursion with backtracking
#Time Complexity: O(n * 2^n)
#Space Complexity: O(n)
#where, n is the length of nums
self.result = []
self.backtracking(nums, 0, [])
return self.result
def backtracking(self, nums, idx, path):
#base
if idx == len(nums):
self.result.append(path.copy())
return
#logic
#not choose
self.backtracking(nums, idx + 1, path)
#choose
path.append(nums[idx])
self.backtracking(nums, idx + 1, path)
#backtracking
path.pop()
"""
#Solution 3
"""
def subsets(self, nums: List[int]) -> List[List[int]]:
#Approach: Recursion
#Time Complexity: O(n * 2^n)
#Space Complexity: O(n * 2^n) // deep copy of path at every node
#where, n is the length of nums
self.result = []
self.helper(nums, 0, [])
return self.result
def helper(self, nums, idx, path):
#base
if idx == len(nums):
self.result.append(path)
return
#logic
#not choose
self.helper(nums, idx + 1, path.copy())
#choose
path.append(nums[idx])
self.helper(nums, idx + 1, path.copy())
"""
|
2599a61dc1699469e6988fc07012e25fbe63cd28 | nickhuber327/budget | /actualPercents.py | 1,860 | 3.734375 | 4 | #actualPercents
import csv
def calcPercents(filename):
"""Calculates the actual percentages of the 5 category budget at any income"""
budget = {"Housing" : 0,
"Transportation" : 0,
"Food" : 0,
"Personal" : 0,
"Savings" : 0,
"Debt" : 0,
"Income" : 0,
"Total" : 0}
with open(filename, mode='r') as budgetFile:
budgetReader = csv.DictReader(budgetFile)
for row in budgetReader:
if row["category"] == "housing":
budget["Housing"] += round(abs(float(row["cost"])),2)
elif row["category"] == "transportation":
budget["Transportation"] += round(abs(float(row["cost"])),2)
elif row["category"] == "food":
budget["Food"] += round(abs(float(row["cost"])),2)
elif row["category"] == "personal":
budget["Personal"] += round(abs(float(row["cost"])),2)
elif row["category"] == "savings":
budget["Savings"] += round(abs(float(row["cost"])),2)
elif row["category"] == "debt":
budget["Debt"] += round(abs(float(row["cost"])),2)
elif row["category"] == "income":
budget["Income"] += round(abs(float(row["cost"])),2)
for key in budget:
if key != "Total":
budget["Total"] += budget[key]
return budget
def budgetPercents(filename):
"""Displays 5 category budget"""
budget = calcPercents(filename)
income = budget["Income"]
print("DOLLAR VALUES:")
for key in budget:
print(f'{key}: {budget[key]}')
print("\n")
budget.pop("Income")
print("PERCENTAGES:")
for key in budget:
print(f'{key}: {budget[key] / income * 100}')
if __name__ == "__main__":
budgetPercents()
|
ee16920bdad9f99f3937bb7433dd7a9acb0fc254 | Patryck1999/Curso_em_Video | /PythonExercicios/Mundo_2/ex038.py | 495 | 3.84375 | 4 | """
Escreva um programa que leia dois números inteiros e compare-os mostrando na tela uma mensagem:
- O primeiro valor é maior
- O segundo valor é maior
- Não existe valor maior, os dois são iguais
"""
valor_1 = int(input("Digite o primeiro valor: "))
valor_2 = int(input("Digite o segundo valor: "))
if valor_1 > valor_2:
print("O Primeiro valor é maior")
elif valor_2 > valor_1:
print("O segundo valor é maior")
else:
print("Não existe valor maior, os dois são iguais")
|
6920a63d717d5b2a6501b6aae644163254f53873 | MartaSzuran/Python-for-the-Absolute-Beginner-M.Dawson | /Chapter 5/who_is_your_father_1.py | 1,974 | 3.8125 | 4 | # program kto jest twoim ojcem
# dodanie imienia i nazwiska osoby z przyporzadkowaniem imienia i nazwiska ojca
#słownik fathers przedstawia wartość imienia i nazwiska ojca w stosunku do klucza syna
fathers = {"Miś Puchatek" : "Miś Grizzly", "Rycerz Bez Piątej Klepki" : "Rycerz Bez Czwartej Klepki", "Brad Pitt" : "Bóg" }
#przytitanie
print("Witaj w programie:\n \tKto jest Twoim ojcem?")
choice = None
while choice != "0":
print("""
Wybierz jedna z opcji:
0 - zakończ
1 - dodaj
2 - wymień
3 - usuń
""")
choice = input("Ktora opcje wybierasz: ? \n")
if choice == "1":
new_son = input("Podaj imie i nazwisko syna: \n")
if new_son not in fathers:
new_father = input("Podaj imie i nazwisko ojca: \n")
fathers[new_son] = new_father
print("Para ojciec i styn zostala dodana.")
print(fathers)
else:
print("These son and father are already in dictionary.")
elif choice == "2":
son_for_change = input("Ktorego syna zmienic? \n")
if son_for_change in fathers:
new_son = input("Podaj imie i nazwisko syna: \n")
new_father = input("Podaj imie i nazwisko ojca: \n")
del fathers[son_for_change]
fathers[new_son] = new_father
print("Zmiany zostały zachowane.")
print(fathers)
else:
print("Para syn, ojciec nie istnieje w bazie.")
elif choice == "3":
son_for_delete = input("Podaj imie i nazwisko syna w celu usuniecia pozycji: \n")
if son_for_delete in fathers:
del fathers[son_for_delete]
print("Para ojciec i syn zostali usunieci.")
print(fathers)
else:
print("Para syn, ojciec nie istnieje w bazie.")
elif choice == "0":
print("Do widzenia.")
else:
print("Niestety nieprawidlowy wybor.")
input("Aby zakończyć program wcisnij klawisz Enter.")
|
878a941728a4108abc810a42bbb11a768b641e66 | KXJiao/ResearchTime | /dicClassifier.py | 676 | 3.546875 | 4 | text = open("subInfo.txt").read()
def findCount(sub):
count = 0
terms = open(sub).readlines()
terms = [t.strip().lower() for t in terms]
for t in terms:
if t in text:
count += 1
return count
subArr = []
subArr.append((findCount("biology_terms.txt"), "biology_terms.txt"))
subArr.append((findCount("chemistry_terms.txt"), "chemistry_terms.txt"))
subArr.append((findCount("History_terms.txt"), "History_terms.txt"))
subArr.append((findCount("physics_terms.txt"), "physics_terms.txt"))
subArr.append((findCount("math_terms.txt"), "math_terms.txt"))
subArr = sorted(subArr)[::-1]
print(subArr)
print(subArr[0][1])
|
40e8fafcfe717d7385cf12cecbea27db08903c17 | wchung94/Rosalind | /Bioinformatics/lia.py | 2,171 | 3.65625 | 4 | #!/usr/bin/env python3
"""
Author: WYC
Given: Two positive integers k (k≤7) and N (N≤2k). In this problem, we begin with Tom, who in the 0th generation has
genotype Aa Bb. Tom has two children in the 1st generation, each of whom has two children, and so on. Each organism
always mates with an organism having genotype Aa Bb.
"""
# Import statements
from sys import argv
import itertools
#Functions
def read_file(filetxt):
"""
Turns dataset into dictionary object
Input: fasta file with multiple short sequences
Output: dictionary of fasta id and sequence
"""
fasta_dict = {}
with open(filetxt,'r') as text:
dataset = text.readlines()
for line in dataset:
line = line.strip()
if line.startswith('>'):
fasta_dict[line[1:]] = ''
current_line = line[1:]
else:
fasta_dict[current_line] += line
return fasta_dict
def read_dataset(filetxt):
"""
Turns dataset into string object
Input: txt file with string
Output: string of data from txt file.
"""
text = open(filetxt, 'r')
dataset = text.read()
dataset = dataset.strip()
text.close()
return dataset
def split_dataset(dataset):
"""
Turns dataset string separated by \n into a list
"""
sequence = dataset.split()
return sequence
def next_generation(K,N):
gen_count = 0
K = 1
N = 1
hetero_zyg = ['AaBb']
mate = ['A','a','B','b']
parent = ['A','a','B','b']
generation_a = list(itertools.product(mate[0:2], parent[0:2]))
print(generation_a)
generation_b = list(itertools.product(mate[2:4], parent[2:4]))
print(generation_b)
generation = list(itertools.product(generation_a, generation_b))
print(generation)
for allele in generation:
print(list(itertools.chain.from_iterable(allele)))
return
if __name__ == "__main__":
data_structure = read_dataset(argv[1])
data_structure = split_dataset(data_structure)
numbers = list(map(int, data_structure))
print(numbers)
AaBb_prob = next_generation(numbers[0],numbers[1])
#print(AaBb_prob) |
b2ddad622beb6df04adc0aa686268814ba7bbd14 | funtion/praise | /praise/tests/helper.py | 317 | 3.609375 | 4 | def caption_check(word, word_list):
if not word.isalpha():
return True
return word.isupper() and word.lower() in word_list
def first_letter_caption_check(word, word_list):
if not word.isalpha():
return True
return word[0].isupper and word[1:].islower() and word.lower() in word_list
|
55c9a653b14824324053aebcffb89f4babcaeedc | kaphleyy/Backup | /DSA/Dictionary.py | 734 | 4.0625 | 4 | # constructors of dictionary
myDict = dict([('Name', 'Amrit'), ('age', 24)])
d1 = {'one': 1, 'two': 2, 'three': 3}
d2 = dict(one=1, two=2, three=3)
print(myDict)
print(d1)
print(d2)
print()
# add and update element in a list
d2['four'] = 4
d2['three'] = 33
print(d2)
# delete an element, all elements or whole list
del(d2['three'])
d1.clear()
del[myDict]
print(d1)
print(d2)
# print(myDict)
# keys and values and items retrival
print(d2.keys())
print(d2.values())
print(d2.items())
# iteration
for k in d2.keys():
print(k, d2[k])
for v in d2.values():
print(v) # key cant be accessed using value
for key, value in d2.items():
print("%s : %s"q % (key, value))
# checking if present
print(('one', 1) in d2.items())
|
fda9caf4c95d4bb6757be94be161f098c21c8c82 | Florence-TC/Hangman | /Topics/Loop control statements/Party time/main.py | 166 | 3.625 | 4 | guest_list = []
while True:
name = input()
if name != ".":
guest_list.append(name)
else:
break
print(guest_list)
print(len(guest_list))
|
2ec705a9b3df2d3f6df6306fa5b5ee0215a4d152 | aabhishek-chaurasia-au17/MyCoding_Challenge | /coding-challenges/week10/day04/Q.2.py | 1,826 | 3.78125 | 4 | """
Q-2 )Baseball Game: (5 marks)
https://leetcode.com/problems/baseball-game/
(Easy)
You are keeping score for a baseball game with strange rules. The game
consists of several rounds, where the scores of past rounds may affect future
rounds' scores.
At the beginning of the game, you start with an empty record. You are given a list
of strings ops, where ops[i] is the ith operation you must apply to the record and
is one of the following:
1. An integer x - Record a new score of x.
2. "+" - Record a new score that is the sum of the previous two scores. It is
guaranteed there will always be two previous scores.
3. "D" - Record a new score that is double the previous score. It is
guaranteed there will always be a previous score.
4. "C" - Invalidate the previous score, removing it from the record. It is
guaranteed there will always be a previous score.
Return the sum of all the scores on the record.
Example 1:
Input: ops = ["5","2","C","D","+"]
Output: 30
Explanation:
"5" - Add 5 to the record, record is now [5].
"2" - Add 2 to the record, record is now [5, 2].
"C" - Invalidate and remove the previous score, record is now [5].
"D" - Add 2 * 5 = 10 to the record, record is now [5, 10].
"+" - Add 5 + 10 = 15 to the record, record is now [5, 10, 15].
The total sum is 5 + 10 + 15 = 30.
"""
def baseballGame(ops):
stack = []
temp = 0
for op in ops:
if op == "C":
temp -= stack.pop()
elif op == 'D':
stack.append(2*stack[-1])
temp += stack[-1]
elif op == "+":
stack.append(stack[-1] + stack[-2])
temp += stack[-1]
else:
stack.append(int(op))
temp += stack[-1]
return temp
if __name__ == "__main__":
ops = ["5","2","C","D","+"]
ans = baseballGame(ops)
print(ans)
|
fbf32a5c02df9e2bc817e27a1b092e5d5ce84dd7 | meliyahu/python-tut-101 | /functions.py | 438 | 3.8125 | 4 |
def power(value):
return value**2
def how_long(value=None):
if (value != None):
return len(value)
else:
return "No length"
def converter(origin_unit, units="m", coefficient=0.348):
result = (origin_unit * coefficient)
return f"{result} {units}"
def cels_to_fah(celsius):
return (celsius * 9/5) + 32
print("10 degrees celsius is ", cels_to_fah(10), "Fahrenheit")
print(converter(4, "km", 0.6))
|
2b2c3a907f2fc960eb8457b8313ffb5972afa9b2 | nandyorama/PyPractise | /enumerate.py | 600 | 4.75 | 5 | # Accessing items using enumerate()
cars = ["Aston" , "Audi", "McLaren "]
for i, x in enumerate(cars):
print (x)
print (list(enumerate(cars)))
for x in enumerate(cars):
print (x[0],x[1])
#Enumerate takes parameter start which is default set to zero. We can change this parameter to any value we like. In the below code we have used start as 1.
# demonstrating use of start in enumerate
for x in enumerate(cars, start=1):
print (x[0], x[1])
#enumerate() helps to embed solution for accessing each data item in iterator and fetching index of each data item.
|
0ebf6e438ccfaa6c55dd3505c2e23c36493145f8 | 3bdifatah/lab5 | /ui.py | 376 | 3.703125 | 4 |
def get_name():
name=input('name: ')
return name
def get_country_and_record():
country = input('country: ')
record = int(input('number of chainsaws caught: '))
return country, record
def get_new_record():
new_record = int(input('number of chainsaws caught: '))
return new_record
def error_message(name):
print(f'{name} not in the database') |
4b3c1f377671eb60dae11f071320bd32ed775bc6 | ABoxOfPringles/Math-Formulas | /rectangle.py | 252 | 4.0625 | 4 | # Calculating the area of a square
l = input("What is the length? ")
w = input("What is the width? ")
area = float(l) * float(w)
if l == w:
print("That is a square, you fucking idiot.")
else:
print("The area of the rectangle is " + str(area))
|
3003c6e7c0ab8d1153d1c3cdb348f574c4ceffc8 | auchappy/MA305 | /cw7/cw7.py | 965 | 4.03125 | 4 | #!/usr/bin/env python3
import numpy as np
from matplotlib import pyplot as plt
"""
========================================================================
MA305 - cw 7: Chapman, Piers - 15NOV18
Purpose: Use a function to plot some stuff. Yeah.
========================================================================
"""
def g(x,mu=0,sig=1.5):
expon = np.exp(-(((x-mu)**2)/(2*sig**2)))
return (1/(sig*np.sqrt(2*np.pi)))*expon
mu = 0
sig = 0.5
i = 20
xs = -10
y0 = []
y1 = []
y2 = []
y3 = []
x,dx = np.linspace(-10,10,100,retstep=True)
y0 = g(x)
y1 = g(x,0,0.5)
y2 = g(x,0,1.0)
y3 = g(x,0,1.5)
area = sum(y0)*dx
print('area=',area)
gp = (g(x+dx)-g(x))/dx
f=plt.figure()
plt.plot(x,y0,x,gp)
plt.show()
f=plt.figure()
plt.plot(x,y1,x,y2,x,y3)
plt.xlabel('x')
plt.ylabel('g(x)')
plt.legend(['$\sigma=0$','$\sigma=1$','$\sigma=1.5$'],loc='best')
plt.title('Gaussian function with $\mu=0$ and different values of $\sigma$')
plt.show()
f.savefig('Gauss_function.pdf')
|
2da2c9395a7b99fd75bb40ba50bf75a2ebf9108c | kolchinSI/friendly | /django-exemples/mysite/mysite/1.py | 589 | 3.578125 | 4 | def bread(func):
def wrapper():
print("Булочка")
func()
print("<\Булочка/>")
return wrapper
def ingredients(func):
def wrapper():
print("#помидоры#")
func()
print("~салат~")
return wrapper
def sandwich(food="--ветчина--"):
print(food)
@bread
@ingredients
def sandwich(food="--ветчина--"):
print(food)
sandwich()
def incrementer():
i = '1'
while True :
yield i
i=i+'e'
inc = incrementer()
print(next(inc))
print(next(inc))
print(next(inc))
|
19b05950db913c9b3834eabadb79285669d877c9 | Ashish-012/Competitive-Coding | /recursion/arraySum.py | 139 | 3.671875 | 4 | def arraysum(arr):
if len(arr) == 0:
return 0
num = arr[0]
return num + arraysum(arr[1:])
arr = [15, 12, 13, 10]
print(arraysum(arr)) |
1389d79fb934db1cbc34aad384f4280fe29ae7c0 | GaryXiongxiong/python | /ex11.py | 565 | 4.125 | 4 | #coding:utf-8
#################
# 习题11:提问
#################
# 前言
#
# 这里主要理解:接收用户的输入
#
print "How old are you?",
# 接收控制台的输入信息
age = raw_input() # 在python3.x 中,raw_input 被 input代替(待深究)
print "How tall are you?",
height = raw_input()
print "How much do you weight?",
weight = raw_input()
print "So,you're %s old, %s tall and %s heavy." % (age, height, weight)
# 笔记
# 1.raw_input()是接受控制台输入的任何信息
# 2.在print后面加“,”可以让输入在同一行
|
f2b8ed6767160d50615feb1bd3d948f221f4cb07 | vadim-job-hg/checkio.org | /py.checkio.org/Elementary/Popular Words.py | 683 | 3.84375 | 4 | def popular_words(text, words):
# your code here
return {word:text.replace(","," ").replace("\n"," ").replace("."," ").lower().split().count(word) for word in words}
if __name__ == '__main__':
print("Example:")
print(popular_words('''
When I was One,
I had just begun.
When I was Two,
I was nearly new.
''', ['i', 'was', 'three']))
# These "asserts" are used for self-checking and not for an auto-testing
assert popular_words('''
When I was One,
I had just begun.
When I was Two,
I was nearly new.
''', ['i', 'was', 'three']) == {
'i': 4,
'was': 3,
'three': 0
}
print("Coding complete? Click 'Check' to earn cool rewards!")
|
2ce1b15417384cabe857bdb1d21428f8aeaccd36 | furuhama/sicp | /sicp_in_python/src/my_package/account.py | 1,286 | 4.0625 | 4 | """
every Account instance has its holder & balance
"""
class Account(object):
interest = 0.02 # class attribute
@classmethod
def show_inheritance(cls):
print([c.__name__ for c in cls.mro()])
"""
instance methods
"""
def __init__(self, account_holder):
self.balance = 0
self.holder = account_holder
def deposit(self, amount):
self.balance += amount
return self.balance
def withdraw(self, amount):
if amount > self.balance:
return 'Insufficient funds'
self.balance -= amount
return self.balance
def status(self):
print("====== basic info ======\n{}\nholder: {}\nbalance: {}".format(
self, self.holder, self.balance))
class CheckingAccount(Account):
interest = 0.1
withdraw_charge = 0.1
def withdraw(self, amount):
return Account.withdraw(self, amount * (1 + self.withdraw_charge))
class SavingAccount(Account):
deposit_charge = 0.1
def deposit(self, amount):
return Account.deposit(self, amount * (1 - self.deposit_charge))
class CampaignAccount(CheckingAccount, SavingAccount):
def __init__(self, account_holder):
self.holder = account_holder
self.balance = 1 # From Campaign
|
37c322b9bac05e9935c36054c9530a344558f702 | jagtapshubham/Python | /Strings/VowelConsonentCount.py | 757 | 4.0625 | 4 | #!/usr/bin/python3
def vowel_consonent_count(string):
cvowel=0
cconsonent=0
cdigit=0
cspchar=0
for i in string:
if i>='a' and i<='z' or i>='A' and i<='Z':
i=i.lower()
if i=='a' or i=='e' or i=='i' or i=='o' or i=='u':
cvowel+=1
else:
cconsonent+=1
elif i>='0' and i<='9':
cdigit+=1
else:
cspchar+=1
print("Vowel count in string=%d"%cvowel)
print("Consonent count in string=%d"%cconsonent)
print("Digits count in string=%d"%cdigit)
print("Special character count in string=%d"%cspchar)
def main():
string=input("Enter String=")
vowel_consonent_count(string)
if __name__=='__main__':
main()
|
4b7936c69a301824659cec82561b076dcbd6c522 | Artem-Vorobiov/Tic-Tac-Toe | /ttt_2.py | 1,602 | 3.921875 | 4 | import os
import time
import random
# Define the board
board = [' ',' ',' ',' ',' ',' ',' ',' ',' ',' ']
def print_the_header():
print('\n\n\t\t\t\t_______ TIC--TAC--TOE _______\n\n\n')
def print_board():
print(' | | ')
print(' '+board[1]+' | '+board[2]+' | '+board[3]+' ')
print(' | | ')
print('----|----|----')
print(' | | ')
print(' '+board[4]+' | '+board[5]+' | '+board[6]+' ')
print(' | | ')
print('----|----|----')
print(' | | ')
print(' '+board[7]+' | '+board[8]+' | '+board[9]+' ')
print(' | | ')
while True:
os.system('Clear')
print_the_header()
print_board()
# Get Player X Input
choice = input('Please, choose an empty space for X. Type a digit from 0 to 8: ')
choice = int(choice)
# Check to see if the space is empty first
if board[choice] == ' ':
board[choice] = 'X'
else:
print('Sorry, that space is not empty')
time.sleep(2)
# Check for X win
if (board[1] == 'X' and board[2] == 'X' and board[3] == 'X') or \
(board[4] == 'X' and board[5] == 'X' and board[6] == 'X') or \
(board[7] == 'X' and board[8] == 'X' and board[9] == 'X') or \
(board[1] == 'X' and board[4] == 'X' and board[7] == 'X') or \
(board[2] == 'X' and board[5] == 'X' and board[8] == 'X') or \
(board[3] == 'X' and board[6] == 'X' and board[9] == 'X') or \
(board[1] == 'X' and board[5] == 'X' and board[9] == 'X') or \
(board[7] == 'X' and board[5] == 'X' and board[3] == 'X'):
os.system('Clear')
print_the_header()
print_board()
print('\n\n\t\t\t\t_______ -----TAC----- _______\n\n\n')
break
|
eddf150b5ecf4a3fa057cdad5c63e315ba112b3e | Arality/Dice-Roller | /roller.py | 428 | 3.9375 | 4 | import random
class Dice:
pass
def __init__(self):
self = self
pass
def roll(self, dice)
return random.randint(1,dice)
TotalDice = int(input("Home many Dice would you like to roll:"))
TotalSides = int(input("How many sides on the Dice:"))
Sum = 0
x = 0
while x != TotalDice:
Sum = Sum + random.randint(0, TotalSides)
print("{} Dice Rolled".format(x+1))
x = x + 1
print(Sum)
|
dd7d81e59769e5711bb9d84f8fadee014cbe325f | Astlight/blockChain | /PoW.py | 174 | 3.78125 | 4 | # -*- coding:utf-8 -*-
from hashlib import sha256
x = 5
y = 0 # y未知
while sha256(f'{x*y}'.encode()).hexdigest()[-1] != "":
y += 1
print(f'The solution is y = {y}') |
82d5190ff1a94b03aa42b8bb4f50ad0b4856ec03 | qinyanjuidavid/Hands-On-Python | /Dictionaries.py | 783 | 4.09375 | 4 | #Dictionaries are simply a collection of words matched with their definations.
#Dict are usually made up of key and values
spanish=dict()
spanish['hello']='hola'
spanish['yes']='si'
print(spanish,type(spanish),sep="|")
#Trial two
name=dict()
name['David']=23
name["Jane"]=32
name['John']=42
print(name,type(name),sep="|")
print(name["John"])
def createDictionary():
spanish=dict()
spanish['hello']='hola'
spanish['yes']='si'
return spanish
def Main():
dictionary=createDictionary()
print(dictionary["hello"])
Main()
#trial
def createNameDict():
coders=dict()
coders["David"]="Python"
coders["John"]="Java"
coders["Jane"]="C"
return coders
def Main():
details=createNameDict()
print(details["John"],type(details),sep="|")
Main()
|
a78f42c95ebb8d9931ce54c84cfed7f2b98ac288 | JohnSalazarTec/Portafolio1 | /NumeroPar.py | 469 | 4 | 4 | """
Nombre:numeroPar
Entradas:
n: Entero positivo mayor o igual a cero
salidas:
Entero mayor a cero donde el numero sea elegido verdadero si es par
o sea elegido falso si es impar.
Restricciones:
Entero positivo mayor o igual a cero
"""
def numeroPar(num):
if(isinstance(num,int)and num>0):
if(num%2==0):
return True
else:
return False
else:
return 'Digite un numero entero'
|
d64ddd4d9e2e435d71c156022079b0fd3d0d2eb2 | harshhx/codeforces-practice | /Candies and Two Sisters.py | 131 | 3.640625 | 4 | t = int(input())
for _ in range(t):
n = int(input())
if n<3:
print(0)
elif n%2 != 0:
print(n//2)
else:
print(n//2 - 1)
|
57ef8955ae34d0751981f264d5add1a79440a0d9 | mundopacheco/lindenmayer | /src/tortuga.py | 1,640 | 3.859375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 16 09:28:39 2019
@author: mundo
"""
import matplotlib.pyplot as plt
from math import cos, sin, pi
from stack import Stack
class Tortuga:
# Tortuga constructor
def __init__(self,d,delta,x=0,y=0,angle=0,color='c'):
self.x = x
self.y = y
self.x_p = x
self.y_p = y
self.angle = angle
self.d = d
self.delta = delta
self.color = color
plt.figure()
plt.axis('off')
plt.axis('equal')
self.stack = Stack()
self.stack.push((x,y,angle))
# Move without drawing
def move(self):
self.x_p, self.y_p = self.x, self.y
self.x = self.x + (self.d * cos(self.angle))
self.y = self.y + (self.d * sin(self.angle))
# Move drawing
def draw(self):
plt.plot([self.x_p, self.x], [self.y_p, self.y], color=self.color)
#plt.pause(.2)
# Read single symbol
def __read__(self, c):
if c == "F":
self.move()
self.draw()
elif c == "f":
self.move()
elif c == "+":
self.angle = self.angle + self.delta
elif c == "-":
self.angle = self.angle - self.delta
elif c == "[":
self.stack.push((self.x,self.y,self.angle))
elif c == "]":
self.x, self.y, self.angle = self.stack.pop()
# Read all symbols
def play(self,s):
if len(s) == 1:
self.__read__(s)
elif len(s)>1:
self.__read__(s[0])
self.play(s[1:])
|
229e1ec67c523bc9805606ea3d9c7ddb1c1d634b | licosty/learning_python | /chapter_3/exercise_2.py | 1,190 | 3.984375 | 4 | ''' Страница упражнения - 55 '''
# 3-4
print()
party = ['Hoba', 'Boba', 'Ad']
print('Hey ' + party[0] + ', go to my party')
print('Hey ' + party[1] + ', go to my party')
print('Hey ' + party[2] + ', go to my party')
# 3-5
print()
print(party[2])
party[2] = 'Kevin'
print('Hey ' + party[0] + ', go to my party')
print('Hey ' + party[1] + ', go to my party')
print('Hey ' + party[2] + ', go to my party')
# 3-6
print()
print('More guests for the god of guests!!!')
party.insert(0, 'Merry')
party.insert(2, 'Bill')
party.append('you')
print('Hey ' + party[0] + ', go to my party')
print('Hey ' + party[1] + ', go to my party')
print('Hey ' + party[2] + ', go to my party')
print('Hey ' + party[3] + ', go to my party')
print('Hey ' + party[4] + ', go to my party')
print('Hey ' + party[5] + ', go to my party')
# 3-7
print()
print('Only two of you will go to lunch. Fight!')
print(party.pop() + " couldn't ")
print(party.pop() + " couldn't ")
print(party.pop() + " couldn't ")
print(party.pop() + " couldn't ")
print('Hey ' + party[0] + ', go to my party (now for sure)')
print('Hey ' + party[1] + ', go to my party (now for sure)')
del party[1]
del party[0]
print(party) |
f6e29c889e4912abaf7fe471933533673b46b66e | sumsted/python_class | /lesson11-moreclasses/exercise.py | 1,451 | 4.0625 | 4 |
class Animal:
def __init__(self, classification):
# add a parameter called classification to __init__()
# store the classification parameter in an instance variable
self.classification = classification
def __eq__(self, other):
return self.classification == other.classification
# create a class called Fish it inherit Animal
# and it should take in a parameter called name in its __init__()
# create an instance variable called name to store the name parameter
class Fish(Animal):
def __init__(self, name):
super().__init__('Fish')
self.name = name
self.lives = 'water'
def __eq__(self, other):
return Animal.__eq__(self, other)
# create a class called Bird it inherit Animal
# and it should take in a parameter called name in its __init__()
# create an instance variable called name to store the name parameter
class Bird(Animal):
def __init__(self, name):
super().__init__('Bird')
self.name = name
def __eq__(self, other):
return Animal.__eq__(self, other)
# create an object called bass from Fish, pass in a name
bass = Fish('Billy')
# create an object called shark from Fish, pass in a name
shark = Fish('Sammy')
# create an object called eagle from Bird, pass in a name
eagle = Bird('Eddie')
pass
# test to see if bass and shark are the same classification
# test to see if bass and eagle are the same classification
|
b7832ade8eccf3d99d47c40564c98f52a5fcb9dd | deppwater/- | /singleListNode.py | 3,541 | 3.9375 | 4 | """
链表的题主要考察的coding能力是尽量缩小辅助空间
"""
class Node(object):
def __init__(self, elem):
self.elem = elem
self.next = None
class SingleLinkList(object):
def __init__(self, elem):
head_node = Node(elem)
self.head = head_node
def isEmpty(self):
return self.head is None
def length(self):
if self.head:
cur = 1
else:
return 0
cur_node = self.head
while cur_node.next is not None:
cur_node = cur_node.next
cur += 1
return cur
def travel(self):
if self.head:
cur_node = self.head
while cur_node is not None:
print(cur_node.elem)
cur_node = cur_node.next
def append(self, item):
node = Node(item)
if self.head is None:
self.head = node
else:
cur_node = self.head
while cur_node.next is not None:
cur_node = cur_node.next
cur_node.next = node
return node
def add(self, item):
node = Node(item)
if self.head is None:
self.head = node
else:
node.next = self.head
node, self.head = self.head, node
def insert(self, pos, item):
node = Node(item)
result = self.length()
if pos > result or pos < 0:
ex = Exception('pos参数错误')
raise ex
cur_node = self.head
cur_set = 1
while pos > cur_set:
cur_node = cur_node.next
cur_set += 1
if pos == 0:
node.next = cur_node
else:
node.next = cur_node.next
cur_node.next = node
def search(self, item):
cur_node = self.head
while cur_node is not None:
if cur_node.elem == item:
return True
cur_node = cur_node.next
return False
def delete(self, item):
cur_node = self.head
pre_node = None
if not self.search(item):
ex = Exception('参数错误')
raise ex
if cur_node.elem == item:
self.head = cur_node.next
return
while cur_node.elem != item:
pre_node = cur_node
cur_node = cur_node.next
pre_node.next = cur_node.next
def findLoopStart(self):
fast_node = self.head
slow_node = self.head
while fast_node.next is not None:
if fast_node.next.next is None:
return None
fast_node = fast_node.next.next
slow_node = slow_node.next
if slow_node == fast_node:
fast_node = self.head
while fast_node != slow_node:
fast_node = fast_node.next
slow_node = slow_node.next
return slow_node
if __name__ == '__main__':
text = SingleLinkList(1)
text.append(2)
text.append(3)
text.append(4)
text.append(5)
text.travel()
res = text.length()
print(res)
text.insert(1, 6)
print('=' * 30)
text.travel()
print('=' * 30)
text.insert(6, 7)
text.travel()
print('=' * 30)
res = text.search(7)
print(res)
print('=' * 30)
text.delete(2)
print(text.head.elem)
text.travel()
|
340551b9307b26a3eef0ab2fef371800e10bc64c | aditya-doshatti/Leetcode | /random_point_in_non_overlapping_rectangles_497.py | 1,595 | 3.65625 | 4 | '''
497. Random Point in Non-overlapping Rectangles
Medium
Given a list of non-overlapping axis-aligned rectangles rects, write a function pick which randomly and uniformily picks an integer point in the space covered by the rectangles.
Note:
An integer point is a point that has integer coordinates.
A point on the perimeter of a rectangle is included in the space covered by the rectangles.
ith rectangle = rects[i] = [x1,y1,x2,y2], where [x1, y1] are the integer coordinates of the bottom-left corner, and [x2, y2] are the integer coordinates of the top-right corner.
length and width of each rectangle does not exceed 2000.
1 <= rects.length <= 100
pick return a point as an array of integer coordinates [p_x, p_y]
pick is called at most 10000 times.
Example 1:
Input:
["Solution","pick","pick","pick"]
[[[[1,1,5,5]]],[],[],[]]
Output:
[null,[4,1],[4,1],[3,3]]
https://leetcode.com/problems/random-point-in-non-overlapping-rectangles/
'''
class Solution:
def __init__(self, rects: List[List[int]]):
self.rects = rects
weight, c = [], 0
for rect in rects:
x1, y1, x2, y2 = rect
c += (x2-x1+1)*(y2-y1+1)
weight.append(c)
self.weightc = [w/c for w in weight]
def pick(self) -> List[int]:
u = random.random()
ix = bisect.bisect_left(self.weightc, u)
x1, y1, x2, y2 = self.rects[ix]
x = random.randint(x1,x2)
y = random.randint(y1,y2)
return [x,y]
# Your Solution object will be instantiated and called as such:
# obj = Solution(rects)
# param_1 = obj.pick()
|
c768c150fd6c410fe2b3c9ba8329f1ed6308bc78 | cshintov/python | /anand-python/chapter2/ex38invertdict.py | 831 | 4.0625 | 4 | import sys
#Returns the key,value tuple list sorted based on the key
def v(_dict):
key_val=_dict.items()
key_val.sort(key=key_fn)
sort_val=[]
for tup in key_val:
sort_val.append(tup[1])
print sort_val
return key_val
#Interchanges each of the (key, value) pair
def invertdict(_dict):
new_dict={}
for key, val in _dict.items():
new_dict[val]=key
print new_dict
return new_dict
#This is the main function
def main():
invertdict({'x': 1, 'y': 2, 'z': 3})
'''
if len(sys.argv) >=2:
args=sys.argv[1:] #command line arguments as list of strings
else:
print "usage: python module.py [numlist] "
sys.exit(1)
result=function(args)
print "The result : \n", result '''
if __name__=="__main__":
print "**************************\n"
main()
print "\n**************************"
|
9502832482ee6f0941407f202864b8f1fa252c38 | brimmann/python-exercises | /book2/chap3/general.py | 149 | 3.625 | 4 | class Chair(object):
"""This class represents chairs."""
def __init__(self, name, legs=4):
self.name = name
self.legs = legs
|
89bb8c382cf6fecbe542b18725a5565af1b061cc | learninglegion/PCC | /old_exercises/chap10exercises.py | 5,040 | 3.984375 | 4 | #10.1
# with open('learning_python.txt') as file_object:
# contents = file_object.read()
# print(contents.rstrip())
# filename = 'learning_python.txt'
# with open(filename) as file_object:
# for line in file_object:
# print(line.strip())
# with open(filename) as file_object:
# lines = file_object.readlines()
# text_string = ''
# for line in lines:
# text_string += line
# print(text_string.rstrip())
#
##10.2
#filename = 'learning_python.txt'
#
#with open(filename) as file_object:
# lines = file_object.readlines()
#sub_string = ''
#for line in lines:
# sub = line.replace('python', 'C')
# sub_string += sub
#print(sub_string.rstrip())
#10.3
#filename = 'guest.txt'
#
#with open(filename, 'w') as file_object:
# print("Please provide your name for the guestbook.")
# file_object.write(input("Your name: "))
##10.4
#filename = 'guest_book.txt'
#finished = False
#
#while finished == False:
# with open(filename, 'a') as file_object:
# name = input("Please provide your names for the guestbook (type 'q' when finished): ")
# if name == 'q':
# finished = True
# break
# print(f"Thanks for coming, {name}! Welcome!")
# name = name + '\n'
# file_object.write(name)
##10.5.
#brent.windstreamhosting.bizme = 'programming_poll.txt'
#finished = False
#
#while finished == False:
# with open(filename, 'a') as file_object:
# name = input("Please enter your name for the poll ('q' if finished): ")
# if name == 'q':
# finished = True
# break
# reason = input("Why do you like programming: ")
# file_object.write(f"{name} answered '{reason}'.\n")
##10.6 and 10.7
#print("Give me two numbers and I'll add them.")
#print("Type 'q' to quit.")
#while True:
# first_number = input("First number: ")
# if first_number == 'q':
# break
# second_number = input("Second number: ")
# if second_number == 'q':
# break
# try:
# print(int(first_number) + int(second_number))
# except ValueError:
# print("Numbers only please.")
##10.8 and 10.9
#filenames = ['cats.txt', 'dogs.txt']
#
#for filename in filenames:
# try:
# with open(filename) as f:
# for line in f:
# print(line.title().rstrip())
# except FileNotFoundError:
# #print(f"I could not find {filename}.")
# pass
##10.10
#filename = 'huckfinn.txt'
#
#print("Let's search for words in a book.")
#searchword = input("Give me a word to search for: ")
#searchword_count = 0
#
#with open(filename, encoding='utf-8') as f:
# #contents = f.read()
# #words = contents.split()
# #num_words = len(words)
# #print(f"The file {filename} has {num_words} words in it.")
# for line in f:
# searchword_count += line.lower().count(f'{searchword}')
#print(f"The file {filename} has {searchword_count} '{searchword}'s in it.")
#10.11 and 10.12
#import json
#
#def get_stored_number():
# """Say favorite number"""
# filename = 'favnum.json'
# try:
# with open(filename) as f:
# favnum = json.load(f)
# except FileNotFoundError:
# return None
# else:
# return favnum
#
#def get_new_number():
# """Ask for favorite number"""
# filename = 'favnum.json'
# favnum = input("What is your favorite number? ")
# with open(filename, 'w') as f:
# json.dump(favnum, f)
# return favnum
#
#def favorite_number():
# """Ask for favorite number if we don't know it."""
# favnum = get_stored_number()
# if favnum:
# print(f"I know your favorite number, it's {favnum}!")
# else:
# favnum = get_new_number()
#
#favorite_number()
#10.13
import json
def get_stored_username():
"""Get stored username if available"""
filename = 'username.json'
try:
with open(filename) as f:
username = json.load(f)
except FileNotFoundError:
return None
else:
return username
def get_new_username():
"""Prompt for a new username"""
filename = 'username.json'
username = input("What is your name? ")
with open(filename, 'w') as f:
json.dump(username, f)
return username
def check_user():
username = get_stored_username()
answer = ''
print(f"Is {username} your username?")
while answer != 'y' or answer != 'n':
answer = input("Type 'y' or 'n' to answer: ")
if answer.lower() == 'y':
return True
elif answer.lower() == 'n':
return False
else:
print("Answer 'y' or 'n' please.")
def greet_user():
"""Greet the user by name"""
username = get_stored_username()
if username:
if check_user() == True:
print(f"Welcome back, {username.title()}!")
else:
print("You need your own username.")
username = get_new_username()
else:
username = get_new_username()
print(f"We'll remember you when you come back, {username.title()}!")
greet_user() |
e20655ac6937f781722b4130a0834e0189df566f | xCUDx/PycharmPythona-z | /hello/assignment5.py | 1,088 | 4.4375 | 4 | # Define a first_three_characters function that accepts a string argument.
# The function should return the first 3 characters of the string.
#
# EXAMPLES:
# first_three_characters("dynasty") => "dyn"
# first_three_characters("empire") => "emp"
def first_three_characters(word):
return word[0:3]
print(first_three_characters("hello"))
# Define a last_five_characters function that accepts a string argument.
# The function should return the last 5 characters of the string.
#
# EXAMPLES:
# last_five_characters("dynasty") => "nasty"
# last_five_characters("empire") => "mpire"
def last_five_characters(Word):
return Word[-5:]
print(last_five_characters("dynasty"))
# Define a is_palindrome function that accepts a string argument.
# The function should return True if the string is spelled
# the same backwards as it is forwards.
# Return False otherwise.
#
# EXAMPLES:
# is_palindrome("racecar") => True
# is_palindrome("yummy") => False
def is_palindrome(text):
return text[::1] == text[::-1]
print(is_palindrome("hello"))
print(is_palindrome("123321"))
|
0c00d69ef7c315571ffd54603be8bbc4f6c058ac | j-mai/BreakOut | /Ball.py | 1,131 | 3.890625 | 4 | #Ball class for Breakout game
#Jasmine Mai
from cs1lib import *
class Ball:
def __init__(self, x, y, radius, r, g, b, velocity_x, velocity_y):
self.x = x
self.y = y
self.radius = radius
self.r = r
self.g = g
self.b = b
self.velocity_x = velocity_x
self.velocity_y = velocity_y
#move the ball
def move(self):
self.x += self.velocity_x
self.y += self.velocity_y
#draw the ball
def draw(self):
set_fill_color(self.r, self.g, self.b)
draw_ellipse(self.x, self.y, self.radius, self.radius)
#getters and setters
def get_x (self):
return self.x
def get_y(self):
return self.y
def set_x (self, x):
self.x = x
def set_y(self, y):
self.y = y
def get_radius (self):
return self.radius
def get_velocityX(self):
return self.velocity_x
def get_velocityY(self):
return self.velocity_y
def set_velocityY(self, velocity):
self.velocity_y = velocity
def set_velocityX(self, velocity):
self.velocity_x = velocity
|
d41c4eeba9751d660428f9d69ccd94dcecedb85f | dogbyt3/Data-Science-Projects | /Neural Networks/Steepest Descent/experiment3.py | 2,108 | 3.53125 | 4 | import numpy as np
import matplotlib.pyplot as plt
import random
import nnlib
def main():
# number of samples to create
n = 20
# number of repititions to run NN for
nReps = 200
# data set percentages
train_pct = 0.60
test_pct = 0.20
valid_pct = 0.20
# create some random independent variable data
X = np.linspace(0.,20.,n).reshape((n,1))
# create some random nonlinear dependent variable data
T = 0.2 + 0.05 * X + 0.4 * np.sin(X) + 0.05 * np.random.normal(size=(n,1))
# set number of inputs and outputs
nSamples = X.shape[0]
nOutputs = T.shape[1]
# set hidden layers, and learning rates of neural network
hidden_array = np.array([1, 5, 10, 25, 50])
rhoh = 0.5
rhoo = 0.01
rh = rhoh / (nSamples*nOutputs)
ro = rhoo / (nSamples*nOutputs)
weight_dist = 0.1
tot_test_errors = []
tot_valid_errors = []
# loop through the array of nHiddens and create a nn from it
for i in range(np.size(hidden_array)):
# create a neuralNet object
nn = nnlib.neuralNet(nSamples, nOutputs, hidden_array[i], rhoh, rhoo, weight_dist)
# make the Training, Testing, and Validation sets
nn.makeDataSets(X, T, train_pct, test_pct, valid_pct)
# run the nnet and plot the results
nn.train(nReps)
# get the errors from the nnet
(testing_error, validation_error) = nn.get_FinalErrors()
tot_test_errors.append(testing_error)
tot_valid_errors.append(validation_error)
# plot the avg RMS training and testing errors versus testing set fraction
plotRMSErrors(hidden_array, tot_test_errors, tot_valid_errors)
def plotRMSErrors(hidden_array, tot_testing_errors, tot_valid_errors):
plt.clf()
plt.plot(hidden_array, tot_testing_errors, label="testing rmse")
plt.plot(hidden_array, tot_valid_errors, label="validation rmse")
plt.ylabel("RMS Error")
plt.xlabel("Hidden Units")
plt.legend(('testing rmse', 'validation rmse'))
plt.show()
#prefer to explicitly call my main()
if __name__ == '__main__':
main()
|
4873b1523737be173f42e3ee000d0e52cd9e47a5 | alqamahjsr/InterviewBit-1 | /07_DynamicProgramming/ways_to_color_a_3xN_board.py | 1,019 | 3.59375 | 4 | # Ways to color a 3xN Board
# https://www.interviewbit.com/problems/ways-to-color-a-3xn-board/
#
# Given a 3Xn board, find the number of ways to color it using at most 4 colors such that no two adjacent boxes have same color. Diagonal neighbors are not treated as adjacent boxes.
# Output the ways%1000000007 as the answer grows quickly.
#
# 1<= n < 100000
#
# Example:
# Input: n = 1
# Output: 36
#
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
class Solution:
# @param A : integer
# @return an integer
def solve(self, A):
color2, color3 = 12, 24
for i in range(2, A + 1):
temp = color3
color3 = (11 * color3 + 10 * color2) % 1000000007
color2 = (5 * temp + 7 * color2) % 1000000007
return (color2 + color3) % 1000000007
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
if __name__ == "__main__":
s = Solution()
print(s.solve(1)) |
05a8b827dac2bc41fe3849cf1aaed04cf3e5d55f | JaydeepKachare/Python-Classwork | /Session4/functions /Functions.py | 936 | 3.9375 | 4 | # Functions.py
# 1 : function accept nothing and return nothing
def fun() :
print("function fun")
# 2 : function accept parameter and return nothing
def gun(no) :
print("function gun with paramter : " ,no)
# 3 : function accept paramter and return value
def sun(no):
print("function sun with parameter : ",no)
return no+1
# 4 : function accepts multiple values and return multiple values
def AddSub (num1, num2) :
add = num1 + num2
sub = num1 + num2
return num1,num2
# 5 : nested function definition
def marvellous() :
print("inside marvellous")
def infosystem() :
print("inside infosystem")
infosystem()
def main() :
fun()
gun(11)
ret = sun(10)
print("return value of sun is : ",ret)
add,sub = AddSub(30,20)
print("Addition : ",add)
print("Subtraction : ",sub)
marvellous()
if __name__ == "__main__" :
main() |
ce3f80e4614504a971c2a170d643fe098c67207c | dansoh/python-intro | /python-crash-course/exercises/chapter-6/6-10-favorite-numbers.py | 252 | 3.671875 | 4 | favorite_numbers = {
'daniel' : [28, 69],
'anthony' : [4, 14, 25],
'alex' : [9, 24, 35],
}
for name, numbers in favorite_numbers.items():
print("\n" + name.title() + "'s favorite number is:")
for number in numbers:
print("\t" + str(number))
|
e05a8770ace02f25048ea1f02550d2d575b3416d | cgdaker/si475 | /final/state.py | 4,855 | 3.53125 | 4 | class State:
# takes in a position and a disctionary of balloon locations
def __init__(self, position, balloons, goal, parent=None, priority=1000):
self.position = position
self.balloons = balloons
self.goal = goal
self.parent = parent
self.visited = False
self.g = 0
self.priority = priority
# returns list of all possible states
def get_possible_states(self):
# list to return
to_return = []
#near_balloons = {}
for state in self.drive_to():
#print(state.to_string())
to_return.append(state)
#print(self.to_string())
for state in self.pick_up():
#print(state.to_string())
to_return.append(state)
for state in self.put_down():
#print(state.to_string())
to_return.append(state)
return to_return
def put_down(self):
to_return = []
# check if near enough goal location to put down
for key in self.goal.balloons:
if self.balloons[key] != None:
continue
if self.get_distance(self.goal.balloons[key]) < 1:
put_down = self.balloons.copy()
put_down[key] = self.position
ret = State(self.position, put_down, self.goal)
#print(ret.to_string())
to_return.append(ret)
return to_return
def drive_to(self):
to_return = []
# find all other positions can go to
for key in self.balloons:
if (self.balloons[key] == None):
continue
if (self.get_distance(self.balloons[key]) < .5):
continue
toreturn = State(self.balloons[key], self.balloons, self.goal)
#print(toreturn.to_string())
to_return.append(toreturn)
for key in self.goal.balloons:
# make sure it doesn't keep driving to same state
if (self.get_distance(self.goal.balloons[key]) < .5):
continue
toreturn = State(self.goal.balloons[key], self.balloons, self.goal)
to_return.append(toreturn)
return to_return
def to_string(self):
return str(self.position) + ': ' + str(self.balloons)
def pick_up(self):
to_return = []
# check if space to pick up
count = 0
for key in self.balloons:
if self.balloons[key] == None:
count += 1
# if greater than one skip
if count < 2:
# check if near a balloon to pick up
for key in self.balloons:
if (self.balloons[key] == None):
continue
# check if can pick up
if self.get_distance(self.balloons[key]) < 1:
# set position of balloon to none to show its being carried
pick_up = self.balloons.copy()
pick_up[key] = None
ret = State(self.position, pick_up, self.goal)
#print(ret.to_string())
to_return.append(ret)
return to_return
def __lt__(self, other):
return self.priority < other.priority
# returns distance from goal state
# returns -1 if this is goal state
def get_heuristic(self):
# get total distance from each balloon to ideal balloon
total = 0
for key in self.balloons:
current = self.balloons[key]
goal = self.goal.balloons[key]
# check if already being carried
if current == None:
current = self.position
#continue
diff = (current[0] - goal[0]) ** 2
diff += (current[1] - goal[1]) ** 2
diff = (diff ** .5) / 2
total += diff
if total < .5:
return -1
return total
# returns distance between two states
def get_distance(self, position):
to_return = (self.position[0] - position[0]) ** 2
to_return += (self.position[1] - position[1]) ** 2
return to_return ** .5
# start and end state, nodelist
# balloons = { 'B': (7,4), 'A': (10, 10), 'C': (100,100) }
# goal_balloons = { 'B': (3,3), 'A': (5,5), 'C': (50,50) }
#
# goal = State ( (0,0), goal_balloons, None, None)
# start = State( (3,3), balloons, goal, None)
# list = start.put_down()
# for state in list:
# print(state.to_string())
# balloons = { 'B': None, 'A': (10, 10), 'C': (100,100) }
# goal_balloons = { 'B': (3,3), 'A': (5,5), 'C': (50,50) }
# #
# goal = State ( (0,0), goal_balloons, None, None)
# start = State( (3,3), balloons, goal, None)
# for state in start.get_possible_states():
# print(state.position)
# print(state.balloons)
# print('\n')
|
27b4b5c852d38f427ff5cb18f837c4971fd9718a | theindianczar/VirtEnvProj | /ageINput.py | 161 | 3.953125 | 4 | name= input("hello what is your name")
print("hello",name)
print('so',name,'how old are you')
age = input()
age = int(age)
print('next year you would be ',age+1) |
ac157d48861cc0863114adffa3aae0a00ad3f691 | sachin-rajput/ctci-v6-solutions | /ch1_Arrays_Strings/q1.2.py | 1,051 | 3.921875 | 4 | # Question:
# Given two strings, write a method to decide if one is a permutation of the other.
# Runtime: O(n * log n)
def isPermutation1(str1, str2):
if len(str1) != len(str2):
return False
# Runtime for sorted here is O(n log n)
if(''.join(sorted(str1)) != ''.join(sorted(str2))):
return False
return True
NO_OF_CHARS = 256
# Runtime: O(n)
def isPermutation2(str1, str2):
if len(str1) != len(str2):
return False
# Let's keep a count of each
# character occurence
charList1 = [0] * NO_OF_CHARS
charList2 = [0] * NO_OF_CHARS
# Increment counters for str1
for x in str1:
charList1[ord(x)] += 1
# Increment counters for str2
for x in str2:
charList2[ord(x)] += 1
# Loop over NO_OF_CHARS and check
# if there is mismatch on counters
for x in range(NO_OF_CHARS):
if(charList1[x] != charList2[x]):
return False
return True
print(isPermutation1('scahin','sachin'))
print(isPermutation2('scahin','sachio')) |
bc53b4178d8f954149112b8694b5c5987328a39c | SamMorton123/26.2-app | /src/components/trackrankings.py | 1,706 | 3.734375 | 4 | '''
Streamlit "component" for rendering
track rankings.
Sam Morton, TwentySix.Two
January 26, 2020
'''
import pandas as pd
import plotly.graph_objects as go
import streamlit as st
# constants
CURR_YEAR = 2020
TABLE_WIDTH = 1350
TABLE_HEIGHT = 700
def TrackRankings(selected_event):
'''
Render most recent track rankings.
'''
# load most recent rankings for selected event
selected_event_altered = selected_event.replace("'", '').replace(' ', '_').lower()
event_filename = f'data/generated_ratings_data/{selected_event_altered}_{CURR_YEAR}.csv'
df = pd.read_csv(event_filename)
# reformat data for viewing
df = df[df['Most Recent Race Date'] >= CURR_YEAR - 2]
df = df.drop(columns = ['Most Recent Race Date'])
df = df[df['Number Of Races'] > 2]
df = df.iloc[0: 20, :]
df['Rating'] = [round(score - 1500, 2) for score in df['Rating']]
df.columns = ['athlete', 'rating', 'num_races', 'nationality', 'dob']
df.index = list(range(1, len(df.index) + 1))
# create figure
fig = go.Figure(
data = [go.Table(
header = dict(
values = ['Rank', 'Athlete', 'Rating', 'Number of Races', 'Nationality', 'Date of Birth'],
fill_color = '#D03737',
font = dict(color = 'white')
),
cells = dict(
values = [
df.index, df.athlete, df.rating, df.num_races, df.nationality, df.dob
],
fill_color = 'white'
)
)],
layout = dict(
width = TABLE_WIDTH,
height = TABLE_HEIGHT
)
)
# render plotly figure
st.plotly_chart(fig)
|
4c436cea3e57a5a0a05e8518efa5b7f9a3ef3867 | pony6666/100--master | /untitled0.py | 155 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jun 9 08:58:56 2019
@author: malin
"""
def f(x):
x=x+1
print('inf(x):x=',x)
return x
x=3
z=f(x) |
dbd150d851ffa03cdcb4a2b65714f573a9e1658a | SabithaSubair/Luminar_PythonDjangoProjects_May | /collections/list/divisbleby8_listcomprhnsion.py | 227 | 3.609375 | 4 | # ls=[i for i in range(1,1000) if i%8==0]
# print("Even number between 1 to 1000 is:",ls,"\n","count is:",len(ls))
ls=[i for i in range(1,1000) if i%5==0]
print("Even number between 1 to 1000 is:",ls,"\n","count is:",len(ls)) |
1047408bf92a17308f8257b05f648ac1663b9bce | ksrntheja/08-Python-Core | /venv/oops/102HierarchicalInheritance.py | 789 | 3.75 | 4 | class P:
def p01(self):
print('Parent p01 method')
class C1(P):
def c1m01(self):
print('Child c1m01 method')
class C2(P):
def c2m01(self):
print('Child c2m01 method')
print('C1')
c1 = C1()
c1.p01()
c1.c1m01()
# c1.c2m01()
# Traceback (most recent call last):
# File "/Code/venv/oops/102HierarchicalInheritance.py", line <>, in <module>
# c1.c2m01()
# AttributeError: 'C1' object has no attribute 'c2m01'
print('C2')
c2 = C2()
c2.p01()
# c2.c1m01()
# Traceback (most recent call last):
# File "/Code/venv/oops/102HierarchicalInheritance.py", line <>, in <module>
# c2.c1m01()
# AttributeError: 'C2' object has no attribute 'c1m01'
c2.c2m01()
# C1
# Parent p01 method
# Child c1m01 method
# C2
# Parent p01 method
# Child c2m01 method
|
4a2c0ee05278589197b0e8333c1781d335a9445b | AndersonHJB/Student_homework | /xiaokai/课堂代码/01-函数的定义/def_fun02.py | 419 | 3.796875 | 4 | # -*- coding: utf-8 -*-
# @Time : 2021/6/9 9:18 上午
# @Author : AI悦创
# @FileName: def_fun02.py.py
# @Software: PyCharm
# @Blog :http://www.aiyc.top
# @公众号 :AI悦创
def HelloUser(username=None, age=None):
result = "hello {}, age: {}".format(username, age)
# print(result)
return result
a = HelloUser(age=18, username="aiyc")
print(a)
str1 = "aiyc"
a = str1.replace("a", "lll")
# print(a) |
bb3ff06321788546a36d9b07219581dec9d473d4 | anivicks/nanotech | /MyPython/timetable.py | 343 | 3.796875 | 4 | table = [1, 2, 3, 4, 5]
for x in range(1, 11):
multitable = []
for y in table:
pro = x * y
multitable.append(pro)
print(multitable)
for x in range(1, 11):
multitable = []
multitable.append(x)
for y in range(4):
x += multitable[0]
multitable.append(x)
print(multitable) |
37a7da81f3bf35aec7a4600333721b1cb4e1aeda | Malvyn/DL | /DL2(Teacher-Fang)/p40_24points.py | 2,355 | 3.59375 | 4 |
import numpy as np
def get_random_numbers(num, minimum, maximum):
return np.random.randint(minimum, maximum, [num])
def get_values(numbers):
"""
:param numbers: a list of the numbers which is great than zero
:return: a list of the tuples of (value, exp) that the numbers can compose with addition(+), subtraction(-),
multiplication(*) and/or division(/), as well as any number of paranthesis.
"""
if len(numbers) == 1:
return [(numbers[0], str(numbers[0]))]
result = []
for i in range(1, len(numbers)):
for left_params in get_params_list(numbers, i):
right_params = get_right_params(numbers, left_params)
left = get_values(left_params)
right = get_values(right_params)
for left_value, left_exp in left:
for right_value, right_exp in right:
result.append((left_value + right_value, '(' + left_exp + ' + ' + right_exp + ')'))
result.append((left_value - right_value, '(' + left_exp + ' - ' + right_exp + ')'))
result.append((right_value - left_value, '(' + right_exp + ' - ' + left_exp + ')'))
result.append((left_value * right_value, left_exp + ' * ' + right_exp))
if right_value != 0:
result.append((left_value / right_value, left_exp + ' / ' + right_exp))
if left_value != 0:
result.append((right_value / left_value, right_exp + ' / ' + left_exp))
return result
def get_right_params(numbers, left_params):
return [e for e in numbers if e not in left_params]
def get_params_list(numbers, num):
if num == 0:
yield []
elif len(numbers) == num:
yield [e for e in numbers]
else:
first = numbers[0]
rest = numbers[1:]
for params in get_params_list(rest, num-1):
yield [first] + params
if num <= len(rest):
for params in get_params_list(rest, num):
yield params
if __name__ == '__main__':
numbers = get_random_numbers(4, 1, 20)
print(numbers)
for value, exp in get_values([2, 3, 7]):
print(value, ',', exp)
print('-' * 200)
for value, exp in get_values(numbers):
if value == 24:
print(exp, '=', 24)
|
dec458417c5e072b512c2771974bbad951d6dd55 | Mikhail-Khanaev/Tic-tac-toe | /tic-tac-toe.py | 3,862 | 3.609375 | 4 | # Внешний вид игрового поля
field = [
[' ', '0', '1', '2'],
['0', '-', '-', '-'],
['1', '-', '-', '-'],
['2', '-', '-', '-']]
move = "O" # Переменная, которая отвечает за то, чей сейчас ход, первые всегда ходят крестики
Flag = False # Флаг, который будет меняться после выполнения условий в бесконечном цикле
counter = 0 # Счётчик, который будет считать количество ходов, если он будет равняться 9, то будет ничья
# Вывод в консоль игрового поля
def field_form():
for x in field:
print(x[0], x[1], x[2], x[3])
# Ход
def token_input():
i = input("Введите номер столбца: ")
j = input("Введите номер строки: ")
print()
if (i in "012") and (j in "012"): # Если значения не выходят из допустимого предела, выполнится код ниже
if (field[int(j) + 1][int(i) + 1] == "-"):
field[int(j) + 1][int(i) + 1] = move
else:
print("Клетка занята", "Попробуйте ещё раз", sep="\n")
token_input()
else: # Если значения выходят из допустимого предела, выполнится код ниже, который предложит игроку попробовать снова
print("Вы ввели несуществующий номер поля", "Попробуйте ещё раз", sep="\n")
token_input()
# бесконечный цикл, который прервётся только в случае победы или ничьи
field_form() # Генерация игрового поля
while True:
if move == "O":
move = "X"
else:
move = "O"
if (Flag == False):
print()
if (counter == 9):
print("Ничья")
break
print()
counter += 1
print(f"Сейчас ходит {move}")
token_input()
field_form()
elif (Flag == True):
if move == "O": # тут какая-то путаница короче, пусть будет вот такой костыль
move = "X"
else:
move = "O"
print(f"Выиграл {move}")
break
# условия для победы
if field[1][1] == field[1][2] == field[1][3] == move: # вся первая строка по горизонтали
Flag = True
elif field[2][1] == field[2][2] == field[2][3] == move: # вся вторая строка по горизонтали
Flag = True
elif field[3][1] == field[3][2] == field[3][3] == move: # вся третья строка по горизонтали
Flag = True
elif field[1][1] == field[2][1] == field[3][1] == move: # вся первая строка по вертикали
Flag = True
elif field[1][2] == field[2][2] == field[3][2] == move: # вся вторая строка по вертикали
Flag = True
elif field[1][3] == field[2][3] == field[3][3] == move: # вся третья строка по вертикали
Flag = True
elif field[1][1] == field[2][2] == field[3][3] == move: # по диагонали с левого верхнего в правый нижний
Flag = True
elif field[3][1] == field[2][2] == field[1][3] == move: # по диагонли с левого нижнего в правый верхний
Flag = True
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.