blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
2564b805465fe17ed12affabc466e7420fc8d1c3 | iamsabhoho/PythonProgramming | /Q1-3/WUP#12/reversingwords.py | 150 | 4.3125 | 4 | #Write a Python program that accept a word from the user and reverse it using for loops.
for j in range(len(i)-1, -1, -1):
s = i[j]
print(s)
|
d6d026988df36a63136417082122ec0053e91bfc | iamsabhoho/PythonProgramming | /Q1-3/key.py | 3,521 | 4.28125 | 4 | def get_alphabet():
"""
This function returns the alphabet in a list
:return: list
"""
alphabet = list()
for a in range(26):
alphabet.append(chr(97+a))
return alphabet
def cipher_alphabet(key='meowc'):
"""
Creates the cipher alphabet with the key provided
:param key: string
:return cipher: list
"""
#Convert the key to list, add it to cipher
#cipher = list(key)
alphabet = get_alphabet()
'''
for a in alphabet:
if a not in key:
cipher.append(a)
'''
cipher = list(key) + [a for a in alphabet if a not in key]
'''
cipher_d = dict()
for a, c in zip(alphabet, cipher):
cipher_d[a] = c
'''
cipher_d = {a:c for a, c in zip(alphabet, cipher)}
return cipher_d
def encrypt(msg, key='meowc'):
"""
Encrypts the msg using the key provided
:param msg: string
:param key: string
:return encrypted_msg: string
"""
#cipher alphabet
cipher = cipher_alphabet(key)
encrypted_msg = ''
for s in msg.lower():
encrypted_msg += cipher.get(s, s)
return encrypted_msg
def decrypt(encrypted_msg, key='meowc'):
cipher = cipher_alphabet(key)
reversed_cipher = {v:k for k, v in cipher.items()}
msg = ''
for s in encrypted_msg:
msg += reversed_cipher.get(s,s)
return msg
i = cipher_alphabet()
print(i)
print(decrypt('''ifz cda qmvmpdi ecdpdetmpfqtfeq tcdt jdam cmp queemqqsui fk ifsm.
tcmqm ecdpdetmpfqtfeq nplnmiima cmp tcplubc tmppfrim elkaftflkq fk cmp ecfiaclla,
ifvfkb fk ecdlq, smdp, dka mvmk qussmpfkb splj bpmdt ilqqmq.
tcm ecdpdetmpfqtfeq qcm nlqqmqqmq dpm slpbfvmkmqq dka rpdvmkmqq.
tcmqm ecdpdetmpfqtfeq ecdkbma fk afssmpmkt jdbkftuamq dq ifz bpmw liamp;
kmvmptcmimqq, tcmqm nplbpmqqflk fk ifzq ecdpdetmp diilwma cmp tl amdi wftc
qftudtflkq eimvmpiy, rut fq diql drim tl jlvm lk fk cmp lwk ifsm wcmk sdefkb
tcm dryqq ls ifsm, fk alfkb cmp vmpy rmqt fk decfmvfkb bpmdt bldiq dka rmttmp tcfkbq,
pmbdpaimqq ls ltcmpq kmbdtfvm fksiumkemq.'''))
print()
print(encrypt('''I have a dog, two cats, two tortoises, and a tank of fish. Once I had a mouse but it
ran away long time six years ago. Tomorrow is my dog's eighth year-old birthday. Although
she is getting old, but she still act like kid running around all the time with the cats.
And most of the time she run just to catch the cats. Mentioned about cats, I had the first
cat last year March. He was two weeks old then, and was weighted less than one kilogram.
Now he is about one and a half year-old but he is now six and a half kilograms!!! I am afraid
that he will get too fat in the future T^T'''))
def cici(c):
c = list()
for i in range(7893600):
print(c)
cici('''ifz cda qmvmpdi ecdpdetmpfqtfeq tcdt jdam cmp queemqqsui fk ifsm.
tcmqm ecdpdetmpfqtfeq nplnmiima cmp tcplubc tmppfrim elkaftflkq fk cmp ecfiaclla,
ifvfkb fk ecdlq, smdp, dka mvmk qussmpfkb splj bpmdt ilqqmq.
tcm ecdpdetmpfqtfeq qcm nlqqmqqmq dpm slpbfvmkmqq dka rpdvmkmqq.
tcmqm ecdpdetmpfqtfeq ecdkbma fk afssmpmkt jdbkftuamq dq ifz bpmw liamp;
kmvmptcmimqq, tcmqm nplbpmqqflk fk ifzq ecdpdetmp diilwma cmp tl amdi wftc
qftudtflkq eimvmpiy, rut fq diql drim tl jlvm lk fk cmp lwk ifsm wcmk sdefkb
tcm dryqq ls ifsm, fk alfkb cmp vmpy rmqt fk decfmvfkb bpmdt bldiq dka rmttmp tcfkbq,
pmbdpaimqq ls ltcmpq kmbdtfvm fksiumkemq.''')
|
60140c55c6e6b002931c8fe16280ce14bed7186c | iamsabhoho/PythonProgramming | /Q1-3/MasteringFunctions/PrintingMenu.py | 713 | 4.21875 | 4 | #Write a function for printing menus in the terminal.
#The input is a list of options, and the output is the option selected by the user.
print('The options are: ')
#list = input()
#menu = ['Meat','Chicken','Fish']
menu = []
print(menu)
print()
def options(menu):
menu = input('Please enter the options: ')
for i in range(len(menu)):
option = i + 1
print(str(option) + menu[i])
user = input('What is your preference? Press X to exit: ')
if user == 'x':
exit()
elif user == '1':
print(menu[0])
return user
elif user == '2':
print(menu[1])
return user
else:
print(menu[2])
return user
return user
options()
|
c7c547252f8deb024b850f43dea0e73c3e8d849f | iamsabhoho/PythonProgramming | /Q1-3/WUP#7/Driving.py | 1,121 | 4.375 | 4 | #You are driving a little too fast, and a police officer stops you. Write an script that computes the result as “no ticket”, “small ticket”, and “big ticket”. If speed is 60 or less, the result is “no ticket”. If speed is between 61 and 80 inclusive, the result is “small ticket”. If speed is 81 or more, the result is “big ticket”. Unless it is your birthday -- on that day, your speed can be 5 higher in all cases. The input of the script in your speed and a boolean variable that indicates if it is your birthday.
import sys
print('The arguments passed were(birthday?/speed?): ')
print(sys.argv)
birthday = str(sys.argv[1])
speed = float(sys.argv[2])
#see if it is the driver's birthday
if birthday == str('yes'):
if 0 <= float(speed) <= 65:
print('No ticket.')
elif 66 <= float(speed) <= 85:
print('Small ticket.')
elif 86 <= float(speed):
print('Big ticket.')
else:
if 0 <= float(speed) <= 60:
print('No ticket.')
elif 61 <= float(speed) <= 80:
print('Small ticket.')
elif 81 <= float(speed):
print('Big ticket.')
|
c514760a50455fecbfc23ce0c8efc4749bcd14d5 | lyubomyrr/For_test | /Class work 2.py | 1,096 | 4.03125 | 4 | #for i in range(0, 100, 2):
# print(i)
# for i in range(1, 100, 2):
# print(i)
# if i == 5:
# break
# print(i)
#print ("end")
# list_number=[2,4,5,8,9,10]
#contain_odd=False
#for item in list_number:
# if not item % 2==0:
# contain_odd=True
# break
#if contain_odd:
# print ("there are odd numbers in the list")
#else :
# print("there are only even numbers in the list ")
#list_number=[2,4,5,8,9,10]
#contain_odd=False
#for item in list_number:
# if not item % 2==0:
# contain_odd=True
# break
#if contain_odd:
# print ("there are odd numbers in the list")
#else :
# print("there are only even numbers in the list ")
#list_number= [32,52,12,52]
#i=0
#for a in list_number:
# list_number[i] =float(a)
# i = i + 1
# print (list_number)
#list_number=["433","banana","chary","tomato"]
#for x in list_number:
# for j in x:
# print(j,end="#")
# print ()
#list_number=[0, 1, 1, 2 ,3 , 5, 8, 13]
#n=input("enter ")
#while n == list_number:
# if n==3:
# break
#print ()
|
31b72e290f02aaf458ae7f3689a383bb8edcaa96 | lyubomyrr/For_test | /clas_work_3.py | 1,597 | 4.0625 | 4 | # my_list = [int(input("Enter int {}: ".format(i+1))) for i in range(10)]
# print(" Max number is:", max(num_list))
# print(" Min number is:", min(num_list))
# print(my_list)
#or
# amount_of_numbers=int(input('Input amount of numbers\n'))
# list_of_numbers=[int(input('input number\n')) for i in range(amount_of_numbers)]
# print('max number in input list is {}\nmin number in input list is {}'. format(max(list_of_numbers),min(list_of_numbers)))
#Розширено
# nums = []
# k=int(input("Please enter the count of the elements of sequence: "))
# for i in range(k):
# n = int(input("Please enter the element: "))
# nums.append(n)
# print(nums)
# max = nums[0]
# min = nums[0]
# for i in range(k):
# if nums[i] > max:
# max = nums[i]
# if nums[i] < min:
# min = nums[i]
# #print("Maximum number = %d. Minimum number = %d." %(max, min))
# print("Maximum number = {}. Minimum number = {}.".format(max, min))
# for x in range(1, 11):
# if x % 2==0:
# print(X, 'is even ,ultiple of 2')
# elif x % 3==0:
# print (x, 'is an odd multiple of 3')
# else:
# print(x, 'not divisible by 2 and 3')
#number=int(input("Введіть ціле додатнє число: "))
#factorial=1
#for i in range(1,number+1):
# factorial*=i
#print("Факторіал числа",number,"дорівнює",factorial)
user_name = input('enter your login: ')
while user_name!='first':
print("eror:wrong")
user_name=input('Username')
print (user_name)
print ("welcome")
.
|
cbed7ee6660fa870e613ec09ba30a5b938243897 | adamkerz/akData | /akData/format/number.py | 1,497 | 3.796875 | 4 | from decimal import Decimal
def formatDollars(d,noneValue='',zeroValue='$0'):
"""Formats a number as a whole dollar value with alternatives for None and 0."""
if d is None:
return noneValue
elif d==0:
return zeroValue
return '${:.0f}'.format(d)
def formatDollarsCents(d,noneValue='',zeroValue='$0.00'):
"""Formats a number as a dollar and cent value with alternatives for None and 0."""
if d is None:
return noneValue
elif d==0:
return zeroValue
return '${:.2f}'.format(d)
def formatInteger(n,noneValue='',zeroValue='0'):
"""Formats an integer with alternatives for None and 0."""
if n is None:
return emptyValue
elif n==0:
return zeroValue
return '{:d}'.format(n)
def formatDecimal(n,precision,noneValue='',zeroValue='0'):
"""Formats a decimal with alternatives for None and 0."""
if n is None:
return emptyValue
elif n==0:
return zeroValue
return '{:.{}f}'.format(n,precision)
def formatPercentage(n,outOf,decimalPlaces=0,noneValue='',zeroValue='0%'):
"""Formats a percentage with alternatives for None and 0."""
if n is None:
return emptyValue
elif n==0:
return zeroValue
if not isinstance(n,Decimal): n=Decimal('{}'.format(n))
if not isinstance(outOf,Decimal): outOf=Decimal('{}'.format(outOf))
percent=n*100/outOf
return '{:0.{}f}%'.format(percent,decimalPlaces)
|
702a9b9f74e2bf5b5ec5751965f2e6e8d2c9400b | AlexandraKar/Alexandra-Karaseva | /python%20homework/hw4.py | 73 | 3.84375 | 4 | s = input('enter a word:')
for i in range(len(s)):
print(s[:i+1])
|
6b14b65dcf792f2c6525bd2341f360fe5a110849 | alvercau/dsp | /python/advanced_python_dict.py | 2,152 | 3.59375 | 4 | import pandas as pd
from collections import defaultdict
faculty_dict = defaultdict(list)
# Q6
with open("faculty.csv") as f:
data = pd.read_csv(f)
data = data.rename(columns=lambda x: x.strip())
df = data['name'].str.rsplit(' ', expand=True, n=1)
data = data.join(df[1])
data = data.ix[:, ['degree', 'title', 'email', 1]]
data[2] = data[['degree', 'title', 'email']].values.tolist()
data_needed = data[[1,2]]
for row in data_needed.itertuples():
faculty_dict[row[1]].append(list(row[2]))
print {k: faculty_dict[k] for k in faculty_dict.keys()[:3]}
# Q7
with open("faculty.csv") as f:
data = pd.read_csv(f)
data = data.rename(columns=lambda x: x.strip())
df = data['name'].str.rsplit(' ')
names = []
professor_dict = defaultdict(list)
for row in df:
if len(row) == 3:
row = row[::2]
names.append(row)
else:
names.append(row)
tuple_names = [tuple(name) for name in names]
data['name_clean'] = tuple_names
data = data.ix[:, ['degree', 'title', 'email', 'name_clean']]
data['info'] = data[['degree', 'title', 'email']].values.tolist()
data_needed = data[['name_clean','info']]
for row in data_needed.itertuples():
professor_dict[row[1]] = (row[2])
print {k: professor_dict[k] for k in professor_dict.keys()[:3]}
# Q8
with open("faculty.csv") as f:
data = pd.read_csv(f)
data = data.rename(columns=lambda x: x.strip())
df = data['name'].str.rsplit(' ')
names = []
professor_dict = defaultdict(list)
for row in df:
if len(row) == 3:
row = row[::2]
names.append(row[::-1])
else:
names.append(row[::-1])
tuple_names = [tuple(name) for name in names]
data['name_clean'] = tuple_names
data = data.ix[:, ['degree', 'title', 'email', 'name_clean']]
data['info'] = data[['degree', 'title', 'email']].values.tolist()
data_needed = data[['name_clean','info']]
for row in data_needed.itertuples():
professor_dict[row[1]] = (row[2])
print {k: professor_dict[k] for k in professor_dict.keys()[:3]} |
aa2886b2e59bc35ce98e9f7f89b398b7c8c31972 | naviroa92/prueba1 | /Guia 1 - Pandas.py | 4,378 | 3.796875 | 4 | # Ejercicio 1
import ast
import pandas as pd
import re
df_books = pd.read_csv("data/books.csv", dtype={'postal_code': str},
converters={'books': ast.literal_eval})
df_ratings = pd.read_csv("data/books_rating.csv")
print('')
print('')
print('|' * 50)
print( 'DF_BOOKS.INFO - ORIGINAL')
print('|' * 50)
print('')
print('')
df_books.info()
df_books_original = df_books.copy()
df_ratings_original = df_ratings.copy()
print('')
print('*' * 50)
print('EJERCICIO 1 ')
print('Se establece que la columna (name) es un identificador, por lo cual'
'se procede a eliminar la columna con df_books = df_books.drop ')
print('*' * 50)
#Se elimina la columna 'name', ya que se considera un diferenciador.
df_books = df_books.drop(columns=['name'])
print('|' * 50)
print('DATA FREAME SIN COLUMNA NAME - INFO')
print('|' * 50)
print('')
print(df_books.info())
#Ejercicio 2
print('')
print('*' * 50)
print('EJERCICIO 2 ')
print('*' * 50)
print('')
print('Para este ejercicio convertimos el df_books y el df_ratings en un diccionario para '
'iterar entre diccionarios y hacer la respectiva comparacion')
print('')
print('Creamos el diccionario d_users, la cual recibe los valores (user_ide / name) de '
'la comparacion del valor de la llave (books - d_books) y el valor de (d_ratinds), cuando estos sean iguales'
'se almacenaran en la valriable (d_users) ')
#Codido para convertir df_books en un diccionario
d_books=df_books_original.to_dict('index')
#Codido para convertir df_rating en un diccionario
d_ratings = df_ratings.groupby(['user_id'])['book'].apply(lambda grp: list(grp.value_counts().index)).to_dict()
d_ratings_2=df_ratings_original.to_dict('index')
print()
print()
print('|' * 50)
print( 'D_BOOKS DICCIOANRIO')
print('|' * 50)
print()
print(d_books)
print()
print('|' * 50)
print('D_RATINGS DICCIONARIO')
print('|' * 50)
print()
print(d_ratings)
d_users = []
for d_books_key, d_books_value in d_books.items():
for d_ratings_key, d_ratings_value in d_ratings.items():
if set(d_books_value['books']) == set(d_ratings_value):
one_user= {}
one_user['user_id'] = d_ratings_key
one_user['name'] = d_books_value['name']
d_users.append(one_user)
print()
print('|' * 50)
print('D_USERS DICCIONARIO')
print('|' * 50)
print(d_users)
#Ejericio 3
print('')
print('*' * 50)
print('EJERCICIO 3 ')
print('*' * 50)
print('')
print('Generamos un diccioanio donde se publica los valores (name - sex - age - postal_code - book - rating) con el'
'objetivo de dentificar el rating de cada libro por cada usuario')
print('')
print('')
d_users_name = []
for d_ratings_key, d_ratings_value in d_ratings.items():
for d_books_key, d_books_value in d_books.items():
for d_ratings_2_key, d_ratings_2_value in d_ratings_2.items():
if set(d_books_value['books']) == set(d_ratings_value): # Comparacion de listado de libros
if (d_ratings_key) == (d_ratings_2_value['user_id']): # comparacion id entre (id - libros ) / ( id - rating )
books_user= {}
books_user['name'] = d_books_value['name']
books_user['sex'] = d_books_value['sex']
books_user['age'] = d_books_value['age']
books_user['postal_code'] = d_books_value['postal_code']
books_user['book'] = d_ratings_2_value['book']
books_user['rating'] = d_ratings_2_value['rating']
d_users_name.append(books_user)
print('|' * 50)
print('d_users_name')
print('|' * 50)
print('')
print(d_users_name)
#Ejericio 4
print('')
print('*' * 50)
print('EJERCICIO 4 ')
print('*' * 50)
print('')
#https://stackoverflow.com/questions/56999525/how-to-mask-specific-values-in-particular-column-in-python
df_books['postal_code'] = df_books['postal_code'].apply(lambda s: re.sub(r"(\d{3})\d{2}",r"\1**",s))
print(df_books)
#Ejericio 5
print('')
print('*' * 50)
print('EJERCICIO 5 - RANK SWAPPING')
print('*' * 50)
print('')
df_books['age'] = df_books['age'].rank(ascending=False)
print('|' * 50)
print('df_books')
print('|' * 50)
print(df_books[['sex','age','postal_code']])
print('|' * 50)
print('df_books_original')
print('|' * 50)
print(df_books_original[['sex','age','postal_code']])
|
dbece212a7cbf94c2bc33dc0b26dee6c0933cb81 | ATLS1300/pc04-generative-section11-sydney-green | /PC04_GenArt.py | 2,373 | 4.1875 | 4 | """
Created on Thu Sep 15 11:39:56 2020
PC04 start code
@author: Sydney Green
This code creates two circle patterns from two seperate turtles.
This is different than my pseudocode as I struggled bringing that to life but I was
able to make something I liked so much more. Turtle 1 is a larger circle with larger
cirlces making it up and alternating colors. Turtle 2 is a smaller circle
made up of smaller cirlces containing different alternating colors as turtle 1. The
random aspect of this code is that each time that it is run the circles are located
in different places as the time before. The array of colors represented in each of the patterns
makes me feel warm and happy as both circles contain bright and vibrant color palettes.
"""
#Randomized Circle Dots
#Borrowed code helped me randomize the locations of the circle dots
#Borrowed code is from "Quick guide to random library" canvas assignment page
import turtle
import math, random
turtle.colormode(255)
panel = turtle.Screen().bgcolor('black')
T1large = turtle.Turtle()
#Turtle 1 has its name because it will create the larger circle pattern made of cirlcles
T2small = turtle.Turtle()
#Turtle 2 has its name because it will create the smaller circle pattern made of circles
T2small.shapesize(3)
T1large.width(2)
T2small.width(2)
T1large.speed(11)
T2small.speed(11)
T1large.goto(random.randint(0,250),random.randint(0,250))
#Turtle 1's goto is random. It's random because I want its location to change each time the code is ran.
#This first for loop creates many large circles that come together forming one large complete circle.
for i in range(10):
for colours in [(217,4,41), (220,96,46), (254,215,102), (104,163,87), (4,139,168)]:
T1large.color(colours)
T1large.down()
T1large.circle(50)
T1large.left(10)
T1large.up()
T2small.goto(random.randint(100,350),random.randint(100,350))
#Turtle 2's goto is random. It's random because I want its locaction to change each time the code is ran.
#This second for loop creates many small circles that come together forming one smaller complete circle.
for i in range(10):
for colours in [(138,234,146), (167,153,183), (48,102,190), (255,251,252), (251,186,114)]:
T2small.color(colours)
T2small.down()
T2small.circle(20)
T2small.left(10)
T2small.up()
turtle.done()
|
0da07a59dbb070270d770c8a0e940b35b36375e5 | nelvinpoulose999/Pythonfiles | /Fileio/filesop1.py | 180 | 3.578125 | 4 | f=open('news','r')
name=set()
for line in f:
words=line.rstrip('\n,.,,').split(' ')
for word in words:
name.add(word)
print(name)
for word in name:
print(word) |
64246927e8e7fe56a178fc96a7195abd755e3b49 | nelvinpoulose999/Pythonfiles | /oops/bankapplication.py | 871 | 4.0625 | 4 | class Bank:
bankname='SBK' # class variable/static variable it is used for reduce memory allocations
def create_account(self,accno,pname,minbalance):
self.accno=accno #}
self.personname=pname #} instance variable(self.accno,self.personname,etc
self.balance=minbalance #}
print(self.accno,self.personname,self.balance,Bank.bankname)
def deposit(self,amount):
self.balance+=amount
print(self.personname,'account credited with',amount,'the balance amount',self.balance)
def withdraw(self,amount):
if amount>self.balance:
print("insufficient balance")
else:
self.balance-=amount
print('account debited with', amount, 'the balance amount', self.balance)
obj = Bank()
obj.create_account(1000,'Akhil',3000)
obj.deposit(5000)
obj.withdraw(2000)
|
b6a1e7ea40436cb92ed481da960fa99573d7874a | nelvinpoulose999/Pythonfiles | /Fileio/fileop.py | 231 | 3.59375 | 4 | f=open("demofile","r") #path of file or file name ,operation
lst=[]
name=set()
for lines in f:
lst.append(lines.rstrip('\n')) #.rstrip used to strip the unwanted elements
name.add(lines.rstrip('\n'))
print(lst)
print(name)
|
1a796e09dad209f1957eb41e31da6173fcead274 | nelvinpoulose999/Pythonfiles | /LanguageFundamentals/flowcontrols/looping/primenumberfrom_nnumbers.py | 403 | 4.03125 | 4 | # prime numbers from 1-num
num=int(input("enter the limit"))
for i in range(1,num+1):# i=1,2
flag=0
for j in range (2,i):# (2,1),(2,2)
if(i%j==0):# 1%2==0-not equal,2%2==0,3%2==0-not equal
flag=1
break
else:
pass
if(flag==0):
print("the number is prime number", i)
else:
print("the number is not prime number")
|
15718d9d613431c7bb4b7ed189c3dae7e395c005 | nelvinpoulose999/Pythonfiles | /LanguageFundamentals/flowcontrols/decisionMaking/negitiveorpositive.py | 166 | 4.21875 | 4 | num = int(input("enter the number"))
if (num<0):
print("the number is negitive")
elif(num==0):
print("the number is zero")
else:
print("the number is positive") |
5e4da675ae102831a30af49576b89c665f7ed89c | nelvinpoulose999/Pythonfiles | /practice_prgms/factorial.py | 222 | 4.21875 | 4 | num=int(input('enter the number'))
factorial=1
if num<0:
print('no should be positive')
elif num==0:
print('the number is 1')
else:
for i in range (1,num+1):
factorial=factorial*i
print(factorial)
|
533cfd4eec3edea45929103b02d734dcc0e10fa8 | nelvinpoulose999/Pythonfiles | /pythoncollections/listprograms/patternprinting.py | 160 | 3.671875 | 4 | # print pattern
# 1
# 12
# 123
# 1234
for i in range(1,5): # row elements
for j in range(1,i+1): # column elements
print(j,end=' ')
print() |
3732aa440a8b2ff3c7ad30a50674a363078bea67 | nelvinpoulose999/Pythonfiles | /LanguageFundamentals/flowcontrols/looping/addpowers.py | 179 | 4.09375 | 4 | # print the output :123=1^3+2^3+3^3=36
num =int(input("enter the number"))
sum=0
while num!=0:
digit=num%10
print(digit)
sum=(digit**3)+sum
num=num//10
print(sum)
|
81541e01f3906af84b5a038418cacd75f156a9b5 | JuliaAlmaLuna/KexJobbProject | /relu.py | 361 | 3.796875 | 4 | import matplotlib.pyplot as plt
import numpy as np
data = [7, 1, 10, 0.5, 11, 4, 18, 13]
x = [1, 2, 3, 4, 5, 6, 7, 8]
y = np.multiply(x, 1.8)
plt.plot(x, data, '-', label='a)')
plt.plot(x, y, label='b)')
plt.plot(x, np.exp(x)*0.01 + 3, label='c)')
plt.scatter(x, data, c='k', label='data')
plt.title('Example of a Regression Problem')
plt.legend()
plt.show() |
9bfc470a0656f879c729e2963675c71f00c06d02 | mercury9181/data_structure_using_python | /factorial.py | 269 | 4.28125 | 4 | def factorial_using_recursion(n):
if n==0:
return 1
else:
return n * factorial_using_recursion(n-1)
number = int(input('enter the number: '))
result = factorial_using_recursion(number)
print("factorial of "+ str(number)+ " = " + str(result))
|
11fed74e0d762fca43c1f68b5bd99d89fda82d25 | IvyArbor/RightAtSchool | /readers/textreader.py | 459 | 3.828125 | 4 | class TextReader(object):
'''Reads lines of a file and splits them to the map'''
def __init__(self, stream, column_mapping):
self.stream = stream
self.column_mapping = column_mapping
def rows(self):
for line in self.stream.lines():
result = {}
for (name, start, end) in self.column_mapping:
val = line[start:end].strip()
result[name] = val
yield result
|
2e1aaaf780ba9b1b1d0c3c3a0b8f1eaf4105a4fe | timzk/AID1811 | /aid1811/pbase/Python/day18/super_init.py | 492 | 3.78125 | 4 | #显示调用基类的初始化方法__init__
class Human:
def __init__(self,n,a):
self.name = n
self.age = a
def show_info(self):
print("姓名:",self.name)
print("年龄:",self.age)
class Student(Human):
def __init__(self,n,a,s =0):
self.score = s
super().__init__(n,a) #显示调用父类的方法
def show_info(self):
super().show_info()
print("成绩:",self.score)
s = Student("小张",20)
s.show_info() |
ccc4603d3dfba8e23c7c567eb068d0a42e9ea8fb | timzk/AID1811 | /aid1811/pbase/Python/day15/myyield.py | 728 | 3.765625 | 4 | # #此示例示意生成器函数的创建和调用
def myyield():
yield 2 #一旦使用yield便是一个生成器函数
print("即将生成3")
yield 3
yield 5
yield 7
print("生成器生成结果")
gen = myyield() #调用生成器函数生成一个生成器
print(gen)#generator
it = iter(gen) #从生成器中获取一个迭代器
print(next(it)) #向迭代器要数据,此时生成器函数才会执行一步 ,打印2
print(next(it))
# def myyield():
# yield 2 #一旦使用yield便是一个生成器函数
# yield 3
# yield 5
# yield 7
# print("生成器生成结束")
# gen = myyield() #调用生成器函数生成一个生成器
# for x in gen:#generator
# print(x)
|
7a92486fe3f57a8cb23046c2a5802b882757c8f2 | timzk/AID1811 | /aid1811/pbase/Python/day18/class_method.py | 800 | 3.890625 | 4 | #此示例示意用类方法来访问类属性和改变类变量
#类方法是用于描述类的行为的方法,类方法属于类,不属于类的实例
class A:
v = 0 #类属性
@classmethod
def get_v(cls):
return cls.v
@classmethod
def set_v(cls,v):
cls.v = v
#类方法需要使用@classmethod装饰器定义
#类方法至少有一个形参,第一个形参用于绑定类,约定写为'cls'
# print(A.v)
# print(A.get_v())
# A.set_v(80)
# print(A.get_v())
# print(A.v)
#类和该类的实例都可以调用类方法
h1 = A()
h1.get_v() #cls,传递是h1.__class__
print(h1.get_v())
#类方法不能访问此类创建的对象的实例属性
h1 = A()
h1.v = 9999 #创建一个实例属性
h1.set_v(8888) #修改的是类的属性
print(A.get_v()) #打印8888 |
75a96f566ca8f2cfc5374bbf57069845505fdb60 | timzk/AID1811 | /aid1811/pbase/Python/day10/day10.py | 13,669 | 4 | 4 | # def f1():
# print("f1")
# def f2():
# print("f2")
# f1,f2 = f2,f1
# f1()
# def f1():
# print("f1函数被调用")
# def f2():
# print("f2函数被调用")
# def fx(fn): #<function f1 at 0x7f5c1282ef28>
# print(fn)#"f1函数被调用"
# fn()
# fx(f1)
# fx(print) #可以的,打印的是print的内建函数地址
# def myfun(fn):
# L=[1,3,5,7,9]
# return fn(L)
# print(myfun(max))
# print(myfun(min))
# print(myfun(sum))
#此示例示意函数可以返回另一个函数的引用关系
# def get_function():
# s = input("请输入你要做的操作")
# if s == '求最大':
# return max #如果成立返回的max,f绑定max,即max(L),返回10
# elif s == '求最小':
# return min #如果成立返回的max,f绑定min,即min(L),返回2
# elif s == '求和':
# return sum #如果成立返回的sum,f绑定sum,即sum(L),返回25
# else :
# return print
# L = [2,4,6,8,10]
# f = get_function() #f绑定函数get_function()函数的返回值
# print(f(L))
#-----------------------加减乘除运算
# def myadd(x,y):
# return x + y
# def mysub(x,y):
# return x -y
# def mymul(x,y):
# return x * y
# def get_func(op):
# if op == '+' or op == '加':
# return myadd
# elif op == '-' or op =='减':
# return mysub
# elif op == '*' or op =='乘':
# return mymul
# else :
# print("请输入合法的")
# def main():
# while True:
# s = input("请输入计算公式:")
# L = s.split(' ') #L=['10',加,'20']
# a = int(L[0])
# b = int(L[2])
# fn = get_func(L[1])
# print("结果是:",fn(a,b))
# main()
#-----------------------此示例示意函数嵌套定义
# def fn_outer():
# print("fn_outer被调用")
# def fn_inner(): #此函数是局部变量,在fn_outer()里面没有调用的时候不会执行此函数
# print("fn_inner被调用")
# print("fn_outer调用结束")
# fn_outer()
# print("程序结束")
# count = 0
# def hello(name):
# print('你好',name)
# global count #改变count的全局变量,然后使用
# count += 1
# hello('小张')
# while True:
# s = input('请输入姓名:')
# if not s:
# break
# hello(s)
# print("hello函数调用的次数是",count)
#此表达式创建一个函数,判断n这个数的2次方+1能否被5整除,如果能整除返回True,否则返回False
# fx = lambda n:(n**2+1)%5 == 0
# print(fx(3))
#此函数返回两个参数的最大值
# mymax = lambda x,y:max(x,y)
# print(mymax(300,200))
# print(mymax('ABC','123'))
# s = '''
# a = 100
# print(a)
# '''
# exec(s) #打印的是100
# 1. 看懂下面的程序在做什么? 高阶函数
# def fx(f, x, y):
# print(f(x, y),flush = True)
# fx((lambda a, b: a + b), 100, 200)
# fx((lambda a, b: a ** b), 3, 4)
# # 程序直到此处时有几个全局变量?
# 2. 写一个函数 mysum(x) 来计算:
# 1 + 2 + 3 + 4 + .... + x 的和,并返回
# (要求: 不允许调用sum函数)
# 如:
# print(mysum(100)) # 5050
# 方法1:
# def mysum(x):
# sum1 = 0
# for i in range(1,x+1):
# sum1 +=i
# return sum1
# print(mysum(100))
#3. 写一个函数myfac(n) 来计算n!(n的阶乘)
# n! = 1*2*3*4*...*n
# 如:
# def myfac(n):
# fac_ = 1
# for i in range(1,n+1):
# fac_ *= i
# return fac_
# print(myfac(7))
# print(myfac(5)) # 120
#递归方法
#4. 写一个函数计算 1 + 2**2 + 3**3 + ... + n**n的和
# (注: n给个小点的数)
# def m_sum(n):
# m = 0
# for i in range(1,n+1):
# m = i**i + m
# return m
# print(m_sum(4))
#-------函数式编程---------
# def fun(n):
# return sum(map(lambda x:x**x,range(1,n+1)))
# print(fun(3))
# 5. 实现有界面的学生信息管理程序
# 选择菜单如下:
# +-----------------------------+
# | 1) 添加学生信息 |
# | 2) 显示学生信息 |
# | 3) 删除学生信息 |
# | 4) 修改学生成绩 |
# | q) 退出 |
# +-----------------------------+
# 请选择: 1
# 学生信息和存储方法与原程序相同: 用列表里包含来存信息
# 要求: 每个功能写一个函数与之相对应
#---------------------------------------------------
# L = []# 创建一个列表,准备放字典
# def input_student():
# x = 0
# while True:
# n = input("请输入姓名: ")
# if n == '': # if not n:
# break
# a = int(input("请输入年龄: "))
# s = int(input("请输入成绩: "))
# nub = input("请输入编号: ")
# d = {} # 每次创建一个
# d['name'] = n
# d['age'] = a
# d['score'] = s
# d['nub'] = nub
# for i in L:
# if i['nub'] == nub:
# print("编号重复,请重新输入")
# x += 1
# if x == 0:
# L.append(d)
# return L
# def output_student(L):
# print("+---------------+----------+----------+----------+")
# print("| 姓名 | 年龄 | 成绩 | 编号 |")
# print("+---------------+----------+----------+----------+")
# print("+---------------+----------+----------+----------+")
# for d in L:
# sn = d['name']
# sa = str(d['age']) # 转为字符串,容易居中
# ss = str(d['score'])
# snub = d['nub']
# print("|%s|%s|%s|%s|" % (sn.center(14),
# sa.center(10),
# ss.center(10),snub.center(10)))
# print("+---------------+----------+----------+----------+")
# def del_student(s_nub):
# x = 0
# y = 0
# for i in L:
# if i['nub'] == s_nub:
# L.pop(x)
# print("删除成功")
# y += 1
# else :
# x+=1
# if y == 0:
# print("没有你输入的学生信息!")
# def change_student(s_chg):
# x = 0
# for i in L:
# if i['nub'] == s_chg:
# sa = input("请输入要修改的年龄:")
# ss = input("请输入要修改的成绩:")
# i['age'] = sa
# i['score'] = ss
# print("修改成功")
# x += 1
# if x == 0:
# print("没有找到你学生信息")
# def output_student_by_score_desc():
# def L_()
# return i['score']
# s = filter(L,key = L_)
# def main():
# while True:
# print('1) 添加')
# print('2) 显示 ')
# print('3) 删除 ')
# print('4) 修改 ')
# print('按学生成绩高~低显示学生信息')
# print('按学生成绩低~高显示学生信息')
# print('按学生年龄高~低显示学生信息')
# print('按学生年龄低~高显示学生信息')
# print('q) 退出')
# s = input("请选择: ")
# if s == '1':
# input_student()
# elif s == '2':
# # 显示学生信息:
# output_student(L)
# elif s == '3':
# #删除学生信息
# s_nub = input("请输入要删除的学生编号:")
# del_student(s_nub)
# elif s == '4':
# #修改学生成绩
# s_chg = input("请输入要修改的学生编号:")
# change_student(s_chg)
# elif s == '5':
# output_student_by_score_desc() # 分数降序
# elif s == '6':
# output_student_by_score_asc() # 分数升序
# elif s == '7':
# output_student_by_age_desc() # 年龄降序
# elif s == '8':
# output_student_by_age_asc() # 年龄升序
# elif s == 'q':
# break
# main()
# 1. 有一只小猴子,摘了很多桃.
# 第一天吃了全部桃子的一半,感觉不饱又吃了一个
# 第二天吃了剩下的一半,感觉不饱又吃了一个
# ... 以此类推
# 到第十天,发现只剩一个了
# 请问一天摘了多少桃子?
# day10 = 1
# day09 = (day10 + 1) * 2
# day08 = (day09 + 1) * 2
# day07 = (day08 + 1) * 2
# peach = 1 # 第十天的桃子数
# for day in range(9, 0, -1):
# peach = (peach + 1) * 2 # 算出当天的桃子数
# print("第", day, '天有', peach, '个桃')
#原理,第9天是第十天的两倍加上一个,第8天是第9天的两倍加上一个
# 3. 改写之前的学生信息管理程序,添加如下四个功能:
# | 5) 按学生成绩高~低显示学生信息 |
# | 6) 按学生成绩低~高显示学生信息 |
# | 7) 按学生年龄高~低显示学生信息 |
# | 8) 按学生年龄低~高显示学生信息 |
# def input_student():
# L = [] # 创建一个列表,准备放字典
# while True:
# n = input("请输入姓名: ")
# if n == '': # if not n:
# break
# a = int(input("请输入年龄: "))
# s = int(input("请输入成绩: "))
# d = {} # 每次创建一个
# d['name'] = n
# d['age'] = a
# d['score'] = s
# L.append(d)
# return L
# def output_student(L):
# print("+---------------+----------+----------+")
# print("| 姓名 | 年龄 | 成绩 |")
# print("+---------------+----------+----------+")
# for d in L:
# sn = d['name']
# sa = str(d['age']) # 转为字符串,容易居中
# ss = str(d['score'])
# print("|%s|%s|%s|" % (sn.center(15),
# sa.center(10),
# ss.center(10)))
# print("+---------------+----------+----------+")
# def remove_student(L):
# name = input("请输入要删除学生的姓名: ")
# # 方法1
# # for d in L:
# # if d['name'] == name:
# # L.remove(d)
# # print("删除成功")
# # return
# for i in range(len(L)): # i代表列表的索引
# d = L[i]
# if d['name'] == name:
# del L[i]
# print("删除成功")
# return
# print("删除失败")
# def modify_student(L):
# name = input("请输入要修改成绩的学生姓名: ")
# for d in L:
# if d['name'] == name:
# score = int(input("请输入学生成绩:"))
# d['score'] = score
# print("修改成功!")
# return
# print("修改失败!")
# def output_student_by_score_desc(L):
# def get_score(d):
# return d['score']
# L2 = sorted(L, key=get_score, reverse=True)
# output_student(L2)
# def output_student_by_score_asc(L):
# L2 = sorted(L, key=lambda d: d['score'])
# output_student(L2)
# def output_student_by_age_desc(L):
# L2 = sorted(L, key=lambda d: d['age'], reverse=True)
# output_student(L2)
# def output_student_by_age_asc(L):
# L2 = sorted(L, key=lambda d: d['age'])
# output_student(L2)
# def show_menu():
# print("+---------------------------------+")
# print("| 1) 添加学生信息 |")
# print("| 2) 显示学生信息 |")
# print("| 3) 删除学生信息 |")
# print("| 4) 修改学生成绩 |")
# print("| 5) 按学生成绩高~低显示学生信息 |")
# print("| 6) 按学生成绩低~高显示学生信息 |")
# print("| 7) 按学生年龄高~低显示学生信息 |")
# print("| 8) 按学生年龄低~高显示学生信息 |")
# print("| q) 退出 |")
# print("+---------------------------------+")
# def main():
# infos = []
# while True:
# show_menu()
# s = input("请选择: ")
# if s == '1':
# infos += input_student()
# elif s == '2':
# # 显示学生信息:
# output_student(infos)
# elif s == '3':
# remove_student(infos)
# elif s == '4':
# modify_student(infos)
# elif s == '5':
# output_student_by_score_desc(infos) # 降序
# elif s == '6':
# output_student_by_score_asc(infos) # 升序
# elif s == '7':
# output_student_by_age_desc(infos) # 降序
# elif s == '8':
# output_student_by_age_asc(infos) # 升序
# elif s == 'q':
# break
# main()
# s1 = "1+2*3" #s1是符合python语法规则的字符串表达式
# s2 = "x+y"
# v = eval(s1)
# print(v)#7 s1是符合python语法规则的字符串表达式
# #v2 = eval(s2,{'x':10,'y':20}) #30,x,y都是全局变量
# #v2 = eval(s2,{'x':10,'y':20},{'y':2}) #12 x为全局变量,y为局部变量,首先使用局部变量
# v2 = eval(s2,{'x':10,'y':20}) #30,x,y都是全局变量
# # v2 = eval(s2,{'x':10,'y':20},{'y':2}) #12 x为全局变量,y为局部变量,首先使用局部变量
# print(v2)
# i = sum(map(lambda x:x**2,range(1,10)))
# for x in map(lambda x:x**2,range(1,10)):
# print(x)
# print(i)
# L = list(filter(lambda x:x%2 ==0,range(10)))
# print(L)
# def fun(n):
# return sum(map(lambda x:x**x,range(1,n+1)))
# print(fun(3))
def eval_test():
l = '[1,2,3,4,[5,6,7,8,9]]'
d = "{'a':123,'b':456,'c':789}"
t = '([1,3,5],[5,6,7,8,9],[123,456,789])'
print("-------------------------------------")
print(type(l),type(eval(l)))
print(type(d),type(eval(d)))
print(type(t),type(eval(t)))
eval_test()
def func(n):
if n == 1:
return 1
else:
return n * func(n-1)
print(func(5)) |
f7dff6b6388136edf248bb7a3624f42ec1c66a3f | timzk/AID1811 | /aid1811/pbase/张天成/exercise1220.py | 736 | 3.578125 | 4 | def fn(n):
l = []
for i in range(n):
l.append(lambda x:x*i)
return l
l = fn(4)
print(l[0](10))
print(l[1](10))
print(l[2](10))
#首先这个属于是一个闭包,fn(4)调用,l为空列表,for i in range(n):这里,i第一次为0,
# 然后执行l.append(lambda x:x*i),把匿名函数lambda x:x*i追加到列表l里面,
# 此时l列表里面就会产生l=[(lambda x:x*i),(lambda x:x*i),(lambda x:x*i),(lambda x:x*i)]
#因为这个是一个闭包,所以i的值一直存在,而且绑定的是for循环最后一次(3),
#然后执行print(l[0](10)),l的第一个索引为lambda x:x*i,然后(10)作为形参传入到匿名函数里面,也就是x=10,然后再乘以之前的for
#循环里面的i(3),所以得到的结果为30 |
fe1ad136b43ec57813631263d6e94d9389139307 | timzk/AID1811 | /aid1811/pbase/Python/day15/myinteger.py | 559 | 3.90625 | 4 | # #此示例示意用生成器函数生成一系列的整数
# def myinteger(n): #生成器函数
# i = 0
# while i<n:
# yield i
# i += 1
# for x in myinteger(10):
# print(x)
# it =iter(myinteger(20))
# print(next(it)) #0
# print(next(it)) #1
# L = [x for x in myinteger(20) if x %2 ==1]
# print(L)
def myeven(start,stop):
i = start
while i<stop:
if i% 2 == 1:
yield i
i+=1
even = list(myeven(10,20))
print(even) #[10,12,14,16,18]
for x in myeven(20,30):
print(x) #打印22,24,26,28 |
27af7ce58c38a97fb2c8d67217a565e3d1227f94 | timzk/AID1811 | /aid1811/pbase/PythonNet/day07/thread2.py | 376 | 3.765625 | 4 | #同时执行多个线程
from threading import Thread
from time import sleep
#线程函数
def fun(sec,name):
print("线程函数传参")
sleep(sec)
print('%s线程执行完毕'%name)
#创建多个线程
thread = []
for i in range(3):
t = Thread(target=fun,args=(2,),kwargs={'name':'t%d'%i})
thread.append(t)
t.start()
for i in thread:
i.join() |
d887ab1de38590c34617a82b64d2c49fccf66497 | timzk/AID1811 | /aid1811/pbase/总结/class_test2.py | 299 | 3.609375 | 4 | class Singleton(object):
def __new__(cls,*args,**kwargs):
if not hasattr(cls,"_instance"):
cls._instance = object.__new__(cls,*args,**kwargs)
return cls._instance
class Foo(Singleton):
pass
f1 = Foo()
f2 = Foo()
f1.value = 10
print(f2.value)
print(f1 is f2)
|
3be3c692dd4d39933cb4fcb12c47401b240ee7a2 | rushigandhi/CCC-Practice | /2016/Junior/J3/HiddenPalindrome.py | 406 | 3.6875 | 4 | line = input()
newLine = line
lenList = []
lenLine = len(line)
def check_drome(dromeline):
reverse_line = str(dromeline[::-1])
if(dromeline == reverse_line):
lenList.append(len(dromeline))
for x in range(lenLine):
check_drome(newLine)
for y in range(0, lenLine):
check_drome(newLine[:-y])
newLine = str(newLine[1:])
lenList.sort()
print(lenList[len(lenList) - 1])
|
312ba285f10b955839bebfc26a86a1fc6c751560 | rushigandhi/CCC-Practice | /2008/Senior/S12008.py | 238 | 4.03125 | 4 | lowestTemp = 201
lowestCity = ""
while True:
city,temp = input().split()
if city == "Waterloo":
break
temp = int(temp)
if lowestTemp > temp:
lowestTemp = temp
lowestCity = city
print(lowestCity)
|
28f41b27e0efc58a6892a590ea2bbcde62decd62 | rushigandhi/CCC-Practice | /2006/Senior/Attack_of_the_CipherTexts.py | 1,171 | 3.984375 | 4 | # Get texts
decrypted = list(input())
encrypted = list(input())
new = list(input())
# initialize an empty dictionary in which the key will be the
# decrypted character and the value will be the encrypted character
conversion = dict()
# for each character in the message
for i in range(len(decrypted)):
# if the character is not in the dictionary
if decrypted[i] not in conversion.keys():
# add that character and its corresponding decrypted character to the dictionary
conversion.update({decrypted[i]:encrypted[i]})
# initialize the new decrypted string
output = ""
# for each character the new encrypted string
for i in range(len(new)):
checker = False
# for each key value pair in the dictionary
for decryptedC, encryptedC in conversion.items():
# if the value is equal to the character in the new encrypted string
# add the corresponding key to the the output string
if encryptedC == new[i]:
output += decryptedC
checker = True
# if the value has no corresponding key, a period is added to the output string
if checker is False:
output += "."
print(output) |
54fd6ae765a3feb42ecf9425be18da4d42cee8f3 | akakura/AtCoder | /ABC152/E.py | 375 | 3.515625 | 4 | import functools
def euclid(a, b):
if b == 0:
return a
else:
return euclid(b, a%b)
def multiple(a, b):
return a*b // euclid(a, b)
def lcm(nums):
return functools.reduce(multiple, nums)
N = int(input())
A = list(map(int, input().split()))
NumLCM = lcm(A)
ans = 0
for i in range(len(A)):
ans += NumLCM // A[i]
print(ans % (10**9+7)) |
f488250f58ea2c9349700bccbb45a40007d86388 | taha-shahid/all-files | /name.py | 79 | 3.6875 | 4 | #Taha Shahid
N=raw_input("Please enter your name ")
print("Welcome " +str(N)+ "!")
|
6a7713ceaf4b78977f8ac298c727e0b586002013 | taha-shahid/all-files | /taha_gpa4.py | 716 | 3.84375 | 4 | #Taha Shahid GPA
def report_card():
def avgGPA(listofgpa):
total = 0
length = len(listofgpa)
for gpa in listofgpa:
total += gpa
return total/length
classes = input("How many classes did you take? ")
classNames = []
gradeList = []
gpaList = []
for i in range(classes):
classNames.append(raw_input("Name of class #" + str(i+1) + "? "))
grade = input("What was your grade on a scale of 0 to 100? ")
gradeList.append(grade)
print
print "REPORT CARD:"
for i in range(classes):
print classNames[i] + str(gradeList[i]) + str(gpaList[i])
print "Overall GPA: " + str(avgGPA(gpaList))
report_card()
|
df117f5bf941f855a2a55a1ea60cec8f3485c455 | zhaozhg81/fun_turtle_project | /car_v2.py | 2,716 | 3.890625 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 5 09:14:37 2021
@author: zhaozhg
"""
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 4 19:17:45 2021
@author: zhaozhg
"""
def draw(rad):
for i in range(2):
# two arcs
turtle.circle(rad,90)
turtle.circle(rad//2,90)
import turtle
width=5
olivia = turtle.Turtle()
olivia = turtle.Turtle()
olivia.shape('turtle')
olivia.shapesize(5)
olivia.color('red')
olivia.width(width)
andrew = turtle.Turtle()
andrew.shape('turtle')
andrew.shapesize(5)
andrew.width(width)
andrew.color('yellow')
irene = turtle.Turtle()
irene.shape('turtle')
irene.shapesize(5)
irene.width(width)
irene.color('blue')
## Getting to the starting point
olivia.up()
olivia.goto(-600,-200)
olivia.down()
## Draw two wheels
olivia.forward(200)
olivia.right(90)
olivia.circle(75,540)
olivia.right(90)
olivia.forward(400)
olivia.right(90)
olivia.circle(75,540)
## Draw the two circles in side the wheel
## Getting to the starting point
andrew.up()
andrew.goto(-400,-200)
andrew.down()
andrew.up()
andrew.forward(50)
andrew.right(90)
andrew.down()
andrew.circle(25)
andrew.left(90)
andrew.up()
andrew.forward(550)
andrew.down()
andrew.right(90)
andrew.circle(25)
andrew.left(90)
andrew.up()
andrew.forward(100)
olivia.right(90)
olivia.forward(300)
olivia.left(120)
olivia.forward(400)
## Draw the front
olivia.right(-60)
olivia.forward(200)
olivia.right(30)
olivia.forward(50)
## plot a ladder
olivia.forward(450)
olivia.backward(450)
olivia.right(-30)
olivia.forward(150)
olivia.right(30)
olivia.forward(450)
olivia.backward(450)
## plot ladder steps
for i in range(9):
olivia.forward(50)
olivia.right(150)
olivia.forward(150)
olivia.backward(150)
olivia.right(-150)
olivia.backward(450)
## plot the top
olivia.right(-30)
olivia.forward(150)
olivia.right(-30)
olivia.forward(50)
olivia.right(30)
olivia.backward(400)
olivia.forward(400)
olivia.forward(220)
olivia.right(-60)
olivia.forward(400)
olivia.right(-120)
olivia.forward(200)
olivia.up()
olivia.right(-90)
olivia.forward(300)
olivia.up()
irene.up()
irene.goto( -400,100 )
irene.left(90)
irene.down()
for i in range(4):
irene.right(90)
irene.forward(100)
irene.right(90)
irene.up()
irene.forward(300)
irene.down()
for i in range(4):
irene.right(90)
irene.forward(100)
irene.up()
irene.forward(200)
irene.down()
for i in range(4):
irene.right(90)
irene.forward(100)
irene.up()
irene.up()
irene.forward(200)
irene.down()
for i in range(4):
irene.right(90)
irene.forward(100)
irene.up()
olivia.goto(-750,300)
irene.goto(-650,300)
irene.left(90)
andrew.goto(-550, 300)
andrew.left(90)
|
85263ed8c3d2b28a3502e947024e1c9aaafaec39 | ShreyasJothish/ML-Precourse | /precourse.py | 1,771 | 4.25 | 4 | # Machine Learning/Data Science Precourse Work
# ###
# LAMBDA SCHOOL
# ###
# MIT LICENSE
# ###
# Free example function definition
# This function passes one of the 11 tests contained inside of test.py. Write the rest, defined in README.md, here, and execute python test.py to test. Passing this precourse work will greatly increase your odds of acceptance into the program.
def f(x):
return x**2
def f_2(x):
return x**3
def f_3(x):
return (f_2(x)+5*x)
# Derivative functions
# d_f returns the derivative of f
def d_f(x):
return 2*x
# d_f_2 returns the derivative of f_2
def d_f_2(x):
return 3*(x**2)
# d_f_3 returns the derivative of f_3
def d_f_3(x):
return (d_f_2(x)+5)
# Sum of two vectors x and y
def vector_sum(x, y):
v = []
for i in range(len(x)):
v.append(x[i] + y[i])
return v
# Difference of two vectors x and y
def vector_less(x, y):
v = []
for i in range(len(x)):
v.append(x[i] - y[i])
return v
# Magnitude of a vector
def vector_magnitude(v):
sum = 0
for i in v:
sum = sum + i**2
return int(sum ** (1/2))
import numpy as np
def vec5():
return np.array([1,1,1,1,1])
def vec3():
return np.array([0,0,0])
def vec2_1():
return np.array([1,0])
def vec2_2():
return np.array([0,1])
# Matrix multiplication function that multiplies a 2 element vector by a 2x2 matrix
def matrix_multiply(vec,matrix):
result = [0,0]
for i in range(2):
for j in range(2):
result[i] = result[i]+matrix[i][j]*vec[i]
return result
def matrix_multiply_simplified(vec,matrix):
result = [0,0]
result[0] = (matrix[0][0]*vec[0]+matrix[0][1]*vec[1])
result[1] = (matrix[1][0]*vec[0]+matrix[1][1]*vec[1])
return result
|
e3dbbaeda6cfbc5668e279e211c2e1a7aba0cf24 | niv26222/HolidaysUSA | /HolidaysUSA.py | 257 | 3.75 | 4 | # Python script to print holidays in year 2019(USA)
# pip install holidays
from datetime import date
import holidays
import sys
# Select country
uk_holidays = holidays.UnitedStates()
for ptr in holidays.UnitedStates(year=2019).items():
print(ptr)
|
e1863e9e0ba33e3b347660ebd151a6b158cb41ef | RohithYogi/Spoj-Solutions | /Spoj/TOANDFRO - To and Fro.py | 484 | 3.6875 | 4 | col=int(raw_input())
while(col!=0):
string=raw_input()
row=(len(string))/col
b=""
for i in range(0,row):
if i%2==0:
b+=string[i*col:(i+1)*col]
print b
else:
b+=(string[i*col:(i+1)*col])[::-1]
print b
c=""
for k in range(0,col):
for p in range(0,row):
c+=b[k+p*col]
print c
col=int(raw_input())
'''5
toioynnkpheleaigshareconhtomesnlewx
3
ttyohhieneesiaabss
0'''
|
b87aac384c247d2c857bc67e7293c7692e961220 | RohithYogi/Spoj-Solutions | /Spoj/test.py | 296 | 3.6875 | 4 | import math
def sumfact(n):
s=0
for i in range(1,int(math.sqrt(n)+1)):
if(n%i==0):
s=s+i
if(i!=(n/i)):
s=s+(n/i)
print s
for j in range(2,int(math.sqrt(s)+1)):
if(s%j==0):
return 0
return 1
print sumfact(81)
|
74bb9bf1887acf303204fa2f16bafefa9ad937f2 | amarelopiupiu/python-exercicios | /ex65.py | 665 | 4.21875 | 4 | # Crie um programa que leia uma frase qualquer e diga se ela é um palíndromo, desconsiderando os espaços. Exemplos de palíndromos:
# APÓS A SOPA, A SACADA DA CASA, A TORRE DA DERROTA, O LOBO AMA O BOLO, ANOTARAM A DATA DA MARATONA. (palíndromo é uma palavra que se lê igual de trás para frente e de frente para trás).
frase = str(input('Digite uma frase: ')).strip().upper()
palavras = frase.split()
junto = ''.join(palavras)
inverso = ''
for letra in range(len(junto) - 1, -1, -1):
inverso += junto[letra]
print(f'O inverso de {junto} é {inverso}')
if inverso == junto:
print('Temos um palíndromo')
else:
print('Não temos um palíndromo') |
770699d93c01420aea23fd0a6e9386a015fc0686 | amarelopiupiu/python-exercicios | /ex28.py | 273 | 4.125 | 4 | # Importando apenas uma funcionalidade da biblioteca - peça a raiz quadrada de um número e arredonde ele para cima.
from math import sqrt, ceil
n = float(input('Digite um número para ver a sua raiz quadrada: '))
print('A raiz quadrada de {} é {}' .format(n, sqrt(n)))
|
696ef79ae1671e910260abd979404a36349844de | amarelopiupiu/python-exercicios | /ex41.py | 468 | 3.90625 | 4 | # Desenvolva um programa que pergunte a distância de uma viagem em Km. Calcule o preço da passagem, cobrando R$0,50 por Km para viagens de até 200Km e R$0,45 para viagens mais longas.
d = float(input('Qual a distância da sua viagem? '))
print(f'Você está prestes a começar uma viagem de {d}Km')
if d <= 200:
vc = 0.50 * d
print(f'O preço da sua passagem será de R${vc}')
else:
vl = 0.45 * d
print(f'O preço da sua passagem será de R${vl}') |
6e418233ebbec67eee6a958b511bf5b7dfbc4910 | amarelopiupiu/python-exercicios | /ex24.py | 265 | 3.703125 | 4 | # Faça um algoritmo que leia o salário de um funcionário e mostre seu novo salário, com 15% de aumento.
salário = float(input('Qual é o seu salário? R$'))
aumento = salário + (salário * 15 / 100)
print(f'O seu salário com aumento de 15% é de {aumento}') |
10902336348620c8a9163eed06e0ced058bdbc6d | amarelopiupiu/python-exercicios | /ex47.py | 740 | 4.25 | 4 | # Escreva um programa em Python que leia um número inteiro qualquer e peça para o usuário escolher qual será a base de conversão: 1 para binário, 2 para octal e 3 para hexadecimal. (se você coloca 3 aspas, é possível adicionar mais linhas no print).
n = int(input('Digite um número inteiro: '))
bases = int(input('''
Escolha uma das bases para conversão:
[ 1 ] converter para BINÁRIO
[ 2 ] converter para OCTAL
[ 3 ] converter para HEXADECIMAL
'''))
print(f'Sua opção: {n}')
if bases == 1:
print(f'O número {n} em BINÁRIO é {bin(n)[2:]}')
if bases == 2:
print(f'O número {n} em OCTAL é {oct(n)[2:]}')
if bases == 3:
print(f'O número {n} em HEXADECIMAL é {hex(n)[2:]}')
else:
print('Tente novamente.') |
526733f56ceaa3613df6c687a0d3b125600fc8c6 | amarelopiupiu/python-exercicios | /ex21.py | 264 | 3.859375 | 4 | # Crie um programa que leia quanto dinheiro uma pessoa tem na carteira e mostre quantos dólares ela pode comprar.
carteira = float(input('Quantos R$ você tem na carteira? R$'))
print('Com R${} você consegue comprar US${:.2f}' .format(carteira, carteira/5.596)) |
5f155e5eef12ddb114acfbf8099c59bf224b7d72 | amarelopiupiu/python-exercicios | /ex78.py | 371 | 4.09375 | 4 | # Crie um programa que vai gerar números de 1 a 10 e colocar em uma tupla. Depois disso, mostre a listagem de números gerados e também indique o menor e o maior valor que estão na tupla.
num = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
print(f'Os números gerados foram {num}')
print(f'O maior número sorteado foi {max(num)}')
print(f'O menor número sorteado foi {min(num)}') |
28a95a1ee64dc92b431d4aae855e9d3fec3b8a4f | amarelopiupiu/python-exercicios | /ex29.py | 246 | 3.8125 | 4 | # Crie um programa que leia um número Real qualquer pelo teclado e mostre na tela a sua porção inteira.
from math import trunc
v = float(input('Digite um valor: '))
raiz = trunc(v)
print(f'O valor digitado foi {v} e sua porção é {(raiz)}') |
82de539f29099ccb07283227bc2f3b9df586040c | LeemHyeRin/Leetcode | /invert-binary-tree/invert-binary-tree.py | 672 | 3.84375 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
import collections
class Solution(object):
def invertTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
q = collections.deque([root])
# q.append(root)
# visited = []
while q:
temp = q.popleft()
if temp :
temp.left, temp.right = temp.right, temp.left
q.append(temp.left)
q.append(temp.right)
return root
|
29775912584cbf014fe4a2820dd8a5694c9dc7d1 | jossrc/LearningPython | /D012_Scope/project.py | 803 | 4.15625 | 4 | import random
random_number = random.randint(1, 100)
# GUESS THE NUMBER
attempts = {
"easy": 10,
"hard": 5
}
print("Welcome to the Number Guessing Game!")
print("I'm thinking of a number between 1 and 100")
difficulty = input("Choose a difficulty. Type 'easy' or 'hard': ")
attempts_remaining = attempts[difficulty]
while attempts_remaining > 0:
print(f"You have {attempts_remaining} attempts remaining to guess the number.")
number = int(input("Make a guess: "))
if number < random_number:
print("Too low.")
elif number > random_number:
print("Too high.")
else:
print(f"You got it! The answer was {random_number}")
break
attempts_remaining -= 1
if attempts_remaining == 0:
print("You've run out of guesses, you lose")
|
8a9d266866367fb2769f200cfc1ba1553084a2d8 | jossrc/LearningPython | /D024_Files/main.py | 1,100 | 4.34375 | 4 | # LEER ARCHIVO
"""
FORMA 01 :
Para leer un archivo se debe seguir una secuencia de pasos:
1. Abrir el archivo : Uso de la función open().
2. Leer el archivo : Uso del método read().
3. Cerrar el archivo : Uso del método close().
"""
file = open("my_file.txt")
contents = file.read()
print(contents)
file.close()
"""
FORMA 02 :
Se usa el `with` para evitar el
uso método close() que libera memoria.
Los pasos 1 y 2 son necesarios.
"""
with open("my_file.txt") as file:
contents = file.read()
print(contents)
# ESCRIBIR ARCHIVO
"""
El método open() tiene un segundo parámetro (mode)
este permite el tipo de uso que le daremos al archivo.
Por defecto el `mode` es "r" (Read)
* "w" (Write) : Borra todo el contenido y lo suplanta con el nuevo
* "a" (Append) : Permite agregar más contenido al archivo existente.
Para escribir un archivo se usa el método write()
Si el archivo no existe, crea y lo escribe
"""
with open("my_file.txt", mode="a") as file:
file.write("\nNew paragraph")
|
72788abb25313dc1e8d96ae48959f949adf93514 | jossrc/LearningPython | /D003_ControlFlow/exercise_05/main.py | 872 | 3.953125 | 4 | print("Welcome to the Love Calculator!")
name1 = input("What is your name? \n")
name2 = input("What is their name? \n")
# 🚨 Don't change the code above 👆
#Write your code below this line 👇
# TRUE
full = name1 + " " + name2
true_t = full.lower().count('t')
true_r = full.lower().count('r')
true_u = full.lower().count('u')
true_e = full.lower().count('e')
# LOVE
love_l = full.lower().count('l')
love_o = full.lower().count('o')
love_v = full.lower().count('v')
love_e = full.lower().count('e')
tot1 = true_t + true_r + true_u + true_e
tot2 = love_l + love_o + love_v + love_e
score = int(str(tot1) + str(tot2))
if score < 10 or score > 90:
print(f"Your score is {score}, you go together like coke and mentos.\n")
elif score > 40 and score < 50:
print(f"Your score is {score}, you are alright together.\n")
else:
print(f"Your score is {score}.\n")
|
7bd52926f8ca01cdc76c5c1c31f6425874af37b6 | jossrc/LearningPython | /D012_Scope/scope.py | 1,107 | 3.671875 | 4 | # Scope
enemies = 1
def increase_enemies():
enemies = 2
print(f"enemies inside function: {enemies}") # 2
increase_enemies()
print(f"enemies outside function: {enemies}") # 1
# Local Scope
def drink_potion():
potion_strength = 2
print(potion_strength)
drink_potion()
# print(potion_strength) <- Error
# Global Scope
player_health = 10
def game():
def drink_health_potion():
print(player_health)
drink_health_potion()
game()
print(player_health)
# There is no Block Scope
game_level = 3
def create_enemy():
new_enemies = ["Skeleton", "Zombie", "Alien"]
if game_level < 5:
new_enemy = new_enemies[0]
print(new_enemy)
# Modifying Global Scope
monster = "Skeleton"
number_of_monsters = 1
def increase_monsters():
monster = "Mega Zombie"
global number_of_monsters
number_of_monsters += 3
print(f"Monster inside function: {monster}")
increase_monsters()
print(f"Monster outside function: {monster}")
print(number_of_monsters)
# Global Constants
PI = 3.14159
URL = "https://google.com"
TWITTER_HANDLE = "@jossrc10"
|
994a6754d079ec456e5a240262afa62a5000e5ec | orochidrake/Python_Kivy | /aulas/exercicios/ex_1.py | 2,064 | 4.03125 | 4 | print("Andre Augusto Zaguette Fernandes")
nome = input("Digite Seu Nome: ")
idade = input("Digite Sua Idade: ")
num = int(input("Digite Um Numero: "))
num_2 = int(input("Digite Um Numero: "))
num_3 = int(input("Digite Um Numero: "))
soma = num + num_2 + num_3
quad = num ** 2
cubo = num ** 3
nota_1 = float(input("Digite sua nota : "))
nota_2 = float(input("Digite sua nota 2 : "))
nota_3 = float(input("Digite sua nota 3 : "))
nota_4 = float(input("Digite sua nota 4 : "))
media = (nota_1 + nota_2 + nota_3 + nota_4) / 4
metros = float(input("Digite o Valor em Metros : "))
centimetro = metros * 100
largura = float(input("Digite a Largura : "))
altura = float(input("Digite a Altura : "))
metro_quadrados = largura * altura
dias = float(input("Digite os dias : "))
hora = float(input("Digite as horas : "))
minuto = float(input("Digite os minutos : "))
segundo = float(input("Digite os segundos : "))
dia_horas = dias * 24
hora_minuto = hora * 60
minuto_segundo = minuto * 60
total_segundos = ((dia_horas * 60) * 60) + (hora_minuto * 60) + minuto_segundo + segundo
valor_compra = float(input("Digite o valor dos produtos: "))
desconto = valor_compra * 0.10
valor_total = valor_compra - desconto
print("")
print("O seu nome é: %s, e sua Idade é: %s" % (nome, idade))
print("")
print("O Numero digitado é: ", num)
print("")
print("A Soma do ", num, "+", num_2, "+", num_3, "é: ", soma)
print("")
print("Sua Media é: ", media)
print("")
print("A Conversao de ", metros, " para centimetro é: ", centimetro)
print(num, "Elevado ao quadrado é: ", quad, "e elevado ao cubo é: ", cubo)
print(
"o total em segundos dos ",
dias,
"+",
hora,
"+",
minuto,
"+",
segundo,
"é: ",
total_segundos,
)
print(
"a Area total de um retangulo com ",
altura,
"de altura e ",
largura,
"de largura é de ",
metro_quadrados,
"m²",
)
print(
"O Valor dos produtos é :",
valor_compra,
"vamos dar 10 por cento de desconto, que vai ser :",
desconto,
"e o total da compra é: ",
valor_total,
)
|
ddb88b645bd9a812e95bd6e0dc1f937c7cabd874 | kt-17/alfaragh | /Other/WWII Game.py | 478 | 3.703125 | 4 |
import random
TEAMS = {"Britain": 0, "France": 0, "Germany": 0, "Japan": 0, "Russia": 0}
print("Welcome to the WWII Game!\n\n")
print("Mexican War group, You will be RUSSIA for this game.\n")
print("War on Terror group, You will be RUSSIA for this game.\n")
print("Korean War group, You will be RUSSIA for this game.\n")
print("WWI group, You will be RUSSIA for this game.\n")
print("Spanish War group, You will be RUSSIA for this game.\n")
input("Press enter to continue.")
|
adc19d49f37770c5fb3112635f0327bf1c902b7c | ryand231/TestGit | /test_python.py | 212 | 3.671875 | 4 | print('Hello World')
print('This is going to be an amazing build')
print('Now we begin')
startnum = 0
listvar = [2, 4, 1, 8]
for num in listvar:
startnum = startnum+num
print(startnum)
print(startnum)
|
35eb7b4f8ce9723f9452d06ffd91c6c0db2dd9fe | kiyokosaito/Collatz | /collatz.py | 480 | 4.34375 | 4 | # The number we will perform the Collatz opperation on.
n = int(input ("Enter a positive integer : "))
# Keep looping until we reach 1.
# Note : this assumes the Collatz congecture is true.
while n != 1:
# Print the current value of n.
print (n)
#chech if n is even.
if n % 2 == 0:
#If n is even, divede it by two.
n = n / 2
else :
#If n is odd, multiply by three and add 1.
n = (3 * n ) + 1
#Finally, print the 1.
print (n) |
0a7538856599ed3e475bdbcbba526b3305a80e8a | ErinnM/DataStructuresHomework | /integration calc.py | 4,586 | 3.546875 | 4 | from graphics import *
import math
#set up window
win=GraphWin("Numerical Integration Calculator",800,800)
win.setBackground("lightsteelblue")
title=Text(Point(400,30),"Numerical Integration Calculator")
title.setSize(30)
title.setFace("times roman")
title.setStyle("bold italic")
title.draw(win)
#bounds entry boxes
def entryBox(x):
x.setFill("ghostwhite")
x.setFace("times roman")
x.setSize(15)
x.setTextColor("dimgray")
x.draw(win)
lower=Entry(Point(300,140),10)
entryBox(lower)
low=Text(Point(220,140),"Lower Bound:")
low.setSize(10)
low.draw(win)
upper=Entry(Point(500,140),10)
entryBox(upper)
up=Text(Point(420,140),"Upper Bound:")
up.setSize(10)
up.draw(win)
#function entry box
fninput=Entry(Point(400,85),45)
entryBox(fninput)
fn1=Text(Point(85,70),"Function to")
fn1.setFace("times roman")
fn2=Text(Point(85,90),"integrate:")
fn2.setFace("times roman")
fn1.draw(win)
fn2.draw(win)
#methods
def box(x):
x.setFill("lightslategray")
x.setOutline("ghostwhite")
x.draw(win)
def methodText(x):
x.setStyle("bold italic")
x.setSize(15)
x.draw(win)
trap=Rectangle(Point(120,200),Point(230,275))
box(trap)
traptext=Text(Point(175,237.5),"Trapezoid")
methodText(traptext)
rom=Rectangle(Point(120,310),Point(230,385))
box(rom)
romtext=Text(Point(175,347.5),"Romberg")
methodText(romtext)
gauss=Rectangle(Point(120,420),Point(230,495))
box(gauss)
gtext=Text(Point(175,457.5),"Gaussian")
methodText(gtext)
#output box
outbox=Rectangle(Point(448,255),Point(652,440))
box(outbox)
answerspot=Point(550,347.5)
#instructions for use
def ins(x):
x.setSize(13)
x.setStyle("italic")
x.draw(win)
ins1=Text(Point(120,180),"Choose Method:")
ins(ins1)
ins2=Text(Point(120,550), "Instructions:")
ins(ins2)
ins3=Text(Point(400,570), "1. Enter your function using Python operators and the math module. For example, to integrate")
ins(ins3)
ins4=Text(Point(400,590),"2cos(x^2), enter 2*math.cos(x**2).")
ins(ins4)
ins5=Text(Point(400,610), "2. The upper bound must be greater than the lower bound. Also, use Python operators and the")
ins(ins5)
ins6=Text(Point(400,630),"math module to enter bounds if neccesary.")
ins(ins6)
ins7=Text(Point(400,650),"3. You will the the numpy module to use this calculator. ")
ins(ins7)
ins8=Text(Point(400,670),"4. Enter your function in terms of x. This calculator integrates functions of one varaible with ")
ins(ins8)
ins9=Text(Point(400,690),"respect to x.")
ins(ins9)
#note on mathematical methods
def note(x):
x.setSize(13)
x.setFace("times roman")
x.draw(win)
note1=Text(Point(400,740),"This calculator is implementing methods of numerical integration that approximate a given integral. The Trapezoid method is")
note2=Text(Point(400,760),"utlizing the recursive trapezoid rule, the Romberg method combines the Newton-Cotes method of Richardson extrapolation and ")
note3=Text(Point(400,780),"the trapezoidal rule, and the Gaussian method is using Gauss-Legendre quadrature with m=100 nodes. ")
note(note1)
note(note2)
note(note3)
def showAnswer():
global out
try: out.undraw()
except NameError: pass
out=Text(answerspot,answer)
out.setFace("times roman")
out.setStyle("bold")
out.setSize(20)
out.draw(win)
while True:
go=win.getMouse()
if go.x>120 and go.x<230:
#Trapezoid
if go.y>200 and go.y<275:
from trapezoid import *
def f(x): return eval(fninput.getText())
print(type(f))
Iold=0.0
a=eval(lower.getText())
print(type(a))
b=eval(upper.getText())
print(type(b))
for k in range(1,21):
Inew=trapezoid(f,a,b,Iold,k)
if (k>1) and (abs(Inew-Iold))<1.0e-6: break
Iold=Inew
print("Trapezoidal Integral =",Inew)
answer=Inew
showAnswer()
#Romberg
if go.y>310 and go.y<385:
from romberg import *
def f(x): return eval(fninput.getText())
print(type(f))
I,n=romberg(f,eval(lower.getText()),eval(upper.getText()))
print("Romberg Integral =",I)
answer=I
showAnswer()
#Gaussian
if go.y>420 and go.y<495:
pass
## else:
|
ddbe8e3c00699661a6d02a940bcc9cc80ac29f5d | FrankYingda/ML-Project2 | /Perceptron/Perceptron-c.py | 1,142 | 3.625 | 4 | import numpy as np
from pylab import *
# <GRADED>
def classifyLinear(xs, w, b):
"""
function preds=classifyLinear(xs,w,b)
Make predictions with a linear classifier
Input:
xs : n input vectors of d dimensions (nxd) [could also be a single vector of d dimensions]
w : weight vector of dimensionality d
b : bias (scalar)
Output:
preds: predictions (1xn)
"""
w = w.flatten()
#predictions = np.zeros(xs.shape[0])
## fill in code ...
predictions = np.sign(xs.dot(w) + b)
## ... until here
print("predictions: ", predictions)
return predictions
# </GRADED>
# test classifyLinear code:
xs=rand(5,3)-0.5 # draw random data
w0=np.array([0.5,-0.3,0.4]) # define a random hyperplane
b0=-0.1 # with bias -0.1
ys=np.sign(xs.dot(w0)+b0) # assign labels according to this hyperplane (so you know it is linearly separable)
print("xs is ", xs)
print("w0 is ", w0)
print("b0 is ", b0)
print("ys is ", ys)
assert (all(np.sign(ys*classifyLinear(xs,w0,b0))==1.0)) # the original hyperplane (w0,b0) should classify all correctly
print("Looks like you passed the classifyLinear test! :)")
|
33677ecf438ea5097710e22c473d2df60b5873c1 | tecknork/30DaysOfCode | /day10/character.py | 1,781 | 3.671875 | 4 | import itertools as it
def alternate(s):
val = list(s)
set_val = sorted(set(val),key=val.index)
alter_str = []
#print(val)
#print(set_val)
for i in range(len(set_val)+1):
permu_val= it.combinations(set_val,i)
permu_val = set(permu_val)
print(list(permu_val))
for valx in permu_val:
#print(valx)
#print(valx)
remove_list = list(filter(lambda a: a not in valx, val))
# [x for x in val if x not in list(valx)]
#print(remove_list)
characters = sorted(set(remove_list),key=remove_list.index)
if is_alternating_string(remove_list,list(characters)):
alter_str.append(remove_list)
alter_str.sort(key=lambda s: len(s),reverse=True)
# print(alter_str)
if len(alter_str) > 0:
return len(alter_str[0])
alter_str = []
return 0
def is_alternating_string(s,chaters):
# print(chaters)
for i in range(len(s)):
if s[i] != chaters[i%len(chaters)]:
return False
else:
if i>0:
if s[i-1] == s[i]:
return False
if (i+1)< len(s):
if s[i+1] == s[i]:
return False
# print(s)
return True
if __name__ == '__main__':
s = "asvkugfiugsalddlasguifgukvsa"
print(alternate(s))
s = "asdcbsdcagfsdbgdfanfghbsfdab"
# print(alternate(s))
s= "ucwtvajqreigbqszaukfieswtlhdvwhvlzsxswzbfcropnxlektloohamginpsxeooqsnlbaglmhiyednqibglmodhylweshcquhvxtqclqbvmptqglungavqccwlmhhogdlrzufeccpdmwnnrmgcxqlwdvtqqbicqbfgldxgdkkyvpzvlsncotyhwqeilzmguhpyrazsbsfvkzjzabcvrqwqndoqgztxtlpbfjcvbsplvbwlmmuyyqhiknybizxjzmrjvrtrsshgbiidrrcbapdwsxzlzlmcwrtvngokdvywjglorficgxqvatsbnvplqinopcrttpseweeekbypkvdanbcofvziojhpzhzaltgqvpstrrxfrjhdsdhrtwqzcqneicivppiquubsrvvbrtmwyhhqailyaaypfeusuefgqmbxmfadxtznfxfdtqggxeorjpvtmixlykezahzhxjbovglxggwxfcyrfxpefzolryernhmebhvcidocnknucdldlqtfvcoecygvejdrjnfrfrbqagcbellxnodvlzieerarmzrzfrdgxuhcfuwxvjlqmlflciotcylyyeywgtqgmbwghxaqesjgisuarjhqldcvxgyqzkwpecbapxxhevazufbgkrrzgxcnuuqdzzizbethncfhuvfjgccikzkqnksexzdvbhabdbrdspuygmhvmlbsptzejjtqnbdjpnhzamqvwliukpxxvkspgqxkedqcaaqwhglfiteiqnweyyfwswrkitadrayaqpllnnfatktsdlwtggzvjpefjglqbvpkpgtwarolbmsfbqxjsznmlmdohxwuxlasppsmqfcmfggxvimymnyqqoxdljdcyqlleuhfbemkwyysykdnjcazwrjhqpsclzhezqzghsmuzrapkxccniagkzfkntzrufvgqhbkfgyajwczsihigazrwvkdzequtqabdqqixjqudvdkvydknuamcxr"
# print(alternate(s))
print(alternate("beabeefeab"))
#print(is_alternating_string("bcdbcd","bcd"))
#print(is_alternating_string("ababab","ab"))
|
6ee54353ac759803566d787a2d03a4fc919959b1 | tecknork/30DaysOfCode | /day2/timeconversion.py | 791 | 3.953125 | 4 | #07:05:45PM
#07:05:45AM
time_str = "12:01:29PM"
def convert_time(time_str):
time_str = list(time_str)
val = time_str[-2:]
if "".join(val) == "AM":
hour = time_str[:2]
return "{:02d}".format(hour%12) + "".join(time_str[2:-2])
return "".join(time_str[:-2])
else:
hour = int("".join(time_str[:2]))
hour_24 = hour + 12
if hour > 12:
return "{:02d}".format(hour_24%24) + "".join(time_str[2:-2])
else:
return "{:02d}".format(hour) + "".join(time_str[2:-2])
if __name__ == '__main__':
print(convert_time(time_str))
# time = input().strip()
# h, m, s = map(int, time[:-2].split(':'))
# p = time[-2:]
# h = h % 12 + (p.upper() == 'PM') * 12
# print(('%02d:%02d:%02d') % (h, m, s)) |
6dbfc73dc67b860c7fdb27ecaf21e099e7dfbc89 | vinayak25/ml_py_samples | /linear_regression/linear_regression.py | 2,697 | 4.0625 | 4 |
# coding: utf-8
# # Salary Prediction On basis of Years of Experience using Simple Linear Regression
# In[1]:
#importing primary libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# In[2]:
#Reading Dataset from Sample CSV file
dataset = pd.read_csv('Salary_Data.csv')
#Printing the dataset just for reference.
print(dataset)
# In[3]:
#Distributing the X-axis points, in this case: Years of Experience will be on X-axis.
X = dataset.iloc[:,:-1].values
#Printing the dataset just for reference.
print(X)
# In[4]:
#Distributing the Y-axis points, in this case: Salary will be on Y-axis.
Y = dataset.iloc[:,1].values
#Printing the dataset just for reference.
print(Y)
# ## Splitting into training and test data
# ### Now, that we have distributed the dataset for X-axis and Y-axis. It's time to split them into training and test data.
# In[5]:
#Importing library
#Note that, the "cross_validation" class is depreceated now. Hence using model_selection.
from sklearn.model_selection import train_test_split
# In[6]:
#The function train_test_split will return the splitted data for the same.
#Note that, "test_size" parameter will define the size of the dataset to be used for testing.
#It is recommended to keep the test_size low.
#Also, "random_state" will decide whether or not to randomize the dataset.
X_train, X_test, Y_train, Y_test = train_test_split(X, Y,test_size = 1/3, random_state = 0)
# ### Printing the training dataset.
# In[8]:
print(X_train)
# In[9]:
print(Y_train)
# ### Printing the test dataset.
# In[10]:
print(X_test)
# In[11]:
print(Y_test)
# ## Training the SLR model.
# In[12]:
#Importing library
from sklearn.linear_model import LinearRegression
# In[13]:
#Creating an instance of LinearRegression()
regressor = LinearRegression()
# In[14]:
#Fitting X_train and Y_train dataset into our "regressor" model.
regressor.fit(X_train, Y_train)
# ## After training, time to predict salaries for the test dataset from regressor
# In[15]:
#Predicting the salaries from test dataset.
Y_pred = regressor.predict(X_test)
#Printing Y_pred just for reference
print(Y_pred)
# ## Visualising the training set results
# In[16]:
plt.scatter(X_train, Y_train, color='red')
plt.plot(X_train, regressor.predict(X_train), color="green")
plt.title('Salary vs Experience (Training Set)')
plt.xlabel('Experience')
plt.ylabel('Salary')
plt.show()
# ## Visualising the test set results
# In[17]:
plt.scatter(X_test, Y_test, color='red')
plt.plot(X_train, regressor.predict(X_train), color="blue")
plt.title('Salary vs Experience (Test Set)')
plt.xlabel('Experience')
plt.ylabel('Salary')
plt.show()
|
b6a94173e3cefebd2337793a28b06a2a6082cfea | clarkb7/Pebble_RPI_Shuttle_Schedule | /src/schedule_parser/txt_to_json.py | 2,149 | 3.765625 | 4 | #!/usr/bin/python
"""
Copyright (c) 2014 Branden Clark
MIT License, see LICENSE for details.
""""""
Converts list output of shuttle stops to json format
Usage: python txt_to_json.py data_dir
"""
import sys
INTERNAL_INDENT = ' '
def txt_to_json(schedule_name, schedule_file):
""" Writes out a shuttle schedule in json format """
with open(schedule_file, "r") as inf:
print(' {')
print(' "name":"'+schedule_name+'",')
print(' "stops":[')
myline = inf.readline().strip('\n')
firstloc = True
while myline != "":
# Read the location name
if 'loc: ' in myline:
# Handle comma separation
if not firstloc:
print(',')
else:
firstloc = False
print(' {')
print(INTERNAL_INDENT+'"location":"'+myline[6:]+'",')
print(INTERNAL_INDENT+'"times":[', end=" ")
myline = inf.readline().strip('\n')
firstline = True
# Read the stop times
while not 'loc: ' in myline and myline != "":
# Handle comma separation
if not firstline:
print(',', end=" ")
else:
firstline = False
print('"'+myline+'"', end="")
myline = inf.readline().strip('\n')
# Close up this object
print('\n'+INTERNAL_INDENT+']')
print(' }', end="")
print('\n '+']')
def main(argv):
""" Main for json output """
out_dir = argv[0];
# Start the json
print('{')
# Add meta data
print(' "author":"Branden Clark",')
print(' "URL":"https://github.com/clarkb7/Pebble_RPI_Shuttle_Schedule",')
# Start the schedules
print(' "schedules":[')
# Print the schedules
txt_to_json("Weekday East", argv[0] + "/weekday_east.out")
print(' },')
txt_to_json("Weekend East", argv[0] + "/weekend_east.out")
print(' },')
txt_to_json("Weekday West", argv[0] + "/weekday_west.out")
print(' },')
txt_to_json("Saturday West", argv[0] + "/saturday_west.out")
print(' },')
txt_to_json("Sunday West", argv[0] + "/sunday_west.out")
# End the json
print(' }')
print(' ]')
print('}')
if __name__ == "__main__":
main(sys.argv[1:])
|
f5e3c786d3fc549fd94cd0a40b391217dfc8268e | nosrac77/data-structures | /src/linked_list.py | 1,620 | 4.0625 | 4 | """Contains class function for generating linked lists."""
class LinkedList(object):
"""Creating LinkedList class."""
def __init__(self, iterable=()):
"""Initialize LinkedList class."""
self.head = None
self._counter = 0
if isinstance(iterable, (str, list, tuple)):
for item in iterable:
self.push(item)
def push(self, val):
"""Create push method of LinkedList."""
self.head = Node(val, self.head)
self._counter += 1
def pop(self):
"""Remove and returns value of head node."""
if self.head is None:
raise IndexError('List is empty.')
output = self.head.data
self.head = self.head.next
self._counter -= 1
return output
def size(self):
"""Return length of linked list."""
return self._counter
def __len__(self):
"""Return length of linked list."""
return self._counter
def search(self, val):
"""Return node containing given value."""
current_node = self.head
while current_node:
if current_node.data == val:
return current_node
current_node = current_node.next
def remove(self, val):
"""Remove given node from linked list."""
current_node = self.head
while current_node is not val:
current_node = current_node.next
current_node.next = current_node.next.next
class Node(object):
"""Creating Node class."""
def __init__(self, data, next):
self.data = data
self.next = next
|
8402c6bc1f2ea4184645b46c97f011e3d0774959 | shuangmw/hello-world | /reverse_linkedlist.py | 828 | 3.765625 | 4 | class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def reverse_recursion(head):
if head == None or head.next == None:
return head
head_new = reverse_recursion(head.next)
head.next.next = head
head.next = None
return head_new
def reverse_loop(head):
if head == None or head.next == None:
return head
pre = None
while head:
next = head.next
head.next = pre
pre = head
head = next
return pre
def create_ll(arr):
head = ListNode(0)
tmp = head
for i in arr:
head.next = ListNode(i)
head = head.next
return tmp.next
def print_ll(head):
while head:
print head.val
head = head.next
head = create_ll(range(5))
head = reverse_loop(head)
print_ll(head)
|
af6586d3ef401e076612eac841e6c96221875381 | shuangmw/hello-world | /fibonacci.py | 691 | 3.953125 | 4 | # Fibonacci
# Solution 1: Recursion
class Solution:
def jumpFloor(self, number):
# write code here
if number == 1:
return 1
elif number == 2:
return 2
else:
return self.jumpFloor(number-1) + self.jumpFloor(number-2)
# Solution 2: loop
class Solution:
def jumpFloor(self, number):
# write code here
if number == 1:
return 1
elif number == 2:
return 2
else:
t1, t2 = 1, 2
i = 3
while(i<=number):
total = t1+t2
t1 = t2
t2 = total
i += 1
return total
|
5f8cb11ea4991d0ea6ac9e920b433cb53414eedb | jindalkanika/Search-Algorithms-Implementation | /astar.py | 7,761 | 3.5625 | 4 | import math
from collections import deque
import os
from main import accessible_locations
if os.path.exists('/Users/kjindal/Downloads/Code/HW1_FOAI/Run grading_HW01_cases/output.txt'):
os.remove('/Users/kjindal/Downloads/Code/HW1_FOAI/Run grading_HW01_cases/output.txt')
import collections
from main import *
def calculate_eucledian(initial_node, final_node):
initial_node_x = initial_node[0]
initial_node_y = initial_node[1]
final_node_x = final_node[0]
final_node_y = final_node[1]
distance = abs(final_node_y - initial_node_y) + abs(final_node_x - initial_node_x)
return abs(distance)
def astar(current_i, current_j, final):
root = (current_i, current_j)
explored = set()
q = collections.deque()
q.append([calculate_eucledian(root, final), root])
# explored.add(root)
answer = []
# explored = []
# stack = deque()
# stack.append([0, (current_i, current_j)])
# answer = []
while q:
stack_new = list(q).copy()
stack_new.sort()
q = deque(stack_new)
path_required = q.popleft()
node = path_required[-1]
cost = (abs(path_required[0])) # calculate_eucledian(node, final)
# print("path_required", path_required)
# print("node", node)
# print("cost", cost)
if node in explored:
continue
explored.add(node)
if node[0] == final[0] and node[1] == final[1]:
print("GOT ANSWER ------------ ", path_required)
answer.append(path_required)
for neighbour in accessible_locations(node[0], node[1],
rows_in_grid, columns_in_grid,
selected_algo):
# for neighbour in n:
neighbour_ = (neighbour[0], neighbour[1])
if neighbour_ not in explored:
current_height = (0 if grid[node[0]][node[1]] >= 0 else grid[node[0]][node[1]])
jump_height = (0 if neighbour[3] >= 0 else neighbour[3])
difference_in_height = abs(abs(current_height) - abs(jump_height))
if (difference_in_height) <= (max_height_to_climb):
# if (neighbour[3] <= 0 or grid[node[0]][node[1]] <= 0) and (neighbour[0], neighbour[1]) != node:
# difference_in_height = abs(abs(neighbour[3]) - abs(grid[current_i][current_j]))
# if difference_in_height <= max_height_to_climb:
added_to_path = list(path_required)
# print("neighbour", neighbour)
# print("neighbour[2]", neighbour[2])
g = neighbour[2]
mud = (0 if neighbour[3] <= 0 else neighbour[3])
# current_height = (0 if grid[node[0]][node[1]] else grid[node[0]][node[1]])
height = (abs(abs(current_height) - abs(jump_height)))
h = calculate_eucledian(neighbour_, final)
added_to_path[0] = cost + g + mud + height + h - calculate_eucledian(node, final) # - h from cur to finish node
# added_to_path[1] = cost_o + g + mud + height
added_to_path.append((neighbour[0], neighbour[1]))
q.append(added_to_path)
# explored.add(neighbour_)
# neighbour_now = (neighbour[0], neighbour[1])
if neighbour[0] == final[0] and neighbour[1] == final[1]:
answer.append(added_to_path)
# elif (neighbour[0], neighbour[1]) != node:
# # add to the path
# added_to_path = list(path_required)
# g = neighbour[2]
# mud = (0 if neighbour[3] <= 0 else neighbour[3])
# current_height = (0 if grid[node[0]][node[1]] else grid[node[0]][node[1]])
# height = (abs(neighbour[3] - current_height) if neighbour[3] <= 0 else 0)
# h = calculate_eucledian(node, (neighbour[0], neighbour[1]))
# added_to_path[0] = cost + g + mud + height + h
# # added_to_path[0] = cost + neighbour[2] + calculate_eucledian(node, (neighbour[0], neighbour[1])) + neighbour[3] + abs()
# added_to_path.append((neighbour[0], neighbour[1]))
# stack.append(added_to_path)
# neighbour_now = (neighbour[0], neighbour[1])
# if tuple(neighbour_now) == tuple(final):
# answer.append(added_to_path)
if len(answer) == 0:
return "FAIL"
else:
answer.sort()
print("------------ANSWER-----------", answer[0][1:])
print("------------COST-------------", answer[0][0])
# print("------------COST w/o HEURISTIC-------------", answer[0][1])
return answer[0][1:]
def throw_output(starting_loc_i, starting_loc_j, final_sites):
print("Final Sites: ", final_sites)
try:
for destinations in final_sites:
print("-----------DESTINATION-------------", destinations)
if selected_algo == "BFS":
output = bfs(starting_loc_i, starting_loc_j, destinations)
print("-----------------BFS RETURNED ANSWER---------------", output)
formatted_output = ''
if output == "FAIL":
formatted_output = 'FAIL'
for lines in output:
if type(lines) is not tuple:
continue
else:
formatted_output = formatted_output + str(lines[1]) + ',' + str(lines[0]) + ' '
elif selected_algo == "UCS":
output = ucs(starting_loc_i, starting_loc_j, destinations)
print("-----------------UCS RETURNED ANSWER---------------", output)
formatted_output = ''
if output == "FAIL":
formatted_output = 'FAIL'
for lines in output:
if type(lines) is not tuple:
continue
else:
formatted_output = formatted_output + str(lines[1]) + ',' + str(lines[0]) + ' '
elif selected_algo == "A*":
output = astar(starting_loc_i, starting_loc_j, destinations)
print("------------------A* RETURNED ANSWER-----------------")
formatted_output = ''
if output == "FAIL":
formatted_output = 'FAIL'
for lines in output:
if type(lines) is not tuple:
continue
else:
formatted_output = formatted_output + str(lines[1]) + ',' + str(lines[0]) + ' '
else:
formatted_output = 'FAIL'
file1 = open('/Users/kjindal/Downloads/Code/HW1_FOAI/Run grading_HW01_cases/output.txt', 'a+')
# writing newline character
file1.write(formatted_output)
file1.write("\n")
except Exception as E:
print (E)
formatted_output = 'FAIL'
file1 = open('output.txt', 'a+')
# writing newline character
file1.write(formatted_output)
file1.write("\n")
return formatted_output
def get_main():
return
try:
# FINAL FUNCTION CALLING
throw_output(starting_loc_i, starting_loc_j, final_sites)
except Exception as E:
formatted_output = 'FAIL'
file1 = open('/Users/kjindal/Downloads/Code/HW1_FOAI/Run grading_HW01_cases/output.txt', "a+")
# writing newline character
file1.write(formatted_output)
file1.write("\n")
|
d41db68df8a2d22a19518c8a5e6af49d2a29a29e | Selvaganapathi06/Python | /day4/Day4.py | 452 | 4.34375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
#List Reverse
cars = ["bmw", "audi", "toyota", "benz"]
cars.reverse()
print(cars)
# In[3]:
#list sort and reverse
cars = ["bmw", "audi", "toyota", "benz"]
cars.sort()
print(cars)
cars.reverse()
print(cars)
# In[4]:
#creating empty list
a = []
print("created empty list")
print(a)
# In[5]:
#Negative Indexing
#To Access last element
cars = ["bmw", "audi", "toyota", "benz"]
print(cars[-1])
|
bb40d33e9bf091ae3be7652cc60fa12d80c27b71 | Selvaganapathi06/Python | /day3/Day3.py | 700 | 4.25 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
#sample list and print
bicycles = ["trek", "redline","hero"]
print(bicycles)
# In[2]:
#accessing first element in the list
print(bicycles[0])
# In[4]:
#Apply title()
print(bicycles[0].title())
# In[5]:
#replace element values
bicycles[0] = "Honda"
print(bicycles)
# In[6]:
#append
bicycles.append("ranger")
print(bicycles)
# In[7]:
#insert
bicycles.insert(1,"shine")
print(bicycles)
# In[8]:
#delete from a list
bicycles.pop()
print(bicycles)
# In[9]:
#delete specific element from a list
bicycles.pop(1)
print(bicycles)
# In[11]:
#sorting
cars = ["audi","bmw","benz","toyota"]
cars.sort()
print(cars)
# In[ ]:
|
5e9b2290612e3e0aa5ef6890ceba178ffa652746 | Selvaganapathi06/Python | /day11/day11.py | 593 | 3.84375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[4]:
#looping through dictionaries
un = {'uname':'first','first':'selva','last':'gana',
}
for key,value in un.items():
print(f"\nkey :{key}")
print(f"value: {value}")
# In[5]:
#looping through dictionaries only in key
un = {'uname':'first','first':'selva','last':'gana',
}
for keyvalue in un.keys():
print(f"\nkey :{keyvalue}")
# In[8]:
#looping through dictionaries only in value
un = {'uname':'first','first':'selva','last':'gana',
}
for onlyval in un.values():
print(f"\nvalue: {onlyval}")
# In[ ]:
|
4ae7aa620a792d6572689a306d945872c5eea614 | Selvaganapathi06/Python | /day22/day22.py | 641 | 3.984375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
#with out module
x = int(input("Enter X: "))
y = int(input("Enter y: "))
def add(a,b):
return a+b
def sub(a,b):
return a-b
def mul(a,b):
return a*b
ans1 = add(x,y)
ans2 = sub(x,y)
ans3 = mul(x,y)
print(ans1)
print(ans2)
print(ans3)
# In[7]:
#module
import mathlo
x = int(input("Enter X: "))
y = int(input("Enter y: "))
ans1 = mathlo.add(x,y)
ans2 = mathlo.sub(x,y)
ans3 = mathlo.mul(x,y)
print(ans1)
print(ans2)
print(ans3)
# In[2]:
#with module
import numpy as np
x = int(input("Enter X: "))
y = int(input("ENter Y: "))
vec1 = np.array([x,y])
vec2 = np.array([-x,-y])
|
eb7cb8206114685a655baf3fc8c43f9862743eca | jatinsinghal1921/TkinterPractice | /src/tkinter/dropdownMenu.py | 529 | 4.0625 | 4 | from tkinter import *
root = Tk()
root.title("Tk dropdown example")
label = Label(root, text="Choose a dish")
label.grid(row = 1, column = 1)
tkvar = StringVar(root)
choices = ['Pizza','Lasagne','Fries','Fish','Potatoe']
popupMenu = OptionMenu(root, tkvar, *choices)
popupMenu.grid(row = 2, column =1)
tkvar.set('Pizza') # set the default option
# on change dropdown value
def change_dropdown(*args):
print( tkvar.get() )
# link function to change dropdown
tkvar.trace('w', change_dropdown)
root.mainloop() |
e78c2aa541993df0a90cd216ea20b4f726efb7d1 | zackaryjwright-jcu/Tutorials | /prac_02/random_module_test.py | 266 | 3.78125 | 4 | import random
def main():
print(random.randint(5, 20)) # range between 5 & 20
print(random.randrange(3, 10, 2)) # range between 3 & 10, in steps of 2
print(random.uniform(2.5, 5.5)) # range between 2.5 & 5.5 (random floating point numbers)
main()
|
0faebc3fc76c558d4f942a46686b0e6580f9e47e | zackaryjwright-jcu/Tutorials | /prac_01/sales_bonus.py | 431 | 3.96875 | 4 | """
Program to calculate and display a user's bonus based on sales.
If sales are under $1,000, the user gets a 10% bonus.
If sales are $1,000 or over, the bonus is 15%.
"""
sales_value = float(input("Please enter the value of the Sales: $"))
if sales_value < 1000:
bonus = sales_value * 0.1
print("User's Bonus: ${:.2f}".format(bonus))
else:
bonus = sales_value * 0.15
print("User's Bonus: ${:.2f}".format(bonus))
|
7bc130847c8522ab5980dd0beedf333811f42ece | maj3r1819/Data-Structures-and-Algorithms | /Sorting Algorithms/MergeSort.py | 439 | 4.0625 | 4 | """
-Merge sort is a divide and sort algorithm
-Divide the input arrays into two halves and we keep halving recursively until they
become too small that they cannot be broken further
-Merge halves by sorting them
"""
def mergeSort(customList, l, m, r):
n1 = m - l +1
n2 = r - m
L = [0] * n1
R = [0] * n2
for i in range(n1):
l[i] = customList[l + i]
for i in range(n2):
R[i] = customList[m + 1 + i] |
177c7094bbfcd9eb79097b45e64bf5eaa5fcfb72 | maj3r1819/Data-Structures-and-Algorithms | /Linked List/Practice Questions/Remove_Duplicates.py | 1,075 | 3.875 | 4 | import sys
sys.path.insert(0, 'D:\Projects\Data-Structures-and-Algorithms\Linked List\Singly Linked List')
from SinglyLinkedListOperations import SLinkedList, Node
#Method to delete duplicates in a Linked List
def remove_duplicates(linked_list):
if linked_list.head is None:
return
else:
currNode = linked_list.head
visited_set = {currNode.value}
while currNode.next:
if currNode.next.value in visited_set:
currNode.next = currNode.next.next
else:
visited_set.add(currNode.next.value)
currNode = currNode.next
return linked_list
custom_ll = SLinkedList()
custom_ll.insertSLL(0,1)
custom_ll.insertSLL(1,1)
custom_ll.insertSLL(2,1)
custom_ll.insertSLL(3,1)
custom_ll.insertSLL(3,1)
print("----------------------------------")
print("Practice Question Starts!")
print("Original Linked List: ")
print([node.value for node in custom_ll])
remove_duplicates(custom_ll)
print("Linked List after deleting duplicates: ")
print([node.value for node in custom_ll])
|
20f0f8306f263e15b0a2b25c1c8d6be02b3b5cdd | maj3r1819/Data-Structures-and-Algorithms | /Linked List/Singly Linked List/SinglyLinkedList.py | 363 | 3.578125 | 4 | class Node:
def __init__(self, value = None):
self.value = value
self.next = None
class SLinkedList:
def __init__(self):
self.head = None
self.tail = None
singlylinkedlist = SLinkedList()
node1 = Node(1)
node2 = Node(2)
singlylinkedlist.head = node1
singlylinkedlist.head.next = node2
singlylinkedlist.tail = node2 |
80621b13fdeda586254ceee24d48f9cdcccc7b85 | maj3r1819/Data-Structures-and-Algorithms | /Linked List/Practice Questions/sum.py | 676 | 3.671875 | 4 | import sys
sys.path.insert(0, 'D:\Projects\Data-Structures-and-Algorithms\Linked List\Singly Linked List')
from SinglyLinkedListOperations import SLinkedList, Node
def num(linked_list):
num1 = 0
if linked_list.head is None:
return None
else:
currNode = linked_list.head
while currNode:
val = currNode.value
num1 = num1*10 + val
currNode = currNode.next
return num1
custom_ll = SLinkedList()
custom_ll.insertSLL(1,1)
custom_ll.insertSLL(2,1)
custom_ll.insertSLL(3,1)
custom_ll.insertSLL(3,1)
print("----------------------------------")
print([node.value for node in custom_ll])
print(num(custom_ll)) |
5199fbf404b12654c03c0ac45b9e7d8e8098ed14 | lero003/python | /繰り返し.py | 380 | 3.953125 | 4 | #for文
for i in range(5):
print(i)
#break文
for i in range(5):
if i == 3:
break
print(i)
#continue文
for i in range(5):
if i == 3:
continue
print(i)
#for文ネスト構造(sep引数)
for i in range(3):
for j in range(3):
print(i,j,sep="-")
#組み合わせ
arr = [2,4,6,8,10]
sum = 0
for i in arr:
sum += i
print(sum) |
b6099f7526fed35f165a9bff642904fbfb543c17 | Knifesurge/Hjalmion-The-Rise-Of-Fencor | /player.py | 917 | 3.640625 | 4 | #Nick Mills
class player():
def __init__(self, hp, max_hp, level, xp, xp_to_level, victory):
self.hp = hp
self.max_hp = max_hp
self.level = level
self.xp = xp
self.xp_to_level = xp_to_level
self.victory = victory
def is_alive(self):
return self.hp > 0 and not self.hp == 0
def levelUp(self):
self.level += 1
self.hp = 100
self.max_hp = self.hp + 10
self.xp_to_level = 100
print("You have reached level {}!".format(self.level))
return self.level, self.hp, self.max_hp, self.xp_to_level
class Player(player):
def __init__(self):
super().__init__(hp = 100,
max_hp = 100,
level = 1,
xp = 0,
xp_to_level = 100,
victory = 0)
|
b8b174f5b2a7d9854362c688ce86f1c4b373c990 | csitedexperts/CSE1321Python | /review/User.py | 493 | 4.03125 | 4 | # https://www.w3schools.com/python/python_classes.asp
class Student:
id
name = ""
age = 20
def __init__(self, id, name, age):
self.id = id
self.name = name
self.age = age
def sayHello(self):
print("Hello my name is: " + self.name )
print (" my id is ", self.id)
print (" I am ", self.age, " years old")
s1 = Student(101, "John", 36)
print("Name: ", s1.name)
print("Id: ", s1.id)
print("Age: ", s1.age)
s1.sayHello()
|
aff18d22d5353a8efcc12df358fec2ef580fe4c9 | rgraybeal/IntroToProg-Python | /Module05Assignment.py | 4,661 | 4.25 | 4 | # -------------------------------------------------#
# Title: Working with Dictionaries
# Dev: RRGraybeal
# Date: August 11, 2018
# ChangeLog: (Who, When, What)
# RRoot, 11/02/2016, Created starting template
# RRGraybeal, August 11,2018, Added code to complete assignment 5
# https://www.tutorialspoint.com/python/python_dictionary.htm
# 1. Create a text file called Todo.txt using the following data:
# Clean House,low
# Pay Bills,high
# 2. When the program starts, load each row of data from the ToDo.txt text file into a Python dictionary.
# (The data will be stored like a row in a table.)
# Tip: You can use a for loop to read a single line of text from the file and then place the data
# into a new dictionary object.
# 3. After you get the data in a Python dictionary, Add the new dictionary “row” into a Python
# list object (now the data will be managed as a table).
# 4. Display the contents of the List to the user.
# 5. Allow the user to Add or Remove tasks from the list using numbered choices. Something like this would work:
# Menu of Options
# 1) Show current data
# 2) Add a new item.
# 3) Remove an existing item.
# 4) Save Data to File
# 5) Exit Program
# 6. Save the data from the table into the Todo.txt file when the program exits.
# -------------------------------------------------#
# -- Data --#
# declare variables and constants
objFile = () #used to read and write to file
strNewTask = () #user input and key in dictionary
strPriority = () #user input and value in dictionary
strChoice = () #menu choice from user
dicToDo = {} #dictionary for Todo list
lstTable = [] # a list to hold the dictionary items
# -- Input/Output --#
# User can see a Menu (Step 2)
# User can see data (Step 3)
# User can insert or delete data(Step 4 and 5)
# User can save to file (Step 6)
# -- Processing --#
# Step 1
# When the program starts, load the any data you have
# in a text file called ToDo.txt into a python Dictionary.
with open("./ToDo.txt", "r") as objFile:
for row in objFile:
splitRow = row.strip().split(",")
dicToDo[splitRow[0]] = ",".join(splitRow[1:])
# # 3. After you get the data in a Python dictionary, Add the new dictionary “row”
# into a Python list object (now the data will be managed as a table).
for task, priority in dicToDo.items():
row = (task, priority)
lstTable.append(row)
# Step 2 - Display a menu of choices to the user
while (True):
print("""
Menu of Options
1) Show current data
2) Add a new item.
3) Remove an existing item.
4) Save Data to File
5) Exit Program
""")
strChoice = str(input("Which option would you like to perform? [1 to 4] - "))
print() # adding a new line
# Step 3 -Show the current items in the table
if (strChoice.strip() == '1'): # show current data
print("Your ToDo List:\n")
for task, priority in dicToDo.items(): #shows contents of dictionary
print(task, ":", priority)
continue
# Step 4 - Add a new item to the list/Table
elif (strChoice.strip() == '2'):
strNewTask = input("What task do you want me to add?:")
strNewTask = strNewTask.lower()
if strNewTask not in dicToDo:
strPriority = input("What is the priority?:")
dicToDo[strNewTask] = strPriority # add new task and priority to dictionary
row = (strNewTask, strPriority)#add new task and priority to list
lstTable.append(row) #append the new items to the Table
else:
print(strNewTask, "already exists. Try another")
# Step 5 - Remove a new item to the list/Table from book pg 145
elif (strChoice == '3'):
# try:
strRemoveTask = input("What would you like to remove? ")
strRemoveTask = strRemoveTask.lower()
if strRemoveTask in dicToDo:
del dicToDo[strRemoveTask]
print("\n", strRemoveTask, "has been deleted.")
else:
print("\nSorry, I was unable to remove", strRemoveTask, "as it isn't yet on the list.")
continue
# Step 6 - Save tasks to the ToDo.txt file
elif (strChoice == '4'):
with open("./ToDo.txt", "w") as objFile:
for task, priority in dicToDo.items():
objFile.write("%s:%s\n" % (task, priority))
print("Your data has been saved. ")
continue
# Step 7
# Exit program
elif (strChoice == '5'):
objFile.close()
break # and Exit the program
# -------------------------------
|
4f42463a24b317ac80bdb1a878510e2da9696b7e | Foxious/phEngine | /proto/DungeonGenerator.py | 2,747 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This temporary script file is located here:
C:\Users\Drachis\.spyder2\.temp.py
"""
import random
import math
class point():
def __init__(self,position = (0,0)):
self.position = position
class room():
def __init__(self):
#generate a room that will conect to a number of other rooms based on the number of exits it has
self.exits = self.numberOfExits()
self.neighbors = []
def numberOfExits(self,maximum=4):
#sugessted maximum of 8
self.exits = random.randint(1,maximum)
class dungeon():
def __init__(self):
self.roomNum= self.numberOfRooms()
self.rooms = []
self.fillDungeon()
def numberOfRooms(self,max=13):
return random.randint(5,max)
def fillDungeon(self):
i = 0
while i < self.roomNum:
i += 1
cell = room()
if cell.exits >= 2:
neighbors = 0
while neighbors < cell.exits:
neighbors += 1
i += 1
cell.neighbors.append(room())
self.rooms.append(cell)
def placeRoom(self, cell):
while self.roomNum < len(self.rooms) and len(cell.neighbors) < cell.exits:
pass
cell = room()
if cell.exits >= 2:
neighbors = 0
while neighbors < cell.exits:
neighbors += 1
i += 1
cell.neighbors.append(room())
self.rooms.append(cell)
def makeRoom(size):
room = list()
iterator = 0
while iterator <= size:
room.append(generateRow(size))
iterator +=1
return room
def generateCell():
value = [
'F',
'W',
'P',
][int(random.random()*3)]
return value
def generateRow(size):
dungeon = list()
for each in range(0,size+1):
dungeon.append(generateCell())
return dungeon
def selectRoom(roomlist):
placed = []
while len(placed) <= len(roomlist):
room = selectRoom(roomList)
if room not in placed:
placed.append(room)
return placed
def selectRoom(rooms):
return rooms[int(random.random()*len(rooms))]
class floor():
def __init__(self,size = (3,3)):
for i, value in size:
#size should only be holding a set of integers each greater than 3
if 3 > value :
size[i] = 3
self.size = size
#initial spawn is in the center of the floor
self.entrance = point(
position=(
random.randint(0, size[0]-1),
random.randint(0, size[1]-1)
)
) |
fa18f4de7c79fd258c18cceb2ff6fb5b3d69970e | watsonwanda/soulsurfer | /study/chapter_03/5-2.py | 992 | 3.6875 | 4 | def getArrayByIndex(index):
list = ['A','B','C','D','E','F','G','H']
if index < len(list):
print('선택한 값은 ', list[index], '입니다.')
else:
print(len(list), ' 보다 작은수를 입력하세요.')
print('수를 선택하세요.')
index = int(input())
getArrayByIndex(index)
listArray = ['A','B','C','D','E','F','G','H']
print(listArray[:])
listArray.append('123')
print(listArray[:])
listArray.insert(7,'777')
print(listArray[:])
listArray.extend(['1','2','3','4'])
print(listArray[:])
listArray.remove('777')
print(listArray[:])
listArray.pop()
print(listArray[:])
#list.clear()
#print(list[:])
print('reversed',listArray[::-1])
print(list('파이썬'))
print(tuple('파이썬'))
print(''.join(['가난하다고','외로움을','모르겠는가']))
print(''.join(('가난하다고','외로움을','모르겠는가')))
print('.'.join('가난,하다,고'.split(',')))
print('.'.join(listArray))
print('/'.join(listArray))
print('-'.join(listArray)) |
f45f0ba4bed8108779744d20296703b7b71616db | watsonwanda/soulsurfer | /study/chapter_08/8-6.py | 3,708 | 3.609375 | 4 | class Food():
# 음식을 나타내는 클래스
def __init__(self, taste, calorie, name):
# 인스턴스 초기화
self._taste = taste # 맛
self._calorie = calorie # 칼로리
self._name = name # 이름
def __str__(self):
# 음식 설명
return self._name + ' 은 ' + str(self._taste) + ' 이런 맛이고 ' + str(self._calorie) + ' 칼로리 입니다.'
def __add__(self, other):
# 맛을 더함
taste = self._taste + other._taste # 맛을 더함
calorie = self._calorie + other._calorie # 칼로리를 더함
return Food(taste, calorie, self._name + ' / ' + other._name + ' 이 합쳐진') # 새로운 인스턴스 반환
def __ge__(self, other):
# >=
# 음식평가, 맛이 좋으면 더큼. 같은맛이면 칼러리가 적은것이 큼. 모두 같으면 같음.
gapTaste = self._taste - other._taste
gapCalorie = self._calorie - other._calorie
foodName = ''
if(gapTaste > 0):
foodName = self._name
elif(gapTaste < 0):
foodName = other._name
elif(gapTaste == 0 and gapCalorie > 0):
foodName = self._name
elif(gapTaste == 0 and gapCalorie < 0):
foodName = other._name
elif(gapTaste == 0 and gapCalorie == 0):
foodName = self._name + '|' + other._name
print(foodName + ' 이 더 좋은 평가를 받았습니다. ', str(gapTaste), str(gapCalorie))
return foodName
def __lt__(self, other):
# <
# 음식평가, 맛이 좋으면 더큼. 같은맛이면 칼러리가 적은것이 큼. 모두 같으면 같음.
gapTaste = self._taste - other._taste
gapCalorie = self._calorie - other._calorie
foodName = ''
if(gapTaste > 0):
foodName = self._name
elif(gapTaste < 0):
foodName = other._name
elif(gapTaste == 0 and gapCalorie > 0):
foodName = self._name
elif(gapTaste == 0 and gapCalorie < 0):
foodName = other._name
elif(gapTaste == 0 and gapCalorie == 0):
foodName = self._name + '|' + other._name
print(foodName + ' 이(가) 더 좋은 평가를 받았습니다. ', str(gapTaste), str(gapCalorie))
return foodName
# food1 = Food(7, 68)
# print(food1.to_string())
# food2 = Food(1, 250)
# print(food2.to_string())
# food3 = food1.add(food2)
# print(food3.to_string())
# 아래 코드는 이중밑줄 메소드를 사용했을때 사용가능
# https://python.bakyeono.net/chapter-8-5.html 참고
# print(Food(7,85) + Food(3, 256))
# 코드 8-60 연산자 대신 이중 밑줄 메서드로 연산하기
# number = 10
# print('equal : ',number.__eq__(20))
# print('multiply : ',number.__mul__(5))
# print('less then : ',number.__lt__(20))
# print('isFloat : ',number.__float__())
# print('toString : ',number.__str__())
# print('isBool : ',number.__bool__())
# 연습문제 8-13 음식 클래스에 연산 추가하기
# < => __lt__
# >= => __ge__
# + < => __add__ __lt__
# == => __eq__
strawberry = Food(9, 32, '딸기')
potato = Food(6, 66, '감자')
sweet_potato = Food(12, 131, '고구마')
pizza = Food(13, 266, '핏자')
print('딸기 < 감자: ', strawberry < potato)
print('감자 + 감자 < 고구마: ', potato + potato < sweet_potato)
print('피자 >= 딸기: ', pizza >= strawberry)
print('피자 >= 피자: ', pizza >= strawberry)
print('감자 + 딸기 < 피자: ', potato + strawberry < pizza)
print('딸기 == 딸기: ', potato == potato)
|
00c71b45bda6460044e50a5d6966af191d907908 | iainrwolfheart/pythonpractice | /loop1.py | 162 | 3.578125 | 4 | msg=input("Write a sentence and I'll repeat: ")
i=0
word=""
while i<len(msg):
if msg[i]==" ":
print(word)
word=""
else:
word=word+msg[i]
i+=1
print(word) |
171ef477a1b1649bf005cbfb08b0b738f29a86d2 | iainrwolfheart/pythonpractice | /Changecalc2.py | 339 | 3.71875 | 4 | name=(input("What is your name?"))
sal=int(input("What's your salary?"))
ni=sal/100*12
if sal>=50000:
tax=sal/100*40
if sal in range(30000, 49999):
tax=sal/100*25
if sal in range(12500, 29999):
tax=sal/100*20
if sal<12500:
tax=0
print("Name:",name)
print("Salary:",sal)
print("N.I.:",ni)
print("Tax:",tax)
print("Net Sal:",sal-ni-tax)
|
aa41fbe812065538940ca7db0f2e0b1a1d5b4ad5 | MartijnWillemsAltran/DigitsRecognizer | /mlflow_runner/digits_recognizer.py | 1,376 | 3.640625 | 4 | from sklearn.datasets import load_digits
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPClassifier
from sklearn.preprocessing import StandardScaler
import mlflow
with mlflow.start_run():
mlflow.sklearn.autolog()
# Loading data
digits = load_digits(as_frame=True)
# Splitting the data in the input and the resulting output
x = digits.data
y = digits.target
# Splitting the data in test and training sets
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.50)
# Feature Scaling training data to values between -1 and 1.
# This makes it easier for the classifier to train
scaler = StandardScaler()
scaler.fit(x_train)
x_train = scaler.transform(x_train)
x_test = scaler.transform(x_test)
# Constructing a classifier and using it to train a new model
mlp = MLPClassifier(hidden_layer_sizes=(64, 128, 64), max_iter=1000, verbose=True)
mlp.fit(x_train, y_train.values.ravel())
# Validating the model using test data
predictions = mlp.predict(x_test)
mlflow.log_metric("Iterations", mlp.n_iter_)
mlflow.log_metric("Accuracy", accuracy_score(y_test, predictions))
for index in range(len(mlp.loss_curve_)):
mlflow.log_metric("Loss", mlp.loss_curve_[index], step=index+1)
|
28137d27ee05e26935519f5a037b52bf2dcbe2c9 | joren485/Sudokuplotter | /Main code/comb.py | 2,752 | 3.59375 | 4 | ## import all the neccessary libraries, os and the custom ones
import os
import algx
import finder
import motor_control
## Take the photo using raspistill.
print "Taking photo"
os.system("sudo raspistill -roi .4,0.05,1,1 -cfx 128:128 -w 600 -h 450 -q 100 -ex night -e jpg -sh 100 -co 100 -o image.jpg")
## Find the sudoku in the image using OCR.
sudoku = finder.OCR("image.jpg")
## Print out the found sudoku.
for row in sudoku:
string = ""
for digit in row:
string += str(digit) + " "
print string
## Do the necessary preprocessing before solving the sudoku.
Set, keys, values = algx.sudo2set(sudoku)
matrix = {}
for i in xrange(len(keys)):
key = keys[i]
matrix[key]=[]
for value in values:
if value in Set[key]:
matrix[key].append(1)
else:
matrix[key].append(0)
## Solve the sudoku.
print "solving"
solutions = algx.exactcover(matrix)
## Print out the solved sudoku.
sudostring = ""
for i in sorted(solutions[0]):
sudostring += str(i[2]) + " "
solved_sudoku = [sudostring[i:i+18] for i in xrange(0, 81*2, 18)]
for i in solved_sudoku:
print i
### Select first solution and convert it into needed steps
solution = finder.split_len( sorted( solutions[0] )[::-1], 9)
## Filter the points that need to be filled and sort them the right way.
steps = []
for row in range(9):
if row%2 == 0:
for digit in solution[row][::-1]:
row = digit[0]
column = digit[1]
if sudoku[row][column] == "x":
steps.append( digit)
else:
for digit in solution[row]:
row = digit[0]
column = digit[1]
if sudoku[row][column] == "x":
steps.append(digit)
## 1 cell takes 1850 rotations of 1 motor, so 1/6 of 1 cell = 308.33
## To correct small defects, we rounded 308.33 down to 300
x = 300
## calculate and set step to the first digit start
print motor_control.steps_calc( None, steps[0])[0]
motor_control.set_step( motor_control.steps_calc( None, steps[0])[0], x)
## Move the pen down so it hits the paper.
motor_control.pen_down(90)
for step_i in xrange( len( steps ) ):
## Print out the number and the cell the solver is going to write.
print steps[step_i]
## Write the number
motor_control.write_number( steps[step_i], x )
## If the number is not the 81st number the program needs to go to the next number.
## The program calculates the path it needs to take.
if step_i < len(steps) - 1 :
print motor_control.steps_calc( steps[step_i] , steps[ step_i+1] )
motor_control.set_step( motor_control.steps_calc( steps[step_i] , steps[ step_i+1] ), x )
## Move the pen up because the sudoku is solved.
motor_control.pen_up(90)
|
f46f595c87f154ddb2dc131e80cf13f23489fe30 | surajbarailee/PythonExercise | /python_topics/file_handling.py | 5,380 | 4.375 | 4 | # text file and binary file
# Python Image Library
# inbuilt open function
# open(filename, mode)
# Modes
# r = for reading – The file pointer is placed at the beginning of the file. This is the default mode.
# The r throws an error if the file does not exist or opens an existing file without truncating it for reading; the file pointer position at the beginning of the file.
# r+ = Opens a file for both reading and writing. The file pointer will be at the beginning of the file.
# The r+ throws an error if the file does not exist or opens an existing file without truncating it for reading and writing; the file pointer position at the beginning of the file.
# w = Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.
# The w creates a new file or truncates an existing file, then opens it for writing; the file pointer position at the beginning of the file.
# w+ = Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, it creates a new file for reading and writing.
# The w+ creates a new file or truncates an existing file, then opens it for reading and writing; the file pointer position at the beginning of the file.
# rb+ = Opens a file for both reading and writing in binary format.
# rb = Opens a file for reading only in binary format. The file pointer is placed at the beginning of the file.
# wb+ = Opens a file for both writing and reading in binary format. Overwrites the existing file if the file exists. If the file does not exist, it creates a new file for reading and writing.
# a = Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.
# The a creates a new file or opens an existing file for writing; the file pointer position at the end of the file.
# ab = Opens a file for appending in binary format. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.
# a+ = Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.
# The a+ creates a new file or opens an existing file for reading and writing, and the file pointer position at the end of the file.
# ab+ = Opens a file for both appending and reading in binary format. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.
# # x = open for exclusive creation, failing if the file already exists (Python 3)
# https://mkyong.com/python/python-difference-between-r-w-and-a-in-open/#:~:text=The%20r%20means%20reading%20file,and%20writing%20file%2C%20append%20mode.
# r r+ w w+ a a+
# read * * * *
# write * * * * *
# create * * * *
# truncate * *
# position at start * * * *
# position at end * *
# P.S In this context, truncate means delete the content of the file.
# file = open("abcd.txt", "r")
# print(file.read())
# file.close()
# print("=========================================")
# file = open("abcd.txt", "r")
# print(file.read(5))
# file.seek(0)
# print(file.read(20))
# print(file.read(5))
# print(file.read(5))
# file.close()
# file = open("abcd.txt", "r")
# print(file.readline())
# print(file.readline())
# print(file.readline())
# file.close()
# file = open("abcd.txt", "r")
# print(file.readlines())
# file.close()
# print("====================================\n")
# Check this out
# file = open("abcd.txt", "r")
# the value passed to file is iterable
# print(len(file.readlines()))
# for line in file:
# print(file.readline())
# file.close()
# f = open("abcd1.txt", "w")
# f.write("This is a testing write")
# f.close()
# f = open("abcd123.txt", "w")
# f.write("This is a testing write that is overwritten")
# f.close()
# f = open("abcd1.txt", "a")
# f.write("This is a testing write that is appended")
# f = open("cotiviti.txt", "x")
# f.write("This is a testing write that is appended")
# # deleting a file in python
# import os
# os.remove("cotiviti.txt")
# os.path.exists to check file
# os.rmdir to delete directory
# os.rename(old_file_name, new_file_name) to rename file
# f = open("abcd123.bin", "wb")
# s = str.encode("This is a testing write that is appended")
# f.write(s)
# f = open("abcd123.bin", "rb")
# data = f.read() b'This is a testing write that is appended' b'\x36\x23\'
try:
f = open("cotiviti.txt", "x")
except FileExistsError:
print("File already exists")
read = open("cotiviti.txt", "r")
lines = len(read.readlines())
read.close()
f = open("cotiviti.txt", "a")
f.write(
f"\n This is a testing write that is appended in the line number {lines + 1}"
)
else:
f.write("this will be the first line number 1")
finally:
f.close()
print("File is closed")
# Context Manager
# f = open("cotiviti.txt", "r")
try:
f = open("cotiviti.txt", "r")
except FileNotFoundError:
pass
else:
f.read()
finally:
f.close()
|
edb0162e3d1c5b0582c9305da3fe9aff1d9a317b | surajbarailee/PythonExercise | /python_topics/generators.py | 2,369 | 4.53125 | 5 | """
Retur:. A function that returns a value is called once. The return statement returns a value and exits the function altogether.
Yield: A function that yields values, is called repeatedly. The yield statement pauses the execution of a function and returns a value. When called again, the function continues execution from the previous yield. A function that yields values is known as a generator.
# https://www.codingem.com/wp-content/uploads/2021/11/1_iBgdO1ukASeyaLtSv3Jpnw.png
A generator function returns a generator object, also known as an iterator.
The iterator generates one value at a time. It does not store any values. This makes a generator memory-efficient.
Using the next() function demonstrates how generators work.
In reality, you don’t need to call the next() function.
Instead, you can use a for loop with the same syntax you would use on a list.
The for loop actually calls the next() function under the hood.
"""
def infinite_values(start):
current = start
while True:
yield current
current += 1
"""
When Use Yield in Python
Ask yourself, “Do I need multiple items at the same time?”.
If the answer is “No”, use a generator.
The difference between return and yield in Python is that return is used with regular functions and yield with generators.
The return statement returns a value from the function to its caller. After this, the function scope is exited and everything inside the function is gone.
The yield statement in Python turns a function into a generator.
A generator is a memory-efficient function that is called repeatedly to retrieve values one at a time.
The yield statement pauses the generator from executing and returns a single value. When the generator is called again, it continues execution from where it paused. This process continues until there are no values left.
A generator does not store any values in memory. Instead, it knows the current value and how to get the next one. This makes a generator memory-efficient to create.
The syntactical benefit of generators is that looping through a generator looks identical to looping through a list.
Using generators is good when you loop through a group of elements and do not need to store them anywhere.
"""
# https://docs.python.org/3/howto/functional.html#generator-expressions-and-list-comprehensions |
2b9430393d60953cbcab7a207f6c4e637814d4a1 | surajbarailee/PythonExercise | /python_topics/randoms/polymorphism-3 methodoverloadingoverriding.py | 368 | 3.890625 | 4 | #Method overloading
class Student:
def __init__(self,m1,m2):
self.m1=m1
self.m2=m2
def sum(self,a,b,c=None):
s=a+b
return s
s1=Student(58,69)
print(s1.sum(5,9))
#Method overriding
class A:
def show(self):
print("in a show")
class B(A):
def show(self):
print("in b show")
pass
a1=B()
a1.show() |
a04dac292585096e840d4a039907724754b29b69 | surajbarailee/PythonExercise | /python_topics/randoms/Sets.py | 278 | 3.765625 | 4 | #not duplicate unordered and unindexed
thisset={"apple","mango","mango","apple"}
print(thisset)
#cannot change but add
thisset.add("another apple")
thisset.update(["another mango","another kela"])
print(thisset)
abcd="aabbccddssdfsdfsddddfsdfsdfsdf"
abcd=set(abcd)
print(abcd) |
b03282cb9349e6bbad73609dcfe369287d6fa6e6 | surajbarailee/PythonExercise | /python_topics/strings.py | 973 | 4.375 | 4 | """
Strings in python
"""
string = "Hello*World!"
"""
H e l l o * W o r l d !
0 1 2 3 4 5 6 7 8 9 10 11
-12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
"""
print(string[2:]) # get every element from second index
print(string[-2:]) # get every element from -2
print(string[2:6]) #get every element from second element to sixth (sixth exclusive)
print(string[2:-6])
print(string[::2])
print(string[::-1])
print(string[::-2])
print(string[::-3])
print(string[6:1:-2]) # get every second element from 6 to 1 in reversed
print("=====")
print(string[3::-3]) # get evey third element starting from 3 in reversed
print(string[11:11])
print(len(string))
print(string.upper())
print(string.lower())
print(string.upper())
print(string.lower())
print(string.capitalize())
print(string.title())
print(string.swapcase())
print(string.strip())
print(string.lstrip())
print(string.rstrip())
print(string.replace("World", "Universe"))
|
c971d2c838a4e3d69730865fc072be9974a70a6f | haojian/python_learning | /1. twosum.py | 1,000 | 3.75 | 4 | # Given an array of integers, find two numbers such that they add up to a specific target number.
#
# The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
#
# You may assume that each input would have exactly one solution.
#
# Input: numbers={2, 7, 11, 15}, target=9
# Output: index1=1, index2=2
class Solution:
# @return a tuple, (index1, index2)
def twoSum(self, num, target):
map = {}
for i in range(0, len(num)):
if map.has_key(target-num[i]):
return (map[target-num[i]]+1, i+1)
else:
map[num[i]] = i
def twoSum_v1(self, num, target):
map = {}
for idx, val in enumerate(num):
if target-val in map:
return (map[target-val]+1, idx+1)
else:
map[val] = idx
if __name__ == "__main__":
# print __name__
sol = Solution()
print sol.twoSum([1, 2], 3)
print sol.twoSum_v1([1, 2], 3) |
e6c6fef0b0262ef221e5b0d366b754dd6aad3a9c | haojian/python_learning | /4. add2num.py | 763 | 3.65625 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @return a ListNode
def addTwoNumbers(self, l1, l2):
preHeader = ListNode(0)
cur = preHeader
carry = 0
while l1 and l2:
tmp = l1.val + l2.val + carry
carry = tmp / 10
cur.next = ListNode( tmp - carry*10 )
l1 = l1.next
l2 = l2.next
cur = cur.next
while l1:
tmp = l1.val + carry
carry = tmp / 10
cur.next = ListNode( tmp - carry*10 )
l1 = l1.next
cur = cur.next
while l2:
tmp = l2.val + carry
carry = tmp / 10
cur.next = ListNode( tmp - carry*10 )
l2 = l2.next
cur = cur.next
if carry > 0:
cur.next = ListNode(carry)
return preHeader.next |
d116a621877ed86d22fcc2d83aee141196172652 | haojian/python_learning | /37. solveSudoku.py | 924 | 3.8125 | 4 | class Solution:
# @param board, a 9x9 2D array
# Solve the Sudoku by modifying the input board in-place.
# Do not return any value.
def solveSudoku(self, board):
self.dfs(board)
def dfs(self, board):
for row in range(9):
for col in range(9):
if board[row][col] == '.':
for k in "123456789":
board[row][col] = k
if self.isValid(board, row, col) and self.dfs(board):
return True
board[row][col] = '.'
return False
return True
def isValid(self, board, tr, tc):
target = board[tr][tc]
board[tr][tc] = 'D'
#check row
for row in range(9):
if board[row][tc] == target:
return False
#check col
for col in range(9):
if board[tr][col] == target:
return False
#check cube
for row in range(3):
for col in range(3):
if board[(tr/3)*3+row][(tc/3)*3+col] == target:
return False
board[tr][tc] = target
return True |
27a3f6e6bf1aa242ba93b4607cc7c652051bc71a | haojian/python_learning | /20. validparentheses.py | 496 | 3.796875 | 4 | class Solution:
# @return a boolean
def isValid(self, s):
leftP = ['(', '{', '[' ]
rightP = [')', '}', ']']
stack = []
for char in s:
if char in leftP:
stack.append(char)
elif char in rightP:
if len(stack) == 0:
return False
left = stack.pop()
if leftP.index(left) != rightP.index(char):
return False
else:
return False
return len(stack) == 0
if __name__ == "__main__":
# print __name__
sol = Solution()
print sol.isValid("()())")
|
ef8d060d4b11278ae846fd163b4daf4866ea6007 | haojian/python_learning | /14. longestcommonprefix.py | 629 | 3.796875 | 4 | class Solution:
# @return a string
def longestCommonPrefix(self, strs):
if len(strs) == 0:
return ''
if len(strs) == 1:
return strs[0]
if len(strs) == 2:
return self.getCommonPrefix(strs[0], strs[1])
left = strs[:len(strs)/2]
right = strs[len(strs)/2:]
return self.getCommonPrefix( self.longestCommonPrefix(left), self.longestCommonPrefix(right) )
def getCommonPrefix(self, str1, str2):
res = ''
for char1, char2 in zip(str1, str2):
if char1 == char2:
res += char1
else:
break
return res
if __name__ == "__main__":
sol = Solution()
print sol.longestCommonPrefix(["a", "a", "b"]) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.