blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
e033c04fefdebc2bfec367b3b97456c504dba801 | AndrewAct/DataCamp_Python | /Introduction to Deep Learning with Keras/2 Going Deeper/10_The_History_Callback.py | 1,150 | 3.578125 | 4 | # # 8/9/2020
# The history callback is returned by default every time you train a model with the .fit() method. To access these metrics you can access the history dictionary parameter inside the returned h_callback object with the corresponding keys.
# The irrigation machine model you built in the previous lesson is loaded for you to train, along with its features and labels now loaded as X_train, y_train, X_test, y_test. This time you will store the model's historycallback and use the validation_data parameter as it trains.
# You will plot the results stored in history with plot_accuracy() and plot_loss(), two simple matplotlib functions. You can check their code in the console by pasting show_code(plot_loss).
# Let's see the behind the scenes of our training!
# Train your model and save its history
h_callback = model.fit(X_train, y_train, epochs = 50,
validation_data=(X_test, y_test))
# Plot train vs test loss during training
plot_loss(h_callback.history['loss'], h_callback.history['val_loss'])
# Plot train vs test accuracy during training
plot_accuracy(h_callback.history['acc'], h_callback.history['val_acc']) |
93cee3a5f9b2bc7b6282fa9533a74bb00bc29846 | maq-622674/python | /廖Py教程/py/10.错误,调试和测试/1.错误处理.py | 8,465 | 4.21875 | 4 | '''
1.错误处理
在程序运行的过程中,如果发生了错误,可以事先约定返回一个错误代码,这样,就可以知道是否有错,以及出错的原因。在操作系统提供的调用中,返回错误码非常常见。比如打开文件的函数open(),成功时返回文件描述符(就是一个整数),出错时返回-1。
用错误码来表示是否出错十分不便,因为函数本身应该返回的正常结果和错误码混在一起,造成调用者必须用大量的代码来判断是否出错:
'''
def foo():
r = some_function()
if r==(-1):
return (-1)
# do something
return r
def bar():
r = foo()
if r==(-1):
print('Error')
else:
pass
'''
一旦出错,还要一级一级上报,直到某个函数可以处理该错误(比如,给用户输出一个错误信息)。
所以高级语言通常都内置了一套try...except...finally...的错误处理机制,Python也不例外。
'''
'''
2.try
'''
try:
print('try...')
r = 10 / 0
print('result:', r)
except ZeroDivisionError as e:
print('except:', e)
finally:
print('finally...')
print('END')
'''
当我们认为某些代码可能会出错时,就可以用try来运行这段代码,如果执行出错,则后续代码不会继续执行,而是直接跳转至错误处理代码,即except语句块,执行完except后,如果有finally语句块,则执行finally语句块,至此,执行完毕。
上面的代码在计算10 / 0时会产生一个除法运算错误:
'''
try:
print('try...')
r = 10 / int('a')
print('result:', r)
except ValueError as e:
print('ValueError:', e)
except ZeroDivisionError as e:
print('ZeroDivisionError:', e)
finally:
print('finally...')
print('END')
#int()函数可能会抛出ValueError,所以我们用一个except捕获ValueError,用另一个except捕获ZeroDivisionError。
#此外,如果没有错误发生,可以在except语句块后面加一个else,当没有错误发生时,会自动执行else语句:
try:
print('try...')
r = 10 / int('2')
print('result:', r)
except ValueError as e:
print('ValueError:', e)
except ZeroDivisionError as e:
print('ZeroDivisionError:', e)
else:
print('no error!')
finally:
print('finally...')
print('END')
'''
Python的错误其实也是class,所有的错误类型都继承自BaseException,所以在使用except时需要注意的是,它不但捕获该类型的错误,还把其子类也“一网打尽”。比如:
'''
try:
foo()
except ValueError as e:
print('ValueError')
except UnicodeError as e:
print('UnicodeError')
'''
第二个except永远也捕获不到UnicodeError,因为UnicodeError是ValueError的子类,如果有,也被第一个except给捕获了。
Python所有的错误都是从BaseException类派生的,常见的错误类型和继承关系看这里:
https://docs.python.org/3/library/exceptions.html#exception-hierarchy
使用try...except捕获错误还有一个巨大的好处,就是可以跨越多层调用,比如函数main()调用bar(),bar()调用foo(),结果foo()出错了,这时,只要main()捕获到了,就可以处理:
'''
def foo(s):
return 10 / int(s)
def bar(s):
return foo(s) * 2
def main():
try:
bar('0')
except Exception as e:
print('Error:', e)
finally:
print('finally...')
#也就是说,不需要在每个可能出错的地方去捕获错误,只要在合适的层次去捕获错误就可以了。这样一来,就大大减少了写try...except...finally的麻烦。
'''
3.调用栈
如果错误没有被捕获,它就会一直往上抛,最后被Python解释器捕获,打印一个错误信息,然后程序退出。来看看err.py:
'''
# err.py:
def foo(s):
return 10 / int(s)
def bar(s):
return foo(s) * 2
def main():
bar('0')
main()
#执行,结果如下:
'''
$ python3 err.py
Traceback (most recent call last):
File "err.py", line 11, in <module>
main()
File "err.py", line 9, in main
bar('0')
File "err.py", line 6, in bar
return foo(s) * 2
File "err.py", line 3, in foo
return 10 / int(s)
ZeroDivisionError: division by zero
'''
'''
出错并不可怕,可怕的是不知道哪里出错了。解读错误信息是定位错误的关键。我们从上往下可以看到整个错误的调用函数链:
错误信息第1行:
Traceback (most recent call last):
告诉我们这是错误的跟踪信息。
第2~3行:
File "err.py", line 11, in <module>
main()
调用main()出错了,在代码文件err.py的第11行代码,但原因是第9行:
File "err.py", line 9, in main
bar('0')
调用bar('0')出错了,在代码文件err.py的第9行代码,但原因是第6行:
File "err.py", line 6, in bar
return foo(s) * 2
原因是return foo(s) * 2这个语句出错了,但这还不是最终原因,继续往下看:
File "err.py", line 3, in foo
return 10 / int(s)
原因是return 10 / int(s)这个语句出错了,这是错误产生的源头,因为下面打印了:
ZeroDivisionError: integer division or modulo by zero
根据错误类型ZeroDivisionError,我们判断,int(s)本身并没有出错,但是int(s)返回0,在计算10 / 0时出错,至此,找到错误源头。
出错的时候,一定要分析错误的调用栈信息,才能定位错误的位置。
'''
'''
4.记录错误
如果不捕获错误,自然可以让Python解释器来打印出错误堆栈,但程序也被结束了。既然我们能捕获错误,就可以把错误堆栈打印出来,然后分析错误原因,同时,让程序继续执行下去。
Python内置的logging模块可以非常容易地记录错误信息:
'''
# err_logging.py
import logging
def foo(s):
return 10 / int(s)
def bar(s):
return foo(s) * 2
def main():
try:
bar('0')
except Exception as e:
logging.exception(e)
main()
print('END')
#同样是出错,但程序打印完错误信息后会继续执行,并正常退出:
#通过配置,logging还可以把错误记录到日志文件里,方便事后排查。
'''
5.抛出错误
因为错误是class,捕获一个错误就是捕获到该class的一个实例。因此,错误并不是凭空产生的,而是有意创建并抛出的。Python的内置函数会抛出很多类型的错误,我们自己编写的函数也可以抛出错误。
如果要抛出错误,首先根据需要,可以定义一个错误的class,选择好继承关系,然后,用raise语句抛出一个错误的实例:
'''
# err_raise.py
class FooError(ValueError):
pass
def foo(s):
n = int(s)
if n==0:
raise FooError('invalid value: %s' % s)
return 10 / n
foo('0')
'''
执行,可以最后跟踪到我们自己定义的错误:
$ python3 err_raise.py
Traceback (most recent call last):
File "err_throw.py", line 11, in <module>
foo('0')
File "err_throw.py", line 8, in foo
raise FooError('invalid value: %s' % s)
__main__.FooError: invalid value: 0
只有在必要的时候才定义我们自己的错误类型。如果可以选择Python已有的内置的错误类型(比如ValueError,TypeError),尽量使用Python内置的错误类型。
最后,我们来看另一种错误处理的方式:
'''
# err_reraise.py
def foo(s):
n = int(s)
if n==0:
raise ValueError('invalid value: %s' % s)
return 10 / n
def bar():
try:
foo('0')
except ValueError as e:
print('ValueError!')
raise
bar()
'''
在bar()函数中,我们明明已经捕获了错误,但是,打印一个ValueError!后,又把错误通过raise语句抛出去了,这不有病么?
其实这种错误处理方式不但没病,而且相当常见。捕获错误目的只是记录一下,便于后续追踪。但是,由于当前函数不知道应该怎么处理该错误,所以,最恰当的方式是继续往上抛,让顶层调用者去处理。好比一个员工处理不了一个问题时,就把问题抛给他的老板,如果他的老板也处理不了,就一直往上抛,最终会抛给CEO去处理。
raise语句如果不带参数,就会把当前错误原样抛出。此外,在except中raise一个Error,还可以把一种类型的错误转化成另一种类型:
'''
try:
10 / 0
except ZeroDivisionError:
raise ValueError('input error!')
|
76b8803b49b982dc6cd087d76eb66f038c0de1fc | EljEnoch/highma | /0x0B-python-input_output/2-read_lines.py | 690 | 4.4375 | 4 | #!/usr/bin/python3
"""This module defines a function the reads and prints n lines from file"""
def read_lines(filename="", nb_lines=0):
"""Read and print n lines from file
Arguments:
filename: file to read from
nb_lines: number of lines to read/print
"""
line_count = 0
with open(filename, mode='r', encoding='utf-8') as f:
for line_count, lines in enumerate(f):
pass
if nb_lines <= 0 or nb_lines > (line_count + 1):
f.seek(0)
print(f.read(), end='')
else:
f.seek(0) # return to file beginning
for line in range(nb_lines):
print(f.readline(), end='')
|
6c9d2230d49f674f16a3d014fcebb4eece182a5b | pchudzik/mocked-http-server | /server.py | 2,924 | 3.515625 | 4 | import argparse
from http.server import BaseHTTPRequestHandler, HTTPServer
from random import random
import json
arg_parser = argparse.ArgumentParser(
description='Simple http server which will to serve request with specified ratio and errors')
arg_parser.add_argument(
"--port",
help="Port on which server will listen",
default=8181,
type=int)
arg_parser.add_argument(
"--error-ratio",
help="Error ratio. 0.2 means 20% of requests will fail",
type=float)
arg_parser.add_argument(
"--error-file",
help="File with errors to be send to user (one by one)",
required=False)
arg_parser.add_argument(
"--success-file",
help="File with success responses to be send to user (one by one)",
required=False)
arg_parser.add_argument(
"--path",
help="Path under which all requests will be served",
default="/api")
def load_responses(location):
if location:
with open(location) as file:
return infinite_generator(json.load(file))
def infinite_generator(collection):
while True:
for item in collection:
yield item
def create_handler_factory(config):
available_errors = load_responses(config.error_file)
available_success = load_responses(config.success_file)
def handler_factory(request, client_address, server):
return FailingHandler(
request, client_address, server,
next(available_errors) if random() < config.error_ratio else next(available_success))
return handler_factory
class FailingHandler(BaseHTTPRequestHandler):
def __init__(self, request, client_address, server, server_response):
self.server_response = server_response
super().__init__(request, client_address, server)
def do_GET(self):
if self.path != config.path:
return self.__send_response({"status": 404, "response_json": {"error": "Not Found"}})
return self.__send_response(self.server_response)
def __send_response(self, response):
self.send_response(response["status"])
has_content_type = False
if response.get("headers"):
for item in response["headers"]:
for name, value in item.items():
if name == "Content-type":
has_content_type = True
self.send_header(name, value)
if not has_content_type:
self.send_header("Content-type", "application/json")
self.end_headers()
self.wfile.write(json.dumps(response["response_json"]).encode())
if __name__ == "__main__":
config = arg_parser.parse_args()
try:
server = HTTPServer(('', config.port), create_handler_factory(config))
print(f"Started httpserver on port {config.port}")
server.serve_forever()
except KeyboardInterrupt:
print("shutting down the server")
server.socket.close()
|
61c85785fdd5422b9fb1f96aa20b6f36b7aae974 | hhgman/beakjoon | /2442.py | 114 | 3.921875 | 4 | num = int(input())
for i in range(1,num+1):
star = "*"*(2*i-1)
space = " "*(num-i)
print(space+star)
|
622b7b4ed8286cf999b2033b92fedca9f350579f | Phantomn/Python | /study/ch1/if/grade.py | 162 | 3.9375 | 4 | print("Input score : ",end="")
score=int(input())
if(score>=90 and score<=100):
print("A")
elif(score>=80 and score<90):
print("B")
else:
print("F")
|
2cc1f6dc22158f8ac72c4fdfbdb7566347775c74 | arzzon/PythonLearning | /PythonInbuilts/Advanced/Map/map.py | 644 | 4.71875 | 5 | '''
Map is used to generate another iterable from the iterable provided to it along with
the lambda function, where each element of the generated iterable is mapped/modified
to some value based on the lambda function logic provided to it.
It returns a map object which contains all those filtered elements. We can type cast
these objects to iterables like list/set etc.
Syntax:
=> map(lambda function, iterable)
type casting to list:
=> list( map(lambda function, iterable) )
'''
L = [1, 2, 3, 4, 5, 6]
# Each element in the list is squared.
squaredList = list(map((lambda x: x**2), L))
print(squaredList) |
5cabb228233f3c2d3034e105e49525dda46f2e07 | a0927024706/second_hight | /second_hight.py | 428 | 3.96875 | 4 | students = [['a', 123], ['b', 211], ['c', 100], ['d', 101]]
def second_highest(students):
grades = [s[1] for s in students] # 只把成績拿出來
grades = sorted(grades, reverse = True)
second = grades[1] # grades[0]是最高,grades[1]是第二高
second_high_students = [s[0] for s in students if s[1] == second]
for student in second_high_students:
print(student)
second_highest(students) |
6971d5c611639fce1ef4f3ed413fd89c93ded218 | AlisonWonderland/Scripts | /litte_caesars/litte_caesars.py | 5,733 | 3.6875 | 4 | #! /usr/bin/env python
import time, sys
#For the delay at the end to close the browser after its done
from selenium import webdriver
#To launch browser
from selenium.webdriver.common.by import By
#Helps us find things on a page. Like a login
from selenium.webdriver.support.ui import WebDriverWait
#To wait for the page to load.
from selenium.webdriver.support import expected_conditions as EC
#Makes sure that page has loaded by looking at the the thing we specify to look at.
from selenium.common.exceptions import TimeoutException
#For handling timeouts
def choose_profile(profiles):
print("Enter number of profile you want to use or 'q' to return to menu: ", end = "")
while (1):
user_input = input()
#Check if input is number or string
if(user_input.isdigit()):
user_input = int(user_input)
elif(user_input == 'q'):
print() #For clearer output
return None
#If else is entered, it means user inputted an invalid string
else:
print('Invalid. Try again: ', end = "")
continue
#Reaching this point means that user input is an int and it needs to be
#be a valid index of the list 'profiles'
if((user_input < 0) or (user_input > len(profiles) - 1)):
print('Invalid. Try again: ', end = "")
else:
return profiles[user_input]
def new_profile():
profiles_file = open('profiles.txt', 'a+')
#Asking for login info
while(1):
print('\nEnter your login email: ', end = "")
email = input()
print('Enter your login password: ', end = "")
password = input()
print('\nYour username:', email, '| Your password:', password)
print("Is this correct? Enter y to proceed, q to return to menu, anything else to repeat: ", end = "")
response = input()
print() #For whitespace
if(response == 'y'):
profiles_file.write(email + ' ' + password + '\r\n') #Add login to file
break
elif(response == 'q'):
break
profiles_file.close()
return
def get_profiles():
#check if file exists
try:
profiles_file = open('profiles.txt')
except:
while(1):
response = input("profiles.txt doesn't exist. Would you like to create it?\nEnter 'y' to create or 'n' to go back to menu.\n")
if(response == 'y'):
return
elif(response == 'n'):
return
else:
print('Invalid. Try again.')
profiles = profiles_file.readlines() # Store logins in a list
#Check if there are profiles in the file
if(not len(profiles)):
print('\nNo logins stored. Add new ones.\n')
#Print number of the login alongside the actual email and password
else:
print('\n-------------------------------------------------------------------')
for number, profile in enumerate(profiles):
print(number, profile)
print('-------------------------------------------------------------------\n')
profiles_file.close()
return profiles
def intro():
while(1):
print("Enter '1' to show all usernames and choose one. '2' to enter a new login.\nEnter q if you want to exit.\n")
user_input = input()
if(user_input == '1'):
#Print available profiles
profiles = get_profiles()
#If profiles is empty then repeat menu msg
if(len(profiles)):
profile = choose_profile(profiles)
if(profile == None):
continue
else:
return profile
elif(user_input == '2'):
new_profile()
elif(user_input == 'q'):
print('Exiting program.')
sys.exit()
else:
print('Invalid input')
#Get login
login_info = intro()
login_info = login_info.split(' ')
#Little caesars username
lc_email = login_info[0]
#Little caesars password, remove the newline before storing it into lc_password
newline_index = login_info[1].find("\n")
lc_password = login_info[1][0:newline_index]
# Specifying incognito mode as you launch your browser[OPTIONAL]
option = webdriver.ChromeOptions()
option.add_argument("--incognito")
browser = webdriver.Chrome(executable_path='/mnt/d/Users/dimitri/Desktop/chromedriver.exe', chrome_options=option)
# Go to little caesars website
browser.get("https://littlecaesars.com/en-us/")
# Wait 20 seconds for page to load, to press login button
timeout = 20
try:
# Wait until the login logo shows up.
WebDriverWait(browser, timeout).until(EC.visibility_of_element_located((By.XPATH, "//a[@class='sc-dqBHgY AYCxi']")))
except TimeoutException:
print("Timed out waiting for page to load")
browser.quit()
# Press the button
login_button = browser.find_element_by_xpath("//a[@class='sc-dqBHgY AYCxi']")
print(type(login_button))
login_button.click()
# Wait 20 seconds before entering login info
timeout = 20
try:
# Wait until the login logo shows up.
WebDriverWait(browser, timeout).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='sc-hZeNU hRsEcQ']")))
except TimeoutException:
print("Timed out waiting for page to load")
browser.quit()
email_input = browser.find_element_by_xpath("//input[@id='B1xobMEeZr']")
email_input.send_keys(lc_email)
password_input = browser.find_element_by_xpath("//input[@id='H1-oWG4lZH']")
password_input.send_keys(lc_password)
|
d6a0a8a6394786d17df066026c24b1bdbfc0db2c | patrisor/4.2-Twitter-Challenges | /hangman/src/Auxiliary.py | 1,500 | 3.59375 | 4 | # **************************************************************************** #
# #
# ::: :::::::: #
# Auxiliary.py :+: :+: :+: #
# +:+ +:+ +:+ #
# By: patrisor <[email protected]> +#+ +:+ +#+ #
# +#+#+#+#+#+ +#+ #
# Created: 2019/08/20 21:44:59 by patrisor #+# #+# #
# Updated: 2019/08/20 21:45:27 by patrisor ### ########.fr #
# #
# **************************************************************************** #
import Getch
# Function Listens for key inputs
# Returns a string that was inputted
def get(prompt):
print(prompt)
inkey = Getch._Getch()
while(1):
k=inkey()
if k!='':break
return k
# Quits our game if input is 'q'
def quit(i):
if i == "~":
print("Goodbye!")
exit(-1)
return i
# Function processes Input and checks if it is valid
# Returns string inputted if valid
def processInput():
while True:
ret = quit(get("Guess a Character\n"))
if not ret.isalpha():
print("Invalid Input")
continue
return(ret)
|
725fd692f388cc86cce9e1ac623c3ca9c1c83b31 | eltechno/python_course | /Functions.returning-multiple-values.py | 1,388 | 4.0625 | 4 |
def raise_both(value1, value2):
"""Raise value 1 to the power of value2 and vice versa"""
new_value1 = value1 ** value2
new_value2 = value2 ** value1
new_tuple = (new_value1, new_value2)
return new_tuple
a, b = raise_both(2,4)
print(a)
print(b)
# Define shout with parameters word1 and word2
def shout(word1, word2):
"""Concatenate strings with three exclamation marks"""
# Concatenate word1 with '!!!': shout1
shout1 = word1 + "!!!"
# Concatenate word2 with '!!!': shout2
shout2 = word2 + "!!!"
# Concatenate shout1 with shout2: new_shout
new_shout = shout1 + shout2
# Return new_shout
return new_shout
# Pass 'congratulations' and 'you' to shout(): yell
yell = shout("congratulations", "you")
# Print yell
print(yell)
#############################################################3
# Define shout_all with parameters word1 and word2
def shout_all(word1, word2):
# Concatenate word1 with '!!!': shout1
shout1 = word1 + "!!!"
# Concatenate word2 with '!!!': shout2
shout2 = word2 + "!!!"
# Construct a tuple with shout1 and shout2: shout_words
shout_words = (shout1, shout2)
# Return shout_words
return shout_words
# Pass 'congratulations' and 'you' to shout_all(): yell1, yell2
yell1, yell2 = shout_all("congratulations", "you")
# Print yell1 and yell2
print(yell1)
print(yell2) |
c7f0a9a643fa6300b50a959885569908b2ee98ea | rohan-1998/Assignment9 | /Assignment9.py | 547 | 3.9375 | 4 | #Question 1
try:
a=3
if a<4:
a=a/(a-3)
print(a)
except ZeroDivisionError:
print("You Cannot Deivide By Zero")
#Question 2
INDEX ERROR
#Question 3
'''AN execption'''
#Question 4
-5.0
a/b result in 0
#Question 5
#import Error
try:
import xyz
except ImportError:
print("Please Import Valid Module")
#value Error
try:
a=int(input("Enter a Number ")
except:
print("Please Enter a valid Number")
#index Error
try:
a=[1,2,3,]
print(a[4])
except:
print("Please Enter A valid Index")
|
c93db938347d451f22ffe804dd670788b2f30d57 | MitsurugiMeiya/Leetcoding | /leetcode/Tree/107. Binary Tree Level Order Traversal II(反层序遍历).py | 1,151 | 4 | 4 | """
Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).
For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
"""
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def levelOrderBottom(self, root):
if root is None: return []
res = []
queue = [root]
while queue:
res.append([node.val for node in queue])
level = []
for node in queue:
if node.left:
level.append(node.left)
if node.right:
level.append(node.right)
queue = level
return res[::-1]
"""
其实就是树的层级遍历,因为我们要把每一层都作为一个List储存在res里,最后反转一遍
所以我们在bfs的时候,把每一层的结果都放到一个 [x] 里,最后让这个queue = [x]
然后在开头都时候把queue里的每个元素都放进res里
""" |
61a70603e5444aee66217a3fa69152db5a82f8fe | meta-omega/formal-system-library | /utils/get_leaves.py | 514 | 3.515625 | 4 | from tree.functions.to_node import to_node
from tree.alphabets.logic import get_logic_alphabet
def get_leaves(node):
if len(node.children) == 0:
return [node]
alphabet = get_logic_alphabet()
leaves = []
def to_logic_node(string):
return to_node(string, alphabet)
for child in node.children:
leaves.extend(get_leaves(child))
leaves = list(map(str, leaves))
leaves = list(set(leaves))
leaves = list(map(to_logic_node, leaves))
return leaves
|
b8e07a5c22a0aea8faa07368250b48ffd10858c5 | Jiadalee/storm-swarm | /StormSwarm/controller.py | 837 | 3.59375 | 4 | import numpy as np
class controller:
"""
Class for representing the policy of workers
"""
def __init__(self,
constant_action,
policy,
exploration,
action_space):
self.exploration = exploration
self.action_space = action_space
self.policy = policy
self.constant_action = constant_action
def act(self, state):
if np.random.rand() < self.exploration:
action = np.random.choice(self.action_space)
else:
action = self._policy(state)
return [action]
def _policy(self, state):
"""
Governing the actions to take given a state.
This can be modified accordingly.
"""
action = self.constant_action
return action
|
17124d60f1087e7fd49adbab87952b9af2eb2f65 | g2g2g2g2/PedraPapelTesoura | /PedraPapelOuTesoura_.py | 4,003 | 3.59375 | 4 | from tkinter import *
import tkinter as tk
from random import randint as r
from time import sleep as s
voce = 0
pc = 0
def pedra1():
s(0.5)
if r(1, 3) == 1:
output = Label(Tela, width=18, text='Empatou!!\n Também escolhi Pedra')
output['bg'] = 'red'
output.place(x=140, y=80)
elif r(1, 3) == 2:
output = Label(Tela, width=18, text='Ganhei!!\n Eu escolhi Papel')
output['bg'] = 'red'
output.place(x=140, y=80)
global pc
pc += 1
pc_ = Label(Tela, text='Você: {}'.format(pc))
pc_['bg'] = 'red'
pc_.place(x=150, y=200)
else:
output = Label(Tela, width=18, text='Perdi!!\n Eu escolhi Tesoura')
output['bg'] = 'red'
output.place(x=140, y=80)
global voce
voce += 1
voce_ = Label(Tela, text='Você: {}'.format(voce))
voce_['bg'] = 'red'
voce_.place(x=15, y=200)
def papel1():
s(0.5)
if r(1, 3) == 1:
output = Label(Tela, width=18, text='Perdi!!\n Eu escolhi Pedra')
output['bg'] = 'red'
output.place(x=140, y=80)
global voce
voce += 1
voce_ = Label(Tela, text='Você: {}'.format(voce))
voce_['bg'] = 'red'
voce_.place(x=15, y=200)
elif r(1, 3) == 2:
output = Label(Tela, width=18, text='Empatou!!\n Também escolhi Papel')
output['bg'] = 'red'
output.place(x=140, y=80)
else:
output = Label(Tela, width=18, text='Ganhei!!\n Eu escolhi Tesoura')
output['bg'] = 'red'
output.place(x=140, y=80)
global pc
pc += 1
pc_ = Label(Tela, text='Você: {}'.format(pc))
pc_['bg'] = 'red'
pc_.place(x=150, y=200)
def tesoura1():
s(0.5)
if r(1, 3) == 1:
output = Label(Tela, width=18, text='Ganhei!!\n Eu escolhi Pedra')
output['bg'] = 'red'
output.place(x=140, y=80)
global pc
pc += 1
pc_ = Label(Tela, text='Você: {}'.format(pc))
pc_['bg'] = 'red'
pc_.place(x=150, y=200)
elif r(1, 3) == 2:
output = Label(Tela, width=18, text='Perdi!!\n Eu escolhi Papel')
output['bg'] = 'red'
output.place(x=140, y=80)
global voce
voce += 1
voce_ = Label(Tela, text='Você: {}'.format(voce))
voce_['bg'] = 'red'
voce_.place(x=15, y=200)
else:
output = Label(Tela, width=18, text='Empatou!!\nTambém escolhi Tesoura')
output['bg'] = 'red'
output.place(x=140, y=80)
Tela = Tk()
Tela.title('Pedra, Paper ou Tesoura')
Tela.geometry('300x300+150+200')
imagem = tk.PhotoImage(file='Fundo.png')
w = tk.Label(Tela, image=imagem)
w.imagem = imagem
w.pack()
a = Label(Tela, text='Vamos jogar Pedra, Papel ou Tesoura')
a['bg'] = 'red'
a.place(x=50, y=10)
pedra = Button(Tela, width=15, text='Pedra', command=pedra1)
pedra['bg'] = 'red'
pedra.place(x=20, y=30)
papel = Button(Tela, width=15, text='Papel', command=papel1)
papel['bg'] = 'red'
papel.place(x=20, y=60)
tesoura = Button(Tela, width=15, text='Tesoura', command=tesoura1)
tesoura['bg'] = 'red'
tesoura.place(x=20, y=90)
voce_ = Label(Tela, text='Você: {}'.format(voce))
voce_['bg'] = 'red'
voce_.place(x=15, y=200)
pc_ = Label(Tela, text='Você: {}'.format(pc))
pc_['bg'] = 'red'
pc_.place(x=150, y=200)
output = Label(Tela, width=17, text='')
output['bg'] = 'red'
output.place(x=140, y=30)
decoracao= '''
-=-=-=-=-=-=-=-=-=-=
____________________
____________________
____________________
-=-=-=-=-=-=-=-=-=-=
'''
deco = Label(Tela, width=18, text=decoracao)
deco['bg'] = 'red'
deco.place(x=140, y=30)
Tela.mainloop()
|
083af068fb5d9189133547341dceb277d00feb36 | FreddieMercy/leetcode | /Python/_2017/July2017/July25th2017/_41FirstMissingPositive.py | 253 | 3.578125 | 4 | class Solution(object):
def firstMissingPositive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
ans = 1
while True:
if not ans in nums:
return ans
ans+=1 |
f9e4fbd42dda1e022200917e0529faaa64eaf425 | t3miLo/lc101 | /Unit_1/assignments/country_code.py | 947 | 4.3125 | 4 |
# Write a function that will return a string of country codes from an argument that is a
# string of prices (containing dollar amounts following the country codes).
# Your function will take as an argument a string of prices like the following:
# "US$40, AU$89, JP$200".
# In this example, the function would return the string "US, AU, JP".
def get_country_codes(prices):
# your code here
price_list = list(prices.split("$"))
country_code = ''
for each_word in price_list:
for each_letter in each_word:
if each_letter.isalpha():
country_code += each_letter
country_code += ', '
new_country = country_code[-1::-1].replace(',', '', 2)
print(new_country[:1:-1])
# don't include these tests in Vocareum
get_country_codes("NZ$300, KR$1200, DK$5")
get_country_codes("US$40, AU$89, JP$200")
get_country_codes("AU$23, NG$900, MX$200, BG$790, ES$2")
get_country_codes("CA$40")
|
edb34c6f5f7ba0b38f519ff0dc427c2ab6a9b637 | ericgarciadv/aulas | /9-retanguloQuadrado[1].py | 209 | 3.859375 | 4 | print("Informe as dimensões do retângulo")
base = int(input("Base: "))
altura = int(input("Altura: "))
print("Área calculada: %dcm²" % (base * altura))
if base == altura:
print("Área de um quadrado!") |
5513f4f3c6a2936037c66b42938900386aaa01b7 | DustyQ5/CTI110 | /P4T2_BugCollector_ChazzSawyer.py | 634 | 4 | 4 | # Loop counter that then displays the total number
# Date
# CTI-110 P4T2 - Bug Collector
# Chazz Sawyer
#
total = 0.0
#Greets user and introduces the priogram concept
print ('I heard you like bugs! Lets count how many you can catch in five days!')
#loop asks user how many bugs caught that day
for day in range(0,5):
print("It's day", day+1,'!')
bugs_today = int(input('How many buds did you catch today?'))
total += bugs_today
#If statement that displays bug total outcome
if total > 10:
print("Wow!", total,"Bugs! That's some amzing bug catching skills")
else:
print('Only', total,'bugs?')
|
02439a8abc67f5efbb1e261f81b8caa11c2cb26c | skilldrick/event | /test.py | 292 | 3.828125 | 4 | class Dave:
x = 1
def __init__(self, y):
self.y = y
monkey = Dave(5)
bob = Dave(100)
print monkey.x, monkey.y
print bob.x, bob.y
monkey.x = 2
monkey.y = 3
print monkey.x, monkey.y
print bob.x, bob.y
bob.x = 1001
bob.y = 1002
print monkey.x, monkey.y
print bob.x, bob.y
|
d0d82e564bc58f3b02ca584836f6d7eef70af8c5 | pbarton666/learninglab | /begin_advanced/solution_python2_chapter07_logging.py | 3,057 | 4.25 | 4 |
#solution_python2_chapter07_logging.py
import sqlite3
import csv #python's library for reading csv files
import logging
DB='beer'
TABLE='brewpub'
FILE='py_log_english_brewery_data.csv'
LOG_FILE='brewery.log'
LEVEL=logging.DEBUG
logging.basicConfig(filename=LOG_FILE,
level=LEVEL)
logger=logging.getLogger()
def create_database(db=DB, table=TABLE, file=FILE):
"Creates a database w/ table loaded with file data"
#connect to the database
logger.debug("connecting to database")
conn = sqlite3.connect (DB)
curs = conn.cursor()
#set up a data table
logger.debug("setting up the {} table".format(TABLE))
curs.execute("DROP TABLE IF EXISTS {}".format(TABLE))
cmd = """CREATE TABLE {}
(name TEXT(50),
is_ale TINYINT,
county TEXT(50)
)""".format(TABLE)
curs.execute(cmd)
conn.commit()
#Keeping it DRY, introspect for column names
cmd = "SELECT * FROM {}".format(TABLE)
curs.execute(cmd)
cols=[]
for name in curs.description:
cols.append(name[0])
cols=tuple(cols)
#create a master set of info collected from data file
master=set()
#open the file and read it, dropping each row into the data table
logger.debug("opening {}".format(FILE))
with open(FILE, 'r') as data_file:
reader=csv.reader(data_file)
next(reader) #skips the header row
for data in reader:
#Each row is a list of strings. Clean them up a bit.
name, county = data
name=name.strip()
county=county.strip()
is_ale=0
if "ale" in name.lower():
is_ale=1
#create a tuple for input to INSERT
master.add( (name, is_ale, county) )
#At this point, the master set of info is deduped, so
# add its contents to the database. Note that we could
# add everything to the database then grab unique values
# via a SELECT DISTINCT directive.
for item_tuple in master:
cmd= "INSERT INTO {} {} VALUES {}".format(
TABLE, cols, item_tuple)
curs.execute(cmd)
logger.debug("making commits to the {} table".format(TABLE))
conn.commit()
conn.close()
def get_ale_houses(db=DB, table=TABLE, is_ale=1, county=0):
"finds places based on whether they do ale and their location"
logger.debug("Finding ale houses in {}.".format(TABLE))
conn = sqlite3.connect (DB)
curs = conn.cursor()
if not county:
cmd="SELECT * FROM {} WHERE is_ale={}".format(TABLE, is_ale)
else:
cmd="SELECT * FROM {} WHERE is_ale={} AND county='{}'"\
.format(TABLE, is_ale, county)
curs.execute(cmd)
results=curs.fetchall()
logger.debug("... found {} ale houses!".format(len(results)))
return results
if __name__=='__main__':
create_database()
results=get_ale_houses()
print(results)
|
90fbdca408fd2288ddb12e22b39cb986a6a01019 | laboyd001/python-crash-course-ch3 | /guest_list2.py | 361 | 3.90625 | 4 | #this program demos a list and a way to add and remove items
guest_list = ['Jenn', 'Kathy', 'BT']
cannot_attend = guest_list.pop(0)
print(cannot_attend + " is unable to attend.")
new_guest = guest_list.append('Salty')
print(guest_list[0] + ", you're invited!")
print(guest_list[1] + ", you're invited!")
print(guest_list[2] + ", you're invited!")
|
b2aa6e45e47ed0c767515fb2b930a4eb6ee27476 | sanjay2610/InnovationPython_Sanjay | /Python Assignments/Task3/ques1and2.py | 427 | 3.984375 | 4 | #quesion 1
#Create a list of the 10 elements of four different types of Data Types like int, string, complex, and float
list1=[1,2,3,'hello', 'world', 1+2j, 3+6j, 1.23, 3.45]
print(list1)
# lst contains all number from 1 to 10
lst =list(range(1, 11))
print (lst)
# below list has numbers from 2 to 5
lst1_5 = lst[1 : 5]
print (lst1_5)
# below list has numbers from 6 to 8
lst5_8 = lst[5 : 8]
print (lst5_8) |
7cc6b4d73c667f59b7bed96ad39dab143cd2a099 | ekohilas/comp2041_plpy | /examples/3/tetrahedral.py | 231 | 3.796875 | 4 | #!/usr/local/bin/python3.5 -u
n = 1
while n <= 10:
total = 0
j = 1
while j <= n:
i = 1
while i <= j:
total = total + i
i = i + 1
j = j + 1
print(total)
n = n + 1
|
43394a3d3571947a6a61fdddf1ba011cbbfb5ddf | bYsdTd/Leetcode | /python/690.员工的重要性.py | 1,158 | 3.53125 | 4 | #
# @lc app=leetcode.cn id=690 lang=python3
#
# [690] 员工的重要性
#
# @lc code=start
"""
# Definition for Employee.
class Employee:
def __init__(self, id: int, importance: int, subordinates: List[int]):
self.id = id
self.importance = importance
self.subordinates = subordinates
"""
class Solution:
def getImportance(self, employees: List['Employee'], id: int) -> int:
# DFS,递归实现
# cur = None
# for e in employees:
# if e.id == id:
# cur = e
# break
# if not cur:
# return 0
# imp = cur.importance
# for c in cur.subordinates:
# imp += self.getImportance(employees, c)
# return imp
# BFS, 队列实现
queue = [id]
s = 0
mp = {}
for e in employees:
mp[e.id] = e
while queue:
curId = queue.pop(0)
s += mp[curId].importance
for c in mp[curId].subordinates:
queue.append(c)
return s
# @lc code=end
|
1d204736ae60d0d946e4cd8bbbff364a7d491e21 | Abreu-Ricardo/IC | /clivar.py | 872 | 3.578125 | 4 | # Programador: Ricardo Abreu
# Inicio da clivagem de algoritmos
from LCS import LCS
arquivo = open("entrada.txt", "r")
# Criando objetos
pept1 = LCS()
pept2 = LCS()
resultado = None
for aux in arquivo:
try:
if aux[0] == '>':
continue
else:
pept1.string = aux
if pept2.string == None: # Primeiro linha do arquivo
pept2.string = pept1.string
elif pept1.string != pept2.string:
resultado = LCS.sub_seq(pept1, pept2)
if len(pept2.string) < len(resultado): # Com '>' acha o menor em comum, com '<' o maior em comum
pept2.string = resultado
except EOFError: ### FIM DO ARQUIVO
break
resultado.reverse() #Inverter o vetor
print(resultado)
print("Tamanho da seq:", len(resultado))
print()
arquivo.close() |
bdc95e5ee56ef4279161f0bfdb6f5091dcc0a484 | bsivavenu/Machine-Learning | /Advanced python 7 - 8/Demo12.py | 417 | 3.734375 | 4 | class A:
def calc(self,no1,no2):
print(no1,no2,"sum = ",(no1+no2))
class B(A):
def calc(self,no1,no2):
A().calc(no1,no2)
super().calc(no1,no2)
print(no1,no2,"sub = ",(no1-no2))
#----------------
a1 = A()
print("Enter 2 No's")
a1.calc(int(input()),int(input()))
#----------------------------
b1 = B()
print("Enter 2 No's")
b1.calc(int(input()),int(input()))
|
65eb98fcdfecaa8f2e1c049d500737ccb5fbcc6c | Jmoore1127/aoc2018 | /day2/challenge2.py | 535 | 3.59375 | 4 | #!/usr/local/opt/pyenv/shims/python
def solve():
with open("input.txt", "r") as f:
lines = f.readlines()
for i in range(0, len(lines)):
currentLine = lines[i]
for j in range(i+1, len(lines)):
difference = 0
commonLetters = []
comparedLine = lines[j]
for k in range(0, len(currentLine)):
if currentLine[k] == comparedLine[k]:
commonLetters += currentLine[k]
else:
difference += 1
if difference == 1:
print(''.join(commonLetters))
return
if __name__ == "__main__":
solve() |
b8f0acecdb1cbf1951af64498ba6948bb43a33c4 | Pretty-19/Coding-Problems | /array-stack.py | 238 | 4.09375 | 4 | arr = [1,2,3,4]
arr3 = []
arr2 = []
for i in range (len(arr)):
#print(i)
for j in range (i, len(arr)):
#print(j)
arr2.append(arr[j])
arr3.append(arr2)
print(arr2)
print(arr3) |
37e2423b4f3fff9972a2558849c38adb1651c1c6 | Cubesnail/nasaspaceapps | /materials.py | 3,439 | 3.796875 | 4 | # MATERIALS
class Material:
"""Currently unused class
"""
def __init__(self, name, mass, cost, density):
"""
:param name:
:param mass:
:param cost:
:param density:
:return:
"""
self.name = name
self.mass = mass
self.cost = cost
self.density = density
def get_volume(self):
return self.mass / self.density
def __eq__(self, other):
return self.name == other.name and self.mass == other.mass
def __lt__(self, other):
return self.mass < other.mass
class Resources:
def __init__(self, Al=0, Fe=0, Si=0, acrylic=0, H2O=0, O2=0, food=0):
"""Initialize a list of resources and the amounts.
:param Al: int
:param Fe: int
:param Si: int
:param acrylic: int
:param H2O: int
:param O2: int
:param food: int
:rtype: None
"""
self.Al, self.Fe, self.Si, self.acrylic, self.H2O, self.O2, self.food = \
Al, Fe, Si, acrylic, H2O, O2, food
def __lt__(self, other):
"""Return true if self is less than other and false otherwise
:param other:
:rtype: bool
"""
return self.Al <= other.Al and \
self.Fe <= other.Fe and \
self.Si <= other.Si and \
self.acrylic <= other.acrylic and \
self.H2O <= other.H2O and \
self.O2 <= other.O2 and \
self.food <= other.food
def __eq__(self, other):
"""Return true if other is equal to self and false otherwise.
:param other:
:rtype: bool
"""
return self.Al == other.Al and \
self.Fe == other.Fe and \
self.Si == other.Si and \
self.acrylic == other.acrylic and \
self.H2O == other.H2O and \
self.O2 == other.O2 and \
self.food == other.food
def __gt__(self, other):
"""Return true if other is greater than self and false otherwise
:param other:
:rtype: bool
"""
return other < self
def __str__(self):
"""Return a user-readable string representation of the resources object.
:rtype: str
"""
result = 'Al: {}kg \nFe: {}kg \nSi: {}kg \nAcrylic: {}kg \nH2O: {}kg \nO2: {}kg \nFood: {}kg'.format(
self.Al, self.Fe, self.Si, self.acrylic, self.H2O, self.O2, self.food
)
return result
def __isub__(self, other):
"""Subtract the other resource from self and return the resulting resources object.
:param other:
:rtype: Resources
"""
result = self
result.Al -= other.Al
result.Fe -= other.Fe
result.Si -= other.Si
result.acrylic -= other.acrylic
result.H2O -= other.H2O
result.O2 -= other.O2
result.food -= other.food
return result
def __iadd__(self, other):
"""Add the other resource object to self and return the resulting resources object.
:param other:
:rtype: Resources
"""
result = self
result.Al += other.Al
result.Fe += other.Fe
result.Si += other.Si
result.acrylic += other.acrylic
result.H2O += other.H2O
result.O2 += other.O2
result.food += other.food
return result
|
a5f64edaede8218e9ec9281a81b43a1e27449c33 | diofelpallega/unittests | /tests/account.py | 606 | 3.6875 | 4 |
class Account(object):
def __init__(self, account_number, balance):
if type(account_number) == str and type(balance) == int:
self.account_number = account_number
self.balance = balance
else:
print "error inputs"
class AccountWithdraw(object):
def __init__(self, account_number, balance, withdraw_amount):
if type(account_number) == str and type(balance) == int and type(withdraw_amount) == int and balance > withdraw_amount:
self.balance = balance - withdraw_amount
else:
print "invalid inputs"
|
5c0c2c9ce36a8b2b507328dc678fa1f77ae7503f | PyBeaner/DiveIntoPython3 | /7.Classes & Iterators/fibonacci.py | 779 | 3.828125 | 4 | __author__ = 'PyBeaner'
class Fib:
"""
Iterator that yield numbers in the Fibonacci sequence
"""
def __init__(self,max):
self.max = max
def __iter__(self):
"""
called manually by you or automatically by a for loop
:return:an iterator should always return an object that implements the __next__ method
"""
self.a = 0
self.b = 1
return self
def __next__(self):
fib = self.a
if fib>self.max:
raise StopIteration
self.a,self.b = self.b,self.a+self.b
return fib # Do not use yield here(yield is used in generators)
if __name__ == "__main__":
fib = Fib(1000)
print(fib,fib.__class__,fib.__doc__)
for f in fib:
print(f,end=" ")
|
1f0be79876c5409237e819e809f2009f3a5288db | lindsim/exercise03 | /our_calculator.py | 1,150 | 3.84375 | 4 | from arithmetic import *
from sys import exit
def main():
while True:
cal = raw_input(">")
if cal == "q":
exit()
else:
cal_split = cal.split(" ")
cal_split[:] = [x for x in cal_split if x != ""]
a = float(cal_split[1])
b = float(cal_split[2])
if cal_split[0] == "+":
print add(a, b)
elif cal_split[0] == "-":
print subtract(a, b)
elif cal_split[0] == "*":
print multiply(a, b)
elif cal_split[0] == "/":
if b == 0:
print "ERROR: divison by 0 is not possible."
else:
print divide(a, b)
elif cal_split[0] == "square":
print square(a, b)
elif cal_split[0] == "cube":
print cube(a)
elif cal_split[0] == "pow":
print pow(a, b)
elif cal_split[0] == "mod":
print mod(a, b)
else:
print "ERROR"
if __name__ == '__main__':
main() |
6910585c042ef9d5b052c497c98db12aad618371 | YLin-Z/CXCDATAUPDATE | /Include/main.py | 819 | 3.59375 | 4 | import pandas as pd
import os
def updaterow(row,numofcol):
i=1
print('-----------------------------------------------------------------')
# print(type(row))
while i<numofcol:
# print(row[1][i])
if row[1][i] =='-':
# print('-')
row[1][i]=0
i=i+1
return row
# 填充空的数
def updatedata(path):
df = pd.read_excel(path, sheet_name=0)
numofcol,numofrow=df.shape
result=()
for row in df.iteritems():
newrow = updaterow(row,numofcol) # 每一列填充空位
result =result+newrow
print(result)
df_result = pd.DataFrame(result)
df_result.to_excel("D:/test.xls",index=False)
if __name__ == '__main__':
path = "D:/CXCDATA/yibanyuanchuanbiaover0.xls"#待录入文件的路径
updatedata(path)
|
00837ace4be4dc33f4445a0b707cb431d765918b | raiyansayeed/ProgLangData | /add_field.py | 653 | 3.703125 | 4 | import json
import os
filename = 'data_copy.json'
field = input("Enter a field name: ")
val = int(input("String (1) or String array (2)?: "))
def add_string(lang):
tmp = lang
tmp[field] = "Not updated"
return tmp
def add_array(lang):
tmp = lang
tmp[field] = ["Not updated"]
return tmp
with open(filename, "r") as f:
data = json.load(f)
if val == 1:
data = list(map(add_string, data))
elif val == 2:
data = list(map(add_array, data))
else:
print("You must choose either a string or string array value for your field.")
with open(filename, 'w') as f:
json.dump(data, f, indent=4) |
21801e8041c3d26c4f0b17b562e685d004e69ed0 | elchic00/leetcode | /reverse.py | 124 | 4.09375 | 4 | def reverse(s):
str = ""
for c in s:
str = c + str
return str
s = "string"
print(s)
print(reverse(s))
|
dc38ac93aa069e4f5f0ba37c03b61b6b14f5dea7 | Onac8/X-Serv-14.2-Variaciones | /servidor-http-simple.py | 1,689 | 3.640625 | 4 | #!/usr/bin/python3
"""
Simple HTTP Server
Jesus M. Gonzalez-Barahona and Gregorio Robles
{jgb, grex} @ gsyc.es
TSAI, SAT and SARO subjects (Universidad Rey Juan Carlos)
"""
import socket
# Create a TCP objet socket and bind it to a port
# We bind to 'localhost', therefore only accepts connections from the
# same machine
# Port should be 80, but since it needs root privileges,
# let's use one above 1024
mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Let the port be reused if no process is actually using it
mySocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# Bind to the address corresponding to the main name of the host
mySocket.bind((socket.gethostname(), 1235))
# Queue a maximum of 5 TCP connection requests
mySocket.listen(5)
# Accept connections, read incoming data, and answer back an HTML page
# (in an infinite loop)
try:
while True:
print('Waiting for connections')
(recvSocket, address) = mySocket.accept()
print('HTTP request received:')
print(recvSocket.recv(2048))
print ('Answering back...')
recvSocket.send(bytes('HTTP/1.1 200 OK\r\n\r\n' +
'<html><body><h1>WINTER IS COMING</h1>' +
'<img src="http://cdn.playbuzz.com/cdn/2bfd334d-a2dc-48da-a14b-f15e8bd223c6/22540de3-ba97-497e-8e11-ccac96e2967b.jpg"' +
'alt="Got_Houses" style="width:1000px;height:300px;">' +
'<iframe width="800" height="400" src="https://www.youtube.com/embed/ECewrAld3zw" frameborder="0" allowfullscreen></iframe>' +
'</body></html>' +
'\r\n', 'utf-8'))
recvSocket.close()
except KeyboardInterrupt:
print ("Closing binded socket")
mySocket.close()
|
f10bf8ad5cd324c8880eec233fb852b86150564d | alsimoes/mao-na-massa | /lista1/peso_ideal.py | 137 | 3.546875 | 4 | # -*- coding:utf-8 -*-
altura = float(raw_input('\nQual a sua altura? '))
print '\nSeu peso ideal é %3.1f kilos.\n' % ((72.7*altura)-58) |
30db04329ab776355e05a3e84af563a6e0c62eb1 | yavord/hmm | /test/backward.py | 901 | 3.625 | 4 | def backward(X,A,E):
"""Given a single sequence, with Transition and Emission probabilities,
return the Backward probability and corresponding trellis."""
allStates = A.keys()
emittingStates = E.keys()
L = len(X) + 2
# Initialize
B = {k:[0] * L for k in allStates} # The Backward trellis
for k in allStates:
B[k][-2] = A[k]['E']
#####################
# START CODING HERE #
#####################
# Remaining columns
# for i in range(L-3,-1,-1):
# s = seq[i]
# ...
for i in range(L-3, -1, -1):
s = X[i]
for k in allStates:
terms = [A[k][l]*E[l][s]*B[l][i+1] for l in emittingStates]
B[k][i] = sum(terms)
#####################
# END CODING HERE #
#####################
P = B['B'][0] # The Backward probability -- should be identical to Forward!
return(P,B) |
6535916cfb74a4c43c6f5310433f5910289200cd | guyuzhilian/Programs | /Python/project_euler/problem34.py | 698 | 3.921875 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# author: lidajun
# date: 2015-08-30 17:02
factorial_cache = [1, 1]
def init_factorials():
for i in range(2, 10):
factorial_cache.append(factorial_cache[i-1] * i)
def get_n_digit(num, n):
return int(num // pow(10, n-1) % 10)
def is_the_curious_number(num):
total = 0
for i in range(1, len(str(num)) + 1):
total += factorial_cache[get_n_digit(num, i)]
return total == num
def main():
init_factorials()
total = 0
for num in range(10, factorial_cache[9] * 7):
if is_the_curious_number(num):
print(num)
total += num
print(total)
if __name__ == "__main__":
main() |
83dd5f49bd102c81b6b9b6c2bace7c4845b5a8fd | sametatabasch/Python_Ders | /ders11.py | 772 | 4.03125 | 4 | kullanicilar = {
"samet": {
"sifre": "1234",
"adı": "Samet",
"soyadı": "ATABAŞ"
},
"ahmet": {
"sifre": "ahmet61",
"adı": "Ahmet Can",
"soyadı": "ATABAŞ"
},
"vecihi": {
"sifre": "hürkuş",
"adı": "Vecihi",
"soyadı": "hürkuş"
}
}
gKullaniciAdi= input("Kullanıcı Adınız:").lower()
if gKullaniciAdi in kullanicilar:
gSifre = input("Şifreniz:")
if gSifre == kullanicilar[gKullaniciAdi]["sifre"]:
print("Hoşgeldiniz. Sayın",
kullanicilar[gKullaniciAdi]["adı"].capitalize(),
kullanicilar[gKullaniciAdi]["soyadı"].upper()
)
else:
print("Yanlış Şifre")
else:
print("Böyle bir kullanıcı Yok") |
5695083e8f8516d9e03224af1093d759e4beee61 | Jennymason24/CNS210.60.WN2020 | /oldfib.py | 233 | 3.890625 | 4 | def fibonacci(n):
F0=0
F1=1
if n < 0:
print("Incorrect input")
elif n == 0:
return F0
elif n == 1:
return F1
else:
return
Fibonacci(n-1)+Fibonacci(n-2)
print(fibonacci(9))
|
ebdac5ff1b71d920337598f9bb87e2e7b64c5970 | bopopescu/imfree | /venv/Lib/site-packages/base64_util/__init__.py | 2,260 | 3.859375 | 4 | import re
def get_only_base64_characters(arg):
'''
Returns only the base64 characters from the string, preserving order.
Args:
arg: The string that will have the non-base64 characters removed
Returns:
A string containing only base64 characters
'''
if not arg:
return arg
return re.sub('[^A-Za-z0-9+/=]', '', arg)
def contains_only_base64_characters(arg):
'''
Determines if arg contains only base64 character, regardless of order.
Args:
arg: the string being evaluated
Returns:
True: if the arg contains only base64 characters
False: if is empty, None, or contains non-base64 characters
'''
if not arg:
return False
only_base64 = get_only_base64_characters(arg)
return len(only_base64) is len(arg)
def is_base64(arg):
'''
Detremines if arg is of proper length and only contains valid base64 characters
Args:
arg: the string being considered
Returns:
True: if is a proper base64 string
False: otherwise
'''
if not arg:
return False
pattern = re.compile('^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$')
if pattern.match(arg):
return True
else:
return False
def pad_string_until_proper_base64_length(arg):
'''
Pads arg until it is of proper length to be a valid base64 string.
If arg begins with '=', will reverse it and move forward with padding.
Raises ValueError if arg is not base64
Args:
arg: The string that will be padded
Returns:
padded base64 string, if base64
None or empty string, if arg is None or empty
otherwise, throws exception
'''
if not arg:
return arg
if not contains_only_base64_characters(arg):
raise ValueError("This string has non-base64 characters: {}".format(arg))
if arg[0] == '=':
arg = arg[::-1]
# Adding padding
while(len(arg) % 4 != 0):
arg += '='
if not is_base64(arg):
raise ValueError("This is not a valid Base64 string: {}".format(arg))
return arg
|
e40cead6611db94806ea78ffa79bfbc170cc4cbb | vsdrun/lc_public | /co_uber/621_Task_Scheduler.py | 3,263 | 3.96875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
https://leetcode.com/problems/task-scheduler/description/
https://leetcode.com/problems/task-scheduler/discuss/104507
Given a char array representing tasks CPU need to do.
It contains capital letters A to Z where different letters represent
different tasks.
Tasks could be done without original order.
Each task could be done in one interval.
For each interval, CPU could finish one task or just be idle.
However, there is a non-negative cooling interval n that means
between two same tasks,
there must be at least n intervals that CPU are
doing different tasks or just be idle.
You need to return the least number of intervals the
CPU will take to finish all the given tasks.
Example 1:
Input: tasks = ["A","A","A","B","B","B"], n = 2
Output: 8
Explanation: A -> B -> idle -> A -> B -> idle -> A -> B.
Note:
The number of tasks is in the range [1, 10000].
The integer n is in the range [0, 100].
explain:
Say we were given input AAAA BBBB CCCC DDD EEE FF GG HH JJ KK, and N = 6.
We can start creating a schedule. A, B, and C occur the most times,
so let’s place them first.
We have to make each task of the same type N = 6 spaces apart.
(A _ _ _ _ _ _ )(A _ _ _ _ _ _)(A _ _ _ _ _ _)A _ _
A B _ _ _ _ _ A B _ _ _ _ _ A B _ _ _ _ _ A B _
A B C _ _ _ _ A B C _ _ _ _ A B C _ _ _ _ A B C
Now, we’ll just start putting D’s, E’s, etc.
in left to right order similar to how we put the other letters.
By our justification above, they won’t collide - this will be a valid schedule.
A B C D _ _ _ A B C D _ _ _ A B C D _ _ _ A B C
A B C D E _ _ A B C D E _ _ A B C D E _ _ A B C
A B C D E F _ A B C D E F _ A B C D E _ _ A B C
A B C D E F G A B C D E F _ A B C D E G _ A B C
A B C D E F G A B C D E F H A B C D E G H A B C
Now this is a compact schedule, but we might still have stuff left over.
We can just place them however we want.
In the article there’s justification for why this is possible even
if say J already occurrs in the compact schedule but isn’t exhausted yet.
J K A B C D E F J K G A B C D E F H A B C D E G H A B C
explain:
Say we were given input AAAA BBBB CCCC DDD EEE FF GG HH JJ KK, and N = 1.
We can start creating a schedule. A, B, and C occur the most times,
so let’s place them first.
We have to make each task of the same type N = 6 spaces apart.
(A _ )(A _ )(A _ )A _ _
A B A B A B A B C
"""
class Solution(object):
def leastInterval(self, tasks, N):
"""
:type tasks: List[str]
:type n: int
:rtype: int
"""
import collections
task_counts = collections.Counter(tasks).values()
test = collections.Counter(tasks)
print("test: {}".format(test)) # Counter({'A': 3, 'B': 3})
M = max(task_counts)
print("M: {0}".format(M))
print("task_counts: {0}".format(task_counts))
# task_counts 為 list
# .count 為看看有幾個最大值為M的.
Mct = task_counts.count(M)
print("Mct: {0}".format(Mct))
return max(len(tasks), (M - 1) * (N + 1) + Mct)
def build():
return ["A", "A", "A", "B", "B", "B"], 2
if __name__ == "__main__":
s = Solution()
result = s.leastInterval(*build())
print(result)
|
f710b4cbbe9fa66ede7e8a0c3059e36c937945ea | CodeProgress/misc | /TheGame.py | 4,584 | 3.59375 | 4 |
import random
import cProfile
class Rating(object):
def __init__(self):
self.lowRating = 0
self.highRating = 10
self.averageRating = 5
self.standardDeviationRating = 2
def get_rating(self):
'''
Returns a random float between low and high using a gaussian distribution.
uses
self.lowRating
self.highRating
self.averageRating
self.standardDeviation
To help limit the runtime of this function, the following conditions are enforced:
low <= mu - sigma
high >= mu + sigma
Doing so will ensures a 99.6% chance the method will finish within 5 loops,
a 1 in 4.3 billion chance of taking more than 20 loops
and only a 1 in 1.4x10e48 chance of taking more than 100 loops...
'''
mu = self.averageRating
sigma = self.standardDeviationRating
assert (self.lowRating + sigma) <= mu <= (self.highRating - sigma), 'Limit range must cover at least one std dev from mu in each direction to avoid infinite or near infinite loop'
rating = random.gauss(mu, sigma)
while rating < self.lowRating or rating > self.highRating:
rating = random.gauss(mu, sigma)
return rating
class Person(object):
def __init__(self):
self.rating = Rating().get_rating()
self.mate = None
self.exes = []
def start_relationship(self, otherPerson):
self.mate = otherPerson
def end_relationship(self):
assert self.mate
self.exes.append(self.mate)
self.mate = None
def is_chemistry(self, otherPerson):
'''
true if the other person is within one rating point, false otherwise
can be made more complex later, for example:
pickiness (which might change based on factors)
'''
return abs(self.rating - otherPerson.rating) < 5
class Population(object):
def __init__(self, numX, numY):
self.allX = set(Person() for x in xrange(numX))
self.allY = set(Person() for y in xrange(numY))
self.singleX = self.allX.copy()
self.singleY = self.allY.copy()
self.takenX = set()
self.takenY = set()
def test_single_union_taken_equals_all(self):
assert self.singleX.union(self.takenX) == self.allX
assert self.singleY.union(self.takenY) == self.allY
class TheGame(object):
def __init__(self, numX, numY, numDays):
self.population = Population(numX, numY)
self.numDays = numDays
def run_simulation(self):
for day in xrange(self.numDays):
self.simulate_day()
self.test_invariants()
def test_invariants(self):
self.test_equal_number_of_taken()
self.population.test_single_union_taken_equals_all()
def test_equal_number_of_taken(self):
assert len(self.population.takenX) == len(self.population.takenY)
def simulate_day(self):
self.date_singles()
def date_singles(self):
if not self.population.singleX: return
if not self.population.singleY: return
xSingles = list(self.population.singleX)
ySingles = list(self.population.singleY)
random.shuffle(xSingles)
random.shuffle(ySingles)
while xSingles and ySingles:
x = xSingles.pop()
y = ySingles.pop()
self.go_on_date(x, y)
def go_on_date(self, x, y):
if self.is_date_successful(x, y):
self.pair_up(x, y)
def pair_up(self, x, y):
assert x in self.population.singleX
assert y in self.population.singleY
x.start_relationship(y)
y.start_relationship(x)
self.population.singleX.remove(x)
self.population.singleY.remove(y)
self.population.takenX.add(x)
self.population.takenY.add(y)
def breakup(self, x, y):
assert x in self.population.takenX
assert y in self.population.takenY
x.end_relationship(y)
y.end_relationship(x)
self.population.takenX.remove(x)
self.population.takenY.remove(y)
self.population.singleX.add(x)
self.population.singleY.add(y)
def is_date_successful(self, x, y):
if x.is_chemistry(y) and y.is_chemistry(x):
self.pair_up(x, y)
a = TheGame(100000, 100000, 365)
cProfile.run('a.run_simulation()')
print 'taken x, y: ', len(a.population.takenX), len(a.population.takenY)
|
bf28dd80c9b1b50a5a5afbec1d30abfe2e08991f | Sandhie177/CS5690-Python-deep-learning | /ICP1/ICP1_letter_digit.py | 427 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Aug 24 16:50:28 2018
@author: farid
"""
sentence = input("write down the sentence: ")
length = len(sentence)
digit = 0
letter = 0
for i in range(length):
temp=sentence[i]
if temp.isdigit():
digit +=1
if temp.isalpha():
letter +=1
print ("Number of digits in the sentence:", digit)
print ("Number of the letters in the sentence", letter)
|
7c13480c2ee6b7a83d7bb2bcdffde4b2d16d62f7 | yifengw95/Python-Programming | /Assignment1/6_yifeng_wang.py | 619 | 4.15625 | 4 | import random
random_number = random.randint(1,10)
count = 0
while(True):
guess = input('input your guess')
try:
guess = int(guess)
count = count + 1
if guess > random_number:
print('your guess is larger than the real number')
elif guess < random_number:
print('your guess is smaller than the real number')
else:
print('your guess is accurate')
print('you took {number} guesses to get the accurate number'.format(number = count))
break
except:
print('your input is not valid, please input it again') |
65ecded6b62f037f2a669401fa59f584c09ea04d | alephist/edabit-coding-challenges | /python/test/test_find_the_falsehoods.py | 683 | 3.53125 | 4 | import unittest
from typing import Any, List, Tuple
from find_the_falsehoods import find_the_falsehoods
test_values: Tuple[Tuple[List[Any], List[Any]]] = (
([0, 1, 2, 3], [0]),
(["", "a", "ab"], [""]),
([None, 1, [], [0], 0], [None, [], 0]),
([], []),
([[]], [[]]),
([[[]]], []),
(["0", 1, "", "[]", [], [""], 0, (), {}], ["", [], 0, (), {}])
)
class FindTheFalsehoodsTestCase(unittest.TestCase):
def test_find_falsy_values_in_input_list(self):
for lst, expected_lst in test_values:
with self.subTest():
self.assertEqual(find_the_falsehoods(lst), expected_lst)
if __name__ == '__main__':
unittest.main()
|
983f9a055d15113587c9a1c72ab6b83982a1099a | elainecao93/projecteulerstuff | /30.py | 457 | 3.546875 | 4 | # Find the sum of all the numbers that can be written as the sum of fifth powers of their digits.
# Let f(x) be the sum of the fifth powers of the digits of x, then f(x) < x for all x > 999999 (trivial upper bound)
# brute forcing from 2 to 999999 is inelegant, but isn't too bad and I don't see a cleaner solution
output = 0
for x in range (2, 1000000):
s = str(x)
y = 0
for ch in s:
y += int(ch)**5
if x==y:
print (x)
output += x
print(output) |
9bcb96f0ea058bb7063f14c0f973d969c10968a9 | NurRahmawatiSubuh/tugas1strukturdata | /R.1.7.py | 103 | 3.875 | 4 | def squares_odd_sum(n):
return sum(x*x for x in range(0,n) if x%2==1)
print(squares_odd_sum(7))
|
360faed1ed6efd03c82f23a4466b87adbab732e0 | chrispeabody/Class-Assignments | /Fall-2016/cs5401/as3/sokoban.py | 2,404 | 3.5625 | 4 | # Chris Peabody [email protected]
# Sokoban puzzle
# CS 5400, Artificial intelligence, F16
# Assignment 2 (MAIN FILE)
import sys
import grbefgs
import copy
from datetime import datetime
if __name__ == '__main__':
### --- CONFIGURATION --- ###
# Make sure a file was specified
if len(sys.argv) > 1:
instFile = sys.argv[1]
else:
instFile = input("Please type the puzzle instance file name: ")
# Open the puzzle instance file, and create a list based on it's lines
connected = False
while not connected:
try:
with open(instFile) as f:
instance = list(f)
connected = True
except Exception as e:
print("{}. Try again.".format(e))
instFile = input("Please type the puzzle instance file name: ")
# Trim lines of their extra bits
for line in range(len(instance)):
instance[line] = instance[line].replace('\n','')
# Collect information about map
width, height = instance[0].split(' ')
mapsize = (int(width), int(height))
targetloc = []
crateloc = []
wallloc = []
rawmap = instance[2:]
for y in range(len(rawmap)):
for x in range(len(rawmap[y])):
if rawmap[y][x] == 't':
targetloc.append((x,y))
if rawmap[y][x] == 'c':
crateloc.append((x,y))
if rawmap[y][x] == 'w':
wallloc.append((x,y))
pX, pY = instance[1].split(' ')
playerloc = (int(pX), int(pY))
# pact it neatly into a state
startState = {'player': playerloc,
'targets': targetloc,
'crates': crateloc,
'walls': wallloc,
'size':mapsize}
### --- SOLVE PUZZLE --- ###
# Start the timer! (save the time)
startTime = datetime.now()
# Solve it!
sol = grbefgs.GrBeFGS(startState)
# Stop the timer!
endTime = datetime.now()
# Record it!
with open(instFile.replace('.cfg', '_sol.txt').replace('inst','sol'), 'w') as s:
if sol == None:
s.write("There was no solution.")
else:
s.write('{}\n'.format((endTime - startTime).microseconds))
s.write(str(len(sol.PATH)))
s.write('\n')
s.write(sol.PATH)
s.write('\n')
s.write('{} {}\n'.format(width, height))
s.write('{} {}\n'.format(sol.STATE['player'][0], sol.STATE['player'][1]))
for y in range(int(height)):
for x in range(int(width)):
if (x, y) in sol.STATE['crates']:
s.write('c')
elif (x, y) in sol.STATE['walls']:
s.write('w')
else:
s.write('.')
s.write('\n')
|
4097b12369dd9d797f09ec97c8dd9a62eed973e9 | tonyvu2014/algorithm | /tree/same_tree.py | 1,063 | 4.125 | 4 | # Given the roots of two binary trees p and q, write a function to check if they are the same or not.
# Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
# Tranverse 2 trees simultaniously, at every step, compare nodes from the 2 trees
# If there is difference at one step, return False
# Return True at the end
def is_same_tree(p, q):
if p is None:
return q is None
if q is None:
return p is None
if p.val != q.val:
return False
else:
return is_same_tree(p.left, q.left) and is_same_tree(p.right, q.right)
if __name__ == '__main__':
left = TreeNode(1, None, None)
right = TreeNode(2, None, None)
p = TreeNode(1, left, right)
l = TreeNode(1, None, None)
r = TreeNode(2, None, None)
q = TreeNode(1, l, r)
print(is_same_tree(p, q))
|
a4f5b84fa617b97f13631784b5ae25cb6beeca1c | JulienZe/mega-spark | /megaspark/sql/megaframe.py | 5,044 | 3.546875 | 4 | from pyspark.sql.types import ByteType, ShortType, \
IntegerType, LongType, FloatType, DoubleType, BooleanType, StringType
class MegaFrame(object):
def __init__(self, df):
self._df = df
self.feat_info = [(field.name, field.dataType)
for field in self._df.schema.fields]
def __getitem__(self, *args):
"""Read the DataFrame according to the column names.
Examples
----------
>>> data_df.mega[["PassengerId", "Survived"]].mega.head(3)
PassengerId Survived
0 1 0
1 2 1
2 3 1
"""
col_names = args[0]
return self._df.select(col_names)
def head(self, n: int = 5):
"""This function returns the first `n` rows for
the DataFrame. For negative values of `n`,
this function returns all rows except
the last `n` rows, equivalent to ``df[:-n]``.
Parameters
----------
n : int, default=5
Number of rows to select.
Returns
---------
data_df : pandas DataFrame
The first `n` rows of the caller object.
Examples
----------
>>> data_df.mega.head(5)
PassengerId Survived Pclass ... Fare Cabin Embarked
0 1 0 3 ... 7.25 None S
1 2 1 1 ... 71.2833 C85 C
2 3 1 3 ... 7.925 None S
3 4 1 1 ... 53.1 C123 S
4 5 0 3 ... 8.05 None S
:param n:
"""
return self._df.toPandas().head(n)
def sort_values(self, *col_names, ascending=True):
"""Sort by one or more column names of the data frame
Parameters
----------
col_names: tuple
tuple of column names to sort by.
ascending: bool, default=True
If True, sort values in ascending order, otherwise descending.
Returns
---------
data_df: spark DataFrame
Sorted DataFrame
Examples
----------
>>> data_df.mega.sort_values("PassengerId", "Survived",
... ascending=False).mega.head(3)
PassengerId Survived Pclass ... Fare Cabin Embarked
0 99 1 2 ... 23 None S
1 98 1 1 ... 63.3583 D10 D12 C
2 97 0 1 ... 34.6542 A5 C
"""
return self._df.orderBy(*col_names, ascending=ascending)
def fillna(self, cols_dict={}):
"""Fill in missing values with fill_value
Parameters
------------
cols_dict: dict, default={}
key is colname, value is the missing value to fill in
Returns
------------
data_df: spark DataFrame
DataFrame with no missing value
Examples
----------
>>> data_df.mega.head(5)
PassengerId Survived Pclass ... Fare Cabin Embarked
0 1 0 3 ... 7.25 None S
1 2 1 1 ... 71.2833 C85 C
2 3 1 3 ... 7.925 None S
3 4 1 1 ... 53.1 C123 S
4 5 0 3 ... 8.05 None S
>>> df = data_df.mega.fillna({"Survived": 0, "Cabin": "unknown"})
>>> df.mega.head(5)
PassengerId Survived Pclass ... Fare Cabin Embarked
0 1 0 3 ... 7.25 unknown S
1 2 1 1 ... 71.2833 C85 C
2 3 1 3 ... 7.925 unknown S
3 4 1 1 ... 53.1 C123 S
4 5 0 3 ... 8.05 unknown S
"""
if len(cols_dict) == 0:
for name, dataType in self.feat_info:
if isinstance(dataType, (
ByteType, ShortType, IntegerType, LongType)):
cols_dict[name] = 0
elif isinstance(dataType, (FloatType, DoubleType)):
cols_dict[name] = 0.0
elif isinstance(dataType, (StringType, BooleanType)):
cols_dict[name] = "0"
else:
raise Exception("The missing value "
"of the current data "
"type cannot be handled")
return self._df.na.fill(cols_dict)
def table_alias(self, name):
"""Creates or replaces a local temporary view with DataFrame.
The lifetime of this temporary table is tied to `SparkSession`
Examples
----------
>>> df.table_alias("people")
"""
self._df.createOrReplaceTempView(name)
|
549a8d52a043e83c8d60fdcccd2429156ad814c2 | Imhotep504/PythonCode | /twenty.py | 796 | 4.09375 | 4 | #!/usr/bin/python
#import for system exit
import sys
#prompt user for equation
print("Enter in your equation to be calculated and spit out back at you")
#create vars to accept values and operand from console
line = raw_input()
split = line.split() #just like in Ruby
left = int(split[0])
op = split[1]
right = int(split[2])
#place holder
val = 0
if op == '+':
val = left + right
elif op == '-':
val = left - right
elif op == '*':
val = left * right
elif op == '/':
if right == 0:
print("Cant divide by zero Sunny ;)")
sys.exit()
val = left / right
else:
print("not sure wise guy of the operator: {operator}".format(operator=op))
sys.exit()
#now print to stdout
print("{line_expr} = {value:.2f}".format(line_expr=line, value=val))
|
a467f4915cc4c7b08de934152b37693efb2025e3 | abhaykatheria/cp | /HackerRank2/SOS.py | 297 | 3.625 | 4 | def Search(S):
l=len(S)
p=len(S)/3
count=0
string=S
for i in range(0,l):
if string[i:i+3]=="SOS":
count +=1
string=S[i+3:]
else:
continue
return abs(p-count)
S=str(input())
result=Search(S)
print(int(result))
|
b4c3c4e5b56b152efb7f8de400c80c6315879e07 | rwang249/ops435 | /lab3/lab3e.py | 1,240 | 4.46875 | 4 | #!/usr/bin/env python3
# Create the list called "my_list" here, not within any function defined below.
# That makes it a global object. We'll talk about that in another lab.
my_list = [ 100, 200, 300, 'six hundred' ]
def give_list():
# Does not accept any arguments
# Returns all of items in the global object my_list unchanged
output = my_list[0:]
return output
def give_first_item():
# Does not accept any arguments
# Returns the first item in the global object my_list as a string
output = str(my_list[0])
return output
def give_first_and_last_item():
# Does not accept any arguments
# Returns a list that includes the first and last items in the global object my_list
output = [ my_list[0], my_list[-1] ]
return output
def give_second_and_third_item():
# Does not accept any arguments
# Returns a list that includes the second and third items in the global object my_list
output = [ my_list[1], my_list[2] ]
return output
if __name__ == '__main__': # This section also referred to as a "main block"
print(give_list())
print(give_first_item())
print(give_first_and_last_item())
print(give_second_and_third_item()) |
c6af4647c3afc85bf095b6d072f0f735f7c81cb8 | margosukharenko/GB | /Python/lesson_01/task_04.py | 580 | 4.09375 | 4 | # 4. Пользователь вводит целое положительное число.
# Найдите самую большую цифру в числе. Для решения используйте цикл while и арифметические операции.
num = int(input("Введите целое положительно число >>> "))
max_num = 0
while True:
if num == 0:
break
one_num = num % 10
num = num // 10
if one_num > max_num:
max_num = one_num
print(f"Наибольшая цифра в числе = {max_num}")
|
c7f1f984b58ecaaa68680b187d9261a5b6f40624 | cookies5127/algorithm-learning | /leetcode/default/13_roman_to_int.py | 1,618 | 3.734375 | 4 | '''
13. Roman to Integer
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
For example, two is written as II in Roman numeral, just two one's added together.
Twelve is written as, XII, which is simply X + II. The number twenty seven is
written as XXVII, which XX + V + II.
Roman numberals are usually written
'''
EXAMPLES = [
(('III',), 3),
(('IV',), 4),
(('IX',), 9),
(('LVIII',), 58),
(('MCMXCIV',), 1994),
]
class Solution:
def get_count(self, f: str, str: str) -> int:
i = 1
while str.startswith(i * f):
i += 1
return i - 1
def romanToInt(self, s: str) -> int:
ROMAN_MAP = [
(('M', 'D', 'C'), 100,),
(('C', 'L', 'X'), 10,),
(('X', 'V', 'I'), 1,),
]
v = 0
for (ten, five, one), f in ROMAN_MAP:
if s.startswith(ten):
count = self.get_count(ten, s)
v += count * 10 * f
s = s[count:]
if s.startswith(one+ten):
v += 9 * f
s = s[2:]
if s.startswith(five):
v += 5 * f
s = s[1:]
if s.startswith(one+five):
v += 4 * f
s = s[2:]
if s.startswith(one):
count = self.get_count(one, s)
v += count * f
s = s[count:]
return v
|
9ee750e469732516f7bcc991d2b9c736bf29d216 | Yuchen112211/Leetcode | /problem79.py | 1,841 | 3.9375 | 4 | '''
79. Word Search
Medium
Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
Example:
board =
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]
Given word = "ABCCED", return true.
Given word = "SEE", return true.
Given word = "ABCB", return false.
Solution:
Another classic backtrack problem. The trick here is to set the character that has
passed before to invalid or illegal character.
Should write this easily.
'''
class Solution(object):
def exist(self, board, word):
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
from collections import deque
def isValid(row, col):
if 0 <= row < len(board) and 0 <= col < len(board[0]):
return True
return False
def backtrack(row, col, index):
if index == len(word):
return True
diff_x = [0,0,1,-1]
diff_y = [1,-1,0,0]
res = False
for i in range(4):
current_row = diff_x[i] + row
current_col = diff_y[i] + col
if isValid(current_row, current_col):
if board[current_row][current_col] == word[index]:
tmp = board[row][col]
board[row][col] = '#'
if backtrack(current_row, current_col, index + 1):
res = True
break
board[row][col] = tmp
return res
for i in range(len(board)):
for k in range(len(board[0])):
if board[i][k] == word[0]:
tmp = board[i][k]
board[i][k] = '#'
if backtrack(i,k,1):
return True
board[i][k] = tmp
return False
if __name__ == '__main__':
board = [['A','B','C','E'],['S','F','C','S'],['A','D','E','E']]
word = 'ABCCED'
s = Solution()
print s.exist(board, word)
|
14dbd083366da64b867da1a9eafc48008a57c069 | AllanTumu/PythonBasics | /BreakAndContinue.py | 617 | 3.890625 | 4 | name = "Tumuhimbise"
# using the break Key word
for i in name:
print(i)
if i == "h":
break
print("----------------------")
# using the continue Key word
for i in name:
print(i)
if i == "h":
continue
print("----------------------")
# using break and continue for lists
str = ["python", "Java", ".net", "C#"]
for i in str:
print(i)
if i == ".net":
break
print("----------------------")
districts = ["Mbarara", "Kampala", "Mbale", "Iganga", "Bududa", "Kyenjojo"]
for d in range(len(districts)):
print(districts[d])
if districts[d] == "Mbale":
break
|
8ca17ff327ee0a3c7a1ead8654e8364da938fa27 | hermanholmoy/TDT4109 | /Oppgaver/fibtall.py | 745 | 3.515625 | 4 | import time
def fib_performance(func, inp):
start = time.time()
func(inp)
end = time.time()
print(f"Runtime for n={inp} : ", (end - start))
def fib1(a):
n = 1
m = 1
fibs = [0, 1]
i = 0
while i < a - 3:
fibs.append(n)
temp = n
n = m + n
m = temp
i += 1
print(fibs)
def fib2(ant):
fibs = [0]
def a(n):
return ((1 + 5 ** (1 / 2)) / 2) ** n
def b(n):
return ((1 - 5 ** (1 / 2)) / 2) ** n
def fib_n(n):
return (a(n) - b(n)) / (a(1) - b(1))
for i in range(ant - 1):
fibs.append(int(round(fib_n(i), 0)))
print(fibs)
# n = 10**3
# fib_performance(fib1, n)
# fib_performance(fib2, n)
print(fib1(20))
|
4444c33f44eefa46c0fec2bf556e90e88bcb511d | williampsmith/algorithms | /largest_subsequence_sum.py | 662 | 3.515625 | 4 |
def largest_suybsequence_sum(array):
if not array:
return
largest_interval = (0,0)
largest_sum = array[0]
length = len(array)
for i in range(length):
for j in range(i, length):
new_sum = sum(array[i: j + 1])
if new_sum > largest_sum:
largest_sum = new_sum
largest_interval = (i,j)
return largest_interval
def largest_subsequence_sum_dp(array):
if not array:
return
largest_interval = [0,0]
largest_sum = 0
length = len(array)
for i in range(len(array)):
if largest_sum + array[i] < 0:
largest_interval = [i,i]
largest_sum = array[i]
else:
largest_interval[1] = i
largest_sum += array[i]
return largest_sum
|
9cc512ff71b43e8a79735ba57bbed05d5eaa189c | B-urb/generic_object_tracking | /python/Vector2.py | 588 | 3.578125 | 4 |
class Vector2:
def __init__(self,x=0,y=0, vec_as_list= None):
if vec_as_list is not None:
if len(vec_as_list) != 2:
raise Exception("List not length 2")
else:
self.x = vec_as_list[0]
self.y = vec_as_list[1]
else:
self.x = x
self.y= y
def __add__(self, other):
if isinstance(other,Vector2):
return Vector2(self.x + other.x,self.y+other.y)
def __iadd__(self, other):
self.x += other.x
self.y += other.y
return self
|
eb17a354ccbd1e96a31a526bdef9a182bc357404 | gengletao/learn-python | /1.download/ex6.py | 690 | 3.8125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: letao geng <[email protected]>
# Copyright (C) alipay.com 2011
'''
'''
import os
import sys
def main():
''' main function
'''
x = "There are %d types of people." % 10
binary = "binary"
do_not = "don't"
y = "Those who know %s and those who %s." % (binary, do_not)
print x
print y
print "I said: %r." % x
print "I also said: '%s'." % y
hilarious = False
joke_evaluation = "Isn't that joke so funny?! %r"
print joke_evaluation % hilarious
w = "This is the Left side of..."
e = "a string with a right side."
print w + e
print 'Done'
if __name__ == '__main__':
main()
|
6279da46807be37a13e6e8c8c89b7916bbcdf8ac | Jiezhi/myleetcode | /src/496-NextGreaterElementI.py | 1,372 | 3.515625 | 4 | #!/usr/bin/env python
"""
CREATED AT: 2021/10/19
Des:
https://leetcode.com/problems/next-greater-element-i/
GITHUB: https://github.com/Jiezhi/myleetcode
Difficulty: Easy
Tag:
See:
"""
from typing import List
class Solution:
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
"""
Runtime: 94 ms, faster than 19.85%
Memory Usage: 14.5 MB, less than 73.08%
1 <= nums1.length <= nums2.length <= 1000
0 <= nums1[i], nums2[i] <= 10**4
All integers in nums1 and nums2 are unique.
All the integers of nums1 also appear in nums2.
:param nums1:
:param nums2:
:return:
"""
ret = []
for num in nums1:
index = nums2.index(num)
for n in nums2[index + 1:]:
if n > num:
ret.append(n)
break
else:
ret.append(-1)
return ret
def test():
assert Solution().nextGreaterElement(nums1=[4], nums2=[4]) == [-1]
assert Solution().nextGreaterElement(nums1=[4, 1, 2], nums2=[1, 3, 4, 2]) == [-1, 3, -1]
assert Solution().nextGreaterElement(nums1=[2, 4], nums2=[1, 2, 3, 4]) == [3, -1]
assert Solution().nextGreaterElement(nums1=[2, 4, 3, 1], nums2=[4, 3, 2, 1]) == [-1, -1, -1, -1]
if __name__ == '__main__':
test()
|
31e84e989ae7b1e87347e251028cb941ba1a82d0 | Gabrri/LOGICA2_CC | /Codificacion_y_escritura_formulas/codificacion.py | 1,613 | 3.75 | 4 | # Codificacion y decodificacion de una tabla de Nf filas y Nc columnas
def codifica(f, c, Nf, Nc):
# Funcion que codifica la fila f y columna c
assert((f >= 0) and (f <= Nf - 1)), 'Primer argumento incorrecto! Debe ser un numero entre 0 y ' + str(Nf) - 1 + "\nSe recibio " + str(f)
assert((c >= 0) and (c <= Nc - 1)), 'Segundo argumento incorrecto! Debe ser un numero entre 0 y ' + str(Nc - 1) + "\nSe recibio " + str(c)
n = Nc * f + c
# print(u'Número a codificar:', n)
return n
def decodifica(n, Nf, Nc):
# Funcion que codifica un caracter en su respectiva fila f y columna c de la tabla
assert((n >= 0) and (n <= Nf * Nc - 1)), 'Codigo incorrecto! Debe estar entre 0 y' + str(Nf * Nc - 1) + "\nSe recibio " + str(n)
f = int(n / Nc)
c = n % Nc
return f, c
def codifica3(f, c, o, Nf, Nc, No):
# Funcion que codifica tres argumentos
assert((f >= 0) and (f <= Nf - 1)), 'Primer argumento incorrecto! Debe ser un numero entre 0 y ' + str(Nf - 1) + "\nSe recibio " + str(f)
assert((c >= 0) and (c <= Nc - 1)), 'Segundo argumento incorrecto! Debe ser un numero entre 0 y ' + str(Nc - 1) + "\nSe recibio " + str(c)
assert((o >= 0) and (o <= No - 1)), 'Tercer argumento incorrecto! Debe ser un numero entre 0 y ' + str(No - 1) + "\nSe recibio " + str(o)
v1 = codifica(f, c, Nf, Nc)
v2 = codifica(v1, o, Nf * Nc, No)
return v2
def decodifica3(x, Nf, Nc, No):
# Funcion que codifica un caracter en su respectiva fila f, columna c y objeto o
v1, o = decodifica(x, Nf * Nc, No)
f, c = decodifica(v1, Nf, Nc)
return f, c, o
|
9fbc6f63d84f7c3b74c24ff638bb00bd476f6ffe | MaleehaBhuiyan/pythonBasics | /notes_and_examples/h_functions.py | 853 | 4.0625 | 4 | #Funtions
#a collection of code that performs a specific task
#its good to break up your code into dddifferent functions
#how to create a function
def say_hi():
print("Hello User")
#to execute the code you need to call it
say_hi()
#the flow of functions
print("Top")
say_hi()
print("Bottom")
#making the functions more powerful by giving them information through paramaters
def say_goodnight(noun):
print("Goodnight " + noun)
say_goodnight("moon")
#you can have more than one parameter
def say_bye(name_one, name_two):
print("Bye, " + name_one + ". Bye, " + name_two + ".")
say_bye("Maleeha", "Sadeyah")
#Return statement
#sometimes we want information back from that function, execute code but then give me some information back
def cube(number):
return number * number * number
result = cube(4)
print(result) |
2201673292c7f16222c9a8f659345d9e618bc218 | ChrisJHatfield/Python | /Fundamentals/Functions Intermediate I/Functions_Intermediate1.py | 1,875 | 4.3125 | 4 | # If no arguments are provided, the function should return a random integer between 0 and 100.
# If only a max number is provided, the function should return a random integer between 0 and the max number.
# If only a min number is provided, the function should return a random integer between the min number and 100
# If both a min and max number are provided, the function should return a random integer between those 2 values.
# random.random() returns a random floating number between 0.000 and 1.000
# random.random() * 50 returns a random floating number between 0.000 and 50.000
# random.random() * 25 + 10 returns a random floating number between 10.000 and 35.000
# round(num) returns the rounded integer value of num
import random
def randInt(min=0, max=0):
if min == 0 and max == 0:
num = random.random() * 100
num = round(num)
print('random 0-100:', + num)
return num
elif max > 0 and max <= 100 and min == 0:
num = random.random() * max
num = round(num)
print('max number:', + num)
return num
elif min >= 0 and min < 100 and max == 0:
num = random.random() * (100-min) + min
num = round(num)
print('min number:', + num)
return num
else:
num = random.random() * (max - min) + min
num = round(num)
print('range provided random number:', + num)
return num
random_numbers = randInt()
random_numbers = randInt(min=20)
random_numbers = randInt(max=70)
random_numbers = randInt(min=20, max=40)
#print(randInt()) # should print a random integer between 0 to 100
#print(randInt(max=50)) # should print a random integer between 0 to 50
#print(randInt(min=50)) # should print a random integer between 50 to 100
#print(randInt(min=50, max=500)) # should print a random integer between 50 and 500
|
b7d6485ac153e2500cc40914af1c15c040032a39 | AnkitSrma/PythonWorkshop | /Assignment 2/Conditional/Question 4.py | 224 | 4.25 | 4 | numbers = (1,2,3,4,5,6,7,8,9)
odd = 0
even = 0
for i in numbers:
if not i % 2:
even+=1
else:
odd+=1
print("Number of even numbers :",even)
print("Number of odd numbers :",odd)
|
68f7efd311dedd4b50dfb2d2a24035c85ae5674e | legeannd/codigos-cc-ufal | /APC/AULA 7/Fatores.py | 104 | 3.546875 | 4 | n = int(input())
fator = []
for i in range(1, n+1):
if n%i==0:
fator.append(i)
print(fator)
|
2c79df67506a066a8a88280bb4b93fcb06ced64a | ihatetoast/lpthw | /ex6.py | 746 | 3.875 | 4 | x = "There are %d types of people." %10
binary = "binary"
do_not = "don't"
y = "Those who know %s and those who %s." %(binary, do_not)
print x
print y
print "I said: %r." %x
print "I also said: '%s'." %y
hilarious = False
joke_evaluation = "Isn't that joke so funny?! %r"
print joke_evaluation %hilarious
w = "This is the left side of ..."
e = "a string with a right side."
print w + e
# Go through this program and write a comment above each line explaining it.
#NO, i get most.
# Find all the places where a string is put inside a string. There are four places.
#DONE
# Are you sure there are only four places? How do you know? Maybe I like lying.
# Explain why adding the two strings w and e with + makes a longer string.
#NO. i get it. |
18b25c5920e3570e78ce1ca7182da44aea47bdf9 | rahulpandey-rp/bootcamp_2021 | /Python_Bootcamp/python_day3/fivezeros.py | 161 | 3.875 | 4 | list_zero = [0]*5
print(list_zero)
list_zero = []
for i in range(5):
list_zero.append(0)
print(list_zero)
list_zero = [0 for i in range(5)]
print(list_zero)
|
806f10606548b573fdf8029ba8882b90ebe7bb93 | rj8928/pycharm-master | /base_study/13-变参.py | 220 | 3.703125 | 4 | sums = 0
def sum_num(a,b,*args):
print(args)
sums = a+b
for temp in args:
global sums
print(temp)
sums = sums+temp
return sums
sums_s = sum_num(1,2,3,4,5,6,7,8,9)
print(sums_s)
|
c1f8d6ef44c79c33c6e6d617baae7244eb683e62 | japarker02446/BUProjects | /CS677 Data Analysis with Python/Homework3/JparkerHw3Helper.py | 5,934 | 4 | 4 | # -*- coding: utf-8 -*-
"""
Jefferson Parker
Class: CS 677
Date: April 1, 2022
Homework Problem 3.*
Support functions for Homework 3.
WARNING: IF you are running this in an IDE you need to change the path of the
working directory manually below. The __file__ variable is set when running
python as a script from the command line.
REFERENCE: https://stackoverflow.com/questions/16771894/python-nameerror-global-name-file-is-not-defined
"""
import os
import pandas as pd
# Set the input directory path.
try:
os.chdir(os.path.dirname(os.path.abspath(__file__)))
except NameError:
os.chdir(r'C:\Users\jparker\Code\Python\CS677\HW3')
class JparkerHw3Helper (object):
'''
Helper class for Homework 3.
'''
def load_note_data ():
'''
Load the banknote data set from a text file to a pandas dataframe.
NOTE - the file is saved with .txt extension but if you open it you can
clearly see that it is a CSV (comma separated value) file.
Returns
-------
Pandas DataFrame with banknote data with column names.
'''
note_data = pd.DataFrame()
note_data = pd.read_csv("data_banknote_authentication.txt", \
header = None, \
names=['F1', 'F2', 'F3','F4','Class']
)
return note_data
# End load_note_data.
# Implement the "simple classifier" from homework question 3.2
def simple_simple_classifier(F1: float, F2: float, F3: float, *F4) -> str:
'''
Simple bill classifier based on visual inspection of training data for good
and bad bills.
Parameters
----------
F1 : float
Bank note data parameter F1.
F2 : float
Bank note data parameter F2.
F3 : float
Bank note data parameter F3.
*F4 : TYPE
Bank note data parameter F4 (optional).
Returns
-------
str
Classification selection, 'good' if predicted as authentic bill,
'fake' if predicted to be counterfeit.
'''
if F1 >= 0 and F2 >= 5 and F3 <= 5:
return 'good'
else:
return 'fake'
# End simple_simple_classifier
def simple_classifier(series) -> str:
'''
Parameters
----------
series : TYPE
Pandas Series objects representing one row of bill classifier data.
Returns
-------
str
Classification selection, 'good' if predicted as authentic bill,
'fake' if predicted to be counterfeit.
'''
return(JparkerHw3Helper.simple_simple_classifier(\
float(series['F1']), \
float(series['F2']), \
float(series['F3']) \
) \
)
# End simple_classifier
# Compute [True|False][Positive|Negative] counts, True Positive Rate
# (Sensitivity) and True Negative Rate (Specificity)
def calc_pred_performance(truth_vector, prediction_vector) -> list:
'''
Compare two vectors of values, truth and prediction, to determine
[True|False][Positive|Negative] counts, True Positive Rate (Sensitivity)
and True Negative Rate (Specificity)
Be sure to normalize values for True and False before calling the function.
Parameters
----------
truth_vector : TYPE
Iterable of TRUTH values.
prediction_vector : TYPE
Iterable of PREDICTED values.
Returns
-------
list
Returns a list of TP, FP, TN, FN, Accuracy, TPR (Sensitivity) and TNR
(Specificity)
'''
# Merge the input vectors into a DataFrame.
# Note, this assumes the two vectors have the same index.
calc_table = pd.DataFrame(prediction_vector).merge(truth_vector, \
left_index = True, \
right_index = True)
calc_table.columns = ['Prediction', 'Truth']
# Create empty counter columns of ZEROS.
calc_table['TP'] = 0
calc_table['FP'] = 0
calc_table['TN'] = 0
calc_table['FN'] = 0
# For all the things.
for i in calc_table.index:
# Positive prediction (TP, FP)
if calc_table.loc[i, 'Prediction'] == 0:
if calc_table.loc[i, 'Prediction'] == calc_table.loc[i, 'Truth']:
calc_table.loc[i, 'TP'] = 1
else:
calc_table.loc[i, 'FP'] = 1
# Negative prediction (TN, FN)
else:
if calc_table.loc[i, 'Prediction'] == calc_table.loc[i, 'Truth']:
calc_table.loc[i, 'TN'] = 1
else:
calc_table.loc[i, 'FN'] = 1
# Quantify the total counts of TP, FP, TN, FN.
# Calculate Accuracy, TPR, TNR.
# Return the sums and rates as a list.
TP = sum(calc_table.TP)
FP = sum(calc_table.FP)
TN = sum(calc_table.TN)
FN = sum(calc_table.FN)
# OY! MATH!
try:
accuracy = (TP + TN) / (TP + FP + TN + FN)
except ZeroDivisionError:
accuracy = 0
try:
TPR = TP / (TP + FN)
except ZeroDivisionError:
TPR = 0
try:
TNR = TN / (TN + FP)
except ZeroDivisionError:
TNR = 0
return list([TP, FP, TN, FN, accuracy, TPR, TNR])
# End calc_pred_performance |
7428dd35e2ac792bf5c0b51bc1d8832f2afe869f | AnthonyWaddell/Automating-The-Boring-Stuff-with-Python | /pdfEncrypter.py | 1,384 | 3.734375 | 4 | #! python3
''' Simple python script that goes through a folder and all subfolders and encrypts
all .pdf files with password provided by command line'''
import PyPDF2
import os
import sys
# Get the password and create list for
password = sys.argv[1]
# Start from current working directory and iterateover all files/(sub)folders
for root, directory, filename in os.walk('.'):
# If it's a PDF, we are going to encrypt it
if filename.endwith('.pdf'):
# Get the absolute path
path = os.path.join(root, filename)
pdfReader = PyPDF2.PdfFileReader(open(path, 'rb'))
# If it isn't already encrypted
if pdfReader.isEncrypted is False:
pdfWriter = PyPDF2.PdfFileWriter()
for pdf_page in range(pdfReader.numPages):
pdfWriter.addPage(pdf_reader.getPage(pdf_page))
# Encrypt this PDF as a copy and save it with _encrypted
pdfWriter.encrypt(password)
encrypted_path = (path[:-4] + '_encrypted.pdf')
encrypted_pdf = open(encrypted_path, 'wb')
pdfWriter.write(encrypted_version)
encrypted_version.close()
# If it was encrypted properly
pdfReader = PyPDF2.PdfFileReader(open(encrypted_path, 'rb'))
if pdfReader.isEncrypted:
decrypted = pdfReader.decrypt(password)
if decrypted:
os.remove(path)
# If it wasn't encrypted properly
else:
print('Failed to encrypt: ' + filename)
print(filename + ' not deleted...') |
2647f4412f371e605d0cac08a4ec44b16843e591 | jrainbolt/jrainbolt.github.io | /CS421/Assignments/2/hw2-master/q1.py | 4,303 | 3.640625 | 4 | import argparse
# Class definition for Hidden Markov Model (HMM)
# Do not make any changes to this class
# You are not required to understand the inner workings of this class
class HMM:
"""
Arguments:
states: Sequence of strings representing all states
vocab: Sequence of strings representing all unique observations
trans_prob: Transition probability matrix. Each cell (i, j) contains P(states[j] | states[i])
obs_likelihood: Observation likeliood matrix. Each cell (i, j) contains P(vocab[j] | states[i])
initial_probs: Vector representing initial probability distribution. Each cell i contains P(states[i] | START)
"""
def __init__(self, states, vocab, trans_prob, obs_likelihood, initial_probs):
self.states = states
self.vocab = vocab
self.trans_prob = trans_prob
self.obs_likelihood = obs_likelihood
self.initial_probs = initial_probs
# Function to return transition probabilities P(q1|q2)
def tprob(self, q1, q2):
if not (q1 in self.states and q2 in ['START'] + self.states):
raise ValueError("invalid input state(s)")
q1_idx = self.states.index(q1)
if q2 == 'START':
return self.initial_probs[q1_idx]
q2_idx = self.states.index(q2)
return self.trans_prob[q2_idx][q1_idx]
# Function to return observation likelihood P(o|q)
def oprob(self, o, q):
if not o in self.vocab:
raise ValueError('invalid observation')
if not (q in self.states and q != 'START'):
raise ValueError('invalid state')
obs_idx = self.vocab.index(o)
state_idx = self.states.index(q)
return self.obs_likelihood[obs_idx][state_idx]
# Function to retrieve all states
def get_states(self):
return self.states.copy()
# Function to initialize an HMM using the weather-icecream example in Figure 6.3 (Jurafsky & Martin v2)
# Do not make any changes to this function
# You are not required to understand the inner workings of this function
def initialize_icecream_hmm():
states = ['HOT', 'COLD']
vocab = ['1', '2', '3']
tprob_mat = [[0.7, 0.3], [0.4, 0.6]]
obs_likelihood = [[0.2, 0.5], [0.4, 0.4], [0.4, 0.1]]
initial_prob = [0.8, 0.2]
hmm = HMM(states, vocab, tprob_mat, obs_likelihood, initial_prob)
return hmm
# Function to implement viterbi algorithm
# Arguments:
# hmm: An instance of HMM class as defined in this file
# obs: A string of observations, e.g. ("132311")
# Returns: seq, prob
# Where, seq (list) is a list of states showing the most likely path and prob (float) is the probability of that path
# Note that seq sould not contain 'START' or 'END' and In case of a conflict, you should pick the state at lowest index
def viterbi(hmm, obs):
# [YOUR CODE HERE]
"""use the HMM class and look at viterby pseudocode to finisih this function."""
return ['HOT', 'COLD'], 0.2
# Use this main function to test your code when running it from a terminal
# Sample code is provided to assist with the assignment, feel free to change/remove it if you want
# You can run the code from terminal as: python3 q3.py
# It should produce the following output:
# $python3 q3.py
# P(HOT|COLD) = 0.4
# P(COLD|START) = 0.2
# P(1|COLD) = 0.5
# P(2|HOT) = 0.4
# Path: ['HOT', 'COLD']
# Probability: 0.2
def main():
# We can initialize our HMM using initialize_icecream_hmm function
hmm = initialize_icecream_hmm()
# We can retrieve all states as
print("States: {0}".format(hmm.get_states()))
# We can get transition probability P(HOT|COLD) as
prob = hmm.tprob('HOT', 'COLD')
print("P(HOT|COLD) = {0}".format(prob))
# We can get transition probability P(COLD|START) as
prob = hmm.tprob('COLD', 'START')
print("P(COLD|START) = {0}".format(prob))
# We can get observation likelihood P(1|COLD) as
prob = hmm.oprob('1', 'COLD')
print("P(1|COLD) = {0}".format(prob))
# We can get observation likelihood P(2|HOT) as
prob = hmm.oprob('2', 'HOT')
print("P(2|HOT) = {0}".format(prob))
# You should call the viterbi algorithm as
path, prob = viterbi(hmm, "13213")
print("Path: {0}".format(path))
print("Probability: {0}".format(prob))
################ Do not make any changes below this line ################
if __name__ == '__main__':
exit(main()) |
e494aaeea0077a5e3af83129a112a6104ed185cb | henryfang1989/ctci | /1_7_rotate_matrix.py | 208 | 3.609375 | 4 | # question: Given an image represented by N*N matrix, which each pixel in the image of 4 bytes, write a method to rotate the image by 90 degrees. Can you do this in place?
def rotate_matrix(pixels):
pass |
5eeb3108769f7d4aff575a02b01e8457166992e2 | diamondtron24/code_guild | /lab03.py | 3,579 | 4.34375 | 4 | # Lab 3: Grading
# Let's convert a number grade to a letter grade, using if and elif statements and comparisons.
# Concepts Covered
# input, print
# type conversion (str to int)
# comparisons (< <= > >=)
# if, elif, else
# Instructions
# Have the user enter a number representing the grade (0-100)
# Convert the number grade to a letter grade
# Numeric Ranges
# 90-100: A
# 80-89: B
# 70-79: C
# 60-69: D
# 0-59: F
# Version 2
# Find the specific letter grade (A+, B-, etc). You can check for more specific ranges using if statements,
# or use modulus % to get the ones-digit to set another string to '+', '-', or ' '.
# Then you can concatenate that string with your grade string.
# Version 3
# Extract the logic used to determine the grade and its qualifier ('+', '-', or ' ') into functions.
# Additionally, use a while loop to repeatedly ask the user if they'd like to compute another grade after each computation.
# Version 1
# grade_enter = input('Please enter your grade percentage: ')
# if grade_enter <= 59:
# print('You got an F.')
# elif grade_enter < 70:
# print('You got a D.')
# elif grade_enter < 80:
# print('You got a C.')
# elif grade_enter < 90:
# print('You got a B.')
# elif grade_enter <= 100:
# print('You got an A.')
# Version 2
# while True:
# grade_enter = int(input('Please enter your grade percentage: '))
# if grade_enter <= 59:
# letter = 'F'
# elif grade_enter < 70:
# letter = "D"
# elif grade_enter < 80:
# letter = 'C'
# elif grade_enter < 90:
# letter = 'B'
# elif grade_enter <= 100:
# letter = 'A'
# elif grade_enter > 100:
# print('Invalid precentage entered')
# print('Goodbye')
# break
# percent = grade_enter % 10
# if grade_enter < 60:
# print(letter)
# elif percent < 5:
# print(f'Your grade = {letter}-')
# elif percent == 5:
# print(f'Your grade = {letter}')
# elif percent > 5:
# print(f'Your grade = {letter}+')
# again = input('Would you like to enter another grade percentage? y/n: ')
# if again != 'y':
# print('OK, Goodbye')
# break
# Version 3
# this is the get lettergrade() function. it's returning the grade letter to pass into gradepercent() function
def lettergrade():
if grade_enter <= 59:
letter = 'F'
return letter
elif grade_enter < 70:
letter = "D"
return letter
elif grade_enter < 80:
letter = 'C'
return letter
elif grade_enter < 90:
letter = 'B'
return letter
elif grade_enter <= 100:
letter = 'A'
return letter
elif grade_enter > 100:
print('Invalid precentage entered')
print('Goodbye')
# This is the gradepercent() function. it has letter passed in from lettergrade()
def gradepercent(letter):
percent = grade_enter % 10
if grade_enter < 60:
print(letter)
elif percent < 5:
print(f'Your grade = {letter}-')
elif percent == 5:
print(f'Your grade = {letter}')
elif percent > 5:
print(f'Your grade = {letter}+')
# this is the loop that asks for grade percentage, returns the letter grade with +- and asks if you would like to enter another.
while True:
grade_enter = int(input('Please enter your grade percentage: '))
letter = lettergrade()
gradepercent(letter)
again = input('Would you like to enter another grade percentage? y/n: ')
if again != 'y':
print('OK, Goodbye')
break
|
a06a3cab846b812f8ad96003b8bfe7a49324b9dc | chenchaojie/leetcode350 | /binary/x的平方根-69.py | 472 | 3.671875 | 4 | class Solution:
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
s, e = 0, x
while s <= e:
mid = (s + e) // 2
if mid ** 2 > x:
e = mid - 1
elif mid ** 2 < x:
if (mid + 1) ** 2 > x:
return mid
s = mid + 1
else:
return mid
if __name__ == "__main__":
print(Solution().mySqrt(10))
|
a5de46349a25f682daba5dd36ff76a2b79a4db78 | sijmenw/schatzoeken | /treasure_map.py | 1,138 | 3.9375 | 4 | # created by Sijmen van der Willik
# 03/02/2018 18:08
import random
class TreasureMap(object):
def __init__(self, width, height, length=10, max_step_size=10):
self.width = width
self.height = height
self.no_instructions = length
self.max_step_size = max_step_size
self.starting_point = self.get_starting_point()
self.map = str(self.starting_point)
self.generate_list()
def generate_list(self):
for i in range(self.no_instructions):
instruction = "\n" + \
random.choice(['x', 'y']) + \
random.choice(['-', '+']) + \
str(random.randint(1, self.max_step_size))
self.map += instruction
def get_starting_point(self):
y = random.randint(0, self.height)
x = random.randint(0, self.width)
return [y, x]
def write_treasure_map(self, path):
with open(path, "w+") as f:
f.write(self.map)
if __name__ == "__main__":
for i in range(1000):
TreasureMap(40, 30).write_treasure_map("treasure_maps/map" + str(i) + ".txt")
|
00dcbd1070459b6ff5a63b3f15e65786dae17667 | RobertMcCutchen/DigitalCrafts_Assignments | /July/July 3rd/Remove_Duplicate_Emails.py | 472 | 3.515625 | 4 | file_name = "Email_List.txt"
duplicate_free_emails = []
with open(file_name) as file_object:
contents = file_object.read()
emails = contents.replace("\n", "").split(', ')
for email in emails:
if email not in duplicate_free_emails:
duplicate_free_emails.append(email)
print(duplicate_free_emails)
string = (', ').join(duplicate_free_emails)
print(string)
with open("duplicate_free_email_list.txt", "w") as file_object2:
file_object2.write(string) |
a051928d9d4616c4028811ae9df5afc4cdc6a32f | ixe013/mongolito | /src/transformations/renameattribute.py | 948 | 3.546875 | 4 | import re
import utils
from transformations import BaseTransformation
class RenameAttribute(BaseTransformation):
'''Takes a key name and renames it, keeping values intact.
Uses Python's re.sub(), so fancy renames with expression
groups can be used.
'''
def __init__(self, attribute, replacement):
'''
>>>renamer = RenameAttribute('(.*)bar', r'blah\1')
:pattern A valid PCRE pattern
:replacement A string (than can refer to the pattern with expression groups)
'''
self.attribute = attribute
self.replacement = replacement
def transform(self, original, ldapobject):
try:
ldapobject[self.replacement] = ldapobject[self.attribute]
del ldapobject[self.attribute]
except KeyError:
#Attribute does not exist in this dict
pass
#Return the new object
return ldapobject
|
cd7e628b59612809eaf829627d2602643c551255 | carpben/fizzbuzz | /fizzbuzz.py | 1,223 | 4.53125 | 5 | import sys
print "Welcome to the Fizzbuzz Game!"
# defining n.
# first option command line argument. command line can have: 0 argument (no n), 1 arguments (n) or more than 1 arguments (mistake/error)
# In case of 1 arguments, the second argument is n. otherwise we will ask user to provide input (n).
#possible problems: argument or input should be an integer in type string. If that is not the case than we have a problem.
# we are instructed to handel error.
# it will arise when we try to convert from type string to type integer.
if len(sys.argv)==2:
n=sys.argv[1]
else: #This will execute if the user provide n, or provided more than 2 arguments.
n=raw_input ("Please enter a number. We will play Fizzbuzz up to the number you choose. ")
while True:
try:
n=int(n)
break
except Exception, e:
n=raw_input ("Please enter a number of type integer. ")
# printing fizzbuzz up to n
print "Fizz buzz counting up to {}".format (n)
for num in range (1,n+1):
if (num%5==0) & (num%3==0):
print("Fizzbuzz")
elif num%5==0:
print("Buzz")
elif num%3==0:
print("Fizz")
else:
print(num)
|
24a029f1f20505e3a2ac7aab520d775c67898103 | sarahlevendoski/Coursera | /assigment 2.py | 2,791 | 4.3125 | 4 | def get_length(dna):
""" (str) -> int
Return the length of the DNA sequence dna.
>>> get_length('ATCGAT')
6
>>> get_length('ATCG')
4
"""
return len(dna)
def is_longer(dna1, dna2):
""" (str, str) -> bool
Return True if and only if DNA sequence dna1 is longer than DNA sequence
dna2.
>>> is_longer('ATCG', 'AT')
True
>>> is_longer('ATCG', 'ATCGGA')
False
"""
return len(dna1) > len(dna2)
def count_nucleotides(dna, nucleotide):
""" (str, str) -> int
Return the number of occurrences of nucleotide in the DNA sequence dna.
>>> count_nucleotides('ATCGGC', 'G')
2
>>> count_nucleotides('ATCTA', 'G')
0
"""
return dna.count(nucleotide)
def contains_sequence(dna1, dna2):
""" (str, str) -> bool
Return True if and only if DNA sequence dna2 occurs in the DNA sequence
dna1.
>>> contains_sequence('ATCGGC', 'GG')
True
>>> contains_sequence('ATCGGC', 'GT')
False
"""
return dna2 in dna1
def is_valid_sequence(dna):
""" (str) -> bool
Return True if and only if the DNA sequence is valid (it contains no characters
other than 'A', 'T', 'C', and 'G'.)
>>> is_valid_sequence('ATCGATCG')
True
>>> is_valid_sequence('ABCDEFGH')
False
>>> is_valid_sequence('ATTGCC')
True
>>> is_valid_sequence('atcg!&')
False
"""
for char in dna:
if char not in 'ACGT':
return False
return True
def insert_sequence(dna1, dna2, index):
""" (str, str, int) -> str
Return the DNA sequence obtained by inserting ht esecond DNA sequence into the
first DNA sequence at the given index. Assume the index is valid.
>>> insert_sequence('CCGG', 'AT', 2)
'CCATGG'
>>> insert_sequence('AT', 'CG', 1)
'ACGT'
>>> insert_sequence('AATCGG', 'CCCG', 0)
'CCCGAATCGG'
"""
return dna1[:index] + dna2 + dna1[index:]
def get_complement(nucleotide):
"""(str) -> str
Return the nucleotide's complement.
>>> get_complement('A')
'T'
>>> get_complement('C')
'G'
"""
if nucleotide is 'A':
return 'T'
if nucleotide is 'T':
return 'A'
if nucleotide is 'C':
return 'G'
if nucleotide is 'G':
return 'C'
def get_complementary_sequence(dna):
"""(str) -> str
Return the DNA sequence that is complementary to the given DNA sequence.
>>> get_complementary_sequence('AT')
'TA'
>>> get_complementary_sequence('ATCGTC')
'TAGCAG'
"""
complementary_sequence = ''
for nucleotide in dna:
complementary_sequence = complementary_sequence + get_complement(nucleotide)
return complementary_sequence
|
7fda9a14b791318477218fb01769e2768a2159f4 | ThiagoLiraRosa/Python_Projects | /AULA 08.py | 316 | 3.875 | 4 | #from math import sqrt
#num=int(input('Digite um Número: '))
#raiz=sqrt(num)
#print('A raiz quadrada de {} é {:.2f}.'.format(num, raiz))
import random
num=random.randint(1, 100)
print('O Número aleatório é: {}'.format(num))
#import emoji
#print(emoji.emojize('Ola Mundo :earth_americas:', use_aliases=True))
|
326195a3b3a25e409bc62a64f6b388a250dd3c46 | UPSD1/Temperature-Conversion-on-Python | /BaseTwotoBaseSixteen David Akinboro.py | 570 | 4.3125 | 4 | # Python Program - Convert Binary to Hexadecimal and Octal
print("This is a program converting BASE 2 to BASE 16");
print("Enter 'x' for exit.");
binary = input("Enter a number in Binary Format (1's AND 0's): ");
if binary == 'x':
exit();
else:
# converting binary to Hexadecimal using the hex built-in function
temp = int(binary, 2);
print(binary,"in Hexadecimal =",hex(temp));
print("Enter 'x' for exit.");
res = input("Enter x to exit the program: ");
if res == 'x':
exit();
else:
print("invalid input enetered.");
|
b850858449ed09d6b118867a3dc4fb215f74a86f | jizefeng0810/Databases_Learning | /MySQL/mysql_basic.py | 966 | 3.609375 | 4 | # 导入pymysql
import pymysql
if __name__=='__main__':
# 连接mysql数据库的服务
connc = pymysql.Connect(user='root',password='***',database='person',charset='utf8')
# 创建游标对象
cur = connc.cursor()
# 编写sql语句
sql = 'select * from info;'
# 使用游标对象去执行sql
cur.execute(sql)
# 获取结果
result = cur.fetchall()
print(result)
try:
# 增加数据 jizefeng 25 男
c_sql = 'insert into info values(%s,%s,%s,%s);'
add_data = [0, 'jizefeng', 25, '男']
cur.execute(c_sql, add_data)
connc.commit() # 提交操作
except Exception as e:
print(e)
connc.rollback() # 数据回滚
finally:
# 查询表
sql = 'select * from info;'
cur.execute(sql)
result = cur.fetchall()
print(result)
# 关闭游标对象
cur.close()
# 关闭连接
connc.close()
|
2a1d994692654fbfb6293db7d9cc12e6816d0bbc | glenonmateus/ppe | /secao20/intro_unittest.py | 1,425 | 4.28125 | 4 | """
Introdução ao módulo Unittest
Unittest -> Testes Unitários
O que são testes unitários?
Teste unitário é a forma de se testar unidades individuais de código fonte.
Unidades individuais podem ser:
- funções, métodos, classes, módulos, etc.
# OBS: Teste unitário não é específico da linguagem Python.
Para criar nossos testes, criamos classes que herdam de unittest.TestCase
e a partir de então ganhamos todos os 'assertions' presentes no módulo.
Para rodar os testes, utilizamos unittest.main()
TestCase -> Casos de teste para sua unidade
# conhecendo as assertions
https://docs.python.org/3/library/unittest.html
Method Checks that
assertEqual(a, b) a == b
assertNotEqual(a, b) a != b
assertTrue(x) bool(x) is True
assertFalse(x) bool(x) is False
assertIs(a, b) a is b
assertIsNot(a, b) a is not b
assertIsNone(x) x is None
assertIsNotNone(x) x is not None
assertIn(a, b) a in b
assertNotIn(a, b) a not in b
assertIsInstance(a, b) isinstance(a, b)
assertNotIsInstance(a, b) not isinstance(a, b)
Por convenção todos os testes em um testecase, devem ter seu nome iniciado com
test_
Para executar os testes com Unittest
# python nome_do_modulo.py
Para executar os testes com unittest no modo verbose
# python nome_do_modulo.py -v
# Docstrings nos testes
Podemos acrescentar (e é recomendado) docstrings nos nossos testes
"""
# Prática - Utilizando a abordagem TDD
|
d81e3b07ff05d5801d18172210504e15282aafcc | aashi0707/matplotlib-module-plot-graph | /bar-plot.py | 287 | 3.765625 | 4 | #!/usr/bin/python3
import matplotlib.pyplot as plt
x=[1,2,9]
y=[3,5,7]
y1=[3,6,8]
x1=[4,8,13]
plt.title("simple")
plt.xlabel("x-axis")
plt.ylabel("y-axis")
plt.bar(x,y,label="water",color='g')
plt.bar(x1,y1,label="soil",color='r')
plt.legend()
plt.grid(color='y')
plt.show()
|
509830792d354d964b557217424b2f4711123dd0 | tylersmithSD/Multipurpose_Calculator-Python | /unitObject.py | 2,187 | 3.984375 | 4 | #Developer: Tyler Smith
#Date: 11.06.16
#Purpose: Unit Converter class where the user can
# enter in amount of feet and it is
# converted to different types of
# measurements used.
class unitConverter(object):
def __init__(self, feet): # Constructor of the class that gets ran when
object.__init__(self) # an object gets instantiated with reference to
self.__setMiles(feet) # this class.
self.__setYards(feet) # Go through all variables
self.__setInches(feet) # setting their values based on
self.__setCentimeters() # what data the user passes through
self.__setMillimeters() # when object is instantiated
self.__setMicrometers()
self.__setKilometers()
def __setMiles(self, feet): # Set Miles value
self.__miles = (feet / 5280)
def getMiles(self): # Get Miles value
return self.__miles
def __setYards(self, feet): # Set Yards value
self.__yards = (feet / 3)
def getYards(self): # Get Yards value
return self.__yards
def __setInches(self, feet): # Set Inches value
self.__inches = (feet * 12)
def getInches(self): # Get Inches value
return self.__inches
def __setCentimeters(self): # Set Centimeters value
self.__centimeters = (self.getInches() * 2.54)
def getCentimeters(self): # Get Centimeters value
return self.__centimeters
def __setMillimeters(self): # Set Millimeters value
self.__millimeters = (self.getCentimeters() * 10)
def getMillimeters(self): # Get Millimeters value
return self.__millimeters
def __setMicrometers(self): # Set Micrometers value
self.__micrometers = (self.getMillimeters() * 1000)
def getMicrometers(self): # Get Micrometers value
return self.__micrometers
def __setKilometers(self): # Set Kilometers value
self.__kilometers = (self.getCentimeters() / 100000)
def getKilometers(self): # Get Kilometers value
return self.__kilometers
|
e25569ee58806eac2980f5c2263a63e407dc97f7 | ccsreenidhin/100_Python_Problems | /Learning_Python_100_problems/python32.py | 668 | 3.90625 | 4 | ###############################################################################################################
###################################################SREENIDHIN C C##############################################
###############################################################################################################
"""
2.10
Question:
Define a function that can accept an integer number as input and print the "It is an even number" if the number is even, otherwise print "It is an odd number".
"""
def evenorodd(n):
if n%2==0:
print "It is an even number"
else:
print "It is an odd number"
evenorodd(4)
|
f019a020f145b61da9f45df3dbae1130654baf91 | darya-ver/ERSP201819 | /additionalFiles/getLists.py | 1,034 | 3.5625 | 4 | def main():
fp = open('pythonLists.txt')
minsT = []
onesT = []
twosT = []
threesT = []
maxsT = []
minsB = []
onesB = []
twosB = []
threesB = []
maxsB = []
for i, line in enumerate(fp.readlines() ):
# do something here
#print( i )
#print( line )
split = line.split( ',', -1)
split = split[:-1]
if( i != 0 ):
for str in range(0, len(split) ):
split[i] = float(split[i])
if( i == 1 ):
minsT = split
elif( i == 2 ):
onesT = split
elif( i == 3 ):
twosT = split
elif( i == 4 ):
threesT = split
elif( i == 5 ):
maxsT = split
elif( i == 6 ):
minsB = split
elif( i == 7 ):
onesB = split
elif( i == 8 ):
twosB = split
elif( i == 9 ):
threesB = split
elif( i == 10 ):
maxsB = split
print(minsT)
print(onesT)
print(twosT)
print(threesT)
print(maxsT)
print(minsB)
print(onesB)
print(twosB)
print(threesB)
print(maxsB)
if __name__ == '__main__':
main()
|
a79498a88843e8ba49b5c8068ae9855205ebd28e | dixoncox/6.00.1x | /Old/ps7/TEST.RectangularRoom.py | 5,892 | 4.21875 | 4 |
import math
import random
class Position(object):
"""
A Position represents a location in a two-dimensional room.
"""
def __init__(self, x, y):
"""
Initializes a position with coordinates (x, y).
"""
self.x = x
self.y = y
def getX(self):
return self.x
def getY(self):
return self.y
def getNewPosition(self, angle, speed):
"""
Computes and returns the new Position after a single clock-tick has
passed, with this object as the current position, and with the
specified angle and speed.
Does NOT test whether the returned position fits inside the room.
angle: number representing angle in degrees, 0 <= angle < 360
speed: positive float representing speed
Returns: a Position object representing the new position.
"""
old_x, old_y = self.getX(), self.getY()
angle = float(angle)
# Compute the change in position
delta_y = speed * math.cos(math.radians(angle))
delta_x = speed * math.sin(math.radians(angle))
# Add that to the existing position
new_x = old_x + delta_x
new_y = old_y + delta_y
return Position(new_x, new_y)
def __str__(self):
return "(%0.2f, %0.2f)" % (self.x, self.y)
#return (self.x, self.y)
class RectangularRoomTest(object):
def __init__(self, width, height):
self.width = width
self.height = height
self.roomStatus = {} #Without the "self." prefix these wouldn't work. Without it, it was just a local variable, with it it's an attribute?
self.coords = () #Same as above
for i in range(width):
for j in range(height):
self.coords = (i,j)
self.roomStatus[self.coords] = 'Dirty'
#print roomStatus
def getNumTiles(self):
#NumTiles = self.width * self.height #so when DO I use "self"?
#return NumTiles
#This also works. So when do I use 'self' and not use it?
self.NumTiles = self.width * self.height #so when DO I use "self"? Maybe because using "self." makes in an attribute, otherwise it's just a local variable?
return self.NumTiles
def getRandomPosition(self):
"""
Return a random position inside the room.
returns: a Position object.
"""
random_x = random.randint(0,self.width)
random_y = random.randint(0,self.height)
return Position(random_x, random_y)
#raise NotImplementedError
def isPositionInRoom(self, pos):
"""
Return True if pos is inside the room.
pos: a Position object.
returns: True if pos is in the room, False otherwise.
"""
return (pos.getX() <= self.width) and (pos.getY() <= self.height) #This was giving me problems for the longest time because I didn't include the parens() in pos.getX() & pos.getY().
#Since they are methods that require arguments, they needs parens. self.width and self.height don't since they're attributes.
#This is a RectangularRoom object using a Position object as an argument.
def cleanTileAtPosition(self, pos):
"""
Mark the tile under the position POS as cleaned.
Assumes that POS represents a valid position inside this room.
pos: a Position
"""
#roomStatus = {}
#coords = ()
#for i in range(self.width):
#for j in range(self.height):
#coords = (i,j)
#roomStatus[coords] = 'False'
tileX = int(math.floor(pos.getX()))
tileY = int(math.floor(pos.getY()))
tile = (tileX, tileY)
#print tile
self.roomStatus[tile] = 'Clean'
#print self.roomStatus
#print self.roomStatus[(3,4)]
#print type(self.roomStatus[(0,0)])
#return
#raise NotImplementedError
def isTileCleaned(self, m, n):
"""
Return True if the tile (m, n) has been cleaned.
Assumes that (m, n) represents a valid tile inside the room.
m: an integer
n: an integer
returns: True if (m, n) is cleaned, False otherwise
"""
return self.roomStatus[(m,n)] == 'Clean'
raise NotImplementedError
def getNumCleanedTiles(self):
"""
Return the total number of clean tiles in the room.
returns: an integer
"""
cleanCount = 0
for i in self.roomStatus:
#print self.roomStatus[i]
if self.roomStatus[i] == 'Clean':
cleanCount += 1
return cleanCount
raise NotImplementedError
room = RectangularRoomTest(4,6) #instantiates an *OBJECT* of the RectangularRoomTest *CLASS*, and initializes it with (5,10) dimensions
print 'Dimensions of room: ',room.width, room.height #there are no getX & getY methods, so have to access directly, also since they're attributes no ()'s
print 'Random position in room =',room.getRandomPosition() #doesn't really make sense since it has no dependency on current room object. But hey, it's part of the class.
print 'Room Tiles =',room.getNumTiles() #straightforward, empty parentheses since room is explicity stated
testPosition = Position(3.5,4.5) #instantiating an *OBJECT* of the Position *CLASS* with arguments (3,4)
print 'Test Position =', testPosition.__str__() #testPosition object calling __str__ method
print 'Is Test Position in room?:',room.isPositionInRoom(testPosition)
#print room.cleanTileAtPosition(3.5, 4.5) <-- This didn't work because (3.5, 4.5) isn't a Position object, you just put numbers in there.
print room.cleanTileAtPosition(testPosition)
print 'Is Test Position tile clean?',room.isTileCleaned(3,4)
print 'Number of clean tiles:',room.getNumCleanedTiles()
|
320f2feba29602afc508e5aaf74a852f63858add | gaj995/Random | /momoization/can_construct.py | 795 | 3.71875 | 4 | def can_construct(target, array, memo={}):
if target in memo:
return memo[target]
elif target == '':
return True
for word in array:
if target[:len(word)] == word:
suffix = target[len(word):]
if can_construct(suffix, array, memo) == True:
memo[target] = True
return memo[target]
memo[target] = False
return memo[target]
print (can_construct('abcdef', ['ab', 'abc', 'cd', 'def', 'abcd']))
print (can_construct('skateboard', ['bo', 'rd', 'ate', 't', 'ska', 'sk', 'boar']))
print (can_construct('enterapotentpot', ['a', 'p', 'ent', 'enter', 'ot', 'o', 't']))
print (can_construct('eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeg', ['e', 'ee', 'eeee', 'eeeeeeee', 'eeee', 'eeee', 'asdasd']))
|
3631ba69951dca1f801724c33dfda70921d6f1f7 | Mdmorshadurrahman/Python_Programming | /try_your_luck.py | 1,932 | 4.09375 | 4 | import random
colorDict = {
1: "Red" ,
2: "Black" ,
3: "White" ,
4: "Blue" ,
5: "Green"
}
print('\n\t***Welcome to Our game of Luck by Chance:***\n\n\n ||-> (Rules: Choose your color and check if it match with your luck or not)')
print("\n 1: TEST your luck\t\t\t\t2: Exit\n\n")
j = int(input('\t\t\tENTER YOUR OPTION:'))
e = 1
if j == 1:
print("\n\t\t\t|| Here You Go ||")
a = input('\n\nEnter Your name: ')
while e < 2:
print('\n\t\tHello ~',a,'~ Choose your color from Below list:\n\nRed : 1 Black : 2\tWhite : 3\tBlue :4 Green : 5\n')
b = int (input('Enter Your Input for choosing color: '))
print('\n',a,' You choose the color : ',colorDict.get(b))
print('\n\n\t\t Now wait for computer to pick a color if that match with your one or not......\n\n\t\t')
d = input('\n\t\t\tNow Press Enter to check what computer picked for you??\n\n')
c = random.choice(list(colorDict.keys()))
print('THE COMPUTER BABA has picked the color ',list(colorDict.values())[c-1])
if b == c:
print('\n\n\n\t\t\t*** HURRAY, It Matched.. ~',a,'~ you are Lucky ***\n\n')
print('\t\t 1: Play Again\t\t\t 2: Exit\n\n')
e = int (input('Enter Your Input: '))
if e ==2:
print("\n\n\t\t|| GoodBye ",a," ||\n\n")
#if e == 1:
#continue
else:
print('\n\n\n\t\t\t !!! SORRY, It is not matched.. ~',a,'~ better Luck Next Time Buddy !!!\n\n')
print('\t\t 1: Play Again\t\t\t 2: Exit\n\n')
e = int (input('Enter Your Input: '))
if e ==2:
print("\n\n\t\t|| GoodBye ",a," ||\n\n")
#if e ==2:
#break
elif j == 2:
print("\n\n\t\t|| GoodBye Stranger ||\n\n")
else:
print('\n\n\t\t Either type correctly or try not to play when you are high & Horny ;)\n\n')
|
9a4d54c568c8570d638b20aca55ae43c4d3474b1 | frclasso/CodeGurus_Python_mod2_turma1 | /Cap02_Classes/script4-special-methods.py | 2,235 | 3.984375 | 4 | #!/usr/bin/env python3
# special methods
class Empregados:
num_emps = 0
aumento = 1.04
def __init__(self, nome, sobrenome, salario, empresa): # construtor
self.nome = nome
self.sobrenome = sobrenome
self.salario = salario
self.empresa = empresa
self.email_pro = nome.lower() + '.' + sobrenome.lower() + '@' + empresa + '.com.br'
Empregados.num_emps += 1
@property
def email(self):
nome = self.nome.lower()
sobrenome = self.sobrenome.lower()
empresa = self.empresa.lower()
return '{}.{}@{}.com.br'.format(nome, sobrenome, empresa)
@property
def nome_completo(self):
return '{} {}'.format(self.nome, self.sobrenome)
@nome_completo.setter
def nome_completo(self, nome):
nome, sobrenome = nome.split()
self.nome = nome
self.sobrenome = sobrenome
@nome_completo.deleter
def nome_completo(self):
print('Deletando nomes')
self.nome = None
self.sobrenome = None
def aumento_salario(self):
self.salario = int(self.salario * Empregados.aumento)
@classmethod
def set_novo_aum(cls, aumento):
cls.aumento = aumento
def __repr__(self):
"""Representacao - saida"""
return "Empregado(Nome:{} {}, email:{}, R$ {}, empresa:{})".format(self.nome,
self.sobrenome,
self.email,
self.salario,
self.empresa)
def __str__(self):
return '{} {}'.format(self.nome_completo(), self.email_pro)
emp1 = Empregados('Fabio','Classo', 5000, 'CodeGurus')
# print(emp1.__repr__())
# print(emp1)
# print()
# print(repr(emp1))
# print(str(emp1))
print()
emp2 = Empregados('Peter', 'Parker', 2000, 'PlanetDaily')
# print(str(emp2))
# print(emp2.__str__())
#
# emp1.nome = 'Roger'
# print(emp1.nome_completo())
emp1.nome = 'Jose'
emp1.sobrenome = 'Wagner'
print(emp1.nome)
print(emp1.sobrenome)
print(emp1.email)
print(emp1.nome_completo)
emp1.nome_completo = 'Fabio Classo'
print(emp1.nome)
print(emp1.sobrenome)
|
95ab62e93f9257945f059e4a66ddc96846e26d8c | dhineshns/reinvent_the_wheel | /algorithms/arrays.py | 164 | 3.859375 | 4 | list_apples = ["malgudi", "kansas", "kashmir"];
i = 0;
while (i<len(list_apples)):
print (list_apples[i]);
i=i+1;
for item in list_apples:
print (item); |
39c295ad23fa6398a5de3e952fe285d30c59f834 | j18r1L/Algorithms_analysys | /lab_01/main.py | 2,784 | 3.71875 | 4 | import time
import tests
import PIL
def main():
word1 = enter()
word2 = enter()
if len(word1) < len(word2):
word1, word2 = word2, word1
print()
result_mtr = levenshtein(word1, word2)
print('result levenshtein: ', result_mtr, '\n')
mtr = demerau_levenshtein(word1, word2)
print('demerau_levenshtein: ', mtr, '\n')
start = time.time()
result_rec = recursion(word1, word2)
end = time.time()
print('time recurs: ', end - start)
print('recurs: ', result_rec, '\n')
tests.test()
def enter():
symbol = str(input('Enter word: '))
while (len(symbol) == 0):
print('Entered word empty!')
symbol = str(input('Enter word: '))
symbol = '1' + symbol
return symbol
def levenshtein(word1, word2):
array = [i for i in range(len(word1))]
result_array = [1]
print(array)
start = time.time()
for i in range(1, len(word2)):
for j in range(1, len(word1)):
if (word2[i] == word1[j]):
result = min(array[j - 1], array[j] + 1, result_array[j - 1] + 1)
else:
result = min(array[j - 1] + 1, array[j] + 1, result_array[j - 1] + 1)
result_array.append(result)
array = result_array
print(result_array)
result = result_array[-1]
result_array = [i + 1]
end = time.time()
print('time matrix: ', end - start)
return result
def demerau_levenshtein(word1, word2):
l1, l2 = len(word1), len(word2)
mtr = [[0 for x in range(l2)] for y in range(l1)]
for i in range(l1):
for j in range(l2):
mtr[0][j] = j
mtr[i][0] = i
start = time.time()
for i in range(1, l1):
for j in range(1, l2):
if (i > 1) and (j > 1) and (word1[i] == word2[j - 1]) and (word1[i - 1] == word2[j]) and (word1[i] == word2[j]):
mtr[i][j] = min(mtr[i - 1][j] + 1, mtr[i][j - 1] + 1, mtr[i - 1][j - 1], mtr[i - 2][j - 2] + 1)
elif (i > 1) and (j > 1) and (word1[i] == word2[j - 1]) and (word1[i - 1] == word2[j]) and (word1[i] != word2[j]):
mtr[i][j] = min(mtr[i - 1][j] + 1, mtr[i][j - 1] + 1, mtr[i - 1][j - 1] + 1, mtr[i - 2][j - 2] + 1)
elif word1[i] == word2[j]:
mtr[i][j] = min(mtr[i - 1][j] + 1, mtr[i][j - 1] + 1, mtr[i - 1][j - 1])
elif word1[i] != word2[j]:
mtr[i][j] = min(mtr[i - 1][j] + 1, mtr[i][j - 1] + 1, mtr[i - 1][j - 1] + 1)
end = time.time()
for i in range(l1):
for j in range(l2):
print(mtr[i][j], end=' ')
print()
print('time demerau_lev: ', end - start)
return mtr[i][j]
def recursion(word1, word2):
l1 = len(word1)
l2 = len(word2)
if l1 == 0 or l2 == 0:
return max(l1,l2)
if word1[-1] == word2[-1]:
result = min([recursion(word1[:-1], word2) + 1, recursion(word1, word2[:-1]) + 1, recursion(word1[:-1], word2[:-1])])
else:
result = min([recursion(word1[:-1], word2) + 1, recursion(word1, word2[:-1]) + 1, recursion(word1[:-1], word2[:-1]) + 1])
return result
if __name__ == '__main__':
main()
|
edfc9ea820f0ef77924fcf58fbcda1f721e7c5c0 | nmoore32/coursera-fundamentals-of-computing-work | /1 An Introduction to Interactive Programming in Python/Week 1/1 Functions/exercise-9.py | 163 | 3.890625 | 4 | def name_and_age(name, age):
'''Returns a string giving someone's name and age'''
return f"{name} is {age} years old."
print(name_and_age('Joe Warren', 52))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.