blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
7a672ece6c9328dc9a942d152d6c0073f47be8bf | karensiglaa/aprendoPython2 | /compara.py | 524 | 4.0625 | 4 | numero1=input("numero 1:")
numero2=input("numero 2:")
salida="numeros proporcionados {} y {}. {}."
#solo si los números capturados entran
if (numero1==numero2):
print(salida.format(numero1, numero2, "los numeros son iguales"))
#si los numeros no son iguales
else:
if numero1>numero2:
#cual numero es mayor
print(salida.format(numero1,numero2, "El mayor es el primero"))
else:
#o si el mayor es el segundo
print(salida.format(numero1,numero2, "el mayor es el segundo")) |
bb9d69ac509e2b672033de4f887872c044b804c6 | esosn/euler | /17.py | 923 | 3.546875 | 4 | import time
import math
times = []
times.append(time.clock())
limit = 1000
words = {0:'', 1:'one', 2:'two', 3:'three', 4:'four', 5:'five', 6:'six', \
7:'seven', 8:'eight', 9:'nine', 10:'ten', 11:'eleven', 12:'twelve', 13:'thirteen', \
14:'fourteen', 15:'fifteen', 16:'sixteen', 17:'seventeen', 18:'eighteen', \
19:'nineteen', 20:'twenty', 30:'thirty', 40:'forty', 50:'fifty', 60:'sixty', \
70:'seventy', 80:'eighty', 90:'ninety', 100:'hundred', 1000:'onethousand'}
total = 0
for i in range(1,limit):
if i >= 100:
total += len(words[i // 100])
total += len(words[100])
if i % 100 != 0:
total += 3 # hundred 'and'
i = i % 100
if i <= 20:
total += len(words[i])
else:
total += len(words[(i // 10) * 10])
i = i % 10
total += len(words[i])
total += len(words[limit])
print(total)
times.append(time.clock())
print(times[-1] - times[-2])
|
87516cec830b15e45e878b3b5a90fedfd270afc2 | ronicson/ronicson | /ex010.py | 113 | 3.65625 | 4 | s = float(input('Digite a seu capital em espécie:'))
print('Você pode comprar {:.2f} dólares'.format(s/5.12))
|
8cc48ac3e60be5a441ee72dc4f12f51b245af440 | AvanthaDS/PyLearn_v_1_0 | /Math.py | 648 | 3.625 | 4 | __author__ = 'Avantha'
import math
sqr = math.sqrt
print(sqr(4))
value = input('Please enter the Vale:')
diff = abs(17-int(value))
if int(value)>17:
diff2 =diff*2
print('Since the value >17 the new difference is : %i'%diff2)
else:
print('The difference between the entered value and 17 is: %i'%diff)
def near_thousand(n):
return ((abs(1000 - n) <= 100) or (abs(2000 - n) <= 100))
print(near_thousand(1000))
print(near_thousand(900))
print(near_thousand(800))
print(near_thousand(2200))
a,b,c=input('PLease enter the three number')
if int(a)==int(b)==int(c):
print(int(a)*3)
else:
print(a)
print(b)
print(c)
|
c9f25469c99aa924670879835462ef321d44b1a2 | ajhurst95/personal_archive | /Pydoodles/automatetheboringstuff/commacode.py | 532 | 4.21875 | 4 | ## combines a list into a string of the form
## item1, item2, and item3
## Args:
## items (list): List of strings
##
## Returns:
## string: list items combined into string
def stringit(items):
item_len = len(items)
if item_len == 0:
return ''
elif item_len == 1:
return items[0]
else:
comma = ', '
string = comma.join(items[:-1]) + ', and ' + items[-1]
return string
thestuff = ['bing', 'bong', 'boing', 'bingbong']
print(stringit(thestuff))
|
ebecb2e8a3aa4639684017300f155048d80683ae | lovehoneyginger/LearnPython | /quadratic equation.py | 310 | 3.953125 | 4 | import cmath
print("Enter the a, b, c in the equation ax^2 + bx + c = 0")
a = float(input('Enter a: '))
b = float(input('Enter b: '))
c = float(input('Enter c: '))
print("solution x1 : " + str(((-b) + cmath.sqrt(b**2 - 4*a*c))/(2*a)))
print("solution x2 : " + str(((-b) - cmath.sqrt((b**2) - (4*a*c)))/(2*a)))
|
c6eadd54edbfc7013c701bec2b47359783a92c2b | Anshum4512501/dsa | /trees/bt/btest.py | 443 | 3.609375 | 4 | # class Node:
# def __init__(self,val):
# self.data = val
# self.left = None
# self.right = None
# class Solution:
# def height(self, root):
# if root is None:
# return 0
# return max(self.height(root.left),self.height(root.right))+1
# root = Node(1)
# root.left = Node(2)
# root.left.left = Node(3)
# solution = Solution()
# h = solution.height(root)
# print(h)
|
0a6d483d73e577db03418619f1e2d0f1c9780a5f | hakami1024/femicide | /check_dup.py | 742 | 3.515625 | 4 | # -*- coding: utf-8 -*-
import config
import pandas as pd
def check_existance(target: str) -> bool:
print(F'Searching for {target}')
for f_name in config.SOURCES:
df = pd.read_csv(f_name)
raw_urls = df['ссылки и дополнения'].tolist()
for url_str in raw_urls:
if type(url_str) is float:
continue
if target in url_str:
print(F'It is already in the file {f_name}: ')
print(df[df['ссылки и дополнения' == url_str]])
return True
return False
if __name__ == '__main__':
target = input('Print the link:\n').strip().replace('https://', '').replace('www', '').replace('http://', '')
|
c573db3750ea74fc94fe4fbe35bd94820cc05bcf | jsqihui/lintcode | /Valid_Sudoku.py | 1,288 | 3.578125 | 4 | class Solution:
# @param board, a 9x9 2D array
# @return a boolean
def isValidSudoku(self, board):
ret = True
for i in [0, 3, 6]:
for j in [0, 3, 6]:
ret = ret and self.validCell(board, i, j)
return ret and self.validRow(board) and self.validCol(board)
def validRow(self, board):
for i in range(9):
nums = set()
for j in range(9):
if board[i][j] != '.' and board[i][j] in nums:
return False
else:
nums.add(board[i][j])
return True
def validCol(self, board):
for i in range(9):
nums = set()
for j in range(9):
if board[j][i] != '.' and board[j][i] in nums:
return False
else:
nums.add(board[j][i])
return True
def validCell(self, board, row_start, col_start):
nums = set()
for i in range(row_start, row_start + 3):
for j in range(col_start, col_start + 3):
if board[i][j] != '.' and board[i][j] in nums:
return False
else:
nums.add(board[i][j])
return True
|
79a49b7768beb82f75b6cb77abf74f9cd50be6ed | qmnguyenw/python_py4e | /geeksforgeeks/python/basic/16_12.py | 3,479 | 4.25 | 4 | Python program to swap two elements in a list
Given a list in Python and provided the positions of the elements, write a
program to swap the two elements in the list.
**Examples:**
**Input :** List = [23, 65, 19, 90], pos1 = 1, pos2 = 3
**Output :** [19, 65, 23, 90]
**Input :** List = [1, 2, 3, 4, 5], pos1 = 2, pos2 = 5
**Output :** [1, 5, 3, 4, 2]
**Approach #1:** Simple swap
Since the positions of the elements are known, we can simply swap the
positions of the elements.
__
__
__
__
__
__
__
# Python3 program to swap elements
# at given positions
# Swap function
def swapPositions(list, pos1, pos2):
list[pos1], list[pos2] = list[pos2], list[pos1]
return list
# Driver function
List = [23, 65, 19, 90]
pos1, pos2 = 1, 3
print(swapPositions(List, pos1-1, pos2-1))
---
__
__
**Output:**
[19, 65, 23, 90]
**Approach #2 :** Using Inbuilt list.pop() function
Pop the element at _pos1_ and store it in a variable. Similarly, pop the
element at _pos2_ and store it in another variable. Now insert the two popped
element at each other’s original position.
__
__
__
__
__
__
__
# Python3 program to swap elements
# at given positions
# Swap function
def swapPositions(list, pos1, pos2):
# popping both the elements from list
first_ele = list.pop(pos1)
second_ele = list.pop(pos2-1)
# inserting in each others positions
list.insert(pos1, second_ele)
list.insert(pos2, first_ele)
return list
# Driver function
List = [23, 65, 19, 90]
pos1, pos2 = 1, 3
print(swapPositions(List, pos1-1, pos2-1))
---
__
__
**Output:**
[19, 65, 23, 90]
**Approach #3 :** Using tuple variable
Store the element at _pos1_ and _pos2_ as a pair in a tuple variable, say
_get_. Unpack those elements with _pos2_ and _pos1_ positions in that list.
Now, both the positions in that list are swapped.
__
__
__
__
__
__
__
# Python3 program to swap elements at
# given positions
# Swap function
def swapPositions(list, pos1, pos2):
# Storing the two elements
# as a pair in a tuple variable get
get = list[pos1], list[pos2]
# unpacking those elements
list[pos2], list[pos1] = get
return list
# Driver Code
List = [23, 65, 19, 90]
pos1, pos2 = 1, 3
print(swapPositions(List, pos1-1, pos2-1))
---
__
__
**Output:**
[19, 65, 23, 90]
**Approach #4 :** Using comma assignment
__
__
__
__
__
__
__
# Python3 program to swap elements
# at given positions
def swapPositions(list, pos1, pos2):
list[pos1],list[pos2] = list[pos2],list[pos1]
return list
# Driver Code
List = [23, 65, 19, 90]
pos1, pos2 = 1, 3
print(swapPositions(List, pos1-1, pos2-1))
---
__
__
**Output:**
[19, 65, 23, 90]
Attention geek! Strengthen your foundations with the **Python Programming
Foundation** Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures
concepts with the **Python DS** Course.
My Personal Notes _arrow_drop_up_
Save
|
4502a3bc184dd772a1c65ae2cbc2ff61783db9b4 | gopupanavila/ABCnDofAI | /lesson3/pd_exercise.py | 1,762 | 3.96875 | 4 | import pandas as pd
# Pandas dataframe exercises
# simple dataframe
# data = {
# 'apples': [3, 2, 0, 1],
# 'oranges': [0, 3, 7, 2]
# }
# purchases = pd.DataFrame(data)
# print(purchases)
# load data from csv file
# df = pd.read_csv('appliances_rating.csv') #, index_col=0)
# print(df)
# print(df.loc[2])
# print(df.set_index('no'))
# convert to csv
# data = {
# 'apples': [3, 2, 0, 1],
# 'oranges': [0, 3, 7, 2]
# }
# df = pd.DataFrame(data)
# df.to_csv('purchases.csv')
# viewing data
# df = pd.read_csv('appliances_rating.csv') #, index_col=0)
# print(df.head()) # optional number
# print(df.tail())
# print(df.columns)
# rename columns
# df.rename(columns={
# 'no': 'unique_id'
# }, inplace=True)
# print(df.columns)
# df.columns = [col.upper() for col in df]
# print(df.columns)
# info and shape of dataframe
# df = pd.read_csv('appliances_rating.csv')
# df.info()
# print(df.shape)
# remove duplicates
# df = df.append(df)
# print(df.shape)
# df.drop_duplicates(inplace=True, keep='first') # first, last, False
# print(df.shape)
# missing with values
# df = pd.read_csv('appliances_rating.csv')
# print(df.isnull())
# print(df.isnull().sum())
# df.dropna() # NaN
# df.dropna(axis=1)
# rating = df['rating']
# rm = rating.mean()
# rating.fillna(rm, inplace=True) # imputation
# print(type(rating))
# print(type(df[['no', 'rating']]))
# index slicing filter
# df = pd.read_csv('appliances_rating.csv')
# print(df.loc[0])
# print(df.iloc[1:7])
# df_new = df[(df.rating == 4) & (df.appliance_type == 'home')]
# print(df_new.count())
# def rating_function(x):
# if x > 3:
# return "good"
# else:
# return "bad"
#
# df["rating_category"] = df["rating"].apply(rating_function)
# print(df.head(2))
|
998f2cb573f1742119fb3222a224c7a2d6e5e4f8 | q1003722295/WeonLeetcode | /_32-LongestValidParentheses/LongestValidParentheses3.py | 1,335 | 3.75 | 4 | '''
给定一个只包含 '(' 和 ')' 的字符串,找出最长的包含有效括号的子串的长度。
示例 1:
输入: "(()"
输出: 2
解释: 最长有效括号子串为 "()"
示例 2:
输入: ")()())"
输出: 4
解释: 最长有效括号子串为 "()()"
'''
'''
见题解2、3.png
'''
# 栈+排序
class Solution1:
def longestValidParentheses(self, s):
res=[]
stack=[]
for i in range(len(s)):
if(stack and s[i]==")"):
res.append(stack.pop())
res.append(i)
if(s[i]=="("):
stack.append(i)
#print(res)
res.sort()
max_len=0
i=0
while(i<len(res)-1):
tmp=i
while(i<len(res)-1 and res[i+1]-res[i]==1):
i+=1
max_len=max(max_len,i-tmp+1)
i+=1
return max_len
# 栈 优化(不排序)
class Solution2:
def longestValidParentheses(self, s):
if(not s):
return 0
stack=[-1]
res=0
for i in range(len(s)):
if(s[i]=="("):
stack.append(i)
else:
stack.pop()
if(not stack):
stack.append(i)
else:
res=max(res,i-stack[-1])
return res
|
ec387c8991940d82edec4b8979c03086aea3d299 | KarlPearson15/Chapter_5 | /Chapter5-2.py | 2,054 | 4.0625 | 4 | #Chapter5-2.py
#Karl Pearson
#11/11/14
party=[]
person=()
strength=0
health=0
wisdom=0
dexterity=0
add=input('Would you like to add a party member? Y/N: ')
while not add == "Y" and "N":
print('You may only choose [Y]es or [N]o')
add=input('Would you like to add a party member? Y/N: ')
while add == "Y":
name=input('What is your name? ')
characterStats=0
print('Customize your stats')
while characterStats!=30:
print('Choose a value for each stat(You may only have 30 points total)')
strength=int(input('Strength stat: '))
health=int(input('Health stat: '))
wisdom=int(input('Wisdom stat: '))
dexterity=int(input('Dexterity sta: '))
characterStats=strength+health+wisdom+dexterity
if characterStats>30:
print('You have too many points, try again')
strength=int(input('Strength stat: '))
health=int(input('Health stat: '))
wisdom=int(input('Wisdom stat: '))
dexterity=int(input('Dexterity stat: '))
elif characterStats<30:
print("You don't have enough points, try again")
strength=int(input('Strength stat: '))
health=int(input('Health stat: '))
wisdom=int(input('Wisdom stat: '))
dexterity=int(input('Dexterity stat: '))
elif characterStats==30:
print('You have completed character setup')
print('Your stats are: ')
print('Strength: '+str(strength))
print('Health: '+str(health))
print('Wisdom: '+str(wisdom))
print('Dexterity: '+str(dexterity))
sure=input('Is this okay? Y/N:')
if sure=="Y":
person=(name+','+str(strength)+','+str(health)+','+str(wisdom)+','+str(dexterity))
party.append(person)
print(party)
add=input('Would you like to add a party member? Y/N: ')
elif sure=="N":
characterStats=0
print('Reassign points')
if add == "N":
print(party)
input('\n\n Press enter to exit')
|
6b7c0b12bae7353f189152b8ec527efb1f53dbf9 | GHMan2021/python-project-lvl1 | /brain_games/games/games_prime.py | 723 | 3.9375 | 4 | from random import randint
from ..check_answer import f_check_answer
def is_prime():
print('Answer "yes" if given number is prime. Otherwise answer "no".')
counter = 1
result = True
while result is True and counter <= 3:
number = randint(0, 500)
print('Question:', number)
right_answer = 'yes' if f_is_prime(number) else 'no'
user_answer = input('Your answer: ')
if f_check_answer(right_answer, user_answer):
counter += 1
else:
return False
return True
def f_is_prime(number):
if number % 2 == 0:
return number == 2
d = 3
while d * d <= number and number % d != 0:
d += 2
return d * d > number
|
d61dd616dc32c188c10e115b81d37a37786f4781 | susmitpy/Interview_Practice | /bal_brackets.py | 510 | 3.65625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 29 09:03:07 2019
@author: susmitvengurlekar
"""
from collections import deque
def isBalanced(s):
stack = deque()
opening = ["(", "[", "{"]
closing = [")", "]", "}"]
for i in s:
if i in opening:
stack.append(i)
else:
if len(stack) == 0:
return "NO"
if not opening.index(stack.pop()) == closing.index(i):
return "NO"
return "YES"
|
6eedd857d44549f59f21102f0b645d3d00cad0bf | Viveckh/Duell_Py | /Game.py | 12,041 | 3.90625 | 4 |
# coding: utf-8
# Game Class
# Implements the necessary details to run a game like conducting initial toss, getting user input for moves, displaying updated game board and turn notifications.
#
""" ************************************************************
* Name: Vivek Pandey *
* Project: Duell Python *
* Class: CMPS 366 *
* Date: 12/10/2016 *
************************************************************ """
from msvcrt import getche
from random import randint
from Board import Board
from BoardView import BoardView
from Computer import Computer
from Human import Human
from Notifications import Notifications
class Game:
#Default Constructor
def __init__(self):
#GameBoard, display and notification objects
self.board = Board()
self.boardView = BoardView()
self.notifications = Notifications()
#Player objects
self.human = Human()
self.computer = Computer()
#Toss Variables
self.humanDieToss = 0
self.computerDieToss = 0
#Control variables
self.humanTurn = False
self.computerTurn = False
#Variables to store user input of coordinates
self.startRow = 0
self.startCol = 0
self.endRow = 0
self.endCol = 0
#1 for vertical first, 2 for lateral first
self.path = 0
""" *********************************************************************
Function Name: implement_game
Purpose: Runs a full game until someone wins or user requests serialization
Parameters:
restoringGame, boolean value stating whether a restore of previous game was requested by user
nextPlayer, a string that contains who's turn is next (if restoring) (Computer or Human)
Return Value: 'c' if bot wins, 'h' if human wins, 'S' if serialization requested during bot turn, 's' if serialization requested during human turn
Local Variables: none
Assistance Received: none
********************************************************************* """
#Implements a Round.
#Return value is 'h' for human winner, 'c' for computer winner, 'S' for serializing during computer's turn, 's' for serializing during human's turn
def implement_game(self, restoringGame, nextPlayer=""):
#Set the turns if restoring a game from saved state
if restoringGame:
if (nextPlayer == "Computer"):
self.computerTurn = True
if (nextPlayer == "Human"):
self.humanTurn = True
#Draw Initial Board
self.boardView.draw_board(self.board)
#Conduct a toss if the controls haven't been assigned while restoring
if (not self.humanTurn and not self.computerTurn):
self.toss_to_begin()
#Continue the loop until one of the king is captured, one of the key squares gets occupied or user chooses to serialize and quit
while True:
refresh = False
#If it is computer's turn
if self.computerTurn:
self.notifications.msg_turns("COMPUTER'S TURN")
if (self.computer.play(self.board, False)):
#Transfer Controls
self.computerTurn = False
self.humanTurn = True
self.notifications.msg_turns("BOARD AFTER COMPUTER'S MOVE")
refresh = True #Using this boolean to prevent human's loop from running immediately
else:
continue
#If it is human's Turn
if not refresh:
if self.humanTurn:
self.notifications.msg_turns("YOUR TURN")
if self.turn_help_mode_on():
self.notifications.msg_helpmode_on()
#Calling computer Play in Help Mode
self.computer.play(self.board, True)
self.get_user_input()
if (self.human.play(self.startRow, self.startCol, self.endRow, self.endCol, self.board, self.path)):
self.humanTurn = False
self.computerTurn = True #Transferring controls
self.notifications.msg_turns("BOARD AFTER HUMAN'S MOVE")
else:
self.notifications.msg_invalid_move()
continue
#After the move is made
#Re-draw the board after each move
self.boardView.draw_board(self.board)
#If game over condition met
if(self.game_over_condition_met()):
#Whoever just received the control is the one who lost
if self.humanTurn:
self.notifications.msg_game_over("COMPUTER")
return 'c' #Bot Winner
else:
self.notifications.msg_game_over("HUMAN")
return 'h' #Human Winner
"""Stop the game and return if user wants to serialize
return 'S' if serializing during computer's turn, 's' if serializing during human's turn"""
if self.user_wants_to_serialize():
if self.computerTurn:
return 'S'
if self.humanTurn:
return 's'
""" *********************************************************************
Function Name: turn_help_mode_on
Purpose: Ask human player if they want to turn help mode on
Parameters: none
Return Value: true if user requests help mode, false otherwise
Local Variables: none
Assistance Received: none
********************************************************************* """
# Receives user input on whether they want to turn on help mode
def turn_help_mode_on(self):
#Continue asking user for input until they press 'y' or 'n'
while True:
self.notifications.msg_help_mode_prompt()
input = getche()
if (input == 'y' or input == 'Y'):
return True
if (input == 'n' or input == 'N'):
return False
self.notifications.msg_improper_input()
""" *********************************************************************
Function Name: user_wants_to_serialize
Purpose: Ask human player if they want to serialize
Parameters: none
Return Value: true if user requests serialization, false otherwise
Local Variables: none
Assistance Received: none
********************************************************************* """
# Asks if user wants to serialize & returns true if user wants to serialize
def user_wants_to_serialize(self):
#Continue asking user for input until they press 'y' or 'n'
while True:
self.notifications.msg_serialize_prompt()
input = getche()
if (input == 'y' or input == 'Y'):
return True
if (input == 'n' or input == 'N'):
return False
self.notifications.msg_improper_input()
""" *********************************************************************
Function Name: game_over_condition_met
Purpose: To check if the condition for game over has been met
Parameters: none
Return Value: true if condition met for game to be over, false otherwise
Local Variables: none
Assistance Received: none
********************************************************************* """
# Checks if the condition to end the game has been met
def game_over_condition_met(self):
#If one of the kings captured
if (self.board.get_human_king().captured or self.board.get_bot_king().captured):
return True
#If the human key square is occupied by the bots king die
if (self.board.get_square_resident(0, 4) != None):
if (self.board.get_square_resident(0, 4).botOperated):
if (self.board.get_square_resident(0, 4).king):
return True
#If the computer key square is occupied by the Human king die
if (self.board.get_square_resident(7, 4) != None):
if (not self.board.get_square_resident(7, 4).botOperated):
if (self.board.get_square_resident(7, 4).king):
return True
#If none of the game over conditions are met
return False
""" *********************************************************************
Function Name: get_user_input
Purpose: To get user input for coordinates
Parameters: none
Return Value: none
Local Variables: none
Assistance Received: none
********************************************************************* """
# Gets user input for coordinates if it is a human's turn
def get_user_input(self):
self.startRow = 0
self.startCol = 0
self.endRow = 0
self.endCol = 0
self.path = 0
#Continue asking user for input until they press all the digits
#Ask for origin row
while True:
self.notifications.msg_enter_origin_row()
input = getche()
try:
self.startRow = int(input)
break
except ValueError:
self.notifications.msg_improper_input()
#Ask for origin column
while True:
self.notifications.msg_enter_origin_column()
input = getche()
try:
self.startCol = int(input)
break
except ValueError:
self.notifications.msg_improper_input()
#Ask for destination row
while True:
self.notifications.msg_enter_destination_row()
input = getche()
try:
self.endRow = int(input)
break
except ValueError:
self.notifications.msg_improper_input()
#Ask for destination column
while True:
self.notifications.msg_enter_destination_column()
input = getche()
try:
self.endCol = int(input)
break
except ValueError:
self.notifications.msg_improper_input()
#In case of a 90 degree turn, ask the path preference as well
if ((self.startRow != self.endRow) and (self.startCol != self.endCol)):
while True:
self.notifications.msg_90degree_path_selection()
input = getche()
try:
if (int(input) == 1 or int(input) == 2):
self.path = int(input)
break
except ValueError:
self.notifications.msg_improper_input()
""" *********************************************************************
Function Name: toss_to_begin
Purpose: To conduct a toss and set the turn of appropriate player to true
Parameters: none
Return Value: none
Local Variables: none
Assistance Received: none
********************************************************************* """
# Does a toss to determine which team will start the game
def toss_to_begin(self):
#Continue until both have different toss results
while True:
self.humanDieToss = randint(1, 6)
self.computerDieToss = randint(1, 6)
if (self.humanDieToss != self.computerDieToss):
break
#Whoever has the highest number on top - wins the toss
if (self.humanDieToss > self.computerDieToss):
self.humanTurn = True
self.notifications.msg_toss_results("You", self.humanDieToss, self.computerDieToss)
else:
self.computerTurn = True
self.notifications.msg_toss_results("Computer", self.humanDieToss, self.computerDieToss)
|
cae615385524e32d95c204ee874965f2941723dd | cowaar/advent2019 | /Day6/second_.py | 491 | 3.828125 | 4 | import networkx as nx
import matplotlib.pyplot as plt
list = open("input.txt").read().split()
print(list)
G = nx.Graph()
for item in list:
inner,outer = item.split(")")
print('inner = ' +inner +" outer = " + outer)
G.add_edge(outer, inner)
for neighbour in nx.neighbors(G,"SAN"):
santas_planet = neighbour
for neighbour in nx.neighbors(G,"YOU"):
your_planet = neighbour
print(your_planet,santas_planet)
print(nx.shortest_path_length(G, your_planet, santas_planet))
|
760b19149c6f59d84cfc6569c88b08bba0fed5ea | daniel-reich/ubiquitous-fiesta | /aj7JPnAuW8dy4ggdp_17.py | 127 | 3.75 | 4 |
def parity(n):
remainder = bool(n % 2)
if remainder == False:
return "even"
if remainder == True:
return "odd"
|
6af0f346e07eeedf48d949d801b4577e0afec858 | chengchaos/watchlist | /mytrain/alien.py | 774 | 3.78125 | 4 | # -*- coding:utf-8 -*-
import print as print
alien_0 = {"color": "green", "points": 5}
print(alien_0["color"])
print(alien_0['points'])
alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)
del alien_0['points']
print(alien_0)
favorite_languages = {
"jen": "python",
"sarah": "c",
"edward": "ruby",
"phil": "python",
}
print(favorite_languages)
for k, v in favorite_languages.items():
print("Key" + k + " => " + v.title())
for lan in set(favorite_languages.values()):
print("lan => " + lan)
# 输入回车以后继续
# message = input("Tell me somehing, and I will repeat it back to you: ")
# print("The Message: => " + message)
current_number = 1
while current_number <= 5:
print(current_number)
current_number += 1
|
d0f4cced62680d432e13ee6b283d6b0a0aa52ce1 | pnayab/dsp | /python/advanced_python_csv.py | 372 | 3.65625 | 4 | import csv
f = open("faculty.csv")
txt = f.read()[1:]
header = txt.splitlines()[:1]
lines = txt.splitlines()[1:]
csv_f = csv.reader(lines)
degree_list = []
for row in csv_f:
degree_list.append(row[3])
f.close()
with open('emails.csv', 'wb') as testfile:
csv_writer = csv.writer(testfile, delimiter='\n')
csv_writer.writerow([x for x in degree_list])
|
d38f5fc63715e647c0538a77b42f141e29322502 | jackyko1991/ConvNet-pytorch | /convnet.py | 869 | 3.546875 | 4 | from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
import torch
class ConvNet(nn.Module):
# neural net in pytorch inherits pytorch nn module class
def __init__(self):
super(ConvNet, self).__init__()
# convnet
# class initation defines convolution, pooling and cross product (fully connected) layers
self.conv1 = nn.Conv2d(3, 6, 5)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 = nn.Linear(16 * 5 * 5, 120) #linear fully connected layer
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
def forward(self, x):
# image forwarding through the net, F is the functional module of pytorch
x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.conv2(x)))
x = x.view(-1, 16 * 5 * 5)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x |
e5867cbec367df050953c3506e5e1f139fb9f70b | JuanMPerezM/AlgoritmosyProgramacion_Talleres | /taller de estructuras de control de repeticion/ejercicio7.py | 214 | 3.53125 | 4 | """
Entradas
Dato 1-->int-->x
Dato 2-->int-->m
Salidas
"""
while True:
inp=input().split()
x,m=inp
x=int(x)
m=int(m)
if (x==0 and m==0):
break
else:
n=x*m
print(n) |
0e4617ecbba8d6579b53c98087b96364e5dc6e83 | neulab/tranx-study | /analysis/submissions/0ed2dff1d23b0de1cfcf9edb0ba35b1c_task1-1_1591986411/task1-1/main.py | 463 | 3.640625 | 4 | # Example code, write your program here
import random
import string
from collections import defaultdict
def main():
letters = [random.choice(string.ascii_lowercase) for _ in range(100)]
numbers = [random.randint(1, 20) for _ in range(100)]
d = defaultdict(list)
for c, x in zip(letters, numbers):
d[c].append(x)
print("\n".join(f"{c} {' '.join(map(str, xs))}" for c, xs in sorted(d.items())))
if __name__ == '__main__':
main()
|
b83a96edb849205eb16e489fc71097cee4956c60 | Fe-Ordan/GitUp | /Quadratic Formula (ax^2+bx+c) Solver.py | 1,127 | 4.0625 | 4 | print(" Type a Quadratic Formula (ax^2+bx+c)")
print(" =====================================")
print(" But first we Have to do it the hard way")
print(" " + "Do you Agree?")
ans = "yes"
answer = input()
if answer == ans :
print("Ok ,cool")
else :
print("alas!!")
exit()
for i in ["========","=========","========"]:
print(i)
print("............let's go ...............")
print("type the (-a- of ax ) number:")
a = float(input())
print("type the 'b' of bx number")
b = float(input())
print("Now , type the 'c' and to get the to solution if c=0 type 0")
c = float(input())
op1 = b**2-4*a*c
if op1 > 0 :
print("Delta equal = " + str(op1))
elif op1 == 0 :
print("The solution is :" + str(-1*b/2*a))
exit()
else :
op2 = (-1*b - op1**(1/2))/2*a
op3= (-1*b + op1**(1/2))/2*a
print("Delta is < 0 it has no Solutions in the Real numbers")
print("Do you want Solution on Complex Numbers ?")
answer = input()
an = "yes"
if answer == an :
print("First solution is : " + str(op2))
print("Second solution is : " + str(op3))
else :
exit()
|
bff28c27cf07ca5a0afd7c5608896440ba834d56 | dmolony3/bland-altman | /bland_altman.py | 3,253 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jan 30 10:07:00 2018
# Code for creating Bland Altman plot and Concordance Correlation Coefficient plots
@author: David
"""
import pandas as pd
import matplotlib.pyplot as plt
import argparse
from numpy import polyfit
example_text = r'Example Usage: python bland_altman.py --fname=C:\Users\David\Desktop\Plaque_burden_data.csv \
--minlimit=0 --maxlimit=100 --var1="Computed Plaque Burden" --var2="Measured Plaque Burden"'
parser = argparse.ArgumentParser(description=\
'Create Bland-Altman and Concordance correlation coefficient plots', \
epilog=example_text, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('--fname', help='Enter filename')
parser.add_argument('--minlimit', type=int, help='Enter min limits')
parser.add_argument('--maxlimit', type=int, help='Enter max limits')
parser.add_argument('--var1', help='name of variable1')
parser.add_argument('--var2', help='name of variable2')
#optional arguments for x and y labels
args = parser.parse_args()
data = pd.read_csv(args.fname)
xlim = [args.minlimit, args.maxlimit]
ylim = [args.minlimit, args.maxlimit]
# drop an rows that contain nans
data = data.dropna(axis=0, how='any')
# determine mean and difference
mean = (data.iloc[:, 0] + data.iloc[:, 1])/2
diff = data.iloc[:, 0] - data.iloc[:, 1]
# get mean and standard deviation of the differences
mean_diff = diff.mean()
std_diff = diff.std()
# determine 95% limits of agreement
LoA_plus = mean_diff + 1.96*std_diff
LoA_neg = mean_diff - 1.96*std_diff
# plot figure
fig = plt.figure()
ax1 = fig.add_subplot(121)
ax1.scatter(mean, diff, s=4)
ax1.set_xlim((xlim[0], xlim[1]))
xval = ax1.get_xlim()
ax1.plot(xval, (mean_diff, mean_diff))
ax1.plot(xval, (LoA_plus, LoA_plus), 'r--')
ax1.plot(xval, (LoA_neg, LoA_neg), 'r--')
# set text
ax1.text(xval[1] - (xval[1]/8), LoA_plus + xval[1]*0.015, '+1.96SD')
ax1.text(xval[1] - (xval[1]/8), LoA_neg + xval[1]*0.015, '-1.96SD')
ax1.text(xval[1] - (xval[1]/8), mean_diff + xval[1]*0.015, 'MEAN')
ax1.text(xval[1] - (xval[1]/8), LoA_plus - xval[1]*0.035, round(LoA_plus, 2))
ax1.text(xval[1] - (xval[1]/8), LoA_neg - xval[1]*0.035, round(LoA_neg, 2))
ax1.text(xval[1] - (xval[1]/8), mean_diff - xval[1]*0.035, round(mean_diff, 2))
if args.var1:
var1 = args.var1
var2 = args.var2
ax1.set_xlabel('Mean of ' + var1 + ' and ' + var2)
ax1.set_ylabel('Difference between ' + var1 + ' and ' + var2)
# concordance correlation coefficient
covar = data.cov()
ccc = 2*covar.iloc[0, 1]/(covar.iloc[0, 0] + covar.iloc[1, 1] + \
(data.iloc[:, 0].mean() - data.iloc[:, 1].mean())/2)
# determine fit
coeff = polyfit(data.iloc[:, 0], data.iloc[:, 1], 1)
print('Coefficients are {}'.format(coeff))
ax2 = fig.add_subplot(122)
ax2.scatter(data.iloc[:, 0], data.iloc[:, 1], s=4)
ax2.plot((xlim[0],xlim[1]), (coeff[0]*0 + coeff[1], coeff[0]*ylim[1] + coeff[1]))
# plot concordance line
ax2.plot((xlim[0],xlim[1]), (ylim[0], ylim[1]), 'k--')
ax2.text(xlim[0]+(xlim[1]/20), xlim[1]-(xlim[1]/10), 'CCC={}'.format(round(ccc, 2)))
ax2.set_xlim((xlim[0], xlim[1]))
ax2.set_ylim((ylim[0], ylim[1]))
if args.var1:
var1 = args.var1
var2 = args.var2
ax2.set_xlabel(var1)
ax2.set_ylabel(var2)
plt.show() |
2c4d25bbd91e1abf4cee55efae40626c87d6b750 | xiaoxin12/pythonlearn | /learnign/12.素数判断.py | 814 | 3.828125 | 4 | # !/usr/bon/python
# _*_ coding: UTF-8 _*_
# 题目:判断101-200之间有多少个素数,并输出所有素数。
# 程序分析:判断素数的方法:用一个数分别去除2到sqrt(这个数),如果能被整除,则表明此数不是素数,反之是素数。
count =0
for x in range(101, 200):
# 首先先把这个输放出来
# 如果这个输字能被人一一个2 到自己的数字整除,则不是素数
issu = 0
for i in range(2, x):
if x % i == 0:
issu = 1
if issu == 0:
count += 1
print(x)
print('总共有%s 个素数' % (count))
# L = list(filter(lambda x: x not in set([i for i in range(101,201) for j in range(2,i) if not i%j]), range(101,201)))
# print('一共有{}个素数,这些素数分别是:{}'.format(len(L),L))
|
1456da1bdf2b674ed5a4ca382a83536c3e0cb45a | angelosuporte/PythonLearning | /app_pyLearning/Exercise1.py | 539 | 3.8125 | 4 | a = int(input('Primeiro bimestre: '))
if a > 10:
int(input('Você digitou um número errado. Digite novamente: '))
b = int(input('Segundo bimestre: '))
if b > 10:
int(input('Você digitou um número errado. Digite novamente: '))
c = int(input('Terceiro bimestre: '))
if c > 10:
int(input('Você digitou um número errado. Digite novamente: '))
d = int(input('Quarto bimestre: '))
if d > 10:
int(input('Você digitou um número errado. Digite novamente: '))
media = ( a + b + c + d ) / 4
print('Média: {}'.format(media))
|
f4f79ee8e93556baa1758073bc1b76fc93656102 | TrisDing/algorithm010 | /01/rotate-array.py | 2,226 | 3.921875 | 4 | """
189. Rotate Array <Easy>
https://leetcode.com/problems/rotate-array/
"""
from typing import List
class Solution:
def rotate1(self, nums: List[int], k: int) -> None:
"""
Solution #1: Brute Force, rotate k times
Time: O(n*k)
Space: O(1)
"""
for i in range(k):
prev = nums[len(nums) - 1]
for j in range(len(nums)):
nums[j], prev = prev, nums[j]
def rotate2(self, nums: List[int], k: int) -> None:
"""
Solution #2: Extra Array
Time: O(n)
Space: O(n)
"""
n = len(nums)
res = [0] * n
for i in range(n):
res[(i+k) % n] = nums[i]
for i in range(n):
nums[i] = res[i]
def rotate3(self, nums: List[int], k: int) -> None:
"""
Solution #3: Cyclic Replacement
Time: O(n)
Space: O(1)
"""
n = len(nums)
k %= n
start = count = 0
while count < n:
curr, prev = start, nums[start]
while True:
next_idx = (curr + k) % n
nums[next_idx], prev = prev, nums[next_idx]
curr = next_idx
count += 1
if start == curr:
break
start += 1
def rotate4(self, nums: List[int], k: int) -> None:
"""
Solution #3: Reverse
Time: O(n): n elements are reversed a total of three times.
Space: O(1)
"""
n = len(nums)
k %= n
self.reverse(nums, 0, n - 1)
self.reverse(nums, 0, k - 1)
self.reverse(nums, k, n - 1)
def reverse(self, nums: list, start: int, end: int) -> None:
while start < end:
nums[start], nums[end] = nums[end], nums[start]
start, end = start + 1, end - 1
solution = Solution()
nums = [1,2,3,4,5,6,7]
solution.rotate1(nums, 1)
print(nums) # [7, 1, 2, 3, 4, 5, 6]
nums = [1,2,3,4,5,6,7]
solution.rotate2(nums, 2)
print(nums) # [6, 7, 1, 2, 3, 4, 5]
nums = [1,2,3,4,5,6,7]
solution.rotate3(nums, 3)
print(nums) # [5, 6, 7, 1, 2, 3, 4]
nums = [1,2,3,4,5,6,7]
solution.rotate4(nums, 4)
print(nums) # [4, 5, 6, 7, 1, 2, 3]
|
33103a5b720d88c34696887740d4a886a8778d61 | AbdulAhadSiddiqui11/PyHub | /File Handling/Append.py | 517 | 4.40625 | 4 | # Append mode is used to attach new data to the exisiting text file rather than overwriting it.
# Write Mode :
path = "assets/Random.txt"
file = open(path, "w")
file.write("Hey! This is the second message and it repalced the previous one!")
file.close()
# Everytime you run the program, the lines are removed and the new ones are added.
# Append mode :
file = open(path, "a")
file.write("\nNow, data won't be lost! That's because the file is opened in append mode.")
file.close()
input("Press any key to exit ") |
5e84a164bd423af5ede5ec4cbc572fedbea42e5e | laippmiles/Leetcode | /66_加一.py | 1,143 | 3.828125 | 4 | '''
给定一个非负整数组成的非空数组,在该数的基础上加一,返回一个新的数组。
最高位数字存放在数组的首位, 数组中每个元素只存储一个数字。
你可以假设除了整数 0 之外,这个整数不会以零开头。
示例 1:
输入: [1,2,3]
输出: [1,2,4]
解释: 输入数组表示数字 123。
示例 2:
输入: [4,3,2,1]
输出: [4,3,2,2]
解释: 输入数组表示数字 4321。'''
class Solution(object):#36ms
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
for i in range(len(digits)):
digits[i] = str(digits[i])
num = str(int(''.join(digits)) + 1)
digi = []
for i in num:
digi.append(int(i))
return digi
class SolutionBest(object):#26ms
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
tmp = ''
for i in digits:
tmp += str(i) #善用字符串合并大法
tmp = int(tmp) + 1
digits = [int(i) for i in list(str(tmp))]
return digits |
bb02b6f7c4f95c6d65b2a8189d1a348891c7980f | caitanojunior/python | /Coursera/semana2/dezenas.py | 1,293 | 3.921875 | 4 | entrada = int(input('Digite um número inteiro: '))
numeroStr = str(entrada)
if(entrada < 100):
dezena = entrada // 10
print('O dígito das dezenas é', dezena)
elif(entrada < 1000):
dezena = numeroStr[1:2]
print('O dígito das dezenas é', dezena)
elif(entrada < 10000):
dezena = numeroStr[2:3]
print('O dígito das dezenas é', dezena)
elif(entrada < 100000):
dezena = numeroStr[3:4]
print('O dígito das dezenas é', dezena)
elif(entrada < 1000000):
dezena = numeroStr[4:5]
print('O dígito das dezenas é', dezena)
elif(entrada < 10000000):
dezena = numeroStr[5:6]
print('O dígito das dezenas é', dezena)
elif(entrada < 100000000):
dezena = numeroStr[6:7]
print('O dígito das dezenas é', dezena)
elif(entrada < 1000000000):
dezena = numeroStr[7:8]
print('O dígito das dezenas é', dezena)
elif(entrada < 10000000000):
dezena = numeroStr[8:9]
print('O dígito das dezenas é', dezena)
elif(entrada < 10000000000):
dezena = numeroStr[9:10]
print('O dígito das dezenas é', dezena)
elif(entrada < 100000000000):
dezena = numeroStr[9:10]
print('O dígito das dezenas é', dezena)
elif(entrada < 1000000000000):
dezena = numeroStr[10:11]
print('O dígito das dezenas é', dezena)
|
604a6bf4069b75ac2d42b95c3dd2161b6740d2af | BridgetWright/B8IT105_Program_10354568 | /bw_ca5b.py | 3,833 | 3.9375 | 4 | # Bridget Wright
# Student No: 10354568
# B8IT105 Programming for Big Data
# CA5b - Calculator, Python, Lambda, Map, Filter, Reduce
# A calculator that can handle lists of data
# Lambda, Map, Reduce, Filter, List Comprehension, Generator
# Code from tutorial in class
add = lambda x,y : x+y
print add(1,1)
def fahrenheit(t):
return ((float(9)/5)*t + 32)
def celsius(t):
return (float(5)/9*(t - 32))
temp = (36.5, 37, 37.5, 39)
F = map(fahrenheit, temp)
print F
C = map(celsius, F)
print C
a = [1,2,3,4]
b = [17,12,11,10]
c = [-1, -4, 5, 9]
print map (lambda x,y:x+y, a,b)
print map(lambda x,y,z:x+y+z, a,b,c)
print map(lambda x,y,z:x+y-z, a,b,c)
fib = [0,1,1,2,3,5,8,13,21,34,55]
result = filter(lambda x: x % 2, fib)
print result
result = filter(lambda x: x % 2 == 0, fib)
print result
print reduce(lambda x, y: x+y, [47, 11, 42, 13])
f = lambda a,b: a if (a>b) else b
print reduce(f, [47, 11, 42, 13])
# Functions using reduce
def max (values):
return reduce (lambda a,b: a if (a>b) else b, values)
print max([47, 11, 42, 13])
def min (values):
return reduce (lambda a,b: a if (a<b) else b, values)
print min([47, 11, 42, 13])
def add (values):
return reduce (lambda a,b: a if (a+b) else b, values)
print add([47, 11, 42, 13])
# Functions using filter
def is_even (values):
return filter (lambda x: x % 2 == 0, values)
print is_even([47, 11, 42, 13])
def is_odd (values):
return filter (lambda x: x % 2, values)
print is_odd([47, 11, 42, 13])
# Functions using reduce
def divide (values):
return reduce (lambda a,b: a/float(b) if (b != 0 and a != 'Nan')
else 'Nan', values)
print divide([47, 11, 0, 42, 13, 0])
print divide([47, 11, 42, 13, 0])
print divide([47, 11, 42, 13])
def multiply (values):
return reduce (lambda a,b: a*b, values)
print multiply([47, 11, 42, 13, 0])
# Functions using map
def to_fahrenheit (values):
return map (fahrenheit, values)
print to_fahrenheit ([0, 37, 40, 100])
def to_celcius (values):
return map (celcius, values)
print to_fahrenheit ([0, 32, 100, 212])
def sum(to):
return reduce (lambda x, y: x+y, range (1, to+1))
print sum(100)
# Function using list comprehension
Celsius = [39.2, 36.5, 37.3, 37.8]
Fahrenheit = [ ((float(9)/5)*x + 32) for x in Celsius ]
print Fahrenheit
# Pythagorean triples
#### note here the use of 2 indents - Python recognises that 2 lines are on the 1 line
print [(x,y,z) for x in range(1,30) for y in range(x,30)
for z in range(y,30) if x**2 + y**2 == z**2]
# Product of two sets
colours = [ "red", "green", "yellow", "blue" ]
things = [ "house", "car", "tree" ]
coloured_things = [ (x,y) for x in colours for y in things ]
print coloured_things
# Name Generators
def city_generator():
yield("Konstanz")
yield("Zurich")
yield("Schaffhausen")
yield("Stuttgart")
x = city_generator()
print x.next()
print x.next()
print x.next()
print x.next()
# print x.next()
# this code is not in tutorial
cities = city_generator()
for city in cities:
print city
### don't forget n in the first line!
def get_triplets(n):
for x in range (1,n):
for y in range (x,n):
for z in range (y,n):
if x**2 + y**2 == z**2:
yield (x,y,z)
triplets = get_triplets(30)
for triplet in triplets:
print triplet,
# Function with yield statement
### Fibonacci - create a generator that will go up to the 5th Fibonacci sequece
def fibonacci(n):
"""Fibonacci numbers generator, first n"""
a, b, counter = 0, 1, 0
while True:
if (counter > n): return
yield a
a, b = b, a + b
counter += 1
f = fibonacci(50)
for x in f:
print x,
print
|
de4860107641e4c39f0f121d5898ef2d21a993e7 | karrui/taskrr | /test/read_file.py | 704 | 3.734375 | 4 | from os import getcwd
import csv
# Convert any item in the row, from string to float
def parse_csv_row(row):
new_arr = []
for item in row:
try:
new_arr.append(float(item))
except:
new_arr.append(item)
return new_arr
## Read a csv file, return the data as list of tuples
def read_csv(filename):
path_to_csv = "{}/db/csv/".format(getcwd())
with open("{}{}".format(path_to_csv, filename), 'r') as inp_file:
target_csv = csv.reader(inp_file, delimiter=',')
# Ignore the first header row
next(target_csv)
data = []
for row in target_csv:
data.append(tuple(parse_csv_row(row)))
return data
|
e3ae49d8e381779796efb35dafe16fd8d76b56b5 | rakshith4able/python-password-generator | /main.py | 3,175 | 3.8125 | 4 | from tkinter import *
from tkinter import messagebox
from random import choice, randint, shuffle
import pyperclip
# ---------------------------- PASSWORD GENERATOR ------------------------------- #
def generate_password():
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u',
'v',
'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q',
'R',
'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+']
password_letters = [choice(letters) for _ in range(randint(8, 10))]
password_symbols = [choice(symbols) for _ in range(randint(2, 4))]
password_numbers = [choice(numbers) for _ in range(randint(2, 4))]
password_list = password_letters + password_numbers + password_symbols
shuffle(password_list)
password = "".join([char for char in password_list])
password_input.insert(0, password)
pyperclip.copy(password)
# ---------------------------- SAVE PASSWORD ------------------------------- #
def add_to_file():
website = website_input.get()
username = username_input.get()
password = password_input.get()
if len(website) == 0 or len(password) == 0:
messagebox.showinfo(title="Oops", message="Do not leave any fields empty")
else:
is_ok = messagebox.askokcancel(title=website,
message=f"Details:\nwebsite:{website}\nusername:{username}\npassword:{password}\nAre you OK with generated password?")
if is_ok:
with open("data.txt", mode="a") as file:
file.write(f"{website} | {username} | {password}\n")
website_input.delete(0, "end")
password_input.delete(0, "end")
# ---------------------------- UI SETUP ------------------------------- #
window = Tk()
window.title("Password Manager")
window.config(padx=20, pady=20, bg="white")
canvas = Canvas(window, width=200, height=200, bg="white", highlightthickness=0)
canvas.grid(row=0, column=1)
img = PhotoImage(file="logo.png")
canvas.create_image(100, 100, image=img)
website_label = Label(text="Website:", bg="white")
website_label.grid(row=1, column=0)
website_input = Entry(width=51)
website_input.grid(row=1, column=1, sticky='w', columnspan=2)
website_input.focus()
username_label = Label(text="Email/Username:", bg="white")
username_label.grid(row=2, column=0)
username_input = Entry(width=51)
username_input.grid(row=2, column=1, sticky='w', columnspan=2)
username_input.insert(0, "[email protected]")
password_label = Label(text="Password:", bg="white")
password_label.grid(row=3, column=0)
password_input = Entry(width=32)
password_input.grid(row=3, column=1, sticky='w')
generate_button = Button(text="Generate Password", command=generate_password)
generate_button.grid(row=3, column=2, sticky='w')
generate_button.config()
add_button = Button(text="Add", width=36, command=add_to_file)
add_button.grid(row=4, column=1, sticky='w', columnspan=2)
window.mainloop()
|
85a60d251b7f5a4a8baf95c86b04520d695676d1 | kbuczek/computerScienceStudies | /Python/Zadania9/9.6.py | 3,086 | 3.75 | 4 | class Node:
def __init__(self, data=None, left=None, right=None):
self.data = data
self.left = left
self.right = right
def __str__(self):
return str(self.data)
def insert(self, node):
if node.data < self.data: # mniejsze na lewo
if self.left:
self.left.insert(node)
else:
self.left = node
else: # większe lub równe na prawo
if self.right:
self.right.insert(node)
else:
self.right = node
def count(self):
counter = 1
if self.left:
counter += self.left.count()
if self.right:
counter += self.right.count()
return counter
def search(self, data):
if self.data == data:
return self
if data < self.data:
if self.left:
return self.left.search(data)
else:
if self.right:
return self.right.search(data)
return None
def remove(self, data): # self na pewno istnieje
# Są lepsze sposoby na usuwanie.
if data < self.data:
if self.left:
self.left = self.left.remove(data)
elif self.data < data:
if self.right:
self.right = self.right.remove(data)
else: # self.data == data
if self.left is None: # przeskakuje self
return self.right
else: # self.left na pewno niepuste
# Szukamy największego w lewym poddrzewie.
node = self.left
while node.right: # schodzimy w dół
node = node.right
node.right = self.right # przyczepiamy
return self.left
return self
def count_leafs(self): #liczy liście drzewa binarnego
counter = 0
if not self.right and not self.left:
counter += 1
else:
if self.left:
counter += self.left.count_leafs()
if self.right:
counter += self.right.count_leafs()
return counter
def count_total(self): #suma liczb przechowywanych w drzewie
counter = 0
counter += self.data
if self.left:
counter += self.left.count_total()
if self.right:
counter += self.right.count_total()
return counter
def print(self):
if self is None:
return
print('left: ', self.left, 'data:', self.data, 'right: ', self.right)
if self.left:
self.left.print()
if self.right:
self.right.print()
binaryTree = Node(4)
binaryTree.insert(Node(2))
binaryTree.insert(Node(6))
binaryTree.insert(Node(8))
binaryTree.insert(Node(5))
binaryTree.insert(Node(3))
print(binaryTree.count_leafs()) #3
print(binaryTree.count_total()) #28
print()
binaryTree.print() |
09053100811651fbeffa44915434353bea2d28f3 | p234a137/caltech_ml | /hw1/Perceptron_hw1.py | 2,307 | 3.640625 | 4 |
# coding: utf-8
# # Perceptron exercise from homework 1, April 8, 2013
# In[15]:
#get_ipython().magic(u'pylab inline')
import random
import numpy as np
# In[31]:
number_runs=20
number_iterations=1000
number_training=10
iterations_to_convergence=[];
for run in range(0,number_runs):
# target function
x1=random.uniform(-1,1); y1=random.uniform(-1,1);
x2=random.uniform(-1,1); y2=random.uniform(-1,1);
# classifies points as +1 or -1 depending on whether they are above or below the line
def target(x,y):
if y>=(y1+(x-x1)*(y2-y1)/(x2-x1)):
return 1
else:
return -1
# training points
xn=[]; yn=[]; zn=[];
for i in range(1,number_training):
x=random.uniform(-1,1)
y=random.uniform(-1,1)
xn.append(x)
yn.append(y)
# classify using zn depending on whether they fall above or below the line
if y>(y1+(x-x1)*(y2-y1)/(x2-x1)):
zn.append(+1)
else:
zn.append(-1)
# iterate PLA until it converges
x0=1
w = [0,0,0] # [w0=b, w1 for x, w2 for y]
for iter in range(1,number_iterations):
i = random.randint(0,len(xn)-1); # pick randomly a point from xn
# use cmp to simulate the sign function
hyp = cmp(w[0]*1. + w[1]*xn[i] + w[2]*yn[i], 0); # hypothesis
trg = target(xn[i],yn[i]); # target function
if not cmp(hyp, trg) == 0 :
w[0] = w[0] + trg*x0
w[1] = w[1] + trg*xn[i]
w[2] = w[2] + trg*yn[i]
#compare two arrays to check whether algorithm converged
converged = False
nr_converged = 0;
for j in range(0,len(xn)):
hyp = cmp(w[0]*1. + w[1]*xn[j] + w[2]*yn[j], 0); # hypothesis
trg = target(xn[j],yn[j]); # target function
if cmp(hyp, trg) == 0:
nr_converged = nr_converged+1
if nr_converged == len(xn):
converged= True
iterations_to_convergence.append(iter);
print "PLA for ",number_training," points converged after ",iter," iterations"
break; # stop iterations
# In[ ]:
print("iterations mean, median, rms", np.mean(iterations_to_convergence), np.median(iterations_to_convergence), np.sqrt(np.std(iterations_to_convergence)));
|
eb0f205c4d2ae04a43eaa29350f6b5870a588a1b | malayandi/bCoursesGB | /sectionComp.py | 3,036 | 3.96875 | 4 | """
Given a CSV file containing the gradebook data from bCourses, prints a data
frame containing the section averages and standard deviations for the specified
assignment.
Command line input should be as follows:
python sectionComp.py path_to_data assignment
Parameters:
path_to_data: path to CSV file containing gradebook
assigment: name of assigment(s), separated by whitespace
"""
import sys
import pandas as pd
import numpy as np
NUM_SECTIONS = 13
MAX_STUDENTS = 35
"""
Returns a data frame containing the scores of students for the given assignment
categorised by sections. The columns are the sections section.
"""
def sectionScores(data, assignment):
# removing row containing possible points and storing
possible_pts = data.ix[0]
data = data.drop(0, axis=0)
# replace -1 hw scores with 0
data = data.replace(-1, 0)
# name of assignment as stored in gradebook
col_name = None
for column in data.columns:
if assignment.lower() in column.lower():
col_name = column
break
if not col_name:
return("Assignment " + assignment + " not found!")
df = pd.DataFrame(np.zeros((MAX_STUDENTS, 0)))
for i in range(1, NUM_SECTIONS):
num = 100 + i
section = "STAT 134 DIS " + str(num) + " and STAT 134 LEC 001"
subset = data[data['Section'] == section]
score = subset[col_name]
score.index = range(len(score))
df[num] = score
return df
"""
Given a data frame containing student scores categorised by sections (in
columns), returns a data frame giving the mean and standard deviation of each
section.
"""
def collate(df):
df = pd.DataFrame([df.mean(), df.std()], index=['mean', 'std'])
df = df.transpose()
return df
"""
Given a data frame containing student scores categorised by sections (in
columns), returns a list containing the assignment number and section numbers
for which grades have not been uploaded.
"""
def missing(df):
return pd.isnull(df).all(0).nonzero()[0] + 101
if __name__ == "__main__":
args = sys.argv
data_file = args[1]
assignments = list(args[2:])
data = pd.read_csv(data_file, sep=",")
frames = []
not_uploaded = {}
for assignment in assignments:
frame = sectionScores(data, assignment)
frames.append(frame)
missing_grades = missing(frame)
# Check if grades are missing for this assignment
if missing_grades != []:
not_uploaded[assignment] = missing_grades
# Check if assignment can't be found
if isinstance(frame, str):
print(frame)
sys.exit()
df = pd.concat(frames)
df = collate(df)
print("===")
print("Section Comparison for " + str(assignments))
print(df)
print("===")
if not_uploaded:
print("Warning! Grades for the following assignments and sections have not been uploaded:")
for assignment in not_uploaded.keys():
print(assignment + ":" + str(not_uploaded[assignment]))
|
dbf103fbf156e8f3d06326de2c10dd46c4f494dc | yuwen37/algorithm021 | /Week_02/429.n-叉树的层序遍历.py | 1,152 | 3.515625 | 4 | #
# @lc app=leetcode.cn id=429 lang=python
#
# [429] N 叉树的层序遍历
#
# @lc code=start
"""
# Definition for a Node.
class Node(object):
def __init__(self, val=None, children=None):
self.val = val
self.children = children
"""
class Solution(object):
def levelOrder(self, root):
"""
:type root: Node
:rtype: List[List[int]]
"""
# 递归
ans = []
def dfs(root, index):
if not root:return
if len(ans) <= index:
ans.append([])
ans[index].append(root.val)
for child in root.children:
dfs(child, index + 1)
dfs(root, 0)
return ans
# 迭代
# import collections
if not root:return []
ans = []
deq = deque([root])
while deq:
tmp = []
for _ in range(len(deq)):
root = deq.popleft()
if root:
tmp.append(root.val)
deq.extend(root.children)
ans.append(tmp)
return list(ans)
# @lc code=end
|
6976a00c9db0fe5a06e735be6a7c6e11c28b291d | yang-0115/shiyanlou-code | /jump7.py | 121 | 3.640625 | 4 | a=0
while a <=99:
a = a+1
if (a%7 ==0) or (a%10 ==7) or (a//10 ==7):
continue
else:
print(a)
|
0e79fbea8d4474433ad6c3649be303cfedef0eea | yasmineElnadi/python-introductory-course | /Assignment 4/4.7.py | 1,141 | 3.84375 | 4 | import math
class QuadraticEquations:
def __init__(self, a, b, c):
self.__a = a
self.__b = b
self.__c = c
def geta(self):
return self.__a
def getb(self):
return self.__b
def getc(self):
return self.__c
#def checkDiscriminant(self):
# if (self.__b)**2 - (4 * self.__a * self.__c) == 0:
#return "the equation has no roots"
def getDiscriminant(self):
return (self.__b)**2 - (4* self.__a * self.__c)
def getRoot1(self):
return (-(self.__b) + math.sqrt(self.getDiscriminant()))/ (2 * self.__a)
def getRoot2(self):
return (-(self.__b) - math.sqrt(self.getDiscriminant()))/(2 * self.__a)
def printEquation(self):
if (self.__b)**2 - (4 * self.__a * self.__c) <= 0:
print("the equation has no roots")
else:
print("the First Root is", self.getRoot1(), "the second root is", self.getRoot2())
equation = QuadraticEquations(5,2,1)
equation.printEquation()
equation = QuadraticEquations(5,6,1)
equation.printEquation()
#print(equation.getRoot1())
#print(equation.getRoot2()) |
e998645c3bea51297bb6dc94bd9b2e1c6da11614 | shuforov/CheckiO | /Roman_numerals/roman_numerals.py | 1,968 | 3.703125 | 4 | """translater from latin number to roman"""
def roman_numerals(number_lat):
"""translate number"""
roman_num = {1: 'I',
2: 'II',
3: 'III',
4: 'IV',
5: 'V',
6: 'VI',
7: 'VII',
8: 'VIII',
9: 'IX',
10: 'X',
20: 'XX',
30: 'XXX',
40: 'XL',
50: 'L',
60: 'LX',
70: 'LXX',
80: 'LXXX',
90: 'XC',
100: 'C',
200: 'CC',
300: 'CCC',
400: 'CD',
500: 'D',
600: 'DC',
700: 'DCC',
800: 'DCCC',
900: 'CM',
1000: 'M',
2000: 'MM',
3000: 'MMM',
3999: 'MMMCMXCIX'}
new_lat_num = str(number_lat)
add_zero = '0' * len(new_lat_num)
number_rom = ''
if number_lat in roman_num:
return roman_num[number_lat]
else:
for temp in xrange(len(new_lat_num)):
if new_lat_num[temp] == '0' and temp == len(new_lat_num)-1:
break
if temp + 1 == len(new_lat_num) and int(
new_lat_num[-1:] in roman_num):
number_rom += roman_num[int(new_lat_num[temp])]
elif temp + 1 == len(new_lat_num) and int(
new_lat_num[-2:]) in roman_num:
number_rom += roman_num[int(new_lat_num[-2:])]
elif temp < len(new_lat_num) and new_lat_num[temp] != '0':
number_rom += roman_num[int(
new_lat_num[temp] + add_zero[temp+1:])]
return number_rom
print roman_numerals(2)
print roman_numerals(6)
print roman_numerals(76)
print roman_numerals(13)
print roman_numerals(3910)
print roman_numerals(3999)
|
e2d1dd8ecc09e2261b8bf0008669cff2fda3954a | dylan7rdgz/AI | /Training Models/linear_regression.py | 4,049 | 4.5 | 4 | # linear regression is just a machine learning model
import numpy as np
# set of equations
random_values = np.random.rand(100, 1)
print(random_values)
# random values is our input to our dataset and X is the output, the form of the foll: equation is y = mx
X = 2 * random_values
print(X)
# what is numpy.random? it will generate random values of 100 rows and 1 column (row,col)
# how numpy.random works? it uses a Bit generator in conjunction with a Sequence generator
# Bit Generator will manufacture a SEQUENCE of signed integer (32-64) bits and input it into the Generator
# the Generator will transform this sequence of random bits into a sequence of numbers that will follow a specific
# probability distribution(Uniform normal or binomial)
# read more: https://numpy.org/doc/stable/reference/random/index.html?highlight=rand#module-numpy.random
# difference between randn and rand?
# randn: Return a random matrix with data from the “standard normal” distribution.
# rand: Random values in a given shape
random_values_from_normal_distribution = np.random.randn(100, 1)
y = 4 + 3*X + random_values_from_normal_distribution # y is the "target" values
X_b = np.c_[
np.ones((100, 1)), # generate a tensor of shape 100*1
X # add x0 = 1 to each instance
] # add ones to all instances, this is what the .c_ operator does
# X_b is generated for the matrix multiplication, check line 62
print("X_b:", X_b)
# we are using .T and the compiler understands this because this is a numpy data structure
theta_best = np.linalg.inv(X_b.T.dot(X_b)).dot(X_b.T).dot(y)
print(theta_best)
# the function we used to generate the data: y = 3x + 4 + Gaussian noise
# https://towardsdatascience.com/linear-regression-91eeae7d6a2e
# imagine that the Gaussian is some small addition to the actual y value
# this maybe due to rounding up, not sure
# theta_best -> obtained: [4, 3] expected: [4.215, 2.770] (due to gaussian noise)
# now that we have predicted a model that is y = 4.215x + 2.770 we can predict for a data input x what is the output y
# lets take a point from the dataset itself
print("input_data", X[0])
print("target_label", y[0])
predicted_value = 4.215*X[0] + 2.770
print("predicted data", predicted_value)
print("Error for this data point prediction", predicted_value-y[0])
print("this is the equations approach\n")
# or
X_new = np.array([[0], [2]])
X_new_b = np.c_[
np.ones((2, 1)),
X_new
]
# X_new_b is now [0,1] and [2,1]
# consider input instance [2,1]
# the multiplication below is [2,1]*[3
# 4]
#
y_predict = X_new_b.dot(theta_best)
print("this is the matrix approach")
print("predicted data", y_predict)
# this was the error_rate for one data point, lets see for
# lets see the graph of this line
# import matplot as plt
import matplotlib.pyplot as plt
plt.plot(X_new, y_predict, "r-")
plt.plot(X, y, "b.")
plt.axis([0, 2, 0, 15]) # x ranges from 0,2 and y ranges from 0 to 15
plt.show()
# performing linear regression using scikit learn
from sklearn.linear_model import LinearRegression
lin_reg = LinearRegression()
lin_reg.fit(X, y)
print(lin_reg.intercept_, lin_reg.coef_)
lin_reg.predict(X_new)
# why is pseudo inverse superior to Normal Equations?
# 1.even if the matrix XT.X is singular the pseudo inverse is still defined, handles edge cases nicely
# 2. more efficient
# what is pseudo inverse in the first place?
'''
technique used: SVD
decomposes the training matrix into multiplication of 3 sub-matrices: ie. U.P+.VT
P+ is calculated by:
1. sets a threshold
2. all values below this threshold are converted to 0's
3. take inverses (^-1) of remaining values
4. transpose this final matrix
'''
np.linalg.pinv(X_b).dot(y)
# computational complexity
# time complexity
# using normal equations
'''
Normal Equation computes the inverse of (n+1)*(n+1) matrix where n is the number of features
Computational complexity of inverting such a matrix is O(n^3) depending on the implementation
'''
# using SVD
'''
O(n^2)
'''
|
97b84dd0bb1ffd7889331d60e7244717b6d51791 | ankitaapg17/Basic-Python-Codes | /new.py | 311 | 3.75 | 4 | #to generate exception of your type
#custom exception
class salnotinRange(Exception):
salary=None
def __init__(self,salary):
self.salary = salary
salary=int(input("Enter salary"))
if not 5000 < salary < 15000:
raise salnotinRange(salary)
else:
print("Thanks")
|
7afa691066ee1071a8ba4e36c034f9bd50753608 | Alexis-Lopez-coder/ProgramacionLogiaAlexisLopez | /ejercicio1.py | 1,838 | 4.0625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 24 16:13:07 2020
@author: alexis
"""
"""
# Programación Lógica
# Modus ponendo ponens
"el modo que, al afirmar, afirma"
P → Q. P ∴ Q
Se puede encadenar usando algunas variables
P → Q.
Q → S.
S → T. P ∴ T
Ejercicio
Defina una funcion que resuelva con verdadero o falso segun corresponada
Laura esta en Queretaro
Alena esta en Paris
Claudia esta en San Francisco
Queretaro esta en Mexico
Paris esta en Francia
San Francisco esta en EUA
Mexico esta en America
Francia esta en Europa
EUA esta en America
def esta(E1,E2):
pass
print(esta("Alena","Europa"))
# true
print(esta("Laura","America"))
# true
print(esta("Laura","Europa"))
# false
"""
def esta(e1, e2):
base = [["Laura","Queretaro"],
["Alena", "Paris"],
["Claudia","San Francisco"],
["Queretaro","Mexico"],
["San Francisco","EUA"],
["Paris","Francia"],
["EUA","America"],
["Mexico","America"],
["Francia","Europa"]
]
#quien = ""
lugar = ""
for x in base:
if x[0] == e1:
print(x)
#quien = x[0]
lugar = x[1]
if lugar != "":
if lugar == e2:
return True
else:
for y in base:
if lugar == y[0]:
print("lugar_:",lugar)
lugar = y[1]
if lugar == e2:
print("lugar_:",lugar)
return True
return False
print("Respuesta final:",esta('Alena','Europa'))
print()
print("Respuesta final:",esta('Laura','America'))
print()
print("Respuesta final:",esta('Laura','Europa'))
|
62c7d446a3772b74d7cd81a5c40a19b94f8f228a | bongster/leetcode | /solutions/1282-number-of-valid-words-for-each-puzzle/number-of-valid-words-for-each-puzzle.py | 2,621 | 4.03125 | 4 | # With respect to a given puzzle string, a word is valid if both the following conditions are satisfied:
#
# word contains the first letter of puzzle.
# For each letter in word, that letter is in puzzle.
#
# For example, if the puzzle is "abcdefg", then valid words are "faced", "cabbage", and "baggage", while
# invalid words are "beefed" (does not include 'a') and "based" (includes 's' which is not in the puzzle).
#
#
#
# Return an array answer, where answer[i] is the number of words in the given word list words that is valid with respect to the puzzle puzzles[i].
#
# Example 1:
#
#
# Input: words = ["aaaa","asas","able","ability","actt","actor","access"], puzzles = ["aboveyz","abrodyz","abslute","absoryz","actresz","gaswxyz"]
# Output: [1,1,3,2,4,0]
# Explanation:
# 1 valid word for "aboveyz" : "aaaa"
# 1 valid word for "abrodyz" : "aaaa"
# 3 valid words for "abslute" : "aaaa", "asas", "able"
# 2 valid words for "absoryz" : "aaaa", "asas"
# 4 valid words for "actresz" : "aaaa", "asas", "actt", "access"
# There are no valid words for "gaswxyz" cause none of the words in the list contains letter 'g'.
#
#
# Example 2:
#
#
# Input: words = ["apple","pleas","please"], puzzles = ["aelwxyz","aelpxyz","aelpsxy","saelpxy","xaelpsy"]
# Output: [0,1,3,2,0]
#
#
#
# Constraints:
#
#
# 1 <= words.length <= 105
# 4 <= words[i].length <= 50
# 1 <= puzzles.length <= 104
# puzzles[i].length == 7
# words[i] and puzzles[i] consist of lowercase English letters.
# Each puzzles[i] does not contain repeated characters.
#
#
class TrieNode:
def __init__(self):
self.children = {}
self.count = 0
class Trie:
def __init__(self):
self.root = self.getNode()
def getNode(self):
return TrieNode()
def insert(self, word):
curr = self.root
for c in word:
# print(c)
if c not in curr.children:
curr.children[c] = self.getNode()
curr = curr.children[c]
curr.count += 1
def search(self, word):
def dfs(node, found = False):
result = node.count * found
for c in word:
if c in node.children:
result += dfs(node.children[c], found or c == word[0])
return result
return dfs(self.root)
class Solution:
def findNumOfValidWords(self, words: List[str], puzzles: List[str]) -> List[int]:
trie = Trie()
for word in words:
# print('insert trie')
trie.insert(word)
return [trie.search(puzzle) for puzzle in puzzles]
|
c2a9dc318e975e92e5ebd4244292f9229007d6a9 | potomatoo/TIL | /Programmers/kakao_문자열 내림차순으로 배치하기.py | 179 | 3.65625 | 4 | def solution(s):
answer = ''
sort_ls = sorted(s, reverse=True)
for i in range(len(sort_ls)):
answer += sort_ls[i]
return answer
print(solution('Zbcdefg')) |
cb33348cf40a968db5105373aa4f64d36bd83821 | stacecadet17/python | /filter_by_type.py | 992 | 3.953125 | 4 | # If the integer is greater than or equal to 100, print "That's a big number!" If the integer is less than 100, print "That's a small number"
def integer(num):
if num >= 100:
print ("That's a big number!")
else:
print ("that's a small number")
# ****************************************************************************
# If the string is greater than or equal to 50 characters print "Long sentence." If the string is shorter than 50 characters print "Short sentence."
def sentence(str):
if len(str) > 50:
print ("Thats a long sentence")
else:
print ("That's a short sentence")
# ****************************************************************************
# If the length of the list is greater than or equal to 10 print "Big list!" If the list has fewer than 10 values print "Short list."
def list_length(list):
if len(list) > 10:
print ("big list!")
else:
print ("small list")
a = ["bunny", 4, 6, 1, "monkey", "tiger"]
list_length(a)
|
eb6069c8e804f5db3bdbc9bb52d8ba267c5114b4 | deer95/Prog_Sparrow | /Term_2/Syms Palindrome_4.py | 336 | 3.78125 | 4 | import re
def comparer(s):
i = 0
while i <= len(s) / 2:
if s[i] != s[-i - 1]:
return False
else:
i += 1
return True
s = 'Я не стар, брат Сеня'.lower()
s = re.sub('\W', '', s)
if comparer(s):
print('It\'s a palindrome')
else:
print('It\'s not a palindrome')
|
a30ab81661b4ac04d1d61dfe38d04c957fbc5627 | wldusdhso/sw-project-class5-2-2 | /assignment10_20171685_Guess.py | 1,327 | 3.65625 | 4 | class Guess:
def __init__(self, word):
self.secretWord = word
self.numTries = 0
self.guessedChars = []
self.currentStatus = '_'*len(self.secretWord)
self.currentword = '_'*len(self.secretWord)
self.indexnumL =[]
def display(self):
return 'Current: '+ self.currentStatus+'\n'+'Tries: '+ str(self.numTries)
def guess(self, character):
self.guessedChars += [character]
character = character.lower()
if self.secretWord == self.currentStatus:
return True
elif character in self.secretWord:
indexnum = 0
self.indexnumL = []
while self.secretWord.find(character,indexnum)!=-1:
indexnum = self.secretWord.find(character,indexnum)
self.indexnumL += [indexnum]
indexnum += 1
for i in self.indexnumL:
if i == len(self.currentword)-1:
self.currentword = self.currentword[:-1]+character
else:
self.currentword = self.currentword[:i]+character+self.currentword[i+1:]
self.currentStatus = self.currentword
return False
elif self.secretWord.find(character) ==-1:
self.numTries += 1
return False
|
a48171620ef64890d6e72cf1aa68f2de52923b3f | Dev-cSharpe/Algos | /insertion_sort.py | 608 | 3.953125 | 4 | from sort_tester import array_sort_test
def insertion_sort(arr):
'''
insertion sort : complexity ---> o(n^2)
'''
for i in range(1,len(arr)):
key=arr[i]
j=i-1
while j>=0 and key < arr[j]:
arr[j+1]=arr[j]
j-=1
arr[j+1]=key
return arr
#driver code
arr=[64,25,12,22,11]
result=insertion_sort(arr)
print(result)
print(array_sort_test(arr))
#first run
# [25,64,12,22,11]
#second run
# [25,12,64,22,11]
# [12,25,64,22,11]
# third run
# [12,25,22,64,11]
# [12,22,25,64,11]
#forth run
# [11,12,22,25,64] |
692a7320eb41898b3f4d3ddc5c613c09dcf4726a | Aasthaengg/IBMdataset | /Python_codes/p02744/s573177405.py | 440 | 3.5 | 4 | #!/usr/bin/env python3
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**5)
n = int(input())
ans = []
def dfs(arr, max_val):
if len(arr) == n:
ans.append(arr)
return
for i in range(max_val + 2):
next_arr = arr[:]
next_arr.append(i)
dfs(next_arr, max(max_val, i))
dfs([0], 0)
ans.sort()
orda = ord("a")
for line in ans:
print("".join([chr(orda + item) for item in line])) |
2f89a9baa411fbb92a724ed23e3df374daf1c518 | anujkumar163/pythonfiles | /pythonStack/makeArray.py | 910 | 4.3125 | 4 | # Second method to create a 1 D array
N = 5
arr = [0 for i in range(N)]
print(arr)
# Using above second method to create a
# 2D array
rows, cols = (5, 5)
arr = [[0 for i in range(cols)] for j in range(rows)]
print(arr)
# Python 3 program to demonstrate working
# of method 1 and method 2.
rows, cols = (5, 5)
# method 2a
arr = [[0]*cols]*rows
# lets change the first element of the
# first row to 1 and print the array
arr[0][0] = 1
for row in arr:
print(row)
# outputs the following
#[1, 0, 0, 0, 0]
#[1, 0, 0, 0, 0]
#[1, 0, 0, 0, 0]
#[1, 0, 0, 0, 0]
#[1, 0, 0, 0, 0]
# method 2b
arr = [[0 for i in range(cols)] for j in range(rows)]
# again in this new array lets change
# the first element of the first row
# to 1 and print the array
arr[0][0] = 1
for row in arr:
print(row)
# outputs the following as expected
#[1, 0, 0, 0, 0]
#[0, 0, 0, 0, 0]
#[0, 0, 0, 0, 0]
#[0, 0, 0, 0, 0]
#[0, 0, 0, 0, 0]
|
0b0f487979d10051a6c52dd8b2cff4e5562270b1 | chunche95/ProgramacionModernaPython | /Proyectos/ProgramacionVintage/OperadoresMatemáticos/modulo.py | 963 | 4.125 | 4 | # Operadores logicos
# la tupla toma los valores:
# Clave ==> Valor
# A 1
# B 2
# ... ...
# Creo la lista
tupla = ('A','B','C','D','E','F','G','H','I')
# Inicio un contador
indice = 0
# Genero un bucle while para eliminar las letras con valores 3,6,9
# Leo la lista
# while indice < len(tupla):
# # Condicional que me elimina los valores 2,6,9 de la tupla
# if indice+1 == 2 or indice+1 == 6 or indice+1 == 9:
# mataletra()
# indice += 1
# Creo un bucle que lea la lista tantas veces como sea necesario hasta que su valor sea igual o menor que la longitud total de la tupla
while indice <= len(tupla):
# Creo un condicional que saque por pantalla las claves que cumplan la condicion
if (indice +1) % 2 == 0:
# Imprimo por pantalla el valor de la clave
print(tupla[indice])
# Incremento en valor del indice para que vaya sumando y no cree un bucle infinito
indice += 1
|
7098b399e7ae88903f96a79513289158bc458a77 | minalspatil/coding_repo | /csvreader.py | 203 | 3.59375 | 4 | import csv
reader = csv.DictReader(open('salaries.csv', 'rb'))
#rows = sorted(Reader)
for row in reader:
print row
reader = csv.reader(open('salaries.csv', 'rb'))
for row1 in reader:
print row1
|
acdccfdc659e69248b0e8962e7dfee87da63cae0 | nrinn/guessing-game | /guess.py | 650 | 4.0625 | 4 | import random
random_number = random.randrange(1, 101)
print "Hello player, what is your name?",
name = raw_input()
print "%r, I'm thinking of a number between 1 and 100" % (name)
guess = int(input("Try to guess my number."))
while True:
#while guess != random_number:
if guess > random_number:
print "Your guess is high, try again"
guess = int(input("Try to guess my number."))
elif guess < random_number:
print "Your guess is too low, try again."
guess = int(input("Try to guess my number."))
elif guess == random_number:
print "You guessed it! The number was ", + random_number
break |
c3ab763db4d75db29557e031cd9c08650732809d | andye456/OXO | /CreateGameModel.py | 1,055 | 3.859375 | 4 | from RunGame import run_game
from model import TicTacToeModel
print("--- Summary ---")
history,x,o,d=run_game(player1="random", player2="random", loaded_model=None, iterations=10000)
print("X Wins = "+str(x))
print("O Wins = "+str(o))
print("Draws = "+str(d))
# Train the network using the results from the random games
ticTacToeModel = TicTacToeModel(9, 3, 100, 32)
model = ticTacToeModel.train(history)
model.save("OXO_model")
ticTacToeModel.set_model(model)
h, x, o, d = run_game(player1="neural", player2="random", loaded_model=ticTacToeModel, iterations=100)
print("After Learning (Neural = X vs Random = O):")
print("X Wins = "+str(x))
print("O Wins = "+str(o))
print("Draws = "+str(d))
# for i in range(10):
# model = ticTacToeModel.train(h)
# ticTacToeModel.set_model(model)
# h, x, o, d = run_game(player1="neural", player2="random", loaded_model=ticTacToeModel, iterations=100)
# print("After Learning (Neural = X vs Random = O):")
# print("X Wins = "+str(x))
# print("O Wins = "+str(o))
# print("Draws = "+str(d)) |
33f91cf09df6ec773f19bf3afecbcbebc2ce06e1 | xpert-uv/data_structure | /binary_search_tree.py | 5,641 | 4.21875 | 4 | """
binary search tree
"""
class Node:
"""
node for binary search tree
"""
def __init__(self, val, left=None, right=None):
self.val = val
self.right = right
self.left = left
# these two functions created based on video, not tested
# def find(self, sought):
# current_node = self
# while current_node:
# if current_node.val == sought:
# return current_node
# elif current_node.val > sought:
# current_node = current_node.left
# else:
# current_node = current_node.right
# def traverse(node):
# if node.left:
# traverse(node.left)
# print(node.val):
# if node.right:
# traverse(node.right)
class BinarySearchTree:
"""
binary search tree class.
"""
def __init__(self, root=None):
self.root = root
def insert(self, val):
"""
insert iteratively
"""
new_node = Node(val)
if self.root == None:
self.root = new_node
return self
current_node = self.root
while current_node:
if val < current_node.val:
if current_node.left:
current_node = current_node.left
else:
current_node.left = new_node
return self
elif val > current_node.val:
if current_node.right:
current_node = current_node.right
else:
current_node.right = new_node
return self
else:
return self
def insert_recursive(self, val):
"""
insert recursively
"""
new_node = Node(val)
if self.root == None:
self.root = new_node
return self
def recursive_insert(current_node):
if val < current_node.val:
if current_node.left == None:
current_node.left = new_node
return
else:
recursive_insert(current_node.left)
elif val > current_node.val:
if current_node.right == None:
current_node.right = new_node
return
else:
recursive_insert(current_node.right)
else:
return
current_node = self.root
recursive_insert(current_node)
return self
def find(self, val):
"""
find and return node with value val if exists, iterative approach
"""
if self.root == None:
return
current_node = self.root
while current_node:
if current_node.val == val:
return current_node
elif val < current_node.val:
current_node = current_node.left
else:
current_node = current_node.right
return
def find_recursive(self, val):
"""
find and return node with value val if exists, recursive approach
"""
if self.root == None:
return
def recursive_find(current_node):
if current_node == None:
return
if current_node.val == val:
return current_node
if val < current_node.val:
return recursive_find(current_node.left)
if val > current_node.val:
return recursive_find(current_node.right)
current_node = self.root
return recursive_find(current_node)
def dfs_pre_order(self):
"""
depth-first search with pre-order, returns array of each node's value
"""
arr = []
def traverse(current_node, arr):
if current_node == None:
return
arr.append(current_node.val)
traverse(current_node.left, arr)
traverse(current_node.right, arr)
traverse(self.root, arr)
return arr
def dfs_in_order(self):
"""
depth-first search in order, returns array of each node's value
"""
arr = []
def traverse(current_node, arr):
if current_node == None:
return
traverse(current_node.left, arr)
arr.append(current_node.val)
traverse(current_node.right, arr)
traverse(self.root, arr)
return arr
def dfs_post_order(self):
"""
depth-first search with post-order, returns array of each node's value
"""
arr = []
def traverse(current_node, arr):
if current_node == None:
return
traverse(current_node.left, arr)
traverse(current_node.right, arr)
arr.append(current_node.val)
traverse(self.root, arr)
return arr
def bfs(self):
"""
depth-first search with post-order, returns array of each node's value
"""
arr = []
queue = []
if self.root == None:
return
def traverse(current_node, queue, arr):
arr.append(current_node.val)
if current_node.left:
queue.append(current_node.left)
if current_node.right:
queue.append(current_node.right)
if len(queue) > 0:
next_node = queue.pop(0)
traverse(next_node, queue, arr)
traverse(self.root, queue, arr)
return arr
|
04ab63a7c588ef0ee8cd4e22be005e55ecf4b22e | Pooja-DataScientist/Hackerrank_Programs | /grades.py | 568 | 4 | 4 | n = int(input("Enter numbers of students:"))
score = []
names=[]
for i in range(n):
name = input("Enter name: ")
grade = float(input("Enter grade: "))
j = name,grade
j=list(j)
score.append(j)
score.sort(key=lambda x: x[1])
lowest = score[0].__getitem__(1)
second_lowest = 0
for l in score:
if l[1]==lowest:
lowest = l[1]
elif l[1] >lowest:
second_lowest = l[1]
break
for l in score:
if l[1] == second_lowest:
names.append(l[0])
names.sort()
for i in names:
print(i)
|
1fadf2e0267eaa079536c0f93d8b8ec00e62ecd9 | asabnis7/python-basics | /ex48/lexicon.py | 1,365 | 3.703125 | 4 | def convert_num(s):
try:
return int(s)
except ValueError:
return None
def scan(raw):
lexicon = [('direction','north'),
('direction','south'),
('direction','east'),
('direction','west'),
('direction','down'),
('direction','up'),
('direction','left'),
('direction','right'),
('verb','go'),
('verb','stop'),
('verb','kill'),
('verb','eat'),
('stop','the'),
('stop','in'),
('stop','of'),
('stop','at'),
('stop','it'),
('stop','from'),
('noun','door'),
('noun','bear'),
('noun','princess'),
('noun','cabinet'),
('area','castle'),
('area','trail'),
('area','woods')
]
words = raw.split()
sentence = []
for i in range(len(words)):
location = 0;
found = False
j = 0;
if convert_num(words[i]) == None:
low_word = words[i].lower()
while (j < len(lexicon)) and (found == False):
found = lexicon[j].__contains__(low_word)
if found == True:
location = j
j += 1
if found == False:
err = ('error', words[i])
sentence.append(err)
else:
sentence.append(lexicon[location])
elif convert_num(words[i]) != None:
num = ('number', words[i])
sentence.append(num)
return sentence |
0afe4b99b3c224ddc6e32159f478265941c2fae8 | bocoup/stereotropes-analysis | /src/film/posters.py | 5,820 | 3.515625 | 4 | # A module to download film posters from rotten tomatoes
# You can:
# - Scrape rotten tomatoes for metadata and get movie posters
# - Download poster images
#
# You don't have to do both. For example, this will scrape the data:
# python -m src.film.posters --src=data/results/films_full.json
# --dest=data/results/ft.json --scrape=True --failed=data/results/ft_f.json
#
# And this will scrape AND download it:
# python -m src.film.posters --src=data/results/films_full.json
# --dest=data/results/ft.json --scrape=True --failed=data/results/ft_f.json
# --poster_dest=test/
#
# If the data is already scraped, you can set scrape=False and then load the
# file source with the rotten tomato information in src and provide a poster
# destination directory.
import requests
import requests_cache
from os.path import splitext, basename, join
import time
import json
import math
import wget
from src import util
from src.film import util as filmutil
requests_cache.install_cache('rotten_tomatoes_web_cache')
apiKeys = util.read_json('src/film/api-keys.json')
def rotten_tomato_url(film):
"""Returns a rotten tomato data url for a specific movie."""
return ('http://api.rottentomatoes.com/api/public/v1.0/movies.json?'
'q=' + '+'.join(film['name'].split(' ')) + '&page_limit=10&page=1'
'&apikey=' + apiKeys['rotten-tomatoes'])
def normalize_poster_url(movie):
image_url = movie['posters']['thumbnail']
if 'tmb' in movie['posters']['thumbnail']:
image_url = movie['posters']['thumbnail'].replace('tmb', '320')
elif 'unsafe' in movie['posters']['thumbnail']:
dimensions_str = movie['posters']['thumbnail'].split("/")[4]
dimensions = dimensions_str.split("x")
ratio = int(dimensions[0]) / float(dimensions[1])
new_dimensions = [320, int(math.floor(320 / ratio))]
image_url = movie['posters']['thumbnail'].replace(dimensions_str, str(new_dimensions[0])+"x"+str(new_dimensions[1]))
if 'poster_default_thumb' in image_url:
return None
else:
return image_url
def find_movie(imdbid, movies):
for movie in movies:
if 'alternate_ids' in movie:
if (movie['alternate_ids']['imdb'] == imdbid):
return movie
return None
def get_all_posters(films, sleep_interval=0.5):
failed_films = []
for film in films:
if 'rtmetadata' not in film:
res = get_poster(film)
# returned structure:
# (film, poster_url, movie, True) > if found True, False if not.
if res[3] == True:
# Save poster
if res[1] is not None:
film['poster'] = res[1]
# Save rotten tomatoes metadata in case we want something from it
if res[2] is not None:
film['rtmetadata'] = res[2]
else:
failed_films.append(film)
time.sleep(sleep_interval)
return [films, failed_films]
def get_poster(film):
url = rotten_tomato_url(film)
try:
r = requests.get(url)
response = json.loads(r.text)
poster_url = None
if (response['total'] > 0):
if film['metadata'] is not None:
imdbid = film['metadata']['imdbID'][2:]
# Find the right movie match from rotten tomatoes based on the
# id that we have from imdb (collected from omdb.)
movie = find_movie(imdbid, response['movies'])
if movie is not None:
poster_url = normalize_poster_url(movie)
return (film, poster_url, movie, True)
except:
return (film, None, None, False)
def download_poster_images(films, dest_folder, sleep_interval=0.5):
failed_films = []
for film in films:
poster_url = None
if 'poster' in film:
poster_url = film['poster']
poster_file_path = filmutil.get_poster_path(film['id'], poster_url, dest_folder)
if not filmutil.does_poster_exist(film['id'], poster_url, dest_folder):
try:
print poster_url
wget.download(poster_url, out=poster_file_path)
time.sleep(sleep_interval)
except:
failed_films.append(film)
film['poster_filename'] = basename(poster_file_path)
return films
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description='Generate the info dict for tropes')
parser.add_argument('--src', help='Source films dictionary', required=True)
parser.add_argument('--dest', help='Destination for film dictionary', required=False)
parser.add_argument('--failed', help='Where to write failing films', required=False)
parser.add_argument('--scrape', dest='scrape', action='store_true')
parser.add_argument('--no-scrape', dest='scrape', action='store_false')
parser.add_argument('--poster_dest', help='Destination dir for film posters', required=False)
args = parser.parse_args()
films_with_posters = None
# Download rotten tomato data:
if args.scrape:
films = util.read_json(args.src)
films_with_posters = get_all_posters(films)
util.write_json(args.dest, films_with_posters[0])
if args.failed:
util.write_json(args.failed, films_with_posters[1])
# Download posters
if args.poster_dest:
if args.scrape:
films = films_with_posters[0]
else:
films = util.read_json(args.src)
# download poster images
films_with_poster_files = download_poster_images(films, args.poster_dest)
# write out the updated dest file.
util.write_json(args.dest, films_with_poster_files)
|
6487ea78d12ecdb604ce3ca8bfdd333ed4bab9da | fkunneman/ADNEXT_predict | /datahandler.py | 8,774 | 3.765625 | 4 |
import csv
import sys
import re
import random
import utils
class Datahandler:
"""
Datahandler
======
Container of datasets to be passed on to a featurizer. Can convert .csv
files into a dataset
Parameters
------
max_n : int, optional, default False
Maximum number of data instances *per dataset* user wants to work with.
Attributes
-----
dataset : dict
Dictionary where key is the name of a dataset, and the value its rows.
Will not be filled if data is streamed.
rows : list of lists
list of documents, document is a list of csv-fields
Examples
-----
Interactive:
>>> reader = Datareader(max_n=1000)
>>> reader.set('blogs.csv')
>>> docs = reader.rows
>>> reader.set_rows(docs)
"""
def __init__(self):
self.headers = "label tweet_id author_id date time authorname text tagged".split()
self.dataset = {}
self.rows = []
def set_rows(self, rows):
"""
Data reader
=====
Function to read in rows directly
Parameters
-----
rows : list of lists (rows and columns)
"""
self.rows = rows
self.rows_2_dataset()
def set(self, filename):
"""
Csv reader
=====
Function to read in a csv file and store it as a dict of lists
Parameters
-----
filename : str
The name of the csv file
Returns
-----
dataset : dict of lists
each column with an identifier
"""
csv.field_size_limit(sys.maxsize)
rows = []
try:
with open(filename, 'r', encoding = 'utf-8') as csvfile:
csv_reader = csv.reader(csvfile)
for line in csv_reader:
rows.append(line)
except:
csvfile = open(filename, 'r', encoding = 'utf-8')
csv_reader = csv.reader(line.replace('\0','') for line in csvfile.readlines())
for line in csv_reader:
rows.append(line)
self.rows = rows[1:]
self.rows_2_dataset()
def write_csv(self, outfile):
"""
CSV writer
=====
Function to write rows to a file in csv format
"""
self.dataset_2_rows()
utils.write_csv([self.headers] + self.rows, outfile)
def dataset_2_rows(self):
"""
Dataset converter
=====
Converts a dataset into rows
Needed to write a dataset to a file in csv format
Sets
-----
self.rows : list of lists (rows and columns respectively)
"""
self.encode_tagged()
self.rows = list(zip(*[self.dataset[field] for field in self.headers]))
self.decode_tagged()
def rows_2_dataset(self):
"""
Row converter
=====
Converts rows into a dataset
"""
self.dataset = {k: [] for k in self.headers}
for row in self.rows:
for category, val in zip(self.headers, row):
self.dataset[category].append(val)
self.decode_tagged()
def decode_tagged(self):
"""
Frog decoder
=====
Function to decode a frog string into a list of lists per document
"""
if self.dataset['tagged'][0] != '-':
new_tagged = []
for doc in self.dataset['tagged']:
new_tagged.append([token.split("\t") for token in doc.split("\n")])
self.dataset['tagged'] = new_tagged
def encode_tagged(self):
"""
Frog encoder
=====
Function to encode a frog list into a string
"""
tagstrings = []
for doc in self.dataset['tagged']:
tagstrings.append("\n".join(["\t".join(token) for token in doc]))
self.dataset['tagged'] = tagstrings
def split_dataset(self, shuffle = False):
"""
Dataset splitter
=====
Function to split the dataset in two sets of 90% and 10 %
Parameters
-----
shuffle : Bool
choose to shuffle the dataset before splitting (in order to mix
the labels)
Returns
------
train, test : list, list
"""
if shuffle:
random.shuffle(self.rows)
train_split = int(len(self.rows) * 0.9)
return(self.rows[:train_split], self.rows[train_split:])
def return_sequences(self, tag):
"""
Tag selecter
=====
Function to extract the sequence of a specific tag per
document
Presumes a column with frogged data
Parameters
-----
tag : str
the tag of which to return the sequences
options: 'token', 'lemma', 'postag', 'sentence'
Returns
-----
sequences : list of lists
the sequence of a tag per document
"""
tagdict = {'token' : 0, 'lemma' : 1, 'postag' : 2, 'sentence' : 3}
tagindex = tagdict[tag]
sequences = []
for instance in self.dataset['tagged']:
sequences.append([token[tagindex] for token in instance])
return sequences
def filter_instances(self, blacklist):
"""
Instance filter
=====
Function to filter instances from the dataset if they contain a string
from the blacklist
Parameters
-----
blacklist : list of strings
Any instance that contains a word from the blacklist is filtered
"""
tokenized_docs = self.return_sequences('token')
filtered_docs = [] #list of indices
for i, doc in enumerate(tokenized_docs):
black = False
for token in doc:
for string in blacklist:
if re.match(string, token, re.IGNORECASE):
black = True
if not black:
filtered_docs.append(i)
self.dataset_2_rows()
self.rows = [self.rows[i] for i in filtered_docs]
self.rows_2_dataset()
def normalize(self, regex, dummy):
"""
Normalizer
=====
Function to normalize tokens and lemmas that match a regex to a dummy
Parameters
-----
regex : re.compile object
the regular expression to match
dummy : string
the dummy to replace a matching token with
"""
new_tagged = []
for doc in self.dataset['tagged']:
new_doc = []
for token in doc:
if regex.match(token[0]):
token[0] = dummy
token[1] = dummy
new_doc.append(token)
new_tagged.append(new_doc)
self.dataset['tagged'] = new_tagged
def normalize_urls(self):
"""
URL normalizer
=====
Function to normalize URLs to a dummy
"""
find_url = re.compile(r"^(http://|www|[^\.]+)\.([^\.]+\.)*[^\.]{2,}")
dummy = "_URL_"
self.normalize(find_url, dummy)
def normalize_usernames(self):
"""
Username normalizer
=====
Function to normalize usernames to a dummy
presumes 'twitter-format' (@username)
"""
find_username = re.compile("^@\w+")
dummy = "_USER_"
self.normalize(find_username, dummy)
def filter_punctuation(self):
"""
Punctuation remover
=====
Function to remove punctuation from frogged data
"""
new_tagged = []
for doc in self.dataset['tagged']:
new_doc = []
for token in doc:
try:
if not token[2] == "LET()":
new_doc.append(token)
except:
continue
new_tagged.append(new_doc)
self.dataset['tagged'] = new_tagged
def set_label(self, label):
"""
Label editor
=====
Function to set a universal label for each instance
Parameters
-----
label : string
"""
self.dataset['label'] = [label] * len(self.dataset['label'])
self.dataset_2_rows()
def to_lower(self):
new_tagged = []
for doc in self.dataset['tagged']:
new_doc = []
for token in doc:
new_doc.append([token[0].lower(), token[1].lower(), token[2], token[3]])
new_tagged.append(new_doc)
self.dataset['tagged'] = new_tagged
def sample(self, samplesize):
self.rows = random.sample(self.rows, samplesize)
self.rows_2_dataset()
|
35e37f1b8ab3012af69e4eaa2eb82ba7e09f3f84 | wjonesrhys/python | /learning_python/sqlite.py | 3,951 | 3.75 | 4 | import csv
import sqlite3
import os
import calendar
def create_database(db_file):
db = sqlite3.connect(db_file)
cursor = db.cursor()
c_1 = "transaction_id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE NOT NULL"
c_2 = "Organisation_Name TEXT NOT NULL"
c_3 = "Purchase_Order_Number INTEGER NOT NULL"
c_4 = "Order_Date INTEGER NOT NULL"
c_5 = "Total_Value INTEGER NOT NULL"
c_6 = "Supplier_Name TEXT NOT NULL"
c_7 = "Account_Name TEXT NOT NULL"
c_8 = "Service TEXT NOT NULL"
sql_create_table = "CREATE TABLE PurchaseOrderTransactions ({},{},{},{},{},{},{},{})".format(c_1,c_2,c_3,c_4,c_5,c_6,c_7,c_8)
try:
cursor.execute(sql_create_table)
except sqlite3.OperationalError:
print("{} already exists.".format(db_file))
db.commit()
cursor.close()
def clean_currency(currency_string):
return float(currency_string[1:].replace(",",""))
def insert_records(db_file, records):
db = sqlite3.connnect(db_file)
cursor = db.cursor()
for row in records:
row[3] = clean_currency(row[3])
sql_insert = "INSERT INTO PurchaseOrderTransactions(Organisation_Name, \
Purchase_Order_Number, Order_Date, Total_Value, Supplier_Name, \
Account_Name, Service) VALUES ('{}','{}','{}','{}','{}','{}','{}')".format(*row)
print(row)
cursor.execute(sql_insert)
db.commit()
cursor.close()
def print_records(db_file):
db = sqlite3.connect(db_file)
cursor = db.cursor()
sql_select = "SELECT * FROM PurchaseOrderTransactions"
cursor.execute(sql_select)
records=cursor.fetchall()
for r in records:
print(r)
cursor.close()
def total_spent(db_file):
db = sqlite3.connect(db_file)
cursor = db.cursor()
sql_query = "SELECT Total_Value FROM PurchaseOrderTransactions"
total = 0
for row in cursor.execute(sql_query):
total += row[0]
total = round(total, 2)
print("Total spent : " + str(total))
cursor.close()
def total_spent_by_month(db_file):
db = sqlite3.connect(db_file)
cursor = db.cursor()
sql_query = "SELECT Order_Date,Total_Value FROM PurchaseOrderTransactions"
result_dict = {}
for row in cursor.execute(sql_query):
date = row[0].split("/")
month = calendar.month_name[int(date[1])]
year = date[2]
amount = row[1]
key = month + " " + Year
if key in result_dict:
result_dict[key] += amount
else:
result_dict[key] = amount
for k,v in result_dict.items():
print(k + " : " + str(round(v,2)))
cursor.close()
def add_transaction(db_file):
db = sqlite3.connect(db_file)
cursor = db.cursor()
row = []
row.append(input("Organisation Name: "))
row.append(input("Purchase Order Number: "))
row.append(input("Order Date (dd/mm/yyyy): "))
row.append(input("Total Value (number): "))
row.append(input("Supplier Name: "))
row.append(input("Account Name: "))
row.append(input("Service: "))
sql_insert = "INSERT INTO PurchaseOrderTransactions(Organisation_Name, \
Purchase_Order_Number, Order_Date, Total_Value, Supplier_Name, \
Account_Name, Service) VALUES ('{}','{}','{}','{}','{}','{}','{}')".format(*row)
cursor.execute(sql_insert)
db.commit()
cursor.close()
def delete_transaction(db_file, ID):
db = sqlite3.connect(db_file)
cursor = db.cursor()
cursor.execute("DELETE FROM PurchaseOrderTransactions WHERE Transaction_id="+str(ID))
db.commit()
cursor.close()
DB_FILE = "PurchaseOrderTransactions.db"
csv_file = "purchase-orders.csv"
with open(csv_file) as f:
reader = csv.reader(f)
DATA = [line for line in reader][1:]
if not os.path.exists(DB_FILE):
create_database(DB_FILE)
insert_records(DB_FILE, DATA)
total_spent(DB_FILE)
total_spent_by_month(DB_FILE)
delete_transaction(DB_FILE, 1)
add_transaction(DB_FILE)
print_records(DB_FILE)
|
0aa84e964945cf84bf0060b703587cae9e7a3403 | PANNER-BAYARAVAN/Python-Codes | /basic/bubble_sort.py | 291 | 3.65625 | 4 | num1=0
temp=0
arrnum = [7, 4, 1, 3, 8, 6]
for num1 in range(5):
for num1 in range(4):
if arrnum[num1]>arrnum[num1+1]:
temp=arrnum[num1]
arrnum[num1]=arrnum[num1+1]
arrnum[num1+1]=temp
for num1 in range(5):
print(arrnum[num1])
|
db86788c34cd11c579106eb4814b885b0aee2d81 | raymondhfeng/raymondhfeng.github.io | /data_structures_and_algorithms/cold_interview_practice/caching.py | 3,059 | 3.8125 | 4 | The task: Write a program that implements a cache policy.
1. LRU
- Cache manager, has access to the cache and does all accesses.
- Keep track of number of elements in cache
- getter and setter method for all disk accesses.
- Use a dictionary to represent the cache. When inserting an element into the cache
* First check if cacheEntity is already in the cache, if so, access and return. If not
* Call block device manager to get block of data.
* If cache is not full, then insert cacheEntity
* If cache is full, then figure out which cacheEntity to evict
- cacheEntity will need
* Needs key to identify the data
* Variable to hold the data, suppose data has a wrapper class
* Time of last access. Setting or getting would update this number
- cache itself, the dictionary
* To get, requires indexing into dictionary, modifying time of last access, return data
* To set, requires indexing into dictionary, modifying time of last access, return -1 if failed, 1 if success, write back to disk
2. MRU
3. Clock
class CacheManager:
def __init__(self, size=10): # Size in blocks
self.size = 10
self.numEntries = 0
self.cache = {}
self.currTime = 0
self.blockManager = BlockDeviceManager()
def get(self, idNum):
if idNum in cache:
cache[idNum].setTimeLast(self.currTime)
self.currTime += 1
return cache[idNum].getData()
else:
block = self.blockManager.getBlock(idNum)
cacheEntry = CacheEntity(self.currTime,block)
self.currTime += 1
if numEntries >= self.size: # need to find cacheEntry to evict
temp = min(self.cache.values())
res = [key for key in self.cache if self.cache[key] == temp]
keyToEvict = res[0]
if self.cache[keyToEvict].isDirty():
self.blockManager.wroteBlock(keyToEvict,self.cache[keyToEvict])
del self.cache[keyToEvict]
self.numEntries -= 1
self.cache[idNum] = cacheEntry
self.numEntries += 1
return block
def set(self, idNum, data):
cacheEntry = self.get(idNum)
cacheEntry.setData(data)
# self.blockManager.wroteBlockId(idNum,self.cache[idNum])
def flush(self): # Flush all values to disk upon ending the caching protocol
pass
class CacheEntity:
def __init__(self, timeLast, data):
self.timeLast = timeLast
self.data = data
self.dirty = False
def getTimeLast(self):
return self.timeLast
def getData(self):
return self.data
def setData(self, data):
self.data = data
self.dirty = True
def setTimeLast(self, time):
self.timeLast = time
def isDirty(self):
return self.dirty
class BlockDeviceManager:
class Block:
def __init__(self, idNum, blockSize = 4):
self.blockSize = blockSize
self.data = [0 for _ in range(self.blockSize)]
self.idNum = idNum
def __init__(self, blockSize = 4, blockCapacity = 10):
self.blockSize = blockSize
self.blockCapacity = blockCapacity
self.disk = [Block(i, blockSize) for i in range(self.blockCapacity)]
def getBlock(self, idNum): # Input verification
return self.disk[idNum]
def writeBlock(self, idNum, data):
self.disk[idNum] = data |
433b976ebc79de9ed16e5c537a6fa2e0a3d5be01 | akshaya-b/python | /corey.py | 719 | 3.703125 | 4 | class Tree:
#class variable
nooftrees=0
noofbrances=1.05
def __init__(self,name,age,region):
self.name=name
self.age=age
self.region=region
self.biology= name +"-"+ region
Tree.nooftrees +=1
def morphology(self):
return (str(self.age) + self.region)
def branches(self):
return Tree.noofbrances * self.age
tree1=Tree('neem',20,'india')
tree2=Tree('pine',50,'uk')
print(tree1.biology)
print(Tree.morphology(tree1))
print(tree2.morphology())
#class variable output
print(Tree.nooftrees)
print(tree1.branches())
tree1.noofbrances=1.08
print(tree1.noofbrances)
print(tree2.noofbrances)
print(Tree.noofbrances) |
ee0a6cd3c7e71fe252c7a2942316bdf69aee700d | inJAJA/Study | /homework/데이터 과학/p032_sort.py | 775 | 4.1875 | 4 | """
# Sort
: list를 자동으로 정렬해줌
이미 만든 list를 망치고 싶지 않다면 sorted를 함수로 사용해서 새롭게 정렬된 list생성 가능
'오름 차순'으로 정렬
"""
x = [4, 1, 2, 3]
y = sorted(x) # y = [1, 2, 3, 4] / x = [4, 1, 2, 3]
x.sort() # x = [1, 2, 3, 4]
""" 내림 차순 : reverse = True """
a = sorted([-4, 1, -2, 3], reverse= True)
print(a) # [3, 1, -2, -4]
""" 절댓값 : key=abs """
b = sorted([-4, 1, -2, 3], key=abs, reverse = True)
print(b) # [-4, 3, -2, 1]
# 빈도의 내림차순으로 단어와 빈도를 정렬
# wc = sorted(word_counts.items(),
# key = lambda word_and_count : word_and_count[1],
# reverse = True)
# print(wc) |
37301adf61c21f18df52a37023f5c18b763c8d40 | Empythy/Algorithms-and-data-structures | /剑指Offer/把二叉树打印成多行.py | 1,287 | 3.578125 | 4 | """
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
"""
# -*- coding:utf-8 -*-
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# 返回二维列表[[1,2],[4,5]]
def Print(self, pRoot):
# write code here
if pRoot is None:
return []
ret = []
deque1 = [pRoot]
deque2 =[]
while deque1 or deque2:
if deque1:
tmpRet = []
while deque1:
tmpNode = deque1.pop(0)
tmpRet.append(tmpNode.val)
if tmpNode.left:
deque2.append(tmpNode.left)
if tmpNode.right:
deque2.append(tmpNode.right)
ret.append(tmpRet)
if deque2:
tmpRet = []
while deque2:
tmpNode = deque2.pop(0)
tmpRet.append(tmpNode.val)
if tmpNode.left:
deque1.append(tmpNode.left)
if tmpNode.right:
deque1.append(tmpNode.right)
ret.append(tmpRet)
return ret
|
de0ef9e7b023d5ee739ade229e415b2a2692b39c | macjohn96/SI_python | /activitie9.py | 174 | 4.21875 | 4 | myNumber = int(input('Enter an integer: '))
print("Number: {0:0=3d}".format(myNumber))
print("Pow2: {0:0=3d}".format(myNumber**2))
print("Pow3: {0:0=3d}".format(myNumber**3)) |
91b76bbcecbbf331063c03f08300c860899479d7 | Harmandhindsa19/python | /class4/2assignment.py | 139 | 3.703125 | 4 | t=(20,50,30,60,78,19,49)
print("tuple is:" , t)
print("maximun number in tuple is:" , max(t))
print("minimum number in tuple is:" , min(t)) |
f2dff083ba2780be98cd6d7d72e5ccf231e4b665 | fclm1316/mypy | /oop/chapter07/an_error.py | 1,034 | 4.0625 | 4 | #!/usr/bin/python3
#coding:utf-8
def add(a,b):
#就地修改a[list]
a += b
return a
class Company:
def __init__(self,name,staffs=[]):
self.name = name
self.staffs = staffs
def add(self,staffs_name):
self.staffs.append(staffs_name)
def remove(self,staffs_name):
self.staffs.remove(staffs_name)
if __name__ == "__main__":
print("----------------------------")
com1 = Company("com1",["aa1","aa2"])
com1.add("aa3")
com1.remove("aa1")
print(com1.staffs)
com2 = Company("com2")
com2.add("bb1")
print(com2.staffs)
com3 = Company("com3")
com3.add("bb2")
print(com2.staffs)
print(com3.staffs)
print("----------------------------")
a = 1
b = 2
c = add(a,b)
print(c)
print(a,b)
print("----------------------------")
a = [1,2]
b = [3,4]
c = add(a,b)
print(c)
print(a,b)
print("----------------------------")
a = (1,2)
b = (3,4)
c = add(a,b)
print(c)
print(a,b)
|
cfab71901c8e5ae2e22dd895ad57827c8ecf97ea | melany202/programaci-n-2020 | /talleres/taller2.py | 1,432 | 4 | 4 | #Ejercicios while
print("---Ejercicio1---")
preguntaNumero="Ingrese porfavor un numero entero o 0 para terminar : "
NumeroIngresado =int(input(preguntaNumero))
suma = 0
while(NumeroIngresado != 0) :
suma += NumeroIngresado
NumeroIngresado =int(input(preguntaNumero))
print(suma)
#Ejercicio while 2
print("---ejercicio2---")
preguntaNumero1 ="ingrese un numero entero porfavor : "
preguntaNumero2 ="ingrese un numero mayor al primero porfavor : "
numeroIngresado1 =int(input(preguntaNumero1))
numeroIngresado2 =int(input(preguntaNumero2))
while(numeroIngresado1>=numeroIngresado2) :
numeroIngresado2=int(input(preguntaNumero2))
print(numeroIngresado1)
print(numeroIngresado2)
#Ejercicio while 3
print("---ejercicio3---")
preguntaNumeroA ="ingrese un numero entero porfavor : "
preguntaNumeroB ="ingrese un numero entero porfavor : "
numeroingresadoA =int(input(preguntaNumeroA))
numeroingresadoB =int(input(preguntaNumeroB))
while(numeroingresadoA<numeroingresadoB):
numeroingresadoA =numeroingresadoB
numeroingresadoB=int(input(preguntaNumeroB))
#Ejercicio while 4
print("---ejercicio4---")
total= 0
monto=float(input('Monto de una venta : '))
while (monto!=0):
if (monto <0):
print('Monto no valido')
else:
total=+monto
monto=float(input('Monto de una venta :'))
if (total>1000):
total -=total*0.1
print('Monto total a pagar : $',total)
|
3f4b28f1f0a73e386fa1ffd853343a01c62255eb | Wojtbart/Python_2020 | /Zestaw2/kopiowanie.py | 598 | 3.765625 | 4 | import sys
def kopiowanie(inner_file,outer_file ):
text=""
with open(inner_file,"r") as fileRead, open(outer_file,"w") as outFile:
try:
for line in fileRead:
if not line.startswith('#'):
text+=line
outFile.write(text)
finally:
fileRead.close()
outFile.close()
if __name__ == "__main__":
if len(sys.argv)!=3:
print("musisz podać nazwy plików!!!!Zamykam")
sys.exit(1)
fileIn = sys.argv[1]
fileOut = sys.argv[2]
kopiowanie(fileIn,fileOut) |
6dab387392fcc7dbf918196a084c88bb1e25169b | XixinSir/PythonKnowledgePoints | /正则表达式/1、判断是否是手机号码.py | 1,506 | 3.8125 | 4 | import re
def checkPhone(str):
if len(str) != 11:
return False
elif str[0] != "1": # 注意str[0]字符形式 判断的时候要注意这一点
return False
elif str[1:3]!= "38" and str[1:3]!="39":
return False
for i in range(3,11):
if str[i]>"9" or str[i]<"0":
return False
return True
print(checkPhone("13812345678"))
print(checkPhone("13912345678"))
print(checkPhone("138012345678"))
print(checkPhone("138a12345678"))
def checkPhone1(str):
# 13912345678
pat=r"^1[34578]\d{9}$"
# pat=r"^1(([3578]\d)|(47))\d{8}$"
res = re.match(pat,str)
print(res)
checkPhone1("13812345678")
checkPhone1("13912345678")
checkPhone1("138012345678")
checkPhone1("138a12345678")
def checkPhone12(str):
# 13912345678
# pat=r"^1[34578]\d{9}$"
pat=r"(1(([3578]\d)|(47))\d{8})"
res = re.findall(pat,str) # 返回的是组 要看括号的个数
print(res)
print("从一串字符中提取出电话号码")
checkPhone12("fsdf13212345678jwoe4354fsf13523456789")
'''
QQ 6到10位,全是数字
'''
re_QQ=re.compile(r"^[1-9]\d{5,9}$") # 5到9个数字结尾
print(re_QQ.search("1234567890"))
print(re_QQ.search("0234567890"))
print(re_QQ.search("123456a890"))
print(re_QQ.search("12345674657890"))
'''
mail [email protected]
phone 010-55348765
user 数字、字母、下划线 6-12位
passwd
ip
url
'''
|
62191c4a3c439bd5d2d887801cdebf2020d34c5e | bryanlimsin/blood_calculator | /for_usage.py | 315 | 3.640625 | 4 | foods = ["apples", "bananas", "cherries", "donuts"]
amounts = [11, 22, 33, 44]
for i, x in enumerate(foods):
print("{} - {}".format(amounts[i], x))
#########
# With zip()
do_I_like_it = [True, False, False, True]
for y, x, z in zip(amounts, foods, do_I_like_it):
print("{} - {} - {}".format(y,x,z))
|
b9a4267c8f47230ace3ed7a5b8d53e3e37410ff4 | jessychen1984/MiniProj | /src/misc/calculator/calculator.py | 1,930 | 3.953125 | 4 | '''
A simple python calculation question generator
usg: python calculator.py -d "+,-" -c 3 -l 200 -t 30
usg: python calculator.py --op_type="+,-" --op_count=3 --limit=20 --total=30
'''
import sys, getopt, random
def auto_cal_generator(limit=100, op_count=1, op_type=["+"], total=100):
print("Here are today's %d works, good luck!" % total)
l = len(op_type)-1
for j in range(0, total):
up = limit
question = ""
for i in range(0, op_count+1):
num = 0
if i == 0:
num = random.randint(1,max(1,min(limit,up)))
question = "%s%d" % (question, num)
up -= num
continue
op = "+"
if limit - up > 0:
op_i = random.randint(0,l)
op = op_type[op_i]
question = "%s%s" % (question, op)
if op =="+":
num = random.randint(1,max(1,min(limit,up)))
up -= num
elif op == "-":
num = random.randint(1,max(limit-up, 1))
up += num
else:
print("operator error: %s" % op)
sys.exit(1)
question = "%s%d" % (question, num)
print("%d: %s=" % (j+1, question))
def main(argv=None):
if argv is None:
argv = sys.argv
opts, _dummy = getopt.getopt( sys.argv[1:], "l:c:d:t:", ["limit=","op_count=","op_type=","total="])
limit = 100
op_count = 1
op_type = ["+"]
total = 100
for opt,arg in opts:
if opt in ["-l", "--limit"]:
limit = int(arg)
elif opt in ["-c", "--op_count"]:
op_count = int(arg)
elif opt in ["-d", "--op_type"]:
op_type = arg.strip().split(",")
elif opt in ["-t", "--total"]:
total = int(arg)
auto_cal_generator(limit, op_count, op_type, total)
if __name__ == '__main__':
main()
|
94148ce82196e1c63a78c9ca75907da40b352205 | DuttaH/TicTacToe | /GamePlay.py | 2,646 | 3.53125 | 4 | from GameCourt import *
msg = ['Player ',
'Game Draw',
'Winner : ',
'Press any key to continue...',
'ERROR# Cell already occupied',
'ERROR# Invalid input',
'Do you want to save the game? (Y/N) ',
'Your Game has been saved. Press any key to quit...'
]
def save_game(ct):
input(msg[7])
def game_status(ct):
# Check any column, row or diagonals have save values or not
# Check rows
if ct['7'] == ct['8']== ct['9'] != ' ':
return ct['7']
elif ct['4'] == ct['5'] == ct['6'] != ' ':
return ct['4']
elif ct['1'] == ct['2'] == ct['3'] != ' ':
return ct['1']
# Check columns
elif ct['7'] == ct['4'] == ct['1'] != ' ':
return ct['7']
elif ct['8'] == ct['5'] == ct['2'] != ' ':
return ct['8']
elif ct['9'] == ct['6'] == ct['3'] != ' ':
return ct['9']
# Check diagonals
elif ct['7'] == ct['5'] == ct['3'] != ' ':
return ct['7']
elif ct['9'] == ct['5'] == ct['1'] != ' ':
return ct['9']
# If there is no match, check for empty cell. If empty cell is available then continue else game draw
elif ' ' in ct.values():
return 'C'
else:
return 'D'
def new_game():
# Initialize new court
ct = {'7': ' ', '8': ' ', '9': ' ',
'4': ' ', '5': ' ', '6': ' ',
'1': ' ', '2': ' ', '3': ' ',
}
print_court(ct, 9)
# Initialize game variables
status = 'C'
draw = 'X'
move = ' '
# Game is being played within loop. Loop will run until winner is decided / drawn or back / exit input received
while status == 'C':
# Get user input
move = input(msg[0] + draw + ':').upper()
# Check whether user want to back from game
if move == 'B':
return
# Check whether user want to quit the game
elif move == 'Q':
sv_game = input(msg[6]).upper()
if move == 'Y':
save_game(ct)
return
# Validate and record the move
elif move in ct.keys():
if ct[move] == ' ':
ct[move] = draw
else:
print(msg[4])
continue
else:
print(msg[5])
continue
print_court(ct, 9)
# Swap the player
if draw == 'X':
draw = 'O'
elif draw == 'O':
draw = 'X'
# Get the ame status
status = game_status(ct)
# print result of the game
if status == 'D':
print(msg[1])
else:
print(msg[2], status)
input(msg[3])
return
|
f62363bf4ffcdaee67c8e6d34a278ef59a0c6b8e | dtliao/Starting-Out-With-Python | /chap.5/08 p.229 ex.4 practice.py | 755 | 3.890625 | 4 | def allCost(l,i,g,o,t,m,totalAnnual):
print('Loan payment is $ ',format(l, ',.2f'))
print('Insurance expenses is $ ', format(i, ',.2f'))
print('Gas expenses is $ ', format(g, ',.2f'))
print('Oil expenses is $ ', format(o, ',.2f'))
print('Tires expenses is $ ', format(t, ',.2f'))
print('Maintenace expenses is $ ', format(m, ',.2f'))
print('The Total annual cost is $ ', format(totalAnnual, ',.2f'))
l=float(input('Enter the loan payment:'))
i=float(input('Enter the insurance expenses:'))
g=float(input('Enter the gas expenses:'))
o=float(input('Enter the oil expenses:'))
t=float(input('Enter the tires expenses:'))
m=float(input('Enter the maintenance expenses:'))
totalAnnual=l+i+g+0+t+m
allCost(l,i,g,o,t,m,totalAnnual)
|
ee55fc8d29595d66d91dc6cc6ca850d0e36cceb1 | lucasoliveiraprofissional/Cursos-Python | /Curso em Video/desafio027.py | 2,484 | 4.15625 | 4 | '''Fazer um programa que leia o nome completo de uma pessoa
mostrando em seguida o primeiro e o último nome separadamente'''
'''De acordo com a aula 09 o len pode ser usado
O len pode ser usado para medir a quantidade de qualquer coisa
Por exemplo, saber a quantidade de sobrenomes que uma pessoa tem:
quant= nome.split() - poderia ter evitado essa variável quant,
mas para ficar mais explícito, estou fazendo ess exemplo assim
(len(quant)-1)
fiz len-1 porque temos que considerar que o primeiro nome da pessoa
não pode ser considerado um sobrenome.
essa linha será exibida no print como a quantidade de sobrenomes que
a pessoa tem.
no desafio 022, fiz o seguinte:
print('A quantidade de caracteres do seu primeiro nome é: {0}\n'.
format(len(nome.split()[0])))
peguei/separei/isolei o nome.split, o indice 0 desse vetor, que nesse caso é o nome
e, num parenteses antes dele, que será feito depois do split,
contei a quantidade de caracteres dentro desse indice 0 do vetor nome.
o que eu tenho que fazer para exibir o sobrenome da pessoa, uma das formas de se fazer
que é a que eu farei:
vou fazer um nome.split
depois contar com o len a quantidade de elementos que tem dentro de nome.split.
Se no total, tiverem 4 elementos dentro de nome.split,
tenho que considerar 04 indo do índice 0 ao 3, porém não
04 como sendo o último índice do vetor, pois o último índice do
vetor é 03.
Sendo assim, para fazer qualquer coisa com o último sobrenome,
tenho que fazer a contagem de todos os elementos de nome.split
e no fim subtrair 01 dessa conta. Aí sim estarei trabalhando
com o último elemento daquele vetor.
len(nome.split()-1) - assim me refiro ao último elemento
nome.split()[(len(nome.split()-1))]
assim eu digo que, após separar o nome, vou trabalhar com o índice que
refere-se ao seu último elemento.
format(nome.split()[(len(nome.split()-1))] - assim ficará o format
(não sei se precisa dentro do [] desse primento parenteses que engloba
o len-1), mas vou testar mesmo assim, pode ser que não precise
print('último= {}\n'.format(nome.split()[(len(nome.split())-1))]))
'''
nome= str(input('Digite seu nome completo: ')).strip()
print('\nprimeiro: {}'.format(nome.split()[0]))
print('último: {}'.format(nome.split()[(len(nome.split())-1)]))
'''Consegui sozinho!!!, acho que esse foi o mais difícil
Tentei transformar o split em int(nome.split()), mas isso não daria certo
por isso usei o len, que pega a quantidade de algo, já em int''' |
fcdf5acf6285185cda8436cb3082ba2c33cb3acb | SimeonTsvetanov/Coding-Lessons | /SoftUni Lessons/Python Development/Python Fundamentals September 2019/Problems And Files/19 EXERCISE OBJECTS AND CLASSES - Дата 25-ти октомври, 1430 - 1730/07. Articles.py | 1,507 | 4.125 | 4 | """
Objects and Classes - Exericse
Check your code: https://judge.softuni.bg/Contests/Practice/Index/1734#6
SUPyF2 Objects/Classes-Exericse - 07. Articles
Problem:
Create a class Article. The __init__ method should accept 3 arguments: title, content, author.
The class should also have 4 methods:
• edit(new_content) - changes the old content to the new one
• change_author(new_author) - changes the old author to with the new one
• rename(new_title) - changes the old title with the new one
• __repr__() - returns the following string "{title} - {content}: {author}"
Example:
Test Code:
article = Article("some title", "some content", "some author")
article.edit("new content")
article.rename("new title")
article.change_author("new author")
print(article)
Output:
new title - new content: new author
"""
class Article:
def __init__(self, title: str, content: str, author: str):
self.title = title
self.content = content
self.author = author
def edit(self, new_content):
self.content = new_content
def change_author(self, new_author):
self.author = new_author
def rename(self, new_title):
self.title = new_title
def __repr__(self):
return f"{self.title} - {self.content}: {self.author}"
article = Article("some title", "some content", "some author")
article.edit("new content")
article.rename("new title")
article.change_author("new author")
print(article)
|
83b9b2550ab5846af1d641163e2c27a1d5d455ea | luizmariz/cripto | /AL12.1/AL12.1.py | 2,504 | 3.875 | 4 | #Atividade de laboratorio 12.1
from math import sqrt
n = input()
for x in range(n):
numero = input()#calculo da ordem do grupo do numero primo
p = numero
fi = 1
for y in range(2,int(sqrt(numero)+1)):#existe algum fator em 2<= y <= raizdonumero
expoente = 0
while numero%y == 0: #enquanto o numero puder ser dividido por um fator ele sera
expoente+=1
numero = numero//y
if expoente != 0: #caso sim, numero nao e primo,como qlqr coisa^0=1, descartamos
fi = fi*((y**(expoente-1))*(y-1))
if numero != 1: #o algoritmo sempre acaba em 1, caso nao: numero e primo
expoente = 1
fi = fi*((numero**(expoente-1))*(numero-1))
ordem = fi
ordem = fi
lista_fator = []
lista_expoente = []
#algoritmo ingenuo de fatoracao
for y in range(2,int(sqrt(ordem)+1)):#existe algum fator em 2<= y <= raizdonumero
expoente = 0
while ordem%y == 0: #enquanto o numero puder ser dividido por um fator ele sera
expoente+=1
ordem = ordem//y
if expoente != 0: #caso sim, numero nao e primo,como qlqr coisa^0=1, descartamos
print y,expoente
lista_fator.append(y)
lista_expoente.append(expoente)
if ordem != 1: #o algoritmo sempre acaba em 1, caso nao: numero e primo
print ordem,1
lista_fator.append(ordem)
lista_expoente.append(1)
#inic do algoritmo de gauss
def poten_mod(num,exp,mod):
a = num
b = exp
c = mod
#pequeno teorema de fermat, se c e primo
A = a
R = 1
E = b%(c-1)
def impar(x): #funcao que ve se E e impar
if (x%2 != 0):
return True
while(E!=0):
if(impar(E) is True):
R = (R*A)%c
E = (E-1)//2
else:
E = E//2
A = (A*A)%c
return R
k = len(lista_fator)
i = 1
g = 1
#gauss
while i<= k:
a = 2
e = (p-1)//(lista_fator[i-1])
while poten_mod(a,e,p) == 1:
a += 1
e2 = (p-1)//(lista_fator[i-1]**lista_expoente[i-1])
h = poten_mod(a,e2,p)
print lista_fator[i-1],a,h
g = (g*h)%p
i += 1
print g
print "---" |
091ce2f726bcbeb52615bd5a34f4e96cf76b8f18 | seunghee63/study_web_python | /web_study_python/syntax/python_study_class.py | 2,732 | 3.65625 | 4 |
# coding: utf-8
# In[1]:
#self object만의 값
# In[3]:
class Person:
# class Person의 멤버변수
name = "홍길동"
number = "01077499954"
age = "20"
# class Person의 메소드
def info(self):
print("제 이름은 " + self.name + "입니다.")
print("제 번호는 " + self.number + "입니다.")
print("제 나이는 " + self.age + "세 입니다.")
if __name__ == "__main__":# main namespace를 의미합니다.
customer = Person()#Person의 객체 customer 생성
customer.info()#info 함수 호출
# In[4]:
class Person:
# class Person의 멤버변수
# __(double underscore)
# __는 클래스외부에서 클래스 멤버에 접근하지 못하게 하기위함
__name = "홍길동"
__number = "01077499954"
__age = "20"
@property #property 값을 갖고 옴
def name(self):
return self.__name
@name.setter #setter 값을 바꿔줌
def name(self, newName):
self.__name = newName
# class Person의 메소드
def info(self):
print("제 이름은 " + self.__name + "입니다.")
print("제 번호는 " + self.__number + "입니다.")
print("제 나이는 " + self.__age + "세 입니다.")
if __name__ == "__main__":# main namespace를 의미합니다.
customer = Person()#Person의 객체 customer 생성
customer.info()#info 함수 호출
print(customer.name)
customer.name="이태일"
print(customer.name)
# __gkgk__ : 매직메소드
# In[27]:
class Person :
def __init__(self, name):
self.__name = name
#def setname(self, newName):
# self.name = newName
@property
def name(self):
return self.__name
@name.setter
def name(self, newName):
self.__name = newName
if __name__ == "__main__":
p1 = Person("양승희")
p2 = Person("양승희")
p1.name="홍길동"
print (p1.name)
print (p2.name)
# In[30]:
#이터레이터
#매직메소드
#__iter__
#__next__
class Fibo :
def __init__(self) :
self.prv = 0
self.cur = 1
def __iter__(self):
return self
def __next__(self):
self.cur, self.prv = self.cur + self.prv , self.cur
return self.prv
f = Fibo()
for i in range(10):
print(next(f))
# In[31]:
#yield 반환값. yield를 만나면 ajacna => 제너레이터. 리터레이터화가됨.(셀수있는집합)
def fib():
prv = 0
cur = 1
while 1:
yield cur
cur, prv = cur+prv, cur
f = fib()
for i in range(10):
print(next(f))
#따로 next를 정의 해 주지 않아도 됨
# In[ ]:
#클래스
|
1efaf82d805d4d6e9ce6be477ce50b58a6140bdf | SagarNagarajan/MLproject | /PredictingStudentMarks.py | 1,874 | 4.09375 | 4 | import pandas as pd
import matplotlib as plt
import sklearn
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
df = pd.read_csv("C:\\Users\\Sagar\\Desktop\\Think42Labs\\student-performance.csv") # read the student-performance csv into a pandas dataframe
df['mm'] = df['mm'].replace('Male','Male,') # Clean data in the gender column
df['mm'] = df['mm'].replace('Female','Female,')
dummy = pd.get_dummies(df) # Write the categorical variables as dummies and print them out
print('Coding categorical variables:')
print(dummy.head())
Y = dummy['Total Marks'] # Use 'Total Marks' as the dummy variable and other variables as the indicator variables
X = dummy.drop('Total Marks',axis = 1)
lm = LinearRegression() # Build a linear regression model after splitting the examples into training and test sets
X_train,X_test,Y_train,Y_test = train_test_split(X,Y,test_size= 0.33,random_state = 5)
lm.fit(X_train,Y_train)
print("The mean square error on the training set is:" ) # Print out the mean error on the training and test tests and the estimated coefficients
print(np.mean((Y_train-lm.predict(X_train))**2))
print("The mean square error on the test set is :")
print(np.mean((Y_test-lm.predict(X_test))**2))
est_coeff = pd.DataFrame(list(zip(X.columns,lm.coef_)),columns = ('features','estimated_coefficients'))
print(est_coeff)
plt.scatter(lm.predict(X),Y)
plt.xlabel("Predicted Marks") # Plot the predicted marks vs marks graph for all training examples
plt.ylabel("Marks")
plt.title("Marks vs Predicted Marks")
plt.show()
|
d453bd9a2bf15433e5eeed2abdf488e90e216633 | davidfv7/TicTacToe | /main.py | 3,926 | 3.5 | 4 | import numpy as np
play = True
board=[i for i in range(0,9)]
print(board)
#Funcion para evaluar si el tablero esta lleno
def is_board_full(positions):
full = True
plainPositions = [i for pos in positions for i in pos]
for i in plainPositions:
if(i ==''):
full = False
break
return full
#Funcion para evaluar victoria o empate
def check_win(positions,player):
checkList = [pos for pos in positions]
win = True
winners=((0,1,2),(3,4,5),(6,7,8),(0,3,6),(1,4,7),(2,5,8),(0,4,8),(2,4,6))
for tup in winners:
win=True
for x in tup:
if(positions[x]!=player):
win=False
break
if(win==True):
break
return win
def is_match_over(positions,player):
plainPositions = [i for pos in positions for i in pos]
match = check_win(plainPositions,player)
return match
#funciones que asignan la posicion y el jugador
def setPositionA0():
return (0,0)
def setPositionA1():
return (1,0)
def setPositionA2():
return (2,0)
def setPositionB0():
return (0,1)
def setPositionB1():
return (1,1)
def setPositionB2():
return (2,1)
def setPositionC0():
return (0,2)
def setPositionC1():
return (1,2)
def setPositionC2():
return(2,2)
# Funcion que evalua la opcion
def moveCases(option,positions,player):
option = option.upper()
print(option)
switcher= {
"A0": setPositionA0(),
"A1": setPositionA1(),
"A2": setPositionA2(),
"B0": setPositionB0(),
"B1": setPositionB1(),
"B2": setPositionB2(),
"C0": setPositionC0(),
"C1": setPositionC1(),
"C2": setPositionC2(),
}
pos = switcher.get(option, "Invalid option")
positions[pos[0]][pos[1]] = player
while(play):
print(".................JUEGO DEL GATO...........................\n"
"Instrucciones: \n"
" 1. Observa la siguiente matriz \n"
" A B C \n"
" | | \n"
" 0 ____|_____|____ \n"
" | | \n"
" 1 ____|_____|____ \n"
" | | \n"
" 2 | | \n"
" \n"
" 2. Coloca la posición de tu jugada mediante coordenadas\n"
" como (A,0) o (C,2) \n"
" \n")
print("-------------::::COMIENZA EL JUEGO::::--------------------\n")
positions= [["","",""],["","",""],["","",""]]
p1 = "X"
p2 = "O"
actualplayer=p1
winner=False
while(winner==False):
while(is_board_full(positions)==False ):
print("%s move:" % actualplayer)
option = input()
moveCases(option,positions,actualplayer)
print(np.array(positions))
if(is_match_over(positions,actualplayer)==True ):
print("El ganador es: ",actualplayer)
winner=True
break
if(actualplayer=="X"):
actualplayer = "O"
else:
actualplayer="X"
if(is_board_full(positions)==True):
print( "¡¡EMPATE!!")
winner=True
print("¿Otra partida?")
another_one= input()
if(another_one.lower()=="N".lower()):
play=False |
09a951d4b85fe2c6f2a084ca1101e52d47a797c9 | rafaelperazzo/programacao-web | /moodledata/vpl_data/50/usersdata/142/17645/submittedfiles/contido.py | 491 | 3.671875 | 4 | # -*- coding: utf-8 -*-
from __future__ import division
#função
def elementoscomuns (a,b):
cont=0
for x in range(0,len(b),1):
for i in range(0,len(a),1):
if a[i]==b[x]:
cont=cont+1
return cont
#entradas e programa principal
n=input('Digite um valor n:')
m=input('Digite um valor m:')
a=[]
b=[]
for i in range(0,n,1):
a.append(input('Digite um valor:'))
for i in range(0,m,1):
b.append(input('Digite um valor:'))
#saídas
|
fc4052524b4a0e98eb77cb3a347af2633211df81 | JoaolSoares/CursoEmVideo_python | /Exercicios/ex002.py | 305 | 4.25 | 4 | nome = input('Qual è o seu nome?')
print('Estou lisongeado em te conhecer,', nome + '!')
print('-> A proxima é uma maneira com o .format que serve para formatar a variavel para encaixar no testo')
nome1 = input('qual é o seu nome?')
print('Estou lisongeado em te conhecer, {}!' .format(nome))
|
4b5e38b53111da11c1acbe377e0367f4380c206d | mohamedimmu/100_days_of_python | /day_005/challenge/challennge_5.1.py | 350 | 4.15625 | 4 | # 5.1 Average Height
student_heights = input("Input a list of student heights : ").split()
student_heights = [int(student_height) for student_height in student_heights]
sum_of_height = 0
for student_height in student_heights:
sum_of_height += student_height
average_height = round(sum_of_height/len(student_heights))
print(average_height)
|
4600dba0ab1754ad3f7817df8ce71191033edd8d | Nabilabilalla/python_maison | /maison.py | 3,822 | 3.90625 | 4 | from turtle import *
# Pour nommer la fenêtre de jeu
title("Le jeu du Nabila !")
def house():
begin_fill()
color('black', 'pink')
forward(141)
left(90)
forward(100)
left(45)
forward(100)
left(90)
forward(100)
left(45)
forward(100)
left(90)
goto(140, 100,)
forward(-141)
left(90)
goto(140, 0)
end_fill()
# end_fill()
width(4)
house()
up()
right(90)
fd(110)
down()
color('black', 'pink')
forward(141)
left(90)
forward(100)
left(45)
forward(100)
left(90)
forward(100)
left(45)
forward(100)
# draw a door
left(90)
forward(50)
left(90)
forward(50)
right(90)
forward(30)
right(90)
forward(50)
left(90)
up()
right(0)
fd(-110)
down()
down()
color('black')
forward(141)
left(90)
forward(100)
left(45)
forward(100)
left(90)
forward(100)
left(45)
forward(100)
# draw a door
left(90)
forward(50)
left(90)
forward(50)
right(90)
forward(30)
right(90)
forward(50)
left(90)
down()
up()
right(0)
fd(-110)
# house()
up()
right(0)
fd(-110)
# Rayon du cercle utilisé pour la tête du pendu
rayon=25
# Vitesse d'éxécution du dessin
speed("fast")
# Corde
width(3)
right(90)
# Tête
color("pink")
right(90)
begin_fill()
circle(rayon)
end_fill()
# Repositionner la flèche
up()
left(90)
fd(rayon*2)
down()
# Le corps
color("black")
right(360)
fd(100)
# Repositionner la flèche
up()
left(180)
fd(80)
down()
# Premier bras
right(125)
fd(50)
# Repositionner la flèche
up()
right(180)
fd(50)
down()
# Deuxième bras
left(75)
fd(50)
# Repositionner la flèche
up()
bk(50)
left(50)
fd(80)
down()
# Première jambe
left(45)
fd(60)
# Repositionner la flèche
up()
bk(60)
down()
# Deuxième jambe
right(90)
fd(60)
# Repositionner la flèche
up()
bk(60)
left(225)
fd(125)
left(90)
fd(8)
down()
# Oeil gauche
width(2)
left(45)
fd(8)
bk(4)
left(90)
fd(4)
bk(4)
left(180)
fd(4)
bk(4)
# Repositionner la flèche
up()
right(140)
fd(16)
down()
# Oeil droit
left(45)
fd(8)
bk(4)
left(90)
fd(4)
bk(4)
left(180)
fd(4)
bk(4)
end_fill()
up()
right(-50)
fd(110)
#arbre
# Rayon du cercle utilisé pour la tête du pendu
rayon=25
# Vitesse d'éxécution du dessin
speed("fast")
# Corde
width(3)
right(90)
# Tête
color("pink")
right(90)
begin_fill()
circle(rayon)
end_fill()
# Repositionner la flèche
up()
left(90)
fd(rayon*2)
down()
# Le corps
color("black")
right(360)
fd(100)
# Repositionner la flèche
up()
left(180)
fd(80)
down()
# Premier bras
right(125)
fd(50)
# Repositionner la flèche
up()
right(180)
fd(50)
down()
# Deuxième bras
left(75)
fd(50)
# Repositionner la flèche
up()
bk(50)
left(50)
fd(80)
down()
# Première jambe
left(45)
fd(60)
# Repositionner la flèche
up()
bk(60)
down()
# Deuxième jambe
right(90)
fd(60)
# Repositionner la flèche
up()
bk(60)
left(225)
fd(125)
left(90)
fd(8)
down()
# Oeil gauche
width(2)
left(45)
fd(8)
bk(4)
left(90)
fd(4)
bk(4)
left(180)
fd(4)
bk(4)
# Repositionner la flèche
up()
right(140)
fd(16)
down()
# Oeil droit
left(45)
fd(8)
bk(4)
left(90)
fd(4)
bk(4)
left(180)
fd(4)
bk(4)
#article derccc
end_fill()
up()
right(-50)
fd(250)
down()
color('black')
forward(141)
left(90)
forward(100)
left(45)
forward(100)
left(90)
forward(100)
left(45)
forward(100)
# draw a door
left(90)
forward(50)
left(90)
color('pink')
forward(50)
right(90)
forward(30)
right(90)
forward(50)
left(90)
width(4)
end_fill()
end_fill()
up()
right(0)
fd(-750)
down()
color('black')
forward(141)
left(90)
forward(100)
left(45)
forward(100)
left(90)
forward(100)
left(45)
forward(100)
# draw a door
left(90)
forward(50)
left(90)
color('pink')
forward(50)
right(90)
forward(30)
right(90)
forward(50)
left(90)
width(4)
end_fill()
down()
up()
right(0)
fd(-110)
# Message de fin
up()
right(140)
fd(30)
right(90)
fd(100)
down()
color("black")
write("Nabila !")
up()
left(290)
fd(450)
turtle.bgcolor("blue")
|
a5935a432fdc0751637a2ca524982d56688a385b | Skellbags/Previous-Programs | /CS 414/lab09/nim_list.py | 1,757 | 3.9375 | 4 | # 7: Do this last:
# Instead of 3 piles with 5 stones each,
# ask the user for the number of piles,
# and the number of stones per pile.
pile_sizes = []
count = 1
num_of_Piles = int(input("How many piles would you like"))
while True:
num_of_Stones = int(input("Enter the number of stones for Pile"))
pile_sizes.append(int(num_of_Stones))
num_of_Piles -= 1
count += 1
if num_of_Piles == 0:
break
player = 1
while True:
# Print a line to separate this move from the previous move
print ('\n' + '-' * 20)
for index in range(len(pile_sizes)):
print ('Pile', index+1, ':', pile_sizes[index], 'stones')
print ('Player', player, 'is next.')
# Prompt user for a pile, and do input validation
while True:
pile = int(input('which pile? '))
if not (1 <= pile and pile >= num_of_Piles):
print ('Invalid Input')
continue
else:
if pile_sizes[pile-1] <= 0:
print ('Pile ', pile_sizes[pile-1],' is empty. Choose another pile.')
else:
break
# Prompt user for number of stones, and do input validation
while True:
n_stones = int(input('Take how many stones? '))
if n_stones == 0 or n_stones == "":
print ('You MUST take some stones.')
elif pile_sizes[pile-1] < n_stones:
print ('There are only', pile_sizes[pile-1], 'stones in that pile.')
else:
break
pile_sizes[pile-1] -= n_stones
total_stones = sum(pile_sizes)
# Did anybody win?
if total_stones == 0:
if player == 1:
print ('Player 2 wins!')
else:
print ('Player 1 wins!')
break
player = 3 - player
|
ed936f5f49f560d90192d6abdde0b389aa6e786e | adwardlee/leetcode_solutions | /bfs/0444_graph_valid_treeII.py | 2,193 | 3.84375 | 4 | '''
Description
Please design a data structure which can do the following operations:
void addEdge(int a, int b):add an edge between node aa and node bb. It is guaranteed that there isn't self-loop or multi-edge.
bool isValidTree(): Check whether these edges make up a valid tree.
Example
Example 1
Input:
addEdge(1, 2)
isValidTree()
addEdge(1, 3)
isValidTree()
addEdge(1, 5)
isValidTree()
addEdge(3, 5)
isValidTree()
Output: ["true","true","true","false"]
'''
from collections import deque
class Solution:
"""
@param a: the node a
@param b: the node b
@return: nothing
"""
def __init__(self):
self.graph = []
def addEdge(self, a, b):
# write your code here
if [a,b] or [b,a] not in self.graph:
self.graph.append([a,b])
"""
@return: check whether these edges make up a valid tree
"""
def isValidTree(self):
# write your code here
graphlist = {}
graphdict = {}
visited = {}
edges = 0
for edge in self.graph:
if edge[0] not in graphlist:
visited[edge[0]] = 0
graphlist[edge[0]] = []
graphdict[edge[0]] = 1
else:
graphdict[edge[0]] += 1
graphlist[edge[0]].append(edge[1])
if edge[1] not in graphlist:
visited[edge[1]] = 0
graphlist[edge[1]] = []
graphdict[edge[1]] = 1
else:
graphdict[edge[1]] += 1
graphlist[edge[1]].append(edge[0])
edges += 1
if len(graphlist) != edges + 1:
return False
queue = deque()
for key in graphlist:
if len(graphlist[key]) == 1:
queue.append(key)
visited[key] = 1
length = len(graphlist.keys())
count = 0
while queue:
front = queue.popleft()
count += 1
for x in graphlist[front]:
graphdict[x] -= 1
if graphdict[x] <= 1 and not visited[x]:
queue.append(x)
visited[x] = 1
return count == length |
fed1f14b564e5203d2e47a7bddaacad3580076e8 | ripingit/python_crawler | /crawler.py | 1,675 | 3.53125 | 4 |
#代码来源:https://www.cnblogs.com/xuehaiwuya0000/p/10734004.html
# -*- coding: UTF-8 -
# 爬取豆瓣网站关于python的书籍,爬虫完一页后,点击后页菜单循环爬虫
# 缺点:逐页点击并获得数据较费时
import time
from selenium import webdriver
class url_surf(object):
def surf_web(self, url):
num = 1
driver = webdriver.Chrome("/Users/xjq/Downloads/chromedriver")
driver.get(url)
time.sleep(5)
while 1:
ele = driver.find_elements_by_class_name(r"detail")
file = open('python_data3.csv', 'a', encoding='utf-8')
file.write('_openid,title,bookurl \n')
for i in ele:
print('ele: %s' % i)
title = i.find_element_by_class_name("title-text")
bookurl = title.get_attribute('href')
file.write('oaqqm5GeNdxCFzEjeFcqDTCGGRtk,'+title.text +','+ bookurl)
file.write('\n')
print(num, bookurl)
num += 1
print('is searching page: %s' % num)
try: # 搜索到最后一页,next没办法点击或者没有后页的标签,则确认已结束
next_page = driver.find_element_by_class_name('next')
next_page.click()
except:
file.close()
print('game over')
break
time.sleep(5)
if __name__ == "__main__":
url = "https://book.douban.com/subject_search?search_text=Java+&cat=1001&start=0"
a = url_surf()
a.surf_web(url) # 爬取豆瓣网站关于python的书籍,爬虫完一页后,点击后页菜单循环爬虫
|
a7c40fc28768b463c1e2e8ab5c395a476f5d11e5 | majard/prog1-uff-2016.1 | /Dice Values.py | 305 | 3.859375 | 4 |
import random
dice = []
for index in range(10):
dice.append(random.randint(1, 6))
numbers = []
for i in range(6):
numbers.append(0)
for value in dice:
numbers[value - 1] += 1
print('Dice outcomes: {}'.format(dice))
print('Times each number was rolled: {}'.format(numbers))
|
a0371cdc58bf1f651d5e920023d7e66ee4be905b | Mihail-sev/guess-the-number-start | /main.py | 1,240 | 4 | 4 |
from random import randint
from art import logo
print (logo)
level = input ("Welcome to GuessHame.\nTry to guess number from 1 to 100.\n Choose your dificult level: 'hard' or 'easy'.\n")
rand_number = randint (1, 100)
if level == "easy":
attempts = 10
else:
attempts = 5
user_number = int(input(f"You have {attempts} attempts. \n Make you guess: "))
attempts -= 1
def check_number(checked_number):
""" Check guessed user number to correct answer"""
global user_number
if checked_number == rand_number:
print (f"You got it! Correct answer was {rand_number}")
return False
elif checked_number < rand_number:
user_number = int(input(f"Too low.\n Guess again.\n You have {attempts} attempts remaining to guess the number.\n \n Make you guess: "))
return True
elif checked_number > rand_number:
user_number = int(input (f"Too high.\n Guess again.\n You have {attempts} attempts remaining to guess the number.\n \n Make you guess: "))
return True
number_unguessed = True
while number_unguessed:
number_unguessed = check_number (user_number)
attempts -= 1
if attempts == 0:
number_unguessed = False
print (f"You've run out of guesses, you lose. The unguessed number is {rand_number}") |
d272d06fe24c55eb16adcb702dfa63bfcb3431d6 | mrklyndndcst/100-Days-of-Code-The-Complete-Python-Pro-Bootcamp-for-2022 | /Beginner/D002_Understanding_Data_Types_and_How_to_Manipulate_Strings/2.2.BMI_Calculator.py | 271 | 4.0625 | 4 | # 🚨 Don't change the code below 👇
height = input("enter your height in m: ")
weight = input("enter your weight in kg: ")
# 🚨 Don't change the code above 👆
# Write your code below this line 👇
a = float(height)
b = int(weight)
print(round(b/a**2)) |
83c6694ca3eefa4767dbad59c7754681c4306167 | spirit1234/location | /python_work/基础/第七章 用户输入和while循环/while处理列表字典.py | 1,074 | 3.828125 | 4 | # -*- coding-utf-8 -*-
unconfirmed_users = ['alice', 'brian', 'candace']
confirmed_users = []
while unconfirmed_users:
confirmed_user = unconfirmed_users.pop()
print('Verifying user: ' + confirmed_user.title())
confirmed_users.append(confirmed_user)
print("\nThe following users have been confirmed:")
for confirmed_user in confirmed_users:
print(confirmed_user.title())
# 删除包含特定值的所有列表元素
letter = ['a', 'b', 'e', 'c', 'd', 'e', 'f', 'g']
print(letter)
while 'e' in letter:
letter.remove('e')
print(letter)
# 如果把while变成if将只减少一个e
# 使用用户输入填充字典(现实生活中的调查)
responses = {}
polling_active = True
while polling_active:
name = input('What\'s your name? ')
response = input('How old are you? ')
responses[name] = response
repeat = input('Would you like to let another person respond? (yes/ no) ')
if repeat == 'no':
polling_active = False
for name, response in responses.items():
print(str(name) + ' \'s age is ' + str(response) + ' years old')
|
6320e4d63cf1607045fd7ab8765204153456a7d6 | pedrograngeiro/Exercicios-Python | /exercicios cap 3/exercicio 3.6.py | 1,154 | 4.21875 | 4 | # Escreva uma expressão que será utilizada para decidir se um aluno foi ou não aprovado.
# Para ser aprovado, todas as médias do aluno devem ser maiores que 7.
# Considere que o aluno cursa apenas três matérias, e que a nota de cada uma está armazenada nas seguintes
# variáveis: matéria1, matéria2 e matéria3.
materia1 = int(input("Digite a nota da materia1: "))
materia2 = int(input("Digite a nota da materia2: "))
materia3 = int(input("Digite a nota da materia3: "))
print("A nota da materia 1 foi %d" % (materia1))
print("A nota da materia 2 foi %d" % (materia2))
print("A nota da materia 3 foi %d" % (materia3))
# Condição Materia1
if materia1 >= 7:
materia1 = True
else:
materia1 = False
###########################
# Condição Materia2
if materia2 >= 7:
materia2 = True
else:
materia2 = False
###########################
# Condição Materia3
if materia3 >= 7:
materia3 = True
else:
materia3 = False
##########################
aluno = materia1 + materia2 + materia3
# True recebe o valor de 1 e se resultado = 3 aprovado.
if aluno == 3:
print("Aluno aprovado.")
else:
print("Aluno reprovado.") |
635b1c314f1bd733334a209236f275e55d13d678 | fancyQB/utils | /test.py | 4,813 | 3.546875 | 4 | import random
import numpy as np
from collections import Counter
#一行代码实现1-100之间的和
def thesum():
print(sum(range(1,101)))
#如何在一个函数内部修改全局变量
a = 100
def fun():
global a
a= 10
print(a)
#列出5个python标准库
# os sys re math datetime
#字典如何删除键和合并两个字典
def de():
A = dict(a=1, b=2)
del A['a']
print(A)
B = {'name':"zuo", 'age':'18'}
B.update(A)
print(B)
#列表去重
def ss():
lis = ['a', 'b', 'a', 'c']
lis1 = set(lis)
print(lis1)
# init方法初始化后会自动被调用,可接收参数
class Bike:
def __init__(self, newWheelNum, newCololr):
self.wheelNum = newWheelNum
self.Cololr = newCololr
def price(self):
print(200)
class A(object):
def __init__(self):
print('init方法', self)
def __new__(cls):
print('cls的id', id(cls))
print('new方法', object.__new__(cls))
#return object.__new__(cls)
return super().__new__(cls)
#列表[1,2,3,4,5],请使用map()函数输出[1,4,9,16,25],并使用列表推导式提取出大于10的数,最终输出[16,25] map(函数, 列表)
def get_result():
list1 = [1, 2, 3, 4, 5]
def fn(x):
return x**2
res = map(fn, list1)
res = [i for i in res if i>10]
print(res)
#随机生成整数,随机小数,0-1之间的小数方法
def get_rand():
result = random.randint(10,20)
res = np.random.randn(5)
ret = random.random()
print('正整数: ',result )
print('小数', res)
print('0-1小数', ret)
#去重,排序
def Deduplication():
s = "ajldjlajfdljfddd"
s = set(s)
s= list(s)
s.sort()
res = ''.join(s)
print(s)
#lambda函数
def get_la():
sum = lambda a,b:a*b
print(sum(3,4))
def order():
dic = {'name': 'zuoqiang', 'age': '25', 'city': '深圳', 'tel': '15926440508'}
lis = sorted(dic.items(), key=lambda i:i[0], reverse=False)
print(dict(lis))
def ex25():
a= "kjalfj;ldsjafl;hdsllfdhg;lahfbl;hl;ahlf;h"
b=''
for i in a :
if i!=';':
b +=i
res = Counter(b)
print(res)
def ex26():
import re
a = 'not 404 found 张三 99 深圳'
list1 = a.split(' ')
print(list1)
res = re.findall('\d+|[a-zA-Z]+', a)
for i in res:
if i in list1:
list1.remove(i)
print(list1)
new_str = ' '.join(list1)
print(new_str)
def ex27():
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def fn(x):
return x%2==1
new_list = filter(fn, a)
new_list = [i for i in new_list]
print(new_list)
def ex28():
a = [1,2,3,4,5,6,7,8,9,10]
a = [i for i in a if i%2==1]
print(a)
def ex30():
a = (1,)
b = (1)
c = ('1')
print (type(a),type(b),type(c))
def ex31():
l1 = [1, 5, 7, 9]
l2 = [2, 2, 6, 8]
l1.extend(l2)
print(l1)
l1.sort(reverse=False)
print(l1)
'''
python删除文件的方法 和linux删除文件的方法
python: os.remove(文件名字)
linux : rm 文件名
'''
def ex33():
import datetime
warning_time = str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))+' 星期:'+str(datetime.datetime.now().isoweekday())
print(warning_time)
def ex36():
try:
for i in range(5):
if i >3:
raise Exception('数字大于2')
except Exception as ret:
print(ret)
def ex39():
a = [[1, 2], [3, 4], [5, 6]]
x = [j for i in a for j in i ]
print(x)
import numpy as np
b = np.array(a).flatten().tolist()
print(b)
'''
@左:冒泡
def ex40():
list1 = [2,3,7,5,9,6]
for j in range(len(list1))[::-1]:
for i in range(j):
if list1[i]>list1[i+1]:
swap_num = list1[i]
list1[i] = list1[i+1]
list1[i+1] = swap_num
print(list1)
'''
#顺序
class ex40(object):
list1 = [2,3,4,5,9,6]
new_list = []
def get_min(self, list, new_list):
min_num = min(list)
list.remove(min_num)
new_list.append(min_num)
if len(list) > 0:
self.get_min(list, new_list)
return new_list
#单例模式
class Single:
__instance = None
def __new__(cls, *args, **kwargs):
if cls.__instance is None:
cls.__instance = object.__new__(cls, *args, *kwargs)
return cls.__instance
def __init__(self):
pass
#函数装饰器实现单例
def single(cls):
__instance = {}
def inner():
if cls not in __instance:
__instance[cls] = cls()
return __instance[cls]
return inner
@single
class A:
def __init__(self):
pass
#类装饰器实现单例
class Singleton:
def __init__(self, cls):
self._cls = cls
self._instance = {}
def __call__(self):
if self._cls not in self._instance:
self._instance[self._cls] = self._cls()
return self._instance[self._cls]
@Singleton
class B(object):
"""docstring for B"""
def __init__(self):
pass
def ex54():
a = '%.03f'%1.3335
print(a, type(a))
b = round(float(a), 1)
print(b)
b = round(float(a), 2)
print(b)
def ex55(k, v, dic={}):
dic[k] = v
print(dic)
def ex84(num)
if num>0:
res = num + ex84(num-1)
else:
return res
if __name__ == '__main__':
ex55('one', 1)
ex55('two', 2)
ex55('three', 3, {}) |
dd5193c9924d64962533b36a7b7a690004d8206a | marathohoho/leetcode-progress | /200.NumberofIslands/num_of_islands.py | 3,088 | 3.921875 | 4 | """
Given a 2d grid map of '1's (land) and '0's (water), count the number of islands.
An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically.
You may assume all four edges of the grid are all surrounded by water.
Example 1:
Input:
11110
11010
11000
00000
Output: 1
Example 2:
Input:
11000
11000
00100
00011
Output: 3
"""
# The first method is to use UnionFind Data structure to group the islands. First,
# we will compute number of individual islands (not accounting for those islands being connected to each other),
# then we will connect the neighboring islands, and at each connection, we will decrease the counter.
# The final counter value will be the number of separate islands
class DSU :
def __init__(self, grid) :
rows, cols = len(grid), len(grid[0])
self.par = [-1] * (rows * cols)
self.rank = [0] * (rows * cols)
self.counter = 0
for i in range(rows) :
for j in range(cols) :
if grid[i][j] == 1 :
self.par[i * cols + j] = i * cols + j
self.counter += 1
def find(self, x) :
if self.par[x] != x :
self.par[x] = self.find(self.par[x])
return self.par[x]
def union(self, x, y) :
xp, yp = self.find(x), self.find(y)
if xp != yp :
if self.rank[xp] > self.rank[yp] :
self.par[yp] = xp
elif self.rank[xp] < self.rank[yp] :
self.par[xp] = yp
else :
self.par[xp] = yp
self.counter -= 1
class Solution :
def _valid(self, grid, row, col) :
rows, cols = len(grid), len(grid[0])
return row >= 0 and col >= 0 and row < rows and col < cols and grid[row][col] == 1
def numIslands(self, grid) :
if not grid or not grid[0] : return 0
dsu = DSU(grid)
rows, cols = len(grid), len(grid[0])
# combine an island with neighboring islands
neighbors = [(-1,0), (1,0), (0,-1), (0,1)]
for row in range(rows) :
for col in range(cols) :
if grid[row][col] == 1:
for neighbor in neighbors :
nr, nc = row + neighbor[0], col + neighbor[1]
if self._valid(grid, nr, nc) :
dsu.union(row * cols + col, nr * cols + nc)
return dsu.counter
# the second solution is to DFS to explore all the neighbors
# first we traverse the matrix, and on the first accountance with an island,
# we count += 1 and dfs from that cell.
# Inside the dfs, we check the validity of the cell, and if it is equal to 1, we mark it as 0, and dfs from there
class Solution2 :
def numIslands(self, grid) :
if not grid or not grid[0] : return 0
rows, cols = len(grid), len(grid[0])
counter = 0
for i in range(rows) :
for j in range(cols) :
if grid[i][j] == 1 :
counter += 1
self._dfs(grid, i, j)
return counter
def _dfs(self, grid, row, col) :
rows, cols = len(grid), len(grid[0])
if row < 0 or col < 0 or row >= rows or col >= cols or grid[row][col] != 1 :
return
grid[row][col] = 0
self._dfs(grid, row+1, col)
self._dfs(grid, row-1, col)
self._dfs(grid, row, col+1)
self._dfs(grid, row, col-1)
if __name__ == "__main__" :
sol = Solution2()
print(sol.numIslands([[1,1,0,0,0],[1,1,0,0,0],[0,0,1,0,0],[0,0,0,1,1]]))
|
af633fa5df9a1324ac6b56fd49f03992188740d7 | AndriyKhymera/PythonStudy | /Exploration/StringExploration.py | 869 | 4.09375 | 4 | string_1 = "Can use apostrophe easily"
string_2 = 'Can\'t use apostrophe by alone'
# print("""
# Some multiply words
# text
# notice that tabs are still here
# that means all symbols are included
# """)
# print("Singe line example")
string_1 = "Python"
# print("some" "thing")
#
# print (len("Some "))
#
# # First character
# print (string_1[0])
# # The last character in string
# print (string_1[len(string_1) - 1])
# print (string_1[-1])
#
# print (string_1[0:2])
# print (string_1[-1:2])
# print (string_1[5:])
#
# print(string_1.upper())
# print(string_1.lower())
#
# print("Pi: " + str(3.14))
#
# #v2
# string_1 = "some %s formating" % ("Python")
# print string_1
# #v3
# print("Some format example here: {} and here: {}".format("'first word'", "'the second one'"))
## Throws an error cause String is immutable
# string_1[0] = 'b'
print(string_1[-2:])
|
8af857612aa1e678d6bfcbdbc285aaaf3b950b38 | lmorales17/cs61a | /hw/hw6.py | 4,704 | 4 | 4 | # Name: Luis Morales
# Login: cs61a-3w
# TA: Sharad Vikram
# Section: 120
# Q1.
def divide_by_fact(dividend, n):
"""Recursively divide dividend by the factorial of n.
>>> divide_by_fact(120, 4)
5.0
"""
if n == 1:
return dividend/n
return divide_by_fact(dividend / n, n - 1)
# Q2.
def group(seq):
"""Divide a sequence of at least 12 elements into groups of 4 or
5. Groups of 5 will be at the end. Returns a tuple of sequences, each
corresponding to a group.
>>> group(range(14))
(range(0, 4), range(4, 9), range(9, 14))
>>> group(tuple(range(17)))
((0, 1, 2, 3), (4, 5, 6, 7), (8, 9, 10, 11), (12, 13, 14, 15, 16))
"""
num = len(seq)
assert num >= 12
if num <= 24:
number_of_fives = num%4
ending_index = number_of_fives*5
four_multiple_list = seq[:ending_index]
counter1 = 0
four_grouped_list = ()
for numbers in four_multiple_list:
counter1 += 1
if counter1%4 == 0:
four_grouped_list += tuple((range(seq[counter1-4], seq[counter1])))
five_multiple_list = seq[ending_index:]
counter2 = 0
five_grouped_list = ()
for numbers in five_multiple_list:
counter2 += 1
if counter2%5 == 0:
five_grouped_list += tuple((range(seq[counter2-5], seq[counter2])))
final_list = four_grouped_list+five_grouped_list
return final_list
return (group(seq[0:12]), group(seq[12:]))
"""
====
==
========== <--- spatula underneath this crust
========
||
||
\||/
\/
========== }
== } flipped
==== }
========
"""
# Q3.
def partial_reverse(lst, start):
"""Reverse part of a list in-place, starting with start up to the end of
the list.
>>> a = [1, 2, 3, 4, 5, 6, 7]
>>> partial_reverse(a, 2)
>>> a
[1, 2, 7, 6, 5, 4, 3]
>>> partial_reverse(a, 5)
>>> a
[1, 2, 7, 6, 5, 3, 4]
"""
reversing_list = lst[start:]
reversed_list = []
for k in reversing_list:
reversed_list = [k] + reversed_list
lst[start:] = reversed_list
return
# Q4.
def index_largest(seq):
"""Return the index of the largest element in the sequence.
>>> index_largest([8, 5, 7, 3 ,1])
0
>>> index_largest((4, 3, 7, 2, 1))
2
"""
assert len(seq) > 0
largest_index = 0
size_of_largest_index = 0
n = range(0, len(seq))
for index in n:
if seq[index] > size_of_largest_index:
size_of_largest_index = seq[index]
largest_index = index
return largest_index
# Q5.
def pizza_sort(lst):
"""Perform an in-place pizza sort on the given list, resulting in
elements in descending order.
>>> a = [8, 5, 7, 3, 1, 9, 2]
>>> pizza_sort(a)
>>> a
[9, 8, 7, 5, 3, 2, 1]
"""
n = len(lst)
def foo(new_list, a):
if a != n:
largest_element = index_largest(new_list[a:])
partial_reverse(new_list, a + largest_element)
partial_reverse(new_list, a)
foo(new_list, a+1)
foo(lst, 0)
# Q6.
def make_accumulator():
"""Return an accumulator function that takes a single numeric argument and
accumulates that argument into total, then returns total.
>>> acc = make_accumulator()
>>> acc(15)
15
>>> acc(10)
25
>>> acc2 = make_accumulator()
>>> acc2(7)
7
>>> acc3 = acc2
>>> acc3(6)
13
>>> acc2(5)
18
>>> acc(4)
29
"""
total = []
def accumulate(addition):
total.append(addition)
return sum(total)
return accumulate
# Q7.
def make_accumulator_nonlocal():
"""Return an accumulator function that takes a single numeric argument and
accumulates that argument into total, then returns total.
>>> acc = make_accumulator_nonlocal()
>>> acc(15)
15
>>> acc(10)
25
>>> acc2 = make_accumulator_nonlocal()
>>> acc2(7)
7
>>> acc3 = acc2
>>> acc3(6)
13
>>> acc2(5)
18
>>> acc(4)
29
"""
total = 0
def accumulate(addition):
nonlocal total
total += addition
return total
return accumulate
# Q8.
# Old version
def count_change(a, coins=(50, 25, 10, 5, 1)):
if a == 0:
return 1
elif a < 0 or len(coins) == 0:
return 0
return count_change(a, coins[1:]) + count_change(a - coins[0], coins)
# Version 2.0
def make_count_change():
"""Return a function to efficiently count the number of ways to make
change.
>>> cc = make_count_change()
>>> cc(500, (50, 25, 10, 5, 1))
59576
"""
"*** YOUR CODE HERE ***"
|
d1da3baf9053e7c5139df8322daf31fef54cc37f | dhruvarora93/Algorithm-Questions | /Array Problems/prefix to postfix.py | 401 | 3.84375 | 4 | def prefix_to_postfix(string):
stack = []
operators = ['+','-','/','*']
for i in string[::-1]:
if i not in operators:
stack.append(i)
else:
operand1 = stack.pop()
operand2 = stack.pop()
temp = str(operand1) + str(operand2) + i
stack.append(temp)
return stack.pop()
print(prefix_to_postfix('*-A/BC-/AKL')) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.