blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
378c8d17049b895f1ca536f244fa2ffb48b82d21 | csreyno/Digital-Crafts-Classes | /programming101/medium.py | 2,288 | 4.03125 | 4 | #Exercise 1
# bill = float(input("What is the bill amount?\n"))
# split = input("Split how many ways?\n")
# good = .20 * bill
# fair = .15 * bill
# bad = .10 * bill
# if service == "good":
# print(f"Tip Amount: ${good}\nTotal Amount: ${bill + good}")
# elif service == "fair":
# print(f"Tip Amount: ${fair}\nTotal Amount: ${bill + fair}")
# elif service == "bad":
# print(f"Tip Amount: ${bad}\nTotal Amount: ${bill + bad}")
# #Exercise 2 - split bill by umber of people
# bill = float(input("What is the bill amount?\n"))
# service = input("Was your service good, fair, or bad?\n")
# split = float(input("Split how many ways?\n"))
# good = .20 * bill
# fair = .15 * bill
# bad = .10 * bill
# if service == "good":
# print(f"Tip Amount: ${good}\nTotal Amount: ${bill + good}")
# if split > 1:
# print(f"Amount per person: ${(bill + good)/split}")
# elif service == "fair":
# print(f"Tip Amount: ${fair}\nTotal Amount: ${bill + fair}")
# if split > 1:
# print(f"Amount per person: ${(bill + fair)/split}")
# elif service == "bad":
# print(f"Tip Amount: ${bad}\nTotal Amount: ${bill + bad}")
# if split > 1:
# print(f"Amount per person: ${(bill + bad)/split}")
#Exercise 3
# - Write a program that will prompt you for how many coins you want.
# Initially you have no coins. It will ask you if you want a coin? If you type "yes",
# it will give you one coin, and print out the current tally.
# If you type no, it will stop the program.
# print("You have 0 coins.")
# want = input("Do you want a coin? ")
# i = 0
# if want != "yes":
# print("Bye")
# while want == "yes":
# print(f"You have {i+1} coins.")
# i += 1
# want = input("Do you want another? ")
# if want != "yes":
# print("Bye")
#Exercise 4
# width = int(input("width? "))
# height = int(input("height? "))
# if width == 1 and height == 1:
# print("*")
# else:
# i = 0
# print(width * "*")
# while i < (height -2):
# print("*"+(" " * (width - 2))+"*")
# i += 1
# print(width * "*")
#Exercise 5
#Exercise 6 - Print the multiplication table for numbers from 1 up to 10.
# i = 1
# while i < 11:
# j = 1
# while j < 11:
# print(f"{i} X {j} = {i*j}")
# j += 1
# i += 1 |
a54fe967fca959cf86c605cb5736d2db377cabc0 | ShantanuBal/Code | /cracking/ll_mergeSort.py | 1,097 | 4.0625 | 4 |
class LL():
def __init__(self, data=None, next=None):
self.data = data
self.next = next
def print_list(head):
while head != None:
print head.data," ",
head = head.next
print
def mergeList(head1, head2):
if head1 == None:
return head2
if head2 == None:
return head1
if head1.data < head2.data:
head1.next = mergeList(head1.next, head2)
return head1
else:
head2.next = mergeList(head1, head2.next)
return head2
def getListHalves(head):
slow = head
fast = head
while fast.next != None and fast.next.next != None:
slow = slow.next
fast = fast.next.next
back_head = slow.next
slow.next = None
return back_head
def mergeSort(head):
print "mergeSort: "
print_list(head)
print
if head.next == None:
return head
head_back = getListHalves(head)
head_front = head
new_head1 = mergeSort(head_front)
new_head2 = mergeSort(head_back)
new_head = mergeList(new_head1, new_head2)
print "mergedList: "
print_list(new_head)
print
return new_head
head = LL(7, LL(6, LL(5, LL(4, LL(3, LL(2, LL(1)))))))
final_head = mergeSort(head)
print_list(final_head)
|
793eeae3988b0399da1846bfa5f02aa4346a2584 | jibinsaji/coders-house-python- | /triangle_check.py | 220 | 4.15625 | 4 | a=int(input("enter the 1st side"))
b=int(input("enter the 2nd side"))
c=int(input("enter the 3rd side"))
if ((a+b)>c) or ((b+c)>a) or ((c+a)>b) :
print("is a Valid Triangle")
else:
print("is not valid Triangle")
|
0891e3015572db6a2f6e07cc642e01d472f7dbf0 | kebingyu/python-shop | /the-art-of-programming-by-july/chapter1/exercise/exer21.py | 990 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
21、最长连续字符
用递归算法写一个函数,求字符串最长连续字符的长度,比如aaaabbcc的长度为4,aabb的长度为2,ab的长度为1。
"""
def func1(word):#{{{
length = len(word)
if length:
curr_char = None
max_length = 1
curr_length = 1
for _ in word:
if curr_char == None:
curr_char = _
elif curr_char == _:
curr_length = curr_length + 1
else:
curr_char = _
if curr_length > max_length:
max_length = curr_length
curr_length = 1
return max(max_length, curr_length)
return 0
#}}}
def func2(word):#{{{
length = len(word)
if length < 2:
return length
if word[0] == word[1]:
return 1 + func2(word[1:])
return func2(word[1:])
#}}}
import sys
word = [_ for _ in sys.argv[1]]
print func1(word)
print func2(word)
|
b3261b642a6b23ef0a21a8e498041d63e729eba2 | DamianHuerta/Gatech-CS-CourseWork | /CS-1301-Python/HW05.py | 2,488 | 3.515625 | 4 | #!/usr/bin/env python3
import calendar
import statistics
"""
Georgia Institute of Technology - CS1301
HW05 - Tuples and Modules
"""
__author__ = """Damian Huerta-Ortega"""
__collab__ = """I worked on this alone"""
"""
Function name: favorite day
Parameters: dates (list of tups), weekday (int), day (int)
Returns: reduced dates (list of tups)
"""
def favorite_day(dates,weekday,day):
new = []
for thing in dates:
if calendar.weekday(thing[1],thing[0],day) == weekday:
new.append(thing)
else:
continue
return new
"""
Function name: organize_grades
Parameters: grades (list of tups), courses (list of strs)
Returns: results (list of tups)
"""
def organize_grades(grades,courses):
classes= courses
random = []
rip = []
for thing in classes:
random.append([])
for thing in grades:
a = classes.index(thing[1])
random[a].append(thing[0])
for g,w in enumerate(random):
random[g] = statistics.stdev(random[g])
for g,w in enumerate(classes):
a= round(random[g],2), classes[g]
rip.append(a)
return rip
"""
Function name: format_date
Parameters: dateList (list)
Returns: newDateList (list)
"""
def format_date(dates):
for d,h in enumerate(dates):
day = h[0]
month = h[1]
year = h[2]
dates[d] = (month, day, year)
return dates
"""
Function name: todo_tuple
Parameters: todo (list)
Returns: final_list (list)
"""
def todo_tuple(ugh,yay):
gen = []
lower = []
last = []
empty = ()
for done in yay:
lower.append(done.lower())
for g in ugh:
for w in g:
if w.lower() not in lower:
empty += (w,)
if len(empty) != 0:
last.append(empty)
empty = ()
return last
"""
Function name: no_missing_attributes
Parameters: attributeList (list of tuples)
Returns: newAttributeList (list of tuples)
"""
def no_missing_attributes(alist):
newlist = []
empty = ()
for stuff in alist:
if len(stuff) == 2:
user = stuff[0]+ str(stuff[1])
final = (stuff[0],stuff[1],user)
newlist.append(final)
else:
for rosa in stuff:
empty += (rosa,)
newlist.append(empty)
empty = ()
return newlist
|
ca00674f9c1f0a05951a869433961e5cf00c2b8b | AhmetOsmn/Programlamaya-Giris | /057.kalan_borc_hesapla.py | 207 | 3.6875 | 4 | kredi = float(input("Çekilen kredi: "))
ay = int(input("Kaç ay: "))
odenecek = kredi + (kredi*9)/100
aylık = odenecek/ay
for i in range(3):
odenecek -= aylık
print("Kalan Borcunuz: ",odenecek)
|
3969ff7aa2052a76cc92ee3226ac591bafa7bf28 | Aasthaengg/IBMdataset | /Python_codes/p02265/s217222157.py | 419 | 3.6875 | 4 | from collections import deque
x = deque()
for i in range(int(input())):
com = input()
if com == "deleteFirst":
x.popleft()
elif com == "deleteLast":
x.pop()
else:
com,n = com.split()
if com == "insert":
x.appendleft(n)
elif com == "delete":
try:
x.remove(n)
except:
pass
print(*x)
|
e8d25cdf9216dc0bc50bacaea83b22353ed3f96b | Vovchik22/Python_test | /ex20.py | 1,122 | 3.953125 | 4 | from sys import argv
script, input_file = argv # pre-start recognise script and file
def print_all(f): # read recognised file
print( f.read())
def rewind (f): # define position in file in BYTES
f.seek(0)
def print_a_line(line_count, f): # define variable number of a line and a second argument defines a line (first as a default)
print (line_count, f.readline())
current_file = open(input_file) # with this variable we open current file which recognised at pre-start script
print("Lets print a whole file: \n")
print_all(current_file) # function opened file and read it
print("Now lets rewind")
rewind(current_file) # fuction recognised position
print("lets print three lines")
current_line = 1 # variable set number 1
print_a_line(current_line, current_file) # function for each further line we add line in opened file
current_line = current_line + 1 # add a number to a line
print_a_line(current_line, current_file)
current_line = current_line + 1
print_a_line(current_line, current_file)
current_file.close() # close current file after all proceduders
|
4ce1b49e0413dfbd53aa1bb8bb5a709a333a01ca | DeshanHarshana/Python-Files | /pythonfile/findDuplicate.py | 1,145 | 3.703125 | 4 | def checkDuplicateAvailable(lst):
isDuplicate=False;
for i in lst:
if(lst.count(i)>1):
isDuplicate=True
break;
return isDuplicate
lst=[2,3,3,3,4,1,4,6,6]
print(checkDuplicateAvailable(lst))
def Repeat(x):
_size = len(x)
repeated = []
for i in range(_size):
k = i + 1
for j in range(k, _size):
if x[i] == x[j] and x[i] not in repeated:
repeated.append(x[i])
return repeated
print(Repeat(lst))
def remove_dup1(list1):
# intilize a null list
unique_list = []
# traverse for all elements
for x in list1:
# check if exists in unique_list or not
if x not in unique_list:
unique_list.append(x)
# print list
return unique_list
lst=[2,3,3,3,3,3,4,5]
print(remove_dup1(lst))
def remove_dup2(x):
return list(dict.fromkeys(x))
print(remove_dup2(lst))
lst=[1,2,2,3,4,4]
def findNonDups(lst):
nondup=[]
for i in lst:
if(lst.count(i)>1):
continue;
else:
nondup.append(i)
return nondup
print(findNonDups(lst))
|
0c387f937fbf7c1c9da8fd381e6ab586259894da | tsevans/AdventOfCode2020 | /day_3/puzzle_1.py | 1,714 | 4.28125 | 4 | # Count the number of '#' characters seen traversing a (3,1) slope on the given input.
# Implementation is O(n) time complexity and O(n) space complexity.
HORIZONTAL_INC = 3
def load_input():
"""
Load the contents of input.txt into a list.
Returns:
([str]): Lines of input.txt as a list of strings.
"""
with open("input.txt", "r") as infile:
lines = [line.rstrip() for line in infile]
return lines
def highlight_character(line, index):
"""
Print each line with character at given index highlighted.
The '.' character is highlighted green and the '#' character
is highlighted red. This function was useful for debugging.
Args:
line (str): Line to highlight.
index (int): Index of character in line to highlight.
"""
character = line[index]
color_code = 41 if character == "#" else 42
prefix = line[:index]
suffix = line[index+1:]
print("%s\x1b[6;30;%sm%s\x1b[0m%s" % (prefix, color_code, character, suffix))
def count_trees(lines):
"""
Traverse lines on the slope (HORIZONTAL_INC, 1) and count
how many trees ('#') are encountered.
Args:
lines ([str]): Slope representation to traverse.
Returns:
(int): Number of trees counted in traversal of lines.
"""
tree_count = 0
# Define rollover criteria (patterns repeat horizontally)
rollover_size = len(lines[0])
index = 1
for line in lines:
if index != rollover_size:
index %= rollover_size
highlight_character(line, index-1)
if line[index-1] == "#":
tree_count += 1
index += HORIZONTAL_INC
return tree_count
if __name__ == "__main__":
lines = load_input()
tree_count = count_trees(lines)
print("\nEncountered %s trees." % tree_count)
|
7ee8ec23a5f780e767fe12cdf323eb158b3c5b86 | ulgoon/dss-python-basic | /resources/ask_age.py | 172 | 4.125 | 4 | age = int(input("How old are you?"))
if age <= 19:
print("Kid!!!")
elif age <= 29:
print("20th!!")
elif age <= 39:
print("30th!!")
else:
print("Elder!!!")
|
4597d63c3b0d9d9473325da87a1b37efcb8cb95e | jmstudyacc/python_practice | /POP1-Exam_Revision/repl_problems/session_9/bank_account_inheritance.py | 2,377 | 3.796875 | 4 | class Person:
def __init__(self, fn, ln):
self.first_name = fn
self.last_name = ln
self.address = None
def set_address(self, addr):
self.address = addr
# BankAccount class has been created to eliminate redundancy in later account types
class BankAccount:
def __init__(self, sort_code, account_number):
self.sc = sort_code
self.an = account_number
def set_sort_code(self, sort_code):
self.sc = sort_code
def get_sort_code(self):
return self.sc
def set_account_number(self, account_number):
self.an = account_number
def get_account_number(self):
return self.an
def get_account_data(self):
return f"{self.sc} {self.an}"
class IndividualBankAccount(BankAccount):
def __init__(self, sort_code, account_number, owner):
# super() references the extension class and you then use __init__ with the params to populate
super().__init__(sort_code, account_number)
self.owner = owner
def get_account_data(self):
return f"{self.owner.first_name} {self.owner.last_name} {self.sc} {self.an}"
class SharedBankAccount(BankAccount):
def __init__(self, sort_code, account_number, owners):
super().__init__(sort_code, account_number)
self.owners = owners
def get_account_data(self):
return f"{self.owners[0].first_name} {self.owners[0].last_name}, {self.owners[1].first_name} {self.owners[1].last_name}, {self.sc} {self.an}"
john01 = Person("John", "Doe")
john01.set_address("Place")
john01_account = IndividualBankAccount("12-34-56", "12345678", john01)
# Check successful generation
assert john01_account.get_account_data() == "John Doe 12-34-56 12345678"
# Check getters & setters
john01_account.set_sort_code("22-24-26")
assert john01_account.get_sort_code() == "22-24-26"
john01_account.set_account_number("87654321")
assert john01_account.get_account_number() == "87654321"
mary01 = Person("Mary", "Ann")
mary01.set_address("Other place")
mary01_account = IndividualBankAccount("87-65-43", "98765432", mary01)
# Check mary01 account methods
assert mary01_account.get_account_data() == "Mary Ann 87-65-43 98765432"
acc02 = SharedBankAccount("11-22-33", "51015200", [mary01, john01])
# Check shared account details
assert acc02.get_account_data() == "Mary Ann, John Doe, 11-22-33 51015200"
|
871b714dd09397b92298f6fa67d0d102d391ed50 | BoLindJensen/Reminder | /Python_Code/Snippets/Iterations/Generator_Function/generator_function_using_yield.py | 716 | 3.953125 | 4 | '''
Generator functions have at lease one yeild in then, they are used when Lazy evaluation is needed.
Eg sensors, very large data sets, etc
'''
names = []
def read_file(): # Normal function using custom generator function.
try:
f = open("names.txt" , "r")
# instead of using the build in generator .readlines() we create our own, for fun.
# for student in f.readlines():
# To keep getting new results a for loop is needed
for name in read_names(f):
names.append(name)
f.close()
except Exception:
print("Error: Cannot read file")
def read_names(f): # Generator function.
for line in f:
yield line
read_file()
print(names)
|
0017141022b8503a5ea7ec2f77a3e4b53e7a4742 | MysteriousSonOfGod/GUIEx | /JumpToPython/test021(class).py | 1,238 | 3.796875 | 4 | # 계산기
class Calculator:
def __init__(self):
self.result = 0
def add(self, num):
self.result += num
return self.result
def sub(self, num):
self.result -= num
return self.result
cal1 = Calculator()
cal2 = Calculator()
class FourCal:
def __init__(self, first, second):
self.first = first
self.second = second
# def setdata(self, first, second):
# self.first = first
# self.second = second
def add(self):
result = self.first + self.second
return result
def mul(self):
result = self.first * self.second
return result
def sub(self):
result = self.first - self.second
return result
def div(self):
result = self.first / self.second
return result
class MoreFourCal(FourCal):
def pow(self):
result = self.first ** self.second
return result
#a = FourCal()
#b = FourCal()
a = FourCal(4, 2)
b = FourCal(3, 8) #__init__ 했으니 setdata 필요없음
#a.setdata(4, 2)
#b.setdata(3, 8)
print(a.add())
print(a.mul())
print(a.sub())
print(a.div())
print(b.add())
print(b.mul())
print(b.sub())
print(b.div())
a = MoreFourCal(4, 2)
print(a.pow()) |
20d9c0a49119668d83912a5461e520aeae0ffc80 | NagahShinawy/problem-solving | /geeksforgeeks/lists/ex4.py | 245 | 4.28125 | 4 | """
Python | Ways to find length of list
"""
from operator import length_hint
def length(items):
counter = 0
for _ in items:
counter += 1
return counter
print(length("test"))
print(len("test"))
print(length_hint("test")) |
84849b66d58cd42b444848f85cbfcc8feeb58ffa | katochanchal11/BestEnlistInternship | /Day 11/task11.py | 1,003 | 4.4375 | 4 | # Exercise 1 - Write a program using zip() function and list() function
# create a merged list of tuples from the two lists given.
nums1 = [40, 25, 398, 500, 125]
nums2 = [258, 89, 147, 22]
zipped_list = list(zip(nums1, nums2))
print(zipped_list, '\n')
# Exercise 2 - First create a range from 1 to 8. Then using zip
# merge the given list and the range together to create a new list of tuples.
nums = [x for x in range(1, 9)]
nums1 = [40, 25, 398, 500, 125, 258, 89, 147, 22]
zipped_list = list(zip(nums, nums1))
print(zipped_list, '\n')
# Exercise 3 - Using sorted() function, sort the list in ascending order.
nums = [152, 9, 52, 854, 37]
print("Sorted list: ", sorted(nums))
# Exercise 4 - Write a program using filter function
# filter the even numbers so that only odd numbers are passed to the new list.
print("Enter the numbers: ")
temp = map(lambda x: int(x), input().split())
even_nums = list(filter(lambda x: x % 2 == 0, temp))
print('Even numbers are: ', even_nums) |
8945d5950aea49d6b6718d4c02da4811a4a37e61 | UwaisMansuri/DS590 | /Uwais_Mansuri_DS590_Assignment4.py | 1,466 | 3.671875 | 4 | import sys
class MaxHeap:
def __init__(self, max):
self.max = max
self.size = 0
self.BHM = [0] * (self.max + 1)
self.BHM[0] = sys.maxsize # For restricting the size of the list
def parent_node(self, i):
return i // 2
def left_child(self, i):
return 2 * i
def right_child(self, i):
return (2 * i) + 1
def insert(self, i):
if self.size >= self.max:
return
self.size += 1
self.BHM[self.size] = i
self.sift_up(self.size)
def sift_up(self, current_node):
while self.BHM[current_node] > self.BHM[self.parent_node(current_node)]:
self.BHM[current_node], self.BHM[self.parent_node(current_node)] = \
self.BHM[self.parent_node(current_node)], self.BHM[current_node] # Swapping current node woth its
# parent node
current_node = self.parent_node(current_node)
def print_heap(self):
for i in range(1, (self.parent_node(self.size)) + 1):
print(" P: " + str(self.BHM[i]) + " L: " +
str(self.BHM[self.left_child((i))]) + " R: " +
str(self.BHM[self.right_child(i)]))
BHMAX = MaxHeap(15)
BHMAX.insert(42)
BHMAX.insert(29)
BHMAX.insert(18)
BHMAX.insert(14)
BHMAX.insert(7)
BHMAX.insert(18)
BHMAX.insert(12)
BHMAX.insert(11)
BHMAX.insert(5)
BHMAX.print_heap() |
0d6681e6b4fdff2c44e832e9579e2e8f32c78298 | taikinaka/youngWonks | /python/Math_project/math.py | 26,465 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
Spyderエディタ
これは一時的なスクリプトファイルです
"""
import threading
import random
import time
import signal
import os
class GameTimer(threading.Thread):
def restart(self):
self.my_timer = time.time() + 50
self.isOn = True
def turnOff(self):
self.isOn = False
def run(self, *args):
self.restart()
count=50
while 1:
print("\t\t\t\t\t\t\t\t",count)
time.sleep(1)
count=count-1
if time.time() >= self.my_timer or not self.isOn:
break
if self.isOn:
os.kill(os.getpid(), signal.SIGINT)
def timer():
for count in range (10,1,-1):
print("\t\t\t\t\t\t\t\t",count)
time.sleep(1)
print("game over.")
os.kill(os.getpid(), signal.SIGINT)
# raise Exception('exit')
from colorama import Fore
from Color import *
from colorama import Style
from time import sleep
def game():
print( )
print( )
print( )
print( )
print(Fore.BLUE + ' Math Quiz Game')
print(GColor.RGB(148,0,211) + ' Addition or Subtraction or Multiplication or Division')
choice = input()
Score=0
if choice[0] == 'A' or choice[0] == 'a':
print('Easy Medium Difficult')
Level = input()
if Level[0] == 'E' or Level[0] == 'e':
print(Fore.GREEN + 'Addition Level Easy')
try:
timer =GameTimer()
timer.daemon=True
timer.start() # start timer
for a in range (0,10,1):
E_Add = random.randint(1,15)
number1 = E_Add
E_Add = random.randint(1,15)
number2 = E_Add
answer = number1 + number2
print('Question',a + 1,': ',number1, ' + ' ,number2)
pearson_answer = int(input())
if answer == pearson_answer:
print('Correct!')
Score=Score+1
else:
print('Wrong!')
timer.turnOff() #Stop timer
except KeyboardInterrupt:
print("\nGame Over!")
print(GColor.RGB(255,0,0),'You got ',Score,'/10!')
if int(Score) == 10:
print(' ')
print(' ')
print('10 more!')
print(' ')
timer =GameTimer()
timer.daemon=True
timer.start() # start timer
for a in range (0,10,1):
E_Add = random.randint(1,15)
number1 = E_Add
E_Add = random.randint(1,15)
number2 = E_Add
answer = number1 + number2
print('Question',a + 1,': ',number1, ' + ' ,number2)
pearson_answer = int(input())
if answer == pearson_answer:
print('Correct!')
Score=Score+1
else:
print('Wrong!')
timer.turnOff() #Stop timer
print('You got ',Score,'/20!' + Style.RESET_ALL)
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
elif Level[0] == 'M' or Level[0] == 'm':
print(GColor.RGB(255,128,0),'Addition Level Medium')
try:
timer =GameTimer()
timer.daemon=True
timer.start() # start timer
for a in range (0,10,1):
E_Add = random.randint(16,30)
number1 = E_Add
E_Add = random.randint(16,30)
number2 = E_Add
answer = number1 + number2
print('Question',a + 1,': ',number1, ' + ' ,number2)
pearson_answer = int(input())
if answer == pearson_answer:
print('Correct!')
Score=Score+1
else:
print('Wrong!')
print('You got ',Score,'/10!')
timer.turnOff() #Stop timer
except KeyboardInterrupt:
print("\nGame Over!")
print(GColor.RGB(255,0,0),'You got ',Score,'/10!')
if int(Score) == 10:
print(' ')
print(' ')
print('10 more!')
print(' ')
timer =GameTimer()
timer.daemon=True
timer.start() # start timer
for a in range (0,10,1):
E_Add = random.randint(16,30)
number1 = E_Add
E_Add = random.randint(16,30)
number2 = E_Add
answer = number1 + number2
print('Question',a + 1,': ',number1, ' + ' ,number2)
pearson_answer = int(input())
if answer == pearson_answer:
print('Correct!')
Score=Score+1
else:
print('Wrong!')
timer.turnOff() #Stop timer
print('You got ',Score,'/20!',GColor.END)
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
else:
print(GColor.RGB(204, 0, 0),'Addition Level Hard')
try:
timer =GameTimer()
timer.daemon=True
timer.start() # start timer
for a in range (0,10,1):
E_Add = random.randint(50,100)
number1 = E_Add
E_Add = random.randint(50,100)
number2 = E_Add
answer = number1 + number2
print('Question',a + 1,': ',number1, ' + ' ,number2)
pearson_answer = int(input())
if answer == pearson_answer:
print('Correct!')
Score=Score+1
else:
print('Wrong!')
print('You got ',Score,'/10!')
timer.turnOff() #Stop timer
except KeyboardInterrupt:
print("\nGame Over!")
print(GColor.RGB(255,0,0),'You got ',Score,'/10!')
if int(Score) == 10:
print(' ')
print(' ')
print('10 more!')
print(' ')
timer =GameTimer()
timer.daemon=True
timer.start() # start timer
for a in range (0,10,1):
E_Add = random.randint(50,100)
number1 = E_Add
E_Add = random.randint(50,100)
number2 = E_Add
answer = number1 + number2
print('Question',a + 1,': ',number1, ' + ' ,number2)
pearson_answer = int(input())
if answer == pearson_answer:
print('Correct!')
Score=Score+1
else:
print('Wrong!')
timer.turnOff() #Stop timer
print('You got ',Score,'/20!',GColor.END)
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
elif choice[0] == 'S' or choice[0] == 's':
print('Easy Medium Difficult')
Level = input()
if Level[0] == 'E' or Level[0] == 'e':
print(Fore.GREEN + 'Subtraction Level Easy')
try:
timer =GameTimer()
timer.daemon=True
timer.start() # start timer
for a in range (0,10,1):
E_Add = random.randint(10,15)
number1 = E_Add
E_Add = random.randint(1,10)
number2 = E_Add
answer = number1 - number2
print('Question',a + 1,': ',number1, ' - ' ,number2)
pearson_answer = int(input())
if answer == pearson_answer:
print('Correct!')
Score=Score+1
else:
print('Wrong!')
timer.turnOff() #Stop timer
except KeyboardInterrupt:
print("\nGame Over!")
print(GColor.RGB(255,0,0),'You got ',Score,'/10!')
if int(Score) == 10:
print(' ')
print(' ')
print('10 more!')
print(' ')
timer =GameTimer()
timer.daemon=True
timer.start() # start timer
for a in range (0,10,1):
E_Add = random.randint(10,15)
number1 = E_Add
E_Add = random.randint(1,10)
number2 = E_Add
answer = number1 - number2
print('Question',a + 1,': ',number1, ' - ' ,number2)
pearson_answer = int(input())
if answer == pearson_answer:
print('Correct!')
Score=Score+1
else:
print('Wrong!')
timer.turnOff() #Stop timer
print('You got ',Score,'/20!' + Style.RESET_ALL)
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
elif Level[0] == 'M' or Level[0] == 'm':
print(GColor.RGB(255,128,0),'Subtraction Level Medium')
try:
timer =GameTimer()
timer.daemon=True
timer.start() # start timer
for a in range (0,10,1):
E_Add = random.randint(20,30)
number1 = E_Add
E_Add = random.randint(10,20)
number2 = E_Add
answer = number1 - number2
print('Question',a + 1,': ',number1, ' - ' ,number2)
pearson_answer = int(input())
if answer == pearson_answer:
print('Correct!')
Score=Score+1
else:
print('Wrong!')
timer.turnOff() #Stop timer
except KeyboardInterrupt:
print("\nGame Over!")
print(GColor.RGB(255,0,0),'You got ',Score,'/10!')
if int(Score) == 10:
print(' ')
print(' ')
print('10 more!')
print(' ')
for a in range (0,10,1):
E_Add = random.randint(20,30)
number1 = E_Add
E_Add = random.randint(10,20)
number2 = E_Add
answer = number1 - number2
print('Question',a + 1,': ',number1, ' - ' ,number2)
pearson_answer = int(input())
if answer == pearson_answer:
print('Correct!')
Score=Score+1
else:
print('Wrong!')
print('You got ',Score,'/20!',GColor.END)
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
else:
print(GColor.RGB(204, 0, 0),'Subtraction Level Difficult')
try:
timer =GameTimer()
timer.daemon=True
timer.start() # start timer
for a in range (0,10,1):
E_Add = random.randint(80,100)
number1 = E_Add
E_Add = random.randint(50,80)
number2 = E_Add
answer = number1 - number2
print('Question',a + 1,': ',number1, ' - ' ,number2)
pearson_answer = int(input())
if answer == pearson_answer:
print('Correct!')
Score=Score+1
else:
print('Wrong!')
timer.turnOff() #Stop timer
except KeyboardInterrupt:
print("\nGame Over!")
print(GColor.RGB(255,0,0),'You got ',Score,'/10!')
if int(Score) == 10:
print(' ')
print(' ')
print('10 more!')
print(' ')
timer =GameTimer()
timer.daemon=True
timer.start() # start timer
for a in range (0,10,1):
E_Add = random.randint(80,100)
number1 = E_Add
E_Add = random.randint(50,80)
number2 = E_Add
answer = number1 - number2
print('Question',a + 1,': ',number1, ' - ' ,number2)
pearson_answer = int(input())
if answer == pearson_answer:
print('Correct!')
Score=Score+1
else:
print('Wrong!')
timer.turnOff() #Stop timer
print('You got ',Score,'/20!',GColor.END)
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
elif choice[0] == 'M' or choice[0] == 'm':
print('Easy Medium Difficult')
Level = input()
if Level[0] == 'E' or Level[0] == 'e':
print(Fore.GREEN + 'Multiplication Level Easy')
try:
timer =GameTimer()
timer.daemon=True
timer.start() # start timer
for a in range (0,10,1):
E_Add = random.randint(1,5)
number1 = E_Add
E_Add = random.randint(1,5)
number2 = E_Add
answer = number1 * number2
print('Question',a + 1,': ',number1, ' x ' ,number2)
pearson_answer = int(input())
if answer == pearson_answer:
print('Correct!')
Score=Score+1
else:
print('Wrong!')
timer.turnOff() #Stop timer
except KeyboardInterrupt:
print("\nGame Over!")
print(GColor.RGB(255,0,0),'You got ',Score,'/10!')
if int(Score) == 10:
print(' ')
print(' ')
print('10 more!')
print(' ')
timer =GameTimer()
timer.daemon=True
timer.start() # start timer
for a in range (0,10,1):
E_Add = random.randint(1,5)
number1 = E_Add
E_Add = random.randint(1,5)
number2 = E_Add
answer = number1 * number2
print('Question',a + 1,': ',number1, ' x ' ,number2)
pearson_answer = int(input())
if answer == pearson_answer:
print('Correct!')
Score=Score+1
else:
print('Wrong!')
timer.turnOff() #Stop timer
print('You got ',Score,'/20!' + Style.RESET_ALL)
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
elif Level[0] == 'M' or Level[0] == 'm':
print(GColor.RGB(255,128,0),'Multiplication Level Medium')
try:
timer =GameTimer()
timer.daemon=True
timer.start() # start timer
for a in range (0,10,1):
E_Add = random.randint(5,10)
number1 = E_Add
E_Add = random.randint(5,10)
number2 = E_Add
answer = number1 * number2
print('Question',a + 1,': ',number1, ' x ' ,number2)
pearson_answer = int(input())
if answer == pearson_answer:
print('Correct!')
Score=Score+1
else:
print('Wrong!')
timer.turnOff() #Stop timer
except KeyboardInterrupt:
print("\nGame Over!")
print(GColor.RGB(255,0,0),'You got ',Score,'/10!')
if int(Score) == 10:
print(' ')
print(' ')
print('10 more!')
print(' ')
timer =GameTimer()
timer.daemon=True
timer.start() # start timer
for a in range (0,10,1):
E_Add = random.randint(5,10)
number1 = E_Add
E_Add = random.randint(5,10)
number2 = E_Add
answer = number1 * number2
print('Question',a + 1,': ',number1, ' x ' ,number2)
pearson_answer = int(input())
if answer == pearson_answer:
print('Correct!')
Score=Score+1
else:
print('Wrong!')
timer.turnOff() #Stop timer
print('You got ',Score,'/20!',GColor.END)
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
else:
print(GColor.RGB(204, 0, 0),'Multiplication Level Difficult')
try:
timer =GameTimer()
timer.daemon=True
timer.start() # start timer
for a in range (0,10,1):
E_Add = random.randint(20,50)
number1 = E_Add
E_Add = random.randint(20,50)
number2 = E_Add
answer = number1 * number2
print('Question',a + 1,': ',number1, ' x ' ,number2)
pearson_answer = int(input())
if answer == pearson_answer:
print('Correct!')
Score=Score+1
else:
print('Wrong!')
timer.turnOff() #Stop timer
except KeyboardInterrupt:
print("\nGame Over!")
print(GColor.RGB(255,0,0),'You got ',Score,'/10!')
if int(Score) == 10:
print(' ')
print(' ')
print('10 more!')
print(' ')
timer =GameTimer()
timer.daemon=True
timer.start() # start timer
for a in range (0,10,1):
E_Add = random.randint(20,50)
number1 = E_Add
E_Add = random.randint(20,50)
number2 = E_Add
answer = number1 * number2
print('Question',a + 1,': ',number1, ' x ' ,number2)
pearson_answer = int(input())
if answer == pearson_answer:
print('Correct!')
Score=Score+1
else:
print('Wrong!')
timer.turnOff() #Stop timer
print('You got ',Score,'/20!',GColor.END)
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
else:
print('Easy Medium Difficult')
Level = input()
if Level[0] == 'E' or Level[0] == 'e':
print(Fore.GREEN + 'Division Level Easy')
try:
timer =GameTimer()
timer.daemon=True
timer.start() # start timer
for a in range (0,10,1):
dividends = [6,12,18,24,30,36]
number1 = dividends[random.randint(0,5)]
divisors = [3,6]
number2 = random.choice(divisors)
answer = number1 / number2
print('Question',a + 1,': ',number1, ' / ' ,number2)
pearson_answer = int(input())
if answer == pearson_answer:
print('Correct!')
Score=Score+1
else:
print('Wrong!')
timer.turnOff() #Stop timer
except KeyboardInterrupt:
print("\nGame Over!")
print(GColor.RGB(255,0,0),'You got ',Score,'/10!')
if int(Score) == 10:
print(' ')
print(' ')
print('10 more!')
print(' ')
timer =GameTimer()
timer.daemon=True
timer.start() # start timer
for a in range (0,10,1):
dividends = [6,12,18,24,30,36]
number1 = dividends[random.randint(0,5)]
divisors = [3,6]
number2 = random.choice(divisors)
answer = number1 / number2
print('Question',a + 1,': ',number1, ' / ' ,number2)
pearson_answer = int(input())
if answer == pearson_answer:
print('Correct!')
Score=Score+1
else:
print('Wrong!')
timer.turnOff() #Stop timer
print('You got ',Score,'/20!' + Style.RESET_ALL)
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
elif Level[0] == 'M' or Level[0] == 'm':
print(GColor.RGB(255,128,0),'Division Level Medium')
try:
timer =GameTimer()
timer.daemon=True
timer.start() # start timer
for a in range (0,10,1):
dividends = [14,28,42,56,70,84,98]
number1 = dividends[random.randint(0,6)]
divisors = [7,14]
number2 = random.choice(divisors)
answer = number1 / number2
print('Question',a + 1,': ',number1, ' / ' ,number2)
pearson_answer = int(input())
if answer == pearson_answer:
print('Correct!')
Score=Score+1
else:
print('Wrong!')
timer.turnOff() #Stop timer
except KeyboardInterrupt:
print("\nGame Over!")
print(GColor.RGB(255,0,0),'You got ',Score,'/10!')
if int(Score) == 10:
print(' ')
print(' ')
print('10 more!')
print(' ')
timer =GameTimer()
timer.daemon=True
timer.start() # start timer
for a in range (0,10,1):
dividends = [14,28,42,56,70,84,98]
number1 = dividends[random.randint(0,6)]
divisors = [7,14]
number2 = random.choice(divisors)
answer = number1 / number2
print('Question',a + 1,': ',number1, ' / ' ,number2)
pearson_answer = int(input())
if answer == pearson_answer:
print('Correct!')
Score=Score+1
else:
print('Wrong!')
timer.turnOff() #Stop timer
print('You got ',Score,'/20!',GColor.END)
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
else:
print(GColor.RGB(204, 0, 0),'Division Level Difficult')
try:
timer =GameTimer()
timer.daemon=True
timer.start() # start timer
for a in range (10):
dividend = random.choice([16,32,48,64,80,96,112,128,144,160,176,192])
divisor = random.choice([8,16])
answer = dividend / divisor
print('Question',a + 1,': ',dividend, ' / ' ,divisor)
pearson_answer = int(input())
if answer == pearson_answer:
print('Correct!')
Score=Score+1
else:
print('Wrong!')
timer.turnOff() #Stop timer
except KeyboardInterrupt:
print("\nGame Over!")
print(GColor.RGB(255,0,0),'You got ',Score,'/10!')
if int(Score) == 10:
print(' ')
print(' ')
print('10 more!')
print(' ')
timer =GameTimer()
timer.daemon=True
timer.start() # start timer
for a in range (10):
dividend = random.choice([16,32,48,64,80,96,112,128,144,160,176,192])
divisor = random.choice([8,16])
answer = dividend / divisor
print('Question',a + 1,': ',dividend, ' / ' ,divisor)
pearson_answer = int(input())
if answer == pearson_answer:
print('Correct!')
Score=Score+1
else:
print('Wrong!')
timer.turnOff() #Stop timer
print('You got ',Score,'/20!',GColor.END)
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
game()
#t1=threading.Thread(target=timer)
#t2=threading.Thread(target=game)
#t1.start()
#t2.start()
#t1.join()
#t2.join() |
92efea4153f4fd452c2ad4209cda157e1c36fcd4 | DenisFuryaev/PythonProjects | /papacode/word_shuffle.py | 555 | 3.65625 | 4 | import re
import string
def dict_from_str(str):
dict = {}
for char in str:
if char in ',.!?':
if char in dict:
dict[char] = dict[char] + 1
else:
dict[char] = 1
for word in re.split('[ ,.!?]+', str.lower()):
if len(word) == 0:
continue
if word in dict:
dict[word] = dict[word] + 1
else:
dict[word] = 1
return dict
str_1 = input()
str_2 = input()
a = dict_from_str(str_1)
b = dict_from_str(str_2)
print(a == b)
|
b9e085aa7879f0d0e2eab7eb63e5e35699f373e6 | maxter252/Coding-Questions-Solutions | /10-Simple/reverse_int.py | 862 | 4.3125 | 4 | # Given an integer, return the integer with reversed digits.
# Note: The integer could be either positive or negative.
def reverse(input: int) -> int:
input = str(input)
if input[0] == '-':
return '-' + input[:0:-1]
else:
return input[::-1]
# print(reverse(-12345))
# For a given sentence, return the average word length.
# Note: Remember to remove punctuation first.
sentence1 = "Hi all, my name is Tom...I am originally from Australia."
sentence2 = "I need to work very hard to learn more about algorithms in Python!"
def avg_len(input: str) -> float:
words = input.replace('!','').replace('?','').replace(';','').replace(',','').replace('.','').split(" ")
sum = 0
count = 0
for i in words:
count += 1
sum += len(i)
return (sum/count)
print(avg_len(sentence1))
print(avg_len(sentence2)) |
fe3f2e74236454aa09d5a66014b7814eaa77e59d | Proudfeets/Learning-python | /rock-paper-scissors.py | 930 | 4.3125 | 4 | import random
for x in range(1):
machine = random.randint(1,3)
player=raw_input("Choose rock (r), paper (p), or scissors (s):")
if ( player == 'r' ) : print("You choose rock.")
elif ( player == 'p' ) : print("You choose paper.")
elif ( player == 's' ) : print("You choose scissors.")
else: print("I don't understand. Please start over.")
# choice = "rock" or "scissors" or "paper"
if ( machine == 1 ):
choice = "rock"
elif (machine == 2):
choice = "paper"
elif (machine == 3):
choice = "scissors"
else: print(machine)
print("The computer chose " + choice)
if (machine == 1 and player == 'p') or (machine == 2 and player == 's') or (machine == 3 and player == 'r'):
print("Player wins!")
elif (machine == 2 and player == 'p') or (machine == 3 and player == 's') or (machine == 1 and player == 'r'):
print("Tie! The battle between humanity and the machines is over.")
else:
print("Machine wins!")
|
06cf4f15aa2f7a0001dfa3984ab6d3098edaa2c9 | Eric-Xie98/CrashCoursePython | /CrashCoursePython/Chapter 10/StoringData.py | 3,415 | 4.65625 | 5 | ## Because we take a lot input data from users, it's usual that we want to save what they input for things
## such as settings for later use. A simple way to do this is to use a json module:
## We dump simple Python data structures into a file and upload it whenever the program is run. We can use this JSON module
## to share this data between different program, programmers, and coding languages!
# JSON (JavaScript Object Notation) was originally developed for JavaScript but since then has become the main format for many languages.
# We're going to write a short program that takes a list of numbers and saves it then reloads them back in.
# The first program will use json.dump() to store the information and the second will instead use json.load() to retrieve it:
import json
numbers = [2, 3, 5, 17, 24, 33]
filename = 'numbers.json' ## Notice how we're storing the file in a JSON format
with open(filename, 'w') as file_object:
json.dump(numbers, file_object) ## Using the json.dump() function to store the numbers list inside the numbers.json file
## Refer to numbersReading.py to see about json.load()
# Through this method, we can implement user input and store any data for later usage:
username = input("What do you want your username to be? ")
with open('username.json', 'w') as file_obj:
json.dump(username, file_obj)
print("We'll remember you by your username, " + username + "!")
# Once we've stored the username in a json, we can pull it once he comes back.
with open('username.json') as file_obj:
retrieval = json.load(file_obj)
print("Welcome back, " + retrieval + "!")
## The code below summarizes what we're doing:
def retrieveUsername():
"""Get username if its already stored"""
filename = 'username2.json'
try:
with open(filename) as file_object:
name = json.load(file_object)
except FileNotFoundError:
return None
else:
return name
def getNewUsername():
user = input("What would you like your username to be? ")
fileName = 'username2.json'
with open(fileName, 'w') as file_object:
json.dump(user, file_object)
return user
def rememberMe():
username = retrieveUsername()
if username:
answer = input("Are you " + username + "? (Y / N): ")
if answer == 'N':
username = getNewUsername()
print("Welcome back, " + username + "!")
else:
print("We don't seem to have you in our database yet...")
username = getNewUsername()
print("We'll remember you next time, " + username + "!")
rememberMe()
## What we essentially did here is refactor the code, or turn code that would be needed to use multiple times and repetitive into a function
## for later use. Furthermore, we can break down rememberMe() into smaller functions or refactor it.
# Let's try refactoring rememberMe() and make a function that retrievesStoredUsernames:
## This can used to repalce the upper part of the rememberMe():
# Let's refactor getting a new username to for the hell of it:
## Now, our rememberMe() code has simplified into an if-else statement is much more clearer and easier to read!
## Exercises
print()
fave = input("Tell me your favorite number: ")
fave = int(fave)
with open('favorite.json', 'w') as file_object:
json.dump(fave, file_object)
|
230c429f193db0c99918c39b396526e5ad81b419 | 05113/fastapi-testplatform | /demo/xunhuanDemo.py | 233 | 4 | 4 |
# 当n=0时代表false,(python中0代表false)跳出循环
n = 2
while 0:
print(n)
# 当n为None时代表false,跳出循环
k = None
while k:
print(1)
for item in range(10,1,-1):
print(item)
a = [1,2]
a[2] = 3
print(a) |
1fa8de66ba462395dec03b5fcbfbf6cc146565e5 | aristotekoen/datacamp-assignment-pandas | /pandas_questions.py | 5,073 | 4.125 | 4 | """Plotting referendum results in pandas.
In short, we want to make beautiful map to report results of a referendum. In
some way, we would like to depict results with something similar to the maps
that you can find here:
https://github.com/x-datascience-datacamp/datacamp-assignment-pandas/blob/main/example_map.png
To do that, you will load the data as pandas.DataFrame, merge the info and
aggregate them by regions and finally plot them on a map using `geopandas` o.
"""
import pandas as pd
import geopandas as gpd
import matplotlib.pyplot as plt
def load_data():
"""Load data from the CSV files referundum/regions/departments."""
filename_ref = "/Users/Aris/datacamp-assignment-pandas/data/referendum.csv"
filename_reg = "/Users/Aris/datacamp-assignment-pandas/data/regions.csv"
filename_dep = \
"/Users/Aris/datacamp-assignment-pandas/data/departments.csv"
referendum = pd.DataFrame(pd.read_csv(filename_ref, sep=";"))
regions = pd.DataFrame(pd.read_csv(filename_reg, sep=","))
departments = pd.DataFrame(pd.read_csv(filename_dep, sep=","))
return referendum, regions, departments
def merge_regions_and_departments(regions, departments):
"""Merge regions and departments in one DataFrame.
The columns in the final DataFrame should be:
['code_reg', 'name_reg', 'code_dep', 'name_dep']
"""
regions.rename(columns={"code": "code_reg"}, inplace=True)
departments.rename(columns={"region_code": "code_reg"}, inplace=True)
dataset = pd.merge(regions.loc[:, ["code_reg", "name"]],
departments.loc[:, ["code_reg", "code", "name"]],
on="code_reg")
dataset.columns = ['code_reg', 'name_reg', 'code_dep', 'name_dep']
return dataset
def merge_referendum_and_areas(referendum, regions_and_departments):
"""Merge referendum and regions_and_departments in one DataFrame.
You can drop the lines relative to DOM-TOM-COM departments, and the
french living abroad.
"""
columnorder = ['code_dep', 'code_reg', 'name_reg', 'name_dep']
regions_and_departments = regions_and_departments[columnorder]
todrop = referendum[referendum["Department code"]
.str.startswith('Z').isin([True])].index
todrop2 = regions_and_departments[regions_and_departments["code_reg"]
.str.startswith('C').isin([True])].index
referendum = referendum.drop(index=todrop)
regions_and_departments = regions_and_departments.drop(index=todrop2)
toreplace = regions_and_departments.loc[regions_and_departments["code_dep"]
.str.startswith('0').isin([True]),
"code_dep"].index
regions_and_departments.iloc[toreplace, 0] = \
regions_and_departments.iloc[toreplace, 0].str.replace('0', '')
newdf = pd.merge(referendum, regions_and_departments,
left_on="Department code", right_on="code_dep",
how='left')
return newdf
def compute_referendum_result_by_regions(referendum_and_areas):
"""Return a table with the absolute count for each region.
The return DataFrame should be indexed by `code_reg` and have columns:
['name_reg', 'Registered', 'Abstentions', 'Null', 'Choice A', 'Choice B']
"""
columns = ['code_reg', 'name_reg', 'Registered', 'Abstentions',
'Null', 'Choice A', 'Choice B']
df = referendum_and_areas[columns]
df = df.groupby(["code_reg", "name_reg"]).sum()
df = df.reset_index(level=1)
return df
def plot_referendum_map(referendum_result_by_regions):
"""Plot a map with the results from the referendum.
* Load the geographic data with geopandas from `regions.geojson`.
* Merge these info into `referendum_result_by_regions`.
* Use the method `GeoDataFrame.plot` to display the result map. The results
should display the rate of 'Choice A' over all expressed ballots.
* Return a gpd.GeoDataFrame with a column 'ratio' containing the results.
"""
filenamegpd = "/Users/Aris/datacamp-assignment-pandas/data/regions.geojson"
df = gpd.read_file(filenamegpd)
df.rename(columns={"nom": "name_reg"}, inplace=True)
df_2 = pd.merge(referendum_result_by_regions, df, on='name_reg',
how='left')
df_2["ratio"] = df_2["Choice A"]/df_2.drop(columns=["Abstentions", "Null",
"Registered"])\
.sum(axis=1)
df_2 = gpd.GeoDataFrame(df_2)
df_2.plot(column="ratio", legend=True)
return df_2
if __name__ == "__main__":
referendum, df_reg, df_dep = load_data()
regions_and_departments = merge_regions_and_departments(
df_reg, df_dep
)
referendum_and_areas = merge_referendum_and_areas(
referendum, regions_and_departments
)
referendum_results = compute_referendum_result_by_regions(
referendum_and_areas
)
print(referendum_results)
plot_referendum_map(referendum_results)
plt.show()
|
ffb8fde191dc5392e9b75719eeef27bb0be18419 | Callum-Diaper/COM404 | /1-basics/3-decision/2-if-else/bot.py | 208 | 3.609375 | 4 | user_inp = str(input("Please enter the activity to be performed "))
if user_inp == "calculate":
print("Perofrming calculations...")
else:
print("Performing activity...")
print("Activity completed!") |
a52750e35093c8e79ef05bb085eb7ca8cde85336 | Aasthaengg/IBMdataset | /Python_codes/p03805/s180201282.py | 975 | 3.546875 | 4 | #グラフのパスを全探索する関数(再帰)
def dfs(now_node, depth):#deptt:今まで列挙した頂点数
if seen[now_node]:#探索済みであった場合はreturn
return 0
if depth == N:#全ての頂点を通っていた場合、1を返す
return 1
seen[now_node] = True #今から探索するノードを探索済みにする
connect_nodes = graph[now_node]
ans = 0
for node in connect_nodes:#全ての遷移先をチェックする
ans += dfs(node, depth+1)
seen[now_node] = False # 探索済みフラグを折る(ポイント)
return ans
N, M = map(int, input().split())
edges = [list(map(int, input().split())) for i in range(M)]#辺の集合
graph =[[] for i in range(N+1)]#隣接リスト
for edge in edges:
graph[edge[0]].append(edge[1])
graph[edge[1]].append(edge[0])
#訪問済みかどうかを表すリストを用意
seen = [False for i in range(N+1)]
seen[0] = True
print(dfs(1, 1)) |
748d2627fc5ec5766fa0104390d90912ca9967cb | andybloke/python4everyone | /User_Input.py | 193 | 3.84375 | 4 | print("Please enter your First Name")
firstName = input()
print("Please enter your Last Name")
lastName = input()
print("You entered:\nFirst Name: " + firstName + "\nLast Name: " + lastName)
|
c83dfc6baab997f0993a949d55cc7e1a717ad5d4 | supperllx/LeetCode | /530.py | 636 | 3.515625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def getMinimumDifference(self, root: TreeNode) -> int:
nums = []
def func(root):
if root:
nonlocal nums
func(root.left)
nums.append(root.val)
func(root.right)
func(root)
res = float('inf')
for i in range(len(nums) - 1):
if abs(nums[i+1] - nums[i]) < res: res = abs(nums[i+1] - nums[i])
return res |
44fcd91e3bc764da0eeb9d96a31866516116e638 | vaspupiy/home_work | /lesson_02v2/lesson_2_task_3.py | 1,767 | 3.640625 | 4 | while True:
m = input("Введите месяц в виде целого числа от 1 до 12: ")
if m.isdecimal():
m = int(m)
if 0 < m <= 12:
break
print("Ошибка ввода")
l_s = [["зиме", 12, 1, 2], ["весне", 3, 4, 5], ["лету", 6, 7, 8], ["осени", 9, 10, 11]]
for i in l_s:
if m in i:
print(f"Введенный месяц относится к {i[0]}")
break
l_s2 = ["зиме", "зиме", "весне", "весне", "весне", "лету", "лету", "лету", "осени", "осени", "осени", "зиме"]
print(f"Введенный месяц относится к {l_s2[m - 1]}")
d_s = {"зиме": [12, 1, 2], "весне": [3, 4, 5], "лету": [6, 7, 8], "осени": [9, 10, 11]}
for key in d_s:
if m in d_s[key]:
print(f"Введенный месяц относится к {key}")
break
d_s2 = {12: "зиме", 1: "зиме", 2: "зиме", 3: "весне",
4: "весне", 5: "весне", 6: "лету", 7: "лету",
8: "лету", 9: "осени", 10: "осени", 11: "осени"}
print(f"Введенный месяц относится к {d_s2[m]}")
# В качестве бреда :) :
d_s_s = {'12': "зиме", '1': "зиме", '2': "зиме", '3': "весне",
'4': "весне", '5': "весне", '6': "лету", '7': "лету",
'8': "лету", '9': "осени", '10': "осени", '11': "осени"}
while True:
m = input("Введите месяц в виде целого числа от 1 до 12: ")
if m in d_s_s:
print(f"Введенный месяц относится к {d_s_s[m]}")
break
print("Ошибка ввода")
|
c971c6c24da77e70b771be6580b41702bfa80231 | Big-Brain-Crew/learn_ml | /coral_inference/camera.py | 6,031 | 3.640625 | 4 | ''' Classes to stream video from camera sources.
These classes create a background thread that continuously streams camera images.
Any number of other threads can tune in and receive new images. The class structure can
easily be extended by implementing a few package-specific functions. For example, the
OpenCVCamera class only has to implement the code to read an image using OpenCV.
Classes:
BaseCamera: Base class that handles threading, starting/stopping, and getting frames.
OpenCVCamera: Streams video using OpenCV.
'''
import os
import cv2
from abc import abstractmethod
import numpy as np
import time
from thread_manager import ThreadManager
class BaseCamera(object):
''' Base class for streaming video in a background thread.
This class continuously pulls new images in a thread. When a separate thread calls the
get() function to retrieve a frame, the ThreadManager blocks until a new frame comes in
and then returns a frame to all listeners. This ensures that no duplicate frames are retreived.
Attributes:
source (str): The file path of the video source.
For example, this could be "/dev/video0". Run v4l2-ctl --list-devices to find your device.
resolution (tuple[int]): Stores the camera resolution.
frame (array[int]): Stores the current frame.
thread_manager: A separate class that handles incoming requests for frames.
'''
def __init__(self,
source,
resolution):
''' Sets the video source and creates the thread manager.
Args:
source (str): The file path of the video stream.
resolution (tuple[int]): The camera resolution.
'''
self.source = source
self.resolution = resolution
self.frame = None # current frame is stored here by background thread
self.thread_manager = ThreadManager(self)
def __iter__(self):
''' Returns itself as an iterator.
Since the class is structured around generators, there is no need for a separate
iterator.
'''
return self
def __next__(self):
''' Returns the newest frame.
This operator allows the class usage to be abstracted. The user can call next(source), and
the source can be any video stream that implements this operator.
Returns: The newest frame.
'''
return self.get_frame()
def _thread(self):
''' Continuously pulls new frames from the camera.
An infinite generator is used to pull new frames. Once a new frame is pulled,
the thread manager is set, notifying all listeners and handing them the new frame.
If there have been no listeners for 10 seconds, then the thread stops.
'''
frames_iterator = self.frames()
for frame in frames_iterator:
self.frame = frame
# Send signal to listeners
self.thread_manager.set()
# if there haven't been any listeners asking for frames in
# the last 10 seconds then stop the thread
if self.thread_manager.time_lapsed() > 10:
frames_iterator.close()
print('Stopping camera thread due to inactivity.')
break
self.thread_manager.stop()
def start(self):
''' Starts the streaming thread.
'''
self.thread_manager.start()
def get_frame(self):
''' Waits for a new frame and returns it.
'''
self.thread_manager.wait()
return self.frame
def get_resolution(self):
''' Returns the camera resolution.
'''
return self.resolution
@abstractmethod
def frames(self):
''' Generator that continuously yields frames.
This method must be implemented by child classes. It should be an infinite while loop
that yields new camera frames.
Yields: The newest camera frame.
'''
pass
# TODO: Add a way to change the input camera resolution. This will reduce processing time.
class OpenCVCamera(BaseCamera):
''' Streams video from a camera using OpenCV.
Attributes:
camera: The camera source object.
'''
def __init__(self,
source="/dev/video0"):
''' Creates the camera source.
Args:
source (str): The file path of the video source. Defaults to the first video source
(usually a laptop camera or the first usb webcam plugged in).
'''
self.camera = self.set_camera(source)
resolution = (self.camera.get(3), self.camera.get(4))
super(OpenCVCamera, self).__init__(source,
resolution)
def frames(self):
''' Continuously yields new frames.
'''
while True:
# read current frame
_, frame = self.camera.read()
yield frame
def set_camera(self, source):
''' Sets the OpenCV video source.
OpenCV creates a source using an integer that is taken from the last character of the
camera file path. For example, "/dev/video0" can be created with cv2.VideoCapture(0).
Args:
source (str): The file path of the video source. Must be of the form "/dev/videoX",
where X is an integer.
Raises:
ValueError: Cannot interpret the input string.
RuntimeError: Cannot start the camera (meaning camera doesn't exist).
'''
try:
split = source.split("/")
video_source = int(split[2][-1])
except (IndexError, ValueError):
raise ValueError("source must of the form /dev/{source}." +
" Run v4l2-ctl --list-devices for available sources.")
camera = cv2.VideoCapture(video_source)
if not camera.isOpened():
raise RuntimeError('Could not start camera.')
return camera |
d9854f02452ce97e24a80a0ce424894c9642a8fc | zack-carideo/pass_through_dir | /text_preprocessing.py | 756 | 3.828125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Oct 23 17:15:28 2019
@author: zjc10
"""
import string
import re
def clean_sentence(sentence,PUNCTUATION=string.punctuation+"\\\\",stemmer = None, lower=False,stopwords = None):
sentence = sentence.encode('ascii',errors = 'ignore').decode()
sentence=re.sub(f'[{PUNCTUATION}]',' ',sentence)
sentence = re.sub(' {2,}',' ', sentence)
if lower:
sentence= sentence.lower().strip()
else:
sentence= sentence.strip()
if stopwords:
sentence = ' '.join([word for word in sentence.split() if word not in stopwords])
if stemmer:
sentence = ' '.join([stemmer.stem(word) for word in sentence.split()])
return sentence
|
2da54bd6d62c3628adeb4145342b772a8cdb3afb | rdkr/advent-of-code | /2020/01.py | 383 | 3.75 | 4 | import itertools
import functools
import operator
def calculate(combo_length):
for combo in itertools.combinations(numbers, combo_length):
if functools.reduce(operator.add, combo) == 2020:
return functools.reduce(operator.mul, combo)
with open("01.txt") as _input:
numbers = [int(x) for x in _input.readlines()]
print([calculate(x) for x in [2, 3]])
|
7c5f8d6e58a400625a166b8c3e4af72d283aed5d | kcunning/gamemaster-scripts | /general/wounds.py | 2,133 | 3.96875 | 4 | import csv
from random import choice
def get_lines(fn):
''' Gets a bunch of lines from a CSV file
'''
lines = []
with open(fn) as f:
reader = csv.reader(f)
for line in reader:
lines.append(line)
return lines
def create_char_dict(lines):
''' Takes lines from a CSV file and returns a dict of characters.
The format for the characters is:
name, max_wounds, current_wounds (ex: Steve, 3, 0)
'''
d = {}
for name, wounds, current in lines:
d[name] = [int(wounds), int(current)]
return d
def wound_random_char(d):
''' Given a dict of characters, wound one of them! If a character is
already out of the combat, pick someone new.
For now, a wound is .5.
TODO: Make wounds adjustable
'''
c = choice(list(d.keys()))
print ("Wounding", c)
while d[c][1] == d[c][0]:
print ("Cancel that.", c, "is out of the battle.")
c = choice(list(d.keys()))
print ("Wounding", c)
d[c][1] += .5
print (c, "now has", d[c][1], "wounds.")
def print_chars_status(d):
''' Given a dict of characters, print them out. Groups by who is in
battle and who is out.
'''
in_battle = []
out_of_battle = []
for c in d:
if d[c][0] > d[c][1]:
s = "{ch} ({c}/{w})".format(ch=c, c=str(d[c][1]), w=str(d[c][0]))
in_battle.append(s)
else:
out_of_battle.append(c)
print ("In battle:")
in_battle.sort()
for ch in in_battle: print (ch)
if not in_battle: print ("None")
print ("\nOut of battle:")
for ch in out_of_battle: print (ch)
if not out_of_battle: print ("None")
print()
lines = get_lines("wounds_chars.csv")
chars = create_char_dict(lines)
lines = get_lines('wounds_mobs.csv')
mobs = create_char_dict(lines)
r = 1
print ("Starting battle")
while True:
print ("Round", r)
wound_random_char(chars)
wound_random_char(mobs)
print_chars_status(chars)
print_chars_status(mobs)
r += 1
inp = input("X to stop: ")
if inp.lower() == 'x': break |
56b546219d38c559b1f39e0a16874b5307792b01 | patelp456/Project-Euler | /longest_product_series.py | 608 | 3.703125 | 4 | #!/usr/bin/env python
# ========= Import required modules =====================
# for using system commands
import sys
# for using os commands like list directeries etc
import os
# for mathematical functions specially matriices
import numpy as np
# for general maths
from math import *
fname = sys.argv[1]
data = np.loadtxt(fname, dtype = "string")
data = str(data)
data = list(data)
# print data
ans = 0
digits = input("enter the req number of contiguous digits")
for i in range(0,len(data)-digits + 1):
temp = np.array(data[i:i+digits]).astype(int)
ans = max(ans, np.prod(temp))
print temp, ans
|
46b22aca8ae5d4fb82c4e3f9a08771e8e0922925 | wbsjl/ftp-server | /Data/Link_list.py | 921 | 4.03125 | 4 | # class QueueError(Exception):
# pass
#
# class Node:
# def __init__(self,val,next=None):
# self.next=next
# self.val=val
#
# class Lsqueue:
# def __init__(self):
# self.last=self.first = Node(None)
#
#
#
# def is_empty(self):
# return self.first == self.last
#
# def enqueue(self,elem):
# self.last.next = Node(elem)
# self.last = self.last.next
#
#
# def dequeue(self):
# if self.first == self.last:
# raise QueueError("empty")
# self.first = self.first.next
# return self.first.val
#
# if __name__=="__main__":
# sq = Lsqueue()
# print(sq.is_empty())
# sq.enqueue(1)
# sq.enqueue(2)
# sq.enqueue(3)
# print(sq.is_empty())
# while not sq.is_empty():
# print(sq.dequeue())
def recursion(n):
if n <=1:
return 1
return (n*recursion(n-1))
print(recursion(5))
|
500818f6f5610a84dacefa889ff1bde9c93df542 | yuri-flower/GoogleSTEP2020 | /week5/solver_exchangetwo.py | 2,737 | 3.640625 | 4 | #!/usr/bin/env python3
import sys
import math
import random
import copy
from common import print_tour, read_input
def distance(city1, city2):
return math.sqrt((city1[0] - city2[0]) ** 2 + (city1[1] - city2[1]) ** 2)
# greedy
def solve(cities,current_city,dist):
N = len(cities)
for i in range(N):
for j in range(i, N):
dist[i][j] = dist[j][i] = distance(cities[i], cities[j])
unvisited_cities = set(range(0, N))
tour = [current_city]
unvisited_cities.remove(current_city)
while unvisited_cities:
next_city = min(unvisited_cities,
key=lambda city: dist[current_city][city])
unvisited_cities.remove(next_city)
tour.append(next_city)
current_city = next_city
return tour,dist
# 総距離を計算
def total_distance(tour,dist):
length = 0
for i in range(len(tour)+1):
length += dist[tour[i-1]][tour[i % len(tour)]]
return length
# 全てのノードの組み合わせについて、入れ替えると短くなる場合は交換
# 改善できる限り繰り返す
def change_two(tour,dist):
N=len(tour)
improved = True
while improved:
improved=False
for i in range(1,N):
for j in range(i+2,N+1):
A,B,C,D = tour[i-1],tour[i],tour[j-1],tour[j%N]
if dist[A][B]+dist[C][D] > dist[A][C]+dist[B][D]:
tour[i:j] = reversed(tour[i:j])
# print(A,B,C,D,tour)
improved=True
return tour,dist
############ ここから 交差している2点 -> swapに使いました ##########
############### このプログラムでは今回は使ってないです ##############
# 点p1,p2を通る直線の方程式にp3を代入
def f(p1,p2,p3):
return (p2[0]-p1[0]) * (p3[1]-p1[1]) - (p2[1]-p1[1]) * (p3[0]-p1[0])
# p1-p2とp3-p4がクロスしているかの判定
def isCross(p1,p2,p3,p4):
return f(p1,p2,p3)*f(p1,p2,p4)<0 and f(p3,p4,p1)*f(p3,p4,p2)<0
################## ここまで ###################
def search_best_route(cities):
N = len(cities)
sum_dis = 10**9 # とりあえず大きい値で初期化
dist = [[0] * N for i in range(N)]
for _ in range(N): # スタート地点を全ノードで試す
current_city = _
tour, dist = solve(cities,current_city,dist) # greedy
tour,dist = change_two(tour,dist)
# 最も距離の短いものを選択
if sum_dis>total_distance(tour,dist):
ans=tour
sum_dis=total_distance(tour,dist)
return ans
if __name__ == '__main__':
assert len(sys.argv) > 1
cities=read_input(sys.argv[1])
print_tour(search_best_route(cities)) |
abdfbe195debcb5f9b1e495c38267a9f72e9f254 | savsrin/cloudshell | /day-1/hello.py | 322 | 4.21875 | 4 | print("hello world")
print("4" + "3")
print("4"*3)
#string formatting
name = "savitha"
last = "srinivasan"
print(f"good day {name} {last} !!!!")
#built in function: operate/ action --> give you back value
print(len(name))
#concatenation: joining strings 2gether
print("good day " + name.capitalize())
#built in method |
e22f4de2ee32d74c6eb237c9e1d5d261df66d260 | RoslinErla/ekki | /count_instances.py | 475 | 4.03125 | 4 | # ● Count instances
# ○ Implement a recursive function that counts a specific value in a list
# ○ Takes a list and a single value as parameters
# ○ Returns an integer value
# ■ How many times does that value appear in the list?
def count(a_list,value):
if a_list == []:
return 0
if value == a_list[-1]:
return 1 + count(a_list[:-1],value)
else:
return count(a_list[:-1],value)
print(count(["m","a","m","m","a","m"],"m"))
|
b53230030ba20080688007d5f89d2a627c8e7121 | Notheryne/Rapanalyze | /scraping/parts/counters.py | 2,518 | 3.78125 | 4 | from prettytable import PrettyTable
def count(file):
#count how many times each word appeared
with open(file, 'r', encoding = "utf-8") as readfile:
words = readfile.read()
#get words from file
words = words.split(" ") #make list from string
words = [word for word in words if word != ""] #remove empty strings
all_words = len(words) #get number of all words
with open("stopwords.txt", 'r', encoding = "utf-8") as stopfile:
stopwords = stopfile.read()
stopwords = stopwords.split("\n") #get stopwords, because there's no point counting these
words = [word for word in words if word not in stopwords] #delete all stopwords from words
without_stopwords = len(words) #get number of words without stopwords
occurences = {}
for i in words:
if i in occurences.keys():
occurences[i] += 1
else:
occurences[i] = 1
#actual counting
sorted_list = sorted(occurences.items(), key=lambda x: x[1], reverse=True)
#sort by number of occurences (mostly used up top)
unique_words = len(sorted_list)
return sorted_list, all_words, without_stopwords, unique_words
def save_counters(file, outfile):
noname = count(file)
sorted_list = noname[0]
all_words = noname[1]
without_stopwords = noname[2]
unique_words = noname[3]
#get values from count
all_frequencies = [round(i[1] / all_words, 8) for i in sorted_list]
ws_frequencies = [round(i[1] / without_stopwords, 8) for i in sorted_list]
unique_frequencies = [round(i[1] / unique_words, 8) for i in sorted_list]
#get frequencies for each word
all_occurences = [i[1] for i in sorted_list]
occurences = sum(all_occurences)
#get sum of all occurences, should be same as without_stopwords
table = PrettyTable()
table.field_names = ['Words', 'Occurences', 'F (all words)', 'F (no stopwords)', 'F (unique)']
#initialize PrettyTable() with field names
for i in range(len(sorted_list)):
table.add_row([sorted_list[i][0], sorted_list[i][1], all_frequencies[i],
ws_frequencies[i], unique_frequencies[i]])
#add_row for each word to PrettyTable()
with open(outfile, 'w', encoding = "utf-8") as writefile:
writefile.write("Based on {} words, {} after removing stopwords ({} unique words).\n**F means frequency.**\n\n".format(
all_words, without_stopwords, unique_words
))
writefile.write(table.get_string())
#save to outfile
|
711faf6b666cd02f098fe35db3a1e6c5546f87a3 | foxcodenine/practice | /w2resource_python/classes/classes_question1_2.py | 1,673 | 4.375 | 4 | """1. Write a Python class to convert an integer to a roman numeral"""
"""2. Write a Python class to convert a roman numeral to an integer."""
class Convertion:
values = [
('M', 1000), ('CM', 900), ('D', 500), ('CD', 400), ('C', 100),
('XC', 90), ('L', 50), ('XL', 40), ('X', 10), ('IX', 9),
('V', 5), ('IV', 4), ('I', 1)
]
def num_to_roman(self, num):
'''this function convert an int to roman characters.'''
if not isinstance(num, int):
raise ValueError
elif num <= 0:
raise ValueError
else:
roman_num = ''
values = self.values[:]
while num != 0:
tuples = values.pop(0)
factor = num // tuples[1]
roman_num += (tuples[0]*factor)
num -= tuples[1] * factor
return roman_num
def roman_to_num(self, roman):
'''this function convert roman characters to an int.'''
_dict= {}
for tuple in self.values:
_dict.update({tuple[0]: tuple[1]})
number = 0
roman_list = [r for r in roman]
roman_list.append('Z')
while roman_list[0] != 'Z':
# c is for current letter
# n is for next letter
c = roman_list[0]
n = roman_list[1]
c = _dict.get(c)
n = _dict.get(n, 0)
if c >= n:
number += c
else:
number -= c
roman_list.pop(0)
return number
|
ffe234ee3fe1d05ff4320c7bbc6f015163fdbbd3 | pawat88/learn | /PythonCrashCourse/ch5/practice3.py | 1,020 | 4.03125 | 4 | #Hello admin
users = ['big', 'boom', 'admin', 'pa', 'ma']
for user in users:
if user == 'admin':
print("F**, " + user.title())
else:
print("Hello, " + user.title())
#No users
users = []
if users:
for user in users:
if user == 'admin':
print("F**, " + user.title())
else:
print("Hello, " + user.title())
else:
print("Yoou need to find some user!")
#Checking Users
users = ['big', 'boom', 'admin', 'pa', 'ma']
new_users = ['art', 'mix', 'big', 'boom', 'yut']
for new_user in new_users:
if new_user.lower() in users:
print("Username : " + new_user + " is unavailable")
else:
print("You can use " + new_user + " as a username")
#Ordinal Number
numbers = list(range(1,10))
for number in numbers:
if (number == 1):
print(str(number) + "st\n")
elif (number == 2):
print(str(number) + "nd\n")
elif (number == 3):
print(str(number) + "rd\n")
else:
print(str(number) + "th\n")
|
89f987fe70f5ee7eb92335ba1c709af0ce50a90d | dhruvarora93/Algorithm-Questions | /Array Problems/balance_parantheses.py | 1,022 | 3.84375 | 4 | def balance_parens(string):
keep = [False] * len(string)
for idx,letter in enumerate(string):
if letter == '(':
for j in range(idx+1,len(string)):
if not keep[j] and string[j] == ')':
keep[idx] = True
keep[j] = True
break
result = ""
for idx in range(len(string)):
if keep[idx] or (string[idx] != '(' and string[idx] != ')'):
result += string[idx]
return result
def balance_parantheses1(string):
s = list(string)
count = 0
for idx, char in enumerate(s):
if char == '(':
count += 1
elif char == ')':
if count == 0:
s[idx] = '#'
else:
count -= 1
for idx in range(len(s)-1,-1,-1):
if count == 0:
break
if s[idx] == '(':
s[idx] = '#'
count -= 1
return ''.join(s).replace('#','')
print(balance_parantheses1("()())()((")) |
3fcad4e9e8fc1d9614a52f3098392c12829f6588 | TheNathanHernandez/PythonStatements | /Unit 4 - Back To Python/A2 - Loops/part1_countedloops.py | 567 | 3.875 | 4 | from ess import ask
print("FIRST LOOP")
for i in range(5):
print("Hello")
print("")
print("SECOND LOOP")
for j in range(3):
print("j =", j)
print("")
print("THIRD LOOP")
for i in range(6, 10):
print("i =", i)
print("")
print("ADDER")
total = 1
for i in range(4):
num = ask("Enter a number:")
total * num
print("The numbers add to", total)
word = ask("Enter a random word.")
number = ask("Enter a number. This will be used later in the program.")
for i in range(number):
print(word)
print("Your word has been successfully printed", number, "times.") |
87a25cff147b5e3c10e06deddda672dd6d75e9da | alexandraback/datacollection | /solutions_5690574640250880_0/Python/hannanaha/main.py | 11,064 | 3.53125 | 4 | import os
import time
import decimal
import functools
#===============================================================================
# Generic helpers
#===============================================================================
# TODO FOR 14 : rounding functions, graph manipulation, desert lion, AttrDict
#EOL = os.linesep - using this causes weird \r\r\n problems
EOL = "\n"
# ------------------------------------------------------------------------------
def is_equal_approx(x, y, epsilon=1e-6):
"""Returns True iff y is within relative or absolute 'epsilon' of x.
By default, 'epsilon' is 1e-6.
"""
# Check absolute precision.
if -epsilon <= x - y <= epsilon:
return True
# Is x or y too close to zero?
if -epsilon <= x <= epsilon or -epsilon <= y <= epsilon:
return False
# Check relative precision.
return (-epsilon <= (x - y) / x <= epsilon
or -epsilon <= (x - y) / y <= epsilon)
def read_syms(fd):
"""Read a line of whitespace separated symbols."""
return fd.readline().strip().split()
def read_ints(fd):
"""Read a line of whitespace separated integers."""
return [int(p) for p in read_syms(fd)]
def read_floats(fd):
"""Read a line of whitespace separated floats."""
return [float(p) for p in read_syms(fd)]
# ------------------------------------------------------------------------------
class Mtrx(object):
"""A matrix object."""
def __init__(self, rows, cols, data):
assert len(data) == rows * cols
self.rows = rows
self.cols = cols
self.data = data
def cell(self, r, c):
return self.data[r * self.cols + c]
def getrow(self, i):
return [self.cell(i, c) for c in xrange(self.cols)]
def getcol(self, i):
return [self.cell(c, i) for c in xrange(self.rows)]
@classmethod
def readfromfile(cls, fd, readfunc, rows=None, cols=None):
"""Read matrix from file, assuming first line at location is `R C`.
Return a new Mtrx object. Reading values is performed by the `readfunc`.
Pre-determined size can be passed using `rows` and `cols`.
"""
data = []
if rows is None:
assert cols is None
rows, cols = read_ints(fd)
else:
assert cols is not None
for _ in range(rows):
line = readfunc(fd)
assert len(line) == cols
data.extend(line)
return Mtrx(rows, cols, data)
@classmethod
def read_int_matrix(cls, fd, rows=None, cols=None):
return cls.readfromfile(fd, read_ints, rows, cols)
@classmethod
def read_sym_matrix(cls, fd, rows=None, cols=None):
return cls.readfromfile(fd, read_syms, rows, cols)
def __str__(self):
res = ""
for i in xrange(self.rows):
res += str(self.getrow(i)) + EOL
return res
def __repr__(self):
return "{}({}, {}, {})".format(self.__class__.__name__, self.rows,
self.cols, self.data)
# ------------------------------------------------------------------------------
cachetotals = 0
cachemisses = 0
def statreset():
global cachemisses, cachetotals
cachemisses = 0
cachetotals = 0
class memoizeit(object):
"""Decorator. Caches a function's return value each time it is called.
If called later with the same arguments, the cached value is returned
(not reevaluated).
"""
def __init__(self, func):
self.func = func
self.cache = {}
def __call__(self, *args):
# update stats
global cachetotals, cachemisses
cachetotals += 1
try:
return self.cache[args]
except KeyError:
# update stats
cachemisses += 1
value = self.func(*args)
self.cache[args] = value
return value
except TypeError:
# update stats
cachemisses += 1
# uncachable -- for instance, passing a list as an argument.
# Better to not cache than to blow up entirely.
return self.func(*args)
@property
def __name__(self):
return self.func.__name__
def __get__(self, obj, objtype):
"""Support instance methods."""
return functools.partial(self.__call__, obj)
# ------------------------------------------------------------------------------
class timeit(object):
"""Decorator that times a function.
When function ends, print name, runtime, return value and cache stats.
"""
def __init__(self, func):
self.func = func
def __call__(self, *args):
start = time.time()
value = self.func(*args)
delta = time.time() - start
cachedata = (1 - cachemisses/(cachetotals * 1.0)) if \
cachetotals else 0
print self.func.__name__, "{:7.3f}s, (res: {}, cache: {:.2%})".format(
delta, value, cachedata)
return value
def __get__(self, obj, objtype):
return functools.partial(self.__call__, obj)
#===============================================================================
# Input/output
#===============================================================================
def read_input(filename):
data = []
with open(filename, "r") as f:
cases = read_ints(f)[0]
# =============================================
for _ in xrange(cases):
case = {}
case["R"], case["C"], case["M"] = read_ints(f)
data.append(case)
# =============================================
return data
def make_output(fname, output):
CASE_PRFX = "Case #%s: "
fname = fname + time.strftime("%H%M%S") + ".out"
with open(fname, "w") as f:
restext = []
print "Output content ==============="
# =============================================
for i, outdata in enumerate(output):
line = CASE_PRFX % (i + 1,) + EOL + str(outdata) + EOL
print line,
restext.append(line)
# =============================================
print "=" * 30
f.writelines(restext)
#===============================================================================
# Actual solution
#===============================================================================
MINE = "*"
CLICK = "c"
UNK = "."
class Board(object):
def __init__(self, r, c):
self.rows = r
self.cols = c
self.edge_row_idx = self.rows - 1
self.edge_col_idx = self.cols - 1
self.board = [[UNK for _ in xrange(c)] for _ in xrange(r)]
self.board[0][0] = CLICK
def fill_edge_row(self, m):
i = self.edge_col_idx
while m > 0 and i >= 0:
self.board[self.edge_row_idx][i] = MINE
i -= 1
m -= 1
self.edge_row_idx -= 1
def fill_edge_col(self, m):
i = self.edge_row_idx
while m > 0 and i >= 0:
self.board[i][self.edge_col_idx] = MINE
i -= 1
m -= 1
self.edge_col_idx -= 1
def __str__(self):
return EOL.join(["".join(r) for r in self.board])
@memoizeit
def is_stage_solvable(rows, cols, mines):
"""Return True iff stage is solvable.
Also return fill instruction:
0 if impossible/dontcare, 1 to fill row, 2 to fill column,
3 for row special (most in the row), 4 for col special (most in the col)
"""
rc = rows * cols
# all full
if mines == rc:
return False, 0
if rows == 1:
return mines <= rc - 1, 2
if cols == 1:
return mines <= rc - 1, 1
# rows and cols > 1
# single cell in corner
if mines == rc - 1:
return True, 1 # doesn't matter what to fill
# won't find 4 cells for the corner
if mines > rc - 4:
return False, 0
if rows == 2:
return (False, 0) if mines == 1 else (True, 2)
if cols == 2:
return (False, 0) if mines == 1 else (True, 1)
# rows and cols > 2
if rows <= cols:
# try to fill columns
if mines >= rows:
return True, 2
if mines == rows - 1:
if mines == cols - 1:
if rows == 3:
return False, 0
return True, 4 # L shape fill, most in the column
else:
return True, 1 # fill row
return True, 2
else:
# try to fill rows
if mines >= cols:
return True, 1
if mines == cols - 1:
if mines == rows - 1:
if cols == 3:
return False, 0
return True, 3 # L shape fill, most in the row
else:
return True, 2 # fill column
return True, 1
@timeit
def solveit(case):
rows = case["R"]
cols = case["C"]
mines = case["M"]
b = Board(rows, cols)
r, c, m = rows, cols, mines
while m >= 0:
okgo, howtofill = is_stage_solvable(r, c, m)
if not okgo:
return "Impossible"
if howtofill == 1: # fill row
b.fill_edge_row(m)
if m <= c:
break # fill and done
m -= c
r -= 1
elif howtofill == 2: # fill column
b.fill_edge_col(m)
if m <= r:
break # fill and done
m -= r
c -= 1
elif howtofill == 3: # L shape fill, most in the row
b.fill_edge_row(m - 1)
b.fill_edge_col(1)
break # fill and done
elif howtofill == 4: # L shape fill, most in the column
b.fill_edge_col(m - 1)
b.fill_edge_row(1)
break # fill and done
else:
assert False
return str(b)
#===============================================================================
# Main
#===============================================================================
@timeit
def main(fname):
data = read_input(fname)
output = []
for case in data:
statreset() # reset cache stats
# =============================================
res = solveit(case)
output.append(res)
# =============================================
make_output(fname, output)
if __name__ == '__main__':
# main("sample.in")
main("C-small-attempt0.in")
# main("B-large.in")
# main("B-small-attempt0.in")
# main("A-large.in") |
ed6909792ec99771e1852b0bda092bbbf8dc0bfe | bolof2000/AutomationInPython | /test/zipFunction.py | 636 | 3.703125 | 4 |
class Car():
def __init__(self):
print("default construtor")
#define the functionalities of a car
def drive(self):
print("car drives")
def stop(self):
print("car stops")
def accelerate(self):
print("car accelerate")
#toyota inherits Car properties
class Toyota(Car):
def __init__(self):
Car.__init__(self)
def fly(self):
print("toyota flies")
def zoom(self):
print("toyota zoom")
def drive(self):
print("toyota drive in his own class")
c = Car()
t = Toyota()
c.accelerate()
c.drive()
t.accelerate()
t.fly()
t.drive()
|
dd838864f3026b12c9737fcbc9fca6d8d2e34d8c | laxmanlax/Programming-Practice | /InterviewCake/25_kth_to_last_node.py | 801 | 4 | 4 | #!/usr/bin/env python
class LinkedListNode:
def __init__(self, value):
self.value = value
self.next = None
def kth_to_last_node(k, head):
prev, curr = head, head
# Move curr k-1 nodes ahead of head/prev.
for _ in xrange(k - 1):
if not curr.next: raise Exception("List is too short to get the kth to last node.")
curr = curr.next
# Not `while curr` since then would go one node too far.
while curr.next:
prev, curr = prev.next, curr.next
return prev
a = LinkedListNode("Angel Food")
b = LinkedListNode("Bundt")
c = LinkedListNode("Cheese")
d = LinkedListNode("Devil's Food")
e = LinkedListNode("Eccles")
a.next = b
b.next = c
c.next = d
d.next = e
assert kth_to_last_node(3, a).value == 'Cheese'
print 'Test passed!'
|
b32ef7a040576a323702894e9d58f4bcc86a2381 | la-ursic/redtape | /operadores.py | 216 | 3.859375 | 4 | x = y = z = 5
print ("comenzando el programa, x era igual a",x)
print (y)
print (z)
a,b,c = 1,2*3,"Jose"
print (a)
print (b)
print (c)
x = x + 10
x += 10
print ("después de todos los cálculos, x es igual a",x,"") |
4bf324948d49fae967016defa1a95b8f2f95dd44 | mendesivan/Python-the-Basics | /Inheritance.py | 546 | 3.9375 | 4 | #Inheritance
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
#Use the Person class to create an object, and then execute the printname method:
x = Person("John", "Doe")
x.printname()
# Create a class named Student, which will inherit the properties and methods from the Person class:
class Student(Person):
pass
#passes function of Person to Student.
x = Student("Mike","Olsen")
x.printname()
|
cd831087c3ab91c725ec85553658b83d28b0308d | blxnca/python | /kata challenges/detect_pangram.py | 470 | 4.1875 | 4 | # Given a string, detect whether or not it is a pangram.
# Return True if it is, False if not.
# Ignore numbers and punctuation.
import string
from string import ascii_lowercase
def is_pangram(s):
alphabet = "abcdefghijklmnopqrstuvwxyz"
chars = list(filter(lambda x: x in ascii_lowercase,s.lower()))
for i in alphabet:
if i not in chars:
return False
return True
is_pangram("The quick, brown fox jumps over the lazy dog!") # True |
ecf831580cd81836a15980aa1fd7de74ad12ecea | jj0hns0n/impactmap | /modules/cities_on_map.py | 2,173 | 3.6875 | 4 | import numpy
import os
from geodesy import Point
def cities_on_map(A, distance_limit=100):
"""Put selected cities on map.
Ensure that cities shown are at least dis_lim km apart.
Input
A: Selected cities sorted by intensity and population.
distance_limit: Minimum distance [km] between cities shown on map (default is 100 km)
Output
Generates text file for use by GMT to plot cities on map
"""
# Always take the first city (which is the one with the highest intensity)
index = [0]
# Indices of all remaining cities
T = range(1, len(A))
# Loop through remaining cities and determine which to plot
T2 = []
b = 0
while True:
# Find cities more than distance_limit km away from city b (anchor city)
for i in range(len(T)):
k = T[i] # Index of other city
start = Point(latitude=A['lat'][b], longitude=A['lon'][b]) # Anchor city
end = Point(latitude=A['lat'][k], longitude=A['lon'][k]) # Other city
r = start.distance_to(end)/1000 # Calculate distance and convert to km
if r >= distance_limit:
# Select city i because it is sufficiently far away from anchor city
T2 += [(k)]
# Determine whether to use more cities or not
if len(T2) > 1:
# If more than one candidate exist pick the first of the selected cities as new anchor city
b = T2[0]
index += [(b)]
# Replace T with what now remains and reset T2
T = T2[1:]
T2 = []
elif len(T2) == 1:
# If only one city exists add it and exit loop
index += [(T2[0])]
break
else:
# If no cities were found exit loop
break
# Make sure there is no old file hanging around
cmd = '/bin/rm -rf city.txt'
os.system(cmd)
# Record selected cities in GMT file
city_filename = 'city.txt'
for i in index:
cmd = 'cat << END >> %s' % city_filename + '\n'+''+str(A['lon'][i])+' '+str(A['lat'][i])+' 15 0 0 BR '+A['name'][i]+'\n'+'END'
os.system(cmd)
|
b46ab1e5f70778aef60d7cea1d22d69360d01d9a | restavratof/python-cert | /sandbox/ex_iterator.py | 845 | 3.765625 | 4 |
def test():
print(__name__)
print('EXAMPLE:')
class I:
def __init__(self, var='samle'):
self.s = var
self.i = 0
def __iter__(self):
return self
def __next__(self):
if self.i == len(self.s):
raise StopIteration
v = self.s[self.i]
self.i += 1
return v
for x in I('hello'):
print(x, end='')
print('\n','-'*50)
print('FIBONACCI:')
class Fib:
def __init__(self, nn):
print("__init__")
self.__n = nn
self.__i = 0
self.__p1 = self.__p2 = 1
def __iter__(self):
print("__iter__")
return self
def __next__(self):
print("__next__")
self.__i += 1
if self.__i > self.__n:
raise StopIteration
if self.__i in [1, 2]:
return 1
ret = self.__p1 + self.__p2
self.__p1, self.__p2 = self.__p2, ret
return ret
for i in Fib(10):
print(i) |
f0c674ec2822d0b189e907539137941784cdb718 | andersondi/simple-games | /guess_a_number.py | 3,147 | 4.0625 | 4 | #!/usr/bin/env python
"""
Guess_a_number v.1
This is my first program (Hello world's like don't count, ok?!)
This is a classic one and allowed me to try some:
- Functions
- Loops and conditionals
"""
import random
def score_monitor(actual_score, secret_number, attempt, level):
how_far_was_the_attempt = abs(secret_number - (attempt / level))
actual_score = actual_score - how_far_was_the_attempt
return actual_score
def choose_difficulty():
selector = 0
number_of_attempts = 0
while (selector < 1 or selector > 3):
print("Choose the difficulty:")
selector_str = input("( 1 ) EASY\n( 2 ) MEDIUM\n( 3 ) HARD\n")
selector = int(selector_str)
if selector == 1:
number_of_attempts = 20
elif selector == 2:
number_of_attempts = 10
elif selector == 3:
number_of_attempts = 5
else:
print("Invalid option\n\n")
return number_of_attempts, selector
def play():
print("*********************")
print("** Guess a Number! **")
print("*********************")
inferior_limit = 1
superior_limit = 100
actual_score = 1000
# ================================================================================
def get_number(inferior_limit, superior_limit):
# Tests whether the number is within the allowed range
player_attempt = 0
number_below = True
number_above = True
while (number_below or number_above):
player_attempt_str = input("Type a number\n")
print(f"You have typed...{player_attempt_str}\n")
player_attempt = int(player_attempt_str)
if (number_below or number_above):
print(f"Only tries between {inferior_limit} and {superior_limit} are allowed.\nPlease, try again.\n")
number_below = player_attempt < inferior_limit
number_above = player_attempt > superior_limit
return player_attempt
def generate_secret_number(inferior_limit, superior_limit):
return round(random.randrange(inferior_limit, superior_limit + 1))
secret_number = generate_secret_number(inferior_limit, superior_limit)
number_of_attempts, level = choose_difficulty()
for actual_round in range(1, number_of_attempts + 1):
print(f"Your score was: {actual_score}")
print(f"Attempt {actual_round} of {number_of_attempts}")
attempt = get_number(inferior_limit, superior_limit)
hit = secret_number == attempt
greater = attempt > secret_number
lesser = attempt < secret_number
if (hit):
print("You hit! Congratulation!\n")
print(f"Your final score was {actual_score}\n")
break
else:
if (greater):
print("\n\nWrong choise!\n TIP --> Your attempt was ABOVE of secret number.\n")
elif (lesser):
print("\n\nWrong choise!\n TIP --> Your attempt was BELOW of secret number.\n")
actual_score = score_monitor(actual_score, secret_number, attempt, level)
if(__name__ == "__main__"):
play()
|
26fcd8a814e3172a4a6fdd4960267a71462f30e1 | HyunIm/Baekjoon_Online_Judge | /Problem/5361.py | 272 | 3.578125 | 4 | price = (350.34, 230.90, 190.55, 125.30, 180.90)
testCase = int(input())
for _ in range(testCase):
A, B, C, D, E = map(float, input().split())
part = [A, B, C, D, E]
cost = 0
for i in range(5):
cost += part[i] * price[i]
print('$%.2f'%cost)
|
76c8f11ad81f26940248528a09f52f915359fba3 | aleksandromelo/Exercicios | /ex080.py | 399 | 3.6875 | 4 | c = 0
v = []
ultimo = 0
anterior = 0
atual = 0
while c < 6:
n = int(input('Digite um valor: '))
if c == 0:
v.append(n)
ultimo = n
print('Adicionado ao final da lista...')
if c == 1 and n < ultimo:
anterior = n
v.insert(0, anterior)
else:
v.append(n)
anterior = ultimo
ultimo = n
c += 1 |
2bd2b7357eee21b758249d56a3f81745382463d2 | qw632076202/9602skydataTool | /UI/DividingLine.py | 409 | 3.703125 | 4 | #!/usr/bin/python3
# -*- coding: UTF-8 -*-
#图形库包
from tkinter import *
class DividingLine:
fatherComponent = NONE
dividingLine = NONE
def __init__(self, fatherComponent, placeX, placeY):
self.fatherComponent = fatherComponent
super().__init__()
self.dividingLine = Label(self.fatherComponent, text='-'*180, font=('宋体', 13))
self.dividingLine.place(x = placeX, y = placeY)
|
4c4994aee2891c0b55b7da7f862037030bd41348 | fresjo/Prog-klass | /klasser.py | 678 | 3.5625 | 4 | class Pistol(object):
def __init__(self, antalskott):
self.magasin=antalskott
def skjut(self):
print "PANG"
self.magasin=self.magasin-1
if self.magasin<1:
print "Out of Ammo"
def reload(self):
print "reload"
self.magasin=20
def emptymag(self):
print "emtymag"
self.magasin=0
def info(self):
print "Ammo ="
return self.magasin
a=2
b=2
A_pistol=Pistol(a)
print A_pistol.info()
A_pistol.skjut()
print A_pistol.info()
A_pistol.emptymag()
print A_pistol.info()
A_pistol.reload()
print A_pistol.info()
B_pistol=Pistol(b)
print B_pistol.info()
B_pistol.skjut()
B_pistol.skjut()
print B_pistol.info()
B_pistol.reload()
print B_pistol.info()
|
e4c379eafa99ab0e2045b572e2c873b6422b2f02 | Agoming/python-note | /3.高级语法/协程和生成器、迭代器/生成器01-06/04.py | 287 | 4.34375 | 4 | # ʹyieldشgenerator
def odd():
print("step 1")
yield 1
print("step 2")
yield 3
print("step 3")
yield 5
o = odd()
print(next(o)) # ᷢÿµþͻǴһηصyieldпʼִ
print(next(o))
print(next(o)) |
be051f2b5e3fa61b4ca6087e9614f620c41189e8 | pyladies-sergipe/challenges-python | /desafios-py/iniciante/d0000-bem-vinda/d0000-bem-vinda-v1.py | 286 | 3.9375 | 4 | ########
# autora: danielle8farias@gmail.com
# repositório: https://github.com/danielle8farias
########
#strip() remove espaços em branco no início e no fim da string
#capitalize() torna a primeira letra maiúscula
nome = input('Digite seu nome: ').strip().capitalize()
print(f'Bem-vinda, {nome}!')
|
06a8b8d558950dcc1cb8f0d30fcd81090abca41b | claraqqqq/i_c_s_p_a_t_m_i_t | /ps4/ps4_9.py | 7,883 | 3.5625 | 4 | # YOU AND YOUR COMPUTER (1 point possible)
"""
computer the give to need you word, a choose can computer your that Now
playGame the re-implements that code the Write play. to option the
in below described as behave to function the modify will You function.
HAND_SIZE the use should you before, As comments. function's the
out try to sure Be hand. a in cards of number the determine to constant
program. your with HAND_SIZE for values different
Hints and Output Sample
look... should output game the how is Here
end to e or hand, last the replay to r hand, new a deal to n Enter
n game:
u play: computer the have to c play, yourself have to u Enter
t t t e r s a Hand: Current
tatters finished: are you that indicate to "." a or word, Enter
points 99 Total: points. 99 earned "tatters"
points. 99 score: Total letters. of out Run
end to e or hand, last the replay to r hand, new a deal to n Enter
r game:
c play: computer the have to c play, yourself have to u Enter
t t t e r s a Hand: Current
points 99 Total: points. 99 earned "stretta"
points. 99 score: Total
end to e or hand, last the replay to r hand, new a deal to n Enter
x game:
command. Invalid
end to e or hand, last the replay to r hand, new a deal to n Enter
n game:
me play: computer the have to c play, yourself have to u Enter
command. Invalid
you play: computer the have to c play, yourself have to u Enter
command. Invalid
c play: computer the have to c play, yourself have to u Enter
n l x d e c a Hand: Current
points 65 Total: points. 65 earned "axled"
n c Hand: Current
points. 65 score: Total
end to e or hand, last the replay to r hand, new a deal to n Enter
n game:
u play: computer the have to c play, yourself have to u Enter
o z h h y p a Hand: Current
zap finished: are you that indicate to "." a or word, Enter
points 42 Total: points. 42 earned "zap"
o h h y Hand: Current
oy finished: are you that indicate to "." a or word, Enter
points 52 Total: points. 10 earned "oy"
h h Hand: Current
. finished: are you that indicate to "." a or word, Enter
points. 52 score: Total Goodbye!
end to e or hand, last the replay to r hand, new a deal to n Enter
r game:
c play: computer the have to c play, yourself have to u Enter
o z h h y p a Hand: Current
points 80 Total: points. 80 earned "hypha"
o z Hand: Current
points. 80 score: Total
end to e or hand, last the replay to r hand, new a deal to n Enter
e game:
output the about Hints
is little very - carefully output sample above the inspect to sure Be
printed the of Most specifically. function this in out printed actually
and playHand in wrote you code the from comes actually output
function uses and modular is code your that sure be - compPlayHand
functions! helper these to calls
You function. helper dealHand the to calls make also should You
so written we've that function helper other any to calls make shouldn't
code of lines 15-20 about in written be can function this fact, in - far
.
and playHand from output the with output, above the is Here
obscured: compPlayHand
end to e or hand, last the replay to r hand, new a deal to n Enter
n game:
u play: computer the have to c play, yourself have to u Enter
playHand> to <call
end to e or hand, last the replay to r hand, new a deal to n Enter
r game:
c play: computer the have to c play, yourself have to u Enter
compPlayHand> to <call
end to e or hand, last the replay to r hand, new a deal to n Enter
x game:
command. Invalid
end to e or hand, last the replay to r hand, new a deal to n Enter
n game:
me play: computer the have to c play, yourself have to u Enter
command. Invalid
you play: computer the have to c play, yourself have to u Enter
command. Invalid
c play: computer the have to c play, yourself have to u Enter
compPlayHand> to <call
end to e or hand, last the replay to r hand, new a deal to n Enter
n game:
u play: computer the have to c play, yourself have to u Enter
playHand> to <call
end to e or hand, last the replay to r hand, new a deal to n Enter
r game:
c play: computer the have to c play, yourself have to u Enter
compPlayHand> to <call
end to e or hand, last the replay to r hand, new a deal to n Enter
e game:
approachable. more bit a seem problem the makes hint this Hopefully
Runtime On Note A
is This plays. computer the when slowly run things that notice may You
to free feel optional!), (totally want you If expected. be to
is way one - faster go turn computer's the making of ways investigate
so int) -> (string dictionary a into list word the preprocess to
the in faster much becomes word a of score the up looking
function. compChooseWord
- time one preprocessing this do to want only you - though careful Be
of bottom the (at you for wordList the generate we after right probably
inputs what modify to have you'll this, do to choose you If file). the
of instead dictionary word a take probably (they'll take functions your
example). for list, word a
the in code your running when issue this about worry IMPORTANT:Don't
than smaller (much wordList sample small very a load We below! checker
work will code Your out. time code your having avoid to words!) 83667
described. as pre-processing of form a implement don't you if even
Code Your Entering
the in ps4b.py from playGame for definition your paste only to sure Be
definitions. function other any include not Do box. following
"""
def playGame(wordList):
"""
hands. of number arbitrary an play to user the Allow
'e'. or 'r' or 'n' input to user the Asks 1)
game. the exit immediately 'e', inputs user the If *
again. them asking keep 'e', or 'r', 'n', not that's anything inputs user the If *
'c'. a or 'u' a input to user the Asks 2)
again. them asking keep 'u', or 'c' not that's anything inputs user the If *
choices: above the on based functionality Switch 3)
hand. (random) new a play 'n', inputted user the If *
again. hand last the play 'r', inputted user the if Else, *
game the play user the let 'u', inputted user the If *
playHand. using hand, selected the with
the play computer the let 'c', inputted user the If *
compPlayHand. using hand, selected the with game
1 step from repeat hand, the played has user or computer the After 4)
(string) list wordList:
"""
label1 = True
cnt = 0
while label1:
choice1 = raw_input('Enter n to deal a new hand, r to replay the last hand, or e to end game: ')
label2 = True
if choice1 == 'n':
hand = dealHand(HAND_SIZE)
hand_copy = hand.copy()
while label2:
choice2 = raw_input('Enter u to have yourself play, c to have the computer play: ')
if choice2 == 'u':
playHand(hand, wordList, HAND_SIZE)
cnt += 1
label2 = False
elif choice2 == 'c':
compPlayHand(hand, wordList, HAND_SIZE)
cnt += 1
label2 = False
else:
print 'Invalid command.'
elif choice1 == 'r':
if cnt == 0:
print 'You have not played a hand yet. Please play a new hand first!'
else:
hand = hand_copy.copy()
while label2:
choice2 = raw_input('Enter u to have yourself play, c to have the computer play: ')
if choice2 == 'u':
playHand(hand, wordList, HAND_SIZE)
label2 = False
elif choice2 == 'c':
compPlayHand(hand, wordList, HAND_SIZE)
label2 = False
else:
print 'Invalid command.'
elif choice1 == 'e':
label1 = False
else:
print 'Invalid command.'
|
1d36a0cec63d0a13f7db4f4d58c5f561160611cc | mrozsypal81/323-Compilers-Assignment-3 | /compiler/syntax_analyzer/syntax_analyzer.py | 2,676 | 3.515625 | 4 | class Syntax_analyzer (object):
def __init__(self, *arg):
self.lexemes = arg
# print('arg = ', arg)
# statemenize method - create statement list from lexemes
def syntaxA(self):
lexemes = list(self.lexemes[0])
begin = 0
tablestart = 5000
resultlist = []
print('len(lexemes) = ', len(lexemes))
while begin < len(lexemes) and begin >= 0:
isCheck, result, newBegin,newtablestart = checkAllRules(lexemes, begin,tablestart)
print('Returned from CheckAllRules')
resultlist.append(result)
print('isCheck = ', isCheck)
for i in result:
print(i)
begin = newBegin
tablestart = newtablestart
print('\n\n')
print('Done with all Lexemes')
return resultlist
# ==============================================
# End class here
# ==============================================
def checkAllRules(arg, begin,tablestart):
count = begin
tablecount = tablestart
availableLen = len(arg) - begin
print('availableLen = ', availableLen)
#This returns the next semicolon position so that you can tell where to end
#print("Begin value")
print(begin)
semicolkey,semicolval,semicolpos = getSpecificKV(arg,";",begin)
templist = arg[begin:semicolpos+1]
print("++++++++++++++++++++templist++++++++++++++++")
print(templist)
print("++++++++++++++++++++++++++++++++++++++++++++")
#testkey,testval,testpos = getSpecificKVreverse(arg,"+",semicolpos)
#print("isDeclarative Check in CheckAllRules")
if len(templist) == 3:
#print("Going into isDeclarative CheckAllRules")
isDeclare, resultDeclare = isDeclarative (templist)
#print("Return from isDeclarative in CheckAllRules")
if isDeclare:
count = begin + 3
return isDeclare, resultDeclare, count
eqkey,eqval,eqpos = getSpecificKV(templist,"=",0)
#print("isAssign Check in CheckAllRules")
if eqval == "=":
#print("Going into isAssign in CheckAllRules")
isAss, resultAssign, AddCount = isAssign (templist)
#print("Return from isAssign in CheckAllRules")
if isAss:
count += AddCount
return isAss, resultAssign, count
#print("Going into isExpress in CheckAllRules")
isExp, resultExpress, AddCount,newpos = isExpress(templist,0)
#print("Return from isExpress in CheckAllRules")
if isExp:
count += AddCount
return isExp,resultExpress,count
#print('End of CheckAllRules')
return False,[],-1
|
5648d09bec523551c32684e17e429960c4f95356 | Sophiall/ERGASIES | /Εrgasia2 PARENTHESEIS.py | 411 | 3.5625 | 4 | def Par(par):
stack = []
push = "({["
pop = ")}]"
for ch in par :
if ch in push:
stack.append(ch)
elif ch in pop:
if len(stack) != 0 :
top = stack.pop()
br = push[pop.index(ch)]
if top != br:
return False
else:
return False
return len(stack) == 0
if __name__ == '__main__':
par = raw_input('Enter the parenthesis:\n')
print Par(par) |
d57e1839c5846f7894508a009d5a2d06d5057ba2 | Danilo-mr/Python-Exercicios | /Exercícios/ex054.py | 201 | 3.9375 | 4 | maioridade = 0
for c in range(1, 8):
ano = int(input('Digite o ano de nascimento: '))
if 2020-ano >= 18:
maioridade += 1
print(f'{maioridade} pessoas já atingiram a maioridade')
|
04c9a101f3cf262751388c1f2fd48c94863a08b9 | dunitian/BaseCode | /python/2.OOP/3Polymorphism/1.isinstance.py | 438 | 4.03125 | 4 | # 判断一个变量是否是某个类型 ==> isinstance() or Type
class Animal(object):
pass
class Dog(Animal):
pass
def main():
dog = Dog()
dog2 = Dog()
print(type(dog) == Dog)
print(type(dog) == type(dog2))
print(type(dog))
print(isinstance(dog, Dog))
print(isinstance(dog, Animal))
# arg 2 must be a type or tuple
# print(isinstance(dog, dog2))
if __name__ == '__main__':
main()
|
769f2490497fc3f87d17686d09024b9677fc616e | iznauy/LeetCode | /09.py | 966 | 3.65625 | 4 | class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x < 0:
return False
t = 1
while x / t >= 10:
t *= 10
p = t
while True:
if t * t <= p:
return True
else:
left = (x / t) % 10
right = (x % (p * 10 / t)) / (p / t)
if left != right:
return False
t /= 10
class Solution1(object): # don't allow
def isPalindrome(self, s):
return str(s) == str(s)[::-1]
class Solution2(object):
def isPalindrome(self, x):
if x < 0 or (x != 0 and x % 10 == 0):
# necessary
return False
else:
t = 0
while x > t:
t = 10 * t + x % 10
x /= 10
return x == t or x == (t / 10)
|
8b7678294038764895325093d4fb4050414591e7 | wongcyrus/ite3101_introduction_to_programming | /lab/lab03/ch03_t06_grand_finale.py | 114 | 3.5 | 4 | from datetime import datetime
now = datetime.now()
print('%02d:%02d:%04d' % (now.hour, now.minute, now.second))
|
6e5934e75b34f05b98261b7374f067f4819a2c60 | kickbean/LeetCode | /LC/LC_longestCommonPrefix.py | 736 | 3.859375 | 4 | '''
Write a function to find the longest common prefix string amongst an array of strings.
Created on Feb 12, 2014
@author: Songfan
'''
''' compare each position of every string until unequal '''
def solution(strs):
n = len(strs)
if n == 0: return ''
if n == 1: return strs[0]
# find minimum length of the strings
minLen = len(strs[0])
for s in strs:
tmpLen = len(s)
if tmpLen < minLen:
minLen = tmpLen
res = ''
for i in range(minLen): # position
c = strs[0][i]
for j in range(1, n): # strings
if c != strs[j][i]:
return res
res += c
return res
strs = ['abc','ab','acd']
print solution(strs) |
f2813ba4cce38b0f7a6d9564f941bc85342d6fcb | FisicaComputacionalOtono2018/20180816-clase-diagramadeflujoparprimo-melilednav | /j.py | 232 | 3.796875 | 4 | def asfg(x):
if x<2:
flag=False
elif x==2:
flag=True
else:
flag=True
for i in range (2,x-1)=
if x%i==0:
flag=False
break
return flag
p=input("num")
if asfg(p):
print("es primo")
else:
print("no es primo")
|
f093312f730995cd054b1a01ea94ba3180767b89 | cohadar/learn-python-the-hard-way | /ex38.py | 554 | 3.8125 | 4 | ten_things = "Apples Oranges Crows Telephone Light Sugar"
print "Wait there are not 10 things in that list. Let's fix that."
stuff = ten_things.split(' ')
more_stuff = ["Day", "Night", "Song", "Frisbee", "Corn", "Banana", "Girl", "Boy"]
while len(stuff) < 10:
one_stuff = more_stuff.pop()
stuff.append(one_stuff)
print stuff
print stuff[-1]
print '#@'.join(stuff[3:6])
colors = list('abcd')
numbers = ['A', 2, 3, 4, 5, 6, 7, 8, 9, 10, 'Z', 'L', 'K']
cards = [(color, number) for color in colors for number in numbers]
print len(cards)
print cards |
316d5808dbeb89f2aea4726297a25e0c9ae066ce | ncfausti/python-algorithms | /MakeChange.py | 738 | 3.96875 | 4 | """Make change given the fewest amount of coins."""
Coins = {25, 10, 5, 1}
def make_change(amount):
"""Make change given the fewest amount of coins."""
coin_count = 0
while amount > 0:
if amount >= 25:
amount -= 25
coin_count += 1
continue
if amount < 25 and amount > 10:
amount -= 10
coin_count += 1
continue
if amount < 10 and amount > 5:
amount -= 5
coin_count += 1
continue
# Handle pennies here
amount -= 1
coin_count += 1
return coin_count
assert(make_change(25) == 1)
assert(make_change(36) == 3)
assert(make_change(4) == 4)
assert(make_change(72) == 6)
|
ea2d49babd0262534092875e6fce3a8cbab275d0 | rubengr16/OSSU | /ComputerScience/2_MIT6.00.1x_Introduction_to_Computer_Science/2_Core_Elements_of_Programs/happy_world.py | 164 | 4.15625 | 4 | # Print hello world if a number entered by the user is strictly greater than 2
happy = int(input('Enter a number: '))
if happy > 2:
print('happy world', happy)
|
5bd4237b2db53246110fd799bae01420f378ee9f | guiconti/workout | /crackingthecodeinterview/arrays/1-3.py | 328 | 4.09375 | 4 | # Replaces all spaces in a string with %20
# Solution 1 goes through each character in a string if it's a space put a %20
def Solution1(a):
a = list(a.strip())
for i in range(len(a)):
if a[i] == ' ':
a[i] = '%20'
return ''.join(a)
if __name__ == '__main__':
a = 'ab obo ra ameixa '
print(Solution1(a)) |
e9cca559ca1a1b820faa6ad989e2004d24b79e9e | lschanne/DailyCodingProblems | /year_2019/month_03/2019_03_08__maze_min_steps.py | 2,295 | 4.40625 | 4 | '''
March 8, 2019
You are given an M by N matrix consisting of booleans that represents a board.
Each True boolean represents a wall. Each False boolean represents a tile you
can walk on.
Given this matrix, a start coordinate, and an end coordinate, return the
minimum number of steps required to reach the end coordinate from the start.
If there is no possible path, then return null. You can move up, left, down,
and right. You cannot move through walls. You cannot wrap around the edges of
the board.
For example, given the following board:
[[f, f, f, f],
[t, t, f, t],
[f, f, f, f],
[f, f, f, f]]
and start = (3, 0) (bottom left) and end = (0, 0) (top left), the minimum
number of steps required to reach the end is 7, since we would need to go
through (1, 2) because there is a wall everywhere else on the second row.
'''
# Classic dijkstra's algorithm
# Now how does that algorithm go again...
def get_min_steps(maze, start, end):
# return null if no solution exists
no_solution = None
# maze[row][col] = True iff there is a wall there
if maze[start[0]][start[1]] or maze[end[0]][end[1]]:
return no_solution
nodes = {
(row, col): float('inf') for row in range(len(maze))
for col in range(len(maze[0])) if not maze[row][col]
}
# it takes 0 moves to get to the starting position
nodes[tuple(start)] = 0
while nodes:
this_key = min(nodes.keys(), key=nodes.get)
this_dist = nodes.pop(this_key)
if this_key == tuple(end):
return this_dist
for diff in zip((-1, 1, 0, 0), (0, 0, -1, 1)):
neighbor = (this_key[0] + diff[0], this_key[1] + diff[1])
# Only valid moves are contained in the nodes dict
if neighbor in nodes:
nodes[neighbor] = this_dist + 1
return no_solution
if __name__ == '__main__':
import sys
start, end = ([int(x) for x in y.split(',')] for y in sys.argv[1:3])
print('start: {}'.format(start))
print('end: {}'.format(end))
print('maze:')
maze = []
for row in sys.argv[3:]:
row = [True if x == 't' else False for x in row.split(',')]
print(row)
maze.append(row)
result = get_min_steps(maze, start, end)
print('min steps to solve: {}'.format(result))
|
bfcfcbd925d38caec0e553c45e516355ea8d045b | Lunderberg/advent-of-code-2019 | /python/d17.py | 7,191 | 3.546875 | 4 | #!/usr/bin/env python3
from collections import defaultdict
import inspect
import math
import sys
import time
import util
class Memory(list):
"""
Implements a self-expanding memory of integers.
"""
def __getitem__(self,key):
if key < 0:
raise IndexError('Negative memory pos {} not allowed.'.format(key))
elif key >= len(self):
return 0
else:
return super().__getitem__(key)
def __setitem__(self, key, value):
if key < 0:
raise IndexError('Negative memory pos {} not allowed.'.format(key))
extension_needed = (key+1) - len(self)
if extension_needed > 0:
self.extend([0]*extension_needed)
super().__setitem__(key, value)
class Interpreter:
def __init__(self, memory, input_val = None, output_callback = None):
self.memory = Memory(memory[:])
self.ip = 0
self.output_callback = output_callback
self.input_val = input_val
self.output_val = None
self.done = False
self.paused = False
self.relative_base = 0
@property
def input_val(self):
return self._input_val
@input_val.setter
def input_val(self,val):
self._input_val = val
self.paused = False
def iteration(self):
opcode = self.memory[self.ip] % 100
if opcode == 1:
self.op_add()
elif opcode == 2:
self.op_mul()
elif opcode == 3:
self.op_input()
elif opcode == 4:
self.op_output()
elif opcode == 5:
self.op_jump_if_true()
elif opcode == 6:
self.op_jump_if_false()
elif opcode == 7:
self.op_lt()
elif opcode == 8:
self.op_eq()
elif opcode == 9:
self.op_adjust_relative_base()
elif opcode == 99:
pass
else:
raise ValueError('Unknown opcode: {}'.format(opcode))
self.done = (opcode == 99)
def get_mode(self,i):
mode = self.memory[self.ip]
mode = mode // (10**(i+1))
mode = mode % 10
return mode
def get_param(self,i):
mode = self.get_mode(i)
val = self.memory[self.ip+i]
if mode==0:
val = self.memory[val]
elif mode==1:
val = val
elif mode==2:
val = self.memory[val + self.relative_base]
else:
raise ValueError('Unknown mode {} at ip={}, value={}'.format(
mode, self.ip, self.memory[self.ip]
))
return val
def set_param(self, i, val):
mode = self.get_mode(i)
addr = self.memory[self.ip + i]
if mode==0:
self.memory[addr] = val
elif mode==1:
raise ValueError('Cannot use mode==1 (immediate mode) for output params')
elif mode==2:
self.memory[addr + self.relative_base] = val
def op_add(self):
a = self.get_param(1)
b = self.get_param(2)
x = a+b
self.set_param(3, x)
self.ip += 4
def op_mul(self):
a = self.get_param(1)
b = self.get_param(2)
x = a*b
self.set_param(3, x)
self.ip += 4
def op_input(self):
if self.input_val is None:
self.paused = True
return
else:
x = self.input_val
self.input_val = None
self.set_param(1, x)
self.ip += 2
def op_output(self):
a = self.get_param(1)
self.output_val = a
if self.output_callback is not None:
self.output_callback(a)
self.ip += 2
def op_jump_if_true(self):
a = self.get_param(1)
b = self.get_param(2)
if a:
self.ip = b
else:
self.ip += 3
def op_jump_if_false(self):
a = self.get_param(1)
b = self.get_param(2)
if not a:
self.ip = b
else:
self.ip += 3
def op_lt(self):
a = self.get_param(1)
b = self.get_param(2)
x = int(a<b)
self.set_param(3, x)
self.ip += 4
def op_eq(self):
a = self.get_param(1)
b = self.get_param(2)
x = int(a==b)
self.set_param(3, x)
self.ip += 4
def op_adjust_relative_base(self):
a = self.get_param(1)
self.relative_base += a
self.ip += 2
def iterate_until_done(self):
while not self.done and not self.paused:
self.iteration()
directions = [(0,1), (0,-1), (1,0), (-1,0)]
class Scaffolds:
def __init__(self, memory):
self.memory = memory
self.cam_x = 0
self.cam_y = 0
self.tiles = {}
interp = Interpreter(memory, output_callback=self.camera)
interp.iterate_until_done()
self.xmax = max(x for x,y in self.tiles)
self.ymax = max(y for x,y in self.tiles)
def camera(self, c):
c = chr(c)
if c in ('#', '<', '>', '^', 'v'):
self.tiles[(self.cam_x, self.cam_y)] = c
self.cam_x += 1
elif c=='.':
self.cam_x += 1
elif c=='\n':
self.cam_x = 0
self.cam_y += 1
def intersections(self):
output = []
for point in self.tiles:
x,y = point
if all( (x+dx,y+dy) in self.tiles for (dx,dy) in directions):
output.append(point)
return output
def draw(self):
intersections = self.intersections()
xmin = min(x for x,y in self.tiles)
xmax = max(x for x,y in self.tiles)
ymin = min(y for x,y in self.tiles)
ymax = max(y for x,y in self.tiles)
for y in range(0,ymax+1,1):
for x in range(0,xmax+1):
pos = (x,y)
if pos in intersections:
c = 'O'
elif (x,y) in self.tiles:
c = self.tiles[pos]
else:
c = '.'
print(c,end='')
print()
def give_directions(self,
main='A,B,C,A,B,C',
a='',
b='',
c='',
feed=False):
memory = self.memory[:]
memory[0] = 2
def callback(c):
if c<256:
print(chr(c), end='')
else:
print(c)
interp = Interpreter(memory, output_callback=callback)
feed = 'y' if feed else 'n'
commands = '\n'.join([main,a,b,c,feed,''])
for c in commands:
interp.input_val = ord(c)
interp.iterate_until_done()
def main():
memory = [int(x.strip()) for x in
util.get_puzzle_input().split(',')]
s = Scaffolds(memory)
print(sum(x*y for (x,y) in s.intersections()))
s.give_directions(
main='A,C,C,B,C,B,C,B,A,A',
a = 'L,6,R,8,L,4,R,8,L,12',
b = 'L,12,L,6,L,4,L,4',
c = 'L,12,R,10,L,4',
feed = False,
)
if __name__ == '__main__':
main()
|
7983ecb49a0c4fa1bb16825f23fbf287f4933aa0 | TayExp/pythonDemo | /05DataStructure/二叉树的深度.py | 721 | 3.59375 | 4 | # -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def IsBalanced_Solution(self, pRoot):
# write code here
return self.IsBalanced(pRoot, 0)[0]
def IsBalanced(self, pRoot, depth):
if pRoot is None:
return True, 0
bLeft, depthLeft = self.IsBalanced(pRoot.left, depth)
bRight, depthRight = self.IsBalanced(pRoot.right, depth)
if bLeft and bRight:
diff = depthLeft - depthRight
if diff <= 1 and diff >= -1:
return True, max(depthLeft, depthRight) + 1
return False, max(depthLeft, depthRight) + 1 |
b39812f326c6d646907469fe657fb8aa3583868c | ashbwil/LeetCode | /28/implement_str.py | 539 | 3.515625 | 4 | class Solution(object):
def strStr(self, haystack, needle):
length_needle = len(needle)
n = 0
h = 0
if needle == "":
return 0
if needle not in haystack:
return -1
else:
while n < length_needle:
if haystack[h] == needle[n]:
h = h + 1
n = n + 1
final = h - length_needle
else:
h = h - n + 1
n = 0
return final |
3ce2f087927640c36e56c1de07e268cc97ed0565 | mitamit/OW_Curso_Python | /metodos_string.py | 610 | 4.0625 | 4 | curso = "Curso"
my_string = "codigo facilito"
result = "{} de {}".format(curso, my_string)
print(result)
result = "{a} de {b}".format(b = curso, a = my_string) #con alias
#formato
#result = result.lower() #minusculas
#result = result.upper() #mayusculas
#result = result.title() #como titulo
print(result)
#busqueda
pos = result.find('facilito')
print(pos)
count = result.count('c')
print(count)
#substitucion
new_string = result.replace('c', 'x') #cambia las c por x
print(new_string)
new_string2 = result.split(' ') #devuelve un array con el contenido entre los espacios
print(new_string2)
|
7769422afc47e67572b69f80342273a21f2ebd4c | Sajirimendjoge/Python-Assignments | /Task_1/a8.py | 447 | 3.84375 | 4 | # Q.8 If one data type value is assigned to ‘a’ variable and then a different data type value is assigned to ‘a’ again. Will it change the value. If Yes then Why?
#Answer = Yes
#demo:
a = 7
print(type(a))
#output = <class 'int'>
a = 2.5
print(type(a))
#output = <class 'float'>
#Reason:
'''
Because Python is a dymanic language where variables can be reinitialiosed again and again.
The data type of the variables is not static.
''' |
76611440884dc79c9982baa28a16140642d85c54 | AlbertoGiampietrri/python-lessons | /18-fileIn-fileOut.py | 490 | 3.53125 | 4 | def readFile(fileName):
out = []
file = open(fileName)
r = file.readlines()
file.close()
for e in r:
out.append(e.replace("\n", ""))
return out
def saveFile(fileName, list):
file = open(fileName, "w")
for r in list:
file.write(str(r) + "\n")
file.close()
carrello = readFile("./18-input-file.txt")
for e in carrello:
print(e)
print("aggiungo cioccolata al carrello e salvo il file")
carrello.append("cioccolata")
saveFile("./18-output-file.txt", carrello) |
72bd46df9805409604c517c14214b173b67014ef | 1456121347/demo1 | /day03/中国工商银行账户管理系统.py | 8,402 | 3.921875 | 4 | import random
# 准备数据
bank = {} # 空的数据库
bank_name = "中国工商银行昌平回龙观支行"
def bank_addUser(account,username,password,country,province,street,door):
# 是否已满
if len(bank) > 100:
return 3
# 是否存在
if username in bank:
return 2
# 正常开户
bank[username] = { #1
"account":account,
"password":password,
"country":country,
"province":province,
"street":street,
"door":door,
"money":1000,
"bank_name":bank_name
}
return 1
# 用户的开户操作
def addUser():
global bank
username = input("请输入用户名:")
password = input("请输入密码:")
print("请输入您的个人详细地址:")
country = input("\t\t国籍:")
province = input("\t\t省份:")
street = input("\t\t街道:")
door = input("\t\t门牌号:")
account = random.randint(6214850200000001,6214850200000501)
print(account)
status = bank_addUser(account,username,password,country,province,street,door)
if status == 3:
print("对不起,该银行用户已满,请携带证件到其他银行办理!")
elif status == 2:
print("对不起,该用户已开户,请不要重复开户!别瞎弄!")
elif status == 1:
print("恭喜正常开户!以下是您的个人信息:")
info = '''
------------个人信息------------
用户名:%s
银行卡号:%s
密码:*****
国籍:%s
省份:%s
街道:%s
门牌号:%s
余额:%s
开户行名称:%s
'''
print(info % (username,account,country,province,street,door,bank[username]["money"],bank_name))
#取钱3.取钱(传入值:用户的账号,用户密码,取钱金额。返回值:整型值
# (0:正常,1:账号不存在,2:密码不对,3:钱不够)) a)业务逻辑:
# 先根据账号信息来查询该用户是否存在,若不存在,则返回代号1,
# 若存在,则继续判断密码是否正确,若不正确,则返回代号2。
# 若账号密码都正确,则继续判断当前用户的金额是否满足要取出的钱,若不满足,则返回代号3,
# 若满足,则将该用户的金额减去。
def deposit():
global addUser
for i in bank.keys():
get_account = input("请输入银行卡号:")
print("你输入的卡号:", get_account)
get_password = input("请输入密码:")
get_account = int(bank[i]["account"])
if get_account == get_account and get_password == bank[i]["password"]:
gets_money = int(input("请输入你的取款金额"))
print(gets_money)
if gets_money > bank[i]["money"]:
print("卡内余额不足!无法取出")
elif gets_money <= bank[i]["money"]:
bank[i]["money"] = bank[i]["money"]- gets_money
print("取款成功","目前余额{}".format(bank[i]["money"]))
else:
print("输入非法!请正确输入!")
elif get_account != get_account and get_password == bank[i]["password"]:
print("用户输入错误!")
elif get_account == get_account and get_password != bank[i]["password"]:
print("用户密码输入错误!")
else:
print("该用户不存在")
def adddeposit():
global addUser
for i in bank.keys():
get_account = input("请输入银行卡号:")
print("你输入的卡号:", get_account)
get_password = input("请输入密码:")
get_account = int(bank[i]["account"])
if get_account == get_account and get_password == bank[i]["password"]:
gets_money = int(input("请输入你的存金额"))
print(gets_money)
if gets_money + bank[i]["money"] > 1000000000:
print("卡内最多只能存取1000000000")
elif gets_money <= 1000000000 - bank[i]["money"] :
bank[i]["money"] = bank[i]["money"] + gets_money
print("存款成功","目前余额{}".format(bank[i]["money"]))
else:
print("输入非法!请正确输入!")
elif get_account != get_account and get_password == bank[i]["password"]:
print("用户输入错误!")
elif get_account == get_account and get_password != bank[i]["password"]:
print("用户密码输入错误!")
else:
print("该用户不存在")
#查询5.查询账户功能(传入值:账号,账号密码,返回值:空)a)业务逻辑:
# 先根据账号判断用户库是否存在该用户,若不存在则打印提示信息:该用户不存在。
# 否则继续判断密码是否正确。若不正确则打印相对应的错误信息。
# 若账号和密码都正确,则将该用户的信息都打印出来,比如:
# 当前账号:xxxx,密码:xxxxxx,余额:xxxx元,用户居住地址:xxxxxxxxxxxxx,当前账户的开户行:xxxxxxxxxx.
def find_addUser():
global addUser
for i in bank.keys():
get_account = input("请输入银行卡号:")
print("你输入的卡号:",get_account)
get_password = input("请输入密码:")
get_account = int(bank[i]["account"])
if get_account == get_account and get_password == bank[i]["password"]:
print("登录成功!,下面显示该用户信息:")
info = '''
------------个人信息------------
用户名:%s
银行卡号:%s
密码:%s
国籍:%s
省份:%s
街道:%s
门牌号:%s
余额:%s
开户行名称:%s
'''
print(info % (i,bank[i]["account"],bank[i]["password"],bank[i]["country"], bank[i]["province"], bank[i]["street"], bank[i]["door"], bank[i]["money"], bank_name))
elif get_account != get_account and get_password == bank[i]["password"]:
print("用户输入错误!")
elif get_account == get_account and get_password != bank[i]["password"]:
print("用户密码输入错误!")
else:
print("该用户不存在")
# 转账
def transfer():
number = input("请输入您要转账的账号:")
uname = input("请输入您要转账的用户名:")
money = int(input("请输转账金额:"))
for i in bank.keys():
if i == uname:
bank[i]['money'] = bank[i]['money'] + money
print(uname,'用户的帐户余额为',bank[i]['money'])# 转账
def transfer():
number = input("请输入您要转账的账号:")
uname = input("请输入您要转账的用户名:")
money = int(input("请输转账金额:"))
for i in bank.keys():
if i == uname:
bank[i]['money'] = bank[i]['money'] + money
print(uname,'用户的帐户余额为',bank[i]['money'])
break
break
def welcome():
print("----------------------------------------")
print("- 中国工商银行账户管理系统V1.0 -")
print("----------------------------------------")
print("- 1.开户 -")
print("- 2.取钱 -")
print("- 3.存钱 -")
print("- 4.转账 -")
print("- 5.查询 -")
print("- 6.Bye! -")
print("-------------------------------------- -")
# 入口程序
while True:
welcome()
# 输入用户的业务逻辑
chose = input("亲输入您的业务:")
if chose == "1":
addUser()
elif chose == "2":
deposit()
elif chose == "3":
adddeposit()
elif chose == "4":
transfer()
elif chose == "5":
find_addUser()
elif chose == "6":
break
else:
print("输入非法,别瞎弄!重新输入!")
|
e872ad22ef7217a5122440d568e387327f030426 | nyroro/leetcode | /LC212.py | 1,720 | 3.796875 | 4 | class Node(object):
def __init__(self):
self.next = {}
self.end = False
self.word = ''
class Solution(object):
def insert(self, word):
now = self.root
for character in word:
if character not in now.next:
now.next[character] = Node()
now = now.next[character]
now.end = True
now.word = word
def build_tries(self, words):
self.root = Node()
for word in words:
self.insert(word)
def dfs(self, board, i, j, now_node):
if board[i][j] in now_node.next:
now_node = now_node.next[board[i][j]]
else:
return
if now_node.end:
self.ret.add(now_node.word)
self.visits[i][j] = True
steps = [[0,1],[0,-1],[1,0], [-1,0]]
for step in steps:
ni, nj = i+step[0], j+step[1]
if 0<=ni<len(board) and 0<=nj<len(board[0]):
if not self.visits[ni][nj]:
self.dfs(board, ni, nj, now_node)
self.visits[i][j] = False
def findWords(self, board, words):
"""
:type board: List[List[str]]
:type words: List[str]
:rtype: List[str]
"""
self.build_tries(words)
if len(board) == 0 or len(board[0]) == 0:
return []
self.ret = set()
for i in xrange(len(board)):
for j in xrange(len(board[0])):
self.visits = [[False]*len(board[0]) for k in xrange(len(board))]
self.dfs(board, i, j, self.root)
return list(self.ret)
|
926199223e402ef6e050d309a4460a52f21fa947 | Shridevi-PythonDev/quotebook | /day2_exercises.py | 690 | 4.03125 | 4 |
## 1. Exercise 1
name = "Ram"
height = 5.6
age = 30
print(name, height, age)
print(type(name), type(height))
print(type(age))
##2
x = 10
y = 20.1
z = 30
sum1 = x+y+z
print("sum of 3 variables: ", sum1)
### 3 Range
print(list(range(1, 11)))
###4
print(list(range(0, 30, 5)))
### 5
print(list(range(0, 11, 3)))
###list(range('days', 'month'))
## 6
cricket = [10.2, 90, "IPL"]
print(cricket)
## 7
temprature = [10.2, 20, "rainfal", [11, 30.2, 'rain']]
print(temprature)
## 8
mylist = [1, 2, 3, 4, 5, 6, 7]
sqr_list = [x * x for x in mylist]
print(type(sqr_list))
## 9
mylist = ["John", "", "Sam", "", "", "Ram"]
mylist_filter = list(filter(None, mylist))
print(mylist_filter)
|
5995249305bd3a040b701b64087575adfe56f809 | swornim00/house_price_prediction | /house_price_prediction.py | 2,657 | 3.734375 | 4 | from csv import reader
import matplotlib.pyplot as plt
#Function to import csv file and make put the data into dataset list
def read_file(filename):
dataset = list()
with open(filename,'r') as file:
csv_reader = reader(file)
for row in csv_reader:
dataset.append(row)
return dataset
# Converting string into float cause we cannot do arithmetic operations on string
def str_to_float(dataset):
for row in dataset:
for i in range(len(row)):
row[i] = float(row[i])
# Finding out maximum and minimum from dataset for the normalizatoin
def minmax(dataset):
minmax = list()
_min = min(dataset[0])
_max = max(dataset[0])
minmax.append([_min,_max])
return minmax
# Normalizing the data to build a better model
def normalize(dataset,minmax):
for row in dataset:
for i in range(len(row)):
row[i] = (row[i] - minmax[0]) / (minmax[1] - minmax[0])
# Prediction Function
def predict(x,coef):
y = coef[0] + coef[1] * x
return y
# Optmization Function to find the best coeffiecient
def find_coef(dataset,l_rate,epoch):
coef = [0.0 for i in range(len(dataset[0]))]
for i in range(epoch):
for row in dataset:
y = predict(row[0],coef)
error = y - row[1]
coef[0] = coef[0] - error * l_rate
for i in range(len(row) - 1):
coef[i+1] = coef[i+1] - error * l_rate * row[i]
return coef
# Plotting on graph to visualize everything
def plot_on_graph(dataset,predicted):
#Plotting on the graph
fig, ax = plt.subplots()
for row in dataset:
ax.plot(row[0],row[1],marker='o', markersize=3, color="red")
for row in predicted:
ax.plot(row[0],row[1],marker='o',color="black")
ax.grid(True, which='both')
ax.set_aspect('equal')
ax.set_xlabel("Prices per SQ/Ft")
ax.set_ylabel("Size of the house")
plt.show()
# Learning Rate
l_rate =0.01
# Number of Iteration
epoch = 50
# Temporary Dataset cause we just need two colums from this dataset
tmp_dataset = read_file('RealEstate.csv')
dataset = list() #Dataset as list
for row in tmp_dataset:
dataset.append([row[5], row[6]]) #Taking row 5 and 6 into the database
dataset.pop(0) # Popping out the first row cause it's justlabel
str_to_float(dataset)
minmax = minmax(dataset)
normalize(dataset,minmax[0])
coef = find_coef(dataset,l_rate,epoch)
predicted = list() # Declaring predicted as a list
for row in dataset:
predicted.append([row[0],predict(row[0],coef)]) #Predicting the values
plot_on_graph(dataset,predicted) # Plotting graphs to visualize
|
5f322bdf26e570696db5d8c6461ae337d12d22e0 | aregmi450/MCSC202PYTHON | /Q1.py | 1,113 | 4.21875 | 4 | # A ball is thrown vertically up in the air from a height h 0 above the ground at an initial
# velocity v 0 . Its subsequent height h and velocity v are given by the equations
# h = ho + vo t− gt^2
# v = vo − gt
# where g = 9.8 is the acceleration due to gravity in m/s 2 . Write a script that finds the
# height h and velocity v at a time t after the ball is thrown. Start the script by setting h 0 =
# 1.2 (meters) and v 0 = 5.4 (m/s) and have your script print out the values of height and
# velocity.
# Then use the script to find the height and velocity after 0.5 seconds.
# Then modify your script to find them after 2.0 seconds.
def getHeightAndVelocity(timePeriod):
g=9.8
ho=1.2
vo=5.4
h=ho+(vo*timePeriod)-(0.5*g*timePeriod*timePeriod)
v=vo-(g*timePeriod)
return {
"height":h,
"velocity":v
}
print('Height at t=0.5 =>', getHeightAndVelocity(0.5)['height'])
print('Velocity at t=0.5 =>', getHeightAndVelocity(0.5)['velocity'])
print('Height at t=2.0 =>', getHeightAndVelocity(2.0)['height'])
print('Velocity at t=2.o =>', getHeightAndVelocity(2.0)['velocity'])
|
cca40f9563f0dbeff1c91cce9519be81d0fe10fd | sehun4239/Python_Basic | /01_remind.py | 2,159 | 3.921875 | 4 | # my_range = range(10) # 시작, 끝, 증감치 지정이 필요함 - 걍 10만 쓰면 끝이 10이고 증감치 1
# print(my_range)
# print(my_range[1:4]) # range(1, 4) -> slicing은 원본 데이터 유형 그대로 따라감
# # my_range = range(1, 10, 3)
#
# print(list(my_range))
# print(len(my_range))
#
# sum=0
# for i in range(11):
# sum+=i
# print('총 합계는 %d입니다' %sum)
#
# print('1', end = '')
# print('2')
list2 = ['1','2','3','2','4']
list3 = list2[: : -1]
print()
mystr = "12"
restr = mystr[: : -1]
print(restr)
my_dict = {"김":1000, "장":100}
sum = 0
for (key, value) in my_dict.items():
sum += value
print(my_dict.values())
my_dict = {"stu" + str(x): x ** 2 for x in range(1, 10)}
print("my_dict : {0}".format(my_dict))
animal = ["멍멍이","사자","호랑이","개"]
print(",".join(animal))
print("-".join(animal))
a = [1,2,3]
b = ["a","b","c"]
c = list(zip(a,b))
print(c)
str=list(zip("Hello","World"))
print(str)
# map() : 특정함수에 입력값을 주어 반복 호출
def my_func(x):
return x**2
a = list(map(my_func,range(1,10)))
print(a)
a = [ 1, 3, 5, 7, 9, 13, 15 ]
b = [ 4, 5, 6, 8, 13 ]
c = [ 5, 8, 13, 19 ]
d = set(a).intersection(set(b))
e = d.intersection(set(c))
result = list(e)
print(result)
phone_number = "010-1111-2222"
ans = phone_number.replace("-"," ")
print(ans)
string = 'abcdfe2a354a32a'
print(list(bin(27)))
n=6
arr1 = [46, 33, 33, 22, 31, 50]
arr2 = [27, 56, 19, 14, 14, 10]
list_1 = [list(bin(i))[2:] for i in arr1]
list_2 = [list(bin(i))[2:] for i in arr2]
def mola(list):
for i in list:
if len(i) < 6:
while len(i) <= 5 :
i.insert(0,"0")
return list
real_1 = mola(list_1)
real_2 = mola(list_2)
result = []
print(list(zip(real_1,real_2)))
for (i,j) in zip(real_1,real_2):
result2 = []
for num in range(n):
if i[num] == "0" and j[num] == "0":
result2.append(" ")
elif i[num] == "1" or j[num] == "1":
result2.append("#")
result.append(result2)
print(result)
ans = ["".join(i) for i in result]
print(ans)
# ["######", "### #", "## ##", " #### ", " #####", "### # "]
|
8afc5a11c0cfa541f21d5f525e1cd274c02483f9 | HangCoder/micropython-simulator | /tests/basics/string_join.py | 817 | 3.796875 | 4 | print(','.join(()))
print(','.join(('a',)))
print(','.join(('a', 'b')))
print(','.join([]))
print(','.join(['a']))
print(','.join(['a', 'b']))
print(''.join(''))
print(''.join('abc'))
print(','.join('abc'))
print(','.join('abc' for i in range(5)))
print(b','.join([b'abc', b'123']))
try:
''.join(None)
print("FAIL")
raise SystemExit
except TypeError as e:
pass
try:
print(b','.join(['abc', b'123']))
print("FAIL")
raise SystemExit
except TypeError as e:
pass
try:
print(','.join([b'abc', b'123']))
print("FAIL")
raise SystemExit
except TypeError as e:
pass
# joined by the compiler
print("a" "b")
print("a" '''b''')
print("a" # inline comment
"b")
print("a" \
"b")
# the following should not be joined by the compiler
x = 'a'
'b'
print(x)
print("PASS") |
2bfeb9ef91e036c2d21a02f1baa67ac77297c177 | silpaps/mypython | /self/guees_game.py | 177 | 3.828125 | 4 | sc="giraffe"
guess=""
print("it's an animal")
print("mostly found in east africa")
print("tallest animal")
while sc!=guess:
guess=input("give your guess")
print("you win")
|
9858017ed80aa63561be68f63dc08837d2e98622 | Hovden/tomviz | /tomviz/python/Shift_Stack_Uniformly.py | 784 | 3.515625 | 4 | #Shift all data uniformly (it is a rolling shift)
#
#developed as part of the tomviz project (www.tomviz.com)
def transform_scalars(dataset):
from tomviz import utils
import numpy as np
#----USER SPECIFIED VARIABLES-----#
#SHIFT = [0,0,0] #Specify the shifts (x,y,z) applied to data
###SHIFT###
#---------------------------------#
data_py = utils.get_array(dataset) #get data as numpy array
if data_py is None: #Check if data exists
raise RuntimeError("No data array found!")
data_py = np.roll( data_py, SHIFT[0], axis = 0)
data_py = np.roll( data_py, SHIFT[1], axis = 1)
data_py = np.roll( data_py, SHIFT[2], axis = 2)
utils.set_array(dataset, data_py)
print('Data has been shifted uniformly.')
|
8dbdca87d3aa5b77c0b8b3f75addb2ba05a5a09b | zhaoww/python-notes | /study/test06.py | 734 | 4 | 4 | # -*-coding:utf-8-*-
# list生成式 [expr for iter_var in iterable if cond_expr]
list0 = [x * x for x in (range(1, 10)) if x % 2 == 0]
print(list0)
# 生成器[] -> ()
list1 = (x * x for x in (range(1, 10)) if x % 2 == 0)
print(list1)
for x in list1:
print(x, end = ' ')
# yield
# 函数是顺序执行,遇到 return 语句或者最后一行函数语句就返回。而变成 generator 的函数,
# 在每次调用 next() 的时候执行,遇到 yield语句返回,再次执行时从上次返回的 yield 语句处继续执行
def odd():
print ( 'step 1' )
yield ( 1 )
print ( 'step 2' )
yield ( 3 )
print ( 'step 3' )
yield ( 5 )
o = odd()
print( next( o ) )
print( next( o ) )
print( next( o ) ) |
0260224543d1b2f8b51e3cbf22530d176fa1a684 | Zane-ThummBorst/Python-code | /Factorial code.py | 1,117 | 4.21875 | 4 | #
# Zane ThummBorst
#
#9/9/19
#
# demonstrate recursiuon through the factorial
# and list length
def myFactorial(x):
''' return the factorial of x assuming x is > 0'''
# if x == 0:
# return 1
# else:
# return x * myFactorial(x-1)
return 1 if x==0 else x*myFactorial(x-1)
#print(myFactorial(2))
def myLength(L):
'''return the length of the list L'''
if L == []:
return 0
else:
return 1 + myLength(L[1:])
#print(myLength([1,2,3]))
def LCS(S1,S2):
''' return the longest common subsequence between the strings'''
# if len(S1) == 0 or len(S2) == 0:
# return 0
# elif S1[0] == S2[2]:
# #A common firsdt character adds 1 to LCS
# return 1 + LCS(S1[1:], S2[1:])
# else:
# #Drop either first character and recurse
# max(LCS(S1, S2[1:]), LCS(S1, S2[1:]))
#NEXT EXAMPLE IS CRUCIAL FOR RECURSION LAB
def deepLength(L):
if not L:
return 0
else:
head, tail = L[0], L[1:]
headVal = deepLength(head) if isinstance(head,list)else 1
return headVal + deepLength(tail)
|
057c066c503ef3ccd285e2f8d3b36164a5a75a3a | Jayu8/Python3 | /INTRODUCTION.py | 1,278 | 4 | 4 | """Pyton interactive shell:
A shell in biology is a calcium carbonate "wall" which protects snails or mussels from its environment or its enemies.
Python offers a comfortable command line interface with the Python shell, which is also known as the "Python interactive shell".
Python Internals:
Python is both an interpreted and a compiled language.
Python code is translated into intermediate code, which has to be executed by a virtual machine, known as the PVM.
Variables and data types:
As variables are pointing to objects and objects can be of arbitrary data type, variables cannot have types associated with them
x=42. here x is a variable which REFERENCE this newly created object to any data type in this case to int. 42 is an object.
Sequence Types — str, unicode, list, tuple, bytearray, buffer, xrange:
String- methods, formatting
List[] -mutable - push pop peek append,exrend,remove
Tuple() -immutable
Deep and shallow copy:
Usually shallow copy that is x=y point to same object , deep copy seperate objects (C like)
Input:
eval(input("Please enter")) #eval converts input to desired datatype
Print => format method.
print("The capital of {province} is {capital}".format(province="Ontario",capital="Toronto"))
DICTIONARY acess print ** , list *
"""
|
d06bec897147ed6cb62ec2bf0e79212d7a307840 | laurencepettitt/AusculNet-Classifier | /ausculnet/preprocessing/data_augmentation/__init__.py | 1,466 | 3.71875 | 4 | import numpy as np
import pandas as pd
def randomly_crop_recording_sample(sample, sample_rate):
"""
Crops the beginning and end (at random length) off a sample.
Args:
sample: floating point time series representing audio sample
sample_rate: sample rate of time series
Returns:
Cropped sample
"""
sample_length = len(sample)
crop_max = max(3 * sample_rate, sample_length / 3) # TODO - explain
crop_head = np.random.randint(crop_max)
crop_tail = np.random.randint(crop_max)
start, end = crop_head, sample_length - crop_tail
return sample[start:end]
def augment_samples_by_random_crop(data_set, frac, random_state=None):
"""
Augments data set by randomly cropping a random fraction of it's samples
Args:
data_set: pandas dataframe
Must have columns 'audio_recording' and 'sample_rate'
frac: float
fraction of samples in data set to create a randomly cropped version of
random_state: int or numpy.random.RandomState, optional
Seed for the random number generator
Returns:
"""
assert frac > 0
replace = False if frac <= 1 else True
samples = data_set.sample(frac=frac, replace=replace, random_state=random_state)
samples['audio_recording'] = samples.apply(
lambda row: randomly_crop_recording_sample(row.audio_recording, row.sample_rate), axis=1)
return pd.concat([data_set, samples])
|
d8d5cb8402eca71774efd6b1c494a035f6fd9617 | lamb-j/machine-learning | /hw/hw1/submit/id3.py | 5,270 | 3.703125 | 4 | #!/usr/bin/python
#
# CIS 472/572 -- Programming Homework #1
#
# Starter code provided by Daniel Lowd, 1/20/2017
# You are not obligated to use any of this code, but are free to use
# anything you find helpful when completing your assignment.
#
import sys
import re
# Node class for the decision tree
import node
import math
# SUGGESTED HELPER FUNCTIONS:
# - collect counts for each variable value with each class label
def collect_counts(data):
output = [item[len(data[0]) - 1] for item in data]
pos = output.count(1)
neg = output.count(0)
return pos, neg
# - compute entropy of a 2-valued (Bernoulli) probability distribution
def compute_entropy(v1, v2):
if (v1 == 0 or v2 == 0):
return 0
p1 = v1 / float(v1 + v2)
p2 = v2 / float(v1 + v2)
e = -p1 * math.log(p1, 2) - p2 * math.log(p2, 2)
return e
# - partition data based on a given variable
def split_data(data, var):
l_data = []
r_data = []
# right data 1, left data 0
for i in range(0, len(data)):
if data[i][var]:
r_data.append(data[i])
else:
l_data.append(data[i])
return l_data, r_data
# - compute information gain for a particular attribute
def compute_gain(data, var):
if (len(data) == 0):
print "ERROR data == 0"
return
# compute entropy of the root
pos, neg = collect_counts(data)
entropy_s = compute_entropy(pos, neg)
# compute left and right entropy after splitting
l_data, r_data = split_data(data, var)
if (len(r_data) == 0 or len(l_data) == 0):
return 0
l_pos, l_neg = collect_counts(l_data)
entropy_l = compute_entropy(l_pos, l_neg)
r_pos, r_neg = collect_counts(r_data)
entropy_r = compute_entropy(r_pos, r_neg)
# compute information gain
l_p = len(l_data) / float(len(data))
r_p = len(r_data) / float(len(data))
gain = entropy_s - l_p*entropy_l - r_p*entropy_r
return gain
# - find the best variable to split on, according to mutual information
def compute_max_gain(data, varnames):
max_gain = 0
max_index = -1
# compute the max gain
for i in range(0, len(varnames) - 1):
gain = compute_gain(data, i)
#print "var", varnames[i], "gain", gain
if (gain > max_gain):
max_gain = gain
max_index = i
#print "max_gain computed:", max_gain, "var:", varnames[max_index], "index:", max_index
return max_index
# Load data from a file
def read_data(filename):
f = open(filename, 'r')
p = re.compile(',')
data = []
header = f.readline().strip()
varnames = p.split(header)
namehash = {}
for l in f:
data.append([int(x) for x in p.split(l.strip())])
return (data, varnames)
# Saves the model to a file. Most of the work here is done in the
# node class. This should work as-is with no changes needed.
def print_model(root, modelfile):
f = open(modelfile, 'w+')
root.write(f, 0)
# Build tree in a top-down manner, selecting splits until we hit a
# pure leaf or all splits look bad.
def build_tree(data, varnames, depth):
#print "Current Depth:", depth
if len(data) == 0:
print "BAD SPLIT"
return
# compute the max gain
split_index = compute_max_gain(data, varnames)
# Base cases
if split_index == -1:
#print "LEAF CASE"
#print data
#print "\n"
# choose whichever result is more common
pos, neg = collect_counts(data)
#print "pos:", pos, "neg:", neg
if pos > neg:
return node.Leaf(varnames, 1)
else:
return node.Leaf(varnames, 0)
# split the data at max_index attribute
l_data, r_data = split_data(data, split_index)
# make new node split
# left child - buildtree on left split
# right child - buildtree on right split
var = varnames[split_index]
#print "SPLIT CASE:", var
#print "\n"
#print "***Recursing L_tree***"
#print l_data
L_tree = build_tree(l_data, varnames, depth+1)
#print "***L_tree returned, depth=", depth
#print "***Recursing R_tree***"
#print r_data
R_tree = build_tree(r_data, varnames, depth+1)
#print "***R_tree returned, depth=", depth
return node.Split(varnames, split_index, L_tree, R_tree)
# Load train and test data. Learn model. Report accuracy.
def main(argv):
if (len(argv) != 3):
print 'Usage: id3.py <train> <test> <model>'
sys.exit(2)
# "varnames" is a list of names, one for each variable
# "train" and "test" are lists of examples.
# Each example is a list of attribute values, where the last element in
# the list is the class value.
(train, varnames) = read_data(argv[0])
(test, testvarnames) = read_data(argv[1])
modelfile = argv[2]
# build_tree is the main function you'll have to implement, along with
# any helper functions needed. It should return the root node of the
# decision tree.
root = build_tree(train, varnames, 0)
print_model(root, modelfile)
correct = 0
# The position of the class label is the last element in the list.
yi = len(test[0]) - 1
for x in test:
# Classification is done recursively by the node class.
# This should work as-is.
pred = root.classify(x)
if pred == x[yi]:
correct += 1
acc = float(correct)/len(test)
print "Accuracy: ",acc
if __name__ == "__main__":
main(sys.argv[1:])
|
0edd5f84d8d3e432b99aecc29ef8812e8b50294f | 23sarahML/projet2 | /exercies/ex2_bp_tree.py | 2,512 | 3.53125 | 4 | import json
def first(values):
return values[0]
def div_round_up(a, b):
return (a + b - 1) // b
def transpose(columns):
rows = [list(row) for row in zip(*columns)]
return rows
class BPTreeNode:
def __init__(self, keys: list, values: list, is_leaf: bool):
self._keys = keys
self._values = values
self.is_leaf = is_leaf
self.next_leaf = None
def to_dict(self):
values = (
self._values
if self.is_leaf
else [value.to_dict() for value in self._values]
)
return {
"is_leaf": self.is_leaf,
"keys": self._keys,
"values": values,
}
def __str__(self):
return json.dumps(self.to_dict(), indent=4)
def find_inclusive(self, key1, key2):
# Your code for exercise 2 (b) goes here.
pass
def find(self, key):
return self.find_inclusive(key, key)
def _compute_tree_height(num_leaves, m):
height = 1
while num_leaves > 1:
num_leaves = div_round_up(num_leaves, 2 * m + 1)
height += 1
return height
def _make_bp_tree_recursive(leaves, m, depth, height):
if depth == height:
leaf = leaves.pop()
minimum = leaf._keys[0]
maximum = leaf._keys[-1]
return leaf, minimum, maximum
else:
results = [
_make_bp_tree_recursive(leaves, m, depth + 1, height)
for _ in range(2 * m + 1)
if leaves
]
children, minimums, maximums = transpose(results)
minimum = minimums[0]
maximum = maximums.pop()
node = BPTreeNode(keys=maximums, values=children, is_leaf=False)
return node, minimum, maximum
def make_bp_tree(key_value_pairs, m=10) -> BPTreeNode:
if not key_value_pairs:
return BPTreeNode(keys=[], values=[], is_leaf=True)
key_value_pairs = sorted(key_value_pairs, key=first)
num_leaves = div_round_up(len(key_value_pairs), 2 * m)
height = _compute_tree_height(num_leaves, m)
leaves = []
for i in range(num_leaves):
start = i * 2 * m
end = (i + 1) * 2 * m
keys, groups = transpose(key_value_pairs[start:end])
leaves.append(BPTreeNode(keys=keys, values=groups, is_leaf=True))
for leaf1, leaf2 in zip(leaves, leaves[1:]):
leaf1.next_leaf = leaf2
leaves = list(reversed(leaves))
root, minimum, maximum = _make_bp_tree_recursive(leaves, m, 1, height)
return root
|
da23d032c17055b2698218d8c12668a8ff522a13 | gugarosa/textformer | /textformer/models/layers/position_wide_forward.py | 1,439 | 4.125 | 4 | """Position-Wide Feed-Forward layer.
"""
import torch.nn as nn
import torch.nn.functional as F
class PositionWideForward(nn.Module):
"""A PositionWideForward class is used to provide a position-wise feed forward layer for a neural network.
References:
A. Vaswani, et al. Attention is all you need. Advances in neural information processing systems (2017).
"""
def __init__(self, n_hidden, n_forward, dropout):
"""Initialization method.
Args:
n_hidden (int): Number of hidden units.
n_forward (int): Number of forward units.
dropout (float): Dropout probability.
"""
super(PositionWideForward, self).__init__()
# Defining the linear (feed forward) layers
self.fc1 = nn.Linear(n_hidden, n_forward)
self.fc2 = nn.Linear(n_forward, n_hidden)
# Defining the dropout layer
self.drop = nn.Dropout(dropout)
def forward(self, x):
"""Performs a forward pass over the layer.
Args:
x (torch.Tensor): Tensor containing the input states.
Returns:
The feed forward activations.
"""
# Performs the pass over first linear layer and activates using ReLU
x = F.relu(self.fc1(x))
# Pass down to the dropout layer
x = self.drop(x)
# Pass down over the second linear layer
x = self.fc2(x)
return x
|
1d1fe9158510b6ce11957efafc0032da79cf5af7 | ClassyBrute/MetodyNum2020 | /lista1/zad2.py | 197 | 3.75 | 4 | import matplotlib.pyplot as plt
x0 = 0.1
lista = [x0]
n1 = range(0, 101)
for n in range(1, 101):
x0 = 3.5 * x0 * (1 - x0)
lista.append(x0)
plt.scatter(n1, lista)
plt.show()
print(lista) |
59d6f7e2aadff3bc9bd0bc82980a4417f7aeede6 | varunagrawal/advent-of-code | /2018/day5.py | 1,232 | 3.59375 | 4 | import string
def collapse(polymer):
i = 0
reaction = False
while True:
if i >= len(polymer) - 1:
if reaction == False:
break
i = 0
reaction = False
if polymer[i].isupper() and polymer[i].lower() == polymer[i+1]:
# print(i, i+1, polymer[i], polymer[i+1])
polymer = polymer[:i] + polymer[i+1+1:]
reaction = True
elif polymer[i].islower() and polymer[i].upper() == polymer[i+1]:
# print(i, i+1, polymer[i], polymer[i+1])
polymer = polymer[:i] + polymer[i+1+1:]
reaction = True
else:
i += 1
return polymer
def part1(polymer):
polymer = collapse(polymer)
# print(polymer)
print(len(polymer))
def part2(polymer):
min_len = len(polymer)
for c in string.ascii_lowercase:
print(c)
polymer_sub = polymer.replace(c, '').replace(c.upper(), '')
collapsed_polymer = collapse(polymer_sub)
if len(collapsed_polymer) < min_len:
min_len = len(collapsed_polymer)
print(min_len)
s = "dabAcCaCBAcCcaDA"
with open("day5.txt") as f:
s = f.read()
# print(len(s))
part1(s)
part2(s)
|
5bbffe092bef4f21d89a79a44477d5bfc310fb60 | waltermblair/CSCI-220 | /circle_intersection.py | 959 | 4.28125 | 4 | import math
from graphics import *
print("This program computes the two points where your horizontal line intersects with my circle.")
r=eval(input("The radius of the circle: "))
y=eval(input("The y-intercept of the line: "))
try:
x1=math.sqrt(r**2-y**2)
x2=-x1
print("Points of intersect: (",x1,y,") and (",x2,y,")")
print("Thank you, come again.")
win=GraphWin()
win.setCoords(-12,-12,12,12)
xaxis=Line(Point(-12,0),Point(12,0))
yaxis=Line(Point(0,-12),Point(0,12))
xaxis.draw(win)
yaxis.draw(win)
for i in range(0,22,2):
Text(Point(-10+i+0.5,-.5),-10+i).draw(win)
Text(Point(-.5,-10+i+0.5),-10+i).draw(win)
c=Circle(Point(0,0),r)
c.draw(win)
l=Line(Point(-12,y),Point(12,y))
l.setWidth(2)
l.draw(win)
p1=Point(x1,y)
p1.setFill("red")
p1.draw(win)
p2=Point(x2,y)
p2.setFill("red")
p2.draw(win)
except:
print("The line does not intersect!")
|
7d0744f128e0a9e7eab73be99b73a7157b879038 | revolutionisme/ds-and-algo-nanodegree | /P1-Show-me-the-data-structure/Problem_4/T4-active-directory.py | 1,650 | 3.9375 | 4 | class Group(object):
def __init__(self, _name):
self.name = _name
self.groups = []
self.users = []
def add_group(self, group):
self.groups.append(group)
def add_user(self, user):
self.users.append(user)
def get_groups(self):
return self.groups
def get_users(self):
return self.users
def get_name(self):
return self.name
def deeper_group_search(user, group, status):
if user in group.get_users():
return True
if not group.get_groups():
return False
else:
for grp in group.get_groups():
status = deeper_group_search(user, grp, status) or status
return status
def is_user_in_group(user, group):
"""
Return True if user is in the group, False otherwise.
Args:
user(str): user name/id
group(class:Group): group to check user membership against
"""
return deeper_group_search(user, group, False)
parent = Group("parent")
child = Group("child")
sub_child = Group("subchild")
sub_child_2 = Group("subchild2")
sub_child_user = "sub_child_user"
sub_child.add_user(sub_child_user)
sub_child_2.add_user("sub_child_2")
child.add_group(sub_child)
child.add_group(sub_child_2)
parent.add_group(child)
child.add_user("child_user")
print("===========Test Cases ========")
print(is_user_in_group("sub_child_user", parent)) # Expected True
print(is_user_in_group("user", parent)) # Expected False
print(is_user_in_group("child_user", parent)) # Expected True
print(is_user_in_group("sub_child_2", parent)) # Expected True
print(is_user_in_group("", parent)) # Expected False |
6e41b1985b855932d3ad9b046acfc3f056a6c12d | Heartbeatc/python3.6.6 | /dict/code/day005 ◊÷µ‰/02 作业讲解.py | 3,408 | 3.53125 | 4 | # li = ["alex", "WuSir", "ritian", "barry", "wenzhou", "eric"]
#
# l2=[1,"a",3,4,"heart"]
# # print(len(li))
# # li.append("seven")
# li.extend(l2)
# li.remove(li[2])
# li.pop(2)
# print(li)
# li = [1, 3, 2, "a", 4, "b", 5,"c"]
# # ["c"]
# print(li[-1:])
# lis = [2, 3, "k", ["qwe", 20, ["k1", ["tt", 3, "1"]], 89], "ab", "adv"]
# lis[3][2][1][0] = lis[3][2][1][0].upper()
# lis[3][2][1][0] = "TT"
# lis[3][2][1][0] = lis[3][2][1][0].replace("t", "T")
# lis[3][2][1][0] = lis[3][2][1][0].swapcase()
# lis[3][2][1][1] = "100"
# lis[3][2][1][1] = str(lis[3][2][1][1] + 97)
# lis[3][2][1][2] = int(lis[3][2][1][2] + "01")
# lis[3][2][1][2] = 101
# lis[3][2][1][2] = int(lis[3][2][1][2]) + 100
# print(lis)
# li = ["alex", "eric", "rain", "刘伟","你很六"]
# # 1+2+3+4+5....
# s = ""
# for el in li: # el 列表中的每一个字符串
# s = s + el + "_"
# print(s[:-1])
#
# li = ["alex", "WuSir", "ritian", "barry", "wenzhou"]
# for i in range(len(li)):
# print(i)
# lst = []
# for i in range(50):
# if i % 3 == 0:
# lst.append(i)
#
# print(lst)
# for i in range(100, 0, -1):
# print(i)
# lst = []
# for i in range(100, 9, -1):
# if i % 2 == 0 and i % 4 == 0:
# lst.append(i)
# print(lst)
# lst = []
# for i in range(1, 30):
# lst.append(i)
#
# for i in range(len(lst)):
# if lst[i] % 3 == 0:
# lst[i] = "*"
# print(lst)
# 查找列表li中的元素,移除每个元素的空格,并找出以"A"或者"a"开头,并
# 以"c"结尾的所有元素,并添加到⼀个新列表中,最后循环打印这个新列表。
# li = ["TaiBai ", "ale xC", "AbC ", "egon", " ri TiAn", "WuSir", " aqc"]
#
# lst = []
# for el in li:
# el = el.replace(" ", "") # 去掉空格的
# if el.upper().startswith("A") and el.endswith("c"):
# lst.append(el)
# print(lst)
# 敏感词列表 li = ["苍⽼师", "东京热", "武藤兰", "波多野结⾐"]
# 则将⽤户输⼊的内容中的敏感词汇替换成等⻓度的*(苍⽼师就替换***),并添
# 加到⼀个列表中;如果⽤户输⼊的内容没有敏感词汇,则直接添加到上述的列
# 表中。
# li = ["苍老师", "东京热", "武藤兰", "波多野结衣"]
# content = input("请开始你的评论:")
# for el in li:
# if el in content:
# content = content.replace(el, "*"*len(el))
# print(content)
# print(list)
# print(type([]))
# li = [1, 3, 4, "alex", [3, 7, 8, "TaiBai"], 5, "RiTiAn", [3, 7, 8, "TaiBai"]]
# for el in li:
# if type(el) == list:
# for el2 in el:
# if type(el2) == str:
# print(el2.lower())
# else:
# print(el2)
# else:
# if type(el) == str:
# print(el.lower())
# else:
# print(el)
# for i in range(len(li)):
# if i != 4:
# print(li[i])
# else: # 第四个是列表. 继续循环
# for el in li[4]:
# print(el)
# lst = []
# while 1:
# info = input("请输入学生信息(Q退出):") # 张三_44
# if info.upper() == "Q":
# break
# lst.append(info)
# sum = 0
# for el in lst: # 张三_44
# sum += int(el.split("_")[1])
#
# print(sum/len(lst))
# 敲七
# n = int(input("请输入数字n:"))
# lst = []
# for i in range(1, n+1):
# if i % 7 == 0 or "7" in str(i):
# lst.append("咣")
# else:
# lst.append(i)
# print(lst)
|
ad84c40f9f794115c8c8b92cc65353adef424631 | rahulbhatia023/python | /19_Arrays.py | 2,572 | 4.3125 | 4 | # An array is a collection of elements of the same type.
# We can treat lists as arrays. However, we cannot constrain the type of elements stored in a list.
from array import *
# we need to import array module to create arrays
vals = array('i', [1, 2, 3, 4, 5])
# Here, we created an array of int type. The letter 'i' is a type code. This determines the type of the array during
# creation.
# Type code C Type Python Type Minimum size in bytes
# 'b' signed char int 1
# 'B' unsigned char int 1
# 'u' Py_UNICODE Unicode character 2
# 'h' signed short int 2
# 'H' unsigned short int 2
# 'i' signed int int 2
# 'I' unsigned int int 2
# 'l' signed long int 4
# 'L' unsigned long int 4
# 'f' float float 4
# 'd' double float 8
print(vals)
# array('i', [1, 2, 3, 4, 5])
print(vals.buffer_info())
# Return a tuple (address, length) giving the current memory address and the length in elements of the buffer used to
# hold array’s contents.
# (89244448, 5)
print(vals.typecode)
# Returns the typecode character used to create the array.
# i
print(vals.reverse())
# Reverse the order of the items in the array.
print(vals[0])
# We use indices to access elements of an array
# 5
#########################################################
for i in vals:
print(i)
for i in range(len(vals)):
print(vals[i])
#########################################################
vals = array('u', ['a', 'e', 'i', 'o', 'u'])
for i in vals:
print(i)
#########################################################
# Copy the values from vals array to newVals array
newVals = array(vals.typecode, (a for a in vals))
for i in newVals:
print(i)
#########################################################
# Take array elements from user
arr = array('i', [])
length = int(input('Enter the length of array: '))
for i in range(length):
val = int(input('Enter the value: '))
arr.append(val)
print(arr)
#########################################################
# Search for element in array
# Method-1
vals = array('i', [1, 2, 3, 4, 5])
element = int(input('Enter element to search: '))
i = 0
while i < len(arr):
if arr[i] == element:
print(i)
break
i = i + 1
# Method-2
element = int(input('Enter element to search: '))
print(vals.index(element))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.