blob_id
stringlengths 40
40
| repo_name
stringlengths 6
108
| path
stringlengths 3
244
| length_bytes
int64 36
870k
| score
float64 3.5
5.16
| int_score
int64 4
5
| text
stringlengths 36
870k
|
---|---|---|---|---|---|---|
d3218f0926f505c81450576b0abc5103e854a310 | iamkroot/misc-scripts | /bill-split/bill_split.py | 9,085 | 4.03125 | 4 | """
This is a simple script to split bill expenses among various people.
Its main inputs are
1. A TSV file of Bill with columns- quantity,name,price. Usually OCR'd from some service
The first line of the bill should look like "!paid: 1234.00"
This will be used to account for any taxes/discounts in the final paid amount.
The price column of the items should therefore be the ORIGINAL price (before taxes.)
2. A description of the people who consumed each item in the bill. Sample-
# drinks
lemonade: Killua, Gon
Rose punch: Leorio x2 (leorio had two servings)
Tea: Kurapika
# starters: @everyone
nachos
fries
(the above two items will be split across all the people named here)
# main course
pizza: -Gon, Ging x3 (Gon didn't eat it, Ging had thrice as much as others)
pasta: everyone
fried rice: -Kurapika (everyone except Kurapika ate this)
The names of items in the description should closely match the names in the bill.
Final output will be each person's share to the total amount in the bill.
"""
import csv
import re
from collections import Counter, defaultdict
from csv import DictReader
from dataclasses import dataclass
from difflib import get_close_matches
from fractions import Fraction
from pathlib import Path
from pprint import pprint
from typing import Iterable
bill_path = Path("./bill.txt")
expenses_data = Path("./expenses.txt").read_text()
@dataclass
class BillItem:
name: str
price: Fraction
quantity: int = 1
def scale_price(self, multiplier: Fraction):
return BillItem(self.name, self.price * multiplier, self.quantity)
def parse_bill(path: Path):
bill_data = path.read_text()
lines = bill_data.splitlines()
# first parse the !paid directive
assert (
lines[0].strip().startswith("!paid")
), "First line should be paid amount directive. Eg: '!paid: 1234.00'"
total_paid = Fraction(lines[0].split(":")[1].strip())
# now parse the item lines
bill_data2 = DictReader(
[line for line in lines if line.strip() and not line.startswith("!")],
fieldnames=["quantity", "name", "price"],
dialect=csv.excel_tab,
)
items = [
BillItem(r['name'], Fraction(r['price'].replace(',', '')), int(r['quantity']))
for r in bill_data2
]
# adjust the prices based on actual amount paid
item_sum = sum(item.price for item in items)
price_mult = total_paid / item_sum
return [item.scale_price(price_mult) for item in items]
EVERYONE_NAME = "@everyone"
MULT_PAT = re.compile(r'(?P<name>.*?)\s+x(?P<mult>\d+)$')
@dataclass
class Person:
name: str
negate: bool = False
multiplier: int = 1
@staticmethod
def from_names(names: Iterable[str]):
return [Person(name) for name in names]
def expand_alias(self, names: set[str]):
return [Person(name, self.negate, self.multiplier) for name in names]
EVERYONE = Person(EVERYONE_NAME)
def parse_people(names_str: str) -> tuple[list[Person], list[Person]]:
people: list[Person] = []
aliases: list[Person] = []
for person in names_str.strip(", ").split(","):
person = person.strip()
if person == EVERYONE_NAME:
aliases.append(EVERYONE)
continue
neg = False
if person.startswith("-"):
neg = True
person = person.lstrip("-").lstrip()
collection = aliases if '@' in person else people
if match := MULT_PAT.match(person):
collection.append(Person(match['name'], neg, int(match['mult'])))
else:
collection.append(Person(person, neg))
return people, aliases
def parse_expenses(data: str):
cat_people = None
cat_aliases = None
aliases = defaultdict(set)
items: dict[str, list[Person]] = {}
for line in data.splitlines():
if not line:
continue
if line.startswith('@'):
# parsing a group alias
split = line.split(":")
alias = split[0].strip()
persons, parsed_aliases = parse_people(split[1].strip())
aliases[alias].update(name.name for name in persons)
# we will have another pass to resolve all aliases
# for now, we don't allow alias negations, multipliers
assert not any(a.negate or a.multiplier != 1 for a in parsed_aliases)
aliases[alias].update(a.name for a in parsed_aliases)
continue
if line.startswith("#"):
# new category
split = line.split(":")
if len(split) > 1:
# names of people
cat_people, cat_aliases = parse_people(split[1].strip())
aliases[EVERYONE_NAME].update(name.name for name in cat_people)
else:
# reset the cat_people
cat_people = None
cat_aliases = None
continue
# now at a food line
split = line.split(":")
item_name = split[0].strip()
if len(split) == 1:
assert (
cat_people is not None
and cat_aliases is not None
and (cat_people or cat_aliases)
), f"no category people/aliases defined for food item {line}"
cur_all = cat_people + cat_aliases
else:
cur_people, cur_aliases = parse_people(split[1].strip())
aliases[EVERYONE_NAME].update(name.name for name in cur_people)
cur_all = cur_people + cur_aliases
items[item_name] = cur_all
aliases = resolve_aliases(aliases)
return finalize_names(items, aliases)
def resolve_aliases(aliases: dict[str, set[str]]):
"""Expand all aliases recursively till they only contain names.
Plms don't give cyclic.
"""
if all(all('@' not in name for name in v) for v in aliases.values()):
# Done!
return aliases
new_aliases = {}
for name, people in aliases.items():
new_people = people.copy()
for alias in [n for n in people if '@' in n]:
new_people.remove(alias)
new_people.update(aliases[alias])
new_aliases[name] = new_people
return resolve_aliases(new_aliases)
def finalize_names(items: dict[str, list[Person]], aliases: dict[str, set[str]]):
# do a second pass to handle negations and "@everyone"
# our final return value will only have the names and their multipliers
final_items: dict[str, Counter] = {}
for item, names in items.copy().items():
final_names: Counter[str] = Counter()
removed_names = Counter()
if any(name.negate for name in names) and not any(
('@' in name.name) for name in names
):
# if there are negations, and no alias has been provided,
# need to add EVERYONE implicitly. the negations will be removed later
final_names.update(aliases[EVERYONE_NAME])
# first, expand all the aliases
expanded_names = []
for person in names:
if '@' in person.name:
people = aliases[person.name]
expanded_names.extend(person.expand_alias(people))
else:
expanded_names.append(person)
for person in expanded_names:
if person.negate:
removed_names[person.name] += person.multiplier
else:
final_names[person.name] += person.multiplier
final_names -= removed_names
assert not any(
name.startswith("@") for name in final_names
), "found alias in final_names"
assert all(
count >= 0 for count in final_names.values()
), "got negative contribution"
final_items[item] = final_names
return final_items
def is_sampler(name):
return name.lower().startswith("sampler")
def assign_shares(items: dict[str, Counter[str]], bill: list[BillItem]):
samplers = [name for name in items.keys() if is_sampler(name)]
shares = defaultdict(Fraction)
details = defaultdict(dict)
for bill_item in bill:
candidates = items.keys()
if is_sampler(bill_item.name):
candidates = samplers
matches = get_close_matches(bill_item.name, candidates, n=1, cutoff=0.3)
assert matches, f"no match for {bill_item} in {', '.join(candidates)}"
people = items[matches[0]]
per_person = bill_item.price / Fraction(people.total())
for person, mult in people.items():
share = per_person * Fraction(mult)
shares[person] += share
details[person][bill_item.name] = share
print("total", float(sum(shares.values())))
pprint({name: round(float(share), 2) for name, share in shares.items()})
pprint(
dict(
{
p: {n: round(float(v), 2) for n, v in items.items()}
for p, items in details.items()
}
)
)
bill = parse_bill(bill_path)
items = parse_expenses(expenses_data)
assign_shares(items, bill)
|
e2b94c6772f690650a6f9683b19cce8b9509a01d | Index197511/AtCoder_with_Python | /Kyou45.py | 138 | 3.671875 | 4 | q = int(input())
for i in range(q):
tmp = input()
if tmp == "2":
else:
tmp = tmp.split()
functnion
|
f73a73744f8ec488c89d2731ce487c008bb28859 | subbuinti/python_practice | /functions/atmpinvaidation.py | 511 | 3.8125 | 4 | def validate_atm_pin_code(pin):
# Complete this function
is_valid = True
is_having_four_or_six_char = (len(pin) == 4) or (len(pin) == 6)
if is_having_four_or_six_char:
is_all_digits = pin.isdigit()
if not is_all_digits:
is_valid = False
else:
is_valid =False
if is_valid:
print("Valid PIN Code")
else:
print("Invalid PIN Code")
pin = input()
# Call the validate_atm_pin_code function
validate_atm_pin_code(pin)
|
81f35419460f1a495cdab5022c474a0a35d26087 | byblivro/meep | /meeplib.py | 6,046 | 3.546875 | 4 | import pickle
"""
meeplib - A simple message board back-end implementation.
Functions and classes:
* u = User(username, password) - creates & saves a User object. u.id
is a guaranteed unique integer reference.
* m = Message(title, post, author) - creates & saves a Message object.
'author' must be a User object. 'm.id' guaranteed unique integer.
* get_all_messages() - returns a list of all Message objects.
* get_all_users() - returns a list of all User objects.
* delete_message(m) - deletes Message object 'm' from internal lists.
* delete_user(u) - deletes User object 'u' from internal lists.
* get_user(username) - retrieves User object for user 'username'.
* get_message(msg_id) - retrieves Message object for message with id msg_id.
"""
__all__ = ['Message', 'get_all_messages', 'get_message', 'delete_message',
'User', 'set_current_user', 'get_current_user', 'get_user',
'get_all_users', 'delete_user', 'is_user']
###
# internal data structures & functions; please don't access these
# directly from outside the module. Note, I'm not responsible for
# what happens to you if you do access them directly. CTB
# a dictionary, storing all messages by a (unique, int) ID -> Message object.
_messages = {}
# a dictionary, storing all replies by unique ID and Message ID
_replies = {}
def _get_next_message_id():
if _messages:
return max(_messages.keys()) + 1
return 0
def _get_next_reply_id():
if _replies:
return max(_replies.keys()) + 1
return 0
# a dictionary, storing all users by a (unique, int) ID -> User object.
_user_ids = {}
# a dictionary, storing all users by username
_users = {}
#a string that holds the username of the current logged in user
_current_user = ''
def _get_next_user_id():
if _users:
return max(_user_ids.keys()) + 1
return 0
def _reset():
"""
Clean out all persistent data structures, for testing purposes.
"""
global _messages, _users, _user_ids, _replies, current_user
_messages = {}
_users = {}
_user_ids = {}
_replies = {}
_current_user = ''
###
class Message(object):
"""
Simple "Message" object, containing title/post/rank/author.
'author' must be an object of type 'User'.
"""
def __init__(self, title, post, author):
self.title = title
self.post = post
##self.rank = rank
assert isinstance(author, User)
self.author = author
self._save_message()
_saveMeep()
def _save_message(self):
self.id = _get_next_message_id()
# register this new message with the messages list:
_messages[self.id] = self
_saveMeep()
def get_all_messages(sort_by='id'):
return _messages.values()
def get_message(id):
return _messages[id]
## Disable Message Ranking
'''
def inc_msg_rank(msg):
_messages[msg.id].rank += 1
_saveMeep()
def dec_msg_rank(msg):
_messages[msg.id].rank -= 1
_saveMeep()
'''
def delete_message(msg):
assert isinstance(msg, Message)
del _messages[msg.id]
_saveMeep()
class Reply(object):
"""
Simple "Reply" object, containing Post ID number/reply/author.
'author' must be an object of type 'User'.
"""
def __init__(self, id_num, reply, author):
self.id_num = id_num
self.reply = reply
##self.rank = rank
assert isinstance(author, User)
self.author = author
self._save_reply()
_saveMeep()
def _save_reply(self):
self.id = _get_next_reply_id()
print id
# register this new message with the messages list:
_replies[self.id] = self
_saveMeep()
def get_all_replies(sort_by='id'):
return _replies.values()
def get_reply(id):
return _replies[id]
## Disable reply ranking
'''
def inc_reply_rank(reply):
_replies[reply.id].rank += 1
_saveMeep()
def dec_reply_rank(reply):
_replies[reply.id].rank -= 1
_saveMeep()
'''
def delete_reply(reply):
assert isinstance(reply, Reply)
del _replies[reply.id]
_saveMeep()
###
class User(object):
def __init__(self, username, password):
self.username = username
self.password = password
self._save_user()
def __cmp__(self, other):
if (other.username != self.username or other.password != self.password):
return -1
else:
return 0
def _save_user(self):
self.id = _get_next_user_id()
_user_ids[self.id] = self
_users[self.username] = self
_saveMeep()
def set_current_user(username):
print "----"
print username
global _current_user
_current_user = username
print _current_user
print "-----"
_saveMeep()
def get_current_user():
print "xxxx"
print _current_user
print "xxxx"
return _current_user
_saveMeep()
def get_user(username):
return _users.get(username) # return None if no such user
def get_all_users():
return _users.values()
def delete_user(user):
del _users[user.username]
del _user_ids[user.id]
_saveMeep()
def is_user(username, password):
try:
thisUser = get_user(username)
#print 'success1'
except NameError:
thisUser = None
#print 'fail1'
#print thisUser.password
#print password
if thisUser is not None:
if str(thisUser.password) == str(password):
#print "true"
return True
#print "false1"
else:
#print "false2"
return False
_saveMeep()
def _saveMeep():
obj = (_messages, _replies, _users, _user_ids, _current_user)
filename = "meep.pickle"
fp = open(filename, "w")
pickle.dump(obj, fp)
fp.close()
def _openMeep():
global _messages, _replies, _users, _user_ids, _current_user
fp = open("meep.pickle", "r")
obj = pickle.load(fp)
(_messages, _replies, _users, user_ids, _current_user) = obj
fp.close() |
4ab4c45c2dce0f816c22a2fa54901dcac8fbf987 | cy-arduino/leetcode | /37. Sudoku Solver.py | 2,021 | 3.75 | 4 | digit=['1','2','3','4','5','6','7','8','9']
def recursive(board: 'List[List[str]]') -> 'bool':
for row in range(9):
for col in range(9):
if board[row][col]=='.':
for i in digit:
#check same row
if i in board[row]:
#invalid, check netxt i
continue
#check same column
invalid=False
for j in range(9):
if board[j][col] == i:
#invalid, break
invalid=True
break
if invalid:
#invalid, check netxt i
continue
#check block
invalid=False
for tmp_row in range(row//3*3, row//3*3+3):
for tmp_col in range(col//3*3,col//3*3+3):
if board[tmp_row][tmp_col] == i:
invalid=True
break
if invalid:
break
if invalid:
continue
#found a suitable i, try it
board[row][col]=i
ret = recursive(board)
if ret:
return True;
else:
#failed, restore
board[row][col]='.'
continue
# no suitable i
return False
return True
class Solution:
def solveSudoku(self, board: 'List[List[str]]') -> 'None':
"""
Do not return anything, modify board in-place instead.
"""
print('ret=', recursive(board))
|
a13cd74fbfd9331566d1ba454482a743ad1e74dd | YiFeiZhang2/HackerRank | /python/regex_and_parsing/sub.py | 219 | 3.765625 | 4 | #!/usr/local/bin/python3
import re
for _ in range(int(input())):
#ptrn = re.compile(r"\s([&]|[|]){2}\s")
print(re.sub(r"(?<=\s)([&]{2}|[|]{2})(?=\s)", lambda x: "and" if x.group() == '&&' else "or", input()))
|
927aefdc1411a813c1fae0a821b7a8d8e323c1f5 | ieaiea/studyRepo | /Python/Python/Basic/chap_04/def01.py | 587 | 4.15625 | 4 | # 기본함수
def helloDef():
print('hello Def!!')
helloDef() # hello Def!!
# return
num = 5
num2 = 10
def add(a, b):
return a + b
print(add(num, num2)) # 15
# 함수안에 함수선언
def outter():
print('outter')
def inner():
print('inner')
inner()
outter()
# *args
def add(*args):
result = 0
for i in args:
result += i
return result
print(add(1, 2, 3, 4, 5)) # 15
# 타입헌팅
def loopStr(word:str, num:int) -> str :
return word * num
print(loopStr('짱구', 3))
# 람다
add = lambda x : x + 1
print(add(10)) # 11 |
4cf77af5e1ca49be2c72f20926b7cc2e1430adc3 | KadonWills/code-snippets | /python/basics/Repetition.py | 604 | 4.34375 | 4 | # Example of a for loop
words = ['I', 'like', 'to', 'learn', 'python']
for word in words:
print(len(word), word)
# example of the range function
for i in range(5):
print(i)
# Break and continue
v = 0
for i in range(1,10):
if i < 5:
continue
if i == 7:
break
v = i
print("v = ", v)
# example of using else in a for loop
for i in range(10):
print('i=',i)
if i>=3: break
else:
print('finish i=',i)
# This example demonstrate an infinite loop
v = 0
while True:
print("forever young")
v+=1
if v==100: break
print("I was young forever") |
66a175024183eff296acae1a7df6f1666ed59ccd | robisonJohn/Data-Structures-and-Algos | /closest-value-bst/closest-value-bst.py | 1,643 | 3.8125 | 4 | # Solution 1 - Average case space-time complexity of O(log(n)) time | O(log(n)) space
# Worst case space-time complexity of O(n) time | O(n) space
'''Conceptually, I am still a bit buzzy on Binary Trees. I will need to devote a weekend or two in order to better understand
them. '''
def findClosestValueInBst(tree, target):
return findClosestValueInBstHelper(tree, target, tree.value)
def findClosestValueInBstHelper(tree, target, closest):
if tree is None:
return closest
if abs(target - closest) > abs(target - tree.value):
closest = tree.value
if target < tree.value:
return findClosestValueInBstHelper(tree.left, target, closest)
elif target > tree.value:
return findClosestValueInBstHelper(tree.right, target, closest)
else:
return closest
# This is the class of the input tree.
class BST:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
'''
A sample input would look as follows:
{
"tree": {
"nodes": [
{"id": "10", "left": "5", "right": "15", "value": 10},
{"id": "15", "left": "13", "right": "22", "value": 15},
{"id": "22", "left": null, "right": null, "value": 22},
{"id": "13", "left": null, "right": "14", "value": 13},
{"id": "14", "left": null, "right": null, "value": 14},
{"id": "5", "left": "2", "right": "5-2", "value": 5},
{"id": "5-2", "left": null, "right": null, "value": 5},
{"id": "2", "left": "1", "right": null, "value": 2},
{"id": "1", "left": null, "right": null, "value": 1}
],
"root": "10"
},
"target": 12
}
''' |
0c1903d1771688a5ab88944acb032f0db14ac091 | lukaspblima/Estudo_Python | /exe034_aumento_salario.py | 219 | 3.796875 | 4 | sal = float(input('Digite o valor do seu salário: R$'))
if sal < 1250:
print('Seu novo salário é: R${:.2f}'.format(sal+(sal*0.15)))
else:
print('Seu novo salário é: R${:.2f}'.format(sal + (sal * 0.10))) |
13d28090ad002c98cf5d4d78cd135e3ff1fff189 | v1ct0r2911/semana12 | /ejercicio1.py | 216 | 3.828125 | 4 | #1. Elabore una función que
# tome como argumento dos números enteros
# y devuelva el mayor.
def mayor(a, b):
if a>b:
return a
else:
return b
numero_mayor=mayor(10,20)
print(numero_mayor) |
55b95f13f28eab8c0ad70088f421c7bd0d354c0d | ddian20/comp110-21f-workspace | /exercises/ex01/numeric_operators.py | 753 | 4.28125 | 4 | """EX01: Practicing Numeric Operators."""
__author__ = "730292529"
left_hand: int = int(input("Left-hand side: "))
right_hand: int = int(input("Right-hand side: "))
exponent_calculation: int = int(left_hand ** right_hand)
print(str(left_hand) + str(" ** ") + str(right_hand) + " is " + str(exponent_calculation))
division_calculation: float = float(left_hand / right_hand)
print(str(left_hand) + str(" / ") + str(right_hand) + " is " + str(division_calculation))
integer_division: int = int(left_hand // right_hand)
print(str(left_hand) + str(" // ") + str(right_hand) + " is " + str(integer_division))
remainder_calculation: int = int(left_hand % right_hand)
print(str(left_hand) + str(" % ") + str(right_hand) + " is " + str(remainder_calculation)) |
fdca258634cd1c5d5e80416347e2f0fbc93f33de | cnachteg/Notes_Master_BIOINFO_ULB | /Techniques_of_AI/projectCharlotteetHelene2017/Neuron.py | 573 | 3.578125 | 4 |
import random
import math
class Neuron() :
def __init__(self, inputsSize) :
self.weights = []
for i in range(inputsSize + 1):
self.weights.append(random.random()*6-3)
self.size = len(self.weights)
def setWeights (self, weightsList) :
self.weights = weightsList
def actionPot(self, inputsList):
slope = 1.0
sum = self.weights[self.size - 1]
for i in range(len(inputsList)):
sum += inputsList[i]*self.weights[i]
return 1.0/(1 + math.exp(-sum*slope)) |
8dbd355a5f8196db66b70a39facb3c16d7a64abe | lilkeng/CodingChanllege | /leetcode/python/letter_combinations_of_a_phone_number/solution1.py | 857 | 4 | 4 | '''
Given a digit string, return all possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the telephone buttons) is given below.
'''
class Solution(object):
def letterCombinations(self, digits):
"""
:type digits: str
:rtype: List[str]
"""
chr = ["", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"]
res = []
for i in range(len(digits)):
digit = int(digits[i])
tmp = []
for j in range(len(chr[digit])):
if len(res) == 0:
tmp.append(chr[digit][j])
else:
for k in range(len(res)):
tmp.append(res[k] + chr[digit][j])
res = copy.copy(tmp)
return res
|
04422be26f10ef34d4f8c9092d9c94f6d79b3756 | julianconstantine/python-ds | /Introduction/infinitemonkey.py | 609 | 3.78125 | 4 | __author__ = 'Julian'
import random
def randString(lenstr):
alphabet = "abcdefghijklmnopqrstuvwxyz "
randstr = ""
for n in range(lenstr):
index = random.randrange(27)
randstr += alphabet[index]
return randstr
def strScore(test, target):
score = 0
for j in range(len(target)):
if test[j] == target[j]:
score += 1
score /= len(target)
return score
def main():
target = "methinks it is like a weasel"
count = 0
oldscore = 0
while strScore(randString(len(target)), target) < 1:
count += 1
print(count)
|
ca582328e42eef489bacf7142aebda37213eb201 | kimth007kim/python_choi | /python/11주차/11_02.py | 734 | 3.640625 | 4 | from tkinter import *
window = Tk()
window.title("My Calculator")
display = Entry(window, width=33, bg="yellow")
display.grid(row=0,column=0,columnspan=5)
button_list=[
'7','8','9','/','C',
'4','5','6','*',' ',
'1','2','3','-',' ',
'0','.','=','+',' ' ]
def click(key):
if key == "=":
result= eval(display.get())
s= str(result)
display.insert(END,"=" +s)
else:
display.insert(END,key)
row_index =1
col_index =0
for button_text in button_list:
def process(t=button_text):
click(t)
Button(window,text=button_text,width=5,command=process).grid(row=row_index, column=col_index)
col_index += 1
if col_index >4:
row_index +=1
col_index=0
window.mainloop() |
4ab83fbef9ab284999b4878227f30138755f6053 | MajorTomaso/DQS | /ViewSummativeAnswers.py | 4,455 | 3.6875 | 4 | from tkinter import *
class introPage(Frame):
def __init__(self, master):
Frame.__init__(self, master)
self.grid()
self.createPage()
def createPage(self):
lblProg = Label(self, text='Summative Answers', font=('MS', 12,'bold'), width = "20", height = "3")
lblProg.grid(row=0, column=1)
lblGrid= Label(self, width = "20", height = "3")
lblGrid.grid(row=0, column=0)
lblGrid= Label(self, width = "20", height = "3")
lblGrid.grid(row=0, column=2)
butView = Button(self, text='View Answers',font=('MS', 10,'bold'), command = self.View)
butView.grid(row=1, column=1)
def View(self):
ansroot = Toplevel(self)
answerPage(ansroot)
root.withdraw()
class answerPage(Frame):
def __init__(self, master):
Frame.__init__(self, master)
self.grid()
self.answer()
def answer(self):
lblProg = Label(self, text='Answers for Question 1-10', font=('MS', 12,'bold'), width = "20", height = "3")
lblProg.grid(row=0, column=0)
lblQ1= Label(self, text="1. What is the cardinality of the following set?", font=('MS', 9,'bold'), anchor=W)
lblQ1.grid(row=1, column=0, columnspan=3, sticky=W)
lblQ1Ans= Label(self, text="3. (1 and {1} are different)", font=('MS', 9))
lblQ1Ans.grid(row=2, column=0, columnspan=3, sticky=W)
lblQ2= Label(self, text="2. What numbers are used in binary?", font=('MS', 9,'bold'), anchor=W)
lblQ2.grid(row=3, column=0, sticky=W)
lblQ2Ans= Label(self, text="0 and 1", font=('MS', 9))
lblQ2Ans.grid(row=4, column=0, columnspan=3, sticky=W)
lblQ3= Label(self, text="3. What does this symbol ∅ represent?", font=('MS', 9,'bold'), anchor=W)
lblQ3.grid(row=5, column=0, sticky=W)
lblQ3Ans= Label(self, text="Empty set", font=('MS', 9))
lblQ3Ans.grid(row=6, column=0, columnspan=3, sticky=W)
lblQ4= Label(self, text="4. What does HTML stand for?", font=('MS', 9,'bold'), anchor=W)
lblQ4.grid(row=7, column=0, sticky=W)
lblQ4Ans= Label(self, text="Hyper Text Markup Language", font=('MS', 9))
lblQ4Ans.grid(row=8, column=0, columnspan=3, sticky=W)
lblQ5= Label(self, text="5. How many bits are in a Byte?", font=('MS', 9,'bold'), anchor=W)
lblQ5.grid(row=9, column=0, sticky=W)
lblQ5Ans= Label(self, text="8 bits", font=('MS', 9), )
lblQ5Ans.grid(row=10, column=0, columnspan=3, sticky=W)
lblQ6= Label(self, text="6. What is RAM usually measure in?", font=('MS', 9,'bold'), anchor=W)
lblQ6.grid(row=11, column=0, sticky=W)
lblQ6Ans= Label(self, text="megabytes or gigabytes", font=('MS', 9))
lblQ6Ans.grid(row=12, column=0, columnspan=3, sticky=W)
lblQ7= Label(self, text="7. What is the name for a base 16 system used to simplify how binary is represented?", font=('MS', 9,'bold'), anchor=W)
lblQ7.grid(row=13, column=0, sticky=W)
lblQ7Ans= Label(self, text="Hexadecimal", font=('MS', 9))
lblQ7Ans.grid(row=14, column=0, columnspan=3, sticky=W)
lblQ8= Label(self, text="8. Convert 16 decimal to hexadecimal.", font=('MS', 9,'bold'), anchor=W)
lblQ8.grid(row=15, column=0, sticky=W)
lblQ8Ans= Label(self, text="Hexadecimal counts up to 16, including 0 so after the 15th number (F), the system starts at 10.", font=('MS', 9))
lblQ8Ans.grid(row=16, column=0, columnspan=3, sticky=W)
lblQ9= Label(self, text="9. Convert 1011 to decimal.", font=('MS', 9,'bold'), anchor=W)
lblQ9.grid(row=17, column=0, sticky=W)
lblQ9Ans= Label(self, text="[1 x 24]+ [0 x 23] + [1 x 22] + [1 x 21] = 11", font=('MS', 9))
lblQ9Ans.grid(row=18, column=0, columnspan=3, sticky=W)
lblQ10= Label(self, text="10. Convert 26 decimal to Ternary.", font=('MS', 9,'bold'), anchor=W)
lblQ10.grid(row=19, column=0, sticky=W)
lblQ10Ans= Label(self, text="26/3=8 remainder 2, 8/3=2 remainder 2, 2/3= 0 remainder 2. Read remainders backwards gives 222.", font=('MS', 9))
lblQ10Ans.grid(row=20, column=0, columnspan=3, sticky=W)
butView = Button(self, text='Close',font=('MS', 10,'bold'), command = self.close)
butView.grid(row=21, column=0, sticky=E)
def close(self):
root.destroy()
root = Tk()
root.title("Summative Answers")
app = introPage(root)
root.mainloop()
|
e10bcb2b3efeafb3cb260c30b3ee827840011dca | senatn/learning-python | /get-area.py | 1,338 | 4 | 4 | import math
def getArea(shape):
shape = shape.lower()
if shape == "r":
rectangleArea()
elif shape == "c":
circleArea()
elif shape == "t":
triangleArea()
else:
print("Please enter 'r', 'c' or 't' ")
return main()
def rectangleArea():
try:
lenght = float(input("Enter the length: "))
width = float(input("Enter the width: "))
area = lenght*width
print("The area of the rectangle is: {:.2f}".format(area))
except ValueError:
print("Please enter a number")
return rectangleArea()
def circleArea():
try:
radius = float(input("Enter the radius: "))
area = math.pi * (math.pow(radius,2))
print("The area of the circle is: {:.2f}".format(area))
except ValueError:
print("Please enter a number")
return circleArea()
def triangleArea():
try:
height = float(input("Enter the height: "))
base = float(input("Enter the base: "))
area = height * base / 2
print("The area of the triangle is: {:.2f}".format(area))
except ValueError:
print("Please enter a number")
return triangleArea()
def main():
type_of_shape = input("R for Rectangle\nC for Circle\nT for Triangle\nEnter the shape type: ")
getArea(type_of_shape)
main() |
baa0b531536d30523ddfd743b4ef69c09b00a78e | MAZTRO/holbertonschool-higher_level_programming | /0x0B-python-input_output/2-read_lines.py | 491 | 3.75 | 4 | #!/usr/bin/python3
def read_lines(filename="", nb_lines=0):
with open(filename, encoding='utf-8') as my_file:
if nb_lines <= 0:
my_file.seek(0)
print(my_file.read(), end='')
elif (nb_lines > len(my_file.readlines())):
my_file.seek(0)
print(my_file.read(), end='')
else:
my_file.seek(0)
for line in range(nb_lines):
line += 1
print(my_file.readline(), end='')
|
85e96f7d7a46a2deda7431af5e92d11fa106c09d | 0xChrisJL/easy-python | /106_不那么枯燥的猜数游戏.py | 1,313 | 3.9375 | 4 | # 作者:西岛闲鱼
# https://github.com/globien/easy-python
# https://gitee.com/globien/easy-python
# 不那么枯燥的猜数游戏
import random
very_happy = "小蟒今天开心极了,你来猜猜我的心情指数?"
happy = "小蟒现在挺高兴,你猜猜我的心情指数是多少?"
so_so = "小蟒现在感觉还行吧,你想知道我的心情指数是多少吗?"
sad = "小蟒现在不太高兴,你猜猜我的心情指数吧。"
very_sad = "小蟒今天很不开心,要猜你就猜小一点的数字吧。"
level_list = [very_sad, sad, so_so, happy, very_happy]
level = random.randint(0,4)
emotion = level * 20 + random.randint(1,20)
print(level_list[level])
guess = int(input("请输入1~100的数字:"))
n = 1 # 已经猜的次数
while guess != emotion:
if guess - emotion > 10: print("你猜得太大了!!!")
elif guess - emotion > 0: print("大了一点点,加油!")
elif guess - emotion < -10: print("你猜得太小了!!!")
else: print("猜得小了一点,继续!")
guess = int(input("请重新输入你的猜测:"))
n = n + 1
if n < 5:
print("恭喜你", n, "次就猜对了!智商杠杠的!")
else:
print("恭喜你终于猜对了,你猜了", n, "次。加油喔!")
|
819af40b6a91033b9069539241c797fa9691485f | hallnath1/AdventOfCode2020 | /day2/day2.py | 562 | 3.53125 | 4 | countA = 0
countB = 0
with open('input.txt') as file:
for line in file:
lineList = line.strip("\n").split(" ")
policy = lineList[0].split("-")
min = int(policy[0])
max = int(policy[1])
character = lineList[1][0]
charCount = lineList[2].count(character)
if charCount >= min and charCount <= max:
countA += 1
if bool(lineList[2][min-1] == character) != bool(lineList[2][max-1] == character):
countB += 1
print("Part A")
print(countA)
print("Part B")
print(countB)
|
df3360517501b8c5ff4af909df94f84d05579ffc | anulrajeev/MA-323-Monte-Carlo-Simulation | /LAB 8/180123057_MOHAMMAD_HUMAM_KHAN.py | 2,773 | 3.546875 | 4 | ##To run the code type in terminal: python3 180123057_MOHAMMAD_HUMAM_KHAN.py
import math
import random
import numpy as np
import pandas as pd
import statistics
import matplotlib.pyplot as plt
# Function to read adjusted closing price from csv file
def Read_Data():
df = pd.read_csv('SBIN.NS.csv',usecols=['Adj Close'])
StockPrices = []
for i in df.index:
StockPrices.append(df['Adj Close'][i])
return StockPrices
# Function which returns value of mu and sigma calculated using given formulas
def Analyze_Data(StockPrices):
# Calculating the log-return array
u = []
for i in range(1, len(StockPrices)):
u.append(math.log(StockPrices[i]/StockPrices[i-1]))
n = len(u)
Eu = statistics.mean(u)
sigma_square = 0
for x in u:
sigma_square += (x - Eu)**2
sigma_square = sigma_square/(n-1)
sigma = math.sqrt(sigma_square)
mu = Eu + (sigma_square/2)
print("mu = %s " % mu)
print("sigma = %s \n" % sigma)
return n,mu,sigma
#Function that simulates Stock price using Jump-Diffusion Process
def Estimate_Stock_Price(mu,sigma,S0,lamda,delta_t):
EstimatedStockPrices = []
EstimatedStockPrices.append(S0)
Xk = math.log(S0)
for i in range(1000):
Z = np.random.normal(0,1)
N = np.random.poisson(lamda*delta_t)
if N == 0:
M = 0
else:
M = 0
for i in range(N):
Y = np.random.lognormal(mu, sigma)
M += math.log(Y)
drift = delta_t*(mu - (sigma**2)/2)
diffusion = sigma*math.sqrt(delta_t)*Z
jump = M
Sk = math.exp(Xk + drift + diffusion + jump)
EstimatedStockPrices.append(Sk)
Xk = math.log(Sk)
return EstimatedStockPrices
def PlotResults(EstimatedStockPrices,lamda,name):
x = np.linspace(0,1001, 1001)
plt.figure(figsize = (30,10))
plt.title("Sample Path of Simulated Stock Prices using Jump-Diffusion Process \n lambda = %s" % lamda, fontsize=20)
plt.ylabel("Simulated Stock Prices", fontsize=15)
plt.xlabel("Time Points", fontsize=15)
plt.plot(x, EstimatedStockPrices)
plt.savefig(name)
plt.clf()
# Reading data from csv file
StockPrices = Read_Data()
# Calculate mu and sigma
n,mu,sigma = Analyze_Data(StockPrices)
# Initial Stock Price is closing stock price on Sep 30 i.e. S0 = Stock price on 30 Sep
S0 = StockPrices[n]
delta_t = 2
lamda = 0.01
EstimatedStockPrices = Estimate_Stock_Price(mu, sigma, S0, lamda, delta_t)
PlotResults(EstimatedStockPrices,lamda,"plot1")
lamda = 0.05
EstimatedStockPrices = Estimate_Stock_Price(mu, sigma, S0, lamda, delta_t)
PlotResults(EstimatedStockPrices,lamda,"plot2")
lamda = 0.1
EstimatedStockPrices = Estimate_Stock_Price(mu, sigma, S0, lamda, delta_t)
PlotResults(EstimatedStockPrices,lamda,"plot3")
lamda = 0.2
EstimatedStockPrices = Estimate_Stock_Price(mu, sigma, S0, lamda, delta_t)
PlotResults(EstimatedStockPrices,lamda,"plot4")
|
e0c72964b1294736be1d457254f33beb465d5d37 | HalfMoonFatty/Interview-Questions | /131. Palindrome Partitioning.py | 988 | 3.671875 | 4 | '''
Problem:
Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
For example, given s = "aab",
Return
[
["aa","b"],
["a","a","b"]
]
'''
class Solution(object):
def partition(self, s):
def isValid(s,start,end):
while start <= end:
if s[start] != s[end]:
return False
start += 1
end -= 1
return True
def getPart(s,start,res,results):
if start == len(s):
results.append(res[:])
return
else:
for i in range(start,len(s)):
if isValid(s,start,i):
res.append(s[start:i+1])
getPart(s,i+1,res,results)
res.pop()
results = []
getPart(s,0,[],results)
return results
|
d7ce11a933406b42abd6021510c741ca9b9845e8 | alecodigo/Python | /login_system.py | 471 | 3.5625 | 4 | # -*- coding:utf-8 -*-
PASSWORD = '123456*'
def proof_id(passwd):
if passwd:
if PASSWORD == passwd:
return True
else:
return False
if __name__ == '__main__':
print("Welcome Enter Your Secret Password")
passwd = input("password: ")
print(passwd)
if passwd:
result = proof_id(passwd)
if result:
print("Access granted")
else:
print("Access Denied")
|
647594c027a5e72b5f3227ae5048814e42167f95 | AishaDhiya/python | /pyramid.py | 151 | 3.953125 | 4 | def pyramid(n) :
for in range(1,n+1):
for j in range(1,i+1):
print(i*j , end+"")
print("in")
n= int(input("enter step number:"))
pyramid(n)
|
59a59c41d7eeb90a6bad52dd4472ed9540b20419 | shishuaigang/pythonProject | /3.py | 1,084 | 4.15625 | 4 | # 各种简单的排序
import random
def selectSort(List):
# 选择排序,依次将最小的值放置在列表的最左边
i = 0
while i < len(List) - 1:
minVal = List[i]
for j in range(i + 1, len(List)):
if List[j] < minVal:
minVal = List[j]
List[i], List[j] = List[j], List[i]
i += 1
return List
def mergeSort(List):
# 递归
if len(List) <= 1:
return List
mid = List[len(List) // 2]
left = mergeSort([item for item in List if item < mid])
middle = [item for item in List if item == mid]
right = mergeSort([item for item in List if item > mid])
return left + middle + right
def bubbleSort(List):
# 冒泡排序
for i in range(len(List)):
for j in range(i + 1, len(List)):
if List[i] > List[j]:
List[i], List[j] = List[j], List[i]
return List
if __name__ == "__main__":
L = [random.randint(1, 10000000) for _ in range(10000)]
print(selectSort(L))
print(mergeSort(L))
print(bubbleSort(L))
|
0d8eec432e6978f5607a4047912dfc2665ca436e | lostarray/LeetCode | /001_Two_Sum.py | 1,008 | 3.859375 | 4 | # Given an array of integers, return indices of the two numbers such that they add up to a specific target.
#
# You may assume that each input would have exactly one solution.
#
# Example:
# Given nums = [2, 7, 11, 15], target = 9,
#
# Because nums[0] + nums[1] = 2 + 7 = 9,
# return [0, 1].
#
# Tags: Array, Hash Table
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
index = {}
for i in xrange(len(nums)):
a = nums[i]
b = target - a
if b in index:
return [index[b], i]
index[a] = i
def twoSum_1(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
size = len(nums)
for i in xrange(size):
for j in xrange(i + 1, size):
if nums[i] + nums[j] == target:
return [i, j]
|
1c7fcde3e2f10e7c81e993de10eda4205688cb9f | spud-bud/exercism_python | /rna-transcription/dna.py | 321 | 3.75 | 4 | transcription_dict = {'G':'C', 'C':'G', 'T':'A', 'A':'U'}
# def to_rna(dna):
# result = []
# for letter in dna:
# result.append(transcription_dict[letter])
# return ''.join(result)
def to_rna(dna):
result = ''
for letter in dna:
result += transcription_dict[letter]
return result
|
14df18b3f8a29ee4fc8e961396c1004cbaf68802 | cvasani/SparkLearning | /Input/Notes/python_course/tuples/practice_exercises/solution_01.py | 328 | 3.921875 | 4 | #!/usr/bin/env python3
airports = [
("O’Hare International Airport", 'ORD'),
('Los Angeles International Airport', 'LAX'),
('Dallas/Fort Worth International Airport', 'DFW'),
('Denver International Airport', 'DEN')
]
for (airport, code) in airports:
print('The code for {} is {}.'.format(airport, code))
|
79e4583f1c0207caafb490380de352492cd50475 | cendongqi/python-example | /example/list_tuple.py | 1,082 | 4.34375 | 4 | classmate = ['Mike', 'John', 'Rose']
# 取值
print(classmate)
print(len(classmate))
print(classmate[0])
print(classmate[1])
print(classmate[2])
print(classmate[-1])
print(classmate[-2])
print(classmate[-3])
print('----------')
# 末尾追加
classmate.append('adam')
print(classmate)
# 插入
classmate.insert(2,'Jack')
print(classmate)
# 末尾删除
classmate.pop()
print(classmate)
# 指定位置删除
classmate.pop(2)
print(classmate)
# 替换
classmate[1] = 'Sarah'
print(classmate)
# 不同类型
exts = [1, 'John', True]
print(exts)
# list嵌套
classmate.append(exts)
print(classmate)
# 空list
emptyList = []
print(len(emptyList))
# tuple
classmates = ('Michael', 'Bob', 'Tracy')
print(classmates)
# 空tuple
p = ()
print(len(p))
# 一个元素的tuple
t = (1)
print(t)
t = (1,)
print(t)
# exercise
# 请用索引取出下面list的指定元素:
L = [
['Apple', 'Google', 'Microsoft'],
['Java', 'Python', 'Ruby', 'PHP'],
['Adam', 'Bart', 'Lisa']
]
# 打印Apple:
print(L[0][0])
# 打印Python:
print(L[1][1])
# 打印Lisa:
print(L[2][2])
|
aafcc9e47a69ea44873fd15619a5db8a889b58a9 | samiCode-irl/programiz-python-examples | /Functions/power_of_2.py | 203 | 4.25 | 4 | # Python Program To Display Powers of 2 Using Anonymous Function
terms = 10
result = list(map(lambda x: 2 ** x, range(terms)))
for i in range(terms):
print(f'The power of 2 of {i} = {result[i]}')
|
3844bea4eece8785a879da84541b98fdc05cb8c3 | imachuchu/Checkers-CCAINN | /board.py | 7,753 | 3.953125 | 4 | """ A representation of a checker board
Ben Hartman 3/4/2012
"""
import random #For random generation functions
import itertools #For sweet fast list functions
import math #For the e constant
import copy
class board():
""" Represents one checker board
"""
def __init__(self):
"""Creates a starter board
The board is counted from 0 in the upper left, with black on top, and each movable square represented by a character
"""
self.location = list("bbbbbbbbbbbb" + "eeeeeeee" + "rrrrrrrrrrrr")
def randomBoard(self):
"""Generates a random board
NOTE: The generated board may not be an actually valid board (one that could be actually played to)
"""
choices = ['e', 'r', 'b', 'R', 'B']
self.location = [random.choice(choices) for x in range(32)]
def genMoves(self,color,jumpFound=False): # !NOTE: Only works for black currently!
"""Returns a set of future boards generatable from the current board. If none returns an empty set
Color is the current player's color, either "black" or "red". JumpFound is used for recursive calls so should be left alone elsewise
"""
jumpBoards = set({})
for square,location in zip(self.location,range(32)):
if spot is not ('e' or 'r') and location <= 23: # So we can go down-left and down-right
if (location % 4 is not 0) and (self.location[location+7] is 'e'): #Down-left jump
if location % 8 < 4: #Odd numbered row
if (self.location[location+4] is ('r' or 'R') and color is "black") or \
(self.location[location+4] is ('b' or 'B') and color is "red"):
newBoard = copy.copy(self)
newBoard[location+7] = newBoard[location]
newBoard[location] = 'e'
newBoard[location+4] = 'e'
tempSet = newBoard.genMoves(color, jumpFound=True)
if tempSet:
jumpBoards = board | tempSet
else:
jumpBoards.add(newBoard)
else:
if (self.location[location+3] is ('r' or 'R') and color is "black") or \
(self.location[location+3] is ('b' or 'B') and color is "red"):
newBoard = copy.copy(self)
newBoard[location+7] = newBoard[location]
newBoard[location] = 'e'
newBoard[location+3] = 'e'
tempSet = newBoard.genMoves(color, jumpFound=True)
if tempSet:
jumpBoards = board | tempSet
else:
jumpBoards.add(newBoard)
if (location % 4 is not 3) and (self.location[location+9] is 'e'): #Down-right jump
if location % 8 < 4: #Odd numbered row
if (self.location[location+5] is ('r' or 'R') and color is "black") or \
(self.location[location+5] is ('b' or 'B') and color is "red"):
newBoard = copy.copy(self)
tempSet = newBoard.genMoves(color, jumpFound=True)
newBoard[location+9] = newBoard[location]
newBoard[location] = 'e'
newBoard[location+5] = 'e'
if tempSet:
jumpBoards = board | tempSet
else:
jumpBoards.add(newBoard)
if (self.location[location+4] is ('r' or 'R') and color is "black" or \
(self.loation[location+4] is ('b' or 'B') and color is "red":
newBoard = copy.copy(self)
newBoard[location+9] = newBoard[location]
newBoard[location] = 'e'
newBoard[location+4] = 'e'
tempSet = newBoard.genMoves(color, jumpFound=True)
if tempSet:
jumpBoards = board | tempSet
else:
jumpBoards.add(newBoard)
if spot is not ('e' or 'b') and location >= 9: # So we can go up-left and up-right
if (location % 4 is not 0) and (self.location[location-7] is 'e'): #Up-left jump
if location % 8 < 4: #Odd numbered row
if (self.location[location-4] is ('r' or 'R') and color is "black") or \
(self.location[location-4] is ('b' or 'B') and color is "red"):
newBoard = copy.copy(self)
newBoard[location-7] = newBoard[location]
newBoard[location] = 'e'
newBoard[location-4] = 'e'
tempSet = newBoard.genMoves(color, jumpFound=True)
if tempSet:
jumpBoards = board | tempSet
else:
jumpBoards.add(newBoard)
else:
if (self.location[location-5] is ('r' or 'R') and color is "black") or \
(self.location[location-5] is ('b' or 'B') and color is "red"):
newBoard = copy.copy(self)
newBoard[location-7] = newBoard[location]
newBoard[location] = 'e'
newBoard[location-5] = 'e'
tempSet = newBoard.genMoves(color, jumpFound=True)
if tempSet:
jumpBoards = board | tempSet
else:
jumpBoards.add(newBoard)
if (location % 4 is not 3) and (self.location[location-9] is 'e'): #Up-right jump
if location % 8 < 4: #Odd numbered row
if (self.location[location-3] is ('r' or 'R') and color is "black") or \
(self.loation[location-5] is ('b' or 'B') and color is "red"):
newBoard = copy.copy(self)
newBoard[location-9] = newBoard[location]
newBoard[location] = 'e'
newBoard[location-3] = 'e'
tempSet = newBoard.genMoves(color, jumpFound=True)
if tempSet:
jumpBoards = board | tempSet
else:
jumpBoards.add(newBoard)
if (self.location[location-4] is ('r' or 'R') and color is "black") or \
(self.location[location-4] is ('b' or 'B') and color is "red"):
newBoard = copy.copy(self)
newBoard[location-9] = newBoard[location]
newBoard[location] = 'e'
newBoard[location-4] = 'e'
tempSet = newBoard.genMoves(color, jumpFound=True)
if tempSet:
jumpBoards = board | tempSet
else:
jumpBoards.add(newBoard)
if jumpBoards or jumpFound: #We've found at least one jump
return jumpBoards
#No jumps, do the moves
moveList = set()
if spot is not ('e' or 'r') and location <= 27: # So we can go down-left and down-right
if location % 4 is not 0: #Down-left move
if location % 8 < 4: #Odd numbered row
if self.location[location+4] is ('e'):
newBoard = copy.copy(self)
newBoard[location+4] = newBoard[location]
newBoard[location] = 'e'
moveList.add(newBoard)
else:
if self.location[location+3] is ('e'):
newBoard = copy.copy(self)
newBoard[location+3] = newBoard[location]
newBoard[location] = 'e'
moveList.add(newBoard)
if location % 4 is not 3: #Down-right move
if location % 8 < 4: #Odd numbered row
if self.location[location+5] is ('e'):
newBoard = copy.copy(self)
newBoard[location+5] = newBoard[location]
newBoard[location] = 'e'
moveList.add(newBoard)
else:
if self.location[location+4] is ('e'):
newBoard = copy.copy(self)
newBoard[location+4] = newBoard[location]
newBoard[location] = 'e'
moveList.add(newBoard)
if spot is not ('e' or 'b') and location >= 7: # So we can go up-left and up-right
if location % 4 is not 0: #Up-left move
if location % 8 < 4: #Odd numbered row
if self.location[location-4] is ('e'):
newBoard = copy.copy(self)
newBoard[location-4] = newBoard[location]
newBoard[location] = 'e'
moveList.add(newBoard)
else:
if self.location[location-5] is ('e'):
newBoard = copy.copy(self)
newBoard[location-5] = newBoard[location]
newBoard[location] = 'e'
moveList.add(newBoard)
if location % 4 is not 3: #Up-right move
if location % 8 < 4: #Odd numbered row
if self.location[location-3] is ('e'):
newBoard = copy.copy(self)
newBoard[location-3] = newBoard[location]
newBoard[location] = 'e'
moveList.add(newBoard)
else:
if self.location[location-4] is ('e'):
newBoard = copy.copy(self)
newBoard[location-4] = newBoard[location]
newBoard[location] = 'e'
moveList.add(newBoard)
return moveList
|
54f66ece22bdf0f2ef20292fb9a9e9d2f429b5e2 | Th3Lourde/l33tcode | /270.py | 555 | 3.5 | 4 | class Solution:
def closestValue(self, root, target):
self.ans = float('-inf')
def dfs(node, target):
if not node:
return
if abs(target - node.val) < abs(target - self.ans):
self.ans = node.val
if node.val >= target and node.left:
dfs(node.left, target)
if node.val <= target and node.right:
dfs(node.right, target)
dfs(root, target)
return self.ans
'''
1 <
N 2
3.42
dfs(1, 3.5)
'''
|
43b863415585ace675d7034f6ff831753cf05a56 | JunctionChao/LeetCode | /LinkedList/link_list_fun.py | 590 | 3.828125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Date : 2019-09-22
# Author : Yuanbo Zhao ([email protected])
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
# 根据数据生成链表 逆序生成链表
def generateNum(numList: list) -> ListNode:
root = n = ListNode(0)
while numList:
x = numList.pop()
ln = ListNode(x)
n.next = ln
n = n.next
return root.next
# 打印链表
def printListNode(l: ListNode) -> None:
while l:
print(l.val, end='')
l = l.next |
962f80e27ded1976bee08f06b2351a51caa45987 | MonaHe123/coding-exercise | /p_code/RL/MDP/test.py | 132 | 3.84375 | 4 | args = []
arg = ["1","2","3"]
args += [i for i in arg]
print(args)
num = [1]
num2 = [2]
num2 += num
print(num2)
print("_".join(arg)) |
f4720554007f9071e2ee4ad4fe291b3f01ceb1bf | mubaarik/AI | /lab5/lab5.py | 11,753 | 3.515625 | 4 | # MIT 6.034 Lab 5: k-Nearest Neighbors and Identification Trees
# Written by Jessica Noss (jmn), Dylan Holmes (dxh), and Jake Barnwell (jb16)
from api import *
from data import *
import math
log2 = lambda x: math.log(x, 2)
INF = float('inf')
################################################################################
############################# IDENTIFICATION TREES #############################
################################################################################
def id_tree_classify_point(point, id_tree):
"""Uses the input ID tree (an IdentificationTreeNode) to classify the point.
Returns the point's classification."""
#print id_tree
# classify = id_tree.apply_classifier(point)
# if id_tree.is_leaf():
# return classify
# return [id_tree_classify_point(point, node) for node in id_tree.get_branches()]
if id_tree.is_leaf():
return id_tree.get_node_classification()
child = id_tree.apply_classifier(point)
return id_tree_classify_point(point, child)
def split_on_classifier(data, classifier):
"""Given a set of data (as a list of points) and a Classifier object, uses
the classifier to partition the data. Returns a dict mapping each feature
values to a list of points that have that value."""
class_dict={}
for point in data:
classif = classifier.classify(point)
if not classif in class_dict:
class_dict[classif]=[point]
else:
class_dict[classif].append(point)
return class_dict
#### CALCULATING DISORDER
def branch_disorder(data, target_classifier):
"""Given a list of points representing a single branch and a Classifier
for determining the true classification of each point, computes and returns
the disorder of the branch."""
cla = split_on_classifier(data, target_classifier)
total=sum([len(cla[classification]) for classification in cla.keys()])
disorder=sum([-len(cla[x])/float(total)*log2(len(cla[x])/float(total)) for x in cla.keys()])
return disorder
def average_test_disorder(data, test_classifier, target_classifier):
"""Given a list of points, a feature-test Classifier, and a Classifier
for determining the true classification of each point, computes and returns
the disorder of the feature-test stump."""
test_split = split_on_classifier(data, test_classifier)
total = float(len(data))
aver=sum([branch_disorder(test_split[cla], target_classifier)*(len(test_split[cla])/total) for cla in test_split.keys()])
return aver
## To use your functions to solve part A2 of the "Identification of Trees"
## problem from 2014 Q2, uncomment the lines below and run lab5.py:
#for classifier in tree_classifiers:
# print classifier.name, average_test_disorder(tree_data, classifier, feature_test("tree_type"))
#### CONSTRUCTING AN ID TREE
def find_best_classifier(data, possible_classifiers, target_classifier):
"""Given a list of points, a list of possible Classifiers to use as tests,
and a Classifier for determining the true classification of each point,
finds and returns the classifier with the lowest disorder. Breaks ties by
preferring classifiers that appear earlier in the list. If the best
classifier has only one branch, raises NoGoodClassifiersError."""
best_cla = None
best_cla_disorder = INF
for test_cla in possible_classifiers:
disorder = average_test_disorder(data, test_cla, target_classifier)
if disorder<best_cla_disorder:
best_cla=test_cla
best_cla_disorder = disorder
branches = split_on_classifier(data, best_cla)
if len(branches.keys())==1:
raise NoGoodClassifiersError
else:
return best_cla
## To find the best classifier from 2014 Q2, Part A, uncomment:
#print find_best_classifier(tree_data, tree_classifiers, feature_test("tree_type"))
def construct(data, possible_classifiers, target_classifier, id_tree_node):
#print "run"
#
if branch_disorder(data, target_classifier)==0.0:
id_tree_node.set_node_classification(target_classifier.classify(data[-1]))
else:
try:
best_classifier = find_best_classifier(data, possible_classifiers, target_classifier)
except NoGoodClassifiersError:
best_classifier=False
if best_classifier==False:
pass
else:
split = split_on_classifier(data, best_classifier)
next_class=possible_classifiers[:]
next_class.remove(best_classifier)
features = split.keys()
id_tree_node.set_classifier_and_expand(best_classifier, features)
branches = id_tree_node.get_branches()
for name in branches.keys():
construct(split[name], next_class, target_classifier, branches[name])
def construct_greedy_id_tree(data, possible_classifiers, target_classifier, id_tree_node=None):
"""Given a list of points, a list of possible Classifiers to use as tests,
a Classifier for determining the true classification of each point, and
optionally a partially completed ID tree, returns a completed ID tree by
adding classifiers and classifications until either perfect classification
has been achieved, or there are no good classifiers left."""
if id_tree_node==None:
id_tree_node=IdentificationTreeNode(target_classifier)
construct(data, possible_classifiers, target_classifier, id_tree_node)
return id_tree_node
#construct_greedy_id_tree(data, next_class, target_classifier, id_tree_node=None)
## To construct an ID tree for 2014 Q2, Part A:
#print construct_greedy_id_tree(tree_data, tree_classifiers, feature_test("tree_type"))
## To use your ID tree to identify a mystery tree (2014 Q2, Part A4):
#tree_tree = construct_greedy_id_tree(tree_data, tree_classifiers, feature_test("tree_type"))
#print id_tree_classify_point(tree_test_point, tree_tree)
## To construct an ID tree for 2012 Q2 (Angels) or 2013 Q3 (numeric ID trees):
#print construct_greedy_id_tree(angel_data, angel_classifiers, feature_test("Classification"))
#print construct_greedy_id_tree(numeric_data, numeric_classifiers, feature_test("class"))
#### MULTIPLE CHOICE
ANSWER_1 = 'bark_texture'
ANSWER_2 = 'leaf_shape'
ANSWER_3 = 'orange_foliage'
ANSWER_4 = [2,3]
ANSWER_5 = [3]
ANSWER_6 = [2]
ANSWER_7 = 2
ANSWER_8 = 'No'
ANSWER_9 = 'No'
################################################################################
############################# k-NEAREST NEIGHBORS ##############################
################################################################################
#### MULTIPLE CHOICE: DRAWING BOUNDARIES
BOUNDARY_ANS_1 = 3
BOUNDARY_ANS_2 = 4
BOUNDARY_ANS_3 = 1
BOUNDARY_ANS_4 = 2
BOUNDARY_ANS_5 = 2
BOUNDARY_ANS_6 = 4
BOUNDARY_ANS_7 = 1
BOUNDARY_ANS_8 = 4
BOUNDARY_ANS_9 = 4
BOUNDARY_ANS_10 = 4
BOUNDARY_ANS_11 = 2
BOUNDARY_ANS_12 = 1
BOUNDARY_ANS_13 = 4
BOUNDARY_ANS_14 = 4
#### WARM-UP: DISTANCE METRICS
def dot_product(u, v):
"""Computes dot product of two vectors u and v, each represented as a tuple
or list of coordinates. Assume the two vectors are the same length."""
return sum([v[i]*u[i] for i in range(len(u))])
def norm(v):
"Computes length of a vector v, represented as a tuple or list of coords."
return math.sqrt(sum([i**2 for i in v]))
def euclidean_distance(point1, point2):
"Given two Points, computes and returns the Euclidean distance between them."
#print "point: ",point1, "point2: ", point2
return math.sqrt(sum([(point1.coords[i] - point2.coords[i])**2 for i in range(len(point1.coords))]))
def manhattan_distance(point1, point2):
"Given two Points, computes and returns the Manhattan distance between them."
return sum([abs(point1.coords[i]-point2.coords[i]) for i in range(len(point1.coords))])
def hamming_distance(point1, point2):
"Given two Points, computes and returns the Hamming distance between them."
return sum([(point1.coords[i]!=point2.coords[i]) for i in range(len(point2.coords))])
def cosine_distance(point1, point2):
"""Given two Points, computes and returns the cosine distance between them,
where cosine distance is defined as 1-cos(angle_between(point1, point2))."""
cos_ang = dot_product(point1.coords, point2.coords)/(norm(point1.coords)*norm(point2.coords))
dist = 1-math.cos(math.acos(cos_ang))
return dist
#### CLASSIFYING POINTS
def get_k_closest_points(point, data, k, distance_metric):
"""Given a test point, a list of points (the data), an int 0 < k <= len(data),
and a distance metric (a function), returns a list containing the k points
from the data that are closest to the test point, according to the distance
metric. Breaks ties lexicographically by coordinates."""
#print "point: ", point, "data[0]: ", data[0], "distance: ", distance_metric(point, data[0])
_data = sorted(data, key = lambda x: x.coords)
point_dist=sorted([(_point, distance_metric(point, _point)) for _point in _data], key = lambda x: x[1])
return [point_dist[i][0] for i in range(k)]
raise NotImplementedError
def knn_classify_point(point, data, k, distance_metric):
"""Given a test point, a list of points (the data), an int 0 < k <= len(data),
and a distance metric (a function), returns the classification of the test
point based on its k nearest neighbors, as determined by the distance metric.
Assumes there are no ties."""
point_lst = get_k_closest_points(point, data, k, distance_metric)
mar = [x.classification for x in point_lst]
return max(mar, key = mar.count)
## To run your classify function on the k-nearest neighbors problem from 2014 Q2
## part B2, uncomment the line below and try different values of k:
#print knn_classify_point(knn_tree_test_point, knn_tree_data, 5, euclidean_distance)
#### CHOOSING k
def cross_validate(data, k, distance_metric):
"""Given a list of points (the data), an int 0 < k <= len(data), and a
distance metric (a function), performs leave-one-out cross-validation.
Return the fraction of points classified correctly, as a float."""
correct = []
for i in range(len(data)):
point = data[i]
_data = data[:]
_data.pop(i)
cl = knn_classify_point(point, _data, k, distance_metric)
if point.classification==cl:
correct.append(point)
return len(correct)/float(len(data))
def find_best_k_and_metric(data):
"""Given a list of points (the data), uses leave-one-out cross-validation to
determine the best value of k and distance_metric, choosing from among the
four distance metrics defined above. Returns a tuple (k, distance_metric),
where k is an int and distance_metric is a function."""
best_cros_val = 0
dist_m = euclidean_distance
k_best = 0
for distance_metric in [euclidean_distance, manhattan_distance, hamming_distance, cosine_distance]:
for k in range(1, len(data)):
fr = cross_validate(data, k, distance_metric)
if fr>=best_cros_val:
best_cros_val = fr
dist_m = distance_metric
best_k=k
return best_k, dist_m
## To find the best k and distance metric for 2014 Q2, part B, uncomment:
#print find_best_k_and_metric(knn_tree_data)
#### MORE MULTIPLE CHOICE
kNN_ANSWER_1 = 'Overfitting'
kNN_ANSWER_2 = 'Underfitting'
kNN_ANSWER_3 = 4
kNN_ANSWER_4 = 4
kNN_ANSWER_5 = 1
kNN_ANSWER_6 = 3
kNN_ANSWER_7 = 3
#### SURVEY ###################################################
NAME = "Mubarik Mohamoud"
COLLABORATORS = ""
HOW_MANY_HOURS_THIS_LAB_TOOK = 7
WHAT_I_FOUND_INTERESTING = "id trees"
WHAT_I_FOUND_BORING = "nearest neighbors"
SUGGESTIONS = ""
|
ce50d1caccd5127e94769b36df37d30f3b664bb0 | victsnet/Geoanalytics-and-Machine-Learning | /SOM-Remote Sensing-Geology/toolbox.py | 6,859 | 3.59375 | 4 | from tqdm import trange
import numpy as np
import matplotlib.pyplot as plt
def window3x3(arr, shape=(3, 3)):
r_win = np.floor(shape[0] / 2).astype(int)
c_win = np.floor(shape[1] / 2).astype(int)
x, y = arr.shape
for i in range(x):
xmin = max(0, i - r_win)
xmax = min(x, i + r_win + 1)
for j in range(y):
ymin = max(0, j - c_win)
ymax = min(y, j + c_win + 1)
yield arr[xmin:xmax, ymin:ymax]
def gradient(XYZ_file, min=0, max=15, figsize=(6, 8), **kwargs):
"""
:param XYZ_file: XYZ file in the following format: x,y,z (including headers)
:param min: color bar minimum range.
:param max: color bar maximum range.
:param figsize: figure size.
:param kwargs:
plot: to plot a gradient map. Default is True.
:return: returns an array with the shape of the grid with the computed slopes
The algorithm calculates the gradient using a first-order forward or backward difference on the corner points, first
order central differences at the boarder points, and a 3x3 moving window for every cell with 8 surrounding cells (in
the middle of the grid) using a third-order finite difference weighted by reciprocal of squared distance
Assumed 3x3 window:
-------------------------
| a | b | c |
-------------------------
| d | e | f |
-------------------------
| g | h | i |
-------------------------
"""
kwargs.setdefault('plot', True)
grid = XYZ_file.to_numpy()
nx = XYZ_file.iloc[:,0].unique().size
ny = XYZ_file.iloc[:,1].unique().size
xs = grid[:, 0].reshape(ny, nx, order='A')
ys = grid[:, 1].reshape(ny, nx, order='A')
zs = grid[:, 2].reshape(ny, nx, order='A')
dx = abs((xs[:, 1:] - xs[:, :-1]).mean())
dy = abs((ys[1:, :] - ys[:-1, :]).mean())
gen = window3x3(zs)
windows_3x3 = np.asarray(list(gen))
windows_3x3 = windows_3x3.reshape(ny, nx)
dzdx = np.empty((ny, nx))
dzdy = np.empty((ny, nx))
loc_string = np.empty((ny, nx), dtype="S25")
for ax_y in trange(ny):
for ax_x in range(nx):
# corner points
if ax_x == 0 and ax_y == 0: # top left corner
dzdx[ax_y, ax_x] = (windows_3x3[ax_y, ax_x][0][1] - windows_3x3[ax_y, ax_x][0][0]) / dx
dzdy[ax_y, ax_x] = (windows_3x3[ax_y, ax_x][1][0] - windows_3x3[ax_y, ax_x][0][0]) / dy
loc_string[ax_y, ax_x] = 'top left corner'
elif ax_x == nx - 1 and ax_y == 0: # top right corner
dzdx[ax_y, ax_x] = (windows_3x3[ax_y, ax_x][0][1] - windows_3x3[ax_y, ax_x][0][0]) / dx
dzdy[ax_y, ax_x] = (windows_3x3[ax_y, ax_x][1][1] - windows_3x3[ax_y, ax_x][0][1]) / dy
loc_string[ax_y, ax_x] = 'top right corner'
elif ax_x == 0 and ax_y == ny - 1: # bottom left corner
dzdx[ax_y, ax_x] = (windows_3x3[ax_y, ax_x][1][1] - windows_3x3[ax_y, ax_x][1][0]) / dx
dzdy[ax_y, ax_x] = (windows_3x3[ax_y, ax_x][1][0] - windows_3x3[ax_y, ax_x][0][0]) / dy
loc_string[ax_y, ax_x] = 'bottom left corner'
elif ax_x == nx - 1 and ax_y == ny - 1: # bottom right corner
dzdx[ax_y, ax_x] = (windows_3x3[ax_y, ax_x][1][1] - windows_3x3[ax_y, ax_x][1][0]) / dx
dzdy[ax_y, ax_x] = (windows_3x3[ax_y, ax_x][1][1] - windows_3x3[ax_y, ax_x][0][1]) / dy
loc_string[ax_y, ax_x] = 'bottom right corner'
# top boarder
elif (ax_y == 0) and (ax_x != 0 and ax_x != nx - 1):
dzdx[ax_y, ax_x] = (windows_3x3[ax_y, ax_x][0][-1] - windows_3x3[ax_y, ax_x][0][0]) / (2 * dx)
dzdy[ax_y, ax_x] = (windows_3x3[ax_y, ax_x][1][1] - windows_3x3[ax_y, ax_x][0][1]) / dy
loc_string[ax_y, ax_x] = 'top boarder'
# bottom boarder
elif ax_y == ny - 1 and (ax_x != 0 and ax_x != nx - 1):
dzdx[ax_y, ax_x] = (windows_3x3[ax_y, ax_x][1][-1] - windows_3x3[ax_y, ax_x][1][0]) / (2 * dx)
dzdy[ax_y, ax_x] = (windows_3x3[ax_y, ax_x][1][1] - windows_3x3[ax_y, ax_x][0][1]) / dy
loc_string[ax_y, ax_x] = 'bottom boarder'
# left boarder
elif ax_x == 0 and (ax_y != 0 and ax_y != ny - 1):
dzdx[ax_y, ax_x] = (windows_3x3[ax_y, ax_x][1][1] - windows_3x3[ax_y, ax_x][1][0]) / dx
dzdy[ax_y, ax_x] = (windows_3x3[ax_y, ax_x][-1][0] - windows_3x3[ax_y, ax_x][0][0]) / (2 * dy)
loc_string[ax_y, ax_x] = 'left boarder'
# right boarder
elif ax_x == nx - 1 and (ax_y != 0 and ax_y != ny - 1):
dzdx[ax_y, ax_x] = (windows_3x3[ax_y, ax_x][1][1] - windows_3x3[ax_y, ax_x][1][0]) / dx
dzdy[ax_y, ax_x] = (windows_3x3[ax_y, ax_x][-1][-1] - windows_3x3[ax_y, ax_x][0][-1]) / (2 * dy)
loc_string[ax_y, ax_x] = 'right boarder'
# middle grid
else:
a = windows_3x3[ax_y, ax_x][0][0]
b = windows_3x3[ax_y, ax_x][0][1]
c = windows_3x3[ax_y, ax_x][0][-1]
d = windows_3x3[ax_y, ax_x][1][0]
f = windows_3x3[ax_y, ax_x][1][-1]
g = windows_3x3[ax_y, ax_x][-1][0]
h = windows_3x3[ax_y, ax_x][-1][1]
i = windows_3x3[ax_y, ax_x][-1][-1]
dzdx[ax_y, ax_x] = ((c + 2 * f + i) - (a + 2 * d + g)) / (8 * dx)
dzdy[ax_y, ax_x] = ((g + 2 * h + i) - (a + 2 * b + c)) / (8 * dy)
loc_string[ax_y, ax_x] = 'middle grid'
hpot = np.hypot(abs(dzdy), abs(dzdx))
slopes_angle = np.degrees(np.arctan(hpot))
if kwargs['plot']:
slopes_angle[(slopes_angle < min) | (slopes_angle > max)]
plt.figure(figsize=figsize)
plt.pcolormesh(xs, ys, slopes_angle, cmap='Greys', vmax=max, vmin=min)
plt.colorbar()
plt.tight_layout()
plt.show()
return slopes_angle, xs, ys
def hillshade(array, azimuth, angle_altitude):
x, y = np.gradient(array)
slope = np.pi / 2. - np.arctan(np.sqrt(x * x + y * y))
aspect = np.arctan2(-x, y)
azimuthrad = azimuth * np.pi / 180.
altituderad = angle_altitude * np.pi / 180.
shaded = np.sin(altituderad) * np.sin(slope) \
+ np.cos(altituderad) * np.cos(slope) \
* np.cos(azimuthrad - aspect)
hillshade_array = 255 * (shaded + 1) / 2
return hillshade_array
|
7970b4a3c3e079573bd61513f6e1670c026cd7d7 | parth3033/python-problems | /sumevennumber.py | 105 | 3.78125 | 4 | sum=0
for i in range (1,31):
if(i==10 or i==20):
continue
elif(i%2==0):
sum=sum+i
print(sum)
|
982793670d17cf2757f19788bd0e4d5ca98a1d5d | kanwar101/Python_Review | /src/Chapter07/pets.py | 116 | 3.796875 | 4 | pets = ['dog','cat','mouse','fish','cat','ant']
print (pets)
while 'cat' in pets:
pets.remove('cat')
print (pets) |
a366d1c83a2f111d1f05a2de03f609a4e158a2ae | MargauxMasson/useful_scripts | /change_file_extension.py | 508 | 3.84375 | 4 | import os
import glob
# Path to directory with the files that need a new extension
path_to_directory = './path_to_directory_with_files_that_need_new_extension'
current_extension = '.png'
new_extension = '.jpg'
list_files = glob.glob(path_to_directory + '/*' + current_extension)
for path_to_file in list_files:
pre, ext = os.path.splitext(path_to_file)
path_renamed = pre + new_extension
os.rename(path_to_file, path_renamed)
print("File {} renamed {}".format(path_to_file, path_renamed))
|
1fae33240386d73315c2f17846876414524adf2b | iliyankrastanov/Python | /file39.py | 535 | 3.765625 | 4 | def foo(a):
a = 10
print(f"a = {a}")
def sort_values(values):
values.sort()
def bar(a = [], b = {}):
print(f"a = {a}")
print(f"b = {b}")
print("- " * 20)
n = len(a)
a.append(n)
b[n] = n
if __name__ == "__main__":
#1.
#x = 100
#foo(x)
#print(f"x = {x}")
#2.
#arr = [9,8,6,5,3,2]
#sort_values(arr)
#print(f"arr = {arr}")
#3.
bar()
bar([5,6,7], {"x":100})
bar()
bar()
bar([5,6,7,3,6], {"x":100, "Z":2})
bar()
print("--- --- --- ---") |
61e5beadf41baf3e6905d487f1f1e1ed77e3b90a | edu-athensoft/stem1401python_student | /py210116f_python3a/day10_210403/sample/label_15_config_counter_2.py | 791 | 3.546875 | 4 | """
lable counter 2
optimizing
optimization
optimize
refactor
refactoring
"""
# import tkinter as tk
from tkinter import *
def start_counting(mylabel):
print("entered start_counting()")
counter=0
def counting():
nonlocal counter
counter = counter + 1
mylabel.config(text=str(counter))
mylabel.after(50, counting)
counting()
# main program
root = Tk()
root.title('Python GUI - Label counter')
root.geometry("{}x{}+200+240".format(640, 480))
root.configure(bg='#ddddff')
# label object
digit_label = Label(root,
bg = "seagreen",
fg = 'white',
height = 3,
width = 10,
font = "Helvetic 30 bold")
digit_label.pack()
start_counting(digit_label)
root.mainloop()
|
86c1db89b3397a93110f1c8f4ca4a1e48c042748 | 2017100235/Mix---Python | /Skill curso em video - Python - mundo 2/desafio 65.py | 494 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jun 24 00:34:42 2019
@author: juan
"""
soma = maior = menor = num = int(input('Numero: '))
cont = 1
resp = str(input('Quer continuar [S/N]: '))
while (resp.lower()=='s'):
num = int(input('Numero: '))
if num > maior:
maior = num
if num < menor:
menor = num
soma +=num
cont+=1
resp = str(input('Quer continuar [S/N]: '))
print('''
Media = {}
Maior = {}
Menor = {}
'''. format(soma/cont,maior,menor))
|
b7a333a93c492c59d08235bd9350af3057c5b06c | ananda-wahyu-nur-said/I0320124_Ananda-Wahyu-Nur-said_Aditya-Mahendra_Tugas4 | /I0320124_Exercise4.9.py | 98 | 3.609375 | 4 | #Exercise 4.9
#string
str = "Hello World"
#substring
substr = str[3:5]
#Otput
print(substr) |
13e2c50f46462545cdf58cb78c0c14e6add57330 | rafaelperazzo/programacao-web | /moodledata/vpl_data/310/usersdata/278/84210/submittedfiles/investimento.py | 276 | 3.5 | 4 | # -*- coding: utf-8 -*-
from __future__ import division
#COMECE SEU CODIGO AQUI
ii = float(input("Digite o valor do investimento inicial: " ))
cp = float(input("Digite a taxa de crescimento percentual [0,1]: "))
t=1
m=0
while (t<=10):
total = ii*(1+cp)+m
print(total) |
f6923d07c5006ccc9777822f320b57c43d0de333 | JamesDoane/practical_python_practice | /num_guess_game.py | 843 | 4.03125 | 4 | import random
def the_game():
num_to_guess = random.randint(1,100)
player_name = input("What's your name?\n")
player_guess = int(input(player_name + ", I'm thinking of a number between 1-100.\nGuess my number:\n"))
counter = 1
while player_guess != num_to_guess:
if player_guess > num_to_guess:
print("your guess is too high. try again.")
player_guess = int(input("New guess?\n"))
counter+=1
else:
print("your guess is too low. try again.")
player_guess = int(input("New guess?\n"))
counter+=1
print("Congratulations", str(player_name), "the number was",str(num_to_guess)+ "! It took you",counter,"attempts.")
repeater = input("Would you like to play again? y/n\n")
if repeater == "y":
the_game()
the_game() |
7c441a727489fca80448b861b583a35461ab9f5d | pythonnewbird/LeetCodeSolution | /6.13/99.恢复二叉搜索树hard.py | 802 | 3.890625 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def __init__(self):
self.pre=None
self.p1=None
self.p2=None
def inorder(self,root):
if not root: return
self.inorder(root.left)
if self.pre and root.val<self.pre.val:
if not self.p1:
self.p1=self.pre
self.p2=root
self.pre=root
self.inorder(root.right)
def recoverTree(self, root):
"""
:type root: TreeNode
:rtype: void Do not return anything, modify root in-place instead.
"""
self.inorder(root)
self.p1.val,self.p2.val=self.p2.val,self.p1.val |
910d0f82585e466e0fe03549fdcb535cd6d1e83a | udayt-7/Python-Assignments | /Assignment_1_Basic_Python/s1p21.py | 252 | 4.125 | 4 | #to Calculate the Number of Upper Case Letters and Lower Case Letters in a String
i = input("Enter the string:")
c1=0
c2=0
for ch in i:
if (ch.isupper()):
c1+=1
if (ch.islower()):
c2+=1
print("Uppercase: ",c1)
print("Lowercase: ",c2) |
40470fa87486b21d6978617399824595e4aba44a | daivikvennela/python-udemy | /EZGrader.py | 240 | 3.828125 | 4 | Correct = eval(input("Total Correct: "))
#Total = eval(input("Total Problems: "))
Total = 65
Result = round((Correct/Total)*100,2)
print(Result, "%")
if Result >= 73 :
print("You passed, Congrats!")
else :
print("You failed")
|
dcbd61300fd8da1f75646f0b328158ce6099fc4b | z2labplus/algorithm-python | /algorithm/sort/basic_sort.py | 3,400 | 4 | 4 | """
python3.6.4
@Date : "2018-10-15"
@Author :"HerryZhang"
#Reference :https://time.geekbang.org/column/article/41802
"""
def bubble_sort(raw_list):
"""
冒泡排序
"""
flag = False
list_len = len(raw_list)
for i in range(list_len):
for j in range(list_len - i - 1):
if raw_list[j] > raw_list[j + 1]:
tmp = raw_list[j]
raw_list[j] = raw_list[j + 1]
raw_list[j + 1] = tmp
flag = True
if not flag:
break
return raw_list
def insertion_sort(raw_list):
"""
插入排序
"""
list_len = len(raw_list)
if list_len <= 1:
return
for i in range(1, list_len):
value = raw_list[i] # 1
for j in range(i, -1, -1):
if raw_list[j - 1] > value:
raw_list[j] = raw_list[j - 1]
else:
break
raw_list[j] = value
return raw_list
def selection_sort(raw_list):
"""
选择排序
"""
list_len = len(raw_list)
end_border = list_len - 1
for i in range(end_border):
sub = i
for j in range(i + 1, list_len):
if raw_list[sub] > raw_list[j]:
sub = j
raw_list[i], raw_list[sub] = raw_list[sub], raw_list[i]
return raw_list
def merge_sort(raw_list):
"""
归并排序
"""
if len(raw_list) <= 1:
return raw_list
mid = len(raw_list) // 2
left = merge_sort(raw_list[:mid])
right = merge_sort(raw_list[mid:])
return merge(left, right)
def merge(left, right):
pre = 0
off = 0
res = []
while pre < len(left) and off < len(right):
if left[pre] <= right[off]:
res.append(left[pre])
pre = pre + 1
else:
res.append(right[off])
off = off + 1
res += left[pre:]
res += right[off:]
return res
def quick_sort(items):
"""
快速排序
"""
if len(items) <= 1:
return items
left = []
right = []
pivot = items.pop()
for num in items:
if num > pivot:
right.append(num)
else:
left.append(num)
return quick_sort(left) + [pivot] + quick_sort(right)
def bucket_sort(items):
"""
桶排序
"""
maxs = max(items)
result = [0 for i in range(maxs + 1)]
res = []
for i in items:
result[i] = result[i] + 1
for i in range(maxs + 1):
for j in range(result[i]):
res.append(i)
return res
def counting_sort(items):
"""
计数排序
"""
maxs = max(items)
c = [0 for i in range(maxs + 1)]
for i in items:
c[i] = c[i] + 1
for i in range(1, maxs + 1):
c[i] = c[i - 1] + c[i]
res = [0 for i in range(len(items))]
for i in items[::-1]:
res[c[i] - 1] = i
c[i] = c[i] - 1
return res
def radix_sort(items):
"""
基数排序
Least Signficant Digit First(LSD)
"""
size = len(str(max(items)))
tmp = [[] for i in range(10)]
n = 1
for i in range(size):
res = []
for single in items:
m = single // n % 10
tmp[m].append(single)
for i in range(10):
for s in tmp[i]:
res.append(s)
items = res
tmp = [[] for i in range(10)]
n = 10 * n
return res
|
5dcc3a6fe3e9699ca03c05db59813a41961b5a27 | xioperez01/holbertonschool-higher_level_programming | /0x02-python-import_modules/2-args.py | 364 | 3.609375 | 4 | #!/usr/bin/python3
if __name__ == "__main__":
import sys
imput = len(sys.argv) - 1
if imput == 1:
print("{} argument:".format(imput))
elif imput == 0:
print("{} arguments.".format(imput))
else:
print("{} arguments:".format(imput))
for i in range(imput):
print("{}: {}".format(i + 1, str(sys.argv[i + 1])))
|
2de37bf6e52364dc8f53a84305a9a838ffe66f49 | smuhit/2019-advent-code | /day-01/solver.py | 379 | 3.6875 | 4 |
data = open('input').read().split()
# PART 1
fuel = 0
for datum in data:
fuel += int(datum) // 3 - 2
print('Fuel needed is', fuel)
# Part 2
fuel = 0
for datum in data:
fuel_needed = int(datum) // 3 - 2
fuel += fuel_needed
while fuel_needed > 5:
fuel_needed = int(fuel_needed) // 3 - 2
fuel += fuel_needed
print('Actual Fuel needed is', fuel) |
0faf9ec3892740cf45f0f36508b3410e8a53f1b6 | Leetcode-tc/Leetcode | /python/500/Keyboard_Row.py | 1,021 | 3.671875 | 4 | class Solution(object):
def findWords(self, words):
"""
:type words: List[str]
:rtype: List[str]
"""
wordList = ['QWERTYUIOP', 'ASDFGHJKL', 'ZXCVBNM']
res = []
for x in words:
line = 0
for i in range(3):
if x[0].upper() in wordList[i]:
line = i
break
flag = True
for c in x:
if c.upper() not in wordList[line]:
flag = False
break
if flag:
res.append(x)
return res
class Solution(object):
def findWords(self, words):
"""
:type words: List[str]
:rtype: List[str]
"""
wordList = [set('QWERTYUIOP'),set('ASDFGHJKL'),set('ZXCVBNM')]
res = []
for x in words:
for y in wordList:
if set(x.upper()) <= y:
res.append(x)
break
return res |
7cd9545035216117ec9f87af1746090dd3872075 | iWonder118/atcoder | /python/ABC192/B.py | 346 | 3.8125 | 4 | import string
word = list(input())
odd_count = 0
even_count = 0
for i in range(len(word)):
if (i + 1) % 2 == 1 and word[i] in string.ascii_lowercase:
odd_count += 1
elif (i + 1) % 2 == 0 and word[i] in string.ascii_uppercase:
even_count += 1
if odd_count + even_count == len(word):
print("Yes")
else:
print("No")
|
63503e5276c6a9b5dcd4bf8b34864eb1bc101199 | fedalza/lighthouse-data-notes | /Week_4/Day_5/.ipynb_checkpoints/question_04-checkpoint.py | 1,031 | 3.984375 | 4 | """
- Connect to the hr.db (stored in supporting-files directory) with sqlite3
- Write a query to get the department name and number of employees in the department.
- Sort the data by number of employees starting from the highest.
Expected columns:
- department_name
- number_of_employees
Notes:
- Use tables employees and departments
- You can connect to DB from Jupyter Lab/Notebook, explore the table and try different queries
- In the variable 'SQL' store only the final query ready for validation
"""
import sqlite3 as sqlite
from sqlalchemy import create_engine
import pandas as pd
SQL = """ SELECT d.department_name, count(e.employee_id) as number_of_employees from departments as d
JOIN employees as e
ON d.department_id = e.department_id
GROUP BY department_name
ORDER BY number_of_employees DESC
"""
with create_engine('sqlite:///supporting_files/hr.db').connect() as con:
df = pd.read_sql(SQL, con)
con.close() |
2486fa5e6ea3a7f2cb21504dc06aa731e45767e6 | Aasthaengg/IBMdataset | /Python_codes/p03068/s698180922.py | 148 | 3.5 | 4 | N = int(input())
S = [str(x) for x in input()]
K = int(input())
for a in range(N):
if not S[a] == S[K - 1]:
S[a] = '*'
print(''.join(S)) |
d11e38226320958613cd73e7d270db517e3eaff9 | llgeek/leetcode | /37_SudokuSolver/solution.py | 2,424 | 3.640625 | 4 | """
wrong ans
"""
from typing import List
class Solution:
def solveSudoku(self, board: List[List[str]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
if not any(board) or len(board) != 9 or len(board[0]) != 9:
return
self.solver(board)
def solver(self, board):
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j] == '.':
for c in range(1, 10):
c = str(c)
if self.valid(board, i, j, c):
board[i][j] = c
if self.solver(board):
return True
else:
board[i][j] = '.'
return False
return True
def valid(self, board, row, col, c):
for i in range(len(board)):
if board[i][col] == c:
return False
for j in range(len(board[0])):
if board[row][j] == c:
return False
for i in range(row // 3 * 3, row // 3 * 3 + 3):
for j in range(col // 3 * 3, col // 3 * 3 + 1):
if board[i][j] == c:
return False
return True
if __name__ == "__main__":
sol = Solution()
board = [["5","3",".",".","7",".",".",".","."],["6",".",".","1","9","5",".",".","."],[".","9","8",".",".",".",".","6","."],["8",".",".",".","6",".",".",".","3"],["4",".",".","8",".","3",".",".","1"],["7",".",".",".","2",".",".",".","6"],[".","6",".",".",".",".","2","8","."],[".",".",".","4","1","9",".",".","5"],[".",".",".",".","8",".",".","7","9"]]
sol.solveSudoku(board)
print(board)
# board = [["5","3","1","6","7","8","9","2","4"],["6","7","2","1","9","5","3","4","8"],["1","9","8","3","4","7","5","6","2"],["8","1","9","7","6","2","4","5","3"],["4","2","6","8","5","3","7","9","1"],["7","5","3","9","2","4","8","1","6"],["9","6","4","5","3","1","2","8","7"],["2","8","7","4","1","9","6","3","5"],["3","4","5","2","8","6","1","7","9"]]
# for i in range(len(board)):
# for j in range(len(board[0])):
# c = board[i][j]
# board[i][j] = '.'
# if not sol.valid(board, i, j, c):
# print(i, j, c)
# print('falid')
# board[i][j] = c |
55168870a72cb358ad548f8253d7f5436b4275d5 | gomtarus/KH_QClass | /Workspaces09_Python/Python00/opr.py | 852 | 3.96875 | 4 | # 산술연산
a = 21
b = 2
print(a + b)
print(a - b)
print(a * b)
print(a ** b) # a의 b승
print(a / b)
print(a // b) # 몫 (floor division)
print(a % b)
# 비교연산
a, b = 5, 3
print(a == b)
print(a != b)
print(a > b)
print(a >= b)
print(a is b)
print(a is not b)
# 범위연산
list01 = list(range(100)) # 0 ~ 99
print(list01)
# [start: end] -> start ~ end-1
# [start: end: step] -> start ~ end-1까지 step만큼씩
print(list01[12: 50])
print(list01[12: 49: 3])
start01 = 'Hello World!'
# H 출력
print(start01[0])
# Hello 출력
print(start01[0:5])
# World 출력
print(start01[6:11])
# World! 출력
print(start01[6: ])
# ! 출력
print(start01[-1])
print(start01[-1: ])
print(start01[: -1])
print(start01[:: -1])
# in, not in
start02 = [1, 2, 3, 4, 5, 6]
print(3 in start02)
print(6 not in start02)
print(9 not in start02)
|
5c44dd3664e533ec2f3222d4f1853679227d1c79 | muchikon/Curso-python | /Objetos5.py | 773 | 3.75 | 4 | class Persona():
def __init__(self,nombre,edad,lugar_residencia):
self.nombre=nombre
self.edad=edad
self.lugar_residencia=lugar_residencia
def descripcion(self):
print("Nombre: ",self.nombre," Edad: ",self.edad," Residencia: ",self.lugar_residencia)
class Empleado(Persona):
def __init__(self,salario,antiguedad,nombre_empleado,edad_empleado,residencia_empleado):
super().__init__(nombre_empleado,edad_empleado,residencia_empleado) #super llama metodos de la otra clase
self.salario=salario
self.antiguedad=antiguedad
def descripcion(self):
super().descripcion()
print(" Salario: ",self.salario," Antiguedad: ",self.antiguedad)
Antonio=Persona("Antonio",45,"Portugal")
Jose=Empleado(1500,15,"Jose",35,"Italia")
Antonio.descripcion()
Jose.descripcion() |
8b3c5d4317b91028e765182667ff4404d8fbf875 | RoundingExplorer/rock-paper-scissor | /game/main.py | 856 | 3.921875 | 4 | import random
import os
no_of_games = 3
games_played = 0
choices = ['rock' , 'paper' , 'scissor']
def rock():
computer_choice = random.choice(choices)
if computer_choice == 'paper':
print("Computer wins")
games_played = games_played + 1
else:
print("You win")
games_played = games_played + 1
return rock()
def paper():
computer_choice = random.choice(choices)
if computer_choice == 'scissor':
print("Computer wins")
games_played = games_played + 1
else:
print("You win")
games_played = games_played + 1
return paper()
def scissor():
computer_choice = random.choice(choices)
if computer_choice == 'rock':
print("Computer wins")
games_played = games_played + 1
else:
print("You win")
games_played = games_played + 1
return scissor()
|
ab463c8e4ab203f5f8b45c93c88a3c511bf30ddd | yakobie/homework | /exercise 11/eleventh.py | 304 | 4 | 4 | num = int(raw_input("How many fibbonaci numbers would you like to generate?:"))
def fibnum(amt):
loop = 0
first = 0
second = 1
next = 0
while loop < amt:
loop += 1
if loop <= 1:
next = loop
else:
next = first + second
first = second
second = next
print(next)
fibnum(num)
|
e7a8e3081761561f5f5658d36f1026f9fb1cb478 | vaishnavinalawade/Python-Programs | /Find_Armstrong_Number.py | 254 | 4.28125 | 4 | /*
* problem description : program to find if the given number is an armstrong number
*/
n = int(input("Enter the number:"))
t = n
s = 0
while t>0:
r = t%10
s += r**3
t //= 10
if n == s:
print "{x} is an Armstrong number".format(x = n)
|
b7877042a7467dc14cedf32dc116c082cec88e06 | caesarii/learning-python | /chapter-26/first-class.py | 413 | 3.515625 | 4 |
class FirstClass:
def setData(self, value):
self.data = value
def display(self):
print(self.data)
x = FirstClass()
y = FirstClass()
x.setData('caesar')
x.display()
x.data = 'new name'
x.display()
y.setData('qinhge')
y.display()
class SecondClass(FirstClass):
def display(self):
print('Current value = "%s"' % self.data)
z = SecondClass()
z.setData("sdjfkl")
z.display() |
c21dd6f27f9e4b5386570439dd091ae79c28aec9 | jakszewa/Python-Notes | /Examples/what_is_if_name_and_main.py | 1,283 | 4.34375 | 4 | #What is the meaning of 'if __name__ == '__main__':
#let see what is __name__ by default
print('This is first module ' + __name__)
#Other way of writing
print("First Module's Name: {}".format(__name__))
'''
OUTPUT: __main__
what is happening over here?
When python run any code it sets a few special variables
__name__ is one of those special variables
When python runs a python file directly(not imported through another file)
it sets this __name__ variable equal to __main__
thats what we are doing, we are running this code from the file itself not
through some other file(s)
We can also import this file then the __name__ variable will be set to file name
Example:
first_module.py
print('This is first module ' + __name__)
second_module.py
import first_module
RUN: python3 second_module.py
OUTPUT: first_module
This is happening because the file is not run directly but its imported by some other file.
'''
def main():
print("First Module's Name: {}".format(__name__))
if __name__ == "__main__": # we are checking if this file is directly run by python or imported via some other file
main()
'''
if you want to run main() from first_module.py in second_module.py do below
import first_module
first_module.main()
'''
|
d253f1ad88d60d1e9e0990ed5a0120ff3cc5eb83 | JaD33Z/random-functions-reference-solutions-cheat-sheet | /main.py | 6,246 | 4.09375 | 4 | ########## SPARE-PARTS ##########
########## MY BIN OF RANDOM FUNCTIONS FOR VARIOUS THINGS ###############
######## A PYTHON PROBLEM-SOLVING SOLUTIONS REFERENCE SHEET ##################
############## RETURNING STRINGS:
def greet(name):
return ("Hello, " + name + " how are you doing today?")
####### FIZZ-BUZZ QUESTION:
def fizz_buzz():
for i in range(1, 100):
if i % 3 == 0:
print("fizz")
if i % 5 == 0:
print("buzz")
if i % 3 and i % 5 == 0:
print("fizz-Buzz")
else:
print(i)
############ CONVERT NUMBER TO DOLLARS AND CENTS:
def format_money(amount):
if amount >= 0:
return '${:.2f}'.format(amount)
###### CREATE A PHONE NUMBER:
#Function that accepts an array of 10 integers
# (between 0 and 9), that returns a string of those numbers
# in the form of a phone number.
def create_phone_number(n):
one = "".join(map(str, n[:3]))
two = "".join(map(str, n[3:6]))
three = "".join(map(str, n[6:]))
return f"({one}) {two}-{three}"
########### MULTIPLY:
def multiply(a, b):
multiply = a * b
return multiply
######## CAPITALIZE A STRING:
capitalize_word = str.capitalize
###### FUNCTION TO CAPITALIZE STRING:
def capitalize_word(word):
return word.title()
####### IS IT EVEN?:
def is_even(n):
return n % 2 == 0
########### ABREVIATE A TWO WORD NAME:
def abbrevName(name):
final_name = []
name_list = name.split()
for n in name_list:
final_name.append(n[0].upper())
return ".".join(final_name)
###### SUM OF SINGLE ITEMS IN ARRAY:
def repeats(arr):
return sum([ num for num in arr if arr.count(num) == 1])
#### NUMBERING LETTERS A-Z THEN ADDING THE SUM 0F CHOSEN WORD/STRING:
# EXAMPLE: a=1, b=2, etc.
def words_to_nums(s):
return sum(ord(letter) - 96 for letter in s)
######## QUARTER OF THE YEAR:
# Given a month as an integer from 1 to 12,
# return to which quarter of the year it belongs as an integer number.
def quarter_of(month):
if month >= 1 and month < 4:
return 1
elif month >= 4 and month < 7:
return 2
elif month >= 7 and month < 10:
return 3
else:
return 4
######## REMOVE CONSECUTIVE DUPLICATE WORDS:
import string
from itertools import groupby
def remove_consecutive_duplicates(s):
return " ".join([x for x, y in groupby(s.split())])
##### ALTERNATE CASE:
# switch every letter in string from upper to lower
# and from lower to upper. E.g: Hello World -> hELLO wORLD
def alternateCase(s):
return s.swapcase()
######## REPEAT STRING N TIMES:
# repeats the given string exactly "count" times.
def repeat_str(repeat, string):
return repeat * string
######### RETURN EVEN NUMBERED CHARACTERS OF A STRING:
# function that returns a sequence (index begins with 1)
# of all the even characters from a string
def even_chars(st):
if len(st) > 1 and len(st) < 100:
return list(st[1::2])
else:
return "invalid string"
##### DETECTING IF PANGRAM OR NOT:
# A pangram is a sentence that contains every single letter
# of the alphabet at least once. For example,
# the sentence "The quick brown fox jumps over the lazy dog" is a pangram,
# because it uses the letters A-Z at least once.
from collections import Counter
def scramble(s1, s2):
letters = Counter(s1)
word = Counter(s2)
diff = word - letters
return len(diff) == 0
########## REMOVES VOWELS FROM STRINGS, MAKES ACRONYM:
def string_task(s):
s = s.lower()
return ''.join('.'+ i for i in s if i not in 'aeiouy')
###################### ARRAYS AND LIST RELATED ########################
########## GET NAME BY INDEX NUMBER: DICTIONARIES, KEY, VALUE.
def get_planet_name(id):
return {1: "Mercury",
2: "Venus",
3: "Earth",
4: "Mars",
5: "Jupiter",
6: "Saturn",
7: "Uranus",
8: "Neptune",
}.get(id)
########## DIFFERENCE BETWEEN OLDEST AND YOUNGEST IN A GROUP:
def difference_in_ages(ages):
age = sorted(ages)
return (age[0], age[-1], (age[-1] - age[0]))
####### SHORT STRING/LONG STRING/SHORTSTRING: SORTING, ALGORITHMS:
# EXAMPLE: ('1', '22') = '1221'
def solution(a, b):
if len(a) > len(b):
return b + a + b
elif len(a) < len(b):
return a + b + a
######## RETURN SUM OF ALL POSITIVE NUMBERS IN A LIST:
import math
def positive_sum(arr):
return sum(x for x in arr if x > 0)
######### VOWEL COUNT: COUNTING SPECIFIC ITEMS IN STRING/LIST:
def get_count(input_str):
num_vowels = 0
for i in input_str:
if i == 'a' or i == 'e' or i == 'i' or i == 'o' or i == 'u':
num_vowels = num_vowels + 1
return num_vowels
####### CHECK LIST/ARRAY FOR A SPECIFIC VALUE:
def check(seq, elem):
if elem in seq:
return True
else:
return False
########## FINDING FIRST NON-CONSECUTIVE ITEM IN AN ARRAY:
def first_non_consecutive(arr):
for i in range(1, len(arr)):
if arr[i] - arr[i - 1] > 1:
return arr[i]
# ############ CONSECUTIVE NUMBERS:
# You are given a list of unique integers arr, and two integers a and b.
# Check whether or not a and b appear consecutively in arr,
# and return a boolean value.
def consecutive(arr, a, b):
x = arr.index(a)
y = arr.index(b)
return abs(x-y) == 1
######### ARRAY PLUS ARRAY:
def array_plus_array(arr1, arr2):
num = sum(arr1) + sum(arr2)
return num
########### TOTAL AMOUNT OF POINTS IN EACH GAME:
# The result of each match look like "x:y". Results of all
# matches are recorded in the collection.
# For example: ["3:1", "2:2", "0:1", ...]
def points(a):
return sum((x >= y) + 2 * (x > y) for x, y in (s.split(":") for s in a))
############# FINDING THE ITEM THAT OCCURRS ODD NUMBER OF TIMES IN AN ARRAY:
# Given an array of integers, find the one that appears an odd number of times.
def find_it(seq):
seq_size = len(seq)
for i in range(0, seq_size):
count = 0
for j in range(0, seq_size):
if seq[i] == seq[j]:
count += 1
if (count % 2 != 0):
return seq[i]
return -1 |
cdc76de467aec8a1ca98e96ba9c827af650caa63 | Zchhh73/Python_Basic | /chap15_sql/db_connect.py | 1,021 | 3.59375 | 4 | import pymysql
connection = pymysql.connect(host='localhost',
user='root',
password='1234',
database='MyDB',
charset='utf8')
# 有条件查询
# select name,userid from user where userid > ? order by userid
'''
try:
with connection.cursor() as cursor:
# 执行sql操作
sql = 'select name,userid from user where userid > %(id)s'
cursor.execute(sql, {'id': 0})
# 提取结果集
result_set = cursor.fetchall()
for row in result_set:
print('id : {0}-name:{1}'.format(row[1], row[0]))
finally:
connection.close()
'''
# 无条件查询
try:
with connection.cursor() as cursor:
sql = 'select max(userid) from user'
cursor.execute(sql)
#提取一条数据
row = cursor.fetchone()
if row is not None:
print('最大用户id:{0}'.format(row[0]))
finally:
connection.close()
|
d062298505618adcdf47314b6ad7f77b8b25d4cc | saadbinmanjur/CodingBat-Codes | /Logic-2/close_far.py | 431 | 3.796875 | 4 | # Given three ints, a b c, return True if one of b or c is "close" (differing
# from a by at most 1), while the other is "far", differing from both other
# values by 2 or more.
def close_far(a, b, c):
return (is_close(a, b) and is_far(a, b, c)) or \
(is_close(a, c) and is_far(a, c, b))
def is_close(a, b):
return abs(a - b) <= 1
def is_far(a, b, c):
return abs(a - c) >= 2 and abs(b - c) >= 2
|
0775cd34abbcfb8c2c25492af8b2628c642bd9ed | jjb33/PyFoEv | /Chapter09/exercise.py | 1,214 | 4.34375 | 4 | """
Write a program that categorizes each mail message by
which day of the week the commit was done. To do this look for lines
that start with “From”, then look for the third word and keep a running
count of each of the days of the week. At the end of the program print
out the contents of your dictionary (order does not matter).
"""
daycounts = {}
f=0
l = 0
while f == 0:
try:
fname = input('What\'s the name of the txt file? (No extention. Press Ctrl+c to quit)')
fhand = open('R:\\OneDrive\\PythonProjects\\InputOutput\\Input\\' + fname + '.txt')
print('File available. Working...')
f = 1
except:
print('Could not find file. Please try again')
for line in fhand:
l += 1
#print('Trying line', l)
if line.startswith('From '):
print('Found on line', l)
line = line.strip()
words = line.split()
day = words[2]
if day not in daycounts:
daycounts[day] = 1
else:
daycounts[day] += 1
print(daycounts)
# define a dictionary
# find the lines starting with From
# strip lin
# split line
# get 3rd word
# if its not in dict its count is one, otherwise count is +=1
# print dict
|
b9f1bf0c6e412df48695e7ea1442cc6ecf53bb73 | nancyletranx3/employment_mgmt_system | /employment_mgmt_sys_two.py | 6,852 | 3.671875 | 4 | # CS/IS-151 Spring 2020
# Nancy Tran
# Phase 2
import pickle as p
def main():
intro()
file_name = 'employee.dat'
db = load(file_name)
exit = False
while not exit:
print("Main Menu:")
print("1. Add an Employee")
print("2. Find an Employee (By Employee ID)")
print("3. Find an Employee (By Name)")
print("4. Delete an Employee")
print("5. Display Statistics")
print("6. Display All Employees")
print("7. Exit")
selection = False
while not selection:
user_input = input("Enter you selection (1..7):\n")
if (user_input == '1'):
emp_id = input("Enter an Employee ID or QUIT to stop:")
if (emp_id.lower() != "quit"):
emp_id = int(emp_id)
if (emp_id in db):
print("This employee ID has already been taken. Please try again.")
pass
else:
db[emp_id] = {}
db[emp_id]["name"] = input("\nEnter employee name:")
db[emp_id]["dept"] = input("\nEnter employee department:")
db[emp_id]["title"] = input("\nEnter employee title:")
db[emp_id]["salary"] = float(input("\nEnter employee salary:\n"))
selection = True
elif (user_input == '2'):
emp_id = input("Enter an Employee ID or QUIT to stop:")
if (emp_id.lower() != "quit"):
emp_id = int(emp_id)
if (emp_id in db):
print("\nEmployee ID:", emp_id)
print("\tName:", db[emp_id]["name"])
print("\tDepartment:", db[emp_id]["dept"])
print("\tTitle:", db[emp_id]["title"])
print("\tSalary:", format(db[emp_id]["salary"], ",.2f"))
selection = True
else:
print("Employee ID: " + emp_id + " was not found in the database.")
selection = True
emp_id = input("Enter an Employee ID or QUIT to stop:\n")
elif (user_input == '3'):
emp_name = input("Enter an employee name or QUIT to stop:")
count = 0
if (emp_name.lower() != "quit"):
for key, value in db.items():
if (emp_name in value["name"]):
count =+ 1
print("\nFound", count, "employee with that name.")
print("Employee ID:", key)
print("\tName:", value["name"])
print("\tDepartment:", value["dept"])
print("\tTitle:", value["title"])
print("\tSalary:", format(value["salary"], ",.2f"))
selection = True
else:
print("Employee Name: " + emp_name + " was not found in the database.")
elif (user_input == '4'):
delete_emp_id = input("Enter an Employee ID to delete or QUIT to stop:")
if (delete_emp_id.lower() != "quit"):
delete_emp_id = int(delete_emp_id)
try:
if (delete_emp_id == emp_id):
del db[emp_id]
except:
print("This employee was not found in the database.")
elif (user_input == '5'):
print("Department Statistics:")
departments = {"Engineering": 0}
for empid, stats in db.items():
if (stats["dept"] in departments):
departments[stats["dept"]] += 1
else:
departments[stats["dept"]] = 1
for stats, values in departments.items():
if (values == 1):
print("\tDepartment:", stats, "-", values, "employee")
print("There is", len(departments), "department in the database.")
print("There is", len(db), "employee in the database.")
selection = True
else:
print("\tDepartment:", stats, "-", values, "employees")
if (len(departments) > 1):
print("There are", len(departments), "departments in the database.")
print("There are", len(db), "employees in the database.")
selection = True
elif (user_input == '6'):
if (len(db) != 0):
for empid, stat in db.items():
print("Employee ID:", empid)
print("\tName:", db[empid]["name"])
print("\tDepartment:", db[empid]["dept"])
print("\tTitle:", db[empid]["title"])
print("\tSalary:", format(db[empid]["salary"], ",.2f"))
if (len(db) == 1):
print("There is", len(db), "employee in the database.")
else:
print("There are", len(db), "employees in the database.")
selection = True
else:
print("Employee database is empty.")
selection = True
elif (user_input == '7'):
print("Thank you for using Employee Management System (EMS)")
return
else:
print("Invalid selection.")
continue
save(db, file_name)
def intro():
print("Welcome to Employee Management System (EMS)")
def load(file_name):
try:
input_file = open(file_name, 'rb')
db = p.load(input_file)
input_file.close()
except:
print("Unable to load the database from binary file " + file_name + ".")
print("Creating an empty database.")
db = {}
return db
def save(db, file_name):
output_file = open(file_name, 'wb')
p.dump(db, output_file)
output_file.close()
return db, output_file
menu(db)
main()
|
5ecdd8a6447f34ab58f95c972891cfc0803a304c | 1411279054/Python-Learning | /Data-Structures&Althorithms/力扣算法/十月份算法题/(10.2)36. 有效的数独.py | 2,831 | 3.5625 | 4 | # class Solution:
# def isValidSudoku(self, board: list[list[str]]) -> bool:
# result = True
# matrix = [[] for i in range(1,10)] #创造九个向量:判断列是否满足条件
# matrix_nine = [[] for i in range(1, 10)] # 创造九个向量:判断九格是否满足条件
# for i in board:
# points = [] # 提取出每行点的数量
# nums = [] # 提取出每列数字的数量
# num = 0
# for j in i:
# matrix[num].append(j)
# if j == ".":
# points.append(j)
# else:
# nums.append(j)
# num = num + 1
# # 验证行是否满足条件
# if len(set(nums)) + len(nums) < 9:
# result = False
# if result == True:
# for i in matrix:
# # 验证列是否成立
# col_points = []
# col_nums = []
# for j in i:
# if j == ".":
# col_points.append(j)
# else:
# col_nums.append(j)
# if len(set(col_nums)) + len(col_nums)<9:
# result = False
# for row in range(1,9):
# for col in range(1,9):
# i = (row // 3) * 3
# j = col//3
class Solution:
def isValidSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: bool
"""
# init data
rows = [{} for i in range(9)]
columns = [{} for i in range(9)]
boxes = [{} for i in range(9)]
# validate a board
for i in range(9):
for j in range(9):
num = board[i][j]
if num != '.':
num = int(num)
box_index = (i // 3) * 3 + j // 3
# keep the current cell value
rows[i][num] = rows[i].get(num, 0) + 1
columns[j][num] = columns[j].get(num, 0) + 1
boxes[box_index][num] = boxes[box_index].get(num, 0) + 1
# check if this value has been already seen before
if rows[i][num] > 1 or columns[j][num] > 1 or boxes[box_index][num] > 1:
return False
return True
matrix = [
["5","3",".",".","7",".",".",".","."],
["6",".",".","1","9","5",".",".","."],
[".","9","8",".",".",".",".","6","."],
["8",".",".",".","6",".",".",".","3"],
["4",".",".","8",".","3",".",".","1"],
["7",".",".",".","2",".",".",".","6"],
[".","6",".",".",".",".","2","8","."],
[".",".",".","4","1","9",".",".","5"],
[".",".",".",".","8",".",".","7","9"]
]
result = Solution().isValidSudoku(matrix)
print(result) |
49bedf3b24f570d2003fbfe305193372dfc97212 | himanij11/Python---Basic-Programs | /GUI/radio_button.py | 506 | 4.09375 | 4 | import tkinter as tk
root=tk.Tk()
v=tk.IntVar()
v.set(0) #initializing the choice i.e.Python
languages=[("Python",1),("Perl",2),("Java",3),("C++",4),("C",5)]
def ShowChoice():
print(v.get())
tk.Label(root,text="""Choose your favourite programming languages:""",justify=tk.LEFT,padx=20).pack()
for val,language in enumerate(languages):
tk.Radiobutton(root,text=language,padx=20,variable=v,fg="royal blue",command=ShowChoice,value=val).pack(anchor=tk.W)
root.mainloop()
|
86b1339ede28031617e50bc76d36da6394624192 | RossouwVenter/Python-crash-course | /Chap08/Example.py | 1,431 | 3.96875 | 4 | # Functions
def pets(PetType,PetName,PetColour,PetAge):
print('\nmy pets are')
print(f'I have a {PetType}')
print(f'Her name is {PetName}')
print(f'She has {PetColour} fur')
print(f'She is still young at an age of {PetAge}')
pets('Dog','Nyla','White',f'6 months')
pets('Dog','luca','White',f'14 years')
print('\n')
def pets(PetType='Dog',PetName='Nyla',PetColour='White',PetAge=f'6 months'):
print('\nMy pets are:')
print(f'I have a {PetType}')
print(f'Her name is {PetName}')
print(f'She has {PetColour} fur')
print(f'She is still young at an age of {PetAge}')
pets()
#Optional functions
print('\n')
def customer(name,surname,favstore=''):
if favstore:
customerDetails = f'{name} {surname} favorite store is: {favstore}'
else:
customerDetails = f'{name} {surname} favorite store is: unknown'
return customerDetails.title()
customer1 = customer('John','jobs','Nike')
print(customer1)
customer2 = customer('Steve','mallic')
print(customer2)
# while loop + function
def getFullname(first_name,last_name):
full_name = f'{first_name} {last_name}'
return full_name.title()
while True:
print('\n Please tell me your name:')
print('Enter quit to quit')
f_name = input('first name: ')
l_name = input('last name: ')
formatted_name = getFullname(f_name,l_name)
if (f_name or l_name ) == "quit":
break
else:
print(f'Hello,{formatted_name}!')
# Doesnt work
# Importing an entire Module
# importing: |
f0cec744857518e4065f911639b35305b0ba31ce | Palleri-Aju/Python-files | /Experiment4.py | 6,334 | 4.46875 | 4 | '''
Experiment -4
Name :
Class: SE-IT
Div :
Roll number:
--------------------------------------
Topic : Python Tuple
Aim: Write a menu driven program to demonstrate the use of nested tuples in python
1.Display All student records
2.Search a student and display its records
3.Delete a student from the tuple
4.Sort the tuple
5.Exit
'''
import os
student=[]
def addStudentRecords():
global student
n=int(input("Enter number of students :"))
for i in range(n):
print("--------------------------------------")
r_no=int(input("Enter student roll number :"))
name=input("Enter student name :")
sub1=int(input("Enter marks in subject 1 :"))
sub2=int(input("Enter marks in subject 2 :"))
sub3=int(input("Enter marks in subject 3 :"))
templist=(r_no,name,sub1,sub2,sub3)
student.append(templist)
#print("--------------------------------------")
_ = os.system('cls')#this statement will work on windows only
print('Student Records stored in nested tuples')
global studTuple
studTuple=tuple(student)
#print(student)
print(studTuple)
'''
def studList():
x=int(input("Enter the number of students you want to enter:"))
global inp
for i in range(x):
student.append(eval(input("Enter student details \nIn the form Rollno,'Name',Marks1,Marks2,Marks3:\n")))
print(student)
'''
def searchStudent():
global studTuple
sname=input("Enter student name to be searched :")
found=False
for x in student:
if sname in x:
found=True
print("Student roll no:",x[0])
print("Student marks:",x[2:5])
if found==False:
print("Student record not found in tuple")
def deleteStudent():
global studTuple
sname=input("Enter student name to be deleted :")
found= False
for x in student:
if sname in x:
found=True
student.remove(x)
print("Record of ",sname," student deleted successfully")
studTuple=tuple(student)
if found==False:
print(sname," student not found in records ")
def sortTuple():
global studTuple
global student
print("Tuple sorted wrt Roll number:",sorted(student))
print("Tuple sorted wrt Name:",sorted(student,key=lambda x:x[1]))
#print(student)
count=0
choice=0
while(choice!=5):
if count==0:
addStudentRecords()
count+=1
print("-------------------------------------------")
print("1.Display All student records")
print("2.Search a student and display its records")
print("3.Delete a student from the tuple")
print("4.Sort the tuple")
print("5.Exit")
print("-------------------------------------------")
choice=int(input("\nEnter Your Choice: "))
if choice==1:
print(studTuple)
elif choice==2:
searchStudent()
elif choice==3:
deleteStudent()
elif choice==4:
sortTuple()
elif choice==5:
print("Thank You!!!")
exit(0)
else:
print("Invalid input")
'''
Output:
Enter number of students :4
--------------------------------------
Enter student roll number :110
Enter student name :Manish
Enter marks in subject 1 :45
Enter marks in subject 2 :56
Enter marks in subject 3 :67
--------------------------------------
Enter student roll number :105
Enter student name :Dinesh
Enter marks in subject 1 :55
Enter marks in subject 2 :66
Enter marks in subject 3 :77
--------------------------------------
Enter student roll number :108
Enter student name :Mayur
Enter marks in subject 1 :54
Enter marks in subject 2 :65
Enter marks in subject 3 :76
--------------------------------------
Enter student roll number :101
Enter student name :Rahul
Enter marks in subject 1 :87
Enter marks in subject 2 :78
Enter marks in subject 3 :45
Student Records stored in nested tuples
((110, 'Manish', 45, 56, 67), (105, 'Dinesh', 55, 66, 77), (108, 'Mayur', 54, 65, 76), (101, 'Rahul', 87, 78, 45))
-------------------------------------------
1.Display All student records
2.Search a student and display its records
3.Delete a student from the tuple
4.Sort the tuple
5.Exit
-------------------------------------------
Enter Your Choice: 1
((110, 'Manish', 45, 56, 67), (105, 'Dinesh', 55, 66, 77), (108, 'Mayur', 54, 65, 76), (101, 'Rahul', 87, 78, 45))
-------------------------------------------
1.Display All student records
2.Search a student and display its records
3.Delete a student from the tuple
4.Sort the tuple
5.Exit
-------------------------------------------
Enter Your Choice: 2
Enter student name to be searched :Rajesh
Student record not found in tuple
-------------------------------------------
1.Display All student records
2.Search a student and display its records
3.Delete a student from the tuple
4.Sort the tuple
5.Exit
-------------------------------------------
Enter Your Choice: 2
Enter student name to be searched :Rahul
Student roll no: 101
Student marks: (87, 78, 45)
-------------------------------------------
1.Display All student records
2.Search a student and display its records
3.Delete a student from the tuple
4.Sort the tuple
5.Exit
-------------------------------------------
Enter Your Choice: 3
Enter student name to be deleted :Rahul
Record of Rahul student deleted successfully
-------------------------------------------
1.Display All student records
2.Search a student and display its records
3.Delete a student from the tuple
4.Sort the tuple
5.Exit
-------------------------------------------
Enter Your Choice: 1
((110, 'Manish', 45, 56, 67), (105, 'Dinesh', 55, 66, 77), (108, 'Mayur', 54, 65, 76))
-------------------------------------------
1.Display All student records
2.Search a student and display its records
3.Delete a student from the tuple
4.Sort the tuple
5.Exit
-------------------------------------------
Enter Your Choice: 4
Tuple sorted wrt Roll number: [(105, 'Dinesh', 55, 66, 77), (108, 'Mayur', 54, 65, 76), (110, 'Manish', 45, 56, 67)]
Tuple sorted wrt Name: [(105, 'Dinesh', 55, 66, 77), (110, 'Manish', 45, 56, 67), (108, 'Mayur', 54, 65, 76)]
-------------------------------------------
1.Display All student records
2.Search a student and display its records
3.Delete a student from the tuple
4.Sort the tuple
5.Exit
-------------------------------------------
Enter Your Choice: 5
Thank You!!! |
58d91fa25fa5afe7bd4ed6c817bd135b24a545ec | priyankapadhu/python-doc | /ex3.py | 152 | 3.71875 | 4 | a=17
b=32
c=31
if(a>b)&(a>c):
print("a is greatest")
elif(b>c):
print("b is greatest")
else:
print("c is greatest")
|
b324dc0ebf997f11053c509237b3cd24b530c6e8 | gvassallo/LeetCode | /235-LowestCommonAncestor.py | 1,148 | 3.8125 | 4 | # Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
#
# According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between
# two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a
# node to be a descendant of itself).”
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if p.val > q.val:
p, q = q, p
if p.val == root.val:
return p
if q.val == root.val:
return q
p_left = self.contains(root.left, p)
q_left = self.contains(root.left, q)
if p_left and q_left:
return self.lowestCommonAncestor(root.left, p, q)
elif p_left and not q_left:
return root
else:
return self.lowestCommonAncestor(root.right, p, q)
def contains(self, root, n):
if root is None:
return False
if root.val == n.val:
return True
return self.contains(root.left, n) or self.contains(root.right, n)
|
9fc546c66dfbbedd4ae246829513f3f96c0321d4 | linmenggui/Udacity-Project-3-Data-Wrangling | /update_phone_number.py | 609 | 4.03125 | 4 | # this code is written in python 3
import re
def is_phone_number(elem):
"""
Return True if the value of the operands are equal. Return False otherwise.
"""
return elem.attrib["k"] == "phone"
def phone_fixer(phone):
"""
Return a phone number after striping its whitespaces or non-digit characters except "+" (plus symbol).
"""
phone_num = phone
join_num = "".join(phone_num.strip().split())
match_num = re.search(r"[^\d+]", join_num)
if match_num:
fix_num = re.sub(match_num.group(), "", join_num)
return fix_num
return join_num |
e80d7fde0a05a58d964bab752812a6ef43955d01 | tushar-rishav/Upwork | /pyautogui/main.py | 2,543 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Extract textual data from a given html document
sample url:
https://www.sec.gov/Archives/edgar/data/1594109/000156459015001303/grub-10k_20141231.htm
"""
from docx import Document
import openpyxl
from openpyxl import Workbook
from openpyxl.writer.write_only import WriteOnlyCell
import os
import pyautogui
from selenium import webdriver
import sys
from tkinter import Tk
from time import sleep
driver = webdriver.Firefox()
driver.implicitly_wait(40)
def browse(url):
"""
Browser handler
:param url: A url to load in browser.
"""
try:
driver.get(url)
except Exception as e:
print(e)
def load_url_from_excel(excel_file="data.xlsx"):
"""
Extract URLs from a given excel file.
:param excel_file: The excel file that contains URLs.
:return: A list of URLs.
"""
if os.path.exists(excel_file) is not None:
wb = openpyxl.load_workbook(excel_file)
sheet = wb.get_sheet_by_name('Sheet1')
return [sheet['A{}'.format(i)].value.encode('utf-8') for i in range(2,12)]
print("{} does not exists.".format(excel_file))
sys.exit(1)
def read_clipboard():
itk = Tk()
itk.withdraw()
try:
while not itk.selection_get(selection="CLIPBOARD"):
sleep(0.1)
except Exception as e:
print(e)
result = itk.selection_get(selection="CLIPBOARD")
itk.destroy()
return result
def save_doc_and_excel(filename):
"""
Create a new word doc with the given filename.
:param filename: The name of new doc.
"""
# Save doc
document = Document()
content = read_clipboard()
document.add_paragraph(content)
document.save(filename + '.doc')
# Save excel sheets
wb = Workbook(write_only=True)
ws = wb.create_sheet()
cell = WriteOnlyCell(ws, value=content)
ws.append([cell])
wb.save(filename + '.xlsx')
def main():
width, height = pyautogui.size()
URLS = load_url_from_excel()
i = 0
pyautogui.PAUSE = 1
for url in URLS:
browse(url)
pyautogui.click(x=width/3, y=height/3)
pyautogui.hotkey('ctrl', 'a') # Select all text
pyautogui.hotkey('ctrl', 'c') # Copy all text
sleep(1)
print("Saving output_{}.doc/xlsx".format(i))
save_doc_and_excel("output_{}".format(i))
i += 1
print("Closing browser")
driver.close()
print("Browser closed")
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
print("Closed") |
65e01bb60ae81d74afd8043605c0d34878eea33c | tillyoswellwheeler/module-02_python-learning | /ch08_mobile-data-bundle-programme/databundle-project/project/lib/databundle_lib.py | 2,521 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Dec 12 09:38:32 2018
@tillyoswellwheeler: 612383362
"""
#Check user state, they are registered or unregistered
class User(object):
def __init__(self, username, passcode):
self.username = username
self.passcode = passcode
def ask_user_state(self, username, passcode):
print("Are you a customer with us?")
if print == "y":
user_registered(username, passcode)
if print == "n":
user_unregistered(self)
else:
print("Invalid input")
def user_registered(username, passcode):
customer_account(username, passcode, credit)
class UnregisteredUser(object):
def user_unregistered(self, username, passcode):
print("Do you want to become a customer with us?")
if print == "y":
user_register_process(self, username, passcode)
if print == "n":
print("That's fine")
ask_user_state(self, username, passcode)
else:
print("Invalid input")
# Filler function for now
def user_register_process(self, username, passcode):
print("register now")
class RegisteredCustomer(User):
def __init__(self, username, passcode, credit):
self.username = username
self.passcode = passcode
self.credit = credit
def customer_account(username, passcode, credit):
check_username(username)
check_passcode(passcode)
check_balance(credit)
def check_username(username, system_username):
# Import database data
username = input("What's your username?")
if username == system_username:
check_passcode(passcode, system_passcode)
if username != system_username:
print("Invalid username")
else:
print("Not a valid imput")
def check_passcode(passcode, system_passcode):
# Import database data
passcode = input("What's your passcode?")
if passcode == system_passcode:
transaction_type(balance, purchase)
if passcode != system_passcode:
print("Invalid passcode")
else:
print("Not a valid imput")
#User enters username
#Users username is checked against the system
#User enters passcode
#Users passcode is checked against the system
#User selects a transaction type from a numbered list
#User is sent back to the start
|
cae4218512558bcaec98350606d1d7573fa3923b | andreinaoliveira/Exercicios-Python | /Exercicios/090 - Dicionário.py | 460 | 3.921875 | 4 | # Exercício Python 090 - Dicionário
# Faça um programa que leia nome e média de um aluno, guardando também a situação em um dicionário.
# No final, mostre o conteúdo da estrutura na tela.
aluno = {'Nome': str(input('Nome: ')).strip(),
'Média': float(input('Média: '))}
if aluno['Média'] >= 7:
aluno['Situação'] = 'Aprovado(a)'
else:
aluno['Situação'] = 'Reprovado(a)'
for i, j in aluno.items():
print(f'{i}: {j}')
|
4a4e97d18fb1663907f32703ac7914a731df9da4 | siddharth20190428/DEVSNEST-DSA | /DA018_Range_sum_of_BST.py | 1,156 | 3.703125 | 4 | """
Given the root node of a binary search tree, return the sum of values of all nodes with a value in the range [low, high].
---------------
Constraints
The number of nodes in the tree is in the range [1, 2 * 10^4].
1 <= Node.val <= 10^5
1 <= low <= high <= 10^5
All Node.val are unique.
"""
def dll(root):
if not root:
return None, None
lh, lt = dll(root.left)
rh, rt = dll(root.right)
if lh:
h = lh
lt.right = root
root.left = lt
else:
h = root
if rh:
t = rt
rh.left = root
root.right = rh
else:
t = root
return h, t
def rangeSumBST(root, low, high):
if not root:
return 0
elif root.val >= low and root.val <= high:
return (
root.val
+ rangeSumBST(root.left, low, high)
+ rangeSumBST(root.right, low, high)
)
elif root.val < low:
return rangeSumBST(root.right, low, high)
elif root.val > high:
return rangeSumBST(root.left, low, high)
root = [10, 5, 15, 3, 7, None, 18]
low = 7
high = 15
# root = [10,5,15,3,7,13,18,1,None,6]
# low = 6
# high = 10 |
ee7c20e7c32f8e88efc4cf1a688d8978cb7b959f | HossamOWL/pyhack | /Pyhack_Python/salle.py | 3,245 | 3.734375 | 4 | #!/usr/bin/python3
"""
Le fichier salle.py crée un objet Salle
en indiquant les coordonnées du point
haut_gauche de la salle, sa largeur et
sa hauteur.
"""
from random import randint, choice
from point import Point
class Salle(Point):
'''
Cette classe, qui hérite de la classe Point,
permet d'afficher des salles et les relier par
des couloirs dans un donjon représenté ici
par une liste en 2 dimensions appelée 'plateforme'
'''
def __init__(self, x, y, largeur, hauteur):
'''
Les paramètres de l'object Salle sont :
(x, y) : les coordonnées du point le plus
haut à gauche de la salle
largeur : largeur de la Salle
hauteur : hauteur de la Salle
'''
self.x = x
self.y = y
self.largeur = largeur
self.hauteur = hauteur
# Partie Salle
def afficher_salle(self, plateforme):
'''
Le fait d'afficher une salle consiste à
vider l'intérieur de l'espace contouré par
les dimensions de la salle.
La méthode prend en argument une liste et renvoie
la liste mutée.
'''
for i in range(self.y, self.y + self.hauteur + 1):
for j in range(self.x, self.x + self.largeur + 1):
plateforme[i][j] = ' '
return plateforme
# Partie Couloir
'''
Cette partie permet de lier des salles
par des couloirs aléatoires.
Nous avons conçu un couloir aléatoire
comme étant un chemin qui lie deux points
aléatoires appartenant à la bordure de deux listes.
'''
def point_bordure(self):
'''
Le point_bordure est un point aléatoire
qui appartient à la bordure de la salle.
Nord, Sud, Ouest et Est seront alors des points tirés
aléatoirement des quatres côtés de la salle.
Nous tirerons alors un point parmi ces quatre points
'''
nord = Point(randint(self.x, self.x + self.largeur), self.y)
est = Point(self.x + self.largeur, randint(self.y, self.y + self.hauteur))
sud = Point(randint(self.x, self.x + self.largeur), self.y + self.hauteur)
ouest = Point(self.x, randint(self.y, self.y + self.hauteur))
liste_points_bordure = [nord, est, sud, ouest]
return choice(liste_points_bordure)
def tracer_couloir(self, point1, point2, plateforme):
"""
Cette méthode, d'abord va tracer un couloir entre deux
points quelconques du plan, soit les deux points
point1, point2
"""
for n in range(min(point1.x, point2.x), max(point1.x, point2.x) + 1):
plateforme[point1.y][n] = ' '
for m in range(min(point1.y, point2.y), max(point1.y, point2.y) + 1):
plateforme[m][point2.x] = ' '
return plateforme
def liaison_couloir(self, salle1, plateforme):
'''
Cette méthode se sert de la méthode tracer_couloir
pour lier deux salles.
Les points choisis sont deux points_bordures des salles.
'''
point1 = self.point_bordure()
point2 = salle1.point_bordure()
self.tracer_couloir(point1, point2, plateforme)
if __name__ == '__main__':
print(8)
|
96d173eabaa882616f1af22bb64d6ad6897bf7cf | manjeet-haryani/python | /exceptionalhandling/demo.py | 534 | 3.734375 | 4 | import logging
logging.basicConfig(filename="mylog.log",level = logging.DEBUG)
try:
f = open("myfile.txt","w")
a,b = [int(x) for x in input("enter two numbers").split()]
logging.info("division in progress")
c = a/b
f.write("writing %d into the file" %c)
except :
print("Division by zero is not allowed")
print("please enter a non zero number")
logging.error("Division by zero")
else:
print("you have entered non zero number")
finally:
f.close()
print("file is closed")
print("code after the exception")
|
20c5b6cf0604d3d1c14b295cf7bc7ae19b1524d7 | poppindouble/AlgoFun | /word_pattern.py | 693 | 3.765625 | 4 | class Solution:
# def wordPattern(self, pattern, str):
# if len(pattern) != len(str.split()): return False
# ptnDict, wordDict = {}, {}
# for ptn, word in zip(pattern, str.split()):
# if ptn not in ptnDict:
# ptnDict[ptn] = word
# if word not in wordDict:
# wordDict[word] = ptn
# if wordDict[word] != ptn or ptnDict[ptn] != word:
# return False
# return True
def wordPattern(self, pattern, str):
t = str.split()
print(list(map(pattern.find, pattern)))
print(list(map(t.index, t)))
return list(map(pattern.find, pattern)) == list(map(t.index, t))
def main():
print(Solution().wordPattern("abba", "dog cat cat dog"))
if __name__ == "__main__":
main() |
d28ea6378ffb6c230b91941ee3424f800d398a0b | IvanOmel/Homework_python_cur | /chapter_03/Ex_05.py | 325 | 3.96875 | 4 |
mass = float(input("Input mass: "))
weight = mass * 9.8
if(weight >= 500):
print("weight: ", round(weight, 2), "H")
print("body is too heavy")
elif(weight <= 100):
print("weight: ", round(weight, 2), "H")
print("body is too light")
else:
print("weight: ", round(weight, 2), "H")
print("body is ok") |
eb59b50591612cc354acad2340c183a587656a7f | mayartmal/python_course | /control_1_sum_in_for_loop.py | 118 | 3.84375 | 4 | n = int(input())
sum = 0
for i in range(0, n):
your_number = input()
sum = sum + int(your_number)
print(sum)
|
2588891eab3f227667a6803af6632af17d67eae4 | BrandonJonesSDMF/PythonTutorialsForTheHomies | /7_user_input.py | 387 | 4.03125 | 4 | name = input("Enter your name: ")
age = input("Enter your age: ")
'''now lets ask for some user input, we just assigned variables to hold the user input that will be taken from the terminal'''
print("Hello " + name + "!")
print("You're " + age + "? Ha! Nice.")
'''try this with your relatives credit card information and send me the screenshots to ensure your code is working'''
|
ee19aa61d1cc42c1139e43f1c5a512e5440778c0 | wdkang123/PythonOffice | /06-pandas_study/pandas_style.py | 935 | 3.765625 | 4 | import pandas as pd
# 实例化Series对象
s1 = pd.Series([1, 2, 3], index=[1, 2, 3], name="s1")
# 输出Series对象
print(s1)
# 输出Series对象的索引
print(s1.index)
# 输出Series对象中索引为1的值
print(s1[1])
# 输出结果
'''
1 1
2 2
3 3
Name: s1, dtype: int64
Int64Index([1, 2, 3], dtype='int64')
1
'''
print("---------------")
# 创建Series对象
s1 = pd.Series([1, 2, 3], index=[1, 2, 3], name="A")
s2 = pd.Series([10, 20, 30], index=[1, 2, 3], name="B")
s3 = pd.Series([100, 200, 300], index=[1, 2, 3], name="C")
# 创建Series对象实例化DataFrame对象
df = pd.DataFrame([s1, s2, s3])
print(df)
'''
1 2 3
A 1 2 3
B 10 20 30
C 100 200 300
'''
print("---")
# 通过字典形式构建DataFrame对象
df2 = pd.DataFrame({
s1.name: s1,
s2.name: s2,
s3.name: s3
})
print(df2)
'''
A B C
1 1 10 100
2 2 20 200
3 3 30 300
'''
print("---")
|
5f4d0246867fbde7bb253868c4e8b080750728f3 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2101/60696/280529.py | 1,356 | 3.59375 | 4 | happy_nums = [1, 7, 10, 13, 19, 23, 28, 31, 32, 44, 49, 68, 70, 79, 82, 86, 91, 94, 97, 100]
unhappy_nums = [4, 16, 37, 58, 89, 145, 42, 20]
def is_happy_num(num):
if num == 0:
return False
if num < 10:
if num * num in happy_nums:
return True
elif num * num in unhappy_nums:
return False
else:
return is_happy_num(num*num)
if num < 100:
a = int(num/10)
b = num % 10
if a * a + b * b in happy_nums:
return True
elif a*a + b*b in unhappy_nums:
return False
else:
return is_happy_num(a*a + b*b)
if num < 1000:
a = int(num/100)
b = int((num%100)/10)
c = num%10
if a*a + b*b + c*c in happy_nums:
return True
elif a*a + b*b + c*c in unhappy_nums:
return False
else:
return is_happy_num(a*a + b*b + c*c)
if num < 10000:
a = int(num/1000)
b = (num%1000)/100
c = (num%100)/10
d = num%10
if a*a + b*b + c*c + d*d in happy_nums:
return True
elif a*a + b*b + c*c + d*d in unhappy_nums:
return False
else:
return is_happy_num(a*a + b*b + c*c + d*d)
if __name__ == '__main__':
n = int(input())
print(is_happy_num(n))
|
a63cfe745e79c653f327ce412571f5c1966612a3 | pacospace/Advent_of_Code | /2017/day01_Inverse_Captcha/day1part1.py | 1,383 | 3.75 | 4 | # Advent of Code - Day 1 (Part 1)
def check_match(current_element, next_element, list_matches):
print()
print('---------------------------')
print('Element number:', current_element[1] + 1)
print('Current element is:', current_element[0])
print('Next element is: ', next_element[0])
if current_element[0] == next_element[0]:
print('\n ---> Match')
list_matches.append(current_element[0])
else:
print('\n ---> No Match')
pass
return list_matches
def main():
captcha = open('captchaday1.txt')
elements = captcha.read()
list_elements = []
element_n = 0
for element in elements:
list_elements.append([int(element), element_n])
element_n += 1
print('The list of elements is:\n', list_elements)
it = 0
list_matches = []
for element in list_elements:
if it < len(list_elements) - 1:
list_matches = check_match(list_elements[it], list_elements[it + 1], list_matches)
elif it == len(list_elements) - 1:
print()
print()
print('Last element of the list')
list_matches = check_match(list_elements[it], list_elements[0], list_matches)
else:
break
it += 1
print('\n\nThe solution of the chaptcha is:', sum(list_matches))
if __name__ == '__main__':
main()
|
c52082a6ce75a26cbfdaa4e1c01bb441105f2c21 | ValerianClerc/project-euler | /p2.py | 383 | 3.78125 | 4 | evenFibs = []
a = 0
b = 1
# iterate until larger number reaches 4000000
while b < 4000000:
# if this fibonacci number is even, add to list
if (a+b)%2 ==0:
evenFibs.append(a+b)
# increment fibonacci numbers, keeping b as the larger
temp = a+b
a = b
b = temp
# sum list of even fibonacci numbers
print("ANSWER: " + str(sum(evenFibs)))
|
cc789f429a861ecaf3f865bed7652baa1afadd00 | asdfvar/gpnc | /math/ann/pyANN/ann.py | 5,532 | 3.90625 | 4 | #!/usr/bin/python3
# inputs are tensors which are defined as Python lists with dimensions like so:
# [batch, channel, 2-D numpy array]
#
# in some cases, they are expressed as [layer, batch, channel, 2-D numpy array]
import numpy as np
class ANN:
def __init__(self, layers, numChannels, actFunc, beta = 0.9):
np.random.seed (0)
self.N = len (layers)
self.numChannels = numChannels
actFuncs = {"sigmoid": self.sigmoid (beta),
"unit": self.unit () }
self.g = actFuncs[actFunc]
# the following are expressed as [layer][channel][numpy array]
self.weights = []
self.bias = []
for layer in range (len (layers)):
self.weights.append ([None] * numChannels[layer])
self.bias.append ([None] * numChannels[layer])
for layer in range (self.N - 1):
for channel in range (len (self.weights[layer])):
# weights
self.weights[layer][channel] = np.random.rand (layers[layer + 1], layers[layer])
# bias weights
self.bias[layer][channel] = np.random.rand (layers[layer + 1])
# "Input" is in the form of [batch][channel][numpy array]
def forward (self, Input):
# the following are expressed as [layer][batch][channel][numpy array]
self.psi = []
self.y = []
self.delta = []
for layer in range (self.N):
self.psi.append ([])
self.y.append ([])
self.delta.append ([])
for batch in range (len (Input)):
self.psi[layer].append ([])
self.y[layer].append ([])
self.delta[layer].append ([])
for channel in range (self.numChannels[layer]):
self.psi[layer][channel].append ([])
self.y[layer][channel].append ([])
self.delta[layer][channel].append ([])
self.y[0] = Input
for layer in range (self.N - 1):
for batch in range (len (self.y[layer])):
for channel in range (len (self.y[layer][batch])):
lweights = self.weights[layer][channel]
y = self.y[layer][batch][channel]
bias = self.bias[layer][channel]
self.psi[layer][batch][channel] = np.matmul (lweights, y) + bias
psi = self.psi[layer][batch][channel]
self.y[layer + 1][batch][channel] = self.g.activate (psi)
return self.y[self.N - 1]
# "Input" is in the form of [batch, channel, 2-D numpy array]
# "Output" is in the form of [batch, channel, 2-D numpy array]
# "stepsize" is a positive real number specifying the step size used in gradient descent
def back (self, Input, Output, stepsize):
z = self.forward (Input)
# the following are expressed as [batch][channel][numpy array]
diff = []
gamma = []
for batch in range (len (z)):
diff.append ([None])
gamma.append ([None])
for batch in range (len (self.y[self.N - 2])):
for channel in range (len (self.y[self.N - 2][batch])):
diff[batch][channel] = z[batch][channel] - Output[batch][channel]
gamma[batch][channel] = diff[batch][channel] * self.g.dactivate (self.psi[self.N - 2][batch][channel])
for layer in np.arange (self.N - 2, -1, -1):
for batch in range (len (self.y[layer])):
for channel in range (len (self.y[layer][batch])):
lweights = self.weights[layer][channel]
ldelta = self.delta[batch][channel]
# last layer
if (layer == self.N - 2):
dEdw = np.outer (gamma[batch][channel], self.y[layer][batch][channel])
lweights -= stepsize * dEdw
dEdu = gamma[batch][channel]
self.bias[layer][channel] -= stepsize * dEdu
# update delta for the next layer
self.delta[batch][channel] = np.matmul (gamma[batch][channel], lweights)
# all other interior layers
else:
# use the previously calculated delta to update the weights
LHS = np.tile (ldelta, (len (self.y[layer]), 1)).transpose ()
gp = self.g.dactivate (self.psi[layer][batch][channel])
RHS = np.outer (gp, self.y[layer])
dEdw = LHS * RHS
lweights -= stepsize * dEdw
dEdu = ldelta * gp
self.bias[layer] -= stepsize * dEdu
if layer > 0:
# update delta for the next layer
Gp = np.diag (gp)
Gpw = np.matmul (Gp, lweights)
self.delta[batch][channel] = np.matmul (ldelta, Gpw)
Error = 0.0
z = self.forward (Input)
for batch in range (len (self.y[self.N - 2])):
for channel in range (len (self.y[self.N - 2][batch])):
diff[batch][channel] = z[batch][channel] - Output[batch][channel]
Error += 0.5 * np.sum (diff[batch][channel] * diff[batch][channel])
return Error
class unit:
def activate (self, x): return x
def dactivate (self, x): return np.ones (len (x))
class sigmoid:
def __init__ (self, beta):
self.beta = beta
def activate (self, x):
return 1.0 / (1.0 + np.exp (-self.beta * x))
def dactivate (self, x):
sig = self.activate (x)
return self.beta * (1 - sig) * sig
|
b91532ea5d83e32309e784194694e144306e1842 | JosewLuis/Curso-Machine-Learning-en-Espanol | /Validación-Evaluación/utilidad.py | 6,252 | 3.59375 | 4 | #Utilidad para nuestros problemas del curso.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
def ejemplo_regresion():
from sklearn.datasets import make_regression
from sklearn.linear_model import LinearRegression
from adspy_shared_utilities import plot_two_class_knn
X,y=make_regression(n_samples=300,n_features=1,n_informative=1,noise=30,random_state=0)
X_train,X_test,y_train,y_test=train_test_split(X,y,random_state=0)
plt.figure()
plt.scatter(X,y,marker='o',s=50)
lr=LinearRegression().fit(X_train,y_train)
plt.plot(X,lr.coef_*X+lr.intercept_,'m-')
plt.title('Ejemplo regresion lineal')
def ejemplo_clasificacion():
from sklearn.datasets import make_classification
from sklearn.neighbors import KNeighborsClassifier
from adspy_shared_utilities import plot_two_class_knn
X,y=make_classification(n_samples=300,n_features=2,n_redundant=0,n_informative=2,n_clusters_per_class=1,flip_y=0.1,class_sep=0.5,random_state=0)
X_train,X_test,y_train,y_test=train_test_split(X,y,random_state=0)
plot_two_class_knn(X_train,y_train,3,'uniform',X_test,y_test)
def ejemplo_overfitting():
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
X=np.array([5,15,25,35,45,55]).reshape((-1, 1))
y=np.array([28,11,3,8,29,30])
plt.figure()
#Lineal:
plt.subplot(3,2,1)
lr=LinearRegression().fit(X,y)
plt.plot(X,y,'ro')
plt.plot(X,lr.coef_*X+lr.intercept_,'k-')
plt.title('Grado 1. R-squared={:.3f}'.format(lr.score(X,y)))
#Grado 2:
plt.subplot(3,2,2)
poly=PolynomialFeatures(degree=2)
X_poly=poly.fit_transform(X)
lr=LinearRegression().fit(X_poly,y)
plt.plot(X,y,'ro')
plt.plot(X,lr.coef_[2]*X**2+lr.coef_[1]*X+lr.intercept_,'k-')
plt.title('Grado 2. R-squared={:.3f}'.format(lr.score(X_poly,y)))
#Grado 3:
plt.subplot(3,2,5)
poly=PolynomialFeatures(degree=3)
X_poly=poly.fit_transform(X)
lr=LinearRegression().fit(X_poly,y)
plt.plot(X,y,'ro')
plt.plot(X,lr.coef_[3]*X**3+lr.coef_[2]*X**2+lr.coef_[1]*X+lr.intercept_,'k-')
plt.title('Grado 3. R-squared={:.3f}'.format(lr.score(X_poly,y)))
#Grado 5:
plt.subplot(3,2,6)
poly=PolynomialFeatures(degree=5)
X_poly=poly.fit_transform(X)
lr=LinearRegression().fit(X_poly,y)
plt.plot(X,y,'ro')
plt.plot(X,lr.coef_[5]*X**5+lr.coef_[4]*X**4+lr.coef_[3]*X**3+lr.coef_[2]*X**2+lr.coef_[1]*X+lr.intercept_,'k-')
plt.title('Grado 5. R-squared={:.3f}'.format(lr.score(X_poly,y)))
def ejemplo_logistica():
from sklearn.linear_model import LogisticRegression
X=np.array([0.5,0.7,1,1.8,2,3,3.5,4,4.5,5,5.2,5.5,6]).reshape((-1, 1))
y=np.array([0,0,0,0,0,0,1,1,1,1,1,1,1])
plt.subplot(2,1,1)
plt.plot(X,y,'ro')
plt.title('Curva para nuestro caso',x=0.3,y=0.7)
X=[0,1,2,2.2,2.4,2.6,2.8,3,3.25,3.5,4,4.5,6]
y=[0.01,0.05,0.05,0.1,0.2,0.3,0.4,0.5,0.64,0.8,0.85,0.9,0.95]
plt.plot(X,y,'k-')
def ejemplo_claslin():
X=np.arange(-2,2,0.1)
y=np.arange(-2,2,0.1)
X_1=[-2,-1.5,-1.4,-1,-1.7,-0.8,-0.6,-0.9,0,1.9]
y_1=[0,0,1,0.2,0.3,1,2,2,0.3,2]
X_2=[0,0.1,0.3,0.2,1,1.5,1.33,1.8,2,1.7]
y_2=[-2,-1.9,-1.4,-0.6,0.4,1,0.1,1.7,1,1.3]
plt.figure()
plt.plot(X_1,y_1,'ro')
plt.plot(X_2,y_2,'bo')
plt.plot(X,y,'k-')
plt.xlabel('Valor x')
plt.ylabel('Valor y')
plt.legend(['Clase 1','Clase 2','Recta de division'])
plt.title('Clasificador Lineal')
def ejemplo_nolineal():
X_1=[-6,-5,-4,0,1,2]
y_1=[0,0,0,0,0,0]
X_2=[-3,-2,-1]
y_2=[0,0,0]
plt.figure()
plt.plot(X_1,y_1,'bo')
plt.plot(X_2,y_2,'ro')
plt.legend(['Clase 1','Clase 2'])
plt.title(r'$v_i=(x_i)$')
def ejemplo_solnolineal():
from sklearn.linear_model import LinearRegression
X_1=[-6,-5,-4,0,1,2]
y_1=[n**2 for n in X_1]
X_2=[-3,-2,-1]
y_2=[n**2 for n in X_2]
xline=np.array([0,-4]).reshape((-1,1))
yline=np.array([0,16])
lr=LinearRegression().fit(xline,yline)
X=np.arange(-6,2,1)
plt.figure()
plt.plot(X_1,y_1,'bo')
plt.plot(X_2,y_2,'ro')
plt.plot(X,X*lr.coef_+lr.intercept_,'k-')
plt.legend(['Clase 1','Clase 2'])
plt.title(r'$v_i=(x_i,x_i^2)$')
def ejemplo_mascomplejo():
from sklearn.datasets import make_blobs
from matplotlib.colors import ListedColormap
cmap_bold=ListedColormap(['#FFFF00','#00FF00','#0000FF','#000000'])
X,y=make_blobs(n_samples=100,n_features=2,centers=8,cluster_std=1.3,random_state=4)
y=y%2
plt.figure()
plt.scatter(X[:,0],X[:,1],c=y,marker='.',s=50,cmap=cmap_bold)
def dibujar_knn():
print(__doc__)
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
from sklearn import neighbors, datasets
n_neighbors=5
#import some data to play with
iris=datasets.load_iris()
#we only take the first two features. We could avoid this ugly
#slicing by using a two-dim dataset
X=iris.data[:, :2]
y=iris.target
h=.02 #step size in the mesh
#Create color maps
cmap_light=ListedColormap(['#FFAAAA', '#AAFFAA', '#AAAAFF'])
cmap_bold=ListedColormap(['#FF0000', '#00FF00', '#0000FF'])
for weights in ['uniform','distance']:
#we create an instance of Neighbours Classifier and fit the data.
clf=neighbors.KNeighborsClassifier(n_neighbors,weights=weights)
clf.fit(X, y)
#Plot the decision boundary. For that, we will assign a color to each
#point in the mesh [x_min, x_max]x[y_min, y_max].
x_min,x_max=X[:,0].min()-1,X[:,0].max()+1
y_min,y_max=X[:,1].min()-1,X[:,1].max()+1
xx,yy=np.meshgrid(np.arange(x_min,x_max,h),np.arange(y_min,y_max,h))
Z=clf.predict(np.c_[xx.ravel(),yy.ravel()])
#Put the result into a color plot
Z=Z.reshape(xx.shape)
plt.figure()
plt.pcolormesh(xx,yy,Z,cmap=cmap_light)
#Plot also the training points
plt.scatter(X[:,0],X[:,1],c=y,cmap=cmap_bold,edgecolor='k',s=20)
plt.xlim(xx.min(),xx.max())
plt.ylim(yy.min(),yy.max())
plt.title("3-Class classification (k = %i, weights = '%s')"% (n_neighbors, weights))
plt.show() |
b0c56eba3ce98ef79e67ed8c04c40432933ebe10 | Algorant/HackerRank | /30_days_of_code/d09_recursion/recursion.py | 237 | 4.03125 | 4 | # Take in input n
n = int(input())
# Simple factorial function
def factorial(n):
start = 1
if int(n) >= 1:
for i in range(1, (n+1)):
start = start * i
return start
# Prints answer
print(factorial(n))
|
8a4dfd706d16db0a3a5d148d11ba2399def19641 | MAPLE-Robot-Subgoaling/IPT | /data/HW3/hw3_118.py | 940 | 4.1875 | 4 | def main():
SOLID_TEMP_CELSIUS = 0
GAS_TEMP_CELSIUS = 100
SOLID_TEMP_KELVIN = 273.15
GAS_TEMP_KELVIN = 373.15
tempNum = float(input("Please enter the temperature: "))
degreeType = input("Please enter 'C' for Celsius or 'K' for Kelvin: ")
if (degreeType == "C"):
if (tempNum <= SOLID_TEMP_CELSIUS):
print("At this temperature, water is a (frozen) solid.")
elif (tempNum > SOLID_TEMP_CELSIUS and tempNum < GAS_TEMP_CELSIUS):
print("At this temperature, water is a liquid.")
else:
print("At this temperature, water is a gas.")
else:
if (tempNum <= SOLID_TEMP_KELVIN):
print("At this temperature, water is a (frozen) solid.")
elif (tempNum > SOLID_TEMP_KELVIN and tempNum < GAS_TEMP_KELVIN):
print("At this temperature, water is a liquid.")
else:
print("At this temperature, water is a gas.")
main()
|
f4b0f89ab16954c433a3a2122bac6564cba7cb13 | Crone1/College-Python | /Year One - Semester One/Week Seven/primes-1.py | 113 | 3.546875 | 4 | #! /usr /bin/env python
total = 0
i = 0
while i < len(a):
if isprime(a[i]):
print a[i]
i = i + 1
|
350c7708a0c3f756e91936580fce7caae89f15b5 | SteeveJose/luminarpython | /pattern/dimond.py | 216 | 4.3125 | 4 | num=int(input("enter the number:"))
def function(num):
for i in range(1,num+1):
print(" " * (num-i) + ("*" + " ") * i)
for i in range(num-1,0,-1):
print(" "*(num-i)+("*"+" ")*i)
function(num) |
ef05872a0f0bc7dcb90b9807d00dbe62128ab714 | peter1314/Space-Trader | /app/py/fleable.py | 537 | 3.765625 | 4 | """file for storing the Fleable ABC"""
from abc import abstractmethod
from .npc import NPC
class Fleable(NPC):
"""Defines an NPC that can flea"""
@abstractmethod
def give_flea_reward(self, player):
"""Gives a reward to a player if the escape"""
@abstractmethod
def give_flea_punishment(self, player):
"""Hurts the player if they don't flee successfully"""
@abstractmethod
def flee(self, player):
"""Allows the player to try and flea. This method should return true if player is"""
|
f28ef5ef7796466a79f01a7976488ff91c78513e | urvib3/ccc-exercises | /hps.py | 1,752 | 3.640625 | 4 | def winner(p1, p2):
if(p1 == 1 and p2 == 2):
return True
elif(p1 == 2 and p2 == 3):
return True
elif(p1 == 3 and p2 == 1):
return True
def main():
try:
filein = open("hps.in", "r")
file = open("hps.out", "w")
print("files opened")
n = int(filein.readline())
# initialize array for plays of each cow
cow1, cow2 = [0]*n, [0]*n
print("cow1 & 2 initialized: ", cow1, cow2)
# all possible combinations
# 1. 1 > 2 > 3 > 1
# a. hoof, scissors, paper
# b. paper, hoof, scissors
# c. scisors, paper, hoof
# 2. 1 < 2 < 3 < 1
# a. paper, scissors, hoof
# b. scissors, hoof, paper
# c. hoof, paper, scissors
# read file and fill cow1 & cow2
for i in range(0,n):
set = filein.readline().split(' ')
cow1[i] = int(set[0])
cow2[i] = int(set[1])
print("files read and cow1 & cow2 filled: ", cow1, cow2)
# max times cow1 wins with combinations 1 & 2
score1, ties = 0, 0
# cycle through all sets and calculate scores in each case
for i in range(0,n):
play1 = cow1[i]
play2 = cow2[i]
if(play1 == play2):
ties += 1
elif(winner(play1, play2)):
score1 += 1
#if(score1 + (n-ties-score1) + ties != n):
#return;
# output the max score of either combination
file.write(str(max(score1, n-ties-score1)))
file.close()
except:
print("exception")
if __name__=="__main__":
main()
|
5d385e605e5ef16e61030eaa84e327efd9a76dd7 | mark-boute/AandDp1 | /common/input.py | 1,254 | 3.828125 | 4 | """
Algorithms and Data Structures
Practicum 1
Mark Boute s1038503
Mark de Jong s1034829
Subpart:
Contains functions for reading the input from the server.
"""
from common.e_print import e_print
def get_input():
"""
Read the input and insert converted input into a dictionary.
:return:
python dictionary: _input
"""
_input = dict()
_input["nodes"] = int(input())
_input["edges"] = int(input())
_input["infected"] = int(input())
_input["infect_contact"] = float(input())
low_up = input().split()
_input["lower_bound"] = int(low_up[0])
_input["upper_bound"] = int(low_up[1])
# tests:
assert _input["nodes"] >= 0
assert 0 < _input["infect_contact"] < 1
assert 0 < _input["lower_bound"] <= _input["upper_bound"]
_input["vertices"] = get_vertices(_input["edges"])
return _input
def get_vertices(edges: int):
"""
get vertices from input
:param edges: how many rows of input should be read
:return: V, list of edge tuples.
"""
vertices = []
for _ in range(edges):
vertex_input = [int(i) for i in input().split()]
if not vertex_input[0] == vertex_input[1]:
vertices.append(tuple(vertex_input))
return vertices
|
32d40bdf37f9db862521b9a34aec36e4c4daf90c | chenp-fjnu/Python | /sqlite.py | 388 | 3.875 | 4 | import sqlite3
conn=sqlite3.connect('test.db')
cursor=conn.cursor()
#print(cursor.execute('create table user (id varchar(20) primary key, name varchar(20))'))
print(cursor.execute('insert into user(id, name) values(\'1\',\'Michael\')'))
print(cursor.rowcount)
print(cursor.execute('select * from user where id=?',('1',)))
values=cursor.fetchall()
print(values)
cursor.close()
conn.close() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.