blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
09e7598d58e01c75e13890667a18bf6a856405c2
|
hoainguyen1999/baithuchanh
|
/bai3.c9.py
| 846 | 3.953125 | 4 |
#chuong trình máy tính thực hiện các phép tính cộng, trừ, nhân , chia
#phép cộng hai so
def add(x,y):
return x + y
#phép trừ 2 so
def subtract(x,y):
return x - y
#phép nhân 2 so
def multiply(x,y):
return x*y
#phép chia 2 so
def divide(x,y):
return x/y
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
#take input from the user
choice = input("Enter choice(1/2/3/4):")
num1 = int(input("Enter first number:"))
num2 = int(input("Enter second number:"))
if choice == '1':
print(num1,"+",num2,"=",add(num1,num2))
elif choice =='2':
print(num1,"-",num2,"=",subtract(num1,num2))
elif choice =='3':
print(num1,"*",num2,"=",multiply(num1,num2))
elif choice =='4':
print(num1,"/",num2,"=",divide(num1,num2))
else:
print("invalid input")
|
ec21c76bddb291ae51f61d59c32cff7252ee31f6
|
myf-algorithm/Leetcode
|
/Huawei/40.输入一行字符,分别统计出包含英文字母、空格、数字和其它字符的个数.py
| 432 | 3.78125 | 4 |
while True:
try:
a = input()
char, space, number, other = 0, 0, 0, 0
for i in a:
if i == " ":
space += 1
elif i.isnumeric():
number += 1
elif i.isalpha():
char += 1
else:
other += 1
print(char)
print(space)
print(number)
print(other)
except:
break
|
ee1be409c13fd286cfae94e0890b48008329a387
|
ChristopherDaigle/Learning_and_Development
|
/Udemy/Learn_Python_Programming_Masterclass/ifChallenge/ifChallenge.py
| 645 | 4.21875 | 4 |
# Write a small program to ask for a name and an age.
# When both values have been entered, check if the person
# is the right age to on a 18-30 holiday (they must be
# over 18 and under 31).
# If they are, welcome them to the holiday, otherwise print
# a (polite) message refusing them entry.
name = input('Enter your name: ')
age = int(input('How old are you, {0}? '.format(name)))
if (age < 18) or (age > 30):
print("Sorry {0}, you can't go on holiday.".format(name))
if age < 18:
print('You can come back in {0} years to go on the holiday.'.format(18-age))
else:
print('Welcome to the 18-30 holiday, {}!'.format(name))
|
4434501a64212ab9c1255ca20ae1693a44a7f7ff
|
dr-dos-ok/Code_Jam_Webscraper
|
/solutions_python/Problem_118/1960.py
| 766 | 3.59375 | 4 |
import math
def palindrome(word):
return word == word[::-1]
def main(file):
inputfile = open(file, 'r')
howmany = int(inputfile.readline()) # how many test cases are there?
stage = 0
outputfile = open('C-small-attempt1.out', 'wd')
while stage < howmany:
word = inputfile.readline().split()
s,f = int(word[0]),int(word[1])+1 #starting and finishing integer for the interval
count = 0
for squrenumber in range(s,f):
if palindrome(str(squrenumber)):
if math.sqrt(squrenumber).is_integer():
if palindrome(str(int(math.sqrt(squrenumber)))):
count += 1
stage += 1
msg = "Case #" + str(stage) + ": " + str(count) + "\n"
outputfile.write(msg)
if __name__ == '__main__':
main('C-small-attempt1.in')
|
b60f9559461058da513fdf491df80bd8386b5953
|
RealDannyTM/Python-Assignments
|
/Functions.py
| 417 | 3.921875 | 4 |
"""Python is Easy - Assignment #2 - Functions
Favorite Song"""
# Functions
def Artist():
ArtistName = "Duncan Lawrence"
return ArtistName
def Song():
SongName = "Arcade"
return SongName
def Awards():
AwardsName = "Album: Eurovision Song Contest Tel Aviv 2019"
return AwardsName
def Year2019():
return True
# Output
print (Artist())
print (Song())
print (Awards())
print (Year2019())
|
a9fe4064f0aa9a13bc6afcfec7b666f3977ff9e9
|
mjdecker-teaching/mdecke-1300
|
/notes/python/while.py
| 1,958 | 4.28125 | 4 |
##
# @file while.py
#
# While-statement in Python based on: https://docs.python.org/3/tutorial
#
# @author Michael John Decker, Ph.D.
#
#while condition :
# (tabbed) statements
# condition: C style boolean operators
# tabbed: space is significant.
# * Avoid mixing tabs and spaces, Python relies on correct position
# and mixing may leave things that look indented correctly, but are not
# * http://www.emacswiki.org/emacs/TabsAreEvil
#
# How might you compute fibonacci (while number is less than 10)?
last = 0
current = 1
while last < 10 :
print(last)
temp = current
current = last + current
last = temp
# Python improvement 1) multiple assignment
# first is in C++, other is not
last, current = 0, 1
while last < 10 :
# need to indent
print(last)
# no temp!!! All, rhs is evaluated before any actual assignment
last, current = current, last + current
# conditions
# * boolean: True, False
while True :
print('Do not do this: ^C to stop')
while False :
print('Never executed')
# * integer: 0 False, True otherwise
count = 10;
while count :
print(count)
count -= 1
# * sequence: len() == 0 False, True otherwise
sequence = ['bar', 'foo']
while sequence :
print(sequence[-1])
tos = sequence.pop()
# Python supports usually comparisons and
# 'and', 'or' and 'not'(C++ has these, but have different precedence)
# https://docs.python.org/3/library/stdtypes.html
# notice that ! is not suppported. Python 2 had <> as well (!=)
# conditions can be chained (but are ands)
x = 1
y = 2
z = 3
x < y <= z
# print is a bit ugly...
# Here is simple print usage: Multiple arguments are handled
# They are space separated, no quotes for strings, and ending in a newline
print("256 ** 2:", 256 ** 2)
last, current = 0, 1
while last < 10 :
# We can specifiy the end character (this is a keyword argument, more when we see functions)
print(last, end=',')
last, current = current, last + current
|
bfc77f5f3600e9e0418ce31447e1f29e5f2b9352
|
b-douglas/ordergroove-to-cybersource-payment-migration-python
|
/misc/extractIdsNoCreditCards.py
| 7,037 | 3.640625 | 4 |
#!/usr/bin/python
"""
Created on Oct 08, 2020
extractIdsNoCreditCards.py
Script runs and extracts the records WITHOUT decrypting the credit card numbers.
@author: dougrob
"""
import configparser
import csv
# import os
# import re
import sys
import base64
import time
# ## Function to open a file as a csv
# ## All of the files are treated as a Csv, whether they are true CSVs or not.
# ## The reason for this is so that if a file needs more columns we have that ability
def open_csv(fname, t="r", fieldnames=""):
""" Function to open a csv file """
fhand = open(fname, t)
if t == "r":
csvfile = csv.DictReader(fhand, dialect='excel')
else:
csvfile = csv.DictWriter(
fhand, dialect='excel', quoting=csv.QUOTE_NONE, fieldnames=fieldnames)
return csvfile
def trace(level, string):
""" Trace function """
if level <= int(config.get('Debug', 'LogLevel')):
print('%s' % string)
sys.stdout.flush()
def decodeCardType(string):
""" Mapping function that converts card types into Cybersource numbers """
cardtype = string.strip().lower()
typecode = "-1"
if cardtype == "visa":
typecode = "001"
elif cardtype == "mastercard" or cardtype == "eurocard":
typecode = "002"
elif cardtype == "american express":
typecode = "003"
elif cardtype == "discover":
typecode = "004"
elif cardtype == "diners club":
typecode = "005"
elif cardtype == "carte blanche":
typecode = "006"
elif cardtype == "jcb":
typecode = "007"
else:
trace(1, "ERROR! Credit Card Type does not match!")
raise ValueError("Credit Card Type does not match!")
return typecode
def formatCyberSourceCSVHeader(recordCount):
""" Function to format the correct CSV Header that Cybersource expects for Batch Upload"""
try:
d = time.strftime("%Y-%m-%d")
batchId = "%s%s" % (config.get(
'Cybersource', 'batchPrefix'), time.strftime("%H%M"))
s = config.get('Cybersource', 'header', vars={
"merchantid": config.get('Cybersource', 'merchantId'),
"batchid": batchId,
"date": d,
"email": config.get('Cybersource', 'statusEmail'),
"recordCount": recordCount
})
return s + "\n"
except Exception as e:
raise e
def decodeOrderGroove(input_file):
""" Decode OrderGroove function
This is the main decode function
It starts off reading in the csv file provided by Order Groove
Then it it puts those into a dictionary
then it decodes each of the Credit Card Numbers
"""
ogcsv = open_csv(input_file)
decodedDictionary = {}
for row in ogcsv:
try:
if len(row) > 0:
rowdict = {
# "paySubscriptionCreateService_disableAutoAuth": "TRUE",
# "merchantReferenceCode": "ogsub" + row["OG Customer ID"].strip() + row["OG Public Payment ID"].strip()[:5],
# "merchantDefinedData_field1": row["OG Customer ID"].strip(),
# "merchantDefinedData_field3": int(decodeCardType(row["CC Type"].strip())),
"merchantDefinedData_field4": row["OG Public Payment ID"].strip(),
# "billTo_firstName": row["Billing First"].strip(),
# "billTo_lastName": row["Billing Last"].strip(),
# "billTo_street1": row["Billing Address 1"].strip(),
# "billTo_street2": row["Billing Address 2"].strip(),
# "billTo_city": row["Billing City"].strip(),
# "billTo_state": row["Billing State"].strip(),
# "billTo_postalCode": row["Billing Zip"].strip()[:5],
# "billTo_country": row["Billing Country"].strip(),
# "billTo_phoneNumber": row["Billing Phone"].strip(),
"billTo_email": row["Email Address"].strip(),
# "card_cardType": decodeCardType(row["CC Type"].strip())
}
trace(5, "%s" % rowdict)
decodedDictionary[row["OG Public Payment ID"].strip()
] = rowdict
else:
trace(3, "Row length was 0")
except Exception as error:
print("Error! %s had the following error %s" %
(row["OG Public Payment ID"], error))
return decodedDictionary
def onlyGood(decodedDictionary, input_file):
""" Only Good
This function takes in another input file with sucessful entries and then creates a new dictionary with only the good ones.
"OGPublicPaymentID","cybersourceToken","ccExpDate","ccType","cybstatus_optional"
"""
ogcsv = open_csv(input_file)
goodones = {}
for row in ogcsv:
try:
if len(row) > 0:
# print(row)
ogpayid = row["OGPublicPaymentID"].strip()
status = row["cybstatus_optional"].strip()
if(status == "100"):
#trace(2, "good - %s" % row)
if ogpayid in decodedDictionary:
goodones[ogpayid] = decodedDictionary[ogpayid]
else:
trace(2, "bad - %s" % row)
else:
trace(3, "Row length was 0")
except Exception as error:
print(error)
print("Error! %s had the following error %s" %
(row["OGPublicPaymentID"], error))
raise error
return goodones
# ## Output Writer
def writeOutput(dictionary, ofile):
""" Function that will write the output file for Cybersource """
f = open(ofile, "w")
# f.write(formatCyberSourceCSVHeader(len(dictionary)))
# f.write("\n")
fnames = "merchantDefinedData_field4,billTo_email"
csvfile = csv.DictWriter(f, dialect='excel',
fieldnames=fnames.split(','))
csvfile.writeheader()
for key, rowdict in dictionary.items():
try:
csvfile.writerow(rowdict)
except Exception as error:
print("Error! %s had the following error %s" % (error, rowdict))
f.write("\n")
# f.write("END,SUM=0")
# f.write("\n")
# f.write("\n")
f.close()
# # This is the main Function for decodeOrderGroove.py
# # This is where it all starts. The Main Function
if __name__ == '__main__':
# # Set up global variables
# Note: We must use Raw Config Parser to prevent interpolation of '%' and other weird characters
config = configparser.ConfigParser()
config.read_file(open('./config.ini'))
inputfile = config.get('Base', 'input_file')
outputfile = config.get('Base', 'tocyb_file')
trace(3, "Output file is %s" % outputfile)
# Open & Decode File
decodedDictionary = decodeOrderGroove(inputfile)
successDict = onlyGood(decodedDictionary, "toog.csv")
# Write output file
writeOutput(successDict, outputfile)
|
88235f3f70c8ca46b98baebca9ac41645ea47010
|
vibhootiagrawal/python_course
|
/number_game.py
| 1,308 | 3.96875 | 4 |
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 13 21:42:45 2019
@author: Education
"""
import random
secret_number=random.randint(1,10)
chance=0
def chancer():
n=6
if(n>0):
chance=n-1
n=n-1
return chance
def gamer():
guess_number=int(input("enter number"))
if(guess_number>0):
if(secret_number==guess_number):
print("player wins and computer loss")
else:
print("player loss and computer wins")
print("secret_number{},guess_number{}".format(secret_number,guess_number))
if(guess_number>secret_number):
print("too High")
elif(guess_number<secret_number):
print("too LOW")
#else:
#pass
a=chancer()
print("number of try left",a)
for i in range(1,6):
option=input("do u want to play again:")
if(option=="play again"):
gamer()
else:
break
else:
print("number is not integer")
gamer()
if(secret_number!=guess_number):
for i in range(1,6):
option=input("do u want to play again:")
if(option=="play again"):
gamer()
else:
break
else:
option=input("do u want to play again:")
if(option=="play again"):
gamer()
else:
print("quit")
|
fcd111e1188cef8074a98cb30353e8d63bdcaa8a
|
dr-dos-ok/Code_Jam_Webscraper
|
/solutions_python/Problem_1/607.py
| 3,109 | 4.03125 | 4 |
#!/usr/bin/env python2.5
def solve_case(engines, queries):
"""
Problem
The urban legend goes that if you go to the Google homepage and search for
"Google", the universe will implode. We have a secret to share... It is
true! Please don't try it, or tell anyone. All right, maybe not. We are
just kidding.
The same is not true for a universe far far away. In that universe, if you
search on any search engine for that search engine's name, the universe
does implode!
To combat this, people came up with an interesting solution. All queries
are pooled together. They are passed to a central system that decides which
query goes to which search engine. The central system sends a series of
queries to one search engine, and can switch to another at any time.
Queries must be processed in the order they're received. The central system
must never send a query to a search engine whose name matches the query. In
order to reduce costs, the number of switches should be minimized.
Your task is to tell us how many times the central system will have to
switch between search engines, assuming that we program it optimally.
"""
# Solution: dynamic programming: starting from the end, know how many
# switches we need if we start with each possible engine. We could start
# from the beginning since the problem is symmetric in time - but it's
# easier to understand if we start from the end.
switches = dict((e, 0) for e in engines)
for q in reversed(queries):
# We only have to switch if we start from `q`.
# Other values don't need to be updated.
switches[q] = min(switches[q2] + 1 for q2 in engines if q2 != q)
return min(switches.values())
def main(lines):
"""
Input
The first line of the input file contains the number of cases, N. N test
cases follow.
Each case starts with the number S -- the number of search engines. The
next S lines each contain the name of a search engine. Each search engine
name is no more than one hundred characters long and contains only
uppercase letters, lowercase letters, spaces, and numbers. There will not
be two search engines with the same name.
The following line contains a number Q -- the number of incoming queries.
The next Q lines will each contain a query. Each query will be the name of
a search engine in the case.
Output
For each input case, you should output:
Case #X: Y
where X is the number of the test case and Y is the number of search engine
switches. Do not count the initial choice of a search engine as a switch.
"""
lines = (line.strip() for line in lines)
N = int(lines.next())
for case in range(1, N + 1):
S = int(lines.next())
engines = [lines.next().strip() for i in range(S)]
Q = int(lines.next())
queries = [lines.next().strip() for i in range(Q)]
print "Case #%s: %s" % (case, solve_case(engines, queries))
if __name__ == '__main__':
import fileinput
main(fileinput.input())
|
ae638a0615b4fa76f47658223ccc33baf0a59348
|
Sandeep1525/99005039
|
/assignment/count_less_mean.py
| 329 | 3.65625 | 4 |
def mean_cnt(l):
index=0
if not l:
print("Empty list")
return 0
else:
mean=sum(l)//len(l)
l.append(mean)
l.sort()
print(l)
for i in range(len(l)):
if mean==l[i]:
index=i
print(index-1)
return 1
|
1203dea80ff38f3957cd60ec055773133b32da28
|
IeuanOwen/LPTHW
|
/LPTHW/LPTHWEX18.py
| 1,552 | 4.5 | 4 |
# Learn Python the hard way EX18
# this is like your scripts with argv
def print_two(*args):
arg1, arg2 = args
print "arg1: %r, arg2: %r" % (arg1, arg2)
# ok, that *args is actually pointless, we can just do this
def print_two_again(arg1, agr2):
print "arg1: %r, arg2: %r" % (arg1, arg2)
# this just takes one argument
def print_one(arg1):
print "arg1: %r" % (arg1)
# this one take no arguments
def print_none():
print "I got nothing"
print_two("Zed", "Shaw")
print_two_again("Zed", "Shaw")
print_one("First!")
print_none()
# Study Drills
## 1 ~ Create a checklist for Function creation
# ~ Did you start your function defi nition with def?
# ~ Does your function name have only characters and _ (underscore) characters?
# ~ Did you put an open parenthesis ( right after the function name?
# ~ Did you put your arguments after the parenthesis ( separated by commas?
# ~ Did you make each argument unique (meaning no duplicated names)?
# ~ Did you put a close parenthesis and a colon ): after the arguments?
# ~ Did you indent all lines of code you want in the function four spaces? No more, no less.
# ~ Did you “end” your function by going back to writing with no indent (dedenting we call it)?
# And when you run (“use” or “call”) a function, check these things:
# ~ Did you call/use/run this function by typing its name?
# ~ Did you put the ( character after the name to run it?
# ~ Did you put the values you want into the parenthesis separated by commas?
# ~ Did you end the function call with a ) character?
|
bb82b1d8d24af2f9dff9d473436f9e7493887e6c
|
Anjytka/Project
|
/pythPlugins/Fiction/moving_average.py
| 2,035 | 3.90625 | 4 |
# -*- coding: utf-8 -*-
"""
data - усредняемые данные
w - размер окна
"""
def moving_average(data, w):
length = len(data)
if (w > length):
raise Exception("Окно должно быть меньше количества замеров")
aver = []
for i in range(length - w + 1):
aver.append(reduce(lambda x, y: x + y, data[i:i+w]) / w)
for i in range(length - w + 1, length):
prev = aver[-1]
prev_w = aver[-w]
k = length - i
aver.append(prev-(prev_w+data[i])/w)
return aver
"""
data - усредняемые данные
w - размер окна
"""
def moving_exp_average(data, w):
length = len(data)
if (w > length):
raise Exception("Окно должно быть меньше количества замеров")
aver = [data[0]]
alpha = float(2)/(w+1)
for i in range(1,length):
aver.append(data[i]*alpha + (1-alpha)*aver[-1])
return aver
"""
acc - ускорение
time - время
w - размер окна
"""
def calc_coord_ma(acc, time, w):
acc_ma = []
for i in range(len(acc)):
acc_ma.append(moving_average(acc,w))
res = [0]
v = x = 0
print len(acc_ma), len(time)
for i in range(len(acc_ma)-1):
t = time[i]
if i == 0:
print acc_ma[i+1], time[i+1], t
v = v + acc_ma[i+1]*(time[i+1]-t)
x = x + v*(time[i+1]-t) + acc_ma[i+1]*pow(time[i+1]-t, 2)/2
res.append(x)
return res
"""
acc - ускорение
time - время
w - размер окна
"""
def calc_coord_ema(acc, time, w):
acc_ema = []
for i in range(len(acc)):
acc_ema.append(moving_average(acc,w))
res = [0]
v = x = 0
for i in range(len(acc_ema)-1):
t = time[i]
v = v + acc_ema[i+1]*(time[i+1]-t)
x = x + v*(time[i+1]-t) + acc_ema[i+1]*pow(time[i+1]-t, 2)/2
res.append(x)
return res
"""
acc - ускорение
time - время
"""
def calc_coord(acc, time):
res = [0]
v = x = 0
for i in range(len(acc)-1):
t = time[i]
v = v + acc[i+1]*(time[i+1]-t)
x = x + v*(time[i+1]-t) + acc[i+1]*pow(time[i+1]-t, 2)/2
res.append(x)
return res
|
f51b0008d1d1c600c0eeda115fbc89aea5587abc
|
gsimon2/python_calculator
|
/calc_main.py
| 5,793 | 4.15625 | 4 |
#!/usr/bin/env python
import sys
from parser_calc import calc_parser
from tkinter import Tk, Label, Button, Entry, END
class calculator():
""" Calculator Class
Creates a small gui for the calc_parser class
"""
def __init__(self, root_window):
""" Init
Initializing the root window for the gui and builds the graphics layout
"""
self.parser = calc_parser()
self.root_window = root_window
self.build_layout()
def solve(self, _input):
""" Solve
Provides param: _input to the calc_parser to solve valid math equations
Return the solution to the input
"""
return self.parser.parse_input(_input)
def build_layout(self):
""" Build Layout
Specifies all graphics within the root window and links associated event procedures
"""
self.root_window.title("Calculator")
# Number buttons
self.button_0 = Button(self.root_window, text = "0", command = lambda : self.button_press_event(button = 0))
self.button_0.grid(row=6, column = 2)
self.button_1 = Button(self.root_window, text = "1", command = lambda : self.button_press_event(button = 1))
self.button_1.grid(row=5, column = 1)
self.button_2 = Button(self.root_window, text = "2", command = lambda : self.button_press_event(button = 2))
self.button_2.grid(row=5, column = 2)
self.button_3 = Button(self.root_window, text = "3", command = lambda : self.button_press_event(button = 3))
self.button_3.grid(row=5, column = 3)
self.button_4 = Button(self.root_window, text = "4", command = lambda : self.button_press_event(button = 4))
self.button_4.grid(row=4, column = 1)
self.button_5 = Button(self.root_window, text = "5", command = lambda : self.button_press_event(button = 5))
self.button_5.grid(row=4, column = 2)
self.button_6 = Button(self.root_window, text = "6", command = lambda : self.button_press_event(button = 6))
self.button_6.grid(row=4, column = 3)
self.button_7 = Button(self.root_window, text = "7", command = lambda : self.button_press_event(button = 7))
self.button_7.grid(row=3, column = 1)
self.button_8 = Button(self.root_window, text = "8", command = lambda : self.button_press_event(button = 8))
self.button_8.grid(row=3, column = 2)
self.button_9 = Button(self.root_window, text = "9", command = lambda : self.button_press_event(button = 9))
self.button_9.grid(row=3, column = 3)
# Math operator buttons
self.button_add = Button(self.root_window, text = "+", command = lambda : self.button_press_event(button = '+'))
self.button_add.grid(row=3, column = 5)
self.button_sub = Button(self.root_window, text = "-", command = lambda : self.button_press_event(button = '-'))
self.button_sub.grid(row=3, column = 6)
self.button_mult = Button(self.root_window, text = "*", command = lambda : self.button_press_event(button = '*'))
self.button_mult.grid(row=4, column = 5)
self.button_divide = Button(self.root_window, text = "/", command = lambda : self.button_press_event(button = '/'))
self.button_divide.grid(row=4, column = 6)
self.button_left_para = Button(self.root_window, text = "(", command = lambda : self.button_press_event(button = '('))
self.button_left_para.grid(row=5, column = 5)
self.button_right_para = Button(self.root_window, text = ")", command = lambda : self.button_press_event(button = ')'))
self.button_right_para.grid(row=5, column = 6)
# Clear and enter buttons
self.button_clear = Button(self.root_window, text = "clear", command = lambda : self.button_press_event(button = 'clear'))
self.button_clear.grid(row=7, column = 0, columnspan=4)
self.button_enter = Button(self.root_window, text = "enter", command = lambda : self.button_press_event(button = 'enter'))
self.button_enter.grid(row=7, column = 3, columnspan=4)
# Text box entry
self.text_box = Entry(self.root_window, justify="right")
self.text_box.grid(row=1, columnspan=7)
self.char_pos = 0
def button_press_event(self, button):
""" Button Press Event
Triggers on the event of any button press
Handles event according to the function associated with the pressed button
"""
# Update insertion position for the text box
if button != "clear":
self.char_pos = self.char_pos +1
# Number buttons
if button == 0:
self.text_box.insert(self.char_pos, 0)
if button == 1:
self.text_box.insert(self.char_pos, 1)
if button == 2:
self.text_box.insert(self.char_pos, 2)
if button == 3:
self.text_box.insert(self.char_pos, 3)
if button == 4:
self.text_box.insert(self.char_pos, 4)
if button == 5:
self.text_box.insert(self.char_pos, 5)
if button == 6:
self.text_box.insert(self.char_pos, 6)
if button == 7:
self.text_box.insert(self.char_pos, 7)
if button == 8:
self.text_box.insert(self.char_pos, 8)
if button == 9:
self.text_box.insert(self.char_pos, 9)
# Math operator buttons
if button == "+":
self.text_box.insert(self.char_pos, "+")
if button == "-":
self.text_box.insert(self.char_pos, "-")
if button == "*":
self.text_box.insert(self.char_pos, "*")
if button == "/":
self.text_box.insert(self.char_pos, "/")
if button == "(":
self.text_box.insert(self.char_pos, "(")
if button == ")":
self.text_box.insert(self.char_pos, ")")
# Clear and enter buttons
if button == "clear":
self.text_box.delete(0,END)
self.char_pos = 0
if button == "enter":
_input = self.text_box.get()
result = self.solve(_input)
self.text_box.delete(0,END)
self.char_pos = len(str(result))
self.text_box.insert(self.char_pos, result)
if __name__ == "__main__":
root_window = Tk()
calc = calculator(root_window)
root_window.mainloop()
|
281589add4daa5b404988edbb4a9e7284ac29cdc
|
dido18/il-pensiero-computazionale-unipi
|
/l01-Algoritmi/avanzati/code/problema_finanziario/cubico.py
| 1,206 | 4.09375 | 4 |
# Programma CUBICO in Python
# Figura 4.2 del libro "Il Pensiero Computazionale: dagli algoritmi al coding"
# Autori: Paolo Ferragina e Fabrizio Luccio
# Edito da Il Mulino
def cubico(d):
"""
Calcola la porzione d[a : v] avente somma massima
provando tutti i possibili intervalli [i,j] in [1,n-1] estremi inclusi
:param d: vettore di numeri positivi e negativi, d[0] valore iniziale dell'azione
"""
n = len(d) # n indica il numero di elementi di d
max_somma = -float('inf')
a = 1
v = 0
for i in range(1, n):
for j in range(i, n):
tmp = 0 # tmp e' un valore temporaneo
for k in range(i, j + 1): # sommiamo gli elementi in d[i,j] estremi inclusi
tmp = tmp + d[k]
if tmp > max_somma:
max_somma = tmp
a = i
v = j
print ("Il guadagno massimo e' {}".format(max_somma))
print ("Esso si realizza nell'intervallo di giorni [{},{}]".format(a, v))
print ("Porzione di d avente somma massima {}".format(d[a:v+1]))
def main():
d = [10, +4, -6, +3, +1, +3, -2, +3, -4, +1, -9, +6]
cubico(d)
if __name__ == "__main__":
main()
|
ff4989543e1292bf695e35d8fd4ef9b28842dc64
|
benamoreira/PythonExerciciosCEV
|
/desafio077.py
| 333 | 3.9375 | 4 |
palavras = ('tudo', 'nada', 'estudar', 'carro', 'mercado', 'mesa', 'janela',
'livro', 'computador', 'lapis', 'caneta', 'celular')
for pos in palavras:
print(f'\nNa palavra {pos.upper()} temos as vogais: ', end='')
for letra in pos:
if letra.upper() in 'AEIOU':
print(letra.upper(), end=' ')
|
163b98e92e2a44e42be3735e308a8706108b3915
|
PedroGoes16/Estudos
|
/Exercicios-Python/exercicios-curso-em-video/d099.py
| 420 | 3.859375 | 4 |
from time import sleep
def maior(*lst):
print(30*'-=')
print('Analisandos os valores passados ...')
for v in lst:
print(v,end=' ')
print(f'Foram informado {len(lst)} valores ao todo.')
if len(lst) > 0:
print(f'O maior valor informado foi {max(lst)}.')
else:
print('O maior valor informado foi 0.')
sleep(2)
maior(2,9,4,5,7,1)
maior(4,7,0)
maior(1,2)
maior(6)
maior()
|
d6a5b613995b62924c65591bad59ddd57981679d
|
AndersonRoberto25/Python-Studies
|
/Lista/Trabalhando com listas/lista2.py
| 1,426 | 4.59375 | 5 |
#Criando listas numéricas
#A função range() de Python facilita gerar uma série de números.
for value in range(1,6):
print(value)
#A função range() faz Python começar a contar no primeiro valor que você lhe fornecer e parar quando atingir o segundo valor especificado. Como ele para nesse segundo valor, a saída não conterá o valor final.
#Se quiser criar uma lista de números, você pode converter os resultados de range() diretamente em uma lista usando a função list().
numbers = list(range(1,6))
print(numbers)
#Também podemos usar a função range() para dizer a Python que ignore alguns números em um dado intervalo. Por exemplo, eis o modo de listar os números pares entre 1 e 10:
even_numbers = list(range(2,11,2))#O valor 2 é somado repetidamente até o valor final, que é 11, ser alcançado ou ultrapassado
print(even_numbers)
#Os dez primeiros quadrados perfeitos em uma lista
squares = []
for value in range(1,11):
#square = value**2
squares.append(value**2)
print(squares)
#List comprehensions
squares = [value**2 for value in range(1,11)]
print(squares)
#Estatística simples com lista de números - Algumas funções Python são específicas para listas de números
digits = [1,2,3,4,5,6,7,8,9,0]
print('\nValores da lista:')
print(digits)
print('Valor mínimo: ' + str(min(digits)) + '\nValor máximo: ' + str(max(digits)) + '\nSoma dos números: ' + str(sum(digits)))
|
d69d012797b2661707f72db49694bd453fa368cf
|
lancelafontaine/coding-challenges
|
/hackerrank/algorithms/01-warmup/time-conversion/python3/time-conversion.py
| 505 | 4.0625 | 4 |
#!/bin/python3
import sys
time = input().strip()
def time_conversion(time):
am_or_pm = time[-2:].lower()
time = time[:-2]
hour = time[:2]
if am_or_pm == "am":
if hour == "12":
return "00" + time[2:]
return time
if am_or_pm == "pm":
if hour == "12":
return time
pm_hour = str(int(hour) + 12)
return pm_hour + time[2:]
else:
raise RuntimeError("Invalid time passed", am_or_pm)
print(time_conversion(time))
|
76fad5198bf1acd894ac4455654f6f33e90b7334
|
KojoAning/PYHTON_PRACTICE
|
/list.py
| 1,794 | 4 | 4 |
# grocery = ['deo','chicken','milk','eggs','sprouts','mug dal' , 199]
# print(grocery[6])
# numbers = [2,5,1,67,9,1]
# list_1 =['f','srinath']
# my_list = numbers[:] # this will ensure that my_list gets only the copy of the numbers
# a = numbers.sort() # its unnecessry to write a function for sorting insted of using the inbuit one
# b = numbers.reverse()
# print(numbers[1::2]) # but doing these actions wil not effect aur original iist
# print(numbers) # a & b has changed the original list
# print(numbers[0::-2])# we should not use no.s less then -1 on 3rd either in str or in list
# print(max(numbers))
# print(min(numbers))
# print(len(numbers))
# numbers.append(91)
# numbers.insert(2,16) # 2 is the index where the number 16 is going to be insorted.
# numbers.remove(9) # 9 will get removed from the list
# numbers.pop() # this wi remove the end iteam from the list.
# numbers[1]=32
# print(numbers[2:]) #print elements starting from 3rd elements in the list
# print(numbers[1:3]) # print elements 2nd and 3rd
# print(numbers*2) # prints the list numbers twice
# print((numbers+list_1)) # provides such a list where there is elements of both numbers and list_1 ( respectivly)
# TUPPLES
# '''mutable - can change
# immutable- can't change'''
# tupple = (3,2,5,1,5)
# print(tupple)
# tp=(1,) # wee need to put a , after the charecter if u have one iteam in ur tupple
# print(tp)
# SWAPPING
# a = 1
# b =3
# a,b = b,a
# temp = a
# a=b
# b = temp
# print(a,b)
#-------------------------------------------------question----------------------------------------
# question to input 10 nums in a list and then display all the elements by multiplying 2
# print('Enter the elements of these list : ')
# lis =[]
# for i in range(0,5):
# a = int(input())
# lis.append(a*2)
# print(lis)
|
73bbc14e4816c6df0db1039a8568109944a2d12a
|
shubhankar01/Python-Datastructures
|
/array/Equilibrium_point.py
| 772 | 3.671875 | 4 |
# Given an array A your task is to tell at which position the
# equilibrium first occurs in the array. Equilibrium position
# in an array is a position such that the sum of elements below
# it is equal to the sum of elements after it.
n = [int(x) for x in input().split(' ')]
def equi(n):
l = 0
r = len(n) - 1
left_sum = n[l]
right_sum = n[r]
while(l<=r):
if left_sum == right_sum:
l += 1
r -= 1
if l == r:
print(n[l])
return
else:
right_sum += n[r]
left_sum += n[l]
elif left_sum > right_sum:
r-=1
right_sum+=n[r]
else:
l+=1
left_sum += n[l]
print(-1)
equi(n)
|
7ad2740f5ccaee4203267c1e59d7a01475125ae3
|
gharseldin/LeetCode-in-Python
|
/Cards/Arrays/1346_CheckIfNAndItsDoubleExist.py
| 679 | 3.546875 | 4 |
# could be solved more efficiently with binary search
class Solution:
def checkIfExist(self, arr: List[int]) -> bool:
arr.sort()
i = 0
j = len(arr) - 1
cache = {}
return self.check(arr, i, j, cache)
def check(self, arr: List[int], i: int, j: int, cache: {str, bool}) -> bool:
if i >= j:
return False
if arr[j] == arr[i]*2 or arr[i] == arr[j]*2:
return True
key = str(i)+"-"+str(j)
if key in cache:
return cache[key]
result = self.check(
arr, i+1, j, cache) or self.check(arr, i, j-1, cache)
cache[key] = result
return result
|
782a99ad83b5563f411c6ce38509dacbe2e02808
|
franckeric96/exonan
|
/exo1.py
| 477 | 3.828125 | 4 |
prix = float(input("entrez le prix unitaire d'une heure :"))
nbheures = int(input("combien d'heure suplémentaire avez vous réaliser? "))
montant = 0
if nbheures <= 39 :
montant = 0
elif nbheures < 45 :
montant = (nbheures -39)*(prix*1.5)
elif nbheures < 50 :
montant = (5*prix*1.5)+(nbheures -44)*(prix*1.75)
else:
montant =(5* prix *1.5)+(5* prix *1.75)+( nbheures -49)*( prix *2)
print("le montant des heures suplémentaire est:",montant)
|
e60eae27b4e82cd94cd866eeb1ef4e5b5ffab9a3
|
Tifinity/LeetCodeOJ
|
/415.字符串相加.py
| 1,019 | 3.53125 | 4 |
import copy
class Solution(object):
def addStrings(self, num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
l1 = []
l2 = []
for s in num1:
l1.append(s)
for s in num2:
l2.append(s)
if len(l1) > len(l2):
res = copy.deepcopy(l1)
else:
res = copy.deepcopy(l2)
print(res)
for i in range(min(len(l1), len(l2))):
n = int(l1[len(l1)-i-1]) + int(l2[len(l2)-i-1])
res[len(res)-i-1] = str(n)
res = list(map(int, reversed(res)))
print(res)
for i in range(len(res)):
if res[i] > 9:
res[i] -= 10
if i == len(res) - 1:
res.append(1)
else:
res[i+1] += 1
res = list(map(str, reversed(res)))
return ''.join(res)
s= Solution()
s1 = "9"
s2 = "99"
print(s.addStrings(s1, s2))
|
1277217ccc9278a4c1f920722c3c84d6edccc354
|
Johannyjm/c-pro
|
/AtCoder/abc/abc174/a.py
| 60 | 3.71875 | 4 |
x = int(input())
if(x >= 30): print("Yes")
else: print("No")
|
64cddf845cae8dec54d9897351efd3a1323d8f1d
|
Yoatn/stepik.org
|
/programming_in_python/2.1.1.py
| 394 | 3.515625 | 4 |
#--------------------------------------------------
# Programm by Yoatn
#
#
# Version Date Info
# 1.0 04.10.2017 Initial Version
#
#--------------------------------------------------
a = int(input())
b = []
while a != 0:
b.append(a)
a = int(input())
b.append(a)
break
while a != 0:
a = int(input())
b.append(a)
print(sum(b))
|
5a3f0b9fcd4e0bdcc3e5789f63e7de3698092d2d
|
fimh/dsa-py
|
/dp/322.py
| 1,463 | 3.8125 | 4 |
"""
Question: Coin Change
Difficulty: Medium
Link: https://leetcode.com/problems/coin-change/
Ref: https://leetcode-cn.com/problems/coin-change/
You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money.
Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.
You may assume that you have an infinite number of each kind of coin.
Example 1:
Input: coins = [1,2,5], amount = 11
Output: 3
Explanation: 11 = 5 + 5 + 1
Example 2:
Input: coins = [2], amount = 3
Output: -1
Example 3:
Input: coins = [1], amount = 0
Output: 0
Constraints:
1 <= coins.length <= 12
1 <= coins[i] <= 231 - 1
0 <= amount <= 104
"""
from typing import List
class Solution:
def coinChange(self, coins: List[int], amount: int) -> int:
dp = [(amount + 1) for _ in range(amount + 1)]
dp[0] = 0
for i in range(1, amount + 1):
for j in range(len(coins)):
if i >= coins[j] and dp[i - coins[j]] + 1 < dp[i]:
# dp[i] = min(dp[i], dp[i - coins[j]] + 1)
dp[i] = dp[i - coins[j]] + 1
return -1 if dp[amount] > amount else dp[amount]
if __name__ == '__main__':
test_coins = [1, 2, 4]
test_amount = 11
ret = Solution().coinChange(test_coins, test_amount)
print(ret)
|
f4702ca6544785f7c0b8210cdae8ae58293f80f4
|
JorgenStenshaugen/IN1000
|
/Oblig 1/beslutninger.py
| 525 | 3.640625 | 4 |
# Spør brukeren om den vil ha en brus
print("Vil du ha en brus? (\"Ja\" eller \"nei\")")
# Setter svaret i en variabel
svar = input()
if svar == "ja" :
# Sjekker dersom verdien på svar variablen er lik "ja" og skriver ut en melding
print("Her har du en brus!")
elif svar == "nei" :
# Sjekker dersom svaret er nei vil en annen melding bli skrevet ut
print("Den er grei.")
else :
# Dersom svaret er noe annet enn "ja" eller "nei" så skriver vi ut en feilmelding.
print("Det forstod jeg ikke helt.")
|
cfc18ff36d4d7e9fb8ce7e8856630f9a779267e6
|
maydhak/project-euler
|
/004.py
| 1,729 | 4.1875 | 4 |
"""
Problem 4:
A palindromic number reads the same both ways.
The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
"""
# I wrote my own method for checking if a number is a palindrome. I thought the number should read the same from
# the start to its middle digit, and from the end to its middle digit in reverse, so that's what my function checks.
# Later I learned that there are much more concise ways to do this... but anyways...
def solution4():
def is_palindrome(num):
import math
work = str(num)
half = int(math.ceil((len(work)/2)))
return work[:half-1] == ''.join(reversed(work[half:])) or work[:half] == ''.join(reversed(work[half:]))
num1, num2, soln = 999, 999, 0
for i in reversed(range(num1)):
for j in reversed(range(num2)):
if is_palindrome(i*j) and i*j > soln:
soln = i*j
print(soln)
# After reading about strides at https://www.digitalocean.com/community/tutorials/how-to-index-and-slice-strings-in-python-3
# I wrote a better version of is_palindrome.
def new_is_palindrome(num):
return str(num) == str(num)[::-1]
# At this point I didn't even need the palindrome checker to be in its own function, so I rewrote the solution:
def solution4_1():
num1, num2, soln = 999, 999, 0
for i in reversed(range(100, num1)):
for j in reversed(range(100, num2)):
# I also realized that only three-digit numbers needed to be included, so I added that in the range calls
if str(i*j) == str(i*j)[::-1] and i*j > soln:
soln = i*j
return soln
print(solution4_1())
|
dbd602e41733cdd59373a520a3fe7dd996ead2e5
|
saki45/CodingTest
|
/py/backtrack/maze.py
| 1,759 | 3.984375 | 4 |
def solvemaze(maze, x, y):
# This method is the classic way to find the route to the exit of a maze by backtrack
# In this program by default the exit is in the upper right corner (maze(0,8))
# The elements in the maze:
# 0 -- unvisited
# 1 -- wall
# 2 -- visited
maze[x][y] = 2
# find one solution
if x==0 and y==8:
print("solution: ")
printmaze(maze)
return
# check how many options we have at the current point to reduce the number of status created
numOfOption = 0
isUp, isDown, isLeft, isRight = False, False, False, False
if x>0 and maze[x-1][y]==0:
isUp = True
upNo = numOfOption
numOfOption += 1
if x<len(maze)-1 and maze[x+1][y]==0:
isDown = True
downNo = numOfOption
numOfOption += 1
if y>0 and maze[x][y-1]==0:
isLeft = True
leftNo = numOfOption
numOfOption += 1
if y<len(maze[0])-1 and maze[x][y+1]==0:
isRight = True
rightNo = numOfOption
numOfOption += 1
if numOfOption == 0:
return
status = [copy.deepcopy(maze) for i in range(1,numOfOption)]
status = [maze] + status
if isUp:
solvemaze(status[upNo],x-1,y)
if isDown:
solvemaze(status[downNo],x+1,y)
if isLeft:
solvemaze(status[leftNo],x,y-1)
if isRight:
solvemaze(status[rightNo],x,y+1)
def printmaze(maze):
for row in maze:
for n in row:
print(n, end=' ')
print()
if __name__ == "__main__":
import copy
maze = [[0 for i in range(0,9)] for j in range(0,9)]
maze[1][1:8] = [1 for i in range(1,8)]
maze[3][0:7] = [1 for i in range(0,7)]
maze[3][8] = 1
maze[4][4] = 1
maze[5][0] = 1
maze[5][2:6] = [1 for i in range(2,6)]
maze[5][7:9] = [1, 1]
maze[7][0:5] = [1 for i in range(0,5)]
maze[7][6:9] = [1 for i in range(6,9)]
printmaze(maze)
maze[3][3] = 0
maze[8][0] = 2
solvemaze(maze,8,0)
|
286afa82e4a950d53c77e46c012a9c23ffd1b9dc
|
Willianan/Algorithm_Book
|
/Chapter7/7.3.py
| 1,774 | 3.53125 | 4 |
# -*- coding:utf-8 -*-
"""
Author:Charles Van
E-mail: [email protected]
Time:2019/3/19 10:45
Project:AlgorithmBook
Filename:7.3.py
"""
"""
如何求正整数n所有可能的整数组合
题目描述:给定一个正整数n,求解出所有和为n的整数组合,要求组合安装递归方式展示,而且唯一。
"""
'''
******* 方法功能:求和为n的所有整数组合
******* 输入参数:sums:正整数;result:存储组合结果;count:记录组合中数字的个数
'''
def getAllCombination(sums,result,count):
if sums < 0:
return
# 数字的组合满足和为sums的条件,打印出所有组合
if sums == 0:
print("满足条件的组合:",end='')
i = 0
while i < count:
print(result[i],end=' ')
i += 1
print()
return
# 打印debug信息,为了方便理解
print("-------当前组合:",end='')
i = 0
while i < count:
print(str(result[i]),end=' ')
i += 1
print("--------------")
# 确定组合中下一个取值
i = 1 if count == 0 else result[count-1]
print("----"+" i = "+str(i)+" count = "+str(count)+"-----")
while i <= sums:
result[count] = i
count += 1
getAllCombination(sums-i,result,count) # 求和为sums-i的组合
count -= 1 # 递归完成后,去掉最后一个组合的数字
i += 1 # 找下一个数字最为组合中的数字
# 方法功能:找出和为n的所有整数的组合
def showAllCombination(n):
if n < 1:
print("参数不满足要求")
return
result = [None]*n # 存储和为n的组合方式
getAllCombination(n,result,0)
if __name__ == "__main__":
showAllCombination(4)
|
f49527155bc5c9b9ede2d30ae774fb084e016776
|
Vladimirvp2/bunker
|
/Services/PasswordGenerator.py
| 10,921 | 3.875 | 4 |
'''
Classes and data for random password generation according to the information
provided by user
'''
import string, random
#defaults
DEFAULT_PASSWORD_LENGTH = 8
#number of passwords generated to the user for choice
DEFAULT_PASSWORD_RANGE = 10
LOOK_LIKE_SYMBOLS = 'l1O0|'
class PasswordGeneratorException(Exception):
'''Base class for all password generator exceptions'''
def __init__(self, value, message):
self.value = value
self.message = message
def __str__(self):
return repr(' {}, {}'.format(self.value, self.message))
class FewSymbolsProvidedException(PasswordGeneratorException):
'''Raised if the user doesn't provided enough symbols for password generation'''
def __init__(self, value, message):
self.value = value
self.message = message
class ZeroPasswordException(PasswordGeneratorException):
'''Raised if the user doesn't provided enough length for password generation'''
def __init__(self, value, message):
self.value = value
self.message = message
class InvalidSymbolsException(PasswordGeneratorException):
'''Raised if the user provided invalid symbol(not printable ascii ) '''
def __init__(self, value, message):
self.value = value
self.message = message
class PasswordSpecification(object):
"""DTO for froviding data to PasswordGenerator"""
def __init__(self):
self.__passwordLength = DEFAULT_PASSWORD_LENGTH
self.__additionalSymbols = ''
self.__excludedSymbols = ''
self.__excludeLookLikeSymbols = False
self.__lowerCase = False
self.__upperCase = False
self.__digit = False
self.__minus = False
self.__underline = False
self.__space = False
self.__dot = False
self.__eachCaracterAtMostOne = False
@property
def passwordLength(self):
return self.__passwordLength
def setPasswordLength(self, value):
"""
Set length for password
@type value: integer
"""
self.__passwordLength = int(value)
@property
def additionalSymbols(self):
return self.__additionalSymbols
def setAdditionalSymbols(self, value):
"""
Add given symbols to password
@type value: string
"""
self.__additionalSymbols = value
@property
def excludedSymbols(self):
return self.__excludedSymbols
def setExcludedSymbols(self, value):
"""
Exclude given symbols from password
@type value: string
"""
self.__excludedSymbols = value
@property
def lowerCase(self):
return self.__lowerCase
def setLowerCase(self, value):
"""
Lowercase symbol in password
@type value: boolean
"""
self.__lowerCase = value
@property
def upperCase(self):
return self.__upperCase
def setUpperCase(self, value):
"""
Uppercase symbol in password
@type value: boolean
"""
self.__upperCase = value
@property
def digit(self):
return self.__digit
def setDigit(self, value):
"""
Digit symbols (0-9) in password
@type value: boolean
"""
self.__digit = value
@property
def minus(self):
return self.__minus
def setMinus(self, value):
"""
Minus symbol in password
@type value: boolean
"""
self.__minus = value
@property
def underline(self):
return self.__underline
def setUnderline(self, value):
"""
Underline symbol in password
@type value: boolean
"""
self.__underline = value
@property
def space(self):
return self.__space
def setSpace(self, value):
"""
Space symbol in password
@type value: boolean
"""
self.__space = value
@property
def dot(self):
return self.__dot
def setDot(self, value):
"""
Dot symbol in password
@type value: boolean
"""
self.__dot = value
@property
def excludeLookLikeSymbols(self):
return self.__excludeLookLikeSymbols
def setExcludeLookLikeSymbols(self, value):
"""
Exclude symbols like l1, O0.. from password
@type value: bool
"""
self.__excludeLookLikeSymbols = value
@property
def eachCaracterAtMostOne(self):
return self.__eachCaracterAtMostOne
def setEachCaracterAtMostOne(self, value):
"""
Each symbol doesn't repet in password
@type value: bool
"""
self.__eachCaracterAtMostOne = value
class PasswordGenerator:
"""Class for generation random password"""
def __init__(self):
#store entropy values taken from user actions, for example mouse movement, to
#increase the randomness by password generation
self.__entropyValues = []
def generatePassword(self, passwordSpecification):
"""
Generate password according to provided requirements
@type number: integer
@param number: number of passwords to generate
@type passwordSpecification: PasswordSpecification
@param passwordSpecification: DTO object to pass conditions for password generation
@raise FewSymbolsProvidedException: if 0 symbols provided of their number isn't enough for
password generation (inclusion of each symbol only once)
@return password(string)
"""
#generate string of all possible symbols for the password
genSymbols = ""
if passwordSpecification.lowerCase:
genSymbols += string.ascii_lowercase
if passwordSpecification.upperCase:
genSymbols += string.ascii_uppercase
if passwordSpecification.digit:
genSymbols += string.digits
if passwordSpecification.minus:
genSymbols += '-'
if passwordSpecification.underline:
genSymbols += '_'
if passwordSpecification.space:
genSymbols += ' '
if passwordSpecification.dot:
genSymbols += '.'
#add additional symbols if there are any
for s in passwordSpecification.additionalSymbols:
if s not in genSymbols:
genSymbols += s
#genSymbols += passwordSpecification.additionalSymbols
self.__symbolList = list(genSymbols)
#exclude excluded symbols
for c in passwordSpecification.excludedSymbols:
if c in self.__symbolList:
self.__symbolList.remove(c)
#exclude look like symbols if enabled
if passwordSpecification.excludeLookLikeSymbols:
for c in LOOK_LIKE_SYMBOLS:
if c in self.__symbolList:
self.__symbolList.remove(c)
#check if the password specification isn't contradictory
self.__dataCheck(self.__symbolList, passwordSpecification)
#shuffle the symbols
random.shuffle(self.__symbolList)
#apply entropy
for value in self.__entropyValues:
print "Shuffle", value
random.shuffle(self.__symbolList, lambda : value)
self.__entropyValues = []
#generate password from prepared symbol sequence
passWord = ""
for counter in range(0, passwordSpecification.passwordLength):
symbol = random.choice(self.__symbolList)
passWord += symbol
if passwordSpecification.eachCaracterAtMostOne:
self.__symbolList.remove(symbol)
return passWord
def generatePasswordRange(self, passwordSpecification, number=DEFAULT_PASSWORD_RANGE):
"""
Generate sequence of passwords for user's choice
@type number: integer
@param number: number of passwords to generate
@type passwordSpecification: PasswordSpecification
@param passwordSpecification: DTO object to pass conditions for password generation
@raise FewSymbolsProvidedException: if 0 symbols provided of their number isn't enough for
password generation (inclusion of each symbol only once)
@return list of passwords(string)
"""
res = []
for n in range(0, number):
password = self.generatePassword(passwordSpecification)
res.append(password)
random.shuffle(self.__symbolList)
return res
def addEntropy(self, x, y):
"""For more randomness in password generation use the method. It's called before password generation"""
x = float(abs(x))
y = float(abs(y))
random_entropy_value = 0.5
if x > 0 and y > 0:
#should be in 0-1 range
random_entropy_value = y / x if y <= x else x / y
print "Adder Entropy" , random_entropy_value
self.__entropyValues.append(random_entropy_value)
def clearEntropy(self):
"""Remove collected entropy"""
self.__entropyValues = []
def __dataCheck(self, genSymbols, passwordSpecification):
"""Check whether data provided by user isn't contradictory"""
if passwordSpecification.passwordLength == 0:
raise ZeroPasswordException('0', "Can't generate empty password")
if len(genSymbols) == 0:
raise FewSymbolsProvidedException('0', 'No symbols provided for password generation')
if (passwordSpecification.eachCaracterAtMostOne) and (passwordSpecification.passwordLength > len(genSymbols)):
raise FewSymbolsProvidedException('{}'.format(len(genSymbols)),
"""Not enough symbols provided for password generation with inclusion of each symbol only once""")
for c in genSymbols:
if c not in string.printable:
raise InvalidSymbolsException(c, 'Invalid symbol. Should be only printable ascii')
if __name__ == "__main__":
gen = PasswordGenerator()
data = PasswordSpecification()
data.setPasswordLength(20)
data.setLowerCase(True)
data.setUpperCase(True)
data.setDigit(True)
data.setExcludedSymbols('2345678')
data.setEachCaracterAtMostOne(True)
data.setExcludeLookLikeSymbols(True)
data.setDot(True)
gen.addEntropy(54, 104)
d = gen.generatePasswordRange(data, 10)
for a in d:
print a
|
cd26a00a7f28078db66930a10967937c9e44a4dc
|
nguyend91/code-courses
|
/python/lpthw/ex42.py
| 1,835 | 4.21875 | 4 |
#!/usr/bin/env python2
# Animal is-a object
class Animal(object):
pass
# Dog is-a Animal
class Dog(Animal):
# class Dog has-a __init__ that takes self and name parameters
def __init__(self, name):
# from self get the name attribute and set it to name
self.name = name
# create class named Cat is-a Animal
class Cat(Animal):
# has-a __init__ that takes self and name parameters
def __init__(self, name):
# from self get the name attribute and set it to name
self.name = name
# create class named Person that is-a object
class Person(object):
# has-a __init__ that takes self and name parameters
def __init__(self, name):
# from self get the name attribute and set it to name
self.name = name
# person has-a pet of some kind
self.pet = None
# create class named Employee that is-a Person
class Employee(Person):
# has-a __init__ that takes self, name, and salary parameters
def __init__(self, name, salary):
super(Employee, self).__init__(name)
# from self take salary attribute and set it to salary
self.salary = salary
# create class Fish that is-a object
class Fish(object):
pass
# create class Salmon this is-a Fish
class Salmon(Fish):
pass
# create class Halibut that is-a Fish
class Halibut(Fish):
pass
# rover is-a Dog
rover = Dog("Rover")
# satan is-a Cat
satan = Cat("Satan")
# mary is-a Person
mary = Person("Mary")
# from mary take pet attribute and set it to satan (has-a)
mary.pet = satan
# frank is-a Employee
frank = Employee("Frank", 120000)
# from frank take pet attribute and set it to rover (has-a)
frank.pet = rover
# set flipper to an instance of class Fish (is-a)
flipper = Fish()
# set crouse to an instance of class Salmon (is-a)
crouse = Salmon()
# set harry to an instance of class Halibut (is-a)
harry = Halibu()
|
f33e15b6c448f56806d8b6c3d3f7f6fe7b932511
|
yse33/exam_01_22
|
/main_consult.py
| 124 | 3.6875 | 4 |
from calculate import *
days = int(input("How many days have you worked here?"))
print("Your income: ", calculate(days))
|
a63743805488b55764b4e21f85ce9646d2ebb5a0
|
ntupenn/exercises
|
/medium/545.py
| 2,482 | 4.40625 | 4 |
"""
Given a binary tree, return the values of its boundary in anti-clockwise direction starting from root. Boundary includes left boundary, leaves, and right boundary in order without duplicate nodes.
Left boundary is defined as the path from root to the left-most node. Right boundary is defined as the path from root to the right-most node. If the root doesn't have left subtree or right subtree, then the root itself is left boundary or right boundary. Note this definition only applies to the input binary tree, and not applies to any subtrees.
The left-most node is defined as a leaf node you could reach when you always firstly travel to the left subtree if exists. If not, travel to the right subtree. Repeat until you reach a leaf node.
The right-most node is also defined by the same way with left and right exchanged.
Example 1
Input:
1
\
2
/ \
3 4
Ouput:
[1, 3, 4, 2]
Explanation:
The root doesn't have left subtree, so the root itself is left boundary.
The leaves are node 3 and 4.
The right boundary are node 1,2,4. Note the anti-clockwise direction means you should output reversed right boundary.
So order them in anti-clockwise without duplicates and we have [1,3,4,2].
Example 2
Input:
____1_____
/ \
2 3
/ \ /
4 5 6
/ \ / \
7 8 9 10
Ouput:
[1,2,4,7,8,9,10,6,3]
Explanation:
The left boundary are node 1,2,4. (4 is the left-most node according to definition)
The leaves are node 4,7,8,9,10.
The right boundary are node 1,3,6,10. (10 is the right-most node).
So order them in anti-clockwise without duplicate nodes we have [1,2,4,7,8,9,10,6,3].
"""
def findBoundary(root):
if not root:
return []
left = findLeft(root)
right = findRight(root)
leaves = findLeaf(root)
return left + leaves + right[len(right)-1:0:-1]
def findLeft(root):
if not root.left and not root.right:
return []
if root.left:
return [root.val] + findLeft(root.left)
else:
return [root.val] + findRight(root.right)
def findRight(root):
if not root.left and not root.right:
return []
if root.right:
return [root.val] + findRight(root.right)
else:
return [root.val] + findRight(root.left)
def findLeaf(root):
if not root.left and not root.right:
return [root.val]
res = []
if root.left:
res += findLeaf(root.left)
if root.right:
res += findLeaf(root.right)
return res
|
c335bca4145748c1fd76cf3253dabea3afce9891
|
kyosukekita/ROSALIND
|
/Bioinformatics textbook track/implement_motifEnumeration.py
| 1,735 | 3.703125 | 4 |
"""問題の指示とは異なる方法の解法"""
import itertools
import collections
def HammingDistance(seq1,seq2,d):
"""2つの配列が与えられ、ハミング距離がd以下であればTrue"""
mismatch=0
for i in range(len(seq1)):
if seq1[i]!=seq2[i]:
mismatch+=1;
return mismatch<=d
def wordsWithmismatch(seq1,d):
"""配列が一つ与えられると、ハミング距離がd以下である配列をリストで返す"""
answer=[]
possible_kmers=[''.join(p) for p in itertools.product(['A','T','C','G'], repeat=len(seq1))]
for i in range(len(possible_kmers)):
if HammingDistance(seq1,possible_kmers[i],d):
answer.append(possible_kmers[i])
return answer
#データ読み込み
file=open('Desktop/Downloads/rosalind_ba2a.txt').read()
k,d=[int(i) for i in file.split("\n")[0].split()]
dnas=file.split("\n")[1:]
def MotifEnumeration(dnas,k,d):
patterns=set([''.join(p) for p in itertools.product(['A','T','C','G'], repeat=k)])#kmerを全て書きだしておく
for i in range(len(dnas)):
kmer=[]#ある一つのDNA配列について、kmerを全て書き出す
for j in range(len(dnas[i])-k+1):
kmer.append(dnas[i][j:j+k])
mismatch=[]
for j in range(len(list(kmer))):
mismatch +=wordsWithmismatch(kmer[j],d)#書き出したkmerについて、ハミング距離がd以内の配列を全て書き出す。
mismatch=set(mismatch)#重複を除去
patterns = patterns & mismatch#重複する項だけがpatternsに残っていく。
return ' '.join(map(str,list(patterns)))
print(MotifEnumeration(dnas,k,d))
|
27908b97b09c6fbc68f3822e17798ba896000ec7
|
Python44/PythonStarter
|
/PythonStarter/1_Lesson/1_1.Geron.py
| 241 | 3.890625 | 4 |
a=input("Введите сторону а ")
a= float(a)
b=input("Введите сторону b ")
b= float(b)
c=input("Введите сторону c ")
c= float(c)
p =(a+b+c)/2
S=(p*(p-a)*(p-b)*(p-c))**0.5
print("Площадь = ", S)
|
751f4f187c70ce715ea2805ba0b9b11f3b94b5e0
|
OskarKozaczka/pp1-OskarKozaczka
|
/01-TypesAndVariables/Programs/1.29.py
| 200 | 3.640625 | 4 |
import random
rzut=random.randint(1,6)
guess=int(input("Zgadnij wyrzuconą liczbę oczek:"))
if guess==rzut:
print("Zgadłeś!")
else:
print("Komputer wyrzucił",rzut,"Spróbuj jeszcze raz!")
|
8f499262a7eb05bb032558e2ce19c195ef19b648
|
fraune/Chess-AI
|
/app/agent/Scorer.py
| 3,878 | 3.609375 | 4 |
from enum import Enum
import chess
from app.agent.scorer_weights_simplified_evaluation_function import white_pawn_weights, white_knight_weights, \
white_bishop_weights, white_rook_weights, white_queen_weights, white_king_weights_middle_game, \
white_king_weights_end_game, black_pawn_weights, black_knight_weights, black_bishop_weights, black_rook_weights, \
black_queen_weights, black_king_weights_middle_game, black_king_weights_end_game
class PieceType(Enum):
PAWN = 1
KNIGHT = 2
BISHOP = 3
ROOK = 4
QUEEN = 5
KING = 6
class Scorer:
def evaluate(self, board: chess.Board) -> float:
"""
Uses the simplified evaluation function.
https://www.chessprogramming.org/Simplified_Evaluation_Function
A positive value indicates the white player is in a stronger position, while
a negative value indicates the black player is in a stronger position. The
magnitude scores indicate the amount of advantage.
"""
end_game: bool = self._is_end_game(board)
white_score = 0
for square_index in chess.scan_reversed(board.occupied_co[chess.WHITE]):
if (piece_type := board.piece_type_at(square_index)) is None:
continue
white_score += self._get_weight(square_index, piece_type, end_game, True)
for square_index in chess.scan_reversed(board.occupied_co[chess.BLACK]):
if (piece_type := board.piece_type_at(square_index)) is None:
continue
white_score -= self._get_weight(square_index, piece_type, end_game, False)
return white_score
def _is_end_game(self, board: chess.Board):
""" Is end game if:
a. Both sides have no queens OR
b. every side which has a queen has additionally no other pieces or one minor-piece maximum
"""
fen = board.fen()
num_white_queens = fen.count('Q')
num_black_queens = fen.count('q')
if num_white_queens == 0 and num_black_queens == 0:
return True
if num_white_queens == 1:
num_white_rooks_pieces = fen.count('R')
num_white_minor_pieces = fen.count('B') + fen.count('N')
num_white_pawns_pieces = fen.count('P')
if num_white_rooks_pieces > 0 or num_white_pawns_pieces > 0 or num_white_minor_pieces > 1:
return False
if num_black_queens == 1:
num_black_rooks_pieces = fen.count('r')
num_black_minor_pieces = fen.count('b') + fen.count('n')
num_black_pawns_pieces = fen.count('p')
if num_black_rooks_pieces > 0 or num_black_pawns_pieces > 0 or num_black_minor_pieces > 1:
return False
return True
def _get_weight(self, sq: int, piece_type, end_game: bool, white: bool):
if piece_type == PieceType.PAWN.value:
return white_pawn_weights[sq] if white else black_pawn_weights[sq]
elif piece_type == PieceType.KNIGHT.value:
return white_knight_weights[sq] if white else black_knight_weights[sq]
elif piece_type == PieceType.BISHOP.value:
return white_bishop_weights[sq] if white else black_bishop_weights[sq]
elif piece_type == PieceType.ROOK.value:
return white_rook_weights[sq] if white else black_rook_weights[sq]
elif piece_type == PieceType.QUEEN.value:
return white_queen_weights[sq] if white else black_queen_weights[sq]
elif piece_type == PieceType.KING.value:
if end_game:
return white_king_weights_end_game[sq] if white else black_king_weights_end_game[sq]
else:
return white_king_weights_middle_game[sq] if white else black_king_weights_middle_game[sq]
else:
raise Exception(f'WTF: {piece_type}')
|
c5f091926da87eb453e4aba36b9984c693329b20
|
krishnamohan-seelam/pythonbeyond
|
/pythonbeyond/beyondcm/loggingcontext.py
| 1,178 | 3.984375 | 4 |
import sys
'''
Simple example to understand context manager
'''
class LoggingContext:
def __enter__(self):
LoggingContext.print_message(self, message=None)
return self
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type is None:
LoggingContext.print_message(self, message="normal exit")
else:
LoggingContext.print_message(self, message="abnormal exit")
print("Exception detected:{} {} {}".format(exc_type, exc_val,
exc_tb))
@staticmethod
def print_message(self, message):
print("{}.{}:{}".format(self.__class__.__name__,
sys._getframe(1).f_code.co_name,
message if message else ""))
def main():
with LoggingContext() as lc:
print("working inside logging context")
print("#"*80)
try:
with LoggingContext() as lc2:
print("working inside logging context")
raise ValueError("Something went wrong")
except ValueError:
print("ValueError occured")
if __name__ == '__main__':
main()
|
7e367d81835a5feaaa895a58a905fb806bffa107
|
YMSPython/Degiskenler
|
/Lesson1/OperatorlerOrnekler.py
| 1,726 | 3.8125 | 4 |
# Örnek 1) Disaridan alinan
# iki sayının toplamiyla farkinin birbirine bolumunden kalanin sonucu kactir?
sayi1 = int(input("Lütfen birinci sayiyi giriniz : "))
sayi2 = int(input("Lütfen ikinci sayiyi giriniz : "))
toplam = sayi1 + sayi2
fark = sayi1 - sayi2
mod = toplam % fark
print("Islem sonucu :", mod)
# Örnek 2) Disaridan girilen bir sayının 10 eksiginin 20 fazlasinin
# 2ye bolumunden kalaninin karesi kactir?
sayi3 = int(input("Lütfen bir sayi giriniz :"))
sonuc = ((sayi3 - 10 + 20) % 2 ) ** 2
print(sonuc)
# Örnek 3) Disaridan girilen iki sayının karelerinin toplami
# ile karelerinin farki toplami kactir?
sayi4 = int(input("Lütfen birinci sayiyi giriniz :"))
sayi5 = int(input("Lütfen ikinci sayiyi giriniz : "))
kare1 = sayi4 * sayi4
kare2 = sayi5 * sayi5
kare3 = sayi4 **2
kare4 = sayi5 **2
toplam = kare1 + kare2
fark = kare1 - kare2
sonuc = toplam + fark
print("islem sonucu :", sonuc)
# Örnek 4) Vize notu'nun % 30'u, final notu'nun % 70'ini alıp öğrencinin not ortalamasini
#cikartan bir uygulama yaziniz...
final = float(input("Lütfen Final Notunuzu Giriniz : "))
vize = float(input("Lütfen Vize Notunuzu Giriniz : "))
not_ortalamasi = (vize * 0.30) + (final * 0.70)
print("Not ortalamanız :", not_ortalamasi)
# Örnek 5) Kullanıcı ilk Adını, 2. Olarak Soyadını girsin ve kullanıcıya mesaj olarak
# [email protected]
ondalikli_sayi = 14.1111111111
print(round(ondalikli_sayi,7)) # virgulden sonraki haneyi belirlemek için kullaniriz.
isim = input("Lütfen adınız giriniz : ")
soyisim = input("Lütfen soyadınız giriniz : ")
mail = isim + "."+ soyisim+"@hotmail.com"
print(mail)
# [email protected]
|
3eb97503f86dd607a4411991921952bc6849e938
|
kylebrownshow/python-programming
|
/unit-3/dictionary.py
| 2,533 | 4.5 | 4 |
#a dictionary is a collection of key/value pairs
# dictionaries use curly brackets { } . sets also use curlies, but we're not talking about that right now.
student = {'name': 'emma', 'age': 25, 'address': 'Toronto'}
#access elements in a dictionary
print(student['name'])
print(student['address'])
print(student['age'])
#a dictionary cannot have duplicate keys
#add items to a dictionary
car = {} #creates an empty dictionary like '' defines an empty string and [] defines an empty list
car['make'] = 'Toyota'
car['model'] = 'Prius'
car['year'] = 2019
car['colour'] = 'silver'
print(car) #note that this computer's version of python uses ordered dictionaries
car['year'] = 1997 #entering this key in twice overwrites the previous value. that's why it's best practice to not use keys twice.
print(car)
#how do we iterate over a dictionary
for item in car:
#if we ever do the "for in" on a dictionary, we'll get back the keys (not the values)
print(item) #this returns the keys
print(car[item]) #this returns the values
#challenge: make a list of dictionaries
cars = [{'make': 'Toyota', 'model': 'Prius', 'year': 1997, 'colour': 'silver'},{'make': 'Chevy', 'model': 'Aveo', 'year': 2006, 'colour': 'black'},
{'make': 'Lincoln', 'model': 'Navigator', 'year': 2010, 'colour': 'red'}, {'make': 'Chevy', 'model': 'Blazer', 'year': 2011, 'colour': 'black'},
{'make': 'Ford', 'model': 'Bronco', 'year': 1990, 'colour': 'blue'}]
#how do we process a list of dictionaries?
count = 0
for vehicle in cars:
if vehicle['make'] == 'Chevy':
count += 1
'''
{
'_id': 100,
'year': 2019,
'title': 'Bodak Yellow',
'artist': {
'name': 'Cardi B'}
}
'tracks': [
{
'_id': 100,
'title':
}
]
}
'''
print(count)
#the return for car is a dictionary, because - in this case - cars is a list of dictionaries. so print(car) would return a list of dictionaries
#write a function called frequency counter that returns the frequency of each letter in the string
#def frequency_counter(string)
#frequency_counter('a testy line of text')
'''
'a': 1
' ': 4
't': 4
'e': 2
's': 1
'y': 1
'l': 1
'i': 1
'n': 1
'o': 1
'f': 1
'x': 1
'''
#use a dictionary
#use the keys method to get the keys of a dictionary
print(car.keys())
#use the values method to get the values of a dictionary
print(car.values())
#use the items method to get both the keys and values of a dictionary
print(car.items())
for key, value in car.items():
print(key, value)
|
01fbb0052d65f72b9364a02d4433837ceaecc502
|
LuKuuu/python-study
|
/lk_02_test2.py
| 805 | 3.8125 | 4 |
words = ['cat', 'window', 'defenestrate']
for w in words[:]: # Loop over a slice copy of the entire list.
if len(w) > 3:
words.insert(0, w)
print(words)
print("-" * 40)
def cheeseshop(kind, *arguments, **keywords):
print("-- Do you have any", kind, "?")
print("-- I'm sorry, we're all out of", kind)
for arg in arguments:
print(arg)
print("-" * 40)
keys = sorted(keywords.keys())
for kw in keys:
print(kw, ":", keywords[kw])
cheeseshop("Limburger", "It's very runny, sir.",
"It's really very, VERY runny, sir.",
shopkeeper='Michael Palin',
client="John Cleese",
sketch="Cheese Shop Sketch")
pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
print(pairs)
pairs.sort(key=lambda pair: pair[1])
print(pairs)
|
71a764ce7795cb303405692b3f8d85d09bf834f0
|
orcinus42/python-script-testonly
|
/day3/mymod.py
| 301 | 3.890625 | 4 |
#!/usr/bin/env python
#
x = 30
def printInfo():
print x + 30
class MyClass():
data = 'hello MyClass'
def __init__(self,who):
self.name = who
def printName(self):
print self.data,self.name
if __name__ == '__main__':
printInfo()
ins1 = MyClass('jerry')
print ins1.data
print ins1.name
|
bbf5ab1a0dc62feb269a610c97ab101a7988d197
|
arjun-19922107/sample
|
/python_day1/letter_G.py
| 472 | 3.859375 | 4 |
result_str="";
for row in range(0,7):
for column in range(0,7):
if ((0<row<6 and column == 0) or ((row == 0 or (column<5 and row ==6) or (column>2 and row ==3)) and (column >1 and column < 6))
or (row == 3 and 1<column <2 and column < 4)or ((0<row<2 or 3<=row<=5)and column==5)):
result_str=result_str+"*"
else:
result_str=result_str+" "
result_str=result_str+"\n"
print(result_str);
|
46061fa65a653a981e8081be7eb096d88c4568f2
|
huran111/python
|
/study_04/format.py
| 662 | 3.875 | 4 |
name = "胡冉"
print("姓名是:" + name)
age = 18
print("年龄是" + str(age))
print("年龄是:%s" % age)
isMarry = False
print("结婚否?回答:%s" % isMarry)
print("年龄是:%d" % age)
# %f 小数点后面的位数,而且是四舍五入
salary = 2323.2323
print("我的薪水:%.2f" % salary)
'''
皮卡丘
'''
message = "乔治说:我今年{}岁了,{}幼儿园".format(age, age)
print(message)
# input
usernmae = input("请输入参与游戏者用户名:")
password = input("输入密码:")
print("%s请充值加入游戏" % usernmae)
coins = input("请充值:")
print(type(coins))
print('%s充值成功,游戏币:%s' % (usernmae, coins))
|
d8636ce6b2414d2f22e88724928e38fe8dffb5e8
|
AnnaAwaria/pyselenium
|
/liczba.py
| 286 | 3.578125 | 4 |
class Number:
def __init__(self, v):
self.value = v
def wyzeruj(self):
self.value = 0;
def ustaw(self, wartosc):
self.value = wartosc
number = Number(9)
print(number.value)
number.wyzeruj()
print(number.value)
number.ustaw(11)
print(number.value)
|
a4ec967b66a363207b38ca2cf619acc2298de14a
|
ShenDeng75/LeetCode
|
/147 对链表进行插入排序.py
| 2,219 | 3.71875 | 4 |
# -*- coding: utf-8 -*-
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def insertionSortList(self, head: ListNode) -> ListNode:
if not head:
return None
res = ListNode(head.val)
root = head.next
p1 = res
while root:
p = res
new = ListNode(root.val)
if p1.val <= new.val: # 针对递增的数据
p1.next = new
p1 = p1.next
elif new.val < p.val:
new.next = p
res = new
else:
while p.next and new.val > p.next.val:
p = p.next
new.next = p.next
p.next = new
root = root.next
return res
def to(ls: list):
node = ListNode(ls[0])
p = node
for i in ls[1:]:
p.next = ListNode(i)
p = p.next
return node
node = to([2, 1, 5, 4, 6])
obj = Solution()
ans = obj.insertionSortList(node)
a = 1
# class Solution: # 更牛皮的做法
# def insertionSortList(self, head: ListNode) -> ListNode:
# if not head or not head.next: # 如果无节点或只有一个节点
# return head
# elif not head.next.next: # 如果刚好两个结点
# if head.next.val < head.val: # 更正顺序
# head.next.next = head
# head = head.next
# head.next.next = None
# return head
#
# slow, fast = head, head # 快慢指针找中点
# while fast.next and fast.next.next:
# fast = fast.next.next
# slow = slow.next
# # 截断并分别递归
# head2 = slow.next
# slow.next = None
# l1 = self.insertionSortList(head)
# l2 = self.insertionSortList(head2)
# # 合并
# head = cur = ListNode(0)
# while l1 and l2:
# if l1.val < l2.val:
# cur.next = l1
# l1 = l1.next
# else:
# cur.next = l2
# l2 = l2.next
# cur = cur.next
# cur.next = l1 or l2
# return head.next
|
c17312a1f0a6859b3d93e1d09e622781be4a4410
|
jburgoon1/python-practice
|
/26_vowel_count/vowel_count.py
| 550 | 4.15625 | 4 |
def vowel_count(phrase):
"""Return frequency map of vowels, case-insensitive.
>>> vowel_count('rithm school')
{'i': 1, 'o': 2}
>>> vowel_count('HOW ARE YOU? i am great!')
{'o': 2, 'a': 3, 'e': 2, 'u': 1, 'i': 1}
"""
vowelCount = {}
vowel = 'aeiou'
for letter in phrase.lower():
if letter in vowel:
key = vowelCount.keys()
if letter in key:
vowelCount[letter]+=1
else:
vowelCount[letter]=1
return vowelCount
|
6776c6f6427f299909112697f9825b663dd97601
|
leofelix077/TGB---Paradigmas---Python
|
/wonder_woman.py
| 2,391 | 3.65625 | 4 |
#------------------------------------------------------------------------------
# Autores: Leonardo Felix, Gisela Miranda Difini, Karolina Pacheco, Tiago Costa
#------------------------------------------------------------------------------
from numpy import random
import random as rand
def NUMBER_OF_TRIES():
return 5
def SPACE():
return ' '
def ADDITIONAL_LETTERS():
return 1
def SCRAMBLE_WORD():
return 2
def MSG_INPUT_DECODE():
return 'Adivinhe a mensagem gerada'
def MSG_WIN():
return "Você decodificou a mensagem"
def MSG_TRY_AGAIN():
return "A mensagem não foi decodificada. Tente novamente"
def MSG_GAME_OVER():
return "O exército alemão acaba de liberar o gás na Bélica"
def CHAR_PAST_Z():
return '['
words = [
"GUERRA",
"ALEMANHA",
"BELGICA",
"NAZI",
"OCIDENTE",
"DIANA",
"ATAQUE",
"MORTAL",
"PRIMEIRA",
"BOMBA"
]
word = ''
generated_word = ''
def increment_word(word):
new_word = ''.join(chr(ord(letter)+1) for letter in word)
new_word_as_letters = list(new_word)
for character in range(0, len(new_word)):
if (new_word[character] is CHAR_PAST_Z()):
new_word_as_letters[character] = 'A'
return ''.join(new_word_as_letters)
def add_letters():
global word
global add_letters_word
global generated_word
generated_word = word
number_of_increments = random.randint(1,3)
increments = 0
while increments < number_of_increments:
generated_word = increment_word(generated_word)
increments += 1
def get_generated_word():
add_letters()
scramble_word()
def scramble_word():
global generated_word
global word
generated_word = ''.join(rand.sample(generated_word, len(generated_word)))
def get_word():
global word
word = words[random.randint(0,len(words)]
def start_decode_game():
tries = 0
print(generated_word[:4])
while tries < NUMBER_OF_TRIES():
print(MSG_INPUT_DECODE())
input_word = input()
if input_word.upper() == word:
print(MSG_WIN())
return
else:
print(MSG_TRY_AGAIN())
tries = tries + 1
print(MSG_GAME_OVER())
#---------------------------------------------------
get_word()
get_generated_word()
start_decode_game()
|
da95e736306e3b348c064056f8d27239b9c3b809
|
erpost/python-beginnings
|
/tuples/tuple_return_sorted_sequence_reversed.py
| 186 | 3.96875 | 4 |
# Return sorted sequence (by value order)
c = {'a': 10, 'c': 22, 'b': 1}
tmp = list()
for k, v in c.items():
tmp.append((v,k))
print(tmp)
tmp = sorted(tmp, reverse=True)
print(tmp)
|
b2cdff9ccbc173406f9b28ed5c86f56ac3614163
|
afieqhamieza/DataStructures
|
/python/type_time.py
| 972 | 4.0625 | 4 |
# Imagine you have a special keyboard with all keys in a single row.
# The layout of characters on a keyboard is denoted by a string keyboard of length 26.
# Initially your finger is at index 0. To type a character, you have to move your finger
# to the index of the desired character. The time taken to move your finger from index i to index j is abs(j - i).
# Given a string keyboard that describe the keyboard layout and a string text,
# return an integer denoting the time taken to type string text.
from typing import List
def type_time(str: List[str], text: List[str]) -> int:
current_i = 0
timeTaken = 0
for i in range(0, len(text)):
text_i = str.index(text[i])
time = abs(text_i - current_i)
timeTaken += time
print(text)
current_i = str.index(text[i])
return timeTaken
if __name__ == '__main__':
str = "abcdefghijklmnopqrstuvwxy"
text = "cba"
print(type_time(list(str), list(text)))
|
4ee96b75d9a6551d566be63508137d972cf20b90
|
EgorMichel/2021_Michel_infa
|
/1st week/tort13.py
| 960 | 3.765625 | 4 |
import turtle as t
t.shape('turtle')
t.speed(0)
def arc(r):
for i in range(90):
t.forward(2 * r * 0.01745)
t.right(2)
def circle(r):
t.penup()
t.forward(r)
t.right(90)
t.pendown()
arc(r)
arc(r)
t.penup()
t.left(90)
t.backward(r)
t.pendown()
#face
t.begin_fill()
arc(100)
arc(100)
t.color("yellow")
t.end_fill()
t.color("black")
#right eye
t.begin_fill()
t.right(60)
t.penup()
t.forward(60)
t.pendown()
circle(15)
t.penup()
t.backward(60)
t.color("blue")
t.end_fill()
t.color("black")
#left eye
t.begin_fill()
t.right(60)
t.forward(60)
t.pendown()
circle(15)
t.penup()
t.backward(60)
t.color("blue")
t.end_fill()
t.color("black")
#nose
t.width(8)
t.left(30)
t.forward(80)
t.pendown()
t.forward(30)
#smile
t.color("red")
t.penup()
t.forward(10)
t.left(90)
t.forward(70)
t.right(90)
t.pendown()
arc(70)
input()
|
f52b048228652eced1c4866f2a9791170aa9c773
|
Phobosmir/checkio-home
|
/the-most-frequent.py
| 960 | 4.21875 | 4 |
"""
ZH-HANS RU JA English
You have a sequence of strings, and you’d like to determine the most frequently occurring string in the sequence.
Input: a list of strings.
Output: a string.
Example:
most_frequent([
'a', 'b', 'c',
'a', 'b',
'a'
]) == 'a'
most_frequent(['a', 'a', 'bi', 'bi', 'bi']) == 'bi'
"""
def most_frequent(data: list) -> str:
"""
determines the most frequently occurring string in the sequence.
"""
res = {}
for d in data:
res[d] = res.get(d, 0) + 1
return max(res, key=lambda x: res[x])
if __name__ == '__main__':
# These "asserts" using only for self-checking and not necessary for auto-testing
print('Example:')
print(most_frequent([
'a', 'b', 'c',
'a', 'b',
'a'
]))
assert most_frequent([
'a', 'b', 'c',
'a', 'b',
'a'
]) == 'a'
assert most_frequent(['a', 'a', 'bi', 'bi', 'bi']) == 'bi'
print('Done')
|
a0e1dc5b15091080d9cf23d8bbb2ea1093861766
|
dbaird1/pl
|
/dbaird1_hw1/pow_full.py
| 392 | 3.859375 | 4 |
#! /usr/bin/env python
import sys
def powF(n, p):
if p == 0:
return 1
else:
return n * pow(n, p-1)
def powI(n,p):
if p == 0:
return 1;
s = 1
while p > 0:
p-=1
s= s*n
return s
if len(sys.argv) != 3:
print("%s usage: [NUMBER] [power]" % sys.argv[0])
exit()
print(powF(int(sys.argv[1]), int(sys.argv[2])))
print(powI(int(sys.argv[1]), int(sys.argv[2])))
|
958e1673473fad4442740dc969e65b67fec9dcfd
|
vavronet/python-for-beginners
|
/functions/daripa/pascal_triangle.py
| 953 | 4.21875 | 4 |
# Create a function that prints on the screen the Pascal triangle with n rows.
# 1
# 1 1
# 1 2 1
# 1 3 3 1
# 1 4 6 4 1
#1 5 10 10 5 1
def get_unknown_content(row, previous_row):
unknown = []
counter = 1
while counter <= (row - 2):
item = previous_row[counter] + previous_row[counter - 1]
unknown.append(item)
counter = counter + 1
return unknown
def pascal_triangle(n):
last_row = []
row = 1
while row <= n:
content = [1]
if row == 1:
content = [1]
elif row == 2:
content.append(1)
else:
unknown = get_unknown_content(row, last_row)
content = content + unknown
content.append(1)
print_row = ' '.join(map(str, content))
spaces_before = ' ' * (n - row)
print(spaces_before + print_row)
last_row = content
row = row + 1
pascal_triangle(6)
|
d2ea629e3747b8281ce6309e36bcdb131dc37dca
|
sbelectronics/nixiecalc
|
/calculator.py
| 4,967 | 3.53125 | 4 |
"""
Calculator Engine
Dr. Scott M Baker, 2014
http://www.smbaker.com/
[email protected]
"""
import math
import sys
class Calculator(object):
def __init__(self):
self.display = 0
self.memory = 0
self.accumulator = None
self.inputBuffer = ""
self.operators = {}
self.operators["+"] = self.plus
self.operators["-"] = self.minus
self.operators["*"] = self.times
self.operators["/"] = self.divide
self.unary = {}
self.unary["!"] = self.factorial
self.unary["10x"] = self.powten
self.unary["x2"] = self.x2
self.unary["x3"] = self.x3
self.unary["int"] = self.int
self.unary["MR"] = self.memRead
self.unary["pi"] = self.pi
self.unary["1/x"] = self.inverse
self.unary["sqrt"] = self.sqrt
self.unary["log"] = self.log10
self.unary["ln"] = self.ln
self.operator = None
self.operand = None
self.lastEqualOperator = None
self.lastKey = None
self.memory = 0
def reset(self):
self.display = 0
self.memory = 0
self.accumulator = None
self.inputBuffer = ""
def handle_key(self, key):
if key in ['0','1','2','3','4','5','6','7','8','9','.']:
self.inputBuffer = self.inputBuffer + key
self.operand = float(self.inputBuffer)
self.display = self.operand
if (self.lastKey == "="):
self.accumulator = None
elif (key == "C") or (key == "AC"):
if (self.inputBuffer != "") or (key == "AC"):
self.inputBuffer = ""
self.operand = 0
self.display = 0
if (key=="AC") or (self.lastKey == "="):
self.accumulator = None
elif key in self.operators.keys():
if (self.operand is None):
return
if self.accumulator is None:
self.accumulator = self.operand
elif self.operator is not None:
self.accumulator = self.operator(self.accumulator, self.operand)
self.display = self.accumulator
self.operator = self.operators[key]
self.inputBuffer = ""
elif key in self.unary.keys():
self.operator = self.unary[key]
self.accumulator = self.operator(self.display)
self.operator = None
self.lastEqualOperator = None
self.display = self.accumulator
self.inputBuffer = ""
elif key=="=":
if self.operator:
self.accumulator = self.operator(self.accumulator, self.operand)
self.lastEqualOperator = self.operator
elif self.lastEqualOperator:
self.accumulator = self.lastEqualOperator(self.accumulator, self.operand)
self.display = self.accumulator
self.inputBuffer = ""
self.operator = None
print "accum", self.accumulator
elif key=="MC":
self.memory = 0
elif key=="M+":
self.memory = self.memory + self.display
elif key=="M-":
self.memory = self.memory - self.display
elif key=="q":
sys.exit(0)
self.lastKey = key
def plus(self, accumulator, operand):
print "plus", accumulator, operand
return float(accumulator) + operand
def minus(self, accumulator, operand):
print "minus", accumulator, operand
return float(accumulator) - operand
def times(self, accumulator, operand):
print "times", accumulator, operand
return float(accumulator) * operand
def divide(self, accumulator, operand):
print "divide", accumulator, operand
return float(accumulator) / operand
def factorial(self, value):
return math.factorial(int(value))
def powten(self, value):
return math.pow(10, value)
def x2(self, value):
return (value * value)
def x3(self, value):
return (value * value * value)
def int(self, value):
return int(value)
def memRead(self, value):
return self.memory
def pi(self, value):
return math.pi
def inverse(self, value):
return 1/value
def sqrt(self, value):
return math.sqrt(value)
def log10(self, value):
return math.log10(value)
def ln(self, value):
return math.log(value)
def getch():
import sys, tty, termios
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
def main():
c = Calculator()
while True:
c.handle_key(getch())
print "%0.0f \r"% c.display,
if __name__ == "__main__":
main()
|
ba30c3dd71cc716dd0871cd216bd990c56673725
|
mrparkonline/python3_functions
|
/exercise1.py
| 1,960 | 4.21875 | 4 |
# U6E1 - Exercise Set 1 Solutions
# Mr Park
'''
note:
- To use any of these functions, you can import the file and try calling the
functions
'''
def isEven(num):
''' isEven determines if the given argument is an even number
--param
num : integer
--return
boolean
'''
return num % 2 == 0
# end of isEven
def isPalindrome(word):
''' isPalindrome determines if the given argument is a palindrome
For this solution, we will assume that there are no whitespaces and special
characters
--param
word : string
--return
boolean
'''
word = word.lower()
return word == word[::-1]
# end of isPalindrome
def isPrime(num):
''' isPrime determines if the given argument integer is a prime number
--param
num : integer
--return
boolean
'''
if num < 2:
return False
elif num in [2,3]:
return True
else:
for i in range(2,num):
if num % i == 0:
return False # return acts like a break
# as soon as it finds a factor, it will exit the function
# and return False
else:
return True
# end of isPrime
def vowelCounter(word):
''' vowelCounter returns the number of vowels in a string
--param
word : string
--return
integer
'''
if word:
counter = 0
for character in word.lower():
if character in 'aeiou':
counter += 1
return counter
else:
# empty string
return 0
# end of vowelCounter
def factorial(num):
''' factorial() is the ! mathematical operator
--param
num : integer
--return
integer
'''
if num < 1:
return -1 # -1 is more of an error code ...
elif num in [0,1]:
return 1
else:
result = 1
for i in range(1,num+1):
result *= i
return result
# end of factorial
|
39aeb9d2bba1827ed0ce62a69ccf4894ba81841a
|
lronl/start01
|
/home_first.py
| 1,644 | 3.53125 | 4 |
#1 Создать список из N элементов (от 0 до n с шагом 1). В этом списке вывести все четные значения.
lis = [i for i in range(50)]
num = 1
out = []
while(num < len(lis)):
if lis[num] % 2 == 0:
out.append(lis[num])
num += 1
print(out)
#2 Создать словарь, Страна:Столица.
Capitals = dict()
Capitals['Russia'] = 'Moscow'
Capitals['Ukraine'] = 'Kiev'
Capitals['USA'] = 'Washington'
Countries = ['Russia', 'France', 'USA', 'Russia']
for country in Countries:
if country in Capitals:
print('Столица страны ' + Capitals[country])
else:
print('В базе нет страны c названием ' + country)
#3 Программа которая считает до 100 и делает замену некоторых чисел на слова.
for x in range(1, 100):
s = '';
if x % 3 == 0:
s += 'Fizz'
if x % 5 == 0:
s += "Buzz"
if s == '':
s = x
print(s, end=' ')
#4 Функция bank
amount = input("Сумма депозита: ")
amount = int(amount)
pct = input("Процент: ")
pct = int(pct)
years = input("кол-во лет: ")
years = float(years)
pct = pct / 100
month_pay = (amount * pct * (1 + pct)**years) / (12 * ((1 + pct)**years - 1))
print("Ваш месячный платеж составит: %.2f" % month_pay)
summa = month_pay * years * 12
print("За весь период вы заплатите: %.2f" % summa)
print("Это составит %.2f%% от первоначальной суммы" % ((summa / amount) * 100))
|
85ec69adfdaa5f913fcf0b94d3dc13b2ee8f76dc
|
oknelvapi/GitPython
|
/Coursera_online/week5/test5.3.4.py
| 339 | 3.625 | 4 |
# Переставьте соседние элементы списка (A[0] c A[1],A[2] c A[3] и т.д.).
# Если элементов нечетное число, то последний элемент остается на своем месте.
a = input().split()
print(*([x for i in range(0, len(a), 2) for x in a[i:i+2][::-1]]))
|
2a861a372bee1234eded99f208ad0d7628bd1335
|
sheldonzhao/LeetCodeFighting
|
/25. Reverse Nodes in k-Group.py
| 1,859 | 4 | 4 |
'''
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
k is a positive integer and is less than or equal to the length of the linked list.
If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
You may not alter the values in the nodes, only nodes itself may be changed.
Only constant memory is allowed.
For example,
Given this linked list: 1->2->3->4->5
For k = 2, you should return: 2->1->4->3->5
For k = 3, you should return: 3->2->1->4->5
'''
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def reverseKGroup(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
if not head or not head.next or k <= 1:
return head
dummy = ListNode(None)
dummy.next = head
self.last_kth_node = dummy
count = 0
node = {}
while head:
node[count] = head
count += 1
head = head.next
if count == k:
self.reverse(node, k)
count = 0
return dummy.next
def reverse(self, node, k):
temp = node[k - 1].next
for i in range(k - 1):
node[k - i - 1].next = node[k - i - 2]
node[0].next = temp
self.last_kth_node.next = node[k - 1]
self.last_kth_node = node[0]
def print(self, head):
while head:
print(head.val)
head = head.next
mySolution = Solution()
head = ListNode(1)
head.next = ListNode(2)
head.next.next = ListNode(3)
head.next.next.next = ListNode(4)
head.next.next.next.next = ListNode(5)
re = mySolution.reverseKGroup(head, 3)
mySolution.print(re)
|
7e3980d18c785ceab36c979ea8ea646e48f1bb38
|
superorakul/while
|
/vsearch.py
| 472 | 3.578125 | 4 |
def search4vowels(phrase: str) -> set:
"""Здесь есть описание которое мне влом писать так что извините"""
vowels = set('aeiou')
return vowels.intersection(set(phrase))
def search4letters(phrase: str, letters: str='aeiou') -> set:
"""Возвращает множество букв из 'letters' найденных в указанной форме """
return set(letters).intersection(set(phrase))
|
c17e88935491cb67e4f8a8751b5bbf6bb66c54e4
|
justinzh/python
|
/nester.py
| 446 | 3.625 | 4 |
'nested class in function'
X = 1
def nester():
X = 2
print(X)
class C:
'docstring for class C'
X = 3
print(X)
def method1(self):
print(X)
print(self.X)
def method2(self):
X = 4
print(X)
self.X = 5
print(self.X)
I = C()
I.method1()
I.method2()
print('docstring:', I.__doc__)
print(X)
nester()
print('-'*40)
|
ad1cc1968545006d11cd2241bb4dc61f2196fc42
|
jordan78906/CSCI-161_projects
|
/HernandezAlmache_Jordan_11.py
| 2,119 | 4.40625 | 4 |
#Jordan Hernandez-Alamche
#CSci 161 L03
#Assignment 11
#Merge sort
'''
-Merge Sort:
1:Find Mid point to divide the array into two halves
2:Call Merge Sort for first half
3:Call Merge Sort for second half
4:Base Case: if array size is 1 or smaller, return.
5:Merge the divided arrays sorted until the complete array is merged.
'''
def mergeSort(main_list):
#1:Mid-Point - Slicing array in half
#Left array from 0-mid Right array from mid-end
L_list = main_list[:len(main_list)//2]
R_list = main_list[len(main_list)//2:]
#4: Base Case - Already sorted, since its a single element.
if len(main_list) <= 1:
return main_list
#2&3: Recursion - slices left & right arrays to the smaller arrays, length of 1 element
mergeSort(L_list)
mergeSort(R_list)
#5: Merge - Merge divided arrays sorted
merge_sorted_arrays(L_list,R_list,main_list)
def merge_sorted_arrays(L_list,R_list,main_list):
#Merge
#keeping track of index positions
#i = left index, j = right index, k = merged index
i = j = k = 0
#Rebuilding main array with multiple smaller arrays of 1 element length
#going through index positions in both L AND R array
while i < len(L_list) and j < len(R_list):
#comparison
if L_list[i] <= R_list[j]:
main_list[k] = L_list[i]
#adding to main array and moving pointer on L_List array over 1
i += 1
else:
main_list[k] = R_list[j]
#adding to main array and moving pointer on R_List array over 1
j += 1
#Moving down the index of merged array, to keep adding elements
k += 1
#continues reading off L_list if R_list finishes first
while i < len(L_list):
main_list[k] = L_list[i]
i += 1
k += 1
#continues reading off R_list if L_list finishes first
while j < len(R_list):
main_list[k] = R_list[j]
j += 1
k += 1
original_list = [26,64,11,34,25,90,12]
print('Input Array:')
print(original_list)
mergeSort(original_list)
print('\nSorted Array:')
print(original_list)
|
619ae3498b34d7f95f825887527837d32b80e11e
|
mradityagoyal/python
|
/NextPermutation.py
| 1,469 | 3.625 | 4 |
class NextPermutation:
def nextPermutation(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
if len(nums) < 2: return
for i in range(len(nums)-1, 0, -1):
prev = i -1
if nums[i] > nums[i-1]:
# find the first num larger than nums[i-i] in nums[last] to nums[i]
idNextLarger = -1
for idx in range(len(nums)-1, i-1, -1):
if nums[idx] > nums[i-1]:
idNextLarger = idx
break
#swap i-1 and idNextLarger
self.swap(nums, i-1, idNextLarger)
#reverse the list from i to the end.
self.reverse(nums, i)
return
# all are ascending. reverse these.
for i in range(0, int(len(nums)/2)):
last = len(nums) -1
self.swap(nums, i, last -i)
def swap(self, nums, i, j):
temp = nums[i]
nums[i]=nums[j]
nums[j]=temp
def reverse(self, nums, startIdx):
"""
reverse the nums from start idx. in place.
:param nums:
:param startIdx:
:return:
"""
for i in range(0, int((len(nums)-startIdx)/2)):
self.swap(nums, startIdx+i , len(nums)-1 - i)
# startup
np = NextPermutation()
nums = [2,3,1]
np.nextPermutation(nums)
print(nums)
|
f19496470f2555a77a3aa855f980dc62e6a64d00
|
henriavo/learning_python_5e
|
/part_2/ch6.py
| 490 | 3.875 | 4 |
#!/usr/bin/python3
import copy
print("mutable objects \n")
print("shared references and equality \n")
lista = [23, 41, 66, 11]
listb = lista
if lista == listb:
print("both lista and listb are variables with same value!\n")
if lista is listb:
print("both lista and listb are variables pointing to the same object!\n")
listb = copy.copy(lista)
if lista == listb:
print("STILL same value!\n")
if lista is not listb:
print("NOT same object!\n")
print("lista is: {}".format(lista))
|
ec5738f3915590b61a8eb2daa039e411e1266cd6
|
rtmoffat/pylearn
|
/fac.py
| 106 | 3.53125 | 4 |
def fac(n):
if (n<=1):
return 1
else:
return (n * fac(n-1))
x=input("Enter number:")
print(fac(x))
|
85404073ff30cda662e2dbed2c4522453ab6edb8
|
parkjeongmi/jamie_study
|
/0626test/0625_1.py
| 508 | 3.8125 | 4 |
#백준
#최소 스패닝 트리
#모든 정점 연결 + 가중치의 합 최소
#Kruskal Algorithm
#1. 간선 정렬
#2. 간선이 잇는 두 정점의 root를 찾음
#3. 다르다면 하나의 root를 바꾸어 연결
def find_parent(parent, x) :
if parent[x] != x :
parent[x] = find_parent(parent, parent[x])
return parent[x]
def make_union(parent, a, b) :
a = find_parent(parent,a)
b = find_parent(parent, b)
if a<b :
parent[b] = a
else :
parent[a] = b
|
2a9aa37463169109695215d2bf44c9052c1069e0
|
tancheng/CacheSim
|
/cachesimulator/word_addr.py
| 316 | 3.765625 | 4 |
#!/usr/bin/env python3
class WordAddress(int):
# Retrieves all consecutive words for the given word address (including
# itself)
def get_consecutive_words(self, num_words_per_block):
offset = self % num_words_per_block
return [(self - offset + i) for i in range(num_words_per_block)]
|
810de4170334c19eb7c20f5e501c92f54a573882
|
vaibhavg12/Problem-Solving-in-Data-Structures-Algorithms-using-Python3
|
/Algorithms/2 Sorting/MInAbsDiffPair.py
| 923 | 3.96875 | 4 |
"""
Given an array of integers, find minimum absoulute difference pair of all the possible pairs.
first approach is to find each pair by runnning two loop and finding minimum among them.
O(n2)
"""
"""
Using sorting munimum diff pairs will be adjacent to each other.
"""
import sys
def MinAbsPairDifferences(arr):
size = len(arr)
minimum = sys.maxint
for i in range(size):
for j in range(i+1, size):
minimum = min(abs(arr[i] - arr[j]), minimum)
return minimum
def MinAbsPairDifferences2(arr):
size = len(arr)
arr.sort()
minimum = min(abs(arr[0] - arr[1]), abs(arr[size-2] - arr[size-1]))
for i in range(1, size - 1):
temp = min(abs(arr[i] - arr[i - 1]), abs(arr[i] - arr[i + 1]))
minimum = min(temp, minimum)
return minimum
# Driver code
arr = [5, 101, 11, 14, 18, 71]
print MinAbsPairDifferences(arr)
print MinAbsPairDifferences2(arr)
|
98b745b499fe4aed5644a5e76e357d88d182b5ed
|
raultm/Enero-String-Calculator
|
/amaneiro/stringcalculator.py
| 1,417 | 3.859375 | 4 |
#!/usr/bin/python
#my own exceptions
class NegativesNotAllowed(Exception): pass
class StringCalculator:
def add(self, values=""):
if (len(values) == 0):
return 0
adapter = EntryValuesAdapter(values)
if (adapter.getNumberOfValues() == 0):
return 0
if (not adapter.hasSomeNegative()):
sum=0
for i in adapter.getValues():
sum=sum+int(i)
return sum
else:
raise NegativesNotAllowed()
class EntryValuesAdapter:
def __init__(self, values):
self.has_negative = False
self.adapted_values = self.parse(values)
def getNumberOfValues(self):
return len(self.adapted_values)
def hasSomeNegative(self):
if (int(min(self.adapted_values)) < 0):
return True
else:
return False
def getValues(self):
return self.adapted_values
def parse(self, values):
"""The strategy choosen is to convert first all possible separators (the user-defined, ',' or '\n') to one of them. And them, split the whole chain of values by that master separator. '\n' will be the master separator. """
if values.startswith("//"):
[custom_separator, values] = values.split("\n", 1)
values = values.replace(custom_separator[2:], '\n')
return values.replace(',', '\n').split('\n')
|
65d3bfdac89d6ae2d6b35bd96e44618de8ed5707
|
xfsala/Cool-ideas-python
|
/Collatz conjecture/Collatz con-3n+1 prob.py
| 495 | 3.8125 | 4 |
def checknum(num):
iterations=1
while(num!=1):
if num%2==0:
num=num//2
else:
num=3*num+1
iterations+=1
print(num,iterations)
for i in range(20,31):
checknum(i)
/*
when n is even set n as n/2.else set n as 3n+1.
Repeat process till num becomes 1.
Here analyse that smaller number doesnt imply algo will take lesser steps or
vice versa.
Still unsolved problem in computer science.
Go and find more on google.
*/
|
dbe8ca2c595afb3f97fbd6de685322a48f3cf6db
|
CaosMx/100-Days-of-Code_Python-Bootcamp-2021
|
/d001_e001.py
| 1,105 | 4.71875 | 5 |
# Day 001
# Exercise 001
# CaosMx
# Dic 2020
"""
Printing to the Console
Instructions
Write a program in main.py that prints the some notes from the previous lesson using what you have learnt about the Python print function.
Warning: The output in your program should match the example output shown below exactly, character for character, even spaces and symbols should be identical, otherwise the tests won't pass.
Example Output
After you have written your code, you should run your program and it should print the following:
Day 1 - Python Print Function
The function is declared like this:
print('what to print')
e.g. When you hit run, this is what should happen:
Test Your Code
Before checking the solution, try copy-pasting your code into this repl:
https://repl.it/@appbrewery/day-1-1-test-your-code
This repl includes my testing code that will check if your code meets this assignment's objectives.
Solution
https://repl.it/@appbrewery/day-1-1-solution
"""
print ("Day 1 - Python Print Function")
print ("The function is declared like this:")
print ("print('what to print')")
|
e9cd859f53d0caf62a96f60e06e5a19ecb8bed1b
|
LopesAbigail/intro-ciencia-computacao
|
/Step-01/SEM7-EX02-PerimetroRetangulo.py
| 324 | 4 | 4 |
# Retângulo
largura = int(input("digite a largura: "))
altura = int(input("digite a altura: "))
for i in range(0, altura):
for j in range(0, largura):
if (i == 0 or i == altura-1 or j == 0 or j == largura-1):
print("#", end = "")
else:
print(" ", end = "")
print("")
|
a19b1e11014ecb6c6c8c121df273dfb80e85e717
|
jiajiabin/python_study
|
/day11-20/day11/03_拷贝构造函数.py
| 2,198 | 4.09375 | 4 |
class Rect:
def __init__(self, length, width):
self.__length, self.__width = length, width
# 在其他语言中,这个就是构造函数,构造函数不是构造对象的函数,而是初始化的函数。
# 在C++当中构造函数和类名相同的,在Python不认为这个函数是构造函数,构造函数是new。init就是初始化函数
def set_length_width(self, l, w):
self.__length, self.__width = l, w
def __repr__(self):
return "({}:{})".format(self.__length, self.__width)
# 拷贝构造函数就是传参是另一个当前类对象的init函数。
def copy(self):
# 创建一个Rect对象,其值和当前对象一样
return Rect(self.__length, self.__width)
r1 = Rect(3, 4)
r2 = r1.copy()
print(r2)
r2.set_length_width(5, 6)
print(r1, r2)
# 我们所有内置数据结构,除Number外都是对象。
ls = [1, 2, 3, 4]
n_ls = ls
# ls 和 n_ls是同一个列表
n_ls[3] = 18
print(ls, n_ls) # 仅仅是引用的复制
new_ls = ls.copy()
new_ls[0] = -1
print(ls, new_ls) # 浅拷贝
# 列表中拥有三个对象
ls = [Rect(1, 2), Rect(3, 4), Rect(5, 6)]
ls2 = ls # 同一个列表
ls2[0].set_length_width(9, 10)
print(ls, ls2)
ls3 = ls.copy() # 不同的列表,但是列表中是同一个对象的引用
ls3[0].set_length_width(-1, -1)
print(ls, ls3)
# 浅拷贝指挥拷贝列表对象,但是列表中的其他对象,仍然只有一个。
# 深拷贝则不仅拷贝最外层的对象,连同子对象,子子对象,一起复制。
ls = [1, 2, 3, 4] # 不是引用,是数值
ls1 = ls
ls1[0] = -1
print(ls, ls1)
ls2 = ls.copy()
ls2[0] = -2
print(ls, ls2)
# 列表里如果是Number值,复制列表,值也就复制了两个.如果列表里是引用,复制列表,引用复制为两个。
# 例题
# ls = [1, 2, 3, 4, [4, 5]]
# ls1 = ls
# ls1[0] = -1
# ls1[4][0] = -2
# print(ls, ls1)
ls = [1, 2, 3, 4, [4, 5]]
ls1 = ls.copy()
ls1[0] = -1 # ls1[0]是个值,复制了就和ls[0]没关系
ls1[4][0] = -2 # ls1[4]是个引用,复制了则ls1[4]和ls[4]是同一个对象的两个引用
print(ls, ls1)
|
9fd56f29d142953aa363e79ad801b2eb62353ff3
|
DiptiGupte/Automate-the-Boring-Stuff-with-Python-projects
|
/inverter.py
| 553 | 3.6875 | 4 |
import openpyxl
#invert the row and colum of the cells in spreadsheet
def invert(spreadsheet):
newWb = openpyxl.Workbook()
newSheet = wb.active
givenWb = openpyxl.load_workbook(spreadsheet)
givenSheet = read.active
for rowNum in range(1, givenSheet.max_row + 1):
for colNum in range(1, givenSheet.max_col + 1):
newSheet.cell(row = colNum, column = rowNum).value = givenSheet.cell(row = rowNum, column = colNum).value
newname = 'inverted_' + spreadsheet
givenSheet.save(newname)
invert('myProduce.xlsx')
|
7894adf619c48a61cec7f861d0efb4212055f8fa
|
JunctionChao/LeetCode
|
/next_bigger_number.py
| 1,463 | 4.15625 | 4 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Date : 2020-11-05
# Author : Yuanbo Zhao ([email protected])
"""
get the next bigger number using the same digits of a number
ex: 123 -> 132
"""
def next_bigger(number):
# 将数字转化为list
number_to_list = []
while number:
number, mod = divmod(number, 10)
number_to_list.append(mod)
number_to_list = number_to_list[::-1]
# 先找到右边比左边大的第一个位置
size = len(number_to_list)
for x in range(size-1, -1, -1):
if number_to_list[x-1] < number_to_list[x]:
break
if x > 0:
# 找第二层较大的数
for y in range(size-1, -1, -1):
if number_to_list[x-1] < number_to_list[y]:
number_to_list[x-1], number_to_list[y] = \
number_to_list[y], number_to_list[x-1]
break
# 后续的数是降序的,做置换调整
for z in range((size-x)//2):
number_to_list[x+z], number_to_list[size-z-1] = number_to_list[size-z-1], number_to_list[x+z]
# 恢复为数字
res, ex = 0, 0
while number_to_list:
res += number_to_list.pop() * 10**ex
ex += 1
return res
# x==0说明左边的数字总是比右边的大
else:
return "the bigger number is not exist"
if __name__ == '__main__':
print(next_bigger(4321))
print(next_bigger(1342))
print(next_bigger(1243))
|
1d345e04ac551d260cfb34fd6aa8e5c64fea76b5
|
frankobe/lintcode
|
/16_permutations-ii/permutations-ii.py
| 1,155 | 3.765625 | 4 |
# coding:utf-8
'''
@Copyright:LintCode
@Author: frankobe
@Problem: http://www.lintcode.com/problem/permutations-ii
@Language: Python
@Datetime: 15-06-23 18:34
'''
class Solution:
"""
@param nums: A list of integers.
@return: A list of unique permutations.
"""
def permuteHelper(self, nums, result, tmpList, visited):
numsLen = len(nums)
if len(tmpList) == numsLen:
result.append(list(tmpList))
return
for i in range(0, numsLen):
if visited[i] == 1 or (i >0 and nums[i] == nums[i - 1] and visited[i - 1] == 1):
continue
visited[i] = 1
tmpList.append(nums[i])
self.permuteHelper(nums, result, tmpList, list(visited))
tmpList.pop()
visited[i] = 0
def permuteUnique(self, nums):
# write your code here
if nums is None or len(nums) == 0:
return []
result = []
nums.sort()
visited = [0]*len(nums)
self.permuteHelper(nums, result, [], visited)
return result
|
a77e3d67abb3552e8e87ea95b73228ed8edff977
|
Ran-Dou/Python-for-Data-Scientist
|
/9 Manipulating DataFrames with pandas.py
| 8,812 | 3.578125 | 4 |
import os
os.chdir('/Users/randou/Esther/Coding/Python/Data Scientist with Python/Python-for-Data-Scientist')
# =============================================================================
# EXTRACTING AND TRANSFORMING DATA
# =============================================================================
import pandas as pd
df = pd.read_csv('sales.csv', index_col='month')
print(df)
# indexing
print(df['salt']['Jan'])
print(df.eggs['Mar'])
print(df.loc['May', 'spam'])
print(df.iloc[4, 2])
print(df_new = df[['salt', 'eggs']])
# Series or Dataframe
print(type(df['eggs'])) #Series
print(type(df[['eggs']])) #DataFrame
# Selection in reverse order
print(df['Mar':'Jan':-1])
# filtering
print(df[df.salt > 60])
# logical combine: & |
print(df[(df.salt >= 60) & (df.eggs < 200)])
# DataFrames with zeros and NaNs
df2 = df.copy()
df2['bacon'] = [0, 0, 50, 60, 70, 80]
df2.loc[:, df2.all()] # exclude column with zero entries
df2.loc[:, df2.any()] # exclude column with all zero entries
df.loc[:, df.isnull().any()] # return column with NaN
df.loc[:, df.notnull().all()]
df.dropna(how='all')
df.dropna(how='any')
# Example
titanic = pd.read_csv('titanic.csv')
# Drop columns in titanic with less than 1000 non-missing values
print(titanic.dropna(thresh=1000, axis='columns').info())
# Transforming DataFrame
df.floordiv(12) # convert to dozens unit
import numpy as np
np.floor_divide(df, 12)
def dozens(n):
return n//12
df.apply(dozens)
df.apply(lambda n: n//12)
# String Transformation
df.index = df.index.str.upper()
print(df)
# for index, there is no apply method, instead its df.index.map
df.index = df.index.map(str.lower)
print(df)
# create new column
df['salty_eggs'] = df.salt + df.eggs
### Example
# Create the dictionary: red_vs_blue
red_vs_blue = {'Obama':'blue', 'Romney':'red'}
# Use the dictionary to map the 'winner' column to the new column: election['color']
election['color'] = election['winner'].map(red_vs_blue)
print(election.head())
# When performance is paramount, you should avoid using .apply() and .map()
# because those constructs perform Python for-loops over the data stored in a pandas Series or DataFrame.
# By using vectorized functions instead, you can loop over the data at the same speed as compiled code (C, Fortran, etc.)!
# NumPy, SciPy and pandas come with a variety of vectorized functions (called Universal Functions or UFuncs in NumPy).
from scipy.stats import zscore
eggs_zscore = zscore(df['eggs])
# =============================================================================
# ADVANCED INDEXING
# =============================================================================
# Index can only be modified by all at once
### Hierarchical indexing
titanic = titanic.set_index(['name', 'sex'])
print(titanic.head())
print(titanic.index) # Multiindex
print(titanic.index.name)
print(titanic.index.names)
titanic = titanic.sort_index()
print(titanic.head())
# The tuple used for the index does not recognize slicing with columns natively
titanic.loc[(slice(None), slice('female')), :]
# =============================================================================
# REARANGING AND RESHAPING
# =============================================================================
### Pivoting
df.pivot(index='...', columns='...', values='...')
df.pivot_table(index='...', columns='...', values='...', aggfunc='...', margins=True)
# if not setting values, all remaining will be used
### Stacking & unstacking
# unstack # pivot multiindex dataframe by gender
titanic_unstack = titanic.unstack(level='sex')
titanic_unstack = titanic.unstack(level=1)
titanic_stack = titanic_unstack.stack(level='name')
swapped = titanic.swaplevel.sort_index(0, 1) #switch levels
### melting
pd.melt(df, id_vars=[...], value_vars=[...], var_name=..., value_name=...)
# =============================================================================
# GROUPBY
# =============================================================================
# Aggregation/Reduction
# mean/std/sum/first/last/min/max/median
df.groupby('eggs').count()
df.groupby('eggs').median()
df.groupby(['eggs','salt']).agg(['max','min']) # multi-level
df.groupby(level=['eggs','salt']).agg(['max','min']) # multi-level
# function can also be customized
# can also use a dictionary in agg
# can also groupby other pandas series with same index value to groupby
### Categorical value
df.column.unique()
df.column = df.column.astype('category')
# Advanteges: less memory/ speed up operations like groupby()
### Example
titanic = pd.read_csv('titanic.csv')
by_class = titanic.groupby('pclass')
count_by_class = by_class.survived.count()
print(count_by_class)
by_mult = titanic.groupby(['embarked', 'pclass'])
count_mult = by_mult.survived.count()
print(count_mult)
# use .strftime('%a') to transform the index datetime values to abbreviated days of the week.
df.index.strfrime('...')
### Transforming
def zscore(series):
return (series - series.mean()) / series.std()
df.groupby('...')[column].transform(function)
# the agg function applies reduction
# the transform function applies a function elementwise to groups
# apply is used for complicated situation
# Example
from scipy.stats import zscore
def zscore(series):
return (series - series.mean()) / series.std()
gapminder = pd.read_csv('gapminder_tidy.csv')
standardized = gapminder.groupby('region')['life','fertility'].transform(zscore)
outliers = (standardized['life'] < -3) | (standardized['fertility'] > 3)
gm_outliers = gapminder.loc[outliers]
print(gm_outliers)
# df.groupby().groups is a dict
under10 = (titanic['age']<10).map({True:'under 10', False:'over 10'})
# Group by under10 and compute the survival rate
survived_mean_1 = titanic.groupby(under10)['survived'].mean()
print(survived_mean_1)
# Group by under10 and pclass and compute the survival rate
survived_mean_2 = titanic.groupby([under10, 'pclass'])['survived'].mean()
print(survived_mean_2)
# =============================================================================
# CASE STUDY
# =============================================================================
medals = pd.read_csv('all_medalists.csv')
USA_edition_grouped = medals.loc[medals.NOC == 'USA'].groupby('Edition')
USA_edition_grouped['Medal'].count()
country_names = medals.NOC
medal_counts = country_names.value_counts()
print(medal_counts.head(15))
# Construct the pivot table: counted
counted = medals.pivot_table(index='NOC', columns='Medal', values='Athlete', aggfunc='count')
counted['totals'] = counted.sum(axis='columns')
counted = counted.sort_values(by='totals', ascending=False)
print(counted.head(15))
ev_gen = medals.loc[:,['Event_gender','Gender']]
# Drop duplicate pairs: ev_gen_uniques
ev_gen_uniques = ev_gen.drop_duplicates()
print(ev_gen_uniques)
medals_by_gender = medals.groupby(['Event_gender','Gender'])
medal_count_by_gender = medals_by_gender.count()
print(medal_count_by_gender)
# Create the Boolean Series: sus
sus = (medals.Event_gender == 'W') & (medals.Gender == 'Men')
suspect = medals[sus]
print(suspect)
### idxmax() / idxmin()
# idxmax() return the row or column label where maximum value is located
# idxmax() return the row or column label where minimum value is located
# Given a categorical Series S, S.nunique() returns the number of distinct categories.
country_grouped =medals.groupby('NOC')
Nsports = country_grouped.Sport.nunique()
Nsports = Nsports.sort_values(ascending=False)
print(Nsports.head(15))
during_cold_war = (medals.Edition >= 1952) & (medals.Edition <=1988)
is_usa_urs = medals.NOC.isin(['USA','URS'])
cold_war_medals = medals.loc[during_cold_war & is_usa_urs]
country_grouped = cold_war_medals.groupby('NOC')
Nsports = country_grouped.Sport.nunique()
print(Nsports)
medals_won_by_country = medals.pivot_table(index='Edition', columns='NOC', values='Athlete', aggfunc='count')
cold_war_usa_urs_medals = medals_won_by_country.loc[1952:1988, ['USA','URS']]
most_medals = cold_war_usa_urs_medals.idxmax(axis='columns')
print(most_medals.value_counts())
# Ploting 1
usa = medals[medals.NOC == 'USA']
usa_medals_by_year = usa.groupby(['Edition', 'Medal'])['Athlete'].count()
usa_medals_by_year = usa_medals_by_year.unstack()
usa_medals_by_year.plot()
plt.show()
# Ploting 2
usa = medals[medals.NOC == 'USA']
usa_medals_by_year = usa.groupby(['Edition', 'Medal'])['Athlete'].count()
usa_medals_by_year = usa_medals_by_year.unstack(level='Medal')
usa_medals_by_year.plot.area()
plt.show()
# Ploting 3
medals.Medal = pd.Categorical(values = medals.Medal, categories=['Bronze', 'Silver', 'Gold'], ordered=True)
usa = medals[medals.NOC == 'USA']
usa_medals_by_year = usa.groupby(['Edition', 'Medal'])['Athlete'].count()
usa_medals_by_year = usa_medals_by_year.unstack(level='Medal')
usa_medals_by_year.plot.area()
plt.show()
|
9582adc414a0635f4b72e5a7ab9ef75e405ababe
|
chronosvv/algorithm
|
/4longestsubstring.py
| 1,433 | 4.09375 | 4 |
# 题目:
#
# Given a string, find the length of the longest substring without repeating characters.
#
# Examples:
# Given "abcabcbb", the answer is "abc", which the length is 3.
# Given "bbbbb", the answer is "b", with the length of 1.
# Given "pwwkew", the answer is "wke", with the length of 3.
# Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
# 思路:用到了python的find函数,找到字符出现在 子串的位置,
# 然后下一个起始点为本轮起始点+字串出现重复的位置的下一个
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:param s:str
:return: int
"""
if not s:
return 0
max_sub = "" #存放最大字符串
find_sub = "" #存放出现的字符串
end = 0
begin = 0
while end < len(s):
if find_sub.find(s[end]) < 0:#find_sub字符串里面不包含s[end]
find_sub += s[end]
if end - begin + 1 > len(max_sub):
max_sub = s[begin:end+1]
else:
sub_begin = find_sub.find(s[end])
begin += sub_begin+1 #重复字符的下一个开始
find_sub = s[begin:end+1]
end += 1
print(max_sub)
return len(max_sub)
s = Solution()
lens = s.lengthOfLongestSubstring("acjajdssi")
print(lens)
|
db94542c073c5085f14377f01330ecc31150214d
|
AlfredFranciss/C0804768_Week2_ClassEX
|
/revname.py
| 245 | 4.40625 | 4 |
# Function which accepts the user's first and last name and prints them in reverse
def getname():
fname = input('Enter your First Name:')
lname = input('Enter your Last Name:')
print(f'Reversed Name is {lname [::-1]} {fname[::-1]}')
|
454eefc85682af10b1d2baf564a8154b22c0c642
|
Gaffey911/Gaffey
|
/file_practice.py
| 1,412 | 3.640625 | 4 |
'''
1.B E:\test.txt
2.默认打开模式是 r 只读
3.二进制形式
4.dump()
5.load()
6.以二进制在末尾追加写入读取
7.不关闭会占用资源并且不会保存内容
8.tell()方法
'''
#9
filename=input('请输入文件名:')
print('请输入内容,【单独输入‘w’保存并退出】')
f=open(filename,'w')
while True:
filecontent=input()
if filecontent!='w':
f.write(filecontent)
else:
break
f.close()
#10
file=input('请输入要打开的文件:')
n=int(input('请输入需要显示几行:'))
f = open(file,'r+')
for i in f.readlines()[0:n] :
print(i)
#11
file=input('请输入要打开的文件:')
n1=int(input('请输入开始行数:'))
n2=int(input('请输入结束行数:'))
f = open(file,'r+')
for i in f.readlines()[n1-1:n2] :
print(i)
#12
file=input('请输入文件名:')
word1=input('请输入需要替换的单词或字符:')
word2=input('请输入新的单词或字符:')
counter=0
count=[]
f=open(file,'r')
for i in f:
for each in i:
if word1==each:
counter+=1
i=i.replace(word1,word2)
count.append(i)
print('文件',file,'中共有',counter,'个',word1,'您确定要把所有',word1,'替换成',word2,'吗?【yes or no】')
chose=input()
if chose=='yes':
f1=open(file,'w')
f1.writelines(count)
f1.close()
f.close()
else:
print('退出程序')
f.close()
|
a193ecb1135a2441d21801c51e621e88bb6e43b8
|
amoahisrael/Global-code-P
|
/week2file/fold.py
| 175 | 3.671875 | 4 |
#from function import even
#num=[2,6,8,12]
def is_even(x):
return x % 2 ==0;
numbers = [1,56,234,87,4,76,24,69,90,135]
a = (list(filter (is_even, numbers)))
print(a)
|
da04feddf1bfdfdb3bff24e6b94896e877e7842c
|
okkays/advent_2020
|
/twentyone/solve.py
| 1,415 | 3.5 | 4 |
import collections
import itertools
import re
inputmatcher = re.compile(r'^([\w\s]+)\(contains ([\w\s,]+)\)$')
def readinput(filename):
with open(filename, 'r') as f:
raw = [l.strip() for l in f.readlines()]
pairs = []
for line in raw:
match = inputmatcher.fullmatch(line)
ingredients = match[1].strip()
allergens = match[2].strip()
pairs.append((set(ingredients.split(' ')), set(allergens.split(', '))))
return pairs
def reduce(pairs):
reduced = {}
for ingredients, allergens in pairs:
for allergen in allergens:
if not reduced.get(allergen):
reduced[allergen] = set(ingredients)
else:
reduced[allergen] = reduced[allergen] & ingredients
return reduced
def solve(filename):
pairs = readinput(filename)
pairs.sort(key=lambda p: -len(p[1]))
all_ingredients = set.union(*[p[0] for p in pairs])
reduced = list(reduce(pairs).items())
solution = {}
while reduced:
reduced.sort(key=lambda p: len(p[1]))
next_reduced = []
allergen, ingredients = reduced.pop(0)
solution[allergen] = ingredients
for other_allergen, other_ingredients in reduced:
next_reduced.append((other_allergen, other_ingredients - ingredients))
reduced = next_reduced
solution = list(sorted(solution.items(), key=lambda i: i[0]))
solution = [s[1].pop() for s in solution]
print('solution', ','.join(solution))
solve('input.txt')
|
d9b646304d9dec4b64acdda810a08e27d315b470
|
liviode/my_python
|
/edu/list_filter.py
| 188 | 3.640625 | 4 |
my_list = [123, 'artus', 'zürich', 22.476]
print('my_list', my_list)
filtered_list = [e for e in my_list if e != 123]
print('...after filtering')
print(my_list)
print(filtered_list)
|
f36322a0c8096f236567f993ec77cc76d7d0a9b0
|
Fabaladibbasey/MITX_6.00.1
|
/longestSubstring
| 1,092 | 4.1875 | 4 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 4 23:48:24 2021
@author: suspect-0
"""
# Assume s is a string of lower case characters.
# Write a program that prints the longest substring of s in which the letters occur in
# alphabetical order. For example, if s = 'azcbobobegghakl', then your program should
# print
# Longest substring in alphabetical order is: beggh
# In the case of ties, print the first substring. For example, if s = 'abcbcd',
# then your program should print
# Longest substring in alphabetical order is: abc
s = 'azcbobobegghakl'
s = 'ntbexglzokiiwxetcy'
s = 'ktmlvqojdnlcchs'
# This loop doesnot work!
# for i in range(len(s) - 1):
# letter = s[i]
# nextLetter = s[i + 1]
# if(letter <= nextLetter):
# currentStr += letter
# print(currentStr)
# else:
# currentStr += letter
# temp = currentStr
# currentStr = ''
# if(len(longestSubStr) < len(temp)):
# longestSubStr = temp
# print(longestSubStr)
longestSubStr = ''
currentStr = ''
temp = ''
|
2bc80e66a5f6137243421a68686234a44ab2e882
|
MarkJParry/MyGMITwork
|
/Week03/absolute.py
| 257 | 4.125 | 4 |
#Filename: absolute.py
#Author: Mark Parry
#Created: 03/02/2021
#Purpose: Program to take in a number and give its absolute value
inNum = float(input("Please enter a negative number: "))
print("the absolute value of {} is: {}".format(inNum,abs(inNum)))
|
c705c14d336bbbfa8dde80dae09dc22726b9f90c
|
hafizadit/Muhammad-Hafiz-Aditya_I0320064_AbyanNaufal_Tugas5
|
/I0320064_Soal1_Tugas5.py
| 481 | 3.6875 | 4 |
# Header
print("")
print("="*50)
end = "Program Sapa"
endCenter = end.center(50)
print(endCenter)
print("="*50)
print("")
# Program
nama = input("Masukkan nama anda :")
LK = input("Masukkan jenis kelamin anda (l/p) :")
print("")
if LK == "l" or "L":
print("Selamat datang, Tuan",nama)
elif LK == "p" or "P":
print("Selamat datang, Nyonya",nama)
# Footer
print("")
print("="*50)
end = "Program Selesai"
endCenter = end.center(50)
print(endCenter)
print("="*50)
print("")
|
2438f745c3c93d677bec9767d491e319f6210c85
|
Everlone/ProjectEuler
|
/euler_001.py
| 770 | 4.03125 | 4 |
'''
euler_001.py
First problem of the Euler Project
------------------------------------------------------------------------------
If we list all the natural numbers below 10 that are multiples of 3 or 5, we
get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
------------------------------------------------------------------------------
Written by Stephen Outten 21 December 2017
'''
import numpy as np
# This is a comment
n = 1000
array3 = np.arange(0,n,3)
array5 = np.arange(0,n,5)
# answer = np.sum(np.arange(0,n,3)) + np.sum(np.arange(0,n,5)) - np.sum(np.arange(0,n,15))
answer = np.sum(np.unique(np.concatenate((array3,array5))))
print('The sum of all the multiples of 3 and 5 below %i is %i' % (n,answer))
|
d794a7444e45815af026bea3a9ce108cf3b430af
|
boreesych/SQLwebinar
|
/from_azure2python.py
| 425 | 3.53125 | 4 |
import psycopg2
conn = psycopg2.connect(
"dbname='' user='' host='' password=''"
)
cursor = conn.cursor()
cursor.execute("SELECT * FROM students")
# cursor.execute("SELECT id, nickname FROM students")
for i in cursor.fetchall():
print(i)
# [print(row) for row in cursor.fetchall()]
# for id, nickname in cursor.fetchall():
# print(f"id: {id}, Nick: {nickname}")
# conn.commit()
conn.close()
|
ddb05d8f840b293d8e621770bb566fbde22243e9
|
ataabi/pythonteste
|
/Desafios/ex013.py
| 234 | 3.671875 | 4 |
# Faça um algoritmo que leia o salario de um funcionario e mostre seu novo salario, com 15% de aumento.
s = float(input('Qual o salário do funcionario ? \n: '))
print(f'Com 15% de aumento o salário sera de R${(s+(s*0.15)):.2f} .')
|
15aa426bfefaac2d48d133607b94b53a135f904b
|
DAVIDnHANG/TL-PythonAllProject-CS
|
/LSC%--Data-structure/names/JoshuaNames.py
| 2,139 | 4.0625 | 4 |
"""
Binary search trees are a data structure that enforce an ordering over
the data they store. That ordering in turn makes it a lot more efficient
at searching for a particular piece of data in the tree.
This part of the project comprises two days:
1. Implement the methods `insert`, `contains`, `get_max`, and `for_each`
on the BSTNode class.
2. Implement the `in_order_print`, `bft_print`, and `dft_print` methods
on the BSTNode class.
"""
class BSTNode:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
# Insert the given value into the tree
def insert(self, value):
if value < self.value:
if self.left:
return self.left.insert(value)
else:
self.left = BSTNode(value)
else:
if self.right:
return self.right.insert(value)
else:
self.right = BSTNode(value)
# Return True if the tree contains the value
# False if it does not
def contains(self, target):
if self.value == target:
return self.value
elif target < self.value and self.left:
return self.left.contains(target)
elif target > self.value and self.right:
return self.right.contains(target)
# elif target < self.data and self.left
#the original runtime of this code was quadratic time.
import time
import sys
f = open('names_1.txt', 'r')
names_1 = f.read().split("\n") # List containing 10000 names
f.close()
f = open('names_2.txt', 'r')
names_2 = f.read().split("\n") # List containing 10000 names
f.close()
sys.path.append('./binary_search_tree')
start_time = time.time()
f = open('names_1.txt', 'r')
duplicates = [] # Return the list of duplicates in this data structure
bst = BSTNode('')
for name_1 in names_1:
bst.insert(name_1)
for name_2 in names_2:
if bst.contains(name_2):
duplicates.append(name_1)
end_time = time.time()
print (f"{len(duplicates)} duplicates:\n\n{', '.join(duplicates)}\n\n")
|
fa254d0f0ec78aa0df1e00c40e6fd979ac16a118
|
stldavids/03-Text-Adventure
|
/gameEngine.py
| 8,084 | 3.578125 | 4 |
#!/usr/bin/env python3
import sys, logging, os, json
version = (3,7)
assert sys.version_info >= version, "This script requires at least Python {0}.{1}".format(version[0],version[1])
logging.basicConfig(format='[%(filename)s:%(lineno)d] %(message)s', level=logging.INFO)
logger = logging.getLogger(__name__)
#Players need to Shower, Brush Teeth, Take Medicine, Wash Face, Do Makeup, Style Hair, and Get Dressed, in that order
# Game loop functions
def render(game,current,moves):
''' Displays the current room, moves '''
r = game['rooms']
c = r[current]
print('\n\nMoves: {moves}'.format(moves=moves))
print('\n\n{name}'.format(name=c['name']))
print(c['desc'])
if len(c['inventory'])>0:
print('You have done the following things:')
def getInput(game,current,verbs):
''' Asks the user for input and normalizes the inputted value. Returns a list of commands '''
toReturn = input('\nWhat would you like to do? ').strip().upper().split()
if (len(toReturn)):
#assume the first word is the verb
toReturn[0] = normalizeVerb(toReturn[0],verbs)
return toReturn
def update(selection,game,current,inventory):
''' Process the input and update the state of the world '''
s = list(selection)[0] #We assume the verb is the first thing typed\
if s == "":
print("\nSorry, I don't understand.")
return current
elif s == 'EXITS':
printExits(game,current)
return current
#Actions needed to complete game; genuinely couldn't get them to work in the json file, so they're here ¯\_(ツ)_/¯
elif current == "SHOWER" and s == "BATHE":
if len(inventory) == 0:
inventory.append("SHOWERED")
print("\nYou successfully TAKE a SHOWER\nNothing beats a shower after a night of too much drinking in a self-destructive streak!")
else:
print("\nYou already showered! No need to raise your water bill any higher than it is.")
elif current == "SINK" and s == "TEETH":
if len(inventory) == 1:
inventory.append("BRUSHED TEETH")
print("\nYou successfully BRUSH you TEETH\nYou already start to feel better.")
elif len(inventory) == 0:
print("\nYou know you can technically brush your teeth before showering, but it just feels weird.")
else:
print("\nYou already brushed your teeth. If your brush them too much, you'll end up getting cavities (weirdly enough).")
elif current == "SINK" and s == "MEDS":
if len(inventory) == 2:
inventory.append("TOOK MEDS")
print("You successfully TOOK your MEDS\n Take that, depression and anxiety! You throw in a tylenol for good measure.")
elif len(inventory) == 0:
print("\nUgh, you're too distracted by how gross you feel. Should probably shower first.")
elif len(inventory) == 1:
print("\nThe taste of your mouth is getting the better of you. Better take care of that.")
else:
print("\nYou already took your meds. They'll kick in soon.")
elif current == "SINK" and s == "FACE":
if len(inventory) == 3:
inventory.append("WASHED FACE")
print("You successfully WASHED your FACE\n Take that, oils and acne!")
elif len(inventory) == 0:
print("\nIf you wash your face before showering, all the moisturizer in your soap will get washed out. It's better to\n shower first.")
elif len(inventory) == 1:
print("\nYou've always been messy when brushing your teeth. Better do that first, then you can rinse off the paste\n from your mouth")
elif len(inventory) == 2:
print("\nIt's usually best to take your meds after brushing your teeth. \nThat way you don't have to wait for the water to cool back down to a drinking temperature.")
else:
print("\nYou already washed your face. Why would you wash out the moisturizer?")
elif current == "MIRROR" and s == "MAKEUP":
if len(inventory) == 4:
inventory.append("APPLIED MAKEUP")
print("You successfully APPLIED your MAKEUP\nHave to make sure the world doesn't know just how hard you\nwent last night.")
elif len(inventory) == 0:
print("\nYou really need to shower.")
elif len(inventory) == 1:
print("\nYou can't just skip brushing your teeth.")
elif len(inventory) == 2:
print("\nYou need to take your meds before you forget.")
elif len(inventory) == 3:
print("\nYou have to wash your face before putting on makeup.")
else:
print("\nYou have enough makeup on.")
elif current == "MIRROR" and s == "HAIR":
if len(inventory) == 5:
inventory.append("STYLED HAIR")
print("You successfully STYLED your HAIR\nIf your hair looks good, no one will know just how messy you really are!")
elif len(inventory) == 0:
print("\nYou're hair is too gross to style.'")
elif len(inventory) == 1:
print("\nYou should brush your teeth first.")
elif len(inventory) == 2:
print("\nYou need to take your meds before you forget.")
elif len(inventory) == 3:
print("\nYou have to wash your face first.")
elif len(inventory) == 4:
print("\nYou should do your makeup first, since your hair needs to be pulled back for that.")
else:
print("\nYour hair is styled enough.")
elif current == "OPEN" and s == "DRESS":
if len(inventory) == 6:
inventory.append("GOT DRESSED")
print("You successfully GOT DRESSED\nNow you are ready to face the day!")
current = 'END'
elif len(inventory) == 0:
print("\nUgh, you still smell like the bar from last night. Should probably take care of that.")
elif len(inventory) == 1:
print("\nYou should brush your teeth first.")
elif len(inventory) == 2:
print("\nYou need to take your meds before you forget.")
elif len(inventory) == 3:
print("\nYou have to wash your face first.")
elif len(inventory) == 4:
print("\nYou should do your makeup first, so you don't get it on your clothes")
elif len(inventory) == 5:
print("\nYou've made the mistake of doing you hair after getting dressed in the past, and ended up with hairspray all\nover your clothes.")
else:
for e in game['rooms'][current]['exits']:
if s == e['verb'] and e['target'] != 'NoExit':
return e['target']
return current
# Helper functions
def printExits(game,current):
e = ", ".join(str(x['verb']) for x in game['rooms'][current]['exits'])
print('\nYou can move to the following: {directions}'.format(directions = e))
def normalizeVerb(selection,verbs):
for v in verbs:
if selection == v['v']:
return v['map']
return ""
def end_game(winning,moves):
if winning:
print('You have won! Congratulations')
print('You finished in {moves} moves! Nicely done!'.format(moves=moves))
else:
print('Thanks for playing!')
print('You finished in {moves} moves. See you next time!'.format(moves=moves))
def main():
gameFile = 'game.json'
game = {}
with open(gameFile) as json_file:
game = json.load(json_file)
current = 'START'
win = ['END']
lose = []
moves = 0
inventory = []
while True:
render(game,current,moves)
selection = getInput(game,current,game['verbs'])
if selection[0] == 'QUIT':
end_game(False,moves)
break
current = update(selection,game,current,inventory)
if current in win:
end_game(True,moves)
break
if current in lose:
end_game(False,moves)
break
moves += 1
if __name__ == '__main__':
main()
|
37872c8564377735354d9c6a1f5d6783044205d3
|
jeffersonjpr/maratona
|
/codewars/python/Smallest unused ID.py
| 736 | 3.609375 | 4 |
# https://www.codewars.com/kata/55eea63119278d571d00006a
# referencia
# https://stackoverflow.com/questions/53513/how-do-i-check-if-a-list-is-empty
# https://stackoverflow.com/questions/3654830/why-are-there-no-and-operators-in-python
# https://www.geeksforgeeks.org/max-min-python/
# http://excript.com/python/operadores-in-not-in-python.html
# Minha Versao
def next_id(arr):
if not arr or min(arr) > 0:
return 0
x = min(arr)
for i in range(len(arr)):
x += 1
if x not in arr:
return x
#Versao mais elegante
def next_id(arr):
for i in range(len(arr) + 1):
if i not in arr:
return i
def next_id(arr):
x = 0
while x in arr:
x += 1
return x
|
e77812de3414766abf9ef1331a69ad9ee911ef8d
|
EmiCohenSoft/eCohenAdimra
|
/semana6/7ºEJ_ingresos_diarios_2020.py
| 3,965 | 3.609375 | 4 |
""" Cálculos sobre ingresos:
Se dispone de un reporte de ingreso diario del año 2020, en archivo de texto con formato CSV
(valores separados por coma), ver adjunto.
1. Cargar el paquete de reportes en una lista.
2. Calcular el promedio diario de ingresos del 1er semestre.
3. Calcular el promedio diario de ingresos del 2do semestre.
4. Calcular el promedio diario de ingresos de todo el año.
5. Calcular el % de días en el año, en los que se logró un ingreso mayor o igual a 8000.
6. Imprimir los 4 cálculos, y además el monto del día de mayor ingreso y el de menor ingreso. """
matIngDiario = [] #Inicializa o crea la lista vacía
ArchivoIngDiario = open("7ºEJ_ingresos_diarios_2020.txt", "r")
#Creamos el objeto o variable ArchivoIngDiario importando la información desde un archivo
#Abre el archivo de texto. La "r"determina que será para lectura,
#Si ponemos "w" podría escribir sobre el archivo
matIngDiario = ArchivoIngDiario.read().split(",")
#El comando read() nos permite leer el archivo,
#split(",") indica que las comas del archivo de texto separan lo valores de la lista
ArchivoIngDiario.close()
#print (matIngDiario) #Hasta aquí, los datos se importa como string.
print()
#Para convertirlos en enteres, utilizamos "for" con "enumerate", que crea un índice para cada ítem
# y en la linea siguiente, se convierte cada valor en entero
for indice , item in enumerate(matIngDiario):
matIngDiario [indice]= int(item)
""" if (indice<5): #Muestra solo los primeros 5 valores de la lista
print (item) """
print(matIngDiario [0:7]) #Muestra valores del índice 0 al 7, uno a contiuación de otro
print()
cantDatos = (len(matIngDiario)) #La función "len" devuelve el tamaño de una lista
cantDiaPriSemtre = int((cantDatos/2)+1)
cantDiaSegSemtre = int(cantDatos-cantDiaPriSemtre)
print ("La cantidad total de días es ",cantDatos)
print("La cantidad de días del primer semestre es ",cantDiaPriSemtre)
print("La cantidad de días del segundo semestre es ",cantDiaSegSemtre)
sumaPriSemtre = 0
sumaSegSemtre = 0
sumaAnual = 0
promPriSemtre = 0
promSegSemtre = 0
promAnual = 0
diasIngMayor = 0
for indice , item in enumerate(matIngDiario):
matIngDiario [indice]= int(item)
sumaAnual = sumaAnual + item
if (item>=8000):
diasIngMayor = diasIngMayor + 1
if (indice < cantDiaPriSemtre):
sumaPriSemtre = sumaPriSemtre + item
elif(indice >= cantDiaPriSemtre):
sumaSegSemtre = sumaSegSemtre + item
else:
if (indice < cantDiaPriSemtre):
sumaPriSemtre = sumaPriSemtre + item
elif(indice >= cantDiaPriSemtre):
sumaSegSemtre = sumaSegSemtre + item
relaDiasIngMayor = float(diasIngMayor/cantDatos)
promPriSemtre = int(sumaPriSemtre/(cantDiaPriSemtre))
promSegSemtre = int(sumaSegSemtre/cantDiaSegSemtre)
promAnual = int(sumaAnual/cantDatos)
print()
print("-------------------------------------------")
print(sumaPriSemtre, " ingresaron el primer semestre")
print(promPriSemtre," es el promedio de personas ingresadas durante los primeros",cantDiaPriSemtre," días")
print()
print(sumaSegSemtre, " ingresaron el segundo semestre")
print(promSegSemtre, "es el promedio de personas ingresadas durante el segundo semestre")
print()
print(sumaAnual, " ingresaron en todo el año")
print(promAnual, " es el promedio anual de ingresos")
print()
print("En ",diasIngMayor," días ingresaron mas de 8000 personas, lo que representa un ", "{:0.0%}".format(relaDiasIngMayor)," del total de días")
print("%0.3f"% (relaDiasIngMayor)) #imprime un número flotante de 3 decimales
print("{:0.3}%".format(relaDiasIngMayor)) #imprime un porcentaje de 3 decimales
print("{:0.2%}".format(relaDiasIngMayor)) #imprime un porcentaje de 2 decimales multiplicando x 100
print()
matIngDiario.sort(reverse=False)
print(matIngDiario[0]," es la menor cantidad ingresada")
print(matIngDiario[-1], " es la mayor cantidad ingresada")
print()
|
2521f72b09553909ebe0ad5a81abcadc63ba54b6
|
AdamZhouSE/pythonHomework
|
/Code/CodeRecords/2526/50263/263886.py
| 234 | 3.609375 | 4 |
str1 = input()
str2 = input()
if 'null' in str1 or 'null' in str2:
str1 = str1.replace(',null','')
str2 = str2.replace(',null','')
list1 = eval(str1)
list2 = eval(str2)
list3 = []
list3 = list1 + list2
print(sorted(list3))
|
122cb10128d81a4e89a7ed8f420c93e8ea69ddbe
|
albertyfwu/project_euler
|
/56.py
| 187 | 3.546875 | 4 |
max_digit_sum = 0
for a in range(2, 100):
for b in range(2, 100):
n = a**b
sum = 0
for c in str(n):
sum += int(c)
max_digit_sum = max(max_digit_sum, sum)
print max_digit_sum
|
927b58db1a7dad055906aa2cb0ec640adb3aa3bb
|
Morgassa/Code_Wars
|
/4 kyu/(4 kyu) Range Extraction.py
| 1,870 | 3.515625 | 4 |
def generator(args):
len_arsgs = len(args)
i = 0
while i < len_arsgs:
low = args[i]
# Enquanto o contador 'i' for um caracter menor que o tamanho da lista e
# o valor do argumento atual +1 for igual ao proximo.
# Soma-se 1 ao contador 'i'.
while i < len_arsgs-1 and args[i]+1 == args[i+1]:
i+=1
# Ao quebrar a sequencia numerica a variavel 'hi' passa a ser o ultimo numero
# da sequencia verificado.
hi = args[i]
# Se ouver algum numero entre o valor do 'hi' e do 'low' yield guarda apenas
# os dois valores posicionados nas extremidadas da sequancia numerica. O maior
# e o menor.
if hi - low >= 2:
yield (low, hi)
# Se os números forem apenas consecutivos mas são apenas dois, 'hi' e 'low' são
# quardados separadamente.
elif hi - low == 1:
yield (low,)
yield (hi,)
# Não havendo valor consecutivo, sendo assim não tem o porque
# separa-los em 'hi' e 'low'.
else:
yield (low,)
i+=1
def solution(ranges):
ddd = generator(ranges)
ls=''
count=0
for r in ddd:
count+=1
if len(r) == 2:
ls+=(''.join(('{}-{},'.format(r[0], r[1]))))
else:
ls+=(''.join(('{},'.format(r[0]))))
return (ls[:-1])
## CODEWARS RESOLUTION ##
## CODEWARS RESOLUTION ##
def solution(args):
out = []
started = end = args[0]
for n in args[1:] + [""]:
if n != end + 1:
if end == started:
out.append(str(started))
elif end == started + 1:
out.extend([str(started), str(end)])
else:
out.append(str(started) + "-" + str(end))
started = n
end = n
return ",".join(out)
|
afacfd880ad32ff86076130e0ffae15978c68654
|
galenwilkerson/Coursework
|
/Kaggle_Titanic_Machine_Learning_2016/kaggle_titanic_1.py
| 21,336 | 3.703125 | 4 |
'''
Basic Titanic Competition submission for kaggle
https://www.kaggle.com/c/titanic
Much of this comes originally from:
https://www.dataquest.io/mission/74/getting-started-with-kaggle
The point of this is to go through all of the steps from reading data to submitting to kaggle
Functions are written as generally as possible, so we don't care what the data set is,
as a step toward automation.
including:
read data
data summary
clean data
change non-numeric values to numeric
train (various models) on data using k-fold training sets
evaluate accuracy scores of results
submit
'''
import pandas as pd
import sys
# Import the linear regression classifier
from sklearn.linear_model import LinearRegression
# logistic regression classifier
from sklearn.linear_model import LogisticRegression
# Sklearn also has a helper that makes it easy to do cross validation
from sklearn.cross_validation import KFold
# helper to get scores from cross validation
from sklearn import cross_validation
import numpy as np
# random forests classifier
from sklearn.ensemble import RandomForestClassifier
import matplotlib.pyplot as plt
# import regular expressions
import re
# (python standard library)
import operator
# select K best features
from sklearn.feature_selection import SelectKBest, f_classif
# for gradient boosting
from sklearn.ensemble import GradientBoostingClassifier
# read in data using pandas
def readData(filename):
# read into dataframe
data = pd.read_csv(filename)
return data
# summarize data using pandas
def summarizeData(data):
# Print the first 5 rows of the dataframe.
print(data.head(5))
print(data.describe())
# fill in NA values
def cleanData(data):
data["Age"] = data["Age"].fillna(data["Age"].median())
data["Embarked"] = data["Embarked"].fillna("S")
data["Fare"] = data["Fare"].fillna(data["Fare"].median())
return data
# make non-numeric columns numerical
def makeNumeric(data):
# Find all the unique genders -- the column appears to contain only male and female.
#print(data["Sex"].unique())
# Replace all the occurences of male with the number 0.
data.loc[data["Sex"] == "male", "Sex"] = 0
data.loc[data["Sex"] == "female", "Sex"] = 1
# Embarked column
#print(data["Embarked"].unique())
data.loc[data["Embarked"] == "S", "Embarked"] = 0
data.loc[data["Embarked"] == "C", "Embarked"] = 1
data.loc[data["Embarked"] == "Q", "Embarked"] = 2
return data
# perform kFoldLinearRegression on data
# inputs: data, the ML algorithm, the predictors, K (num folds)
def kFoldTraining(data, inputAlgorithm, predictors, K):
# Initialize our algorithm class
alg = inputAlgorithm
# Generate cross validation folds for the data dataset. It return the row indices corresponding to train and test.
# We set random_state to ensure we get the same splits every time we run this.
kf = KFold(data.shape[0], n_folds=K, random_state=1)
predictions = []
for train, test in kf:
# The predictors we're using the train the algorithm. Note how we only take the rows in the train folds.
train_predictors = (data[predictors].iloc[train,:])
# The target we're using to train the algorithm.
train_target = data["Survived"].iloc[train]
# Training the algorithm using the predictors and target.
alg.fit(train_predictors, train_target)
# We can now make predictions on the test fold
test_predictions = alg.predict(data[predictors].iloc[test,:])
predictions.append(test_predictions)
return predictions
# evaluate the prediction accuracy against the true values
# enter the predictions trueValues, and threshold, return accuracy
# Note, this does almost the same as sklearn.cross_validation.cross_val_score, without the kFoldTraining
def evaluateAccuracy(predictions, trueValues, threshold):
# The predictions are in three separate numpy arrays. Concatenate them into one.
# We concatenate them on axis 0, as they only have one axis.
predictions = np.concatenate(predictions, axis=0)
# Map predictions to outcomes (only possible outcomes are 1 and 0)
predictions[predictions > threshold] = 1
predictions[predictions <= threshold] = 0
#print(predictions == titanic_train["Survived"])
#print(predictions[predictions == titanic_train["Survived"]])
#print(sum(predictions[predictions == titanic_train["Survived"]]))
# accuracy = sum(predictions[predictions == titanic_train["Survived"]]) / len(predictions)
accuracy = sum(predictions[predictions == trueValues]) / len(predictions)
return accuracy
# plot the performance of a learning algorithm by iterating over various parameters
# basically, this will try to create an N+1 dimensional surface, where N is the number of parameters, and the height is accuracy
#
# try to implement this generically for any number of parameters
# the user is responsible for inputting a good, runnable range of parameters
# inputs: the classification algorithm, the data, the true values to cross-validate,
# a list of parameters, the parameter ranges in tuples of (min, max),
# and the step size to iterate over the parameters
def plotPerformance(alg, data, params, paramRanges, paramStepSize):
#alg = RandomForestClassifier(random_state=1, n_estimators=10, min_samples_split=2, min_samples_leaf=1)
classificationAlgorithm = alg
# for each parameter, iterate through the paramRanges by paramStepSize
# the number of iterators = len(params)
for i in len(params):
# kfold cross validation
#kf = KFold(titanic.shape[0], n_folds=3, random_state=1)
# sklearn.cross_validation.cross_val_score(estimator, X, y=None, scoring=None, cv=None, n_jobs=1, verbose=0, fit_params=None, pre_dispatch='2*n_jobs')
scores = cross_validation.cross_val_score(alg, titanic_train[predictors], titanic_train["Survived"], cv=3)
# print(scores.mean())
meanScore = scores.mean()
return
# A function to get the title from a name.
def get_title(name):
# Use a regular expression to search for a title. Titles always consist of capital and lowercase letters, and end with a period.
title_search = re.search(' ([A-Za-z]+)\.', name)
# If the title exists, extract and return it.
if title_search:
return title_search.group(1)
return ""
# A function to get the family id given a row
# output: dictionary
family_id_mapping = {}
def get_family_id(row):
# Find the last name by splitting on a comma
last_name = row["Name"].split(",")[0]
# Create the family id
# this concatenates the first part ({0}) of the format() (last_name)
# with the second part ({1}) of the format() (row["FamilySize"])
family_id = "{0}{1}".format(last_name, row["FamilySize"])
# Look up the id in the mapping
if family_id not in family_id_mapping:
if len(family_id_mapping) == 0:
current_id = 1
else:
# Get the maximum id from the mapping and add one to it if we don't have an id
current_id = (max(family_id_mapping.items(), key=operator.itemgetter(1))[1] + 1)
family_id_mapping[family_id] = current_id
return family_id_mapping[family_id]
# plot scores vs. predictors
def plotScores(predictors, scores):
plt.bar(range(len(predictors)), scores)
plt.xticks(range(len(predictors)), predictors, rotation='vertical')
plt.show()
# input data, predictors, true values, and K, the number to select
# return the k best scores, where the scores are the log10(pvalues)
def getKBestScoresFromFeatures(data, trueValues, predictors, K):
# Perform feature selection
selector = SelectKBest(f_classif, K)
selector.fit(data,trueValues)
# Get the raw p-values for each feature, and transform from p-values into scores
scores = -np.log10(selector.pvalues_)
return scores
def main():
# # try to read first argument
# try:
# filename = sys.argv[1]
# except:
# #filename = "Data/train.csv"
# filename = "Data/test.csv"
###############################################
# run on training data
filename = "Data/train.csv"
# read into dataframe
titanic_train = readData(filename)
# print a summary
#summarizeData(titanic_train)
# clean the data, fix NA values, etc
titanic_train = cleanData(titanic_train)
# change non-numeric values to numeric (necessary?)
titanic_train = makeNumeric(titanic_train)
# The columns we'll use to predict the target
predictors = ["Pclass", "Sex", "Age", "SibSp", "Parch", "Fare", "Embarked"]
inputAlgorithm = LinearRegression()
numFolds = 3
###############################################
# get k-fold predictions using linear regression
print "linear regression"
predictions = kFoldTraining(titanic_train, inputAlgorithm, predictors, numFolds)
#print predictions
# evaluate accuracy
trueValues = titanic_train["Survived"]
threshold = 0.5
accuracy = evaluateAccuracy(predictions, trueValues, threshold)
print(accuracy)
print
###############################################
# now try logistic regression
print "logistic regression"
# set algorithm to logistic regression
inputAlgorithm = LogisticRegression(C = .3, random_state=1)
# Compute the accuracy score for all the cross validation folds.
scores = cross_validation.cross_val_score(inputAlgorithm, titanic_train[predictors], titanic_train["Survived"], cv=3)
# Take the mean of the scores (because we have one for each fold)
# print(scores)
print(scores.mean())
print
###############################################
# run on test data, make 1st submission
print "running on test data, generating submission"
filename = "Data/test.csv"
# read into dataframe
titanic_test = readData(filename)
# print a summary
#summarizeData(titanic_test)
# clean the data, fix NA values, etc
titanic_test = cleanData(titanic_test)
# change non-numeric values to numeric (necessary?)
titanic_test = makeNumeric(titanic_test)
# Initialize the algorithm class
alg = LogisticRegression(random_state=1)
# Train the algorithm using all the training data
alg.fit(titanic_train[predictors], titanic_train["Survived"])
# Make predictions using the test set.
predictions = alg.predict(titanic_test[predictors])
# Create a new dataframe with only the columns Kaggle wants from the dataset.
submission = pd.DataFrame({
"PassengerId": titanic_test["PassengerId"],
"Survived": predictions
})
#print(submission)
submission.to_csv("kaggle_titanic_submission_1.csv", index=False)
print
###############################################
# improve submission using random forests
print "random forests 1"
predictors = ["Pclass", "Sex", "Age", "SibSp", "Parch", "Fare", "Embarked"]
# Initialize our algorithm with the default paramters
# random_state is for seeding the randomizer, for reproducability
# n_estimators is the number of trees we want to make
# min_samples_split is the minimum number of rows we need to make a split
# min_samples_leaf is the minimum number of samples we can have at the place where a tree branch ends (the bottom points of the tree)
alg = RandomForestClassifier(random_state=1, n_estimators=10, min_samples_split=2, min_samples_leaf=1)
# kfold cross validation
#kf = KFold(titanic.shape[0], n_folds=3, random_state=1)
# sklearn.cross_validation.cross_val_score(estimator, X, y=None, scoring=None, cv=None, n_jobs=1, verbose=0, fit_params=None, pre_dispatch='2*n_jobs')
scores = cross_validation.cross_val_score(alg, titanic_train[predictors], titanic_train["Survived"], cv=3)
print(scores.mean())
print
###############################################
# try again using random forests, with more trees
print "random forests 2"
alg = RandomForestClassifier(random_state=1, n_estimators=150, min_samples_split=4, min_samples_leaf=2)
scores = cross_validation.cross_val_score(alg, titanic_train[predictors], titanic_train["Survived"], cv=3)
print(scores.mean())
print
###############################################
#
# Generating a familysize column
print "creating new features:"
print "FamilySize"
print
titanic_train["FamilySize"] = titanic_train["SibSp"] + titanic_train["Parch"]
print "NameLength"
print
# The .apply method generates a new series
titanic_train["NameLength"] = titanic_train["Name"].apply(lambda x: len(x))
###############################################
#
# Get all the titles and print how often each one occurs.
print "Title"
print
titles = titanic_train["Name"].apply(get_title)
#print(pd.value_counts(titles))
# Map each title to an integer. Some titles are very rare, and are compressed into the same codes as other titles.
title_mapping = {"Mr": 1, "Miss": 2, "Mrs": 3, "Master": 4, "Dr": 5, "Rev": 6, "Major": 7, "Col": 7, "Mlle": 8, "Mme": 8, "Don": 9, "Lady": 10, "Countess": 10, "Jonkheer": 10, "Sir": 9, "Capt": 7, "Ms": 2}
for k,v in title_mapping.items():
titles[titles == k] = v
# Verify that we converted everything.
#print(pd.value_counts(titles))
# Add in the title column.
titanic_train["Title"] = titles
###############################################
#
# Get the family ids with the apply method
print "FamilyId"
print
# dictionary for results
#family_id_mapping = {}
# apply to each row, passing in the family_id_mapping dictionary as a parameter
family_ids = titanic_train.apply(get_family_id, axis=1)
# There are a lot of family ids, so we'll compress all of the families under 3 members into one code.
family_ids[titanic_train["FamilySize"] < 3] = -1
# Print the count of each unique id.
#print(pd.value_counts(family_ids))
titanic_train["FamilyId"] = family_ids
###############################################
#
print "Get K best features"
print
predictors = ["Pclass", "Sex", "Age", "SibSp", "Parch", "Fare", "Embarked", "FamilySize", "Title", "FamilyId"]
# Perform feature selection and get the k best scores
K = 5
scores = getKBestScoresFromFeatures(titanic_train[predictors], titanic_train["Survived"], predictors, K)
# Plot the scores. See how "Pclass", "Sex", "Title", and "Fare" are the best?
plotScores(predictors, scores)
# Pick only the four best features.
predictors = ["Pclass", "Sex", "Fare", "Title"]
alg = RandomForestClassifier(random_state=1, n_estimators=150, min_samples_split=8, min_samples_leaf=4)
scores = cross_validation.cross_val_score(alg, titanic_train[predictors], titanic_train["Survived"], cv=3)
print(scores.mean())
print
###############################################
#
print "Boosting and Ensembling"
print
# The algorithms we want to ensemble.
# We're using the more linear predictors for the logistic regression, and everything with the gradient boosting classifier.
algorithms = [
[GradientBoostingClassifier(random_state=1, n_estimators=25, max_depth=3), ["Pclass", "Sex", "Age", "Fare", "Embarked", "FamilySize", "Title", "FamilyId"]],
[LogisticRegression(random_state=1), ["Pclass", "Sex", "Fare", "FamilySize", "Title", "Age", "Embarked"]]#,
#[RandomForestClassifier(random_state=1, n_estimators=150, min_samples_split=8, min_samples_leaf=4), ["Pclass", "Sex", "Fare", "Title"]]
]
# Initialize the cross validation folds
kf = KFold(titanic_train.shape[0], n_folds=3, random_state=1)
predictions = []
for train, test in kf:
train_target = titanic_train["Survived"].iloc[train]
full_test_predictions = []
# Make predictions for each algorithm on each fold
for alg, predictors in algorithms:
# Fit the algorithm on the training data.
alg.fit(titanic_train[predictors].iloc[train,:], train_target)
# Select and predict on the test fold.
# The .astype(float) is necessary to convert the dataframe to all floats and avoid an sklearn error.
test_predictions = alg.predict_proba(titanic_train[predictors].iloc[test,:].astype(float))[:,1]
full_test_predictions.append(test_predictions)
# Use a simple ensembling scheme -- just average the predictions to get the final classification.
test_predictions = (full_test_predictions[0] + full_test_predictions[1]) / 2
# Any value over .5 is assumed to be a 1 prediction, and below .5 is a 0 prediction.
test_predictions[test_predictions <= .5] = 0
test_predictions[test_predictions > .5] = 1
predictions.append(test_predictions)
# Put all the predictions together into one array.
predictions = np.concatenate(predictions, axis=0)
# Compute accuracy by comparing to the training data.
accuracy = sum(predictions[predictions == titanic_train["Survived"]]) / len(predictions)
print(accuracy)
print
# titanic_train.to_csv("Data/new_titanic_train.csv")
###############################################
#
print "Working on test set"
print
# First, we'll add titles to the test set.
titles = titanic_test["Name"].apply(get_title)
# We're adding the Dona title to the mapping, because it's in the test set, but not the training set
title_mapping = {"Mr": 1, "Miss": 2, "Mrs": 3, "Master": 4, "Dr": 5, "Rev": 6, "Major": 7, "Col": 7, "Mlle": 8, "Mme": 8, "Don": 9, "Lady": 10, "Countess": 10, "Jonkheer": 10, "Sir": 9, "Capt": 7, "Ms": 2, "Dona": 10}
for k,v in title_mapping.items():
titles[titles == k] = v
titanic_test["Title"] = titles
# Check the counts of each unique title.
print(pd.value_counts(titanic_test["Title"]))
# Now, we add the family size column.
titanic_test["FamilySize"] = titanic_test["SibSp"] + titanic_test["Parch"]
# Now we can add family ids.
# We'll use the same ids that we did earlier.
#print(family_id_mapping)
family_ids = titanic_test.apply(get_family_id, axis=1)
family_ids[titanic_test["FamilySize"] < 3] = -1
titanic_test["FamilyId"] = family_ids
# add Namelength
titanic_test["NameLength"] = titanic_test["Name"].apply(lambda x: len(x))
###############################################
#
print "predicting on test set"
print
predictors = ["Pclass", "Sex", "Age", "Fare", "Embarked", "FamilySize", "Title", "FamilyId"]
algorithms = [
[GradientBoostingClassifier(random_state=1, n_estimators=25, max_depth=3), predictors],
[LogisticRegression(random_state=1), ["Pclass", "Sex", "Fare", "FamilySize", "Title", "Age", "Embarked"]]
]
full_predictions = []
for alg, predictors in algorithms:
# Fit the algorithm using the full training data.
alg.fit(titanic_train[predictors], titanic_train["Survived"])
# Predict using the test dataset. We have to convert all the columns to floats to avoid an error.
predictions = alg.predict_proba(titanic_test[predictors].astype(float))[:,1]
full_predictions.append(predictions)
# The gradient boosting classifier generates better predictions, so we weight it higher.
predictions = (full_predictions[0] * 3 + full_predictions[1]) / 4
predictions[predictions <= .5] = 0
predictions[predictions > .5] = 1
predictions = predictions.astype(int)
# Create a new dataframe with only the columns Kaggle wants from the dataset.
submission = pd.DataFrame({
"PassengerId": titanic_test["PassengerId"],
"Survived": predictions
})
#print(submission)
submission.to_csv("kaggle_titanic_submission_2.csv", index=False)
# Try using features related to the cabins.
# See if any family size features might help -- do the number of women in a family make the whole family more likely to survive?
# Does the national origin of the passenger's name have anything to do with survival?
#
#There's also a lot more we can do on the algorithm side:
#
# Try the random forest classifier in the ensemble.
# A support vector machine might work well with this data.
# We could try neural networks.
# Boosting with a different base classifier might work better.
#
#And with ensembling methods:
#
# Could majority voting be a better ensembling method than averaging probabilities?
if __name__ == "__main__":
main()
|
94d62711656f57424cb987fc879c9b0db3335b81
|
mike-jolliffe/Learning
|
/PDX_Code_Guild/DarkRealm/Creature.py
| 4,698 | 3.859375 | 4 |
from Room import *
class Creature(object):
'''Used for creating a creature, giving it stats, and making it fight'''
def __init__(self, name, health, weapon, location):
self.name = name
self.health = health
self.weapon = weapon
self.location = location
def move(self, dir, Room):
'''Given a direction tuple, updates creature object's location on the board'''
move_dict = {"n": (1,0), "s": (-1, 0), "e": (0, 1), "w": (0, -1)}
if dir in move_dict:
location_check = tuple(x + y for x, y in zip(self.location, move_dict[dir]))
if location_check[0] in range(Room.size[0]) and location_check[1] in range(Room.size[1]):
self.location = tuple(x + y for x, y in zip(self.location, move_dict[dir]))
return self.location
class Hero(Creature):
'''Player Character that modifies Creature class'''
def __init__(self, name, health, weapon, location, armor, inventory):
Creature.__init__(self, name, health, weapon, location)
self.armor = armor
self.inventory = inventory
def attacked(self, creature):
'''Makes creature object attack Hero object'''
damage = random.choice([0, 1, 1, 1, 1, 2, 3, 4])
print(
f"The {creature.name} attacks {self.name}, causing {damage} damage.")
self.health -= damage
def fight(self, creature):
print(f"You've encountered a {creature.name}!!")
print(f'''-------- {creature.name.upper()} STATS --------
Health: {creature.health}
Weapon: {creature.weapon.description}
Damage: {creature.weapon.damage}''')
while creature.health > 0 and self.health > 0:
attack = input("1 -- Stab \n"
"2 -- Slash \n"
"3 -- Run Away ")
if attack == '3':
print("You escaped!")
break
elif attack == '1':
points = random.choice([2,2,2,3,3,4])
creature.health -= points
print(f"Your attack did {points} damage!")
elif attack == '2':
points = random.choice([0,0,0,5,5,8])
creature.health -= points
print(f"Your attack did {points} damage!")
self.attacked(creature)
if creature.health <= 0:
print(f"You've defeated the vicious {creature.name}")
# Defeat is True, so creature will be removed from board
return True
elif hero.health <= 0:
print(f"{self.name} has perished in the Dark Realm!")
exit()
else:
# Defeat is False, creature will remain
return False
def get_inventory(self):
'''Returns the hero's current inventory'''
print(f"Your Current Inventory:")
inventory = []
for item in self.inventory:
inventory.append(f"{item}: {self.inventory[item]}")
return inventory
def use_item(self, item, room):
'''if item is a weapon, modifies hero's weapon. if item is potion, modifies hero health. If item is journal
tells hero a story.'''
if item == '+1_Potion':
self.health += 1
self.inventory[item] -= 1
elif item == 'Broadsword':
self.weapon = Room.item_dict['Broadsword']
else:
print(self.read_journal(room))
self.inventory[item] -= 1
def read_journal(self, room):
'''Reads a different page from a journal depending on the room hero finds it in.'''
journal_room = {1: f'''I was walking through the forest collecting herbs for my sick wife when
I fell into this godforsaken place through a hole in the ground. I think
I will never see my family again, and there is something large moving nearby''',
2: f'''I found a small pool of dirty water, and drank from it
without regard for my health, such was my thirst. I cannot
find an exit to this dark realm where the sun never shines.''',
3: f'''Something terrible hunts me in the darkness. I can hear its heavy breathing and a
scrabbling as it moves about the room in search of me.''',
4: f'''I grow to weak to stay away from the creature in this room.
I now sit against the wall as it grows closer.
It won't be too long before '''
}
return journal_room[room]
|
52a8a100a21eafae3c521ad83b64e6b2de36f9ea
|
incidunt/py.standard.lib.practice
|
/re_simple_match.py
| 481 | 3.609375 | 4 |
import re
pattern = 'this'
text = 'does this text match the pattern ?'
match = re.search(pattern, text)
s = match.start()
e = match.end()
print 'found "%s"\nin "%s"\nfrom %d to %d ("%s")' % \
(match.re.pattern, match.string, s, e, text[s:e])
regexes = [ re.compile(p)
for p in [ 'this', 'that' ]
]
print regexes
print 'text: %r\n' % text
for regex in regexes:
print 'seeking "%s" ->' % regex.pattern,
if regex.search(text):
print 'match!'
else:
print 'no match'
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.