blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
a0485f1dc91d36a9f91a4c2e5970dfe1bbdb1180 | DamianRubio/advent-of-code | /2020/12/solution.py | 5,576 | 3.6875 | 4 | from collections import defaultdict
from copy import deepcopy
input_file = '2020/12/input.txt'
ship_instructions = open(input_file).read().strip('\n').split('\n')
ordered_positions = ['north', 'east', 'south', 'west']
def compute_manhattan_distance(movement_dict):
return abs(movement_dict['north']) + abs(movement_dict['east'])
def move_south(movement_dict, amount):
movement_dict['north'] -= amount
return movement_dict
def move_west(movement_dict, amount):
movement_dict['east'] -= amount
return movement_dict
def move_forward(movement_dict, facing, amount):
if facing == 'east' or facing == 'north':
movement_dict[facing] += amount
elif facing == 'south':
movement_dict = move_south(movement_dict, amount)
elif facing == 'west':
movement_dict = move_west(movement_dict, amount)
return movement_dict
def rotate_ship(facing, rotation_side, degrees):
postions_to_rotate = degrees // 90
starting_pos = ordered_positions.index(facing)
if rotation_side == 'L':
return ordered_positions[starting_pos-postions_to_rotate]
elif rotation_side == 'R':
index_after_rotation = starting_pos+postions_to_rotate
if index_after_rotation >= len(ordered_positions):
index_after_rotation = index_after_rotation - \
len(ordered_positions)
return ordered_positions[index_after_rotation]
def parse_movement(ship_instructions):
movement_dict = defaultdict(int)
facing = 'east'
for instruction in ship_instructions:
if instruction[0] == 'F':
movement_dict = move_forward(
movement_dict, facing, int(instruction[1:]))
elif instruction[0] == 'N':
movement_dict['north'] += int(instruction[1:])
elif instruction[0] == 'S':
movement_dict = move_south(movement_dict, int(instruction[1:]))
elif instruction[0] == 'E':
movement_dict['east'] += int(instruction[1:])
elif instruction[0] == 'W':
movement_dict = move_west(movement_dict, int(instruction[1:]))
elif instruction[0] == 'L' or instruction[0] == 'R':
facing = rotate_ship(facing, instruction[0], int(instruction[1:]))
return movement_dict
def move_forward_by_waypoint(movement_dict, waypoint_dict, amount):
movement_dict['north'] += waypoint_dict['north'] * amount
movement_dict['east'] += waypoint_dict['east'] * amount
return movement_dict
def move_waypoint(movement_dict, direction, amount):
if direction == 'north':
movement_dict['north'] += amount
elif direction == 'south':
movement_dict = move_south(movement_dict, amount)
elif direction == 'east':
movement_dict['east'] += amount
elif direction == 'west':
movement_dict = move_west(movement_dict, amount)
return movement_dict
def rotate_waypoint_around_ship(waypoint_dict, rotation_side, degrees):
waypoint_dict_copy = {'north': 0, 'east': 0}
postions_to_rotate = degrees // 90
if rotation_side == 'L':
for pos in ['east', 'north']:
starting_pos = ordered_positions.index(pos)
converts_to = ordered_positions[starting_pos-postions_to_rotate]
waypoint_dict_copy = move_waypoint(
waypoint_dict_copy, converts_to, waypoint_dict[pos])
return waypoint_dict_copy
elif rotation_side == 'R':
for pos in ['east', 'north']:
starting_pos = ordered_positions.index(pos)
index_after_rotation = starting_pos+postions_to_rotate
if index_after_rotation >= len(ordered_positions):
index_after_rotation = index_after_rotation - \
len(ordered_positions)
converts_to = ordered_positions[index_after_rotation]
waypoint_dict_copy = move_waypoint(
waypoint_dict_copy, converts_to, waypoint_dict[pos])
return waypoint_dict_copy
def parse_movement_with_waypoint(ship_instructions):
waypoint_dict = defaultdict(int)
waypoint_dict['north'] = 1
waypoint_dict['east'] = 10
movement_dict = defaultdict(int)
movement_dict['north'] = 0
movement_dict['east'] = 0
for instruction in ship_instructions:
if instruction[0] == 'N':
waypoint_dict['north'] += int(instruction[1:])
elif instruction[0] == 'S':
waypoint_dict = move_south(waypoint_dict, int(instruction[1:]))
elif instruction[0] == 'E':
waypoint_dict['east'] += int(instruction[1:])
elif instruction[0] == 'W':
waypoint_dict = move_west(waypoint_dict, int(instruction[1:]))
elif instruction[0] == 'F':
movement_dict = move_forward_by_waypoint(
movement_dict, waypoint_dict, int(instruction[1:]))
elif instruction[0] == 'L' or instruction[0] == 'R':
waypoint_dict = rotate_waypoint_around_ship(
waypoint_dict, instruction[0], int(instruction[1:]))
return movement_dict
def solve_part_one(ship_instructions):
movement_dict = parse_movement(ship_instructions)
return compute_manhattan_distance(movement_dict)
def solve_part_two(ship_instructions):
movement_dict = parse_movement_with_waypoint(ship_instructions)
return compute_manhattan_distance(movement_dict)
print('Part one. The distance moved by the ship is: {}.'.format(
solve_part_one(ship_instructions)))
print('Part two. The distance moved by the ship is: {}.'.format(
solve_part_two(ship_instructions)))
|
edf5f02ad075fcac802302e8f71bc62746d6d051 | jacob-brown/programming-notes-book | /programming_notes/_build/jupyter_execute/python_basic.py | 4,747 | 4.46875 | 4 | # Python: Basics
## Lists
Methods:
* `append()`
* `clear()`
* `copy()`
* `count()`
* `extend()`
* `index()`
* `insert()`
* `pop()`
* `remove()`
* `reverse()`
* `sort()`
demoList = ["apple", "banana", "orange", "kiwi"]
print(demoList)
Adding/Removing items
demoList.append('cherry')
print(demoList)
demoList.insert(1, 'grape')
print(demoList)
join 2 lists
thislist = ["apple", "banana", "cherry"]
tropical = ["mango", "pineapple", "papaya"]
thislist.extend(tropical)
print(thislist)
or...
thislist = ["apple", "banana", "cherry"]
tropical = ["mango", "pineapple", "papaya"]
thislist + tropical
Removing items
demoList = ["apple", "banana", "orange", "kiwi"]
demoList.remove('apple')
print(demoList)
demoList.pop(1)
print(demoList)
del demoList[0]
print(demoList)
demoList.clear() # removes all items
print(demoList)
## Copying a list
make sure the lists aren't linked, with a deep copy
thislist = ["apple", "banana", "cherry"]
mylist = thislist.copy()
print(mylist)
del thislist[1]
print(thislist)
print(mylist)
## Tuples
unchangeable
`count()` and `index()`
tupExample = (1, 2, 3)
tupExample
## Sets
unordered and unindexed, adding/removing is possible but not changing
thisset = {"apple", "banana", "cherry"}
thisset.add("orange")
print(thisset)
## Dictionaries
fruitDict = {
"type" : "apple",
"colour" : ["red", "green"],
"weight" : 200
}
print(fruitDict)
print(fruitDict["type"])
fruitDict.get("weight")
fruitDict.keys()
fruitDict.values()
fruitDict.items()
Changing, adding, and removing items in a dictionary
fruitDict = {
"type" : "apple",
"colour" : ["red", "green"],
"weight" : 200
}
fruitDict["weight"] = 500
print(fruitDict)
fruitDict.update({"smell" : "appley"})
print(fruitDict)
fruitDict["season"] = "summer"
print(fruitDict["season"])
del fruitDict["colour"]
print(fruitDict)
## Loops
for i in range(0,5):
print(i)
x = 0
while x < 6:
print(x)
x = x + 1
breaks within loops
x = 0
while x < 6:
print(x)
if x == 4:
break
x = x + 1
continue jumps back to the start of the loop
x = 0
while x < 6:
x += 1
if x == 4:
continue
print(x)
i = 1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
## Conditions (If..Else)
a = 2
b = 20
if a > b:
print("a is larger")
elif a == b:
print("they are equal")
else:
print("b is larger")
a = 200
b = 33
c = 500
if a > b or a > c:
print("At least one of the conditions is True")
use `pass` to avoid an error.
if 1 > 10:
pass
## List Comprehension
newList = ["apple", "banana", "cherry"]
[x for x in newList]
[x for x in newList if x != 'apple']
[x for x in newList if x != 'apple']
[x.upper() for x in newList]
## Functions and lambda
lambda can have only one expression
def printHello():
print("Hello")
printHello()
addTen = lambda x : x + 10
addTen(2)
x = lambda a, b : a * b
print(x(5, 6))
## Key Concepts of Functions
**Parameter** - varriable listed *when defining* the function
**Argument** (args)- value that is sent to the function. Passes into a list
**Keyword Argument** (kwargs) - arguments wth a *key = value* syntax. Passes into a dict
```{python}
def add(a, b): # a and b are parameters
return a+ b
add(1, 2) # 1 and 2 are arguments
add(a = 1, b = 2) # both are keyword arguments
```
N.B. positional arguments are those not defined with a keyword
If we do not know how many positional arguments to pass use `*`
def tupleOfNumbers(*numbers):
return numbers
tupleOfNumbers(1, 2, 3, 4, 5, 6)
If we do not know how many keyword arguments to pass use `**`
def makePerson(**infoOnPerson):
for key, value in infoOnPerson.items():
print("{} is {}".format(key,value))
jacob = makePerson(first = "jacob", last = "brown", Age = 26)
## Modules
Code library or a local `.py` file
import numpy as np
np.array([1, 2, 3])
from pandas import DataFrame as df
df([1,2,3])
## RegEx
`import re`
`re.` methods:
* `findall` - Returns a list containing all matches
* `search` - Returns a Match object if there is a match anywhere in the string
* `.span()` - returns a tuple containing the start and end positions of the match.
* `.string` - returns the string passed into the function
* `.group()` - returns the part of the string where there was a match
* `split` - Returns a list where the string has been split at each match
* `sub` - Replaces one or many matches with a string
*from w3*
## File Handling
`open(filename, mode)`
Mode types:
`"r"` - read
`"a"` - append
`"w"` - write
`"x"` - create
open, readlines,and close
```python
f = open("demofile.txt", "r")
print(f.readline())
f.close()
```
|
7eb47946afa1c65507691501706ada044e96ef87 | gaurav-singh-au16/Online-Judges | /Leet_Code_problems/227. Basic_Calculator_II.py | 2,229 | 3.953125 | 4 | """
227. Basic Calculator II
Medium
1992
321
Add to List
Share
Given a string s which represents an expression, evaluate this expression and return its value.
The integer division should truncate toward zero.
Example 1:
Input: s = "3+2*2"
Output: 7
Example 2:
Input: s = " 3/2 "
Output: 1
Example 3:
Input: s = " 3+5 / 2 "
Output: 5
Constraints:
1 <= s.length <= 3 * 105
s consists of integers and operators ('+', '-', '*', '/') separated by some number of spaces.
s represents a valid expression.
All the integers in the expression are non-negative integers in the range [0, 231 - 1].
The answer is guaranteed to fit in a 32-bit integer.
Accepted
237,165
Submissions
621,049
"""
class Solution:
def calculate(self, s: str) -> int:
if not s:
return 0
PRIORITY={
"+":0,
"-":0,
"*":1,
"/":1
}
def operate(num1,num2,op)->int:
if op=="+":
return num1+num2
if op=="-":
return num1-num2
if op == "*":
return num1*num2
if op == "/":
return num1//num2
num_stk=[]
op_stk=[]
op_set=set(["*","/","-","+"])
dig_set=set([str(dig) for dig in range(0,10)])
valid_char=set(op_set).union(set(dig_set))
temp_num=""
#fill stack
for c in s:
if c not in valid_char:
continue
if c in dig_set:
temp_num=temp_num+c
continue
if c in op_set:
num_stk.append(int(temp_num))
temp_num=""
while(len(op_stk) and PRIORITY[c]<=PRIORITY[op_stk[-1]]):
num2=num_stk.pop()
num1=num_stk.pop()
op=op_stk.pop()
num_stk.append(operate(num1,num2,op))
op_stk.append(c)
num_stk.append(int(temp_num))
#empty out stack
while(len(num_stk)!=1 and op_stk):
num2=num_stk.pop()
num1=num_stk.pop()
op=op_stk.pop()
num_stk.append(operate(num1,num2,op))
return num_stk[-1]
|
96cabaad6a9f3978946dfd671f30e5afc0290b17 | r0ckburn/d_r0ck | /The Modern Python 3 Bootcamp/4 - Boolean and Conditional Logic/making_decisions_with_conditional_statements.py | 948 | 4.53125 | 5 | # Conditional Statements
# Conditional logic using if statements represents different paths a program can take based on some type of comparison of input
# if some condition is True:
# do something
# elif some other condition is True:
# do something
# else:
# do something
# You need 1 if, can have as many elif's as you want, and you can only have 1 else
# the colons are important - they indicate an indented block will follow the statement
# indentation is important - you will receive an error if spacing is incorrect
# example
name = ""
if name == "Arya Stark":
print("Valar Morghulis")
elif name == "John Snow":
print("You know nothing")
else:
print("Carry on")
# another example
color = input("What's your favorite color?")
if color == "Brown":
print("Excellent Choice!")
elif color == "Pink":
print("Gross!")
elif color == "Black":
print("Are you a goth?")
else:
print("Cool story!") |
8fda6ea6e3ccd3964e2548bce70897a2ad409555 | glenpike/dbscode | /minecraft/experiments/text/letters.py | 1,843 | 3.828125 | 4 | from dbscode_minecraft import *
from pixelfont_04B_03 import chars
"""
Simple functions to write text in Minecraft
This only works in the x-plane - need to figure out
how to make it directional.
Also uses a "font" which is an object containing a
2D list for each char. This could be refined
to generate the characters on the fly and
with varying sizes, but the font object is quite
a nice thing for learners to see.
"""
spaceWidth = 4;
def writeText(text, type, xPos, yPos, zPos):
lines = text.split("\n")
x = xPos
y = yPos
lineSpace = 1
for line in lines:
pt = makeLine(line, type, x, y, zPos)
y -= pt['h'] + lineSpace
return pt
def makeLine(line, type, xPos, yPos, zPos):
x = xPos
y = yPos
lineHeight = 0
letterSpace = 1
for char in line:
if ' ' == char:
x += spaceWidth
else:
pt = makeLetter(char, type, x, y, zPos)
if lineHeight < pt['h']:
lineHeight = pt['h']
x += pt['w']
x += letterSpace
return {'w': x, 'h': lineHeight}
def makeLetter(char, type, xPos, yPos, zPos):
print "char %s", (char)
letter = None
try:
letter = chars[char]
except KeyError:
print "char ", char, " does not exist"
if letter is None:
letter = chars['A']
x = xPos
y = yPos
width = 0
height = 0
size = point(1, 1, 1)
for row in letter:
for col in row:
if col == 1:
box(type, point(x, y, zPos), size)
x += 1
if width < (x - xPos):
width = x - xPos
x = xPos
y -= 1
# print "letter w ", width, " height ", yPos - y
return {'w': width, 'h': yPos - y}
if __name__ == '__main__':
bulldoze()
writeText('SKI IS ACE', DIAMOND_BLOCK, 0, 10, 0)
|
2dd11f83de1b6d2ea30a2fcdba69edc05d8bfc88 | MrHamdulay/csc3-capstone | /examples/data/Assignment_3/knxchi001/question2.py | 188 | 4.15625 | 4 | #Assignment 3
# Question 2
height= eval(input("Enter the height of the triangle:\n"))
gap= height-1
for i in range(1,(height*2),2):
print(gap*" ","*"*i, sep="")
gap=gap-1 |
ab90586c9714d21d4f172ec5b257a06ddb89968c | gabriellaec/desoft-analise-exercicios | /backup/user_139/ch133_2020_04_01_11_10_28_772568.py | 363 | 4.03125 | 4 | r1 = input ('Está funcionando?')
if r1 == 's':
print ('Sem problemas!')
elif r1 == 'n':
input ('Você sabe corrigir?')
if r1 == 's':
print('Sem problemas!')
elif r1 == 'n':
input ('Você precisa corrigir?')
if r1 == 's':
print ('Apague tudo e tente novamente')
else:
print('Sem problemas!') |
23fe0a018af1fb218bea63056c98f94dba6b21c0 | wadi-1000/News-API | /app/tests/articles_test.py | 664 | 3.71875 | 4 | import unittest
from models import articles
Articles = articles.Articles
class ArticlesTest(unittest.TestCase):
'''
Test Class to test the behaviour of the Articles class
'''
def setUp(self):
'''
Set up method that will run before every Test
'''
self.new_article = Articles('cnn','Mitchell Clark', 'Whatsapp and its advantages','Microsoft update','"https://www.theverge.com/2021/8/6/22613617/microsoft-xbox-night-mode-feature-dim-screen-controller-led','https://cdn','2021-08-05')
def test_instance(self):
self.assertTrue(isinstance(self.new_article,Articles))
if __name__ == '__main__':
unittest.main() |
8bc01590860830c34a2cffcff77c1104b7043657 | ebachmeier/School | /Python/TriangleArea.py | 388 | 4.5 | 4 | # Eric Bachmeier
# This program is used to input dimensions and calculate the area of a triangle.
# Date Completed: September 9, 2011
print "Area of a Triangle Program"
print
height = float (raw_input ("Enter the Height of the Triangle: "))
base = float (raw_input ("Enter the Base of the Triangle: "))
print
print "The area of the triangle is ", height * base * 0.5, "units squared."
|
f70d2039588c81dda2d5e3a88c77bd1e524165fa | avantikaaa/wtef-codes | /assessment1/encrypt.py | 416 | 3.953125 | 4 | def encrypt(input_word):
# YOUR CODE HERE
d = {'a':0, 'e':1, 'o':2,'u':3}
print d
input_word = list((input_word)[::-1])
print input_word
for i in range(len(input_word)):
if input_word[i].lower() in d:
print i
input_word[i] = str(d[input_word[i].lower()])
print input_word
return "".join(input_word)+"aca"
print encrypt("hello")
print encrypt("apple")
|
179a4f69762c1d1b26855166e5bb48e716dc8f50 | paljsingh/bloxorz | /pos.py | 947 | 3.609375 | 4 | from __future__ import annotations
from orientation import Orientation
class Pos:
def __init__(self, x: int, y: int, orientation: Orientation = Orientation.STANDING):
self.x = x
self.y = y
self.orientation = orientation
def __hash__(self):
return hash((self.x, self.y, self.orientation))
def __str__(self):
"""
String representation of position object (for easier debugging)
:return: Position object as string.
"""
return '[x:{}, y:{}, orientation:{}]'.format(self.x, self.y, self.orientation)
def __eq__(self, other: Pos) -> bool:
"""
Compare current position object with another.
:param other: The other position object.
:return: True if the two objects match in x, y coordinates as well as their orientation.
"""
return self.x == other.x and self.y == other.y and self.orientation == other.orientation
|
36531bc8af8a2ec2eec54c89423f88ac8aa6528d | rafaelperazzo/programacao-web | /moodledata/vpl_data/11/usersdata/97/5475/submittedfiles/jogo.py | 574 | 3.78125 | 4 | # -*- coding: utf-8 -*-
from __future__ import division
import math
Cv=input('Digite o número de vitórias do cormengo:')
Ce=input('Digite o número de empates do cormengo:')
Cs=input('Digite o saldo de gols do cormengo:')
Fv=input('Digite o número de vitórias do flaminthias:')
Fe=input('Digite o número de empates do flaminthias:')
Fs=input('Digite o saldo de gols do flaminthias:')
Pc=(Cv*3)+(Ce*1)
Pf=(Fv*3)+(Fe*1)
if Pc>Pf or Cv>Fv or Cs>Fs:
print('C')
elif Pf>Pc or Fv>Cv or Fs>Cs:
print('F')
elif Pc==Pf and Cv==Fv and Cs==Fs:
print('=')
|
8be09a8eba6d428fd3e8e30e3d7c8f1b461dbaa2 | hemanthk97/airflow-k8s-autoscaling | /fruit.py | 275 | 3.546875 | 4 | import sys
import time
fruits = ["apple", "banana", "cherry","apple", "banana", "cherry","apple", "banana", "cherry","apple", "banana", "cherry","apple", "banana", "cherry","apple", "banana", "cherry","apple", "banana", "cherry"]
for x in fruits:
time.sleep(3)
print(x)
|
2e03bbfe1e56e04b295ebb473fda5645b6902ee5 | MatthieuSarter/AdventOfCode | /AoC_2019/Day13/__init__.py | 2,967 | 3.5 | 4 | import ast, os
import sys
from collections import defaultdict
from time import sleep
from typing import Dict, List
from Day10 import Point
from Day9 import run_program, NewProgram
GameMap = Dict[Point, int]
def count_tiles(program, tile_type):
# type: (NewProgram, int) -> int
'''
Count the number of tiles of a given type.
'''
_, output, _, _ = run_program(program)
count = 0
for i in range(0, len(output) // 3):
if output[3 * i + 2] == tile_type:
count += 1
return count
def update_game_map(output, game_map=None):
# type: (List[int], GameMap) -> GameMap
'''
Updates the game map with the program's output
'''
if game_map is None:
game_map = defaultdict(lambda: 0)
for i in range(0, len(output) // 3):
x = output[3 * i]
y = output[3 * i + 1]
value = output[3 * i + 2]
game_map[Point(x, y)] = value
return game_map
def print_game_map(game_map):
# type: (GameMap) -> None
'''
Print the game map in text mode
'''
if sys.platform == 'win32':
os.system('cls')
else:
os.system('clear')
symbols = [' ', '█', '░', '▬', '●']
max_x = max([p.x for p in game_map])
max_y = max([p.y for p in game_map])
print(f'Score: {game_map[Point(-1, 0)]}')
for y in range(0, max_y + 1):
for x in range(0, max_x + 1):
value = game_map[Point(x, y)]
sys.stdout.write(symbols[value])
print('')
def find_object(game_map, object):
# type: (GameMap, int) -> Point
'''
Finds the position of the first occurence a given object in the game map
'''
for p, value in game_map.items():
if value == object:
return p
def play(program, fps=0):
# type: (NewProgram, int) -> int
'''
Play the game until it ends
'''
program[0] = 2
pointer = 0
relative_base = 0
input = []
game_map = None
while pointer != -1:
program, output, pointer, relative_base = run_program(program, input, pointer, True, relative_base)
game_map = update_game_map(output, game_map)
if fps:
print_game_map(game_map)
sleep(1 / fps)
paddle_pos = find_object(game_map, 3)
ball_pos = find_object(game_map, 4)
if (ball_pos is None or paddle_pos is None):
input = [0]
continue
input = [(ball_pos.x > paddle_pos.x) - (ball_pos.x < paddle_pos.x)]
if fps:
print_game_map(update_game_map(output, game_map))
return game_map[Point(-1, 0)]
def run(with_tests = True):
with open(os.path.dirname(__file__) + os.sep + 'input.txt', 'r') as in_file:
program = ast.literal_eval('[' + in_file.read().strip() + ']')
d13p1 = count_tiles(program, 2)
print(f'Day 13, Part 1 : {d13p1}') # 326
d13p2 = play(program)
print(f'Day 13, Part 2 : {d13p2}') # 15988
if __name__ == '__main__':
run()
|
51da2c8673034ec9f9f2153bd4ddffb05617d51c | shtaag/Community-StartHaskell2011 | /exercises/chapter04/solutions/Exercise16.py | 133 | 3.78125 | 4 | from math import sqrt
# calculate the length of the hypotenuse of a right triangle
def pythag(a, b):
return sqrt(a * a + b * b)
|
2a47c61685c7b1988f358242d61c6bd71a68d4e3 | SahaanaIyer/dsci-greyatom | /student_mgmt.py | 868 | 3.796875 | 4 |
# Prepare the student roster
class_1 = ['Geoffrey Hinton', 'Andrew Ng', 'Sebastian Raschka', 'Yoshua Bengio']
class_2 = ['Hilary Mason', 'Carla Gentry', 'Corinna Cortes']
new_class = class_1 + class_2
print(new_class)
new_class.append('Peter Warden')
print(new_class)
new_class.remove('Carla Gentry')
print(new_class)
# Calculating grade
courses = {'Math':65, 'English':70, 'History':80, 'French':70, 'Science':60}
total=0.0
for i in courses :
total=total+courses[i]
print(total)
percentage=(total/500)*100
print(percentage)
# Finding math genius
mathematics={'Geoffrey Hinton':78, 'Andrew Ng':95, 'Sebastian Raschka':65, 'Yoshua Benjio':50, 'Hilary Mason':70, 'Corinna Cortes':66, 'Peter Warden':75}
topper = max(mathematics, key=mathematics.get)
print(topper)
# Scholarship Certificate
topper = 'andrew ng'
first_name = topper.split()[0]
last_name = topper.split()[1]
full_name = last_name + " " + first_name
certificate_name = full_name.upper()
print(certificate_name)
|
316d43fb9c46ba060fbd8d3c062503bef7a5cf6a | agentreno/diveintopython | /chapter5/regex.py | 1,479 | 3.625 | 4 | import re
s = '100 BROAD ROAD APT. 3'
# Raw strings don't have any escape chars:
print(r"re.sub substitutes, \b is a word boundary")
print(re.sub(r'\bROAD\b', 'RD.', s))
# Compact regular expression for roman numeral validity
pattern = """
^ # beginning of string
M{0,3} # thousands - 0 to 3 Ms
(CM|CD|D?C{0,3}) # hundreds - 900 (CM), 400 (CD), 0-300 (0-3 Cs),
# or 500-800 (D, followed by 0-3 Cs)
(XC|XL|L?X{0,3}) # tens - 90 (XC), 40 (XL), 0-30 (0-3 Cs),
# or 50-80 (L, followed by 0-3 Xs)
(IX|IV|V?I{0,3}) # ones - 9 (IX), 4 (IV), 0-3 (0-3 Is),
# or 5-8 (V, followed by 0-3 Is)
$ # end of string
"""
print(re.search(pattern, 'MMMDCCCLXXXVIII', re.VERBOSE))
# Compact regular expression for US phone number capturing
phonePattern = re.compile(r"""
# don't match beginning of string to allow prefixes
(\d{3}) # area code is 3 digits
\D* # optional separator (* is 0 or more, \D non-digit)
(\d{3}) # trunk is 3 digits
\D* # optional separator
(\d{4}) # rest of number is 4 digits
\D* # optional separator
(\d*) # optional extension number any length
$ # end of string
""", re.VERBOSE)
print(phonePattern.search("work 1-(800) 555.1212 #1234").groups())
print(phonePattern.search("800-555-1212"))
|
764b8b38ac36f3eb7942777e2bbfa0ed63bead27 | koteshrv/Python | /APSSDC_Training/Packages/Module.py | 220 | 3.96875 | 4 | # even or odd function
def even(n):
if n % 2 == 0:
return True
return False
# max of three
def unique(lst):
l = []
for i in lst:
if lst.count(i) == 1:
l.append(i)
print(l) |
4e1bab5ab064086d3573c7b8b78ba37f13a0c6ef | jcp510/movie-trailer-website | /media.py | 806 | 3.578125 | 4 | import webbrowser
# Data structure to store favorite movies.
class Movie:
""""Store favorite movies, include title, storyline, box art, and trailer.
Attributes:
title (str): movie title.
storyline (str): movie plot.
poster_image_url (str): url for movie box art.
trailer_youtube_url (str): url for movie trailer.
"""
def __init__(self, movie_title, movie_storyline, poster_image,
trailer_youtube):
self.title = movie_title
self.storyline = movie_storyline
self.poster_image_url = poster_image
self.trailer_youtube_url = trailer_youtube
def show_trailer(self):
"""Opens movie trailer. Takes youtube trailer url as arg."""
webbrowser.open(self.trailer_youtube_url)
|
61f59bfb98d45e1b4b6d4c048045522212809345 | scric/Python3.x-2017 | /begginger/2017-03-12/第七章-Web开发-集成在一起/Athlete.py | 571 | 3.609375 | 4 | import sanitize
class AthleteList(list):
def __init__(self, a_name, a_dob=None, a_times=[]):
list.__init__([])
self.name = a_name
self.dob = a_dob
self.extend(a_times)
def top3(self):
return sorted(set([sanitize.sanitize(t) for t in self]))[0:3]
# 新类代码的使用
# vera = AthleteList('vera vi') # 为vera创建一个新的对象实例
# vera.append('1.31') # 增加一个计时值
# print(vera.top3())
#
# vera.extend(['2.22', '1-21', '2:22'])
# print(vera.top3())
# 让我们使用最终版的readFile吧
|
a23ad694b266cd4a3e4f586c0c423e62bf090798 | gabrieldsumabat/DocSimilarity | /tests/TestCleanText.py | 509 | 3.59375 | 4 | import string
import unittest
from code.CleanText import clean_text
class TestCleanText(unittest.TestCase):
def test_clean_text(self):
bad_text = string.punctuation
self.assertEqual(clean_text(bad_text), "%")
symbol_text = "-- J.R.R. Tolkien, \"The Lord of the Rings\""
self.assertEqual(clean_text(symbol_text), " JRR Tolkien The Lord of the Rings")
weird_text = "nef aear, s'i nef aearon!"
self.assertEqual(clean_text(weird_text), "nef aear si nef aearon")
|
2c3800619ef2018ad3ad342201d3ff5ef939cc5c | Cfoley23/100-Days-Of-Code | /Month 01/Week 04/Day 25/Katie's Turtle.py | 2,316 | 3.828125 | 4 | from turtle import Turtle, Screen
francis = Turtle()
screen = Screen()
turtle_shape = ((0, 16), (-2, 14), (-1, 10), (-4, 7),
(-7, 9), (-9, 8), (-6, 5), (-7, 1), (-5, -3), (-8, -6),
(-6, -8), (-4, -5), (0, -7), (4, -5), (6, -8), (8, -6),
(5, -3), (7, 1), (6, 5), (9, 8), (7, 9), (4, 7), (1, 10),
(2, 14), (0, 16))
bigger_shape = [n*5 for n in turtle_shape]
new_turtle = francis.turtlesize(5, 5)
def turtle_size(amount):
li = []
for a, b in turtle_shape:
num_1 = a * amount
num_2 = b * amount
if a == 0:
num_1 += amount
if b == 0:
num_2 += amount
print(a, b, num_1, num_2)
for index, tuple in enumerate(turtle_shape):
element_one = tuple[0]
element_two = tuple[1]
print(element_one, element_two)
# francis.shape('turtle')
# francis.color('darkred')
# francis.turtlesize(stretch_wid=5, stretch_len=5)
# screen.bgcolor('light blue')
francis.ht()
francis.pu()
francis.goto(0, 16)
francis.pd()
for x in bigger_shape:
francis.goto(x)
screen.exitonclick()
"""
"arrow" : Shape("polygon", ((-10,0), (10,0), (0,10))),
"turtle" : Shape("polygon", ((0,16), (-2,14), (-1,10), (-4,7),
(-7,9), (-9,8), (-6,5), (-7,1), (-5,-3), (-8,-6),
(-6,-8), (-4,-5), (0,-7), (4,-5), (6,-8), (8,-6),
(5,-3), (7,1), (6,5), (9,8), (7,9), (4,7), (1,10),
(2,14))),
"circle" : Shape("polygon", ((10,0), (9.51,3.09), (8.09,5.88),
(5.88,8.09), (3.09,9.51), (0,10), (-3.09,9.51),
(-5.88,8.09), (-8.09,5.88), (-9.51,3.09), (-10,0),
(-9.51,-3.09), (-8.09,-5.88), (-5.88,-8.09),
(-3.09,-9.51), (-0.00,-10.00), (3.09,-9.51),
(5.88,-8.09), (8.09,-5.88), (9.51,-3.09))),
"square" : Shape("polygon", ((10,-10), (10,10), (-10,10),
(-10,-10))),
"triangle" : Shape("polygon", ((10,-5.77), (0,11.55),
(-10,-5.77))),
"classic": Shape("polygon", ((0,0),(-5,-9),(0,-7),(5,-9))),
"blank" : Shape("image", self._blankimage()) """
|
5158d0ee070a9d7d1959d921e30386fa9a397289 | kuroalabo/coding_problems | /Python/30-Days-of-Code/Day8/Day8.py | 417 | 3.640625 | 4 | #!/usr/bin/env python3
number_of_entries = int(input())
phoneBook = {}
arr = []
for i in range(0, number_of_entries):
arr = list(map(str, input().rstrip().split()))
phoneBook[arr[0]] = arr[1]
while True:
try:
query = input()
if query in phoneBook:
print(query + "=" + phoneBook[query])
else:
print("Not found")
except:
break
|
faf20c8fe991f3eb0d125e697f1db874cb1052d0 | gunjan-madan/Python-Solution | /Module3/1.3.py | 1,638 | 4.625 | 5 |
# In one of the previous lessons, you used the print statement to create text art.
# Imagine using the while loop command and the print statements to generate some really awesome text art.
# Let's help Sam create some great text art. All set to give it a try!
'''Task 1: Pattern Printing'''
print("**** Task 1: ****")
print()
# Uncomment the statements below and click Run to see what is displayed
print("**pattern1**")
i=1
while(i<=5):
print("*"*i)
i=i+1
# Wow!! Wasn't that awesome!! Now if you want to reverse the pattern, how will you change the code to generate it?
print()
print("--Pattern 2--")
print()
i=5
while(i>=1):
print("*"*i)
i=i-1
'''Task 2: Combination Pattern'''
print("**** Task 2: ****")
print()
# Ready for the next challenge!
# You just created two patterns. Try combining them and see what you get
print("**Pattern 3**")
i=1
while(i<=5):
print("*"*i)
i=i+1
while(i>=1):
print("*"*i)
i=i-1
'''Task 3: Dazzling Diamond'''
print("**** Task 3: ****")
print()
# Given below is the code that will create a diamond text art on your terminal output window.
# A part of the program has been done for you.
# You need to uncomment the code below and fill in the missing details in while statement and the counters (i and d)
# Once you are done, click Run and see the diamond unfold.
print("**Diamond Pattern**")
print()
i=5 # First half of the diamond
d=1
while(i>=1):
print("*"*i+" "*d+"*"*i)
i=i-1
d=d+2
i=1 #Second Half of the diamond
d=9
while(i<=5):
print("*"*i+" "*d+"*"*i)
i=i+1
d=d-2
'''Fantastic!! You have created some great art work!! You definitely have a wonderful creative side.'''
|
66257e7db5febd8750257e454d783714df635164 | rustom/leetcode | /Miscellaneous/Length of Last Word.py | 261 | 3.609375 | 4 | class Solution:
def lengthOfLastWord(self, s: str) -> int:
string = s.strip()
pieces = string.split(' ')
try:
return len(pieces[-1])
except:
return 0
sol = Solution()
print(sol.lengthOfLastWord('a ')) |
9b887c49052e20619fad39bd1b35b8d054530d96 | aaaaaaaaaaaaaaaaace/cp2019 | /p02/q05_find_month_days.py | 692 | 4.125 | 4 | month = int(input('Enter month:'))
year = int(input('Enter year:'))
months = ["January","February","March","April","May","June","July","August","September","October","November","December"]
if month == 2 and ((year % 4 == 0 and year % 100 != 0) or year % 400 == 0):
print('February' + ' ' + str(year) + ' has 29 days.')
elif month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12:
print(months[month-1] + ' has 31 days')
elif month == 4 or month == 6 or month == 9 or month == 11:
print_months[month-1] + ' has 30 days')
elif month == 2 and year % 4 != 0:
print('February' + ' ' + str(year) + ' has 28 days.')
else:
print('Invalid month')
|
222c1b96decb07eb9fb4fa62a0d188c4d815d338 | nicolargo/pythonarena | /typing/multipletype.py | 485 | 4 | 4 | #!/usr/bin/env python3
from typing import overload
class Foo(object):
def __init__(self, name):
self.name = name
def __str__(self):
return self.name
@overload
def put(self, name: int) -> int:
self.name = int(name)
return self.name
def put(self, name):
self.name = name
return self.name
if __name__ == "__main__":
foo = Foo("foo")
print(foo)
print(type(foo.put("bar")))
print(type(foo.put(42)))
|
2e1e275dd7191f8b18fe73af0a8d7cde49c95289 | gaurangalat/SI506 | /Gaurang_DYU2.py | 1,163 | 4.3125 | 4 | #Week 2 Demonstrate your understanding
print "Do you want a demo of this week's DYU?\nA. Yes B. Not again\n"
inp = raw_input("Please enter your option: ") #Take input from user
if (inp =="B" or inp =="b"):
print "Oh well nevermind"
elif(inp == "A" or inp =="a"): #Check Option
print "\nHere are a few comic book characters"
d={"Batman" : "Robin", "Asterix": "Obelix", "Tintin" :"Snowy"} #Dictionary Initialization
print d.keys() #Print keys of the dictionary
x= raw_input("\nDo you want to know their sidekicks?\nA. Yes B. No\n")
if (x == "A" or x =="a"): #Check for User Option
y = raw_input("Which character's sidekick would you like to know about? ") #Take input
c=0
for ele in d.keys():
if (y.upper()==ele.upper()): #Compare input and key of ditcionary
print d[ele], "is the sidekick of", y, "\n"
else:
c+=1
if(c==3): #Invalid Input checker
print "Please Check Again"
elif(inp =="B" or inp =="b"):
print "\nOh well nevermind"
else:
print "\nNevermind. Sorry to waste your time :)"
else: #Invalid input checker
print ("\nSorry, wrong option. Run again")
|
5ae0f82c011f9ac232a1f95ff1f2163fa230d631 | WhaleJ84/com404 | /1-basics/4-repetition/8-nested-loop/bot.py | 387 | 4.4375 | 4 | # Ask the user how many rows and columns they want
print("How many rows should I have?")
rows = int(input())
print("How many columns should I have?")
columns = int(input())
asciiFace = ":-) "
# Print an ascii face in the rows and columns defined above
print("Here I go:")
for count in range(rows):
for number in range(columns):
print(asciiFace, end="")
print()
print("Done!")
|
edbfbe9b68b1398a75f7ec63fb3d32013bf9c6a6 | astabrq12/Istabrq12.github.io | /exercises.py | 410 | 3.578125 | 4 | import turtle
n = turtle.Turtle()
def c1(x,z):
n.speed(25)
for i in range(180):
n.forward(100)
n.color(z)
n.right(30)
n.forward(20)
n.left(60)
n.color(x)
n.forward(50)
n.color(x)
n.right(30)
n.penup()
n.setposition(0, 0)
n.pendown()
n.right(2)
c1("red","black")
turtle.done() |
af793a40a576e1cf876640c1c6817198d0a15229 | bitscuit/perceptron | /main.py | 3,784 | 3.578125 | 4 | import numpy as np
import pprint
ITERATIONS = 200
LEARNING_RATE = 0.01
BIAS = 1
count = 0
# reads the dataset from CSV file and normalizes it
def getData(filename):
data = np.loadtxt(filename, delimiter=',') # load csv file into numpy array
# normalize data (ignore last column because that is desired output)
normalized = data[:, :-1] / data[:, :-1].max(axis=0)
# put normalized data back into array with desired output column
data[:, :-1] = normalized
return data
# output function of neuron which calculates the weighted sum of inputs
# the output is 1 if sum is greater than 0, 0 otherwise
def activate(input, weights):
# add bias for neuron to determine its own threshold
output = BIAS * weights[0]
# list comprehension to perform element wise multiplication of the input
# and weights lists
output += sum([x * w for x, w in zip(input, weights[1:])])
return 1 if output > 0 else 0
# implementation of a 2 neuron perceptron where weights1 is the set of input
# weights feeding into neuron 1 and weights2 is the set of input weights feeding
# into neuron 2
# the outputs are concatenated and treated like a binary string
def perceptron(input, weights1, weights2):
y1 = activate(input, weights1)
y2 = activate(input, weights2)
return str(y1) + str(y2)
# helper function to update the weights of perceptron while training
def updateWeights(x, w, y, d):
weights = []
# update weight of BIAS input, resulting in perceptron determining its own
# threshold
weights.append(w[0] + ((d - y) * LEARNING_RATE * BIAS))
# update weight, w, for each input, x
for i in range(len(x)):
weights.append(w[i+1] + ((d - y) * LEARNING_RATE * x[i]))
return weights
def trainPerceptron(input, weights1, weights2):
global count
for i in range(ITERATIONS):
for row in input:
y = perceptron(row[:-1], weights1, weights2)
# print('y is: {}, and d is: {}'.format(int(y,2), row[len(row)-1]))
d = row[len(row)-1]
test = format(int(d), '02b')
if int(test[0]) - int(y[0]) != 0:
weights1 = updateWeights(row[:-1], weights1, int(y[0]), int(test[0]))
if int(test[1]) - int(y[1]) != 0:
weights2 = updateWeights(row[:-1], weights2, int(y[1]), int(test[1]))
if int(y, 2) - int(row[len(row)-1]) == 0:
count += 1
# print(y)
print('This many were right: {}'.format(count))
count = 0
print(weights1)
print(weights2)
return (weights1, weights2)
def testPerceptron(input, weights1, weights2):
global count
count = 0
for row in input:
y = perceptron(row[:-1], weights1, weights2)
d = row[len(row)-1]
# print(y)
if int(y, 2) - int(d) == 0:
count +=1
print('This many were right: {}'.format(count))
def main():
weights1 = [-0.1, 1, 0.1, 1, 0.1, -1, 0.1, -1]
weights2 = [-1, 0.1, 1, 0.1, 1, 0.1, 1, 0.1]
# first weight is for bias
# weights1 = [-0.3600000000000002, 1.0124787535410458, 0.008660869565218606, 0.3704475661548351, -0.14466367041199163, -1.1815497148523761, 0.125947634237115, 0.47409770992366457]
# weights2 = [-0.3399999999999994, -1.1172521246458798, 0.544226086956539, 0.7400718719372663, 0.7303610486891207, -0.307255145053313, -0.1705348219032502, -0.35072519083968534]
trainingData = getData('trainSeeds.csv')
np.random.shuffle(trainingData)
# train perceptron
weights1, weights2 = trainPerceptron(trainingData, weights1, weights2)
testData = getData('testSeeds.csv')
np.random.shuffle(testData)
testPerceptron(testData, weights1, weights2)
if __name__ == '__main__':
main()
|
75878ab810fcb7d02f077efbd70221c90369eeeb | rockpz/leetcode-py | /algorithms/reverseWordsInAString/reverseWordsInAString.2.py | 689 | 3.75 | 4 | # Source : https://oj.leetcode.com/problems/reverse-words-in-a-string-ii/
# Author : Ping Zhen
# Date : 2017-04-17
'''**********************************************************************************
*
* Given an input string, reverse the string word by word. A word is defined as a sequence of non-space characters.
*
* The input string does not contain leading or trailing spaces and the words are always separated by a single space.
*
* For example,
* Given s = "the sky is blue",
* return "blue is sky the".
*
* Could you do it in-place without allocating extra space?
*
*
**********************************************************************************''' |
34ad8e36c73dae6b9c7a60dd5e42999044a839f7 | lucasptcastro/projetos-curso-em-video-python | /ex044.py | 936 | 3.6875 | 4 | p = float(input('Informe o valor do produto: '))
print(' ')
print('Tecle [\033[34m1\033[m] para pagamento à vista \033[34mdinheiro\033[m/\033[34mcheque\033[m: \033[33m10% de desconto\033[m')
print('Tecle [\033[34m2\033[m] para pagamento à vista no \033[34cartão\033[m: \033[33m5% de desconto\033[m')
print('Tecle [\033[34m3\033[m] para pagamento em até \033[34m2x no cartão\033[m: \033[33mpreço normal\033[m')
print('Tecle [\033[34m4\033[m] para pagamento \033[34m3x ou mais no cartão\033[m: \033[33m20% de juros\033[m')
print(' ')
r = int(input('Informe aqui: '))
if r == 1:
v1 = (10*p) / 100
r1 = p - v1
print(f'O valor a ser pago será R${r1:.2f}')
elif r == 2:
v2 = (5*p) / 100
r2 = p - v2
print(f'O valor a ser pago será R${r2:.2f}')
elif r == 3:
print(f'O valor a ser pago será R${p:.2f}')
elif r == 4:
v3 = (20*p) / 100
r3 = p + v3
print(f'O valor a ser pago será R${r3:.2f}')
|
cbf7cdc91452c9259134b98d21d8ff626712a7e2 | harshraj22/problem_solving | /solution/leetcode/2302.py | 1,552 | 3.53125 | 4 | # https://leetcode.com/problems/count-subarrays-with-score-less-than-k/
import enum
class Solution:
def possible(self, i, j, nums, pref_sum, k) -> bool:
sum = pref_sum[j] - pref_sum[i] + nums[i]
length = j - i + 1
return k > length * sum
def binary_search(self, index, nums, pref_sum, k) -> int:
# low is always possible, find the largest possible
low, high = index, len(nums) - 1
while low < high:
mid = (low + high + 1) // 2
if self.possible(index, mid, nums, pref_sum, k):
low = mid
else:
high = mid - 1
return low
def countSubarrays(self, nums: List[int], k: int) -> int:
ans = 0
# 1. find pref sum
pref_sum = [nums[0] for _ in nums]
for index, num in enumerate(nums[1:], 1):
pref_sum[index] = num + pref_sum[index-1]
# 2. iterate over nums
for index, num in enumerate(nums):
# 3. for each num, binary search the max len such that subarray
# of found len with starting at the givne index, has score less than k
if num >= k:
continue
last_index = self.binary_search(index, nums, pref_sum, k)
# 4. all subarrays starting at the given index, having length less than the
# found length are included in the answer
ans += last_index - index + 1
# print(f'For index {index} length is {last_index - index + 1}')
return ans |
33ef01b21f309551627809b3edda3750597ea7cb | CL129/my-travel-plans | /单元测试/szys.py | 524 | 3.578125 | 4 | import random
n1 = random.randint(1, 100)
n2 = random.randint(1, 100)
def add(n1, n2):
while n1 + n2 >=100:
n1 = random.randint(1, 100)
n2 = random.randint(1, 100)
return n1 + n2
def sub(n1, n2):
n1, n2 = max(n1, n2), min(n1, n2)
return n1 - n2
def multi(n1, n2):
while n1 * n2 >=100: #控制积不超过100
n1 = random.randint(1, 100)
n2 = random.randint(1, 100)
return n1 * n2
def divide(n1, n2):
n1, n2 = max(n1, n2), min(n1, n2)
return int(n1 / n2)
|
b71ad33c352eb586beaa5c6ba1c011de2fa4d421 | imgeekabhi/HackerRank | /interview-preparation-kit/ctci-is-binary-search-tree.py | 455 | 3.8125 | 4 | """ Node is defined as
class node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
"""
def checkNode(node, min, max):
if node == None:
return True
if node.data <= min or node.data >= max:
return False
return checkNode(node.left, min, node.data) and checkNode(node.right, node.data, max)
def checkBST(root):
return checkNode(root, float('-inf'), float('inf'))
|
bd1f8129b35d3a95896985949efc82a2cbd02270 | liwengyong/p1804_workspace | /p1/p10/blin.py | 84 | 3.75 | 4 | a=int(input('输入'))
s=1
while a> 0:
print(' '*a ,' *'*s)
a=a-1
s=s+1
|
357e6ccdb1d29ea306b11d3c14e19183014a17cd | Dbajj/music-map | /app/model/connection.py | 567 | 3.5625 | 4 | # A connection describes a way two nodes can be related.
# It contains a string type, as well as a dictionary of additional keys
# containing extra information about the connection.
class Connection(object):
def __init__(self, type_desc, extras=None):
if type(type_desc) is not str:
raise TypeError("type_desc should be string")
if type(extras) is not dict:
raise TypeError("extras should be dictionary")
self.type = type_desc
self.extras = extras
def __str__(self):
return f"{self.type}"
|
a6cbda0f07201c5e946c6c24fe118b3766275672 | python-kurs/exercise-2-RobFisch | /second_steps.py | 2,017 | 4.21875 | 4 | # Exercise 2
# Satellites:
sat_database = {"METEOSAT" : 3000,
"LANDSAT" : 30,
"MODIS" : 500
}
# The dictionary above contains the names and spatial resolutions of some satellite systems.
# 1) Add the "GOES" and "worldview" satellites with their 2000/0.31m resolution to the dictionary [2P]
sat_database["GOES"] = 2000
sat_database["WORLDVIEW"] = 0.31
print("I have the following satellites in my database:")
# 2) print out all satellite names contained in the dictionary [2P]
print(sat_database.keys())
# 3) Ask the user to enter the satellite name from which she/he would like to know the resolution [2P]
y = input("Von welchem satelliten möchtest du die Auflösung wissen? (Bitte in Großbuchstaben)")
if y == "METEOSAT":
print("METEOSAT hat eine Auflösung von 3000 Metern.")
elif y == "LANDSAT":
print("LANDSAT hat eine Auflösung von 30 Metern.")
elif y == "MODIS":
print("MODIS hat eine Auflösung von 500 Metern.")
elif y == "GOES":
print("GOES hat eine Auflösung von 2000 Metern.")
elif y == "WORLDVIEW":
print("WORLDVIEW hat eine Auflösung von 0.31 Metern.")
else:
print("Ich habe dich leider nicht verstanden.")
#sat_database
#
#for key,val in sat_database:
# x = input("Von welchem Satelliten möchtest du die Auflösung erfahren?")
# if x =0 (sat_database.keys())
# print(sat_database.values)
#print("Die Auflösung von {} ist {} Meter.".format(val, key))
# 4) Check, if the satellite is in the database and inform the user, if it is not [2P]
if y in sat_database:
print("Der Satellit befindet sich im Datensatz.")
else:
print("Der Satellit befindet sich nicht im Datensatz.")
# 5) If the satellite name is in the database, print a meaningful message containing the satellite name and it's resolution [2P]
Aufl = (sat_database.get(y))
if y in sat_database:
print("Der wunderschöne Satellit {} besitzt eine tolle Auflösung von {} Metern".format(y,Aufl))
else:
print("Es gibt nichts zu sagen.") |
fd5445f6b8f8e7e9e00ba85d2126b7d39162ae0a | rafaelperazzo/programacao-web | /moodledata/vpl_data/389/usersdata/328/72262/submittedfiles/poligono.py | 88 | 3.640625 | 4 | # -*- coding: utf-8 -*-
n=int(input('número de lados do poligono:'))
print('%.1f'%nd) |
a02c9376d32693dca1a9b5730efd6e75e1a48ece | vgaurav3011/Regression-Algorithms | /Ridge_Regression.py | 1,285 | 3.578125 | 4 | #importing necessary files
import numpy as np
import pandas as pd
from pandas import Series, DataFrame
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
#importing test and train file
train = pd.read_csv('Train.csv')
test = pd.read_csv('Test.csv')
#Ridge Regression
from sklearn.linear_model import Ridge
Rreg = Ridge(alpha=0.05, normalize=True)
#Splitting into Training and CV for Cross Validation
X = train.loc[:,['Outlet_Establishment_Year', 'Item_MRP']]
x_train, x_cv, y_train, y_cv = train_test_split(X, train.Item_Outlet_Sales)
#Training the Model
Rreg.fit(x_train,y_train)
#Predicting on the Cross validation set
pred = Rreg.predict(x_cv)
#Calculating the Mean Square Error
mse = np.mean((pred - y_cv)**2)
print('Mean Square Error is: ', mse)
#Calculation of coefficients
coeff = DataFrame(x_train.columns)
coeff['Coefficient Estimate'] = Series(Rreg.coef_)
print(coeff)
#Creating the graph for the regression
x_plot = plt.scatter(pred, (pred - y_cv), c='b')
plt.hlines(y=0, xmin=-1000, xmax=5000)
plt.title('Residual Plot')
plt.show()
#Creating the modal coefficients for the Ridge Regression
predictors = x_train.columns
coef = Series(Rreg.coef_,predictors).sort_values()
coef.plot(kind='bar', title='Modal Coefficients')
plt.show() |
d82bbd7e1a577905b406ec3fc82ee5c9d9ad3df1 | shifubear/CryptWing | /cipher.py | 1,086 | 3.6875 | 4 | #
# CS106 Final Project
# CryptWing
#
# classical ciphers
#
# Shion Fukuzawa (sf27)
# December 15, 2016
#
# This file implementations the base cipher class.
#
# Algorithms referenced from
# http://practicalcryptography.com/
#
class Cipher:
"""
Cipher base class.
Implements the main constructor, string method,
and empty encrypt/decrypt methods.
"""
def __init__(self):
"""
"""
pass
def encrypt(self, text, key=None):
"""
:param text: A string of the message to encrypt.
:param key: A key (type varies between the cipher) to change the encryption.
:return: The encrypted text as a string.
"""
print("Encrypting '" + text + "'...")
pass
def decrypt(self, text, key=None):
"""
Uses the cipher's decryption method to decrypt the text
:param text:
:param key:
:return:
"""
print("Decrypting '" + text + "'...")
pass
if __name__ == "__main__":
c = Cipher()
c.encrypt("Hello")
c.decrypt("Onomatopoeia")
|
3f4342d27ef18010a68dbd4cca59a867b9a69a38 | RBrignoli/Testes-python | /pythonarquivos/somacaracter.py | 128 | 3.90625 | 4 | n = int(input("digite um numero inteiro: "))
res = 0
while n != 0:
a = n % 10
n = n // 10
res = a + res
print (res)
|
7b35e5ebbd6417e765d76793b745f042228368a9 | MRS88/python_basics | /week_5_tuples_cycles_lists/sum_of_factorials.py | 394 | 3.90625 | 4 | '''По данному натуральному n вычислите сумму 1!+2!+3!+...+n!.
В решении этой задачи можно использовать только один цикл.
Формат ввода
Вводится натуральное число n.'''
from math import factorial
res = 0
for i in range(1, int(input())+1):
res += factorial(i)
print(res)
|
504441c49e32f2ed2196f2155c59797a4007dba9 | marcos-saba/Cursos | /Curso Python/PythonExercicios/ex078.py | 539 | 3.84375 | 4 | valores = list()
print('\033[30m='*50)
for c in range(0, 5):
valores.append(int(input(f'Digite o valor na posição {c}: ')))
print('='*50)
print(f'Você digitou os valores {valores}')
print(f'O maior valor digitado foi {max(valores)} nas posições ', end='')
for p, v in enumerate(valores):
if v == max(valores):
print(p, end='... ')
print(f'\nO menor valor digitado foi {min(valores)} nas posições ', end='')
for p, v in enumerate(valores):
if v == min(valores):
print(p, end='... ')
print()
print('='*50)
|
a2c7e7174514aa2ab0535b20133fee97453a8464 | imgagandeep/hackerrank | /python/math/004-mod-power.py | 532 | 4.125 | 4 | """
Task
You are given three integers: a, b, and m, respectively. Print two lines.
The first line should print the result of pow(a,b). The second line should print the result of pow(a,b,m).
Input Format
The first line contains a, the second line contains b, and the third line contains m.
Constraints
1 ≤ a ≤ 10
1 ≤ b ≤ 10
2 ≤ m ≤ 1000
Sample Input:
3
4
5
Sample Output:
81
1
"""
# Solution:
a, b, m = int(input()), int(input()), int(input())
print(pow(a, b))
print(pow(a, b, m))
|
da87ef613bde2015392b25d8bf2dfae2c1295217 | helloworld767/alogrithm | /612 k closest points.py | 1,306 | 3.625 | 4 | points = [[-1,-1],[1,1],[100,100]]
origin = [0,0]
k = 2
# points = [[point.x, point.y] for point in points]
points.sort()
def comp(point1, point2, origin):
d1 = (point1[0] - origin[0]) ** 2 + (point1[1] - origin[1]) ** 2
d2 = (point2[0] - origin[0]) ** 2 + (point2[1] - origin[1]) ** 2
if d1 == d2:
return point1 < point2
return d1 < d2
def max_heapify(heap, heapsize, root, origin):
left = 2 * root + 1
right = left + 1
flag = root
if left < heapsize and comp(heap[flag], heap[left], origin):
flag = left
if right < heapsize and comp(heap[flag], heap[right], origin):
flag = right
if root != flag:
heap[flag], heap[root] = heap[root], heap[flag]
max_heapify(heap, heapsize, flag, origin)
def build_max_heap(heap, origin):
heapsize = len(heap)
for i in range((len(heap) - 2) // 2, -1, -1):
max_heapify(heap, heapsize, i, origin)
def heap_sort(heap):
for i in range(len(heap) - 1, -1, -1):
heap[0], heap[i] = heap[i], heap[0]
max_heapify(heap, i, 0, origin)
heap = points[:k]
build_max_heap(heap, origin)
for i in range(k, len(points)):
if comp(points[i], heap[0], origin):
heap[0] = points[i]
max_heapify(heap, len(heap), 0, origin)
heap_sort(heap)
print(heap) |
aa68052988e7d6bac51c1840391c17507c629a60 | abaumgarner/simplePythonEncryption | /main.py | 604 | 3.546875 | 4 | #!/usr/bin/env python3
""" Author: Aaron Baumgarner
Created: 12/14/20
Updated: 12/14/20
Notes: Simple main to run all files needed for simple text incryption and decryption
"""
import menu
encrypt = []
decrypt = []
""" Infanate loop to run the program until the user selects the 0 exit option """
while True:
menu.displayMenu()
option = int(menu.promptMenuOption())
if option == 2:
encrypt = menu.executeOption(option,encrypt,decrypt)
elif option == 3:
decrypt = menu.executeOption(option,encrypt,decrypt)
else:
menu.executeOption(option,encrypt,decrypt)
|
9851d1f451d3c5a4ed2ba72e03c4248c10147a20 | olivianauman/intro_to_cs | /.join.py | 965 | 3.796875 | 4 | #Get the index where myChar occurs replace the calue in myWord at that index
#with the string "$$", i.e. reassign the value at that index as "$$".
def problem4(myWord,myChar):
charList = list(myWord)
if myChar not in myWord:
return ("Character not found.")
else:
while myChar in charList:
charList[charList.index(myChar)] = "$$"
return "".join(charList)
def problem1(numberOfDollars):
quarters = numberOfDollars * 4
if (numberOfDollars == 0) or (numberOfDollars > 1):
return "There are "+str(quarters)+" quarters in "+str(numbersOfDollars)+" dollars."
elif numberOfDollars == 1:
return "There are "+str(quarters)+" quarters in "+str(numbersOfDollars)+" dollar."
#"\n" new line character in a file
def tryThis(myString):
newString = ""
for char in myString:
if char == 'A':
newString = '4' + newString
return newString |
3c7c3aa7d211258ad9cc684a22892759361d3da4 | xiangz201/Learning-Notes | /python/algorithm/quicksort.py | 705 | 3.84375 | 4 | # -*-coding:utf-8-*-
"""
快速排序
"""
import numpy as np
def create_array(num):
return np.random.randint(20, size=num)
def partition(arr, left, right):
pivot = arr[right]
i = left - 1
for j in range(left, right):
if arr[j] <= pivot:
i += 1
arr[i], arr[j] = arr[j], arr[i]
arr[i + 1], arr[right] = arr[right], arr[i + 1]
return i + 1
def quick_sort(arr, left, right):
if left <= right:
mid = partition(arr, left, right)
quick_sort(arr, left, mid - 1)
quick_sort(arr, mid + 1, right)
if __name__ == '__main__':
arr1 = create_array(10)
print(arr1)
quick_sort(arr1, 0, len(arr1) - 1)
print(arr1)
|
c87696ef9263d690711f1acb4cb3d6033ce889e4 | caio-coutinho/learning_python | /EstruturaDeDecisao/9.py | 1,359 | 4.1875 | 4 | """Faça um Programa que leia três números e mostre-os em ordem decrescente."""
number_one = input("Digite o primeiro numero:")
number_two = input("Digite o segundo numero:")
number_tree = input("Digite o terceiro numero:")
if not number_one.isnumeric():
print("Entrada Invalida")
exit()
if not number_two.isnumeric():
print("Entrada Invalida")
exit()
if not number_tree.isnumeric():
print("Entrada Invalida")
exit()
number_one = float(number_one)
number_two = float(number_two)
number_tree = float(number_tree)
if number_one > number_two and number_one > number_tree:
print(number_one)
if number_two > number_tree:
print(number_two)
print(number_tree)
else:
print(number_tree)
print(number_two)
if number_two > number_one and number_two > number_tree:
print(number_two)
if number_tree > number_one:
print(number_tree)
print(number_one)
else:
print(number_one)
print(number_tree)
if number_tree > number_one and number_tree > number_two:
print(number_tree)
if number_one > number_two:
print(number_one)
print(number_two)
else:
print(number_two)
print(number_one)
"""
1. Solicitar os numeros
2. teste de entradas validas
3. descobrir qual é o maior numero
4.
"""
|
35bd65c512aae27006c934dc97d36370424a5434 | mmontone/acme | /acme/util.py | 235 | 3.5 | 4 | def all_subclasses(klass):
subclasses = []
for cls in klass.__subclasses__():
subclasses.append(cls)
if len(cls.__subclasses__()) > 0:
subclasses.extend(all_subclasses(cls))
return subclasses
|
303fd2e5844338df9c8a13b49dfe71eb4ae6e039 | rupaku/codebase | /DS/string/palindromic.py | 1,574 | 4.15625 | 4 | '''
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Example:
"A man, a plan, a canal: Panama" is a palindrome.
"race a car" is not a palindrome.
Return 0 / 1 ( 0 for false, 1 for true ) for this problem
'''
def sentencePalindrome(s):
l, h = 0, len(s) - 1
# Lowercase string
s = s.lower()
# Compares character until they are equal
while (l <= h):
# If there is another symbol in left
# of sentence
if (not (s[l] >= 'a' and s[l] <= 'z')):
l += 1
# If there is another symbol in right
# of sentence
elif (not (s[h] >= 'a' and s[h] <= 'z')):
h -= 1
# If characters are equal
elif (s[l] == s[h]):
l += 1
h -= 1
# If characters are not equal then
# sentence is not palindrome
else:
return False
# Returns true if sentence is palindrome
return True
# Driver program to test sentencePalindrome()
# s = "A man, a plan, a canal: Panama"
s="race a car"
if (sentencePalindrome(s)):
print("Sentence is palindrome.")
else:
print("Sentence is not palindrome.")
#method2
import re
def isPalindrome(A):
if A == "":
return 1
A = re.sub('[^a-zA-Z0-9]', '', A)
# if A == "":
# return 1
A = A.lower()
i = 0
j = len(A) - 1
while i < j:
if A[i] != A[j]:
return 0
i += 1
j -= 1
return 1 |
df8d3c1cafa10ca2d2fb63c8c4ca7e8118f91e12 | denvaar/Euler | /Problem7/p7.py | 1,022 | 4 | 4 | # By listing the first six prime numbers:
# 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
# What is the 10001st prime number?
import timeit
import math
# I learned that you don't have to go over
# each of the primes, only up to the sqrt(index)
# which saves considerable time.
def solution(index):
primes = [2]
i = 1
while len(primes) != index:
isPrime = True
_next = primes[-1] + i
# OPTIMIZATION 2:
# all primes except 2 are odd.
if _next % 2 == 0:
i = i + 1
continue
# OPTIMIZATION 1:
# Only loop up until the sqrt(index)
for p in primes[:int(math.sqrt(index))]:
if _next % p == 0:
i = i + 1
isPrime = False
break
if isPrime:
i = 1
primes.append(_next)
return primes[-1]
start = timeit.default_timer()
print solution(10001)
stop = timeit.default_timer()
print "Completed in", stop - start, "seconds."
|
977c4015a95d1784e92b9df84982f3c60f795a35 | rehassachdeva/UDP-Pinger | /UDPPingerServer.py | 834 | 3.546875 | 4 | import random
import sys
from socket import *
# Check command line arguments
if len(sys.argv) != 2:
print "Usage: python UDPPingerServer <server port no>"
sys.exit()
# Create a UDP socket
# Notice the use of SOCK_DGRAM for UDP packets
serverSocket = socket(AF_INET, SOCK_DGRAM)
# Assign IP address and port number to socket
serverSocket.bind(('', int(sys.argv[1])))
while True:
# Generate random number in the range of 0 to 10
rand = random.randint(0, 10)
# Receive the client packet along with the address it is coming from
message, address = serverSocket.recvfrom(1024)
# Capitalize the message from the client
message = message.upper()
# If rand is less is than 4, we consider the packet lost and do not respond
if rand < 4:
continue
# Otherwise, the server responds
serverSocket.sendto(message, address)
|
b99df8f753e9ffde7eb29476b2b1b363e23ec5fb | digant0705/Algorithm | /LeetCode/Python/080 Remove Duplicates from Sorted Array II.py | 1,356 | 3.921875 | 4 | # -*- coding: utf-8 -*-
'''
Remove Duplicates from Sorted Array II
======================================
Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?
For example,
Given sorted array nums = [1,1,1,2,2,3],
Your function should return length = 5, with the first five elements of nums
being 1, 1, 2, 2 and 3. It doesn't matter what you leave beyond the new length.
'''
class Solution(object):
'''算法思路:
依旧是填充的思路
'''
def removeDuplicates(self, nums):
tail = 0
for num in nums:
if tail < 2 or num != nums[tail - 1] or num != nums[tail - 2]:
nums[tail] = num
tail += 1
return tail
class Solution(object):
'''算法思路:
对于最多 k 个重复的数字,普遍做法,用双指针,并用一个变量记录当前重复填充了多少个
'''
def removeDuplicates(self, nums):
if not nums:
return 0
n, slow, fast, cnt, k = len(nums), 0, 1, 1, 2
while fast < n:
if nums[fast] != nums[slow] or cnt < k:
cnt = 1 if nums[fast] != nums[slow] else (cnt + 1)
slow += 1
nums[slow] = nums[fast]
fast += 1
return slow + 1
s = Solution()
print s.removeDuplicates([0, 0, 0, 0])
|
a1b8b81cf2abf09b188d39a346ce1d98f0f11049 | prashant97sikarwar/leetcode | /Tree/FindCorrespondingNodeOfaBinaryTreeInACloneofThatTree.py | 825 | 3.828125 | 4 | #Problem Link:- https://leetcode.com/problems/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/
"""Given two binary trees original and cloned and given a reference to a node target in the
original tree.The cloned tree is a copy of the original tree.Return a reference to the same
node in the cloned tree."""
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:
if cloned:
if cloned.val == target.val:
return cloned
else:
return self.getTargetCopy(original,cloned.left,target) or self.getTargetCopy(original,cloned.right,target) |
1b829121f9efe27436c1667c314f5a252e5e7c2d | agbischof/PythonPractice | /chaos.py | 435 | 4.15625 | 4 | # File: chaos.py
# A simple program illustrating chaotic behavior
def main():
print "This program illustrates a chaotic function"
x1, x2 = input('Enter 2 numbers between 0 and 1 separated by commas: ')
# x2 = input('Enter another number between 0 and 1: ')
print "input ", x1, " ", x2
for i in range(10):
x1 = 3.9*x1*(1-x1)
x2 = 3.9*x2*(1-x2)
print " ", x1, " ", x2
if __name__ == "main":
main()
|
4898a4907c0a8ae873f295c15e7a9f5ee2380164 | figgynwtn/Total-Sales | /Ch7Ex1.py | 953 | 4.0625 | 4 | Python 3.8.5 (v3.8.5:580fbb018f, Jul 20 2020, 12:11:27)
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license()" for more information.
>>> def main():
salelist = []
print("The store's sales for each day of the week: ")
for i in range(7):
print("The store sale of the day", (i + 1),":$",sep="",end="")
storesale = float(input(""))
salelist.append(storesale)
print("salelist:",end="")
print(salelist)
total = 0
for element in salelist:
total += element
print("The total sales for the week: $",format(total,'.2f'),sep="")
>>> main()
The store's sales for each day of the week:
The store sale of the day1:$345
The store sale of the day2:$875
The store sale of the day3:$273
The store sale of the day4:$492
The store sale of the day5:$183
The store sale of the day6:$49
The store sale of the day7:$394
salelist:[345.0, 875.0, 273.0, 492.0, 183.0, 49.0, 394.0]
The total sales for the week: $2611.00
>>>
|
13cab3d84d0f347940a9439a9395a5a3927cf88f | Inolas/python | /edX(MIT)/ProblemSets/ProblemSet4/chk.py | 355 | 3.546875 | 4 | import random
VOWELS='AEIOU'
CONSONANTS='QWRTYPLKJHGFDSZXCVBNM'
n=5
hand={}
numVowels = int(n / 3)
for i in range(numVowels):
x = VOWELS[random.randrange(0,len(VOWELS))]
hand[x] = hand.get(x, 0) + 1
for i in range(numVowels, n):
x = CONSONANTS[random.randrange(0,len(CONSONANTS))]
hand[x] = hand.get(x, 0) + 1
print(hand)
|
15e873ca10c30daba08a8b5c9b34b335bde902dc | kiccho1101/atcoder | /abc/249/b.py | 302 | 3.96875 | 4 | S = input()
st = set()
is_upper = False
is_lower = False
no_dup = True
for s in S:
if s.isupper():
is_upper = True
if s.islower():
is_lower = True
if s in st:
no_dup = False
st.add(s)
if is_upper and is_lower and no_dup:
print("Yes")
else:
print("No")
|
bd728d29792c749c60735234702f34b474f5e346 | aviato/programming_for_everyone | /7.2.py | 494 | 4 | 4 | #~~~~~~~~~~~~~~~~~~~Coursera assignment 7.2~~~~~~~~~~~~~~~~~~~
prompt = raw_input("please enter filename: ")
open_file = open(prompt)
num_list = []
count = 0
total = 0
keyword = "X-DSPAM-Confidence:"
for line in open_file:
if keyword in line:
line = line.split()
num = float(line[1])
num_list.append(num)
count += 1
for num in num_list:
total += num
print "Average spam confidence:", total / count
# ~~~~~~~~~~~~~~~~~~~~Alternate solution~~~~~~~~~~~~~~~~~~~~~
# n/a |
86d6540761c44958a0c93f1662d30e0198b911a1 | FrankXuxe/Dictionaries | /CSV_file_read_and_write.py | 275 | 4 | 4 | import csv
customers = open('customers.csv', 'r')
customer_file = csv.reader(customers, delimiter= ',')
next(customer_file)
for record in customer_file:
print(record)
print('First Name: ', record[1])
print('Last Name: ', record[2])
input()
|
f828282a76361624c22339e5f298515bd20d13b6 | coltodu123/Password-gen | /test.py | 386 | 3.609375 | 4 | #!/usr/bin/python
import itertools
#from sys import argv
user_list = raw_input("Enter the aflksdjfalsdf: ")
user_list = (s.strip() for s in user_list.split(','))
with open('datafile') as infile, open('output', 'w') as outfile:
for r in itertools.product((l.rstrip() for l in infile), user_list):
mixed = ''.join(r)
print(mixed)
outfile.write(mixed + '\n')
|
b909b14d942744779ceb009a6e3e98cc018aecd5 | Julianpse/python-exercises | /.~c9_invoke_2pcUWE.py | 399 | 4.0625 | 4 | """
#1. 1 to 10
for numbers in range(1,11):
print(numbers)
#2. n to m
n = int(input("Start from #: "))
m = int(input("End at #: "))
for number in range(n,(m+1)):
print(number)
#3 Odd Numbers
print(num)
if numbers % 2 != 0:
print(numbers)
#4 Print a Square
counter = 0
star = "*"
while counter < 6:
counter += 1
print("*" * 5)
"""
#5 Print a Square II
|
ed417e91271bd1cded60a2ef707867452adc680b | BokaDimitrijevic/Exercises-in-Python | /power_list.py | 354 | 4.25 | 4 | def power_list(numbers):
"""Given a list of numbers, return a new list where each element is the
corresponding element of the list to the power of the list index"""
new_list=[
numbers**index
for index,numbers in enumerate(numbers,start=0)
]
return new_list
print (power_list([2, 2, 2, 2, 2, 2]))
|
9cc76a640167d5e48113759865093939357f2fd0 | christian-miljkovic/interview | /Algorithms/RandomizedQuickSort.py | 1,539 | 4.25 | 4 | # Randomized Quick Sort algorithm on a list of integers
import random
"""
Time complexity
Worst Case: O(n^2) when at every step the partition procedure splits an n-length array into arrays of size 1 and n−1
or when the array is already sorted
Expected Case: O(nlogn) since you have to at least go through every value once, but the swap since we are breaking the array
into sub-arrays
"""
def quickSort(unsortedList, lowIndex, highIndex):
if(lowIndex < highIndex):
partion = randomizedPartion(unsortedList, lowIndex, highIndex)
quickSort(unsortedList, lowIndex, partion - 1)
quickSort(unsortedList, partion + 1, highIndex)
def lomutoPartion(unsortedList, lowIndex, highIndex):
pivot = unsortedList[highIndex]
i = lowIndex
for j in range(lowIndex, highIndex):
if(unsortedList[j] <= pivot):
swap(unsortedList, i, j)
i += 1
swap(unsortedList, i, highIndex)
return i
def randomizedPartion(unsortedList, lowIndex, highIndex):
partion = random.randint(lowIndex,highIndex)
swap(unsortedList, partion, highIndex)
return lomutoPartion(unsortedList, lowIndex, highIndex)
def swap(listToSwap, firstIndex, secondIndex):
tempValue = listToSwap[firstIndex]
listToSwap[firstIndex] = listToSwap[secondIndex]
listToSwap[secondIndex] = tempValue
if __name__ == '__main__':
unsortedTestList = random.sample(range(0,100),10)
print(unsortedTestList)
quickSort(unsortedTestList, 0, len(unsortedTestList) - 1)
print(unsortedTestList) |
487984effee6f8f169ac733af77bf31aadd8c449 | chinahugh/python_workspace | /python_leaning/study/class.py | 2,961 | 4.15625 | 4 | # -*- coding: utf-8 -*-
class MyClass(object):
"""一个简单的类实例"""
__i = 12345
def f(self):
return 'hello world'
def __init__(self,a):
self.data=[]
self.__a=a
print(self)
@property
def __geta(self):
return self.__a
@classmethod
def classdef(cls):
return MyClass.__i
# 实例化类
if __name__ == "__main__":
x = MyClass(9)
print("MyClass 类 x 为:", x)
print("MyClass 类 x.__dict__ 为:", x.__dict__)
print("MyClass 类 x.dir 为:", dir(x))
# 访问类的属性和方法
print("MyClass 类的属性 i 为:", x._MyClass__i)
print("MyClass 类的方法 f 输出为:", x.f())
print(x._MyClass__geta)
print(MyClass.classdef())
# ------------------------------------------------------
#类定义
# class people:
# #定义基本属性
# name = ''
# age = 0
# #定义私有属性,私有属性在类外部无法直接进行访问
# __weight = 0
# #定义构造方法
# def __init__(self,n,a,w):
# self.name = n
# self.age = a
# self.__weight = w
# def speak(self):
# print("%s 说: 我 %d 岁。" %(self.name,self.age))
#单继承示例
# class student(people):
# grade = ''
# def __init__(self,n,a,w,g):
# #调用父类的构函
# people.__init__(self,n,a,w)
# self.grade = g
# #覆写父类的方法
# def speak(self):
# print("%s 说: 我 %d 岁了,我在读 %d 年级"%(self.name,self.age,self.grade))
# s = student('ken',10,60,3)
# s.speak()
# super(student,s).speak() #调用父类方法
# -----------------------
#类定义
# class people:
# #定义基本属性
# name = ''
# age = 0
# #定义私有属性,私有属性在类外部无法直接进行访问
# __weight = 0
# #定义构造方法
# def __init__(self,n,a,w):
# self.name = n
# self.age = a
# self.__weight = w
# def speak(self):
# print("%s 说: 我 %d 岁。" %(self.name,self.age))
# print(self.__weight)
# # 实例化类
# p = people('runoob',10,30)
# p.speak()
# # -----------------
# class Vector:
# def __init__(self, a, b):
# self.a = a
# self.b = b
# def __str__(self):
# return 'Vector (%d, %d)' % (self.a, self.b)
# def __add__(self,other):
# return Vector(self.a + other.a, self.b + other.b)
# v1 = Vector(2,10)
# v2 = Vector(5,-2)
# print (v1 + v2)
# --------------------------------------
# if True:
# msg="asdasd"
# print(msg)
# ---------------------------
# def outer():
# num = 10
# def inner():
# # nonlocal num # nonlocal关键字声明
# num = 100
# print(num)
# inner()
# print(num)
# outer()
# --------------------
# import os
# os.chdir('D:\\') # 修改当前的工作目录
# os.system('mkdir today') # 执行系统命令 mkdir
# ----------------
|
54d5b8666d82eb11c7b99c34256e7c95fc357971 | ygorvieira/exerciciosPython | /ex012.py | 130 | 3.625 | 4 | #Calculando desconto (5%)
p = float(input('Digite o preço: R$'))
print('O valor com desconto é R${:.2f}'.format(p - (p*0.05)))
|
43f68055976c5548b46d35e5da8cb0cfe7006b14 | ZCT-512/Python-study-notes | /SectionB/part_2_modules/09_exercise_calculator.py | 7,007 | 3.6875 | 4 | # Author 张楚潼
# 2020/8/12 13:12
import re
# # 计算二元运算式
def step_operation(short_str):
"""
函数用来计算二元运算式,即a(+-*/)b,这个最底层的运算。
输入和返回值均为字符串类型。
a b 均可正可负,一共2*4*2=16种组合, 即支持"-1.2+-5.6", "-1.2--5.6", "-1.2*-5.6", "-1.2/-5.6 这些输入。
"""
# 先处理 +-, --, *-, /- 四种情况
if re.findall("\\+-", short_str) == ["+-"]:
short_str = re.sub("\\+-", "-", short_str)
elif re.findall("--", short_str) == ["--"]:
short_str = re.sub("--", "+", short_str)
elif re.findall("\\*-", short_str) == ["*-"]: # *- 情况又分a为+,a为- 两种
if re.findall("^-", short_str) == ["-"]:
short_str = re.sub("-", "", short_str)
else:
short_str = re.sub("-", "", short_str)
short_str = "".join(["-", short_str])
elif re.findall("/-", short_str) == ["/-"]: # /- 情况又分a为+,a为- 两种
if re.findall("^-", short_str) == ["-"]:
short_str = re.sub("-", "", short_str)
else:
short_str = re.sub("-", "", short_str)
short_str = "".join(["-", short_str])
else:
pass
one_of_three = re.findall("[*+/]", short_str) # 可解决6种情况 -5+3 -8*6 -9/7 5+3 8*6 9/7
if one_of_three == ["*"]:
multiplication_list = re.split("\\*", short_str)
return str(float(multiplication_list[0]) * float(multiplication_list[1]))
elif one_of_three == ["/"]:
division_list = re.split("/", short_str)
return str(float(division_list[0]) / float(division_list[1]))
elif one_of_three == ["+"]:
plus_list = re.split("\\+", short_str)
return str(float(plus_list[0]) + float(plus_list[1]))
# 另外两种情况 -2-5 2-5
elif re.findall("-", short_str) == ["-"]:
subtract_list = re.split("-", short_str) # 2-5 --> ["2", "5"]
return str(float(subtract_list[0]) - float(subtract_list[1]))
elif re.findall("-", short_str) == ["-", "-"]:
subtract_list = re.split("-", short_str) # -2-5 --> ["", "2", "5"]
return "".join(["-", str(float(subtract_list[1]) + float(subtract_list[2]))])
else:
print("暂不支持此种运算!")
# # 乘除法运算
def multiplication_division_operation(long_str):
while "*" in long_str or "/" in long_str:
step_part = re.search("-?\\d+\\.?\\d*[/*]-?\\d+\\.?\\d*", long_str).group() # 注意匹配二元运算式的方法
long_str = re.sub("-?\\d+\\.?\\d*[/*]-?\\d+\\.?\\d*", step_operation(step_part), long_str, 1) # 一次只替换一个二元运算式
return long_str
# # 加减法运算
def plus_subtract_operation(long_str):
# while "+" in long_str or "-" in long_str: 这个条件不可以用了
while len(re.findall("-?\\d+\\.?\\d*[+\\-]-?\\d+\\.?\\d*", long_str)) != 0:
step_part = re.search("-?\\d+\\.?\\d*[+\\-]-?\\d+\\.?\\d*", long_str).group() # 注意匹配二元运算式的方法
long_str = re.sub("-?\\d+\\.?\\d*[+\\-]-?\\d+\\.?\\d*", step_operation(step_part), long_str, 1) # 一次只替换一个二元运算式
return long_str
# # 运算函数(先乘除,后加减)
def resolution(formula):
formula = multiplication_division_operation(formula)
formula = plus_subtract_operation(formula)
return formula
# # 检查哈合法性函数
def check_legitimacy(s):
"""
检查合法性函数
如出现空格不成对、空括号、非法字符(字母,$ # @...)、非法表示(**,//,***等)
"""
flag = True
if s.count("(") != s.count(")"):
print("括号没有成对输入,请重试!")
flag = False
if re.findall("\\(\\)", s):
print("输入空括号,请重试!")
flag = False
if re.findall("[a-zA-Z_$@#%^&?<>!=\\\\]", s):
illegal_chr = re.findall("[a-zA-Z_$@#%^&?!=\\\\]", s)
print("检测到非法字符", illegal_chr, "(字母、下划线或特殊符号等),请重新输入!")
flag = False
if re.findall("\\*\\*+", s):
illegal_input = re.findall("\\*\\*+", s)
print("检测到非法输入", illegal_input, "(**,***,//,///等),请重新输入!")
flag = False
elif re.findall("//+", s):
illegal_input = re.findall("//+", s)
print("检测到非法输入", illegal_input, "(**,***,//,///等),请重新输入!")
flag = False
return flag
# # 使规范化函数
def standardize(s):
"""
使规范化函数
去空格,化简++ -+ *+ /+,并输出“正数不需要加+号”, 不论原式最外面是否有括号,再整体加一个括号。。。
"""
while re.findall("\\(-?\\d+\\.?\\d*\\)", s): # 去只括一个数的括号,如 2+(-23.3)*3
k = re.findall("\\((-?\\d+\\.?\\d*)\\)", s)
s = re.sub("\\(-?\\d+\\.?\\d*\\)", k[0], s, 1)
s = re.sub("\\s", "", s) # 去空格
s = s.replace("++", "+")
s = s.replace("-+", "-")
s = s.replace("*+", "*")
s = s.replace("/+", "/")
s = s.replace("--", "+")
s = s.replace("+-", "-")
s = "".join(["(", s, ")"]) # 最外层加括号
return s
# 输入要计算的表达式
expression = input("请输入要计算的式子:")
# 检查合法性
if check_legitimacy(expression):
# 规范化
expression = standardize(expression)
while len(re.findall("-?\\d+\\.?\\d*[+\\-*/]-?\\d+\\.?\\d*", expression)) != 0:
# # 取得第一个最里面一层多元运算式( 带一对括号,比如(8/2+7*56) )
ret = re.search("\\([^()]+\\)", expression).group()
# # 去掉括号,得到 8/2+7*56 这样的形式
m = re.findall("[^(].+[^)]", ret)[0]
# # 将其计算并替换
expression = re.sub("\\([^()]+\\)", resolution(m), expression, 1) # 一次只替换一个二元运算式
# print(expression) # 一括号,一步骤
while re.findall("\\(", expression): # 去括号
expression = expression.replace("(", " ")
expression = expression.replace(")", " ")
if re.findall(".0$", expression): # 去掉 .0
expression = re.sub(".0$", "", expression)
print(expression)
# # 2020/8/12 22:27 完成基本功能,支持加减乘除四则混合运算,支持浮点数输入 待添加1:负数输入计算问题
# # 2020/8/13 00:50 解决了负号的计算问题 待修改2:关于多元算式的结束条件(还是负号的问题!)
# # 2020/8/13 10:11 解决了待修改2 完成了要求 可增加1:更多的运算方式 比如幂运算 **, 可增加2:合法性检查,规范化函数
# # 2020/8/13 21:34 完善合法性检查,规范化函数,可继续完善检查内容
# # 2020/8/21 23:18 完善合法性检查,规范化函数
|
150c6942f2f6cd1e33c9fec384c9d075a84250a5 | polyglotm/coding-dojo | /coding-challange/leetcode/medium/147-insertion-sort-list/147-insertion-sort-list.py | 866 | 3.6875 | 4 | # 147-insertion-sort-list
# leetcode/medium/147. Insertion Sort Listx
# URL: https://leetcode.com/problems/insertion-sort-list/description/
#
# NOTE: Description
# NOTE: Constraints
# NOTE: Explanation
# NOTE: Reference
from typing import Optional
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def insertionSortList(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head:
return head
copy = []
while head:
copy.append(head)
head = head.next
dummy = ListNode(0)
new_head = dummy
for i in sorted(copy, key=lambda x: x.val):
dummy.next = ListNode(i.val)
dummy = dummy.next
head = new_head.next
return head
|
1268cf91d716456d637b92d7ef08fe9f3fb22e63 | kristenphan/BinaryTreeTraversal_inOrder_preOrder_postOrder | /tree-orders.py | 5,780 | 3.953125 | 4 | # python3
import sys, threading
sys.setrecursionlimit(10**6) # max depth of recursion
threading.stack_size(2**27) # new thread will get stack of such size
# this class represents a node in a binary tree
class Node:
def __init__(self, key, left=None, right=None):
self.key = key
self.left = left
self.right = right
# this function reads the input and returns binary tree built from the input
# based on the sample input stated in main() function, below is the value of n, key, left, and right list
# n = 10
# key = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
# left = [7, -1, -1, 8, 3, -1, 1, 5, -1, -1]
# right = [2, -1, 6, 9, -1, -1, -1, 4, -1, -1]
def read():
n = int(sys.stdin.readline())
key = [0 for i in range(n)]
left = [0 for i in range(n)]
right = [0 for i in range(n)]
for i in range(n):
[a, b, c] = map(int, sys.stdin.readline().split())
key[i] = a
left[i] = b
right[i] = c
tree = [Node(key[i], left[i], right[i]) for i in range(n)]
# build a binary tree
for i in range(n):
if tree[i].left != -1:
temp = tree[i].left
tree[i].left = tree[temp]
if tree[i].right != -1:
temp = tree[i].right
tree[i].right = tree[temp]
return tree[0] # return the root of the binary tree
# this function traverses through a binary tree in an in-order fashion
# and returns the traversal path taken
def inOrder(tree, result):
# if the current tree (represented as a node) is a leaf, append the tree's key (node's key) to result to document the traversal path and then return to the tree's parent
if tree.left == -1 and tree.right == -1:
result.append(tree.key)
return
# if the subtree has a left child, traverse down the left child subtree
if tree.left != -1:
inOrder(tree.left, result)
# append the tree's key after done traversing its left child
result.append(tree.key)
# traverse down the tree's right child(
if tree.right != -1:
inOrder(tree.right, result)
# this function traverses through a binary tree in a pre-order fashion
# and returns the traversal path taken
def preOrder(tree, result):
# if the current tree (represented as a node) is a leaf, append the tree's key (node's key) to result to document the traversal path
# and then return to the tree's parent
if tree.left == -1 and tree.right == -1:
result.append(tree.key)
return
# append the tree's key to result before traversing its left and right child
result.append(tree.key)
# if the tree has a left child, traverse down that path
if tree.left != -1:
preOrder(tree.left, result)
# if the tree has a right child, traverse down that path
if tree.right != -1:
preOrder(tree.right, result)
# this function traverses through a binary tree in a post-order fashion
# and returns the traversal path taken
def postOrder(tree, result):
# if the current tree (represented as a node) is a leaf,
# append the tree's key to result to document the traversal path and then return to the key's parent
if tree.left == -1 and tree.right == -1:
result.append(tree.key)
return
# if the tree has a left child, traverse down that path
if tree.left != -1:
postOrder(tree.left, result)
# if the tree has a right child, traverse down that path
if tree.right != -1:
postOrder(tree.right, result)
# append the tree's key to result after done traversing through its left descendents and right descendants
result.append(tree.key)
# this function reads the input, build a binary tree from the input,
# traverse through the tree in inOrder, preOrder, and postOrder
# and prints out the traversal paths
# input format:
#### The first line contains the number of vertices 𝑛. The vertices of the tree are numbered from 0 to 𝑛 − 1. Vertex 0 is the root.
#### The next 𝑛 lines contain information about vertices 0, 1, ..., 𝑛−1 in order. Each of these lines contains
#### three integers 𝑘𝑒𝑦𝑖, 𝑙𝑒𝑓𝑡𝑖 and 𝑟𝑖𝑔ℎ𝑡𝑖 — 𝑘𝑒𝑦𝑖 is the key of the 𝑖-th vertex, 𝑙𝑒𝑓𝑡𝑖 is the index of the left
#### child of the 𝑖-th vertex, and 𝑟𝑖𝑔ℎ𝑡𝑖 is the index of the right child of the 𝑖-th vertex. If 𝑖 doesn’t have
#### left or right child (or both), the corresponding 𝑙𝑒𝑓𝑡𝑖 or 𝑟𝑖𝑔ℎ𝑡𝑖 (or both) will be equal to −1.
# output format:
#### Print three lines. The first line should contain the keys of the vertices in the in-order
#### traversal of the tree. The second line should contain the keys of the vertices in the pre-order traversal
#### of the tree. The third line should contain the keys of the vertices in the post-order traversal of the tree
# example:
# input:
# 10
# 0 7 2
# 10 -1 -1
# 20 -1 6
# 30 8 9
# 40 3 -1
# 50 -1 -1
# 60 1 -1
# 70 5 4
# 80 -1 -1
# 90 -1 -1
# tree built from the input using read() operation
# 0 (root)
# / \
# 70 20
# / \ \
# 50 40 60
# / /
# 30 10
# / \
# 80 90
# below is the output in this order: in-order --> pre-order --> post-order traversal path
# 50 70 80 30 90 40 0 20 10 60
# 0 70 50 40 30 80 90 20 60 10
# 50 80 90 30 40 70 10 60 20 0
def main():
tree = read()
result_inorder = []
result_preorder = []
result_postorder = []
inOrder(tree, result_inorder)
preOrder(tree, result_preorder)
postOrder(tree, result_postorder)
print(' '.join(str(x) for x in result_inorder))
print(' '.join(str(x) for x in result_preorder))
print(' '.join(str(x) for x in result_postorder))
threading.Thread(target=main).start()
|
e5e5d4fe5c6737457c9e794cc1c09ed99a99096f | gabriellaec/desoft-analise-exercicios | /backup/user_370/ch46_2019_11_18_14_04_33_399646.py | 422 | 3.71875 | 4 | pergunta=input("Escreva uma palavra e caso queira parar digite 'fim': ")
lista_palavras=[]
while pergunta != "fim":
lista_palavras.append(pergunta)
pergunta=input("Escreva uma palavra e caso queira parar digite 'fim' ")
print(lista_palavras)
lista_final=[]
i=0
while i < len(lista_palavras):
if lista_palavras[i][0] == "a":
lista_final.append(lista_palavras[i])
i+=1
print (lista_final) |
1f3ec2d97b2a0a232d9bdaf64ff83d0b98e58eb7 | GregPhi/l2s3 | /Codage/TP6/repeat_three_times.py | 2,984 | 4.4375 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
def encode(byte):
"""
Encode the byte using repetition coding
Parameters: byte (int) – The byte to encode
Returns: A list of three bytes equal to byte
Return type: list
UC: 0 <= byte < 256
Examples:
>>> encode(123)
[123, 123, 123]
>>> encode(0)
[0, 0, 0]
"""
l=list()
for i in range(3):
l+=list(byte)
return l
def majority(bytes_read):
"""
Parameters: bytes_read – Three bytes
Type: bytes
Returns: The returned byte is constituted of the majoritarian bits among the three bytes
Return type: int
UC: len(bytes_read) == 3
Examples:
>>> majority(bytes([0b00100001, 0b10100011, 0b10000000])) == 0b10100001
True
>>> majority(bytes([0b00000000, 0b10101010, 0b01101101])) == 0b00101000
True
"""
assert len(bytes_read)==3
x1,x2,x3=bytes_read[0],bytes_read[1],bytes_read[2]
return (x1&x2)|(x2&x3)|(x1&x3)
def binary_weight(w):
"""
Parameters: w (int) – A number
Returns: The binary weight (ie. the number of 1 in the binary representation of w).
Return type: int
Examples:
>>> binary_weight(1)
1
>>> binary_weight(0)
0
>>> binary_weight(2)
1
>>> binary_weight(5)
2
>>> binary_weight(2048)
1
"""
cpt=0
p=1
while p<w:
if w&p==1:
cpt+=1
w=w>>1
if w==1:
cpt+=1
return cpt
#Q12
def nb_errors(bytes_read):
"""
Parameters: bytes_read (bytes) – Three bytes
Returns: The total number of errors among the bytes in bytes_read That corresponds to the number of positions where bits differ among the three bytes
Return type: int
UC: len(bytes_read) == 3
Examples:
>>> nb_errors(bytes([0b01, 0b10, 0b11]))
2
>>> nb_errors(bytes([0b0011100, 0b0010111, 0b1001000]))
6
"""
assert len(bytes_read)==3
x1,x2,x3=bytes_read[0],bytes_read[1],bytes_read[2]
cpt=0
while not x1==x2==x3==0:
if (x1&1)!=(x2&1) or (x1&1)!=(x3&1) or (x2&1)!=(x3&1):
cpt+=1
x1,x2,x3=x1>>1,x2>>1,x3>>1
return cpt
#Q13
def decode(bytes_read):
"""
Takes three bytes (encoded with repetition three times) and return a byte plus some information on the number of errors
Parameters: bytes_read (bytes) – Three bytes
Returns: A tuple whose first component is the byte made by looking at each position in the three bytes what bit is in majority, the second component is the number of detected errrors, and the last component is the number of corrected errors (both numbers are equal here).
Return type: tuple
UC: len(bytes_read) == 3
Examples:
>>> decode(bytes([0b00100001, 0b10100011, 0b10000000])) == (0b10100001, 4, 4)
True
>>> decode(b'LLL')==(76, 0, 0)
True
"""
assert len(bytes_read) == 3
maj=majority(bytes_read)
err=nb_errors(bytes_read)
return (maj,err,err)
|
f474217c34b0dc6522f8137abe00cb0e4113b3e5 | Malcolm314159/Python-math | /math6.py | 321 | 3.921875 | 4 | #math6
print("Hello World")
#variables
sum = 0
sum1 = 0
for i in range(1, 101):
sum += i
sum1 += i**2
square = sum**2
difference = square - sum1
print("The sum of the squares is "+str(sum1))
print("The square of the sum is "+str(square))
print("The difference between those two is "+str(difference)) |
f43369fa6391d8d99698105f0e8716893cfbe44a | noorulameenkm/DataStructuresAlgorithms | /DynamicProgramming/longest_common_subsequence.py | 1,224 | 3.8125 | 4 | def maximum(a,b):
return a if a > b else b
def LCS(x,y,x_length,y_length):
table = [[0 for i in range(x_length + 1)] for j in range(y_length + 1)]
for i in range(y_length + 1):
for j in range(x_length + 1):
if i == 0 or j == 0:
table[i][j] = 0
elif y[i-1] == x[j-1]:
table[i][j] = table[i - 1][j - 1] + 1
else:
table[i][j] = maximum(table[i - 1][j],table[i][j - 1])
return table[y_length][x_length]
def Main():
x = input()
y = input()
print("LCS is", LCS(x,y,len(x),len(y)))
if __name__ == '__main__':
Main()
"""
While Filling the table each cell means we are considering
strings till that cell, if the last character matches
then cell value will be 1 + LCS(removing that char from
string1, removing that char from string2)(which means looking
into the diagonal cell [i-1][j-1]), if the last character
doesn't match then the cell value is maximum(LCS(removing
not matching char from string1, not removing any char from string2)
,LCS(not removing any char from string1, removing
not matching char from string2))(which means the max([i][j-1],[i-1][j]))
"""
|
a582580bf78ae9efebdc7f4c86e73938e8559680 | TaurusCanis/ace_it | /ace_it_test_prep/static/scripts/test_question_scripts/math_questions/Test_1/math_2/math_T1_S2_Q9.py | 1,909 | 4.21875 | 4 | import random
trap_mass = random.randint(125,175)
mouse_mass = random.randint(3,6)
answer = trap_mass - (mouse_mass * 28) - 1
question = f"<p>The mass required to set off a mouse trap is {trap_mass} grams. Of the following, what is the largest mass of cheese, in grams, that a {mouse_mass}-ounce mouse could carry and <u>not</u> set off the trap? (1 ounce = 28 grams)</p>\n"
options = [
{
"option": answer,
"correct": True
},
{
"option": answer + 1,
"correct": False
},
{
"option": "28",
"correct": False
},
{
"option": mouse_mass * 28,
"correct": False
},
{
"option": trap_mass - (mouse_mass * 25),
"correct": False
}
]
random.shuffle(options)
print(question)
letter_index = 65
for option in options:
print(chr(letter_index) + ": " + str(option["option"]))
letter_index += 1
user_response = input("Choose an answer option: ")
if options[ord(user_response.upper()[0]) - 65]["correct"]:
print("CORRECT!")
else:
print("INCORRECT!")
print(answer)
# "distractor_rationale_response_level":[
# "You used the conversion rate as the maximum mass of cheese, but the conversion rate is only used to determine the mass of the mouse in grams.",
# "A mouse weighing 4 ounces has a mass of 112 grams, since 4 × 28 = 112. Since 157 – 112 = 45, the cheese must weigh less than 45 grams for the trap to not be be set off. The largest given mass that is less than 45 grams is 44 grams.",
# "You solved the equation 157 – <em>x </em>= 112, but overlooked that the solution represents the minimum mass of cheese that would set off the trap.",
# "You may have multiplied 4 by 25 instead of 28 to find the mass of the mouse in grams, but that mass is 128 grams.",
# "You identified the mass of the mouse in grams, rather than the maximum mass of the cheese that will not set off the trap."
# ]
|
739ea906e1f8acd0a43313e0b890a7937de11c2a | jeanpierrethach/Design-Patterns | /src/main/python/patterns/chain-of-responsability/chain_of_responsability.py | 1,458 | 3.796875 | 4 | from abc import ABC, abstractmethod
class Handler(ABC):
def __init__(self, balance):
self._successor = None
self._balance = balance
def set_successor(self, handler):
self._successor = handler
def can_handle_request(self, amount):
return self._balance >= amount
def handle_request(self, amount):
if self.can_handle_request(amount):
print("Paid by %s" % self.get_name())
print("Old balance: %f" % self._balance)
self._balance -= amount
print("New balance: %f" % self._balance)
elif self._successor:
print(self.get_name() + " cannot pay")
self._successor.handle_request(amount)
else:
print("None could handle the request")
@abstractmethod
def get_name(self):
pass
class Receiver1(Handler):
def get_name(self):
return "Receiver 1"
class Receiver2(Handler):
def get_name(self):
return "Receiver 2"
class Receiver3(Handler):
def get_name(self):
return "Receiver 3"
class Receiver4(Handler):
def get_name(self):
return "Receiver 4"
if __name__ == '__main__':
receiver1 = Receiver1(100)
receiver2 = Receiver2(200)
receiver3 = Receiver3(300)
receiver4 = Receiver4(400)
receiver1.set_successor(receiver2)
receiver2.set_successor(receiver3)
receiver3.set_successor(receiver4)
receiver1.handle_request(350) |
14e8fc7a9b96ae38c48f8c13d709a4efd90f4300 | saradhimpardha/Jupyter_notebooks_AMS | /Computer_Animation/Vorlesung_7/videofiledisp.py | 571 | 3.53125 | 4 | import numpy as np
import cv2
import sys
#Program to open a video input file in argument and display it on the screen.
#command line example: python videofiledisp.py video.mts
#Gerald Schuller, march 2015
cap = cv2.VideoCapture(str(sys.argv[1]))
while(cap.isOpened()):
ret, frame = cap.read()
cv2.imshow('Video',frame)
#Wait for key for 50ms, to get about 20 frames per second playback
#(depends also on speed of the machine, and recording frame rate, try out):
if cv2.waitKey(50) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
|
e4f143b4bf52d56d26d34a228b4c5c987c66b02a | BotondSiklosi/Calendar | /cal.py | 3,867 | 3.609375 | 4 | import sys
import ui
# printing data, asking user for input
import storage
# saving and loading files
MEETING_TITLE = 0
HOW_LONG = 1
STARTING_TIME = 2
def edit_meeting(table, items_to_edit):
new_line = []
new_line_option_list = ["Enter a new meeting title", "Enter a new duration in hours (1 or 2)", "Enter a new start time"]
for i in range(len(table)):
if items_to_edit == table[i][STARTING_TIME]:
new_line = ui.get_input(new_line_option_list, "Edit an existing meeting")
table[i] = new_line
storage.write_file_from_table("meetings.txt", table)
return table
def valid_time_error(items_to_add, table):
work_starts = 8
work_ends = 18
if int(items_to_add[STARTING_TIME]) + int(items_to_add[HOW_LONG]) > work_ends:
return True
if int(items_to_add[STARTING_TIME]) < work_starts:
return True
else:
return False
def already_used_time(items_to_add, table):
for i in table:
if items_to_add[STARTING_TIME] == i[STARTING_TIME]:
return True
if i[HOW_LONG] == "2":
if int(items_to_add[STARTING_TIME]) == (int(i[STARTING_TIME]) + 1):
return True
else:
return False
def too_long_meeting(items_to_add, table):
for i in table:
if items_to_add[HOW_LONG] == "1" or items_to_add[HOW_LONG] == "2":
return False
return True
def schedule_new_meeting(table):
labels_title = ["Enter meeting title", "Enter duration in hours (1 or 2)", "Enter start time"]
while True:
items_to_add = ui.get_input(labels_title, "Schedule a new meeting.")
if valid_time_error(items_to_add, table) == True:
ui.print_error_message("Meeting is outside of your working hours (8 to 18)!")
continue
if already_used_time(items_to_add, table) == True:
ui.print_error_message("Meeting overlaps with existing meeting!")
continue
if too_long_meeting(items_to_add, table) == True:
ui.print_error_message("Duration is out of range!")
continue
else:
table.append(items_to_add)
storage.write_file_from_table("meetings.txt", table)
return table
def cancel_existing_meeting(table):
labels_title = ["Enter the start time"]
while True:
inputs = ui.get_input(labels_title, "Cancel an existing meeting.")
item_to_delete = inputs[0]
if any(item_to_delete in i for i in table):
for i in table:
if i[STARTING_TIME] == item_to_delete:
table.remove(i)
storage.write_file_from_table("meetings.txt", table)
return table
else:
ui.print_error_message("There is no meeting starting at that time!")
def handle_menu():
options = ["schedule a new meeting", "cancel an existing meeting", "edit an existing meeting"]
ui.print_menu("Menu", options, "quit")
def main_menu():
table = storage.get_table_from_file("meetings.txt")
ui.print_table("Your schedule for the day", table)
handle_menu()
inputs = ui.get_input(["Your choise"], "")
options = inputs[0]
if options == "s":
schedule_new_meeting(table)
if options == "c":
cancel_existing_meeting(table)
if options == "e":
starting_time_input = ui.get_input(["Which meeting would you like to edit (starting time)"], "")
items_to_edit = starting_time_input[0]
edit_meeting(table, items_to_edit)
if options == "q":
sys.exit(0)
else:
ui.print_error_message("There is no such option.")
def main():
while True:
try:
main_menu()
except KeyError as err:
ui.print_error_message(str(err))
if __name__ == "__main__":
main()
|
36382d14f4c5ba35d44a7a1e155235e9e3db7ce0 | betelgeuse06/BrokenGoodac_CodingMaker | /BrokenStar/Rock Scissors Paper.py | 626 | 3.796875 | 4 | import random
for i in range(5):
num=int(input("0.가위 1.바위 2.보 중 하나를 선택하세요>>\n"))
com=random.randrange(1,3)
if num>2:
print("잘못 누르셨습니다")
elif num==com:
print("비겼습니다")
elif num+1==com or (num==2 and com==0):
print("컴퓨터 승리")
else:
print("내가 승리")
#내가 가위내면(num=0)-> com=1(진다),com=2(이긴다)
#내가 바위내면 (num=1)-> com=0(이긴다), com= 2(진다)
#내가 보 내면(num=2) -> com=1(이긴다),com=0(진다)
com=random.randrange(1,3)
print(com)
|
b26ce85c9688fe09256d81394479544d895dfc5d | YoyinZyc/Leetcode_Python | /Google/Event Queue.py | 1,356 | 3.921875 | 4 | '''
设计一个event queue。
要求给 定一个event,判断在这个 event之前的一个固定时间段里 有没有出现大于k个event。
event可能是按时间顺序来也可 能是随机来
random:
用heap
顺序:
一个长度为k的queue,小于k,加入;大于k,弹出老的,放入新的
'''
import heapq
from collections import deque
class EventQueue(object):
def __init__(self,k,time):
self.queue = deque()
self.k = k
self.time = time
def random_add(self,e):
if len(self.queue) >= self.k:
heapq.heappush(self.queue, e)
i = self.queue.index(e)
if i < self.k:
return False
elif e - self.queue[i-self.k] <= self.time:
return True
else:
return False
else:
heapq.heappush(self.queue, e)
return False
def add(self,e):
if len(self.queue) >= self.k:
first = self.queue[0]
self.queue.popleft()
self.queue.append(e)
if e-first <= self.time:
return True
else:
return False
else:
self.queue.append(e)
return False
if __name__ == '__main__':
e = EventQueue(3,20)
es = [1,2,4,7,50]
for v in es:
print(e.add(v)) |
2612a1ba7a0ace3cf7083c1e143124702bc4ef72 | TCavalcanti/JudgeCode | /listasDescompactadas/110066518/3.py | 357 | 3.5625 | 4 | if __name__ == '__main__':
[x, y] =[int(i) for i in raw_input().split()]
if x > y:
maior = x
menor = y
else:
menor = x
maior = y
lista = [k for k in range(menor, maior)]
lista.append(maior)
soma = 0
for x in lista:
if x%13 != 0 :
soma+=x
print "%d" % soma |
278664fd2b898eabf50f4d5f37d4f03d7c3868df | vijayroykargwal/Infy-FP | /OOPs/Day1/src/Assign9.py | 2,109 | 3.703125 | 4 | #OOPR-Assgn-9
'''
Created on Mar 5, 2019
@author: vijay.pal01
'''
#Start writing your code here
class Student:
def __init__(self):
self.__student_id = None
self.__age = None
self.__marks = None
self.__course_id = None
self.__fees = None
def get_course_id(self):
return self.__course_id
def get_fees(self):
return self.__fees
def get_student_id(self):
return self.__student_id
def get_age(self):
return self.__age
def get_marks(self):
return self.__marks
def set_student_id(self, student_id):
self.__student_id = student_id
def set_age(self, age):
self.__age = age
def set_marks(self, marks):
self.__marks = marks
def validate_marks(self):
if(self.get_marks()>=0 and self.get_marks()<=100):
return True
else:
return False
def validate_age(self):
if(self.get_age()>20):
return True
else:
return False
def check_qualification(self):
if(self.get_marks()>=0 and self.get_marks()<=100 and self.get_age()>20):
if(self.get_marks()>=65):
return True
else:
return False
else:
return False
def choose_course(self,course_id):
if(course_id==1001):
self.__course_id = 1001
self.__fees = 25575.0
if(self.get_marks()>85):
self.__fees = 0.75*self.__fees
return True
elif(course_id==1002):
self.__course_id = 1002
self.__fees = 15500.0
if(self.get_marks()>85):
self.__fees= 0.75*self.__fees
return True
else:
return False
s1 = Student()
s1.set_student_id(167)
s1.set_age(22)
s1.set_marks(85)
s1.validate_marks()
s1.validate_age()
s1.check_qualification()
s1.choose_course(1002)
|
9e4946435fcd7495435ea7fa168718b5a119fa79 | ibbur/PCC | /bicycles.py | 1,352 | 3.796875 | 4 | # Aaron Frankel 2019-6-19
# The purpose of this file is to exercise lists
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles)
print(bicycles[0])
print(bicycles[0].title())
print(bicycles[1])
print(bicycles[1].title())
print("\n")
print(bicycles[1].title())
print(bicycles[3].title())
print("\n")
print(bicycles[-1].title() + " is the last item in the list.")
print("\n")
message = "My first bicycle was a " + bicycles[0].title() + "."
print(message)
print("\n")
friends = ['jonathan', 'jason', 'ron', 'mark']
flisttest_jon = "Howdy, " + friends[0].title() + "!"
flisttest_jas = "Howdy, " + friends[1].title() + "!"
flisttest_ron = "Howdy, " +friends[2].title() + "!"
flisttest_mar = "Howdy, " + friends[3].title() + "!"
print(flisttest_jon + '\n'+ flisttest_jas + '\n' + flisttest_ron + '\n' + flisttest_mar + '\n')
# Yes, that last line was over the "80 Character limit
vehicles = ['cars','pickup trucks','motorcycles','bicycles']
cars = "I like the way Astin Martin makes " + vehicles[0] + " and would like to own one some day."
trucks = "I prefer driving " + vehicles[1] + ", most days."
motorcycles = "I miss riding " + vehicles[2] + " with my Dad."
bicycles = vehicles[-1].title() + " just don't thrill me after having ridden " + vehicles[2] + "."
print(cars + '\n' + trucks + '\n' + motorcycles + '\n' + bicycles)
|
80771648ba45e3b7999f1f403e1b160769ac5ae4 | sibylle69/CS50-Harvard-course-exercises | /sibylle69-cs50-problems-2020-x-readability/sibylle69-cs50-problems-2020-x-readability/readability.py | 682 | 3.875 | 4 | import math
from cs50 import get_string
def main():
string = get_string("Text: \n");
word = 0;
ltrs = 0;
stce = 0;
i = 0;
for i in range(len(string)):
if string[i].isalpha():
ltrs += 1
elif string[i] == ' ':
word += 1
elif string[i] == '!' or string[i] == '.' or string[i] == '?':
stce += 1
ltrs = (ltrs / word) * 100
stce = (stce / word) * 100
formula = (0.0588 * ltrs - 0.296 * stce - 15.8)
grade = int(round(formula))
if grade > 16:
print("Grade 16+")
elif grade > 1:
print(f"Grade {grade}")
else:
print("Before Grade 1")
main()
|
6ca5a677a76ff287e1edabfb46b6f898e5965492 | dmnhwjin/Python | /leapYear.py | 655 | 3.671875 | 4 | #!c:\python\python.exe
import sys
import string
if len(sys.argv)<2:
print "Usage:leap.py year,year,year..."
sys.exit(0)
for i in sys.argv[1:]:
try:
y=string.atoi(i)
except:
print i,"Is not a year."
continue
leap="no"
if y % 400 ==0:
leap = "Yes"
elif y %100 ==0:
leap = "no"
elif y % 4 == 0:
leap = "yes"
else:
leap = "no"
print y,"leap:", leap,"In the Gregorian calendar"
if y % 4 ==0:
leap = "yes"
else :
leap = "no"
print y,"leap:",leap,"in the Julian calendar"
print "Calculated leapness for ",len (sys.argv)-1,"years"
|
449e1d30bea8359340dbeb02d69d6fb63dafbcd1 | samlobel/PROJECT_EULER_SOLUTIONS | /064/solution.py | 338 | 3.53125 | 4 |
"""
So, 23:
Between 4 and 5.
4 + (√23 - 4).
√23-4 = 1.25....
so, 4, 1
1/(ans-1) = 3.89...
4,1,3
We've got some interesting stuff here.
But the harder part is that we need to actually keep the
actual symbolic solving, not the float.
"""
def solve(n, so_far, dict_so_far):
i_n = int(n)
b = 1.0/(n - i_n)
pass
|
8fb8af942b244d181cb12f8b2abae188593beef7 | Tejas-Naik/Tic-Tac-Toe | /main.py | 3,841 | 4.09375 | 4 | instruction_board = {'7': '7', '8': '8', '9': '9',
'4': '4', '5': '5', '6': '6',
'1': '1', '2': '2', '3': '3',
}
the_board = {'7': ' ', '8': ' ', '9': ' ',
'4': ' ', '5': ' ', '6': ' ',
'1': ' ', '2': ' ', '3': ' ',
}
def instructions(board):
print("Welcome to the Tic-Tac-Toe Club")
print()
print("The format of board is as follows: ")
print(board["7"] + "|" + board["8"] + "|" + board["9"])
print('-+-+-')
print(board["4"] + "|" + board["5"] + "|" + board["6"])
print('-+-+-')
print(board["1"] + "|" + board["2"] + "|" + board["3"])
print("Enjoy the Game!! Good Luck")
print()
def print_board(board):
print()
print(board["7"] + "|" + board["8"] + "|" + board["9"])
print('-+-+-')
print(board["4"] + "|" + board["5"] + "|" + board["6"])
print('-+-+-')
print(board["1"] + "|" + board["2"] + "|" + board["3"])
print()
def game():
instructions(instruction_board)
turn = "X"
count = 0
input("ENTER to start the game!")
for i in range(10):
print_board(the_board)
move = input("It's your turn, " + turn + ".\nPlease enter the number you want!")
if the_board[move] == " ":
the_board[move] = turn
count += 1
else:
print("That's already filled Please choose again: ")
continue
if count >= 5:
if the_board['7'] == the_board['8'] == the_board['9'] != ' ': # across the top
print_board(the_board)
print("\nGame Over.\n")
print(" **** " + turn + " won. ****")
break
elif the_board['4'] == the_board['5'] == the_board['6'] != ' ': # across the middle
print_board(the_board)
print("\nGame Over.\n")
print(" **** " + turn + " won. ****")
break
elif the_board['1'] == the_board['2'] == the_board['3'] != ' ': # across the bottom
print_board(the_board)
print("\nGame Over.\n")
print(" **** " + turn + " won. ****")
break
elif the_board['1'] == the_board['4'] == the_board['7'] != ' ': # down the left side
print_board(the_board)
print("\nGame Over.\n")
print(" **** " + turn + " won. ****")
break
elif the_board['2'] == the_board['5'] == the_board['8'] != ' ': # down the middle
print_board(the_board)
print("\nGame Over.\n")
print(" **** " + turn + " won. ****")
break
elif the_board['3'] == the_board['6'] == the_board['9'] != ' ': # down the right side
print_board(the_board)
print("\nGame Over.\n")
print(" **** " + turn + " won. ****")
break
elif the_board['7'] == the_board['5'] == the_board['3'] != ' ': # diagonal
print_board(the_board)
print("\nGame Over.\n")
print(" **** " + turn + " won. ****")
break
elif the_board['1'] == the_board['5'] == the_board['9'] != ' ': # diagonal
print_board(the_board)
print("\nGame Over.\n")
print(" **** " + turn + " won. ****")
break
if count == 9:
print("Well it's a Tie!")
break
if turn == "X":
turn = "O"
else:
turn = "X"
play_again = input("Do you wanna play again(y/n)").lower()
if play_again == "y":
game()
else:
print("Thank you for playing! Have a good Day")
if __name__ == "__main__":
game()
|
17dc3dd3909a38ef5b2d6e95f8c6469ced70b0eb | Rhapsody0128/python_learning | /base/07.dictionary.py | 5,032 | 3.859375 | 4 | # 字典和json非常像,但是從本質上講,字典是一種數據結構,而json是一種格式;
# 字典有很多內置函數,有多種調用方法,而json是數據打包的一種格式,並不像字典具備操作性,並且是格式就會有一些形式上的限制,比如json的格式要求必須且只能使用雙引號作為key或者值的邊界符號,不能使用單引號,而且“key”必須使用邊界符(雙引號),但字典就無所謂了。
# * 存取字典中的值
# 在python中字典是一系列的鍵-值對,每一個鍵都有一個對應的值,與鍵相關的可以是數值、串列、也可以是另一個字典,在python中字典是用大括號{ }括住一系列的鍵-值對,鍵和值之間是用冒號來分隔,鍵-值對之間是用逗號分開,如果想存取鍵相關的值,可給定字典的名稱,然後以中括號括住指定的鍵
car = {"color":"black","brand":"Toyota"} # 建立一個car字典裡面包含兩個鍵值對
color = car["color"] # 將car字典中color鍵對應的值存到color變數內
print("The car's color is "+color) # 印出color
# * 新增鍵值對
# 字典是動態的結構,可隨時新增鍵-值對進去,想要新增鍵其實跟存取的方式差不多,用法是給定字典的名稱,然後用中括號括住想要新增鍵的名字,再給定鍵的值
car = {"color":"black","brand":"toyota"} # 建立一個car字典裡面包含兩個鍵值對
car["mileage"] = 10 # 新增一個鍵為"mileage"值為10到car字典
print(car) # 印出新增鍵值對後的car字典
# * 修改鍵值對
# 修改鍵對應的值一樣需要給定字典名稱,然後使用中括號括住鍵,再把相關聯的新值指定過去即可
car = {"color":"black","brand":"toyota"} # 建立一個car字典裡面包含兩個鍵值對
car["color"] = "white" # 將car字典中color鍵的值更改成white
print(car) # 印出修改值後的car字典
# * 刪除鍵值對
# 我們是用del陳述句把對應的鍵-值對永久的刪除掉,使用的方法也是跟新增存取一樣,要給定字典的名稱和要刪除的鍵
car = {"color":"black","brand":"toyota"} # 建立一個car字典裡面包含兩個鍵值對
del car["color"] # 刪除car字典中color鍵和它對應的值
print(car) # 印出刪除值後的car字典
# * 遍訪字典中所有的鍵-值對( items()方法 )
car = {"color":"black","brand":"toyota"} # 建立一個car字典裡面包含兩個鍵值對
for key,value in car.items(): # items()方法會讓for迴圈將每個鍵-值對分別存到key和value的變數中
print("key : "+key) # 印出鍵
print("value : "+value) # 印出值
# * 遍訪字典中所有的鍵( keys()方法 )
car = {"color":"black","brand":"toyota"} # 建立一個car字典裡面包含兩個鍵值對
for key in car.keys(): # keys()方法會讓for迴圈將每個鍵存到key變數中
print("key : "+key) # 印出鍵
# * 遍訪字典中所有的值( values()方法 )
car = {"color":"black","brand":"toyota"} # 建立一個car字典裡面包含兩個鍵值對
for value in car.values(): # values()方法會讓for迴圈將每個值存到value變數中
print("value : "+value) # 印出值
# * 以特定順序遍訪字典的鍵( sorted()方法 )
favorite_fruits={"jack":"banana","rose":"grape","steven":"apple","bonny":"apple"} # 建立一個favorite_fruits字典裡面包含四個鍵值對
for key in sorted(favorite_fruits.keys()): # sorted()方法包住keys()方法會讓for迴圈將每個鍵依照字母順序排好存到key變數中
print(key) # 印出鍵
# * 刪除重複的值( set()方法 )
favorite_fruits={"bonny":"apple","jack":"banana","rose":"grape","steven":"apple"} # 建立一個favorite_fruits字典裡面包含四個鍵值對(steven和bonny的value都是"apple")
print("the following fruits have been mentioned :")
for value in set(favorite_fruits.values()) : # set()方法包住keys()方法會讓for迴圈將不重複的值存到value變數中
print(value) # 印出值
# * 字典中的字典
# 建立一個字典裡面包含兩個字典
pets={
"dog":{
"name":"Tony",
"age":4,
"gender":"male",
},
"cat":{
"name":"Kate",
"age":3,
"gender":"female",
},
}
for pet,pet_info in pets.items() : # items()方法會讓for迴圈將每個鍵-值對分別存到pet和pet_info的變數中
print("I have a "+pet+",its name is "+pet_info["name"]+","
+str(pet_info["age"])+" years old,and gender is "+pet_info["gender"] ) # 分別取得鍵(dog,cat)和從字典中的字典取得值
# * 字典中的串列
colors={"orange":["red","yellow"],"green":["blue","yellow"]} # 建立一個colors字典裡面有兩個鍵值對
for keys,values in colors.items() : # items()方法會讓for迴圈將每個鍵-值對分別存到keys和values的變數中
print("If you want to get color "+keys)
print("you need to add :")
for value in values: # 告知python從values串列中取出值,並將取出的值存到value變數內
print(value) |
83fddeb3ea7d770e181922942213e691984b4182 | JoamirS/Exercicios-Python | /Udemy/Class_02.py | 255 | 3.71875 | 4 | first_variable = 'Joamir'
second_variable = 'Maria'
third_variable = 'José'
string = f'a={first_variable} b={second_variable} a={third_variable} c={first_variable}'
formato = string.format(first_variable, second_variable, third_variable)
print(formato)
|
0db2e16aac49991b2be1f3c3278593a37c728cdd | anmolrajaroraa/CorePythonMarch | /while_loop.py | 375 | 4.3125 | 4 | #choice = ""
#while choice != "no":
while True:
num = int(input("Enter a number to check for odd and even : " ))
if num == 0:
print("Please don't enter 0")
continue
elif num % 2 == 0:
print(num, "is even")
else:
print(num, "is odd")
choice = input("Do you want to continue ? ")
if choice == "no":
break
|
3291e6be9dfadf357d7b9aa2dff94d9ec5bdcc70 | wanax/Leetcode | /facebook/tree/199. Binary Tree Right Side View.py | 1,110 | 3.5 | 4 | '''
Xiaochi Ma
2018-11-12
'''
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def rightSideView(self, root):
dic = {}
max_depth = -1
stack = [(root, 0)]
while stack:
node, depth = stack.pop(0)
if node is not None:
max_depth = max(max_depth, depth)
dic[depth] = node.val
stack.append((node.left, depth+1))
stack.append((node.right, depth+1))
return [dic[depth] for depth in range(max_depth + 1)]
if __name__ == '__main__':
root = TreeNode(1)
node1 = TreeNode(2)
node2 = TreeNode(3)
node3 = TreeNode(5)
node4 = TreeNode(4)
root.left = node1
root.right = node2
node1.right = node3
node2.right = node4
solution = Solution()
print(solution.rightSideView(root))
|
0dc7fbf2ac1bde319db1968a157746b77262c6de | williamlopez/Choose-Your-Own-Adventure- | /ChooseYourOwnAdventure.py | 1,651 | 4.4375 | 4 | # Choose.py
# by [Marcos,William,Justin,Luis]
# Description: starter code for the Choose Your
# Own Adventure Project
#asdlf;j
# Import Statements
from tkinter import *
import tkinter.simpledialog
import tkinter.messagebox
root = Tk()
w = Label(root, text="Choose Your Own Adventure")
w.pack()
def intro():
""" Introductory Function -> starts the story going """
messagebox.showinfo("Title", "\nHello, you are a high schooler from Luisito High School. " + \
"You want to try out to a professional soccer club form Oregon like Timbers. Alright? ")
choice = simpledialog.askinteger("Choose wisely",
"Would you like to try out? (When 1 is 'yes' and 2 is 'no'). ")
if choice == 1:
choice1()
elif choice == 2:
choice2()
else:
intro()
################ Student A Functions #####################
def choice1():
choice = simpledialog.askinteger("Choose wisely",
"Eat appropriate food before training? Now you must choose 1(Yes) or 2(No) again.")
if (choice == 1):
messagebox.showinfo("Yes",
"Training goes amazing! You're offered a spot on the team.")
elif (choice == 2):
messagebox.showinfo("No",
"Training goes bad, and you go back home.")
else:
choice1()
################ Student B Functions #####################
def choice2():
choice = messagebox.showinfo("Bye Bye",
"You will regret it!!!!!")
################ Main #####################
intro()
root.destroy()
|
3183d30be025bcaceaeeb62c6c0895d1c223db96 | louisuss/Algorithms-Code-Upload | /Python/FastCampus/recursion/1074+.py | 661 | 3.53125 | 4 | def z_func(n, r, c):
global number
# 2가 최소값임
if n == 2:
if r == R and c == C:
print(number)
return
number += 1
if r == R and c+1 == C:
print(number)
return
number += 1
if r+1 == R and c == C:
print(number)
return
number += 1
if r+1 == R and c+1 == C:
print(number)
return
number += 1
return
z_func(n/2, r, c)
z_func(n/2, r, c + n/2)
z_func(n/2, r + n/2, c)
z_func(n/2, r + n/2, c + n/2)
number = 0
n, R, C = map(int, input().split())
z_func(2**n, 0, 0)
|
44689b280347835c761723ef508035ac81b1b646 | valeriekamen/python | /palindrome.py | 4,786 | 3.578125 | 4 | import math
"""
Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
Input: "aab"
Output:
[
["aa","b"],
["a","a","b"]
]
Input: "aabaa"
Output: [["a","a","b","a","a"],["a","a","b","aa"],["a","aba","a"],["aa","b","a","a"],["aa","b","aa"],["aabaa"]]
"""
class Palindrome:
def __init__(self, s):
self.s = s
self.res = []
self.pals = {}
def check_if_pal(self, s):
r = math.floor(len(s) / 2)
for i in range(r):
if s[i] != s[-(i + 1)]:
return False
return True
def make_into_str_list_and_append(self, alist):
output = []
for item in alist:
astr = self.s[item[0] : item[1]]
output.append(astr)
self.res.append(output)
def recur(self, thislist, start, end):
thislist.append((start, end))
ends = self.pals.get(end)
if not ends:
print(thislist)
self.make_into_str_list_and_append(thislist)
return
else:
for e in ends:
newlist = thislist.copy()
self.recur(newlist, end, e)
def get_all_pals(self):
s_len = len(self.s)
# create hashtable for all pals
for i in range(s_len):
for j in range(s_len):
this_str = self.s[i : j + 1]
if this_str and self.check_if_pal(this_str):
if i in self.pals:
self.pals[i].append(j + 1)
else:
self.pals[i] = [j + 1]
print(self.pals)
for end in self.pals.get(0):
l = []
self.recur(l, 0, end)
print(self.res)
p = Palindrome("aabaa")
p.get_all_pals()
# def recur(res, newlist, end, start, pals):
# newlist.append((start, end))
# ends = pals.get(end)
# print("START AND ENDS ", start, ends)
# print("NEWLIST", newlist)
# if not ends:
# print("APPENDING")
# res.append(newlist)
# else:
# for e in ends:
# thislist = newlist
# print("NEXT", thislist)
# recur(res, thislist, e, end, pals)
# newlist = []
# return res
# def palindrome(s):
# output = []
# pals = {}
# s_len = len(s)
# # create hashtable for all pals
# for i in range(s_len):
# for j in range(s_len):
# this_str = s[i : j + 1]
# if this_str and check_if_pal(this_str):
# if i in pals:
# pals[i].append(j + 1)
# else:
# pals[i] = [j + 1]
# print(pals)
# for end in pals.get(0):
# bigr = []
# r = []
# res = recur(bigr, r, end, 0, pals)
# output.extend(res)
# print(output)
# def check_if_pal(s):
# r = math.floor(len(s) / 2)
# for i in range(r):
# if s[i] != s[-(i + 1)]:
# return False
# return True
# def recur(res, newlist, end, start, pals):
# newlist.append((start, end))
# ends = pals.get(end)
# print("START AND ENDS ", start, ends)
# print("NEWLIST", newlist)
# if not ends:
# print("APPENDING")
# res.append(newlist)
# else:
# for e in ends:
# thislist = newlist
# print("NEXT", thislist)
# recur(res, thislist, e, end, pals)
# newlist = []
# return res
# def palindrome(s):
# output = []
# pals = {}
# s_len = len(s)
# # create hashtable for all pals
# for i in range(s_len):
# for j in range(s_len):
# this_str = s[i : j + 1]
# if this_str and check_if_pal(this_str):
# if i in pals:
# pals[i].append(j + 1)
# else:
# pals[i] = [j + 1]
# print(pals)
# for end in pals.get(0):
# bigr = []
# r = []
# res = recur(bigr, r, end, 0, pals)
# output.extend(res)
# print(output)
# palindrome("aabaa")
# # from someone else
# class Solution:
# # @param s, a string
# # @return a list of lists of string
# def partition(self, s):
# self.res = []
# self.findPalindrome(s, [])
# return self.res
# def findPalindrome(self, s, plist):
# if len(s) == 0:
# self.res.append(plist)
# for i in range(1, len(s) + 1):
# if self.isPalindrome(s[:i]):
# self.findPalindrome(s[i:], plist + [s[:i]])
# def isPalindrome(self, s):
# if s == s[::-1]:
# return True
# else:
# return False
# a = Solution()
# print(a.partition("aabaa"))
|
6a685a0427854028c5541a13f18bdfcd0b9e2925 | PuttTim/MundaneUnevenBug | /hour min.py | 93 | 3.640625 | 4 | hour=0
minute=0
for hour in range (11+1):
for minute in range (59+1):
print(hour, minute)
|
43db3d24815b7928657c03061650deb2fa687b5e | Jiangstte/treasure-house | /t2.py | 498 | 3.6875 | 4 | people = {
'lg' : {
'phone': '12345',
'add': '71905',
},
'lh' : {
'phone' : '23456',
'add' : '71904',
},
'lj' : {
'phone' : '34567',
'add' : '71903',
},
}
#jieshi = {
#'p' : 'phone',
#'a' : 'addres',
#}
name = raw_input('the name is:')
request = raw_input('phone(p) number or address(a):')
if request == 'p': key = 'phone'
if request == 'a': key = 'add'
if name in people: print "%s's %s is %s." % (name,key,people[name][key],)
|
45a82527d6560beaeb597f6c84a2d895aa67a527 | davidlu2002/AID2002 | /PycharmProjects/Stage 2/day18/thread_1.py | 665 | 3.515625 | 4 | """
thread_1.py 线程使用1
"""
from threading import Thread
from time import sleep
import os
a = 1 # 主线程的变量
def fun():
for i in range(3):
print(os.getpid(),"运行程序1")
sleep(2)
print("程序1运行完毕")
global a
print("a =",a)
a = 10000 # 分支线程内改变主线程的变量
# 创建线程对象
t = Thread(target=fun)
t.start() # 启动线程
# 主线程代码与分支线程代码同时执行
for i in range(4):
print(os.getpid(),"运行程序2")
sleep(1)
print("程序2运行完毕")
t.join() # 回收线程
print("main a:",a) # 所有线程共用一块空间 |
1d05e8ed17a6204a1355ce5c26b6bfdc040a781b | lexiaoyuan/PythonCrashCourse | /python_08_class/user.py | 745 | 3.578125 | 4 | class User():
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
self.login_attempts = 0
def describe_user(self):
print(self.first_name)
print(self.last_name)
def greet_user(self):
print("Hello," + self.first_name.title() + " " + self.last_name)
def increment_login_attempts(self):
self.login_attempts += 1
def reset_login_attempts(self):
self.login_attempts = 0
user = User('le', 'xiaoyuan')
user.describe_user()
user.greet_user()
user2 = User('乐', '小猿')
for i in range(5):
user2.increment_login_attempts()
print(user2.login_attempts)
user2.reset_login_attempts()
print(user2.login_attempts)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.