blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
a60df26d281608f7fc18541abbabd820fe5a2696 | arkanttus/Scraper_Google | /bot_google.py | 911 | 3.5 | 4 | import requests
import urllib.request
from bs4 import BeautifulSoup as Bs
import os
import sys
def search(query):
url = "https://www.google.com/search?q=" + query
#header para simular o acesso vindo de um navegador
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}
response=requests.get(url, headers=headers)
soup = Bs(response.text, 'html.parser')
conts = soup.find_all(class_='rc')
#conts = soup.select('.rc > .r')
for cont in conts:
r = cont.find(class_='r')
textLink = r.find('a')
#textLink = cont.find('a')
texto, link = textLink.find(class_='ellip'), textLink['href']
print(texto.text)
print(link)
print('-----')
##### MAIN ######
query = sys.argv[1] #capturar parametro do terminal
search(query)
|
8b8251ec1f2467079b02c6f74ac55da7a77a73bb | CoatesK/Python-Notes | /returnbasics.py | 280 | 3.53125 | 4 | import math
def triarea(b, h):
area = b * h * (1 / 2)
return area
def divisibleByN(n, x):
if x % n == 0:
return True
else:
return False
def pythag(x, y, z, n):
if (x**n) * (y**n) == (z**n):
return true
else:
return false
|
6ce9c25c08ceff46838b4ebc86cdbd02ab982440 | zatostephen/python_programming | /Assignment1/density.py | 504 | 4.5625 | 5 | #create variables that request an expected input from the user.ie input for mass and vol.
mass=float(input("Enter mass: "))
volume=float(input("Enter volume: "))
#create a variable that stores the result of mass input received/volume input received.
density=mass/volume
# we call print function to display density as output
print("The Density of the Object is", density ,"m/l")
#create variables that stores the input received from the user to be used to calculate density
mass=input()
volume=input()
|
d3f54c542b14d7834966192895078b5f756adffb | kadarsh2k00/python-exercise | /Python GitHub/Q52.py | 125 | 3.75 | 4 | class Circle:
def __init__(self,radius):
self.area=(3.14*radius*radius)
C1=Circle(5)
print(C1.area)
|
e2144abfe73684aa626f43fe4cb72c43879b31eb | BoltzBit/LP | /Exercicios/ex09-4f.py | 208 | 4.09375 | 4 | #conversao de fahrenheit para kelvin
fahrenheit = float(input('Informe a temperatura em Fahrenheit: '))
kelvin = ((fahrenheit-32)*(5/9))+273.15
msg = 'Temperatura em Kelvin: {}'
print(msg.format(kelvin))
|
cbf85c62509f8e623d366c705f2b0111bd2dab18 | wangtao090620/LeetCode | /wangtao/leetcode-easy/0066.py | 577 | 3.65625 | 4 | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
# @Author : wangtao
# @Contact : wangtao090620@gmail.com
# @Time : 2020-07-16 00:07
from typing import List
class Solution:
def plusOne(self, digits: List[int]) -> List[int]:
res = []
while digits and digits[-1] == 9:
digits.pop()
res.append(0)
if not digits: # 全部是9,例如:99,999
return [1] + res
else:
digits[-1] += 1
return digits + res
if __name__ == '__main__':
s = Solution()
print(s.plusOne([0, 0, 9]))
|
c21d9ce87e81316c8dc18ea15f4228cb04152e8b | ashutosh-qa/PythonTesting | /PythonBasics/First.py | 509 | 4.28125 | 4 | # To print anything
print("This is first Pyhton program")
# How to define variable in python
a = 3
print(a)
# How to define String
Str="Ashutosh"
print(Str)
# Other examples
x, y, z = 5, 8.3, "Test"
print(x, y, z)
# to print different data types - use format method
print ("{} {}".format("Value is:", x))
# How to know data type, see result in output
print(type(x))
print(type(y))
print(type(z))
#create a variable with integer value.
p=100
print("The type of variable having value", a, " is ", type(p)) |
3cdbdec82678c60109b9558c593acb37912c43d5 | Kirtanshah2303/Auto-Moto | /model/Model1_rewrd.py | 884 | 4.25 | 4 | def reward_function(params):
'''
Example that penalizes slow driving. This create a non-linear reward function so it may take longer to learn.
'''
# Calculate 3 marks that are farther and father away from the center line
marker_1 = 0.1 * params['track_width']
marker_2 = 0.25 * params['track_width']
marker_3 = 0.5 * params['track_width']
# Give higher reward if the car is closer to center line and vice versa
if params['distance_from_center'] <= marker_1:
reward = 1
elif params['distance_from_center'] <= marker_2:
reward = 0.5
elif params['distance_from_center'] <= marker_3:
reward = 0.1
else:
reward = 1e-3 # likely crashed/ close to off track
# penalize reward for the car taking slow actions
# speed is in m/s
# we penalize any speed less than 0.5m/s
SPEED_THRESHOLD = 2
if params['speed'] < SPEED_THRESHOLD:
reward *= 0.5
return float(reward) |
f378a37cf5016a1360b0924f6fe10163fc4664f9 | andrewjscott/PandsWork | /week04/4_2guessExtra.py | 1,064 | 4.40625 | 4 | # Generates a random number between 0 and 100 which the user then has to try and guess
# Author: Andrew Scott
import random
# Defines a variable with a random number between 0 and 100 for the user to guess
numToGuess = random.randint(0,100)
# A variable that contains the value entered as the user's guess
guess = int(input("Guess the number: "))
# A loop that tells the user their guess is wrong when their guessed number is not equal to the initial number and continues to
# ask them to guess again
# The if statement lets the user know if their guess is lower than the initial number, otherwise it tells them it is too high
while guess != numToGuess:
if guess < numToGuess:
print("Wrong! Too low!")
else:
print("Wrong! Too high!")
guess = int(input("Please guess again: "))
# The previous loop ends when the number is correctly guessed and the variable guess is equal to numToGuess which leads to
# a string being printed that tells the user that they are correct
print("Yes! That is correct! The number is " + str(numToGuess) + ".") |
54e04571b912bb6411c7cab2c30ed9420da218f4 | SoumyaDey1994/JS-Exercises | /Python/Looping Statements/Loop Assignment.py | 933 | 4.0625 | 4 | import math
#print all numbers within a range
lower_limit= (int)(input("Enter lower bound: "));
upper_limit=(int)(input("Enter Upper bound: "));
for number in range(lower_limit,upper_limit+1):
print(number);
print();
#print all oddnumbers in a range
lower_limit= (int)(input("Enter lower limit: "));
upper_limit=(int)(input("Enter Upper limit: "));
print();
print("Odd Numbers in range {}-{} are: " .format(lower_limit,upper_limit));
for number in range(lower_limit,upper_limit+1):
if(number%2==1):
print(number);
print();
#check wheather a Number is Prime or not
numbertoCheck=(int)(input("Please Enter an Interger to Check: "));
flag=0;
for i in range(2,int(math.sqrt(numbertoCheck))+1):
if(numbertoCheck%i==0):
flag=1;
break;
else:
continue;
if(flag==0):
print("%d is a Prime Number" %(numbertoCheck));
else:
print("%d is a Non-Prime Number" %(numbertoCheck));
|
782068f85f62a124efe150fa4b77767500a6a062 | vincentmanna/Introprogramming-Labs | /tictactoe.py | 1,676 | 4.03125 | 4 | # CMPT 120 Intro to Programming
# Lab #7 – Lists and Error Handling
# Author: Vincent Manna
# Created: 2020-04-26
symbol = [" ", "x", "o"]
def printRow(row):
row = ['_'] * 9
pass
theBoard = {'7': ' ', '8': ' ', '9': ' ',
'4': ' ', '5': ' ', '6': ' ',
'1': ' ', '2': ' ', '3': ' '}
def printBoard(row):
print('+--------+')
print('|' + row['7'] + ' |' + row['8'] + ' |' + row['9'] + ' |')
print('+--------+')
print('|' + row['4'] + ' |' + row['5'] + ' |' + row['6'] + ' |')
print('+--------+')
print('|' + row['1'] + ' |' + row['2'] + ' |' + row['3'] + ' |')
print('+--------+')
pass
def markBoard(row, col):
if theBoard[move] == ' ':
theBoard[move] = xo
count += 1
else:
print("That spot is taken.\nTry another spot.")
pass
def getPlayerMove():
move = ' '
while True:
if move not in '1 2 3 4 5 6 7 8 9'.split():
print('Where is your next move? (Choose 1-9)')
move = input()
return int(move)
def hasBlanks(board):
for key in theBoard:
board_keys.append(key)
# if so, return True
return True
def main():
xo = symbol[1]
for i in range(100):
printBoard(theBoard)
print("Player 1 is X -- Player 2 is O \nPlayer 1 goes first!")
print("Turn:", xo, ". Which place?")
move = input()
if theBoard[move] == symbol[0]:
theBoard[move] = xo
else:
print("That spot is taken.\nTry another spot.")
continue
if xo == symbol[1]:
xo = symbol[2]
else:
xo = symbol[1]
main()
|
826fc6b0d263accc5627cdcd45e5d12403a8013d | geohotweb/programing | /ecuaciones/wason.py | 475 | 3.953125 | 4 | #Programa que determina cual es el mayor de tres numeros.
primer_num = int(input('Dame el numero 1: '))
segundo_num = int(input('Dame el numero 2: '))
tercer_num = int(input('Dame el numero 3: '))
if primer_num > segundo_num:
if primer_num > tercer_num:
mayor=primer_num
else:
mayor=tercer_num
else:
if segundo_num > tercer_num:
mayor=segundo_num
else:
if tercer_num > primer_num:
if tercer_num > segundo_num:
mayor=tercer_num
print('El mayor es:',mayor) |
2559d8047da2e95407af8ab701e4124230abca34 | markodraisma/lpp_uitwerkingen | /dubbel.py | 372 | 3.5 | 4 | #!/usr/bin/env python3
namen = [ 'els', 'els', 'els', 'els', 'henk', 'henk',
'jan', 'jan', 'john', 'piet', 'piet' ]
# voeg hieronder je eigen code toe
vorige = None
for i, naam in enumerate(namen):
if naam == vorige:
print(i, naam)
vorige = naam
print()
for i in range(1, len(namen)):
if namen[i] == namen[i-1]:
print(i, namen[i])
|
ac95992cb16f54ee5119874a9a8d163f8591f17f | pranavv1251/python-programs | /Prac3/P31.py | 211 | 4.15625 | 4 | list_1 = []
sorted = []
line = input("enter tuples:")
while(line != ''):
list_1.append(tuple(line.split()))
line = input()
print(list_1)
list_1.sort(key=lambda x: x[-1])
print("Sorted list is ", list_1)
|
aa70329db91ab59f3f2eb5f628177ed5df99c48b | mildzf/codeeval | /easy/self_describing_number.py | 995 | 3.828125 | 4 | #!usr/bin/env python3
"""Self Describing Numbers
Challenge Description:
A number is a self-describing number when (assuming digit positions are labeled
0 to N-1), the digit in each position is equal to the number of times that
that digit appears in the number.
If the number is a self-describing number, print out 1. If not, print out 0.
solution by: Mild Z Ferdinand
"""
from collections import Counter
import sys
input_file = sys.argv[1]
ctr = Counter()
def describe(cntr, nums):
for i in range(len(nums)):
digit = nums[i]
if int(digit) != int(cntr[str(i)]):
print(0)
return False
print(1)
return True
def main():
with open(input_file, 'r') as text:
for line in text:
nums = list(line.strip()) # create a list of digits
ctr.update(nums) # Update counter with tally of digits
describe(ctr, nums)
ctr.clear()
return True
if __name__ == "__main__":
main()
|
89c59bb5c8bc869ab6ec9285dbe999a66d5f4a63 | nicecoolwinter/note | /python/data/python_book_slides/code_1_2/numpy_ex2.py | 536 | 3.578125 | 4 |
# -*- coding: utf-8 -*-
import numpy as np
a = np.arange(5)
print("Element's type is", a.dtype)
# 維度
print("Shape is", a.shape)
print()
# 矩陣
from numpy import array, arange
m1 = array([[7, 8, 9], arange(3), [4, 5, 6]])
print("Element's type is", m1.dtype)
print("Shape is", m1.shape)
print(m1)
print()
m2 = array([[1, 2, 3], arange(3), [4, 5, 6]])
print(m2)
print()
m3 = m1 * m2 # not matrix multiplication
print(m3)
print()
m4 = np.dot(m1, m2) # 3.5 should support @
print(m4)
print()
|
9854c4281e0533a75e60078a97c06ea69741e11e | acheimann/PythonProgramming | /Book_Programs/Ch3/distance.py | 479 | 4.3125 | 4 | #distance.py
#calculates the distance betweeen two points given their coordinates
import math
def main():
print "This program calculates the distance between two points."
print
x1, y1 = input("Please enter the x and y coordinates of your first point: ")
x2, y2 = input("Please enter the x and y coordinates of your second point: ")
distance = math.sqrt((x2-x1)**2 + (y2-y1)**2)
print "The distance between these two points is", distance
main() |
78004231685ea9254f27f44706f4adabd877ce93 | TriptoAfsin/Tripto-s-Python-3-Basics | /2(Data Structure)/dictionary.py | 266 | 3.640625 | 4 | # like hashmap/ json
dict = {
'name': 'Tripto', #name, age, favcolor: " keys"
'age': 22,
'favColor': 'Green'
}
print(dict)
print(dict['age'])
dict['isStudent'] = True #adding a key
print(dict)
dict.pop('isStudent') #removing a value
print(dict)
|
d4fbbc85c55bbef718c39962f778bac3672acdb9 | aubcar/Python_code | /Project5/Tree.py | 787 | 3.625 | 4 | class Node:
"""
Args:
attribute (int): Index of the attribute to be test. (None if this is a leaf node)
label (int): Label of leaf node. (None if this is a decision node)
Attributes:
Attribute (int): Index of the attribute to be test. (None if this is a leaf node)
Label (int): Label of leaf node. (None if this is a decision node)
Positive_Branch (Node): The branch taken if the instance's attribute being tested is positive.
Negative_Branch (Node): The branch taken if the instance's attribute being tested is negative.
"""
def __init__(self, attribute=None, label=None):
self.Attribute = attribute
self.Label = label
self.Positive_Branch = None
self.Negative_Branch = None
|
97261f168bdab6c3817608267d9d32a6f96abaf8 | beardedsamwise/AutomateTheBoringStuff | /Chapter 4 - Lists/coinFlipStreaks.py | 571 | 3.828125 | 4 | import random
streakExists = 0
for experimentNumber in range(10000):
# Code that creates a list of 100 'heads' or 'tails' values.
results = ''
for experimentNumber in range(100):
coinFlip = random.randint(0, 1)
if coinFlip == 0:
results += 'H'
else:
results += 'T'
if (results.find('HHHHHH')):
streakExists += 1
elif (results.find('TTTTTT')):
streakExists += 1
# Code that checks if there is a streak of 6 heads or tails in a row.
print('Chance of streak: %s%%' % (streakExists / 100))
|
fb1b7b8d08c7ca37e51953e4405184a762661efb | mohdabrar728/lyric_generator | /poc.py | 838 | 3.59375 | 4 | import os
path = 'songs'
song_list = os.listdir(path)
print(song_list)
def scall():
for i in range(len(song_list)):
print(i+1, '.', song_list[i][:-4])
def select_song():
scall()
select = int(input("Select a song which you want to see lyrics of that:"))
if select in [i+1 for i in range(len(song_list))]:
print(f'You chose {song_list[select-1][:-4]}. Here you go:')
print()
print(f'{"-"*10}{song_list[select-1][:-4]}{"-"*10}')
with open(f"songs/{song_list[select-1]}", 'r') as lyric:
print(lyric.read())
else:
print("invalid option, press * and select from list")
select_song()
while True:
repeat = input("Press * to choose again or press any key to quit.")
if repeat == "*":
select_song()
else:
break
|
1c94b3b893346342d41284745b335e971f56ed48 | rubenpozo/Clase9 | /clase9.py | 290 | 4.03125 | 4 | import time
'''
print(time.localtime())
'''
'''
t=time.localtime()
year=t[0]
month=t[1]
day=t[2]
hour=t[3]
minute=t[4]
second=t[5]
print(year)
print(month)
print(day)
print(hour)
print(minute)
print(second)
'''
for x in range(1,61):
print(x)
for x in range(1,61):
print(x)
time.sleep(1) |
b421b91229e7055122d638e936c38be35cb679fc | kurissu/PythonProgramming | /frequency.py | 268 | 4.09375 | 4 | def freq(message,character):
count = 0
for char in message:
if char == character:
count = count +1
print('the frequency of '+character+' is ',end="")
return (count/len(message))
print(freq('this is to test the frequency of a charater e in the message','e'))
|
e2bbd5e12e36910dddb5c4f9aa5f85581416d867 | dpdahal/python7pm | /datatypes.py | 2,045 | 3.734375 | 4 | # x = 10
#
# print(dir(x))
# print(type(x))
# name = 'ram'
# print(dir(name))
# Numeric: int,float,complex
# int, float, string, boolean,none
# list,tuple, set, dic
# a = 1.98765787687
# print(type(a))
# print("%.2f" % a)
#
# print("".format())
# print(f"")
# a = 10j
# print(type(a))
# print(dir(a))
# print(type(a))
# x = "python"
# y = 123
# print(x + " " + str(y))
# print("{} {}".format(x, y))
# print(f"{x} {y}")
# type casting
# print(x.upper())
# print(type(x))
# print(dir(x))
# print(x)
# print(type(x))
# x = input("Enter any number: ")
# print(type(x))
# y = input("Enter any number: ")
# print(int(x) + int(y))
# x, y = input("Enter x, y").split(",")
# print(x)
# print(y)
# x = 20
# y = 30
# x, y, z = 20, 30, 40
# print(x)
# print(y)
# print(z)
# print(2 < 3)
# age = None
# print(age)
# x = 1323
# list
# like c: array
# data = ["ram", 1234, 34.56, 'sita']
# print(data[1])
# data = ["kalpan", "sophia", 'madan', 'xyz']
# print(data[1])
# students = [
# ["ram", 1234, 34.56, 'sita'],
# ["hari", 67, 65, 'gita'],
# ["kalpan", "sophia", 'madan', 'xyz'],
# ["laxmi", ["gopal", ["mobile"]], 'abc']
# ]
#
# print(students[3][1][1][0])
# print(students[2][1])
# data = ["ram", 'sita']
# data.append("abc")
# print(data)
# print(type(data))
# print(dir(data))
# print(data)
# data[0] = "hari"
# print(data)
# data = ['ram', 'sita', 'gita']
# res = data[0]
# print(res[0])
# print(data[0][:-1])
# Tuple
# data = ("ram", 'sita', 'gita', 'sophia', 12, 356)
# print(data[0])
# data[0] = "abc"
# print(type(data))
# SET - unique
# {} empty: disc - {'ram','sita'}
# data = {'ram', 'sita', 'gita', 'sophia', 'ram', 123, 456, 123}
# data1 = {"name": 'ram', 'gae': 20}
# print(data1)
# print(dir(data))
# print(data)
# print(type(data))
users = [
{"id": 1, "name": "Sophia", "address": "Kathmandu"},
{"id": 2, "name": "Hari", "address": [
{"tmp": "KTM"},
{"pre": "LTP"}
]
}
]
print(users[1]['address'][0]['tmp'])
# print(users[1]['name'])
# print(users['name'])
|
00b361010b234c8a3fe23157b157e6db4b37557a | dhita-irma/miniprojects | /datastructure/binarysearchtree.py | 6,204 | 4.03125 | 4 | class Node:
def __init__(self, value):
self.value = value
self.right = None
self.left = None
class BinarySearchTree:
def __init__(self):
self.root = None
self.count = 0
def __insert(self, current_node, value):
if value == current_node.value:
return False # Cannot insert duplicate
elif value < current_node.value:
if current_node.left:
return self.__insert(current_node.left, value)
else:
current_node.left = Node(value)
else:
if current_node.right:
return self.__insert(current_node.right, value)
else:
current_node.right = Node(value)
return True
def insert(self, value):
"""Add a node to a BST. Return True if value inserted,
otherwise, return False"""
if self.root:
insertion = self.__insert(self.root, value)
if insertion:
self.count += 1
return insertion
else:
self.root = Node(value)
self.count += 1
return True
def __find(self, current_node, value):
if value == current_node.value:
return True
elif value < current_node.value:
if current_node.left:
return self.__find(current_node.left, value)
else:
if current_node.right:
return self.__find(current_node.right, value)
return False
def find(self, value):
"""Find a value in the tree, return True if value exist.
Otherwise, return False."""
if self.root:
return self.__find(self.root, value)
else:
return False
def __delete(self, current_node, value):
"""Returns a a new subtree in which the node of 'value' is deleted.
Current_node may or may not change, depend on which node is deleted"""
if not current_node: # If current_node is None
return current_node
if current_node.value == value:
if not current_node.right: # Current_node has only left child or no child
return current_node.left
elif not current_node.left: # Current_node has only right child or no child
return current_node.right
else: # current_node has two children
successor = self.__inorder_successor(current_node)
current_node.value = successor.value
current_node.right = self.__delete(current_node.right, current_node.value)
elif value < current_node.value:
current_node.left = self.__delete(current_node.left, value)
else: # Value > current_node.value
current_node.right = self.__delete(current_node.right, value)
return current_node
def __inorder_successor(self, current_node):
"""Return a new node in a subtree that is greater than current_node (root) and
smaller than everything else"""
current_node = current_node.right
while current_node.left:
current_node = current_node.left
return current_node
def delete(self, value):
"""Delete a node containing value in a tree"""
if self.root and self.find(value):
self.__delete(self.root, value)
self.count -= 1
return True
return False
def __preorder(self, current_node, item_list):
item_list.append(current_node.value)
if current_node.left:
self.__preorder(current_node.left, item_list)
if current_node.right:
self.__preorder(current_node.right, item_list)
return item_list
def preorder(self):
"""Traverse Root - Left - Right"""
if self.root:
return self.__preorder(self.root, [])
else:
return []
def __postorder(self, current_node, item_list):
if current_node.left:
self.__postorder(current_node.left, item_list)
if current_node.right:
self.__postorder(current_node.right, item_list)
item_list.append(current_node.value)
return item_list
def postorder(self):
"""Traverse Left - Right - Root"""
if self.root:
return self.__postorder(self.root, [])
else:
return []
def __inorder(self, current_node, item_list):
if current_node.left:
self.__inorder(current_node.left, item_list)
item_list.append(current_node.value)
if current_node.right:
self.__inorder(current_node.right, item_list)
return item_list
def inorder(self):
"""Traverse Left - Root - Right"""
if self.root:
return self.__inorder(self.root, [])
else:
return []
def get_size(self):
return self.count
def __isvalid(self, current_node):
if not current_node: # This is the base case
return True
elif current_node.left and current_node.value <= current_node.left.value: # check if this is not a valid node
return False
elif current_node.right and current_node.value >= current_node.right.value: # check if this is not a valid node
return False
return self.__isvalid(current_node.left) and self.__isvalid(current_node.right) # This is the recursive case
def is_valid(self):
if self.root:
return self.__isvalid(self.root)
else:
return True
def min_value(self):
"""Return the smallest value in a BST. Return None if BST is empty."""
if not self.root:
return None
current_node = self.root
while current_node.left:
current_node = current_node.left
return current_node.value
def max_value(self):
"""Return the biggest value in a BST. Return None if BST is empty."""
if not self.root:
return None
current_node = self.root
while current_node.right:
current_node = current_node.right
return current_node.value
|
14a8a18651a3b96084c49ec0c0925274bbc3c825 | AnkitMittal0501/oopsPython | /Multithreading.py | 806 | 3.84375 | 4 | #Global interpretor lock prevent the threads running in parallel in python and can use one processor at a time
# Python use thread/task switching to perfrom multithreading and it executes rapidly that seems like task are running in parallel
# They are not running multiple task in parallel it seems like
import threading
import time
# In order to initiate a thread we need a function
def sleeper(n,name):
print("Hi , I am {}, going to sleep for 5 seconds\n".format(name))
time.sleep(n)
print("{} has woken up from sleep \n".format(name))
sleeper(5,"ankit")
#initialize a thread
t=threading.Thread(target=sleeper,name="thread1",args=(10,"thread1"))
t.start()
print("\nThread")
print("Thread")
print(help("threading"))
print(help("self"))
import math
print(math.sqrt(12.5))
def sum():
|
b7a089f256f79068ed1bc67a3309fb7da4178b7e | ruanymaia/cs50x | /cs50_problems_2020_x_sentimental_mario_more/mario.py | 843 | 4.125 | 4 | # Ruany Maia
# 10 Apr 2020
# Problem Set 6 - Mario - feeling more comfortable version
# This program asks the user for an integer between 1 and 8 and prints a pyramid with the integer's height
from cs50 import get_int
def main():
height = get_positive_int()
spaces = height - 1
bricks = 1
for row in range(height):
for space in range(spaces):
print(" ", end="")
for brick in range(bricks):
print("#", end="")
print(" ", end="")
for brick in range(bricks):
print("#", end="")
print()
if spaces == 0 and bricks == height:
break
else:
spaces -= 1
bricks += 1
def get_positive_int():
while True:
n = get_int("Height: ")
if n > 0 and n <= 8:
break
return n
main() |
29ee24bfeb2f9970b5017a4e26e1aebe73072e63 | SotaLuciano/Python_Lessons_HW | /Lesson_2.1_OOP.py | 2,822 | 3.5 | 4 | # NASLIDYVANN9
#class Base:
# def method(self):
# print("Hello")
#class Child(Base):
# def child_method(self):
# print("Hello from child method")
# def method(self):
# print("Hello from redefined method")
#obj = Child()
#obj.method()
#**********************************************************************************
#class Figure:
# def __init__(self, side = 0.0):
# self.side = side
#class Square(Figure):
# def draw(self):
# for i in range(self.side):
# print('* ' * self.side)
#class Triangle(Figure):
# def draw(self):
# for i in range(1, self.side + 1):
# print('* ' * i)
#class Test(Triangle, Square ):
# pass
#def main():
# square = Square(2)
# triangle = Triangle(5)
# square.draw()
# print()
# triangle.draw()
# test = Test(5)
# test.draw()
#if __name__ == '__main__':
# main()
#*****************************************************************************************************************
# HOME WORK
#2.1 Naslidyvann9
class Editor:
def __init__(self, ver = 2.7):
self.version = ver
def edit_document(self, way):
print('Sorry, but you are using free version, buy ProVersion to use editor')
def view_document(self, way):
try:
file = open(way, 'r')
except ValueError:
print('Wrong value "way"')
else:
str = file.read()
print(str)
file.close()
finally:
print('View ends')
class ProEditor(Editor):
def __init__(self, ver = 3.0):
self.version = ver
def edit_document(self, way):
try:
file = open(way, 'r+')
except ValueError:
print('Wrong value "way"')
else:
tmp = file.read()
print(tmp)
print("Do you want to write something?")
answer = input('Y/N:\t')
if(answer == 'Y' or answer == 'y'):
print()
str = input('Enter string: ')
file.write('\n'+str)
print()
file.seek(0)
tmp = file.read()
print(tmp)
file.close()
finally:
print('Edit ends')
def main():
Key = 'AAAA-AAA1-FVAS-BL2F'
KeyCheck = input('Enter key: ')
if Key == KeyCheck:
obj = ProEditor()
else:
obj = Editor()
print('Welcome to Editor ver. {}'.format(obj.version))
way = input('Enter way to file: ')
obj.view_document(way)
print()
obj.edit_document(way)
if __name__ == '__main__':
main() |
20a81209617236ef9df79349fcf915656bf658d5 | DarshAsawa/Cryptography | /substituion_cipher/autokey_cipher.py | 1,272 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
@author: dasaw
"""
def autokey_encrypt(plaintext,key):
cipher = ''
plaintext = plaintext.lower()
key = key.lower()
for letter in plaintext:
if letter == ' ':
cipher+= ' '
else:
cipher+=chr(((ord(letter) -97) + (ord(key) - 97)) % 26 + 97)
key = letter
return cipher
def autokey_decrypt(ciphertext,key):
plaintext = ''
ciphertext = ciphertext.lower()
key = key.lower()
for letter in ciphertext:
letter_val = ord(letter)
key_val = ord(key)
if letter == ' ':
plaintext+=' '
elif letter_val >= key_val:
plaintext_value = chr(((letter_val - 97) - (key_val - 97)) % 26 + 97)
plaintext+=plaintext_value
key = plaintext_value
else:
plaintext_value = chr(((letter_val - 97) - (key_val - 97) + 26) % 26 + 97)
plaintext+=plaintext_value
key = plaintext_value
return plaintext
plaintext = input("Enter the plaintext: ")
key = input("Enter the key: ")
cipher_text = autokey_encrypt(plaintext,key)
print("Encrypted Text: ", cipher_text)
decrypt_text = autokey_decrypt(cipher_text,key)
print("Decrypted Text: ", decrypt_text)
|
6cccd61562b61d12002bc625a9cc673cedc15466 | siamsubekti/lab-python | /lab-1/lab-1.py | 1,171 | 3.828125 | 4 | # SOAL 1 - Menghitung rata-rata
# Tuliskan program untuk Soal 1 di bawah ini
print("SOAL 1 :")
def find_average(num):
sum_num = 0
for t in num:
sum_num = sum_num + t
avg = sum_num / len(num)
return avg
print("The average is", find_average([18,25,3,41,5]))
print("========================")
print("\n")
# SOAL 2 - Menulis kelipatan bilangan
# Tuliskan program untuk Soal 2 di bawah ini
print("SOAL 2:")
num=eval(input("enter a number : "))
factors=[]
for i in range(1,num+1):
if num%i==0:
factors.append(i)
print ("Factors of {} = {}".format(num,factors))
print("========================")
print("\n")
print(" INTERMEZO")
def pattern(n):
k = 2 * n - 2
x = 0
for i in range(0, n):
x += 1
for j in range(0, k):
print(end=" ")
k = k - 1
for j in range(0, i + 1):
print(x, end=" ")
print("\r")
k = n - 2
x = n + 2
for i in range(n, -1, -1):
x -= 1
for j in range(k, 0, -1):
print(end=" ")
k = k + 1
for j in range(0, i + 1):
print(x, end=" ")
print("\r")
pattern(5)
|
1f178e891f44fe361fe2785ad1f5d7b7e9bb5a41 | gitkabi/streamlit | /demo.py | 619 | 4.03125 | 4 | import streamlit as st
import pandas as pd
# Display data
df = pd.read_csv("reli.csv")
# Method 1
st.dataframe(df,1000,1000) # (Value indicates the size)
# Method 2
st.table(df)
# Adding a color style from pandas
st.dataframe(df.style.highlight_max(axis=0, color= "red"))
st.table(df.style.highlight_max(axis=0, color= "green"))
# Method 3: Using superfunction st.write
st.write(df.head())
# Dislay json
st.json({'data' : 'name'})# (To display json format)
# Display code
mycode = """
def sayhello():
print("Hello Streamlit Lovers)
"""
st.code(mycode,language= 'python') # (To define code of ny language)
|
ab151f31b36cf70d1797116207cae55eff73c135 | Frank-XNS/AutomateAlignmentV2 | /Helper Scripts/mergeOOVs.py | 2,904 | 3.640625 | 4 | import os
import codecs
def file_exists(this_file: str) -> bool:
"""Check whether this_file exists (it should)"""
if not os.path.isfile(this_file):
print("\n")
print("{} does not exist.".format(this_file))
print("Please make sure you typed the name of the file correctly and that you are in the correct"
" directory.\n")
return False
else:
return True
def file_exists_but_shouldnt(this_file: str) -> bool:
"""Check whether this_file exists (it shouldn't)"""
if os.path.isfile(this_file):
print("\n")
print("{} already exists.".format(this_file))
print("Please choose another name or delete the existing file.\n")
return True
else:
return False
def no_forbidden_characters(this_new_item: str) -> bool:
"""Check whether this_new_item (file or folder) contains no forbidden characters"""
forbidden_characters = ['\\', '/', ':', '*', '?', '"', '<', '>', '|']
folder_name_wrong = any([char in forbidden_characters for char in this_new_item])
if folder_name_wrong:
print("\nYou cannot use the following characters in your file name:\n")
print(', '.join(forbidden_characters) + '\n')
return False
else:
return True
def merge_oov(to_merge: list, final_oov_name: str) -> None:
"""Merge the dictionaries in to_merge and name it final_dict_name"""
if (no_forbidden_characters(final_oov_name) and
not file_exists_but_shouldnt(final_oov_name) and
all([file_exists(this_file) for this_file in to_merge])):
allOovs = []
#This opens the oov
all_oov_entries = []
for this_file in to_merge:
with codecs.open(this_file, "r", encoding="utf-8") as current_oov:
current_oov_entries = current_oov.read()
print(current_oov_entries)
old_list_current_oov_entries = current_oov_entries.split("\n")
for entry in old_list_current_oov_entries:
if entry != '':
all_oov_entries.append(entry)
all_oov_entries = list(set(all_oov_entries))
all_oov_entries.sort()
new_oov_file_content = "\n".join(all_oov_entries)
with codecs.open(final_oov_name, 'w', encoding="utf-8") as new_oov_file:
new_oov_file.write(new_oov_file_content)
print("Success!")
if __name__ == '__main__':
done = False
to_merge = []
while not done:
this_oov = input("Enter the name of a oov for the merging (or Q to stop): ")
if this_oov == "Q" or this_oov == "q":
done = True
else:
to_merge.append(this_oov + ".txt")
if to_merge == []:
print("No dictionary entered!")
else:
final_oov_name = input("Enter the name of the final oov: ")
merge_oov(to_merge, final_oov_name + '.txt') |
d69e357d611d72bae09f66b08bb5ce5a652ab181 | emetowinner/Python-Class-Dike | /Python/3-Variables.py | 433 | 4.34375 | 4 | # Creating Variables
x = 5
y = "John"
print(x)
print(y)
x = 4 # x is of type INT
x = "Winner" # x is of type STR
print(x)
# Casting
x = str(3) # x will be "3"
y = int(3) # y will be 3
z = float(3) # z will be 3.0
print(x)
print(y)
print(z)
# Get The Type
x = 5
y = "John"
print(type(x))
print(type(y))
# Single or Double Quotes
x = "John"
# is the same as
x = 'John'
# Case-Sensitive
a = 4
A = "Winner"
# A will not overwrite a |
242b4b24fc5091f409ef1ac457b2ee7e729eadcb | frankyzf/myleetcode_python | /217_containDuplicate.py | 350 | 3.609375 | 4 | __name__ = 'feng'
class Solution(object):
def containsDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
nums.sort()
for i in xrange(0, len(nums)-1):
if nums[i] == nums[i+1]:
return True
return False
if __name__ == '__main__':
s = Solution() |
8bf5cf04eae7c6ba283ab7f3a08ebb2162ff7979 | pengfei99/Spark | /TextMining/Lesson2_Keyword_Extraction.py | 2,570 | 3.765625 | 4 | #################################################################################################################
#################################### Lesson2 keyword Extraction #################################################
#############################################################################################################
import pandas as pd
""" In this lesson, we will learn how to extract key word from articles, since they provide a concise representation
of the article’s content. Keywords also play a crucial role in locating the article from information retrieval
systems, bibliographic databases and for search engine optimization. Keywords also help to categorize the article
into the relevant subject or discipline.
We will use NLP techniques on a collection of articles to extract keywords
"""
""" About the dataset
The dataset which we use is from Kaggle (https://www.kaggle.com/benhamner/nips-papers/home). Neural Information
Processing Systems (NIPS) is one of the top machine learning conferences in the world. This dataset includes the
title and abstracts for all NIPS papers to date (ranging from the first 1987 conference to the current 2016 conference).
The nips-papers.csv contains the following columns:
- id,
- year,
- title,
- event_type,
- pdf_name : the name of the pdf file
- abstract : abstract of the paper
- paper_text : paper main content body
In this lesson, we focus on the concept of keyword extraction, so we only use abstracts of these articles to extract
keywords, because full text search is time consuming
"""
################################# 2.0 Key stages #########################################
"""
1. Text pre-processing
a. noise removal
b. normalisation
2. Data Exploration
a. Word cloud to understand the frequently used words
b. Top 20 single words, bi-grams and tri grams
3. Convert text to a vector of word counts
4. Convert text to a vector of term frequencies
5. Sort terms in descending order based on term frequencies to identify top N keywords
"""
########################## 2.1 Text pre-processing #########################################
############# 2.1.1 Load the dataset ################
df=pd.read_csv('/DATA/data_set/spark/pyspark/Lesson2_Keyword_Extraction/nips-papers.csv', delimiter=',',error_bad_lines=False)
abstractDf=df[['id','year','title','abstract']]
abstractDf.to_csv('/tmp/abstract1.csv',sep='|', header=True, index=False)
#print(heads)
############ 2.1.2 Fetch word count for each abstract #############################
|
65af2368f8573c528eca69f258ca5ac627a3c0c7 | hashtagmurica/ManVSMachine | /game_elements.py | 16,965 | 3.5 | 4 | import pygame
from pygame import *
import random
SCREEN = pygame.Rect((0, 0, 960, 640))
LEVEL = pygame.Rect((0, 0, 1600, 1600))
# global variables to track the player and ai scores
ai_score = 0
player_score = 0
'''
Player class, Camera, and other GameObjects
Reference: https://stackoverflow.com/questions/14354171/
'''
class Camera(object):
def __init__(self, level_size):
self.state = level_size
def apply(self, target):
return target.rect.move(self.state.topleft)
def update(self, target):
l = target.rect.left
t = target.rect.top
self.state = pygame.Rect((SCREEN.centerx-l, SCREEN.centery-t, self.state.width, self.state.height))
class GameObject(pygame.sprite.Sprite):
def __init__(self, pos, length, width):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((length, width))
self.rect = pygame.Rect((pos), (length, width))
def update(self):
pass
class Tile(GameObject):
def __init__(self, pos):
super().__init__(pos, 20, 20)
self.image.fill(Color("#000000"))
class Goal(GameObject):
def __init__(self, pos):
super().__init__(pos, 20, 20)
self.image.fill(Color("#0033FF"))
class Wall(GameObject):
def __init__(self, pos, length, width):
super().__init__(pos, length, width)
self.image.fill(Color("#000000"))
class Player(pygame.sprite.Sprite):
def __init__(self, pos, color):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((40, 40))
self.image.fill(color)
self.rect = pygame.Rect((pos), (40, 40))
self.speed = 0
self.vert = 0
self.grounded = False
self.life_counter = 2000
self.win = False
self.isBot = False
self.goalX = 200
self.goalY = 170
def move(self, left, right, space, up, world):
# Process key input results:
# Moving left or right
if left:
self.speed = -10
if right:
self.speed = 10
# Jumping
if space or up:
if self.grounded:
self.vert -= 12
# Falling
if not self.grounded:
self.vert += 0.5
if not left and not right:
self.speed = 0
# Update position
self.rect.left += self.speed
self.collision(self.speed, 0, world)
self.rect.top += self.vert
self.grounded = False
self.collision(0, self.vert, world)
def collision(self, speed, vert, world):
global ai_score
global player_score
for tile in world.tiles:
if pygame.sprite.collide_rect(self, tile):
# Reached goal object
if isinstance(tile, Goal):
self.vert = 0
self.speed = 0
self.win = True
if self.win and self.isBot:
ai_score += 1
if self.win and not self.isBot:
player_score += 1
world.createWorld(self, self, world.tiles, world.objects)
# Left and right collisions
if speed < 0:
self.rect.left = tile.rect.right
if speed > 0:
self.rect.right = tile.rect.left
# Top and bottom collisions
if vert < 0:
self.rect.top = tile.rect.bottom
if vert > 0:
self.rect.bottom = tile.rect.top
self.vert = 0
self.grounded = True
'''
SolutionPath class generates scheme for a beatable level
Random Level Generation, modeled after Spelunky
Reference: http://tinysubversions.com/spelunkyGen/
This algorithm creates a 4x4 matrix of rooms and assigns
each a value, 0-3
0 rooms are not part of solution path
1 rooms can be passed through left and right
2 rooms can be passed through left, right, and bottom
3 rooms can be passed through left, right, and top
Upon generation, the sequence of rooms is guaranteed to have
a continuous path from the top row to the bottom row
'''
class SolutionPath(object):
def __init__(self):
self.findSolution()
def findSolution(self):
# Level is the final level scheme
self.level = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
i = 0
j = random.randint(0,3)
# Make random room in top row a 1
self.level[i][j] = 1
# Decide where to go next randomly
# 1 or 2 = Left; 3 or 4 = Right; 5 = Down
# Moving left into left edge or right into right edge
# calls for moving down instead
while i < 3:
go = random.randint(1,5)
dropped = False
if go == 1 or go==2:
if j - 1 < 0:
if self.level[i][j] == 3:
continue
dropped = True
self.level[i][j] = 2
i += 1
else:
j -= 1
elif go==3 or go==4:
if j + 1 > 3:
if self.level[i][j] == 3:
continue
dropped = True
self.level[i][j] = 2
i += 1
else:
j += 1
else:
if self.level[i][j] == 3:
continue
dropped = True
self.level[i][j] = 2
i += 1
# Place next room
if dropped or self.level[i][j] == 3:
self.level[i][j] = 3
else:
self.level[i][j] = 1
'''
World class handles level creation and reset
upon contact with the goal
'''
class World(object):
def __init__(self, player, ai_players, tiles, objects):
self.player = player
self.ai_players = ai_players
for bot in ai_players:
bot.rect = pygame.Rect((800, 1520), (40, 40))
bot.win = False
self.player.rect = pygame.Rect((800, 1520), (40, 40))
self.player.win = False
self.tiles = tiles
self.objects = objects
self.room1 = [
" ",
" XXXXXXXXXXXX ",
"XXXXXXXXXXXXXXXXXXXX",
" ",
" ",
" XXXXX ",
" ",
" ",
" ",
" ",
" ",
" XXXXXXXX ",
" ",
" ",
" XXXXXXX ",
" ",
" ",
"XXXXXXX XXXXXXXXXX",
" XXXXXXXXXXXXXX ",
" "
]
self.room1_2 = [
" ",
" XXXXXXXXXXXXX XX",
"XXXXXXXXXXXXXXXXXXXX",
" XXXX ",
" XX ",
" ",
" ",
" ",
" ",
" XXXXXX ",
" ",
" ",
" ",
" ",
" ",
" XXXXXXXXXXX",
" XXXXXXXXX XXX",
" XXX XX XXXX ",
"XXXXXXXX ",
" "
]
self.room2 = [
" ",
" XXXXXXXXXXXXX XX",
"XXXXXXXXXXXXXXXXXXXX",
" XXXX ",
" ",
" ",
" XXX ",
" ",
" ",
" XXX ",
" ",
" ",
" ",
" ",
" ",
" XXXXX",
" ",
"XXXX ",
" XXX XXXX ",
" "
]
self.room2_2 = [
" ",
" XXXXXXXXXXXXX XX",
"XXXXXXXXXXXXXXXXXXXX",
" ",
" ",
" ",
" XXXXXXXXXX ",
" ",
" ",
" ",
" ",
" ",
" XXX ",
" ",
" ",
" XX ",
" ",
"XXXXX ",
" XXX XXXX",
" "
]
self.room3 = [
" ",
" XXX XX",
"XXXXXX XXXX",
" ",
" XXXXXX ",
" XXXXX ",
" ",
" ",
" ",
" XXXXXX ",
" ",
" ",
" ",
" ",
" ",
" XXXXXXXXXXX",
" ",
" XXXX XXXXXXXXX ",
" XXX XX XXXX X",
" "
]
self.room3_2 = [
" ",
" XXXXX XX",
"XXXXX XXXX",
" XXXX ",
" XX ",
" XX ",
" ",
" ",
" ",
" XXXXXX ",
" ",
" ",
" XXX ",
" ",
" ",
" XXXXXXXXXXX",
"XXXXXXXXX ",
" XXXXXXXXX ",
" XXX XX XXXX ",
" "
]
self.room0 = [
" ",
" ",
" ",
" ",
" XXXXXXXX ",
" ",
" ",
" ",
" XX ",
" ",
" ",
" ",
" ",
" ",
" XXX ",
" X ",
" ",
" ",
" ",
" "
]
self.room0_2 = [
" ",
" ",
" ",
" XXX ",
" ",
" ",
" ",
" ",
" XXXXXXXXX ",
" ",
" ",
" ",
" ",
" ",
" ",
" XXXXXXXX ",
" ",
" ",
" ",
" "
]
self.goalRoom = [
" ",
" XXXXXXXXXXXXX XX",
"XXXXXXXXXXXXXXXXXXXX",
" XXXX ",
" ",
" GG ",
" GG ",
" GG ",
" GG ",
" XXXXXX ",
" XX XX ",
" ",
" ",
" ",
" ",
" XXXXX",
" ",
"XXXX ",
" XXX XXXX ",
" "
]
self.createWorld(player, ai_players, tiles, objects)
'''
createWorld function takes in solution scheme as input
and generates playable world as output
The playable world is 1600 x 1600 pixels in area. Each
400 x 400 pixel section corresponds to a solution scheme
room. This sequence creates each playable level section
according to the solution scheme by following the appropriate
room instructions.
Room instructions are an array of strings with Xs or ' '
A tile is placed where every X is to create the section.
'''
def createWorld(self, player, ai_players, tiles, objects):
self.tiles.clear()
self.objects.empty()
self.player.rect = pygame.Rect((800, 1520), (40, 40))
self.player.win = False
soln = SolutionPath().level
goalRoom = True
for i in range(0, 4):
for j in range(0, 4):
choice = random.randint(0, 1)
if soln[i][j] == 0:
if choice:
soln[i][j] = self.room0
else:
soln[i][j] = self.room0_2
if soln[i][j] == 1:
if choice:
soln[i][j] = self.room1
else:
soln[i][j] = self.room1_2
if soln[i][j] == 2:
if choice:
soln[i][j] = self.room2
else:
soln[i][j] = self.room2_2
if goalRoom:
soln[i][j] = self.goalRoom
goalRoom = False
for bot in self.ai_players:
bot.goalX = (j * 400) + 200
if soln[i][j] == 3:
if choice:
soln[i][j] = self.room3
else:
soln[i][j] = self.room3_2
x = y = 0
x2 = y2 = 0
for i in range(0, 4):
for j in range(0, 4):
for row in soln[i][j]:
for col in row:
if col == "X":
tile = Tile((x, y))
tiles.append(tile)
objects.add(tile)
if col == "G":
goal = Goal((x, y))
tiles.append(goal)
objects.add(goal)
x += 20
y += 20
x = x2
x2 += 400
y -= 400
y += 400
x2 = 0
wall = Wall((0, 0), 20, 1600)
tiles.append(wall)
objects.add(wall)
wall = Wall((1580, 0), 20, 1600)
tiles.append(wall)
objects.add(wall)
wall = Wall((20, 0), 1560, 20)
tiles.append(wall)
objects.add(wall)
wall = Wall((20, 1580), 1560, 20)
tiles.append(wall)
objects.add(wall)
objects.add(self.player)
for bot in self.ai_players:
bot.win = False
bot.rect = pygame.Rect((800, 1520), (40, 40))
objects.add(bot)
self.tiles = tiles
self.objects = objects
|
ec85b972fd51c4f98eca084e95bcf66ed431cd0a | renhang0214/learn_python | /qz_day15_面向对象进阶/qz_day15_1.py | 694 | 3.9375 | 4 | # /usr/local/bin/python
# -*- coding: utf-8 -*-
# Author: Ren Hang
# 面向对象 ==>> 进阶1
# 在子类中执行父类的init方法,查看类的成员
class A:
def __init__(self):
print('A的构造方法')
self.a = '动物'
class B(A):
def __init__(self):
print('B的构造方法')
self.b = '猫'
# 执行父类的init方法
super(B, self).__init__()
A.__init__(self)
# 创建类的对象
c = B()
# 类的对象.__dict__ 查看类的成员
print(c.__dict__)
# 以下在qz_day15_2中导入
class C:
def __init__(self, name):
print('C的构造方法')
self.n = name
a = C('alex')
b = a.n
print(b)
|
f1554f9747881a65fb8e807b543745ed8f590eb4 | karolinanikolova/SoftUni-Software-Engineering | /2-Python-Fundamentals (Jan 2021)/Course-Exercises-and-Exams/07-Dictionaries/02_Exercises/09-ForceBook.py | 2,189 | 3.65625 | 4 | # 9. *ForceBook
# The force users are struggling to remember which side are the different forceUsers from, because they switch them too often.
# So you are tasked to create a web application to manage their profiles. You should store an information
# for every unique forceUser, registered in the application.
# You will receive several input lines in one of the following formats:
# {forceSide} | {forceUser}
# {forceUser} -> {forceSide}
# The forceUser and forceSide are strings, containing any character.
# If you receive forceSide | forceUser, you should check if such forceUser already exists,
# and if not, add him/her to the corresponding side.
# If you receive a forceUser -> forceSide, you should check if there is such a forceUser already and if so, change his/her side.
# If there is no such forceUser, add him/her to the corresponding forceSide, treating the command as a new registered forceUser.
# Then you should print on the console: "{forceUser} joins the {forceSide} side!"
# You should end your program when you receive the command "Lumpawaroo". At that point you should print each force side,
# ordered descending by forceUsers count, than ordered by name. For each side print the forceUsers, ordered by name.
# In case there are no forceUsers in a side, you shouldn`t print the side information.
data = input()
force_book = {"Light": [], "Lighter": [], "Dark": [], "Darker": []}
while not data == "Lumpawaroo":
if " | " in data:
force_side, force_user = data.split(" | ")
for value_list in force_book.values():
if force_user not in value_list:
force_book[force_side].append(force_user)
if " -> " in data:
force_user, force_side = data.split(" -> ")
for value_list in force_book.values():
if force_user not in value_list:
force_book[force_side].append(force_user)
else:
value_list.remove(force_user)
force_book[force_side].append(force_user)
print(f"{force_user} joins the {force_side} side!")
break
data = input()
print(force_book)
# for force_user, force_side in force_book.items():
|
d019a4f44ff2873e780807540b3a03f55e54b265 | aroon812/MATHML | /mlTests/oldKerasExperimentation/runNeuralNet.py | 1,094 | 3.6875 | 4 | """Allows the user to test the neural network
on images of their choosing
"""
import numpy
import os
import tensorflow as tf
from keras.models import model_from_json
from keras.preprocessing.image import load_img
from keras.preprocessing.image import img_to_array
from keras.preprocessing.image import array_to_img
#load the neural net in from json file
jsonFile = open('model.json', 'r')
loadedJsonModel = jsonFile.read()
jsonFile.close()
loadedModel = model_from_json(loadedJsonModel)
#load the neural net weights
loadedModel.load_weights("model.h5")
print("loaded model from disk")
loadedModel.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
#tests images showing 1 through 9 of the users choosing
fileNames = ["theBig01.png","theBig3.png","theBig4.png"]
for filename in fileNames:
img = load_img(str(os.getcwd()) + "/bigDigitsImages/" + filename, grayscale=True, target_size=(28, 28))
img = img_to_array(img)
img = img.reshape(1, 28, 28, 1)
img = img.astype('float32')
img = img / 255.0
print(loadedModel.predict_classes(img)) |
2c02e0e5710d55f01b6030745ed81f2d1512b564 | andiegoode12/Intro-to-Computer-Programming | /Assignments/Assignment29.py | 680 | 3.84375 | 4 | """
Andie Goode
10/8/15
While Loop: Input Validation
"""
#prompt user for ID number
ID = int(input("Enter your ID: "))
#set tries equal to 0
tries = 0
#loop until False
while True:
# if the id is valid print statement
if (0<= ID <= 199) or (1200<= ID <= 1350) or (ID == 2376):
print("ID accepted.")
break
#add 1 to tries
tries = tries + 1
# if try to submit more than 5 times, lock out of system
if tries == 5:
print("Invalid ID, you are locked out of the system.")
break
# if tries is less than five prompt for ID number again
print("Invalid ID, you may try again.")
ID = int(input("Enter your ID: "))
|
6c04b913ebbadfb9e6e57044d8a4cec6234c0a5d | aradonj/codingground | /New Project-20160628/main.py | 220 | 3.8125 | 4 | numb = int(input("Enter the number whose divisors would like to be known:"))
x = []
y = []
for i in range(1, (numb+1)):
x.append(i)
for element in x:
if ((numb % element) == 0):
y.append(element)
print(y) |
995095f131acc5d0bb950dd3f37ec8d723ee879f | devon6686/python3 | /exercise/insert_bisect.py | 735 | 3.71875 | 4 | #!/usr/bin/env python3
"""
使用bisect模块,插入一个数字到一个排序的序列中的位置;
"""
import bisect
import sys
HAYSTACK = [1, 2, 4, 5, 8, 11, 13, 14, 17, 19, 22, 25, 28, 31, 33, 38, 40]
NEEDLES = [0, 2, 4, 6, 10, 12, 14, 19, 23, 25, 29, 33, 36, 39, 41]
ROW_FMT = '{0:2d} @ {1:2d} {2}{0:<2d}'
def demo(bisect_fn):
for needle in reversed(NEEDLES):
position = bisect_fn(HAYSTACK, needle)
offset = position*' |'
print(ROW_FMT.format(needle, position, offset))
if __name__ == '__main__':
if sys.argv[-1] == 'left':
bisect_fn = bisect.bisect_left
else:
bisect_fn = bisect.bisect
print("DEMO:", bisect_fn.__name__)
print('haystack ->', ' '.join('%2d' % n for n in HAYSTACK))
demo(bisect_fn) |
df979c28f62687f8b33c24b1ddf38333723a0e40 | zs930831/Practice | /Demo/property_method.py | 613 | 3.828125 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
class Flight(object):
def __init__(self, name):
self.flight_name = name
def check_flightstatus(self):
print ("the flight is %s" % (self.flight_name))
return 0
@property
def flightstatus(self):
status = self.check_flightstatus()
if (status == 0):
print("ready to fly")
elif status == 1:
print("already fly")
@flightstatus.setter
def flightstatus(self, status):
print ("change flight status into %s" % (status))
f = Flight("CA222")
f.flightstatus
f.flightstatus = 1
|
94d8b06491b184eb0a984a3645b8075b12c2491c | MakeSchool-17/twitter-bot-python-noala | /freq-a-leak.py | 314 | 3.546875 | 4 | def histoblamo(text):
word_count = {}
for word in text:
try:
word_count[word] += 1
except KeyError:
word_count[word] = 1
return word_count
if __name__ == '__main__':
sample_text = ["hi", "doge", "i", "see", "doge", "hi"]
print(histoblamo(sample_text))
|
e0f62a813ebbcc84af82e6b267068e4c00df4cf3 | hudsone8024/CTI-110 | /P3T1_AreasOfRectangles_EricHudson.py | 705 | 4.3125 | 4 | #CTI-110
#P3T1- Areas of Rectangles
#Eric Hudson
#29 June 2020
#
# Get the demensions of rectangle 1.
length1 = int(input('Enter the length of rectangle 1: '))
width1 = int(input('Enter the width of rectangle 1: '))
# Get the demensions of rectangle 2.
length2 = int(input('Enter the length of rectangle 2: '))
width2 = int(input('Enter the width of rectangle 2: '))
# Calculate the areas of rectangles.
area1 = length1* width1
area2 = length2* width2
# Determine which rectangle has the greater area.
if area1> area2:
print('Rectangle 1 has the graeter area')
elif area2> area1:
print('Rectangle 2 has the greater area')
else:
print('Both rectangles are equal')
|
8ab8b8fcee34697a3331b3a48e304981a4cd71b6 | Sai-Sindhu-Chunduri/Python-programs | /patterns1.py | 174 | 3.53125 | 4 | '''
Print pattern:
if n=4:
*
* *
* * *
* * * *
'''
n=int(input())
for i in range(n):
for j in range(i+1):
print("*",end=" ")
print()
|
4efaaa5b1c626431f3e427955f6fb67b0957cb38 | Bngzifei/PythonNotes | /流畅的Python笔记/clip.py | 440 | 3.59375 | 4 | # coding:utf-8
# 在指定长度附件截断字符串的函数
def clip(text,max_len=80):
"""在max_len前面或后面的第一个空格处截断文本"""
end = None
if len(text) > max_len:
space_before = text.rfind(" ",0,max_len)
if space_before >= 0:
end = space_before
else:
space_after = text.rfind(" ",max_len)
if space_after >= 0:
end = space_after
if end is None:
end = len(text)
return text[:end].rstrip() |
94ba7e2485966861b7cbf9c05d643557a3db58ab | liamcarroll/python-programming-2 | /Lab_1.1/diamond_011.py | 258 | 3.515625 | 4 | #!/usr/bin/env python3
import sys
def diamond(size):
for i in range(-size+1,size):
i = abs(i)
print(end=' ' * i)
print(' '.join(['*'] * (size-i)))
def main():
n = int(sys.argv[1])
diamond(n)
if __name__ == '__main__':
main() |
79b7a8ee0d846d62c09e0d2de1e5e875d72df44c | arturo1467/Python-Projects | /Challenge Problem 38 Pykemon Simulation App.py | 14,612 | 3.875 | 4 | #Challenge Problem 38 Pykemon Simulation App
import random
#Clases
class Pykemon():
def __init__(self,name,element,health,speed):
self.name = name.title()
self.e_type = element
self.max_health = health
self.current_health = health
self.speed = speed
self.is_alive = True
def light_attack(self,enemy_pykemon):
damage = random.randint(15,25)
print("Pykemon " + self.name + " uses: ")
print("Type of move: light attack")
print("It deal with " + str(damage) + " damage.")
enemy_pykemon.current_health -= damage
def heavy_attack(self,enemy_pykemon):
damage = random.randint(0,50)
print("Pykemon " + self.name + " uses: ")
print("Type of move: Heavy attack" )
if damage < 10:
print("Attack missed")
else:
print("It deal with " + str(damage) + " damage.")
enemy_pykemon.current_health -= damage
def restore(self):
heal = random.randint(15,25)
self.current_health += heal
print(self.name + " recovered " + str(heal) + " of health.")
#Print a message stating that the Pykemon performed a specific attack.
#Use the Pykemon’s name and the name of the move.
print("Pykemon " + self.name + " used: restore")
if self.current_health > self.max_health:
self.current_health = self.max_health
#Clase que determinara cuando el pokemon se desmaye/muera
def faint(self):
if self.current_health <= 0:
self.current_health = 0
self.is_alive = False
print(self.name + " has been fainted. ")
input("Press enter to continue...")
def show_stats(self):
print("\nName: " + self.name)
print("Element type: " + self.e_type)
print("Health: " + str(self.current_health) + "/" + str(self.max_health))
print("Speed: " + str(self.speed))
#Clase hija de Pykemon
class Fire(Pykemon):
def __init__(self,name,element,health,speed):
super().__init__(name,element,health,speed)
#light attack, heavy attack, restore move, and special attack for all water Pykemon.
self.moves = ["Scratch", "Ember", "Light", "Fire Blast"]
# A attack that can damage a lot according of the pykemon type
def special_attack(self,enemy_pykemon):
#Use the Pykemon’s name and the name of the move.
print(self.name + "uses " + self.moves[3])
if enemy_pykemon.e_type == "GRASS":
print("This attack is super effective against grass pykemons")
damage = random.randint(35,50)
elif enemy_pykemon.e_type == "WATER":
print("This attack is not super effective against water pykemons")
damage = random.randint(5,10)
else:
damage = random.randint(10,30)
print("It deal with " + str(damage) + " damage.")
enemy_pykemon.current_health -= damage
def move_info(self):
print("\n" + self.name + " Moves: ")
print("-- Scratch --\nAn efficient attack...\nGuaranteed to do damage within the range of 15 to 25 damage points.")
print("-- Ember --\nA risky attack...\nCould deal up to 50 damage points or as little as 0 damage points.")
print("-- Light --\nA restorative move...\nGuaranteed to heal your Pykemon 15 to 25 health points.")
print("-- Fire Blast --\nA powerful FIRE based attack...\nGuaranteed to deal MASSIVE damage to GRASS type Pykemon.")
class Grass(Pykemon):
def __init__(self,name,element,health,speed):
super().__init__(name,element,health,speed)
#self.name = "Spatol"
#self.e_type = "GRASS"
#self.health = 89
#self.speed = 10
self.moves = ["Vine Whip", "Wrap", "Grow", "Leaf Blade"]
def move_info(self):
print("\n" + self.name + " Moves: ")
print("-- Vine Whip --\nAn efficient attack...\nGuaranteed to do damage within the range of 15 to 25 damage points.")
print("-- Wrap --\nA risky attack...\nCould deal up to 50 damage points or as little as 0 damage points.")
print("-- Grow --\nA restorative move...\nGuaranteed to heal your Pykemon 15 to 25 health points.")
print("-- Leaf Blade --\nA powerful GRASS based attack...\nGuaranteed to deal MASSIVE damage to WATER type Pykemon.")
# A attack that can damage a lot according of the pykemon type
def special_attack(self,enemy_pykemon):
#Use the Pykemon’s name and the name of the move.
print(self.name + "uses " + self.moves[3])
if enemy_pykemon.e_type == "WATER":
print("This attack is super effective against grass pykemons")
damage = random.randint(35,50)
elif enemy_pykemon.e_type == "FIRE":
print("This attack is not super effective against water pykemons")
damage = random.randint(5,10)
else:
damage = random.randint(10,20)
print("It deal with " + str(damage) + " damage.")
enemy_pykemon.current_health -= damage
class Water(Pykemon):
def __init__(self,name,element,health,speed):
super().__init__(name,element,health,speed)
#self.name = "Pyonx"
#self.e_type = "WATER"
#self.health = 80
#self.speed = 4
#light attack, heavy attack, restore move, and special attack for all water Pykemon.
self.moves = ["Bite", "Splash", "Dive", "Water Cannon"]
# A attack that can damage a lot according of the pykemon type
def special_attack(self,enemy_pykemon):
#Use the Pykemon’s name and the name of the move.
print(self.name + "uses " + self.moves[3])
if enemy_pykemon.e_type == "FIRE":
print("This attack is super effective against grass pykemons")
damage = random.randint(35,50)
elif enemy_pykemon.e_type == "GRASS":
print("This attack is not super effective against water pykemons")
damage = random.randint(5,10)
else:
damage = random.randint(10,20)
print("It deal with " + str(damage) + " damage.")
enemy_pykemon.current_health -= damage
def move_info(self):
print("\n" + self.name + " Moves: ")
print("-- Bite --\nAn efficient attack...\nGuaranteed to do damage within the range of 15 to 25 damage points.")
print("-- Splash --\nA risky attack...\nCould deal up to 50 damage points or as little as 0 damage points.")
print("-- Dive --\nA restorative move...\nGuaranteed to heal your Pykemon 15 to 25 health points.")
print("-- Water Cannon --\nA powerful WATER based attack...\nGuaranteed to deal MASSIVE damage to FIRE type Pykemon.")
class Game():
def __init__(self):
self.pykemon_elements = ["FIRE","WATER","GRASS"]
self.pykemon_names = ['Chewdie', 'Spatol','Burnmander', 'Pykachu', 'Pyonx', 'Abbacab', 'Sweetil', 'Jampot',
'Hownstooth', 'Swagilybo', 'Muttle', 'Zantbat', 'Wiggly Poof', 'Rubblesaur']
self.battles_won = 0
#Metodo que se encargara de crear un pykemon al azar, retornara un pykemon
def create_pykemon(self):
health = random.randint(70,100)
speed = random.randint(1,10)
element = random.choice(self.pykemon_elements)
name = random.choice(self.pykemon_names)
if element == "FIRE":
random_pykemon = Fire(name,element,health,speed)
elif element == "WATER":
random_pykemon = Water(name,element,health,speed)
else:
random_pykemon = Grass(name,element,health,speed)
return random_pykemon
#Metodo encargado de escoger un pykemon
def choose_pykemon(self):
starters = []
while len(starters) < 3:
#Crear un pykemon llamando al metodo create_pykemon dentro de la clase actual (game)
new_pykemon = self.create_pykemon()
valid_pykemon = True
for i in starters:
#Check if the given starter’s name is equal to the currently created Pykemon’s name or if the starter’s element is equal to the
#currently created Pykemon’s element. We do not want repeated
#Pykemon names or elements in our starter options.
if i.name == new_pykemon.name or i.e_type == new_pykemon.e_type:
valid_pykemon = False
if valid_pykemon:
starters.append(new_pykemon)
for i in starters:
#LLamo al metodo show stats para mostrar sus stats
i.show_stats()
#Llamo al metodo move_info para mostrar los movimientos que tiene dicho pokemon
i.move_info()
#Presenta 3 pykemons diferentes para que el usuario eliga uno de ellos
print("\nDaniel Camberos presents you with three Pykemon:")
print("(1) - " + starters[0].name)
print("(2) - " + starters[1].name)
print("(3) - " + starters[2].name)
valid_move = True
while valid_move:
choice = int(input("Which Pykemon would you like to choose: "))
if choice < 1 or choice > 3:
print("\nInvalid choice! try again..")
else:
chosen_pykemon = starters[choice-1]
print("\nCongratulations Trainer! You have choosen " + starters[choice-1].name)
valid_move = False
return chosen_pykemon
#Metodo encargado de seleccionar el ataque que el jugador desea realizar
def get_attack(self,pykemon):
print("What move would you like to do? ")
print("(1) - " + pykemon.moves[0])
print("(2) - " + pykemon.moves[1])
print("(3) - " + pykemon.moves[2])
print("(4) - " + pykemon.moves[3])
move_choice = int(input("Please enter your move choice: "))
print("\n------------------------------------------")
return move_choice
#Llama los metodos del ataque dependiendo del movimiento que desea realizar el jugador
def player_attack(self,move,player,computer):
if move == 1:
player.light_attack(computer)
elif move == 2:
player.heavy_attack(computer)
elif move == 3:
player.restore()
elif move == 4:
player.special_attack(computer)
#Verificar si el pykemon de la computadora ya se murio
computer.faint()
#Llama los metodos del ataque dependiendo del movimiento qrealiza la computadora
def computer_attack(self,player,computer):
move = random.randint(1,4)
if move == 1:
computer.light_attack(player)
elif move == 2:
computer.heavy_attack(player)
elif move == 3:
computer.restore()
elif move == 4:
computer.special_attack(player)
#Verificar si el pykemon del jugador ya se murio
player.faint()
def battle(self,player,computer):
#Obtener el movimiento del jugador llamando al metodo get_attack
move = self.get_attack(player)
#Si la velocidad del jugador es mayor o igual que la de la pc, jugador ataca primero, de lo contrario pc atacara primero
if player.speed >= computer.speed:
self.player_attack(move,player,computer)
if computer.is_alive == True:
self.computer_attack(player,computer)
else:
self.computer_attack(player,computer)
if player.is_alive == True:
self.player_attack(self.get_attack(player),computer,player)
#Main
print("Welcome to Pykemon!")
print("Can you become the worlds greatest Pykemon Trainer???")
print("\nDon't worry! Daniel Camberos is here to help you on your quest.")
print("He would like to gift you your first Pykemon!")
print("Here are three potential Pykemon partners.")
input("\nPress Enter to choose your Pykemon!\n")
playing_main = True
#Se crea el objeto de main
while playing_main:
game = Game()
#El jugador debe escoger un pykemon
player_pykemon = game.choose_pykemon()
player_pykemon.move_info()
input("\nYour jorney with " + player_pykemon.name + " begings now...Press Enter")
#Mientras el pykemon del jugado siga vivo...
while player_pykemon.is_alive:
#Se creara un pykemon para la computadora
computer_pykemon = game.create_pykemon()
print("\nOH NO! A wild" + computer_pykemon.name + " has approached!")
computer_pykemon.show_stats()
print("")
#Mientras el pykemon del jugador y de la computadora esten vivos...
while player_pykemon.is_alive and computer_pykemon.is_alive:
#Se llama al metodo battle y se le pasan los dos objetos (jugador y pc) para simular la pelea
game.battle(player_pykemon,computer_pykemon)
#Si ambos pykemons siguen vivos se mostraran las stats que llevan
if player_pykemon.is_alive and computer_pykemon.is_alive:
print("-------------------------------Your Stats---------------------------------------")
player_pykemon.show_stats()
print("")
print("---------------------------------Computer stats---------------------------------")
computer_pykemon.show_stats()
print("--------------------------------------------------------------------------------")
#Si solamente esta vivo el jugador quiere decir que la pc murio y se le sumara uno al atributo de las batallas ganadas
if player_pykemon.is_alive:
game.battles_won+=1
#En caso de que el pykemon del jugador ya no este vivo se saldra del loop y mostrara el sig mensaje
print("")
print(player_pykemon.name + " has fainted.")
print("You defeated a total of " + str(game.battles_won) + " Pykemons.")
#Se le notificara al usuario si quiere volver a jugar, en caso de que no se saldra del loop inicial
play_again = input("\nWould you like to play again? (y/n)")
if play_again.startswith("n"):
print("Thank you for playing Pykemon! ")
playing_main = False
|
b6e963b5767cbee750e1edc4d26c60a11ac631f2 | zkSNARK/pygrep | /pygrep_or.py | 2,286 | 3.8125 | 4 | #!/usr/bin/env python3
"""Utility script to mimic grep in python.
<filename> <search str1> <search str2> ... -o <outfile>
The -o is optional.
Example use1 : This example will search through the file pygrep.py for the strings '4e0000', 'Poll', and 'cancel'.
If any of the 3 are found in a given line, it will output the line to stdout.
python3 pygrep.py 4e0000 Poll cancel -o blah.txt
Example use 2: This example will search through the file pygrep.py for the strings '4e0000', 'Poll', and 'cancel'.
If any of the three are found in a given line, it will output the line to both stdout and to the file
blah.txt.
"""
import argparse
import pathlib
import re
import sys
from typing import List
class FilterNotFound(Exception):
pass
def grep(infile: str, filter_by: List[str], outfile=None):
print(f"Input file : {pathlib.Path(outfile).parent.absolute()}/{infile}")
if outfile:
print(f"writing output to {pathlib.Path(outfile).parent.absolute()}/{outfile}")
outfile = open(outfile, "w+")
print(f"Filtering by {' '.join(filter_by)}")
try:
with open(infile, "r") as file:
for line in file:
found = False
for filter_str in filter_by:
if re.search(filter_str, line):
found = True
break
if not found:
continue
if outfile:
outfile.write(line)
else:
print(line, end="")
except FileNotFoundError:
print(" failed to open input file", file=sys.stderr)
print(" usage : <filename> <search str1> <search str2> ...", file=sys.stderr)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('infile', type=str, help='input file name')
parser.add_argument('filter_by', type=str, nargs='*', help="filter your search by")
parser.add_argument('-o', '--outfile', type=str, required=False, help="output file")
args = parser.parse_args()
infile = args.infile
filters = args.filter_by
outfile = args.outfile
grep(args.infile, args.filter_by, args.outfile)
|
429bdf2e2b4c52ec57eaf1e9404cf85be3b944fe | awsirkis/I_405_ETL | /bus.py | 7,754 | 3.71875 | 4 | #=======================================================================
# General Documentation
#
# Agent for I-405 Simulation
#
#-----------------------Additional Documentation------------------------
# Modification History:
# - 19 May 2019: Bus.py created by Adam Sirkis
# - 04 June 2019: Bus.py finalized by Adam Sirkis
# Notes:
# - Developed for Python 3.x
#=======================================================================
import numpy as np
class Bus:
def __init__(self, x, y, gpm):
""" Constructor for a Bus object
Method Arguments:
- x : int-like representing location on the highway
- y : int-like representing location on the highway
- gpm : int-like representing the maximum number of squares a vehicle can move
Member vaiables:
- near_exit : bool representing if the object is clsoe to an exit object
- in_etl : bool repesenting which type of lane the us is in
- y : int representing vertical distance along the grid
- x : int representing horizontal lane position
- max : aximum number of squares for each move
- near_exit_condition : condition for being said to be near an exit
- exit : an exit object that the bus needs to be near to exit
"""
self.near_exit = False
self.in_etl = False
self.y = int(y)
self.x = int(x)
self.near_exit_condition = 0.5 * gpm #half mile
self.max = gpm
self.exit = None
def move(self, arr, timestep):
"""
MOve behavior for the Bus object
Method Arguments:
- arr : a Highway for the object to move on and update
- timestep : the time interval used
Returns:
An int indicating the number of squaes moved,
the updated highway, and
a bool about whether or not the bus exited
"""
self.exit = self._gen_exit(arr)
exited = False
total_moved = 0
if self.near_exit == False:
self.near_exit = self._near_exit(arr.grid_per_mile)
#NOTE : arr[] is the length, arr[][] is the width
if self.near_exit == True:
if arr.grid[self.y-1, self.x - 1, 0] == 0 and \
arr.grid[self.y, self.x - 1, 1] != 2 and \
arr.grid[self.y, self.x - 1, 0] == 0 and \
arr.grid[self.y+1, self.x - 1, 0] == 0:
squares_moved, arr = self._shift_left(arr)
total_moved += squares_moved
squares_moved, arr, exited = self._move_forward(arr)
total_moved += squares_moved
elif arr.grid[self.y+1, self.x, 0] == 0 and \
arr.grid[self.y + 2, self.x, 0] == 0:
squares_moved, arr, exited = self._move_forward(arr)
total_moved += squares_moved
elif arr.grid[self.y-1, self.x + 1, 0] == 0 and \
arr.grid[self.y, self.x + 1, 1] != 2 and \
arr.grid[self.y, self.x + 1, 0] == 0 and \
arr.grid[self.y+1, self.x + 1, 0] == 0:
squares_moved, arr, exited = self._shift_right(arr)
total_moved += squares_moved
squares_moved, arr, exited = self._move_forward(arr)
total_moved += squares_moved
elif arr.grid[self.y-1, self.x - 1, 0] == 0 \
and arr.grid[self.y, self.x - 1, 1] != 2 and \
arr.grid[self.y, self.x - 1, 0] == 0 and \
arr.grid[self.y+1, self.x - 1, 0] == 0:
squares_moved, arr, exited = self._shift_left(arr)
total_moved += squares_moved
squares_moved, arr, exited = self._move_forward(arr)
total_moved += squares_moved
if self.y + arr.grid_per_mile >= arr.length * arr.grid_per_mile:
exited = True
if exited == True:
arr.grid[self.y - 1, self.x, 0] = False
arr.grid[self.y, self.x, 0] = False
arr.grid[self.y + 1, self.x, 0] = False
arr.grid[self.y + 2, self.x, 0] = False
arr.grid[self.y - 2, self.x, 0] = False
if arr.grid[self.y, self.x, 1] == 1:
self.in_etl = True
else:
self.in_etl = False
return total_moved, arr, exited
def _move_forward(self, arr):
"""
Move the vehicle forward
Method Arguments:
- arr : highway for the object to move on
Returns:
An int indicating the number of squaes moved,
the updated highway, and
a bool about whether or not the bus exited
"""
squares_moved = 0
while arr.grid[self.y+1, self.x, 0] == 0 and \
arr.grid[self.y + 2, self.x, 0] == 0 and \
arr.grid[self.y + 3, self.x, 0] == 0 and \
squares_moved < self.max:
if self.y >= self.exit.y:
return squares_moved, arr, True
if self.y + arr.grid_per_mile >= arr.length * arr.grid_per_mile:
return squares_moved, arr, True
arr.grid[self.y - 1, self.x, 0] = False
arr.grid[self.y + 2, self.x, 0] = True
squares_moved += 1
self.y += 1
return squares_moved, arr, False
def _shift_left(self, arr):
"""
Move the vehicle left
Method Arguments:
- arr : highway for the object to move on
Returns:
An int indicating the number of squaes moved,
the updated highway, and
a bool about whether or not the bus exited
"""
for i in range(3):
arr.grid[self.y - 1 + i, self.x, 0] = False
arr.grid[self.y - 1 + i, self.x - 1, 0] = True
self.x -= 1
return 1, arr
def _shift_right(self, arr):
"""
Move the vehicle right
Method Arguments:
- arr : highway for the object to move on
Returns:
An int indicating the number of squaes moved,
the updated highway, and
a bool about whether or not the bus exited
"""
for i in range(3):
arr.grid[self.y - 1 + i, self.x, 0] = False
arr.grid[self.y - 1 + i, self.x + 1, 0] = True
self.x += 1
return 1, arr
def _near_exit(self, gpm):
"""
Determine if the bus is near an exit
Method arguments:
- gpm : int regarding the maximum amount the bbus can move
Reutrns:
- bool
"""
return self.y >= self.exit.y - (0.1 * gpm)
def _gen_exit(self, arr):
"""
Find the next exit to go to
Method arguments:
- arr : Highway to determine the next exit from
Returns:
- Exit object
"""
for i in range(len(arr.exits_arr)):
if self.y < arr.exits_arr[i].y:
return arr.exits_arr[i]
return arr.exits_arr[-1]
|
048aba81d551aec141a58373c93ed97e98aa5e1a | abhishekk3/Practice_python | /kthSmallest.py | 775 | 4.03125 | 4 | #Leetcode - 378. Kth Smallest Element in a Sorted Matrix
#Given an n x n matrix where each of the rows and columns are sorted in ascending order, return the kth smallest element in the matrix.
#
#Note that it is the kth smallest element in the sorted order, not the kth distinct element.
#Example 1:
#Input: matrix = [[1,5,9],[10,11,13],[12,13,15]], k = 8
#Output: 13
#Explanation: The elements in the matrix are [1,5,9,10,11,12,13,13,15], and the 8th smallest number is 13
def kthSmallest(matrix, k):
res = []
for i in range(len(matrix)):
for j in range(len(matrix[i])):
res.append(matrix[i][j])
res.sort()
return res[k-1]
matrix = [[-5]]
k = 1
final = kthSmallest(matrix, k)
print(final)
|
81b072a414af82138657faf8f8260410e2efbf99 | jspong/advent_of_code | /2020/09/solution.py | 1,128 | 3.515625 | 4 | import itertools
import operator
import sys
PREAMBLE = 25
window = []
def is_sum(num, window):
return any(num == a + b for a, b in itertools.permutations(window, 2))
def find_range(num, window):
print(num, window)
def all_ranges():
for i in range(len(window)):
for j in range(i, len(window)):
sub_window = window[i:j]
x = sum(sub_window)
if x == num:
print(sub_window)
yield sub_window
break
elif x > num:
break
return next(all_ranges())
results = []
all_nums = []
for line in sys.stdin:
num = int(line)
all_nums.append(num)
if len(window) < PREAMBLE:
print(num)
window.append(num)
continue
if is_sum(num, window):
print(num, 'VALID')
results.append((num, 'VALID'))
else:
print(num, 'INVALID')
results.append((num, 'INVALID'))
cont = find_range(num, all_nums)
print(min(cont) + max(cont))
break
window.append(num)
window[:1] = []
|
a4c215ce00be33c520ee3459e97cc9b94b42e812 | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_97/931.py | 1,662 | 3.671875 | 4 | def numshift(s,p):
#print s
#print 'is shifted by '+str(p)
strn=''
for i in range(p,len(s)):
strn = strn+s[i]
#print str
for i in range(0,p):
strn = strn+s[i]
#print strn
return int(strn)
def shift(s,count):
#print s
#print 'shifting by '+str(count)
start = count
flag = 0
while start<len(dig) and flag==0:
#print 'comparing '+str(dig[start])+'with '+str(dig[start-count])
if dig[start]>dig[start-count]:
flag = 1;
else:
start=start+1;
if flag==0:
last = start-count
start = 0
while start<count and flag==0:
#print 'comparing '+str(dig[start])+'with '+str(dig[last])
if dig[start]>dig[last]:
flag = 1;
else:
start=start+1;
last=last+1;
return flag
testcase = None
while not testcase:
try:
testcase = int(raw_input())
except ValueError:
print 'Invalid testcase'
#print 'testcase is '+str(testcase)
for imn in range(testcase):
biglist=[]
s = raw_input();
s_list = s.split(' ');
low = int(s_list[0]);
high = int(s_list[1]);
succount = 0
for input in range(low,high+1):
s = str(input);
length = len(s);
dig=[]
for i in range(length):
dig.append(int(s[i]))
#print 'input is '+s+' len is '+str(length)
if len(dig)==1:
succount = 0
else:
for j in range(len(dig)-1):
#print 'j is '+str(j)
num = numshift(s,j+1);
#print s+' is shifted by '+str(j+1)+' to '+str(num)
if num<=high and num>=low and num>int(s):
tstr = s+'.'+str(num)
if tstr not in biglist:
biglist.append(s+'.'+str(num))
succount=succount+1
print 'Case #'+str(imn+1)+': '+ str(succount) |
5144f9289548951fe144cdfa31342446ccb8d6ea | Vann09/python | /ejercicios random/tiposdatossimples.py | 4,802 | 4.40625 | 4 | #Escribir un programa que muestre por pantalla la cadena ¡Hola Mundo!.
#print ("¡Hola Mundo!")
#Escribir un programa que almacene la cadena ¡Hola Mundo! en una variable y luego muestre por pantalla el contenido de la variable.
#saludo = '¡Hola Mundo!'
#print (saludo)
#Escribir un programa que pregunte el nombre del usuario en la consola y después de que el usuario lo introduzca muestre por pantalla la cadena ¡Hola <nombre>!, donde <nombre> es el nombre que el usuario haya introducido.
#nombre = input ("¿Cómo te llamas? ")
#print (f"¡Hola {nombre}!")
#print ("¡Hola " + nombre + "!")
#Escribir un programa que muestre por pantalla el resultado de la siguiente operación aritmética .
#maths = ((3+2)/(2*5))**2
#print (maths)
#Escribir un programa que pregunte al usuario por el número de horas trabajadas y el coste por hora. Después debe mostrar por pantalla la paga que le corresponde.
#hours = float(input ("¿Cuantas horas trabajas? "))
#cost = float(input ("¿Cuanto cobras por hora? "))
#print (f"{hours*cost} € cobras.")
#Escribir un programa que lea un entero positivo,n, introducido por el usuario y después muestre en pantalla la suma de todos los enteros desde 1 hasta n .
#num = int(input("Dime un número: "))
#print (f"La suma de los primeros numeros enteros desde 1 hasta {num} es {(num*(num+1))/2}.")
#Escribir un programa que pida al usuario su peso (en kg) y estatura (en metros), calcule el índice de masa corporal y lo almacene en una variable, y muestre por pantalla la frase Tu índice de masa corporal es <imc> donde <imc> es el índice de masa corporal calculado redondeado con dos decimales.
#peso = float(input("Dime tu peso en kg: "))
#altura = float (input("Dime tu altura en metros: "))
#imc = peso/(altura)**2
#print (f"Tu indice de masa corporal es {imc:2.2f}")
#Escribir un programa que pida al usuario dos números enteros y muestre por pantalla la <n> entre <m> da un cociente <c> y un resto <r> donde <n> y <m> son los números introducidos por el usuario, y <c> y <r> son el cociente y el resto de la división entera respectivamente.
#num1 = int (input("Dime un número entero: "))
#num2 = int (input("Dime otro número: "))
#print (f"{num1} entre {num2} da un cociente {num1//num2} y un resto {num1%num2}.")
#Escribir un programa que pregunte al usuario una cantidad a invertir, el interés anual y el número de años, y muestre por pantalla el capital obtenido en la inversión.
#dinero = float(input("Cuanto quieres invertir: "))
#inter = float(input ("A que interés anual: "))
#años = int (input("A cuantos años: "))
#print (f"Obtendrás {dinero * (inter/100 + 1) ** años:1.2f} €.")
#Una juguetería tiene mucho éxito en dos de sus productos: payasos y muñecas. Suele hacer venta por correo y la empresa de logística les cobra por peso de cada paquete así que deben calcular el peso de los payasos y muñecas que saldrán en cada paquete a demanda. Cada payaso pesa 112 g y cada muñeca 75 g. Escribir un programa que lea el número de payasos y muñecas vendidos en el último pedido y calcule el peso total del paquete que será enviado.
#clown = 112
#doll = 75
#pclown = int(input ("Payasos a pedir: "))
#pdoll = int(input ("Muñecas a pedir: "))
#print (f"El peso total del pedido a enviar es de {(clown*pclown) + (doll*pdoll)} gramos")
#Imagina que acabas de abrir una nueva cuenta de ahorros que te ofrece el 4% de interés al año. Estos ahorros debido a intereses, que no se cobran hasta finales de año, se te añaden al balance final de tu cuenta de ahorros. Escribir un programa que comience leyendo la cantidad de dinero depositada en la cuenta de ahorros, introducida por el usuario. Después el programa debe calcular y mostrar por pantalla la cantidad de ahorros tras el primer, segundo y tercer años. Redondear cada cantidad a dos decimales.
#money = float(input("Dinero a depositar: "))
#interes = 4
#balance1 = money*(interes/100 + 1)
#print(f"El balance del primer año es de {balance1:1.2f}")
#balance2 = balance1*(interes/100 + 1)
#print(f"El balance del primer año es de {balance2:1.2f}")
#balance3 = balance2*(interes/100 + 1)
#print(f"El balance del primer año es de {balance3:1.2f}")
#Una panadería vende barras de pan a 3.49€ cada una. El pan que no es el día tiene un descuento del 60%. Escribir un programa que comience leyendo el número de barras vendidas que no son del día. Después el programa debe mostrar el precio habitual de una barra de pan, el descuento que se le hace por no ser fresca y el coste final total.
#pan = 3.49
#panp = 0.6
#panpsell = int(input("Pan vendido del dia anterior: "))
#print (f"El precio del pan es de {pan} €, si la barra no es del día se aplica un descuesto del {panp*100} %, por lo que su compra es de {panpsell*pan*(1-panp):1.2f} €.")
|
a5727c2579126f93607cd59aedb9fc0f45662db2 | ratsirarar/prework-repo | /week2/length_last_word.py | 323 | 3.625 | 4 | class Solution:
# @param A : string
# @return an integer
def lengthOfLastWord(self, A):
A = A.strip()
last_word_count = 0
for char in A:
if char == ' ':
last_word_count = 0
else:
last_word_count += 1
return last_word_count
|
4c0d257a97f37cd994b9efc80d7d115cceeee5fb | eliodeberardinis/Tools_Middleware_2_Dungeon | /DungeonProject/DungeonProject/CollisionDetection.py | 2,984 | 3.640625 | 4 | # This module contains the methods used for collision detection
from MathModule import *
import numpy as np
class CollisionSystem:
# Initializes the collision system instance
def __init__(self, useOptimizedAABBCollisions):
self.useOptimizedAABBCollisions = useOptimizedAABBCollisions
self.bbs = []
# Checks if the given BB overlaps with any of the of BB's in the list
def checkAndAddCollision(self, bb1):
if self.useOptimizedAABBCollisions:
aabb = np.array(BBToAABB(bb1))[np.newaxis]
if self.bbs == []:
self.bbs = aabb
else:
if checkCollisionAABBBulk(self.bbs, aabb):
return False
self.bbs = np.append(self.bbs, aabb, 0)
return True
else:
for bb in self.bbs:
if testCollision(bb1, bb):
return False
self.bbs.append(bb1)
return True
# Removes the last element from the collision system
def removeLast(self):
self.bbs = self.bbs[:-1]
# Checks if two BB's (Bounding Boxes) overlap
# A BB is defined by: [centre, [sizeX, sizeY, sizeZ]]
# where centre is a transform (4D vector),
# and sizeN is a pair of two values (each one for each direction)
# This collision test is based on checking collisions in the projections to the planes of each BB
# This is called the Separating Axis Theorem (reference: http://www.dyn4j.org/2010/01/sat/)
def testCollision(bb1, bb2):
return testCollisionOnProjectionPlane(bb1[0][3], bb1, bb2) and \
testCollisionOnProjectionPlane(bb1[0][3] + 90, bb1, bb2) and \
testCollisionOnProjectionPlane(bb2[0][3], bb1, bb2) and \
testCollisionOnProjectionPlane(bb2[0][3] + 90, bb1, bb2)
# Checks if two BB's collide when projected onto the vertical origin-passing plane given by the angle
def testCollisionOnProjectionPlane(angle, bb1, bb2):
# Get the corner points of each BB
bb1points = getBBpoints(bb1)
bb2points = getBBpoints(bb2)
# Project every point onto the plane
projbb1 = [projectPointOntoPlane(angle, point) for point in bb1points]
projbb2 = [projectPointOntoPlane(angle, point) for point in bb2points]
# Check if the AABB's that contain the projected points collide
aabb1 = AABB(projbb1)
aabb2 = AABB(projbb2)
return checkCollisionAABB(aabb1, aabb2)
# Checks if the two AABB's (Axis Aligned Bounding Box) collide
# Reference: https://developer.mozilla.org/en-US/docs/Games/Techniques/2D_collision_detection
def checkCollisionAABB(aabb1, aabb2):
for i in range(len(aabb1)):
if aabb1[i][0] >= aabb2[i][1] or aabb1[i][1] <= aabb2[i][0]:
return False
return True
# Checks if the given aabb collides with any of the given aabbs
def checkCollisionAABBBulk(aabbs, aabb):
checks = np.dstack((aabbs[:,:,0] < aabb[:,:,1], aabbs[:,:,1] > aabb[:,:,0]))
return np.any(np.all(np.all(checks, 2), 1)) |
9c7059592405e84be6abe3d3847075296b20d51f | happy96026/interview-prep | /coding_problems/jul/jul7.py | 675 | 3.78125 | 4 | from typing import List
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
matrix.reverse()
for i in range(len(matrix)):
for j in range(i):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
def main():
s = Solution()
m = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
s.rotate(m)
print(m)
m = [
[5, 1, 9, 11],
[2, 4, 8, 10],
[13, 3, 6, 7],
[15, 14, 12, 16]
]
s.rotate(m)
print(m)
m = [
[1],
]
s.rotate(m)
print(m)
m = []
s.rotate(m)
print(m)
if __name__ == '__main__':
main()
|
9566ed028203f6e6aabf6ce999a6d8cc1f10c73f | Larionov0/IraPoyasnyalki | /1/FUNCTIONS/9.py | 196 | 3.734375 | 4 | def incrementer(a):
return a + 1
numbers = [1, 5, 4, 6, 2, 3]
# for i in range(len(numbers)):
# numbers[i] = numbers[i] + 1
new_list = list(map(incrementer, numbers))
print(new_list)
|
838a542e73bc411b9272e5d5411497235ba2cf92 | catch0/python_may_2017 | /spence_peacock/scoresAndGrades.py | 488 | 4.09375 | 4 | import random
grade = randint(60,100)
def grademe(grade):
if grade>=60 and grade<70:
print "your score is: {} So your grade is a D".format(grade)
elif grade>=70 and grade<80:
print "your score is: {} So your grade is a C".format(grade)
elif grade>=80 and grade<90:
print "your score is: {} your grade is a B".format(grade)
elif grade>=90 and grade<101:
print "your score is: {} your grade is an A".format(grade)
|
bc4c3b9a8af473d7010cacc83d57cd84610488fd | helgalukaj/a2-helgalukaj | /a2_process_data.py | 2,118 | 3.5625 | 4 | import csv
contents = []
with open("a2_input.csv") as input_file:
for row in csv.reader(input_file):
contents = contents + [row]
fatality_before=0
fatality_after=0
for i in range (1,57):
fatality_before += float (contents[i][4])
fatality_after += float (contents[i][7])
fatality_before=fatality_before/56
fatality_after=fatality_after/56
print("""<!DOCTYPE html>
<html lang=\"en\">
<head>
<meta charset="utf-8" />
<title>Airline safety data</title>
<style>
table,td {
border: 2px solid black;
border-collapse: collapse;
}
table td, table th {
padding: 10px;
}
</style>
</head>
<body>
<h1>Airline safety</h1>
<p id="source">Dataset supplied by <a href="https://github.com/fivethirtyeight/data/tree/master/airline-safety">
Airline data</a></p>
<p>The aim of this assignment calculations was to emphasize the dercreasing number of fatalities by the technology improvement:</p>
<p>Average of fatalities 1985-1999 is: %02.f ;
<p>Average of fatalities 2000-2014 is: %0.2f ;
""" % (fatality_before,fatality_after))
#print("This assignment (assignment 2) hasn't been finished.")
#print("All it can do is print out the contents of a couple of cells of the file a2_input.csv:")
#print("Cell at index 0,0:")
#print(contents[0][0])
#print("Cell at index 0,1:")
#print(contents[0][1])
#print("Cell at index 1,0:")
#print(contents[1][0])
#print(contents)
#print(contents[0])
#print(contents[0][0])
#print(type(contents))
#print(type(contents[0]))
#print(type(contents[0][0]))
#print(contents[3][3])
#print(contents[23][2])
#av_seat = 0.0
#for i in range(1, 57):
# av_seat += float(contents[i][1])
#av_seat = av_seat / 56
#print(av_seat)
#dan_airlines=0
#for i in range(1,57):
# if int(contents[i][2])>=12:
# dan_airlines += 1
#print(dan_airlines)
#str1 = contents[0][3]+contents[3][1]
#str2 = 2*contents[0][3]
#print(str1)
#print(str2)
#print(type(str1),type(str2))
print("<table>")
for i in range(57):
print("<tr>")
for m in range(8):
print("<td>" + contents[i][m] + "</td>")
print("</tr>")
print("</table>")
print("""
</body>
</html>""")
|
073cb97a03dd2686fc4f3d820edb797b965194eb | Carloshtda/SistemaRSA | /input_treatment.py | 1,887 | 4.15625 | 4 | class InputTreatment:
'''Faz o tratamento de entrada para as mais diversas situações'''
def __init__(self):
self.input = 0
#Assegura um entrada Booleana
def boolean_input(self):
while True:
print("Input True or False:")
try:
self.input = input()
if self.input.lower() == 'true':
self.input = True
break
if self.input.lower() == 'false':
self.input = False
break
raise ValueError
except ValueError:
print('Wrong Input! Try Again.')
return self.input
# Assegura entrada com strings que contenham apenas letras minúsculos e números.
def message_input(self):
while True:
print("(Please use only lower case letters and numbers)")
try:
self.input = input()
for i in range(len(self.input)):
numerical_represent = ord(self.input[i])
if not (97 <= numerical_represent <= 122 or numerical_represent == 32 or 48 <= numerical_represent <= 57):
raise ValueError
break
except ValueError:
print('Input not supported! Try Again.')
return self.input
# Assegura entrada com inteiros dentro dos limites definidos.
def limited_int_input(self, bottom_lim, upper_lim):
while True:
print("Input a integer between {} and {}:".format(bottom_lim, upper_lim))
try:
self.input = int(input())
if not(bottom_lim <= self.input <= upper_lim):
raise ValueError
break
except ValueError:
print('Input not supported! Try Again.')
return self.input
|
dea76f90b31f191324e6b88b8bf21531bb967ebb | melodist/CodingPractice | /src/LeetCode/Check if All A's Appears Before All B's.py | 740 | 3.75 | 4 | """
https://leetcode.com/problems/check-if-all-as-appears-before-all-bs/
Implementation Problem
"""
#1. My Solution (46ms)
class Solution:
def checkString(self, s: str) -> bool:
n_a = n_b = 0
for c in s:
if c == 'a':
if n_b > 0:
return False
else:
n_a += 1
else:
n_b += 1
return True
#2. Other Solution (20ms)
class Solution:
def checkString(self, s: str) -> bool:
seen_b = False
for char in s:
if char == 'b':
seen_b = True
if char == 'a' and seen_b:
return False
return True
|
03b2ee108f32f52f1a6e8478f3b5e4f91ba73184 | zharro/algorithmic_toolbox | /week1/max_pairwise_product.py | 1,487 | 3.890625 | 4 | # python3
import random
def max_pairwise_product_fast(numbers):
maxIndex1 = -1
for index1 in range(len(numbers)):
if maxIndex1 == -1:
maxIndex1 = index1
continue
if numbers[index1] > numbers[maxIndex1]:
maxIndex1 = index1
maxIndex2 = -1
for index2 in range(len(numbers)):
if maxIndex2 == -1 and maxIndex1 != index2:
maxIndex2 = index2
continue
if index2 != maxIndex1 and numbers[index2] > numbers[maxIndex2]:
maxIndex2 = index2
return numbers[maxIndex1] * numbers[maxIndex2]
def max_pairwise_product(numbers):
n = len(numbers)
max_product = 0
for first in range(n):
for second in range(first + 1, n):
max_product = max(max_product,
numbers[first] * numbers[second])
return max_product
if __name__ == '__main__':
input_n = int(input())
input_numbers = [int(x) for x in input().split()]
result = max_pairwise_product_fast(input_numbers)
print(result)
# Stress test
# while True:
# n = random.randrange(2, 1000)
# numbers = random.sample(range(n), n)
# result = max_pairwise_product(numbers)
# resultFast = max_pairwise_product_fast(numbers)
# if(result != resultFast):
# print("Wrong answer! Numbers:{} Basic:{} Fast:{}".format(numbers, result, resultFast))
# break
# else:
# print("OK")
|
3c98d4e122891127a2a4a7a39f07ed1e209ee730 | iglidraci/functional-programming | /monads/failure.py | 757 | 3.5 | 4 | from typing import Callable
y = lambda x: str(neg(int(x)))
neg = lambda x: -x
class Failure:
def __init__(self, value, has_failed=False):
self.value = value
self._has_failed = has_failed
def bind(self, func: Callable):
if self._has_failed:
return self
try:
result = func(self.value)
return Failure(result)
except:
return Failure(None, True)
def __str__(self):
return f"{self.value}, {self._has_failed}"
def __or__(self, other: Callable):
return self.bind(other)
if __name__ == '__main__':
x = "10"
# print(y(x))
print(Failure(x).bind(int).bind(neg).bind(str))
y = Failure(x) | int | neg | str
print(y.value)
|
d66412a3ca16cc6c19e77f3c8d5abdf28d580775 | kailinshi1989/leetcode_lintcode | /200. Number of Islands.py | 2,281 | 3.5 | 4 | class Solution_1(object):
def numIslands(self, grid):
if not grid or len(grid) == 0 or len(grid[0]) == 0:
return 0
m = len(grid)
n = len(grid[0])
visited = [[False for i in xrange(n)] for i in xrange(m)]
result = 0
for i in xrange(m):
for j in xrange(n):
if visited[i][j] == False and grid[i][j] == '1':
result += 1
self.bfs(grid, visited, i, j)
return result
def bfs(self, grid, visited, i, j):
if i >= 0 and i < len(grid) and j >= 0 and j < len(grid[0]) and visited[i][j] == False and grid[i][j] == '1':
visited[i][j] = True
self.bfs(grid, visited, i - 1, j)
self.bfs(grid, visited, i + 1, j)
self.bfs(grid, visited, i, j - 1)
self.bfs(grid, visited, i, j + 1)
"""
Solution 2: Union & Find 解法
"""
class Solution(object):
def numIslands(self, grid):
"""
:type grid: List[List[str]]
:rtype: int
"""
m = len(grid)
if m == 0:
return 0
n = len(grid[0])
if n == 0:
return 0
islands = set()
self.result = 0
self.father = {}
for x in range(m):
for y in range(n):
if grid[x][y] == '1':
islands.add((x, y))
self.result += 1
self.father[(x, y)] = (x, y)
dx = [1, -1, 0, 0]
dy = [0, 0, 1, -1]
for i in range(4):
new_x = x + dx[i]
new_y = y + dy[i]
if (new_x, new_y) in islands:
self.union((x, y), (new_x, new_y))
return self.result
def union(self, point, new_point):
root = self.find(point)
new_root = self.find(new_point)
if root != new_root:
self.father[root] = new_root
self.result -= 1
def find(self, point):
path = []
while point != self.father[point]:
path.append(point)
point = self.father[point]
for p in path:
self.father[p] = point
return point |
8a101864085947c9e469c97829c04c892de8a3b9 | theguyisnoone/impthw | /ex16/sorting.py | 2,834 | 4.34375 | 4 | from dllist import DoubleLinkedList
from queue import Queue
from random import randint
def bubble_sort(numbers):
"""Sorts a list of numbers using bubble sort."""
while True:
# start off assuming it's sorted
is_sorted = True
# comparing 2 at a time, skipping ahead
node = numbers.begin.next
while node:
# loop through comparing node to the next
if node.prev.value > node.value:
# if the next is greater, then we need to swap
node.prev.value, node.value = node.value, node.prev.value
# oops, looks like we have to scan again
is_sorted = False
node = node.next
# this is reset at the top but if we never swapped then it's sorted
if is_sorted: break
def count(node):
count = 0
while node:
node = node.next
count += 1
return count
def merge_sort(numbers):
numbers.begin = merge_node(numbers.begin)
# horrible way to get the end
node = numbers.begin
while node.next:
node = node.next
numbers.end = node
def merge_node(start):
"""Sorts a list of numbers using merge sort."""
if start.next == None:
return start
mid = count(start) // 2
print(f">>>mid:{mid}")
# scan to the middle
scanner = start
for i in range(0, mid-1):
scanner = scanner.next
# set mid node right after the scan point
mid_node = scanner.next
# break at the mid point
scanner.next = None
mid_node.prev = None
merged_left = merge_node(start)
merged_right = merge_node(mid_node)
print(f"merged_left{merged_left},merged_right{merged_right}")
return merge(merged_left, merged_right)
def merge(left, right):
"""Performs the merge of two lists."""
result = None
print(">>>",left,right)
if left == None: return right
if right == None: return left
if left.value > right.value:
result = right
result.next = merge(left, right.next)
else:
result = left
result.next = merge(left.next, right)
result.next.prev = result
print(f"result{result}")
return result
def random_list(count):
numbers = DoubleLinkedList()
for i in range(count, 0, -1):
numbers.shift(randint(0, 10))
return numbers
def is_sorted(numbers):
node = numbers.begin
while node and node.next:
if node.value > node.next.value:
return False
else:
node = node.next
return True
def test_bubble_sort():
numbers = random_list(max_numbers)
sorting.bubble_sort(numbers)
assert is_sorted(numbers)
max_numbers = 10
numbers = random_list(max_numbers)
print(f"all:{numbers.count()}")
print(numbers.dump())
merge_sort(numbers)
print(numbers.dump())
|
3fcc5781518e808ddbf3531b38cc128bcc830869 | mrsecuritybreaker/Snake_Water_Gun-game | /Snake-Water_Game.py | 3,405 | 4 | 4 | print("Designed By : Ankush")
import random
if __name__== "__main__":
print("\nWelcome To Snake Water Gun Game!\n\n")
attempt = 1
my_point = 0
c_point = 0
while (attempt<=10):
lst=["s","w","g"]
a=random.choice(lst)
b = input("Enter Your Choice(Snake(s),Water(w),Gun(g)): ")
b = b.lower()
if b=='s' and a=='s':
print("Tie")
print(f"You Choose Snake and Computer Also Choose Snake\n")
print("Nobody get point")
elif b=='w' and a=='w':
print("Tie")
print(f"You Choose Water and Computer Also Choose Water\n")
print("Nobody get point")
elif b=='g' and a=='g':
print("Tie")
print(f"You Choose Gun and Computer Also Choose Gun\n")
print("Nobody get point")
elif b=='s' and a=='w':
my_point=my_point + 1
print(f"You Choose Snake and Computer Choose Water\n")
print("Snake Drunk Water\n")
print("you won this round")
print("You have 1 point\n")
elif b=='w' and a=='s':
c_point=c_point + 1
print(f"You choose Water and computer choose Snake\n")
print("Snake Drunk Water\n")
print("You loss this round")
print("Computer have 1 point\n")
elif b=='w' and a=='g':
my_point=my_point + 1
print(f"You Choose Water and Computer Choose Gun\n")
print("The Gun Sank in Water\n")
print("you won this round")
print("You have 1 point\n")
elif b=='g' and a=='w':
c_point=c_point + 1
print(f"You Choose Gun and Computer Choose Water\n")
print("The Gun Sank in Water\n")
print("You loss this round")
print("Computer have 1 point\n")
elif b=='g' and a=='s':
my_point=my_point + 1
print(f"You Choose Gun and Computer Choose Snake\n")
print("The Gun shoot the snake\n")
print("you won this round")
print("You have 1 point\n")
elif b=='s' and a=='g':
c_point=c_point + 1
print(f"You Choose Snake and Computer Choose Gun\n")
print("The Gun shoot the snake\n")
print("You loss this round")
print("Computer have 1 point\n")
else:
print("Invalid Input\n")
continue
print("\nNumber of guess left: {}".format(10 - attempt))
attempt = attempt+1
if attempt>10:
print("\nGame Over")
print(f"Your score:{my_point}\n\nComputer score:{c_point}")
if c_point<my_point:
print("You Won this game and Computer Lost")
elif c_point>my_point:
print("you lost the game and Computer Won")
else:
print("Tie")
print("Both have equal points")
print("number of gusses left",11-attempt,)
attempt = attempt+1
if attempt>10:
print("\nGame over! ")
if c_point > my_point:
print("\nComputer wins and you lose!")
if c_point < my_point:
print("\nYou win and the computer loses!")
print(f"\nYour points are {my_point} and Computer's points are {c_point}!\n")
|
a5e6fa001cba5c687830ed6e9e711f07e695ca4a | Darshnadas/100_python_ques | /DAY14/day14.52.py | 523 | 3.734375 | 4 | """
Define a custom exception class which takes a string message as attribute.
"""
class CustomException(Exception):
"""
Exception raised for custom
message --> explanation of the error raised
"""
def __init__(self, msg):
self.msg = msg
num = int(input())
try:
if num < 10:
raise CustomException("The input is less then 10")
elif num > 10:
raise CustomException("The input is greater than 10")
except CustomException as e:
print("The error is raised: " + e.msg)
|
519ecd10ed9d7033f1019092b70fb830540c1ad7 | zhukaijun0629/Programming_Daily-Practice | /2020-10-16_Remove-k-th-Last-Element-From-Linked-List.py | 1,000 | 3.703125 | 4 | """
Hi, here's your problem today. This problem was recently asked by AirBNB:
You are given a singly linked list and an integer k. Return the linked list, removing the k-th last element from the list.
Try to do it in a single pass and using constant space.
"""
class Node:
def __init__(self, val, next=None):
self.val = val
self.next = next
def __str__(self):
current_node = self
result = []
while current_node:
result.append(current_node.val)
current_node = current_node.next
return str(result)
def remove_kth_from_linked_list(head, k):
dummy=Node(0)
dummy.next=head
i=0
while head:
i+=1
head=head.next
i-=k
head=dummy
while i>0:
head=head.next
i-=1
head.next=head.next.next
return dummy.next
head = Node(1, Node(2, Node(3, Node(4, Node(5)))))
print(head)
# [1, 2, 3, 4, 5]
head = remove_kth_from_linked_list(head, 3)
print(head)
# [1, 2, 4, 5]
|
dfa981342202d42eac547c9b43591f8b0359fbc6 | sunsharing-note/python | /python_notes/day11/fibo.py | 258 | 3.53125 | 4 | #! /usr/bin/env python
# -*- encoding: utf-8 -*-
# here put the import lib
def fib(max):
n, before, after = 0, 0, 1
while n < max:
yield before
before, after = after, before + after
n += 1
print(fib(8))
print(next(fib(8))) |
e3c5c26709d92b056a7392c4bcfb433c3d358480 | GabrielWechta/age-of-divisiveness | /game_screens/logic/tests/buildings_tests.py | 2,621 | 3.5625 | 4 | import unittest
from game_screens.logic import GameLogic
from game_screens.logic import Tile
CIV_ONE = "The Great Northern"
CIV_TWO = "Mixtec"
class BuildingsTest(unittest.TestCase):
def setUp(self) -> None:
self.tiles = []
# these have to be added in the order of bottom to top, left to right in order for get_tile(x, y) to work
# so (0, 0), (1, 0), .... (COLUMNS_NUMBER-1, 0), (0, 1), (1, 1), ...
# this is a linear map with, from left to right, a column of water, plains, hills, plains, mountains
for y in range(5):
self.tiles.append(Tile(0, y, 1, 0))
self.tiles.append(Tile(1, y, 1, 1))
self.tiles.append(Tile(2, y, 1, 2))
self.tiles.append(Tile(3, y, 1, 1))
self.tiles.append(Tile(4, y, 1, 3))
self.game_logic = GameLogic(self.tiles, 5, 5, players=[("one", CIV_ONE, "gray"), ("two", CIV_TWO, "red")],
my_nick="one")
self.game_logic.add_unit(2, 2, "one", 'Settler', 1)
self.settler = self.game_logic.get_tile(2, 2).occupant
self.area = []
self.area.append(Tile(0, 1, 1, 0))
self.area.append(Tile(1, 1, 1, 0))
self.area.append(Tile(2, 1, 1, 1))
self.area.append(Tile(2, 2, 1, 2))
self.area.append(Tile(0, 0, 1, 2))
self.area.append(Tile(1, 2, 1, 3))
self.game_logic.build_city(self.settler, "test_name")
self.tile = self.settler.tile
self.city = self.tile.city
def test_mines(self):
before_goods = self.city.calculate_goods()
self.city.buildings["Mines"] = True
after_goods = self.city.calculate_goods()
self.assertEqual(after_goods["stone"], before_goods["stone"] + 20)
def test_free_market(self):
before_goods = self.city.calculate_goods()
self.city.buildings["Free Market"] = True
after_goods = self.city.calculate_goods()
self.assertEqual(after_goods["gold"], before_goods["gold"] + len(self.city.area) * 3)
def test_free_market_2(self):
self.city.area.append(Tile(0, 0, 1, 0))
before_goods = self.city.calculate_goods()
self.city.buildings["Free Market"] = True
after_goods = self.city.calculate_goods()
self.assertEqual(after_goods["gold"], before_goods["gold"] + len(self.city.area) * 3)
def test_astronomic_tower(self):
self.game_logic.increase_area(*self.tile.coords)
self.assertEqual(len(self.city.area), 13)
self.game_logic.increase_area(*self.tile.coords)
self.assertEqual(len(self.city.area), 25)
|
b89305fae589dd01a3582e26f25ac44b6da808df | madhurakhal/img-search-cnn | /webapp/features_extraction/image_list_creator.py | 1,118 | 3.890625 | 4 | import os, glob
class ImageListCreator(object):
def __init__(self):
pass
# This takes a directory name and looks for jpg images and creates a text file listing those images location.
def make_list_image_filenames(self, image_path):
dir_path = os.path.dirname(os.path.realpath(__file__))
#filename = os.path.join(dir_path , directory_name)
filename = image_path
if os.path.exists(filename):
os.chdir(filename)
text_file = open(os.path.join(dir_path , "images.txt"), "w")
types = ('*.jpeg', '*.jpg' , '*.JPEG' , '*.png') # the tuple of file types
files_grabbed = []
for files in types:
files_grabbed.extend(glob.glob(files))
for file in files_grabbed:
text_file.write(os.path.join(filename , file) + "\n")
text_file.close()
print("images.txt created at location : " + dir_path)
os.chdir(dir_path)
else:
print("No Folder exist of name \"" + image_path + "\" Please create and put images into it")
if __name__ == "__main__":
# How to use
fm = ImageListCreator()
#"Parameter: folder name where your images are located"
fm.make_list_image_filenames("images") |
30270add593ce03d3f5d5652d4e6ce71ec2ddeeb | Ahmed--Mohsen/leetcode | /flatten_tree_to_linked_list.py | 1,163 | 4.375 | 4 | """
Given a binary tree, flatten it to a linked list in-place.
For example,
Given
1
/ \
2 5
/ \ \
3 4 6
The flattened tree should look like:
1
\
2
\
3
\
4
\
5
\
6
If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.
"""
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param root, a tree node
# @return nothing, do it in place
def flatten(self, root):
self.flattenHelper(root)
def flattenHelper(self, root):
if root == None:
return None
# keep track of the subtrees roots
left = root.left
right = root.right
current = root
# Truncate the left subtree
root.left = None
# Flatten the left subtree
current.right = self.flattenHelper(left)
while current.right:
current = current.right
# Flatten the right subtree
current.right = self.flattenHelper(right)
return root |
4f9159d7c6e082438cceb9fb4ac25175ba628392 | EthanPassinoFWCS/Chapter4Anthis | /TIY4_2.py | 147 | 4 | 4 | animals = ["cat", "dog", "monkey"]
for animal in animals:
print(f"A {animal} would be a great pet.")
print("All of these animals have tails!")
|
f54d3b0921d01131e3ef2b1e63d00b7a9ec8c0f8 | hwangt17/MIS3640 | /session10/ex_03.py | 490 | 4.28125 | 4 | #exercise 3
team = 'New England Patriots'
new_team = team.upper()
index = team.find('a')
# str.find(sub[, start[, end]])
# Return the lowest index in the string where substring sub is found within the slice s[start:end].
# Optional arguments start and end are interpreted as in slice notation.
# Return -1 if sub is not found.
name = 'bob'
print(new_team)
print(index)
print(team.find('En'))
print(team.find('a', 10))
print(name.find('b', 1, 2)) #letter 'b' not found inbetween 1 and 2.
|
32133c7eefc66637b3e191e7bfbe72d8ca210b80 | NonCover/leetcode | /BFS ShorterPath/对称二叉树.py | 627 | 3.75 | 4 | class Root:
def __init__(self, x, left=None, right=None):
self.left = left
self.right = right
self.data = x
res = []
def middle(root):
if root is None:
return
middle(root.left)
res.append(root.data)
middle(root.right)
def solution(tree):
print(tree)
if len(tree) == 1:
return True
r = tree.pop()
l = tree.pop(0)
if r == l:
return solution(tree)
else:
return False
if __name__ == '__main__':
tree = Root(1, Root(2, Root(3), Root(4)), Root(2, Root(4), Root(3)))
m = middle(tree)
print(res)
print(solution(res))
|
726711dedcabfb11f75add14ec6f1123f0ab7df1 | Kracav4ik/tmi | /calc_bf_mem.py | 1,410 | 3.515625 | 4 | #!/usr/bin/env python3
import sys
def skip_brackets(s, op, from_i=0):
idx = from_i + op
count = op
while count != 0 and 0 <= idx < len(s):
if s[idx] == '[':
count += 1
elif s[idx] == ']':
count -= 1
idx += op
return idx
def parse_bf(s):
mem = [0]
bf_i = 0
cell_i = 0
while bf_i < len(s):
if s[bf_i] == '>':
cell_i += 1
if len(mem) == cell_i:
mem.append(0)
elif s[bf_i] == '<':
cell_i -= 1
if cell_i < 0:
sys.stderr.write('< for 0th cell\n')
cell_i = 0
elif s[bf_i] == '.':
sys.stdout.write(chr(mem[cell_i]))
sys.stdout.flush()
elif s[bf_i] == '+':
mem[cell_i] += 1
mem[cell_i] %= 256
elif s[bf_i] == '-':
mem[cell_i] += 255
mem[cell_i] %= 256
elif s[bf_i] == '[':
if mem[cell_i] == 0:
bf_i = skip_brackets(s, 1, bf_i) - 1
elif s[bf_i] == ']':
bf_i = skip_brackets(s, -1, bf_i)
bf_i += 1
return len(mem)
if __name__ == '__main__':
if len(sys.argv) == 1:
print('Not enough arguments. It should be used like "%s input_file"' % sys.argv[0])
exit(0)
with open(sys.argv[1], 'r') as input:
print(parse_bf(input.read()))
|
687d09d80189d44720225350d3ba20cea29ec9a5 | Yoshi-oYoshi/POOI | /Treinamento Python/Aula 8/new.py | 281 | 4.0625 | 4 |
valor = float(input('Insira o valor da casa: '))
salario = float(input('Insira o seu sálario: '))
anos = float(input('Insira quantos anos você pretende pagar a casa: '))
if (valor/(anos * 12) > (salario * 0.3)):
print('Empréstimo negado')
else:
print('Empréstimo aprovado') |
2ab720ee7050c0aab7c129bc48046995bbafad18 | ramdharam/MyPythonPrograms | /NoOf1s.py | 133 | 3.609375 | 4 | def numberOf1s(i):
count=0
while i > 0:
if i%2!=0:
count+=1
i=i/2
print(count)
numberOf1s(3) |
6f2afd72e659ae4ed12539b05f8a135d7148579a | Tim-Sotirhos/python-exercises | /4.2_python_exercises.py | 4,361 | 3.703125 | 4 | # What data type would best represent:
type(99.9) # Float
type("False") # Str
type(False) # Bool
type('0') # Str
type(0) # Int
type(True) # Bool
type('True') # Str
type([{}]) # List
type({'a':[]}) # Dict
# What data type would best represent:
# A term or phrase typed into a search box?
String
# If a user is logged in?
Boolean
# A discount amount to apply to a user's shopping cart?
Float
# Whether or not a coupon code is valid?
Boolean
# An email address typed into a registration form?
String
# The price of a product?
Integer
# A Matrix?
Dictionary
# The email addresses collected from a registration form?
List
# Information about applicants to Codeup's data science program?
Dictionary
#For each of the following code blocks,
# read the expression and predict what the result of evaluating it would be,
# then execute the expression in your Python REPL.
'1' + 2
# predict error because adding 2 diff data types
6 % 4
# predict remainder 2
type(6 % 4)
# predict integer
type(type(6 % 4))
# predict type or integer
'3 + 4 is ' + 3 + 4
# predict error diff data types
0 < 0
# predict True
'False' == False
# predict False one is a bool the other is a string
True == 'True'
# predict False one is a bool the other is a string
5 >= -5
# predict True
True or "42"
# predict True because of the True OR
!True && !False
# predict error command not found
6 % 55 < 4 and 1 == 1
# predict False both conditions are not True or False
'codeup' == 'codeup' and 'codeup' == 'Codeup'
# predict False because of the last capital??
4 >= 0 and 1 !== '1'
# predict error because of extra equal sign operator on 2nd condition
6 % 3 == 0
# predict True
5 % 2 != 0
# predict True
[1] + 2
# predict error
[1] + [2]
# predict new list with [1, 2]
[1] * 2
# predict list to be multiply by 2
[1] * [2]
# predict error
[] + [] == []
# predict True
{} + {}
# predict error ??
# The little mermaid (for 3 days), Brother Bear (for 5 days, they love it),
# and Hercules (1 day, you don't know yet if they're going to like it).
# If price for a movie per day is 3 dollars, how much will you have to pay?
daily_rental_rate = 3
# Movies
little_mermaid_days = 3
brother_bear_days = 5
hercules_days = 1
total_rental_cost = (little_mermaid_days + brother_bear_days + hercules_days) * daily_rental_rate
print(total_rental_cost)
# Google, Amazon and Facebook, they pay you a different rate per hour.
# Google pays 400 dollars per hour, Amazon 380, and Facebook 350.
# How much will you receive in payment for this week?
# You worked 10 hours for Facebook, 6 hours for Google and 4 hours for Amazon.
google = 400
amazon = 380
facebook = 350
hours_worked_google = 10
hours_worked_amazon = 4
hours_worked_facebook = 6
total_compensation = (google*hours_worked_google)+(amazon*hours_worked_amazon)+(facebook*hours_worked_facebook)
print(total_compensation)
# A student can be enrolled to a class only if the class is not full and the class schedule does not conflict with her current schedule.
available_seats = 1
schedule_conflict = False
if available_seats > 0 and schedule_conflict == False:
allowed_to_enroll = True
else:
allowed_to_enroll = False
print(allowed_to_enroll)
# A product offer can be applied only if people buys more than 2 items,
# and the offer has not expired. Premium members do not need to buy a specific amount of products.
num_of_items = 2
offer_expired = False
premium_member = True
if premium_member == True or (num_of_items > 2 and offer_expired == False):
product_discounted = True
else:
product_discounted = False
print(product_discounted)
# Use the following code to follow the instructions below:
username = 'codeup'
password = 'notastrongpassword'
# the password must be at least 5 characters
password_character_requirement = len(password) > 5
print(password_character_requirement)
# the username must be no more than 20 characters
password_max_character = len(password) <= 20
print(password_max_character)
# the password must not be the same as the username
password_cannot_be_username = password != username
print(password_cannot_be_username)
# bonus neither the username or password can start or end with whitespace
no_leading_or_ending_whitespace = username[0] != ' ' and username[-1] != ' ' and password[0] != ' ' and password[-1] != ' '
print(no_leading_or_ending_whitespace) |
60f95ebe9c34d3efeb5d3b96c812cb6cd7dbd1bb | abusamrahtechcampus/python | /python2/loop-equal.py | 418 | 3.90625 | 4 | numbers = [2,5,7,8,1,4,3]
sum = 0
for i in numbers:
sum = sum + i
print("Total = ",sum)
my_num = range(1,8)
num = 0
for i in my_num:
num = i + num
print("Total = ",num)
numbers1 = [2,5,7,8,1,4,3]
sum1 = 0
for i in numbers:
sum1 += i
print("Total = ",sum1)
numbers2 = [2,5,7,8,1,4,3]
sum2 = 0
for i in numbers2:
sum2 += i
else :
print(" All Quiryes Done")
print("Total = ",sum2)
|
4516c829c9c80dffecd8d2d30751aa05d15142db | aayush17002/DumpCode | /Foobar/target.py | 486 | 3.859375 | 4 | def subset_sum(numbers, target, partial=[]):
s = sum(partial)
# check if the partial sum is equals to target
if s == target:
print(partial)
# print ("%s" % partial)
elif s >= target:
return # if we reach the number why bother to continue
for i in range(len(numbers)):
n = numbers[i]
remaining = numbers[i+1:]
subset_sum(remaining, target, partial + [n])
if __name__ == "__main__":
subset_sum([1,1,1,1,2,2,4],4)
|
8d52f7aa6b563040ef5529fd9b291b2cf0dabd21 | teocrono/scripts | /sped_correcao/helper.py | 2,718 | 3.625 | 4 | ## funções para auxilio
def soma2strfloat(num1,num2):
num1 = float(num1.replace(",","."))
num2 = float(num2.replace(",","."))
return str(round(num1 + num2,2)).replace(".",",")
def mult2strfloat(num1,num2):
num1 = float(num1.replace(",","."))
num2 = float(num2.replace(",","."))
return str(round(num1 * num2,2)).replace(".",",")
def takeLimit(cursor,line,grupo):
select = ""
select = select + " SELECT r0 "
select = select + " FROM principal "
select = select + " WHERE r0 >= " + str(line) + " "
select = select + " and r1 = \"" + grupo + "\" order by r0 "
temp = cursor.execute(select)
temp = temp.fetchall()
temp = [i[0] for i in temp]
if len(temp) >= 2:
return [temp[0] + 1,temp[1] - 1]
else:
return [temp[0] + 1,temp[0]+100]
def montaSetSql(dados):
texto = ''
for i in dados:
temp = i.split('=')
if len(temp) > 1:
texto = texto + ' ' + temp[0]
if temp[1][0] == 't':
texto = texto + ' = ' + '\"' + temp[1][1:] + '\",'
elif temp[1][0] == 'r':
texto = texto + ' = ' + temp[1][1:] + ' ,'
elif temp[1][0] == 'v':
temp1 = temp[1][1:].split('v')
texto = texto + ' = ' + " REPLACE(CAST( ROUND(( CAST(replace("
texto = texto + temp1[0] + ",',','.') AS FLOAT) * CAST(replace("
if temp1[1][0] == 'r':
texto = texto + temp1[1][1:] + ",',','.') AS FLOAT) / 100),2) AS TEXT),'.',','),"
else:
texto = texto + "\"" + temp1[1] + "\"" + ",',','.') AS FLOAT) / 100),2) AS TEXT),'.',','),"
return texto[:-1]
def montaWhereSql(dados):
texto = ''
for i in dados:
temp = i.split('=')
if len(temp) > 1:
texto = texto + ' AND ' + temp[0]
if temp[1][0] == 't':
if temp[1][1] == 'd':
texto = texto + ' <> ' + '\"' + temp[1][2:] + '\"'
elif temp[1][1] == 'v':
texto = texto + ' = ' + '""' + ' '
else:
texto = texto + ' = ' + '\"' + temp[1][1:] + '\"'
elif temp[1][0] == 'r':
if temp[1][1] == 'd':
texto = texto + ' <> ' + temp[1][2:] + ' '
else:
texto = texto + ' = ' + temp[1][1:] + ' '
elif temp[1][0] == 'i':
temp1 = temp[1][1:].split('i')
texto = texto + ' in ' + '(\"' + '","'.join(temp1) + '\") '
elif temp[1][0] == 'n':
texto = texto + ' = ' + temp[1][1:] + ' '
return texto |
212605465bc41dc5000f0b62f8869e32607426c6 | bmilne-dev/python-utilities-and-functions | /dice.py | 907 | 4.25 | 4 | #!/usr/bin/env python3
# import randint from the random module
# create class Die, with attribute sides.
# default sides=6. write a method
# roll_die() that prints a random number
# between 1 and the number of sides
# the die has. make a 6 sided die, roll it
# 10 times. then make a 10 and 20 sided die.
from random import randint
class Die():
"""virtual dice!!"""
def __init__(self, sides=6):
self.sides = sides
def print_roll(self):
print(f"Your roll (sides = {self.sides}):"
f" {randint(1, self.sides)}")
def roll(self):
return randint(1, self.sides)
# die_1 = Die()
# die_1.roll_die()
# die_1.roll_die()
# die_1.roll_die()
# die_1.roll_die()
# die_1.roll_die()
# die_1.roll_die()
# ten_sides = Die(sides=10)
# twenty_sides = Die(sides=20)
# ten_sides.roll_die()
# twenty_sides.roll_die()
# die_test = Die(10)
# x = die_test.roll()
# print(x)
|
fc77a990666db6c6b7abc654115ea6c4bf260d67 | andrasKelle/HackerRank-Rest-API | /movie_titles.py | 798 | 3.6875 | 4 | """
Task: Get all movies which has the 'substr' in their title, and then sort them by alphabetic order
"""
import urllib.request
import json
def get_json_from_url(url):
with urllib.request.urlopen(url) as response:
html = response.read()
json_data = json.loads(html)
return json_data
def get_all_titles(substr):
url_base = f"https://jsonmock.hackerrank.com/api/movies/search/?Title={substr}&page="
data = get_json_from_url(url_base)
total_pages = data["total_pages"]
titles = []
for i in range(1, total_pages + 1):
url = url_base + str(i)
data = get_json_from_url(url)
for movie_object in data["data"]:
titles.append(movie_object["Title"])
titles.sort()
return titles
print(get_all_titles("spiderman"))
|
01bf616f8703aab457f1fe88af56b84a0d4aa910 | pskataria/Programming_Problems | /second_most_frequent_elem_in_arr.py | 487 | 3.78125 | 4 | #second most frequent 1st july 2017 8:14 pm
arr = [ "ccc", "aaa", "ccc", "ddd", "aaa", "aaa" ]
dic = {}
for word in arr:
if dic.has_key(word):
dic[word] += 1
else:
dic[word] = 1
print dic
fmax = -2
smax = -2
res = ""
sres = ""
for item in dic:
if dic[item] > fmax:
smax = fmax
sres = res
res = item
fmax = dic[item]
elif smax < dic[item] < fmax:
smax = dic[item]
sres = item
print smax
print sres |
217ed5027017487e9925f928bf50e29077e9e743 | njsdias/automated_sw_test_python | /1_refresh_python/3_loops.py | 522 | 4.15625 | 4 | my_variable = "hello"
print("Print first character: ", my_variable[0])
# Print each character of a string using an iteration
# strings, lists, sets, tuples, and more
for character in my_variable:
print(character)
my_num_list = [1, 3, 5, 7, 9]
for number in my_num_list:
print(number ** 2)
user_wants_number = True
while user_wants_number == True:
print(10)
# user_wants_number = False
user_input = input("Should we print again? (y/n)")
if user_input == 'n':
user_wants_number = False
|
abdc94c6633cc0a1f5694fd864ecf54af98a8ae8 | S-Lam/PFB_problemsets | /pset4-part2.py | 121 | 3.796875 | 4 | #!/usr/bin/env python3
import sys
for num in range(int(sys.argv[1]),int(sys.argv[2])+1):
if num % 2 != 0:
print (num)
|
c7909c163feabbb88f9af4b2ddd36ce4ffdd90ee | AlexTaran/automorphology | /src/vocab_expand.py | 1,384 | 3.515625 | 4 | #!/usr/bin/python
import argparse
import codecs
from collections import defaultdict
def read_vocab(path):
vocab = {}
with codecs.open(path, encoding='utf-8') as f:
for line in f:
word, count = line.split()
vocab[word] = int(count)
return vocab
def write_vocab(path, vocab):
with codecs.open(path, 'w', encoding='utf-8') as f:
for i, word in enumerate(sorted(vocab.keys())):
f.write('%s %d\n' % (word, vocab[word]))
def vocab_expand(args):
vocab = read_vocab(args.vocab_input)
print 'Input vocab size: %d' % len(vocab)
expanded_vocab = defaultdict(int)
for word, count in vocab.iteritems():
for spl in xrange(3, len(word)+1):
stem = word[:spl]
suff = word[spl:]
expanded_vocab['STM_' + stem] += count
expanded_vocab['SUF_' + suff] += count
if len(word) < 3:
expanded_vocab['SHR_' + word] += count
print 'Expanded vocab size: %d' % len(expanded_vocab)
write_vocab(args.vocab_output, expanded_vocab)
def main():
parser = argparse.ArgumentParser(description='Vocab expander by splitting the words')
parser.add_argument('--vocab-input', help='Vocab to expand', required=True)
parser.add_argument('--vocab-output', help='Where to write resulting vocab', required=True)
args = parser.parse_args()
print 'Running with args:', args
vocab_expand(args)
if __name__ == '__main__':
main()
|
543fd30c338c9ce2e3f7db550d22691e14b0f46f | ramonjunquera/GlobalEnvironment | /Python/standard/curso/06 Programación funcional/02 map y filter.py | 1,102 | 4.1875 | 4 | #Autor: Ramón Junquera
#Fecha: 20221221
# map y filter
# Son funciones que se aplican a objetos iterables (listas o tuplas)
# map permite aplicar una función a cada uno de los objetos de
# una lista (o tupla) y devuelve otro objeto similar en el
# que sus objetos ya han sido modificados
# En el siguiente ejemplo definimos una función que suma 5 al
# valor pasado como parámetro
# Definimos una lista con valores numéricos
# Con la función map aplicamos la función de sumar 5 a cada uno
# de los elementos de la lista
def suma5(x):
return x+5
miLista=[10,20,30,40,50]
print(list(map(suma5,miLista))) #Resultado: [15, 25, 35, 45, 55]
# Se podría hacer lo mismo con una función lambda
miLista=[10,20,30,40,50]
print(list(map(lambda x:x+5,miLista))) #Resultado: [15, 25, 35, 45, 55]
# filter permite seleccionar sólo los elementos que cumplan
# cierta condición
def esPar(x):
return x%2==0
miLista=[11,22,33,44,55]
print(list(filter(esPar,miLista))) #Resultado [22, 44]
# Con una función lambda sería
miLista=[11,22,33,44,55]
print(list(filter(lambda x:x%2==0,miLista))) #Resultado [22, 44]
|
908571500c85b72586e2810bb575f39cb40ccb6f | bosshentai/pythonLearning | /gaby/ficha9/teste.py | 201 | 3.671875 | 4 | t = [1,2,3,10]
def cumulativa(array):
count = 0
newArray = []
for index in array:
newArray.append(index + count);
count += index
return newArray
print(cumulativa(t)) |
43e14232be9726d8698ad006d9a8d7356d8aa5a5 | BarinderSingh30/Python_Basic | /2.exercises/4.astrologer's_star.py | 246 | 3.859375 | 4 | n=int(input('Enter the no. of rows :\n'))
b=int(input('Enter 1 for true or 0 for false\n'))
if b==1:
b=True
else:
b=False
if b:
for i in range(1,n+1):
print('*'*i)
else:
for i in range(n,0,-1):
print('*'*i)
|
a0359d4ffed078ed110f0d02c04434875ec26bd0 | noozip2241993/basic-python | /task41.py | 130 | 3.65625 | 4 | import os.path
"""Write a Python program to check whether a file exists."""
open('abc.txt','w')
print(os.path.isfile('abc.txt'))
|
eb18ce873b216f4ebfb68eaced773bcb095bb487 | CCH21/Python | /Python 100题/practice_76.py | 189 | 3.5625 | 4 | for num in range(10, 100):
if num * 809 == num * 800 + num * 9:
if 10 <= num * 8 < 100:
if 100 <= num * 9 < 1000:
print('%d\n%d' % (num, 809 * num))
|
d4b500e7c8aff1841765d5853f81e980b6051947 | 0scarW/objektorienterings-intro | /bilregister.py | 1,625 | 3.984375 | 4 | class Car():
'''
En klass som håller reda på några egenskaper hos en bil.
'''
# Metoden __init__, körs alltid då ett objekt skapas
def __init__(self, brand, color, mileage):
# Nedanstående variabler kallas för attribut.
# Alla objekt av klassen Car har egna värden på dessa.
self.brand = brand
self.color = color
self.mileage = mileage
def get_brand(self):
'''
Skriver ut bilmärket
'''
print(self.brand)
def set_brand(self, new_brand):
'''
Parameter: new_brand | sträng
Uppdaterar bilmärket om det existerar. Om det inte existerar
så tilldelas aktuellt objekt märket enligt parametern.
'''
self.brand = new_brand
def set_color(self, new_color):
'''
Ändrar färg
'''
self.color = new_color
def get_color(self):
print(self.color)
def set_milage(self, new_mileage):
self.mileage = new_mileage
def get_mileage(self):
print(self.mileage)
def get_info(self):
self.get_brand()
self.get_color()
self.get_mileage()
# ----------Huvudprogram----------
# Nu när klassen finns kan vi skapa objekt (variabler) med denna typ.
# Dessa objekt har också tillgång till klassens metoder (funktioner).
a_car = Car('Volvo', 'Blå', 1587)
b_car = Car('Porsche', 'Röd', 3500)
c_car = Car('Audi', 'Svart', 7000)
d_car = Car('Mercedes', 'Silver', 150000)
cars = [a_car, b_car, c_car, d_car]
for x in range(len(cars)):
print("------")
cars[x].get_info()
|
a2ee117e17c504b902ae0aa3e97270a3c9b16c4f | HarshpreetKaur/python | /Lesson1/String_methods.py | 2,218 | 3.78125 | 4 | print("charlotte hippopotamus turner".title())
full_name = "charlotte hippopotamus turner"
print(full_name.islower())
print("One fish, two fish, red fish, blue fish.".count('fish'))
prophecy = "And there shall in that time be rumours of things going astray, and there will be a great confusion as to where things really are, and nobody will really know where lieth those little things with the sort of raffia work base, that has an attachment…at this time, a friend shall lose his friends’s hammer and the young shall not know where lieth the things possessed by their fathers that their fathers put there only just the night before around eight o’clock…"
vowel_count = 0
vowel_count = prophecy.count("a") + prophecy.count("e") + prophecy.count("i") + prophecy.count("o") + prophecy.count("u") + prophecy.count("A") + prophecy.count("E") + prophecy.count("I") + prophecy.count("O") + prophecy.count("U")
print(vowel_count)
#OR
vowel_count += prophecy.count('a')
vowel_count += prophecy.count('A')
vowel_count += prophecy.count('e')
vowel_count += prophecy.count('E')
vowel_count += prophecy.count('i')
vowel_count += prophecy.count('I')
vowel_count += prophecy.count('o')
vowel_count += prophecy.count('O')
vowel_count += prophecy.count('u')
vowel_count += prophecy.count('U')
#OR
vowel_count = 0
lower_prophecy = prophecy.lower()
vowel_count += lower_prophecy.count('a')
vowel_count += lower_prophecy.count('e')
vowel_count += lower_prophecy.count('i')
vowel_count += lower_prophecy.count('o')
vowel_count += lower_prophecy.count('u')
user_ip = "208.94.117.90"
url = "/bears/koala"
now = "16:20"
log_message = "IP address {} accessed {} at {}".format(user_ip, url, now)
city = "Seoul"
high_temperature = 18
low_temperature = 9
temperature_unit = "degrees Celsius"
weather_conditions = "light rain"
#alert = "Today's forecast for " + city + ": The temperature will range from " + str(low_temperature) + " to " + str(high_temperature) + " " + temperature_unit + ". Conditions will be " + weather_conditions + "."
alert = "Today's forecast for {0}: The temperature will range from {1} to {2} {3}. Conditions will be {4}.".format(city, str(low_temperature), str(high_temperature), temperature_unit, weather_conditions)
print(alert) |
27cecf9122446a733787233fd658bfce5b5cc449 | mateuspadua/design-patterns | /creational/abstract_factory/refactoring-guru.py | 2,222 | 4.40625 | 4 | from random import randint
"""
Abstract Factory is a creational design pattern
that lets you produce families of related objects
without specifying their concrete classes
"""
# buttons
class ButtonInterface:
"""
This is the common interface for buttons family.
"""
def paint(self):
raise NotImplementedError
class MacOSButton(ButtonInterface):
def paint(self):
print('You have created MacOSButton.')
class WindowsButton(ButtonInterface):
def paint(self):
print('You have created WindowsButton.')
# checkboxes
class CheckboxInterface:
"""
This is the common interface for checkbox family.
"""
def paint(self):
raise NotImplementedError
class MacOSCheckbox(CheckboxInterface):
def paint(self):
print('You have created MacOSCheckbox.')
class WindowsCheckbox(CheckboxInterface):
def paint(self):
print('You have created WindowsCheckbox.')
# factories
class GUIFactoryInterface:
"""
Abstract factory knows aboult all (abstract) product types.
"""
def create_button(self):
raise NotImplementedError
def create_checkbox(self):
raise NotImplementedError
class MacOSFactory(GUIFactoryInterface):
def create_button(self):
return MacOSButton()
def create_checkbox(self):
return MacOSCheckbox()
class WindowsFactory(GUIFactoryInterface):
def create_button(self):
return WindowsButton()
def create_checkbox(self):
return WindowsCheckbox()
# application class
class Application:
def __init__(self, factory):
self.button = factory.create_button()
self.checkbox = factory.create_checkbox()
def paint(self):
self.button.paint()
self.checkbox.paint()
# client
class Demo:
def configure_application(self):
number = randint(1, 10)
if number % 2 == 0:
factory = MacOSFactory()
app = Application(factory)
else:
factory = WindowsFactory()
app = Application(factory)
return app
def run(self):
application = self.configure_application()
application.paint()
# run
Demo().run()
|
3fc448b590b4aefc13c8ae61b1c0ef8a8667a958 | kmerchan/AirBnB_clone | /models/city.py | 284 | 3.515625 | 4 | #!/usr/bin/python3
"""
Defines City class
"""
from models.base_model import BaseModel
class City(BaseModel):
""" City class!
Attributes:
name (str): name of city
state_id (str): ID of state where the city is located
"""
name = ""
state_id = ""
|
4ebb9095d6b84b4f402554011644391d25de8222 | Linkney/LeetCode | /SwordOffer-3/O48.py | 1,521 | 3.984375 | 4 | """
请从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子字符串的长度。
示例 1:
输入: "abcabcbb"
输出: 3
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
示例 2:
输入: "bbbbb"
输出: 1
解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。
示例 3:
输入: "pwwkew"
输出: 3
解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。
"""
from collections import deque
# 队列结构
# 队列中没有重复元素 则入队
# 有重复元素 则出队至 将重复元素出去
# 刷新整个过程中的 max Queue Length
# Ps: 这不就是 滑动窗口 双指针即可解决(双指针数组切片判断 in)
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
maxQueueLength = 0
queue = deque()
# print(queue)
for i in range(len(s)):
if s[i] not in queue:
queue.append(s[i])
else:
while s[i] in queue:
queue.popleft()
queue.append(s[i])
# print(queue)
maxQueueLength = max(maxQueueLength, len(queue))
return maxQueueLength
if __name__ == '__main__':
# s = "abcabcbb"
s = "bbbbb"
# s = "pwwkew"
print(Solution().lengthOfLongestSubstring(s))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.