blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
fc80f7f6bd5bafc50dc024cceaa600ed668a29a0 | ParaschivAlex/FMI-Thangs | /PA/Rezolvari/Lab 1/valori.py | 291 | 3.875 | 4 | n=int(input("care este numarul de valori dorite?"))
max1, max2=0,0
for i in range (n):
x=int(input())
if(x>max1):
max2=max1
max1=x
elif(x<max1 and x >max2):
max2=x
if max1!=0 and max2!=0:
print(max1, " ", max2)
else:
print("Imposibil") |
d17dcd9b81fb665df8db06b636c63c59bfe675a4 | simonzg/leetcode-solutions | /315.Count_of_Smaller_Numbers_After_Self.py | 702 | 3.703125 | 4 | class Solution:
def countSmaller(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
def mergeSort(arr):
half = len(arr)//2
if half:
left, right = mergeSort(arr[:half]), mergeSort(arr[half:])
for i in range(len(arr))[::-1]:
if not right or left and left[-1][1] > right[-1][1]:
res[left[-1][0]] += len(right)
arr[i] = left.pop()
else:
arr[i] = right.pop()
return arr
res = [0 for i in range(len(nums))]
mergeSort(list(enumerate(nums)))
return res |
ebeeb2216c6842494491e70ddcad0d0086d706ab | TomJSoftwire/DevOpsWorkshop1 | /workshop/calculator.py | 4,915 | 4.1875 | 4 | import math
allowed_operators = {'/','x','+','-','%','^'}
def parse_calculation (parameter_list):
if len(parameter_list) != 3:
print('Incorrect number of values entered')
return False
if parameter_list[0] not in allowed_operators:
print('Invalid operator')
return False
try:
return (parameter_list[0], int(parameter_list[1]), int(parameter_list[2]))
except:
print('Invalid values used in calculation')
return False
def execute_calculation(parsed_calculation):
operator = parsed_calculation[0]
first_num = parsed_calculation[1]
second_num = parsed_calculation[2]
match operator:
case '+':
return first_num + second_num
case '-':
return first_num - second_num
case 'x':
return first_num * second_num
case '/':
return first_num / second_num
case '%':
return first_num % second_num
case '^':
return first_num ** second_num
def handle_calculation(calc):
return execute_calculation(parse_calculation(calc))
# STEP 1
# while True:
# command = input('Enter a calculation or "quit": ')
# if command == 'quit':
# break
# parsed_command = parse_command(command.split())
# if parsed_command == False:
# continue
# print(execute_command(parsed_command))
def parse_command(command):
command_parameters = command.split()
return (command_parameters[0], command_parameters[1:])
with open('s2_input.txt', 'r') as f:
raw_commands = f.read().splitlines()
results = []
for raw_command in raw_commands:
try:
command = parse_command(raw_command)
calculation = parse_calculation(command[1])
result = execute_calculation(calculation)
results.append(result)
except:
print('ERROR: command {c} failed'.format(c = raw_command))
sum = 0.0
for result in results:
sum += result
print('step 2:')
print(sum)
def execute_command(raw_command):
command = parse_command(raw_command)
match command[0]:
case 'calc':
return math.floor(handle_calculation(command[1]))
case 'goto':
if len(command[1]) == 1:
position = command[1][0]
return int(position)
else:
inner_command = ' '.join(command[1])
return execute_command(inner_command)
with open('s3_input.txt', 'r') as f:
raw_commands = f.read().splitlines()
seen_commands = set()
active_command = raw_commands[0]
active_line = 1
while not active_command in seen_commands:
try:
seen_commands.add(active_command)
active_line = execute_command(active_command)
active_command = raw_commands[active_line - 1]
except:
print('ERROR: command {c} failed'.format(c = active_command))
print(seen_commands)
break
print('step 3:')
print('line: {l}'.format(l = active_line))
print('command: {c}'.format(c = active_command))
def execute_command4(raw_command, all_commands, active_line):
command = parse_command(raw_command)
match command[0]:
case 'calc':
return math.floor(handle_calculation(command[1]))
case 'goto':
if len(command[1]) == 1:
position = command[1][0]
return int(position)
else:
inner_command = ' '.join(command[1])
return execute_command(inner_command)
case 'remove':
remove_line = int(command[1][0])
if len(all_commands) >= remove_line:
del all_commands[remove_line - 1]
return active_line + 1
case 'replace':
replaced_line = int(command[1][0])
replacing_line = int(command[1][1])
if len(all_commands) >= replaced_line and len(all_commands) >= replacing_line:
all_commands[replaced_line - 1] = all_commands[replacing_line - 1]
return active_line + 1
with open('s4_input.txt', 'r') as f:
raw_commands = f.read().splitlines()
seen_commands = set()
active_command = raw_commands[0]
active_line = 1
while not active_command in seen_commands:
try:
seen_commands.add(active_command)
active_line = execute_command4(active_command, raw_commands, active_line)
if active_line > len(raw_commands):
break
active_command = raw_commands[active_line - 1]
except:
print('ERROR: command {c} failed'.format(c = active_command))
break
print('step 4:')
print('line: {l}'.format(l = active_line))
print('command: {c}'.format(c = active_command))
print(seen_commands)
|
d54a5558d5afcc055933579d4c51f8f44766214c | mhargroder/Python-Snips | /Collections_Counter.py | 432 | 3.640625 | 4 | #import the function from collections library
from collections import Counter as c
#sample object
namelist = ['mike','john', 'gary','mike','john', 'mike']
print(c(namelist))
print(c(namelist).items())
print(c(namelist).most_common(2))
#Set the 2 most values and their counts to a lit of touples
popularNames = c(namelist).most_common(2)
print(popularNames)
#requires integer counters
#
|
064e2b0d631c15ed711e80caa202f269cd46e3d4 | CHAITHRALJ/countries | /restcountries.py | 610 | 3.671875 | 4 | import json,requests # importing the packages
def getData(): # fuction to get the data
url = "https://restcountries.eu/rest/v2/all?fields=name;topLevelDomain" # url which is containaing the information
header = {'content-type': 'application/json'} # the data which is in JSON format
r = requests.get(url).text # convert the json data to text format
data = json.loads(r) # loads the data to a variable
for country in data: # for all the countries in data
print("{0}:{1}".format(country['name'],' '.join(country['topLevelDomain'])))
getData() # returning the required output
|
a078cf8fd75a2c054b29362318f71da9b1b1f0c3 | DamienHall/Maze-Maker | /MazeMaker.py | 4,295 | 3.609375 | 4 | import numpy as Math
from random import randrange
"""
Script by https://github.com/LilZcrazyG
"""
class Grid:
def __init__(self, window, size):
self.window = window
self.width, self.height = self.window.return_size()
self.size = size
self.rows = int(Math.floor(self.height / self.size))
self.columns = int(Math.floor(self.width / self.size))
self.cells = []
self.unvisited = self.columns * self.rows
self.visited = 1
self.showable = True
self.subdivide()
self.current = self.cells[0]
self.next = None
self.stack = []
self.done = False
self.solution = []
self.last = None
self.x = None
self.y = None
def subdivide(self):
for row in range(self.rows):
for column in range(self.columns):
self.cells.append(Cell(column, row, self.size, self))
def remove_walls(self, cell_one, cell_two):
x = cell_one.x / self.size - cell_two.x / self.size
y = cell_one.y / self.size - cell_two.y / self.size
if x == 1:
cell_one.walls[3] = False
cell_two.walls[1] = False
elif x == -1:
cell_one.walls[1] = False
cell_two.walls[3] = False
if y == 1:
cell_one.walls[0] = False
cell_two.walls[2] = False
elif y == -1:
cell_one.walls[2] = False
cell_two.walls[0] = False
def connect_stack(self, graphics):
for cell in self.stack:
graphics.square((cell.x,cell.y),self.size)
graphics.square((self.current.x, self.current.y), self.size)
def show(self, graphics):
for cell in self.cells:
if cell.visited:
cell.show(graphics)
def get_cell(self, x, y):
if x < 0 or y < 0 or x > self.columns - 1 or y > self.rows - 1:
return None
else:
return self.cells[int(x + y * self.columns)]
class Cell:
def __init__(self, x, y, size, grid):
self.x = x * size
self.y = y * size
self.size = size
self.walls = [True, True, True, True]
self.visited = False
self.in_stack = False
self.options = 0
self.dir = None
def show(self, graphics):
for wall in self.walls:
#top
if self.walls[0]:
graphics.line((self.x, self.y), (self.x + self.size, self.y))
#right
if self.walls[1]:
graphics.line((self.x + self.size, self.y), (self.x + self.size, self.y + self.size))
#bottom
if self.walls[2]:
graphics.line((self.x + self.size, self.y + self.size), (self.x, self.y + self.size))
#left
if self.walls[3]:
graphics.line((self.x, self.y + self.size), (self.x, self.y))
def highlight(self, graphics):
graphics.square((self.x + 10, self.y + 10), self.size - 10 * 2)
def check_neighbors(self, grid, bias_left, bias_right, bias_up, bias_down):
neighbors = []
top = grid.get_cell(self.x/self.size, self.y/self.size - 1)
right = grid.get_cell(self.x/self.size + 1, self.y/self.size)
bottom = grid.get_cell(self.x/self.size, self.y/self.size + 1)
left = grid.get_cell(self.x/self.size - 1, self.y/self.size)
if top != None and not top.visited:
for bias in range(bias_up):
neighbors.append(top)
if right != None and not right.visited:
for bias in range(bias_right):
neighbors.append(right)
if bottom != None and not bottom.visited:
for bias in range(bias_down):
neighbors.append(bottom)
if left != None and not left.visited:
for bias in range(bias_left):
neighbors.append(left)
if len(neighbors) > 0:
self.options = len(neighbors)
if len(neighbors)-1 != 0:
dir = neighbors[randrange(len(neighbors))]
else:
dir = neighbors[0]
return dir |
91ac17f90e64c6ab6bd27605f6803ed00b16a84c | vividsky/python-programs | /fibonacci_memiozation.py | 479 | 4.0625 | 4 | cache = {}
def fib(n):
if n == 1:
return 1
elif n == 2:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2)
def fibonacci(n):
if n in cache:
return cache[n]
else:
if n == 1:
return 1
elif n == 2:
return 1
else:
value = fibonacci(n-1) + fibonacci(n-2)
cache[n] = value
return value
for n in range(1, 50):
print(f'{n} : {fibonacci(n)}')
|
242f590fdc7a777c98c7df517c5533455e6c4b3d | skayhan13/Python-Challenge | /PyPoll/Resources/main.py | 4,319 | 4.25 | 4 | # PyPoll
# In this challenge, you are tasked with helping a small, rural town modernize its vote counting process.
# You will be give a set of poll data called election_data.csv. The dataset is composed of three columns: Voter ID, County, and Candidate. Your task is to create a Python script that analyzes the votes and calculates each of the following:
# 1. The total number of votes cast
# 2. A complete list of candidates who received votes
# 3. The percentage of votes each candidate won
# 4. The total number of votes each candidate won
# 5. The winner of the election based on popular vote.
import os #import the python modules you would like to use aka dependencies
import csv #module for reading csv files
file_path='../Resources/Election_Data.csv' #file name
file_path=os.path.join('..', 'Resources', 'Election_Data.csv')
csvfile= open(file_path)
csvreader=csv.reader(csvfile)
csvreader= csv.reader(csvfile, delimiter=',') #since this file is a csv the delimiter is a comma
#print(csvreader) #this will tell us what kind of object the file is: input-output objects
csvheader=next(csvreader) #moves you to the next item of the iterable (i.e. the list)
#print(csvreader)
#print(csvheader) #this will list the headers of the csv file in terminal
#Begin- identify the variables I would like to use
#Define variables
votes= [] #will be using voter id to find total number of votes; aka row 0
candidates= []
for row in csvreader:
#print(row)
votes.append(row[0]) #append global method will tell us the length of a list
candidates.append(row[2])
#print(len(votes))
#print(candidates) - test to see if i am in the right location
total_votes = (len(votes))
#Count each number of candidates in the candidates list:
Khan = int(candidates.count("Khan"))
Correy = int(candidates.count("Correy"))
Li = int(candidates.count("Li"))
O_Tooley = int(candidates.count("O'Tooley"))
#Find the percentage of votes:
Khan_percentage = round((Khan/total_votes) * 100) #round function will round to nearest whole number
Correy_percentage = round((Correy/total_votes) * 100)
Li_percentage = round((Li/total_votes) * 100)
O_Tooley_percentage = round((O_Tooley/total_votes) * 100)
#Print each candidate's name, vote percentage, and number of votes recieved:
# print(f"Khan: {Khan_percentage}% ({Khan})")
# print(f"Correy: {Correy_percentage}% ({Correy})")
# print(f"Li: {Li_percentage}% ({Li})")
# print(f"O'Tooley: {O_Tooley_percentage}% ({O_Tooley})")
#Compare votes and pick winner with the most votes- may be able to accomplish this with a dictionary, but unsure how to do so
if Khan > Correy :
Winner = "Khan"
elif Correy > Khan:
Winner = "Correy"
elif Li > Khan :
Winner = "Li"
elif O_Tooley > Khan :
Winner = "O'Tooley"
#print(f"Winner: {Winner}")
#Print results to the terminal:
print("Election Results")
print("----------------------------------------------------------")
print(f"Total Votes: {total_votes}")
print("----------------------------------------------------------")
print(f"Khan: {Khan_percentage}% ({Khan})")
print(f"Correy: {Correy_percentage}% ({Correy})")
print(f"Li: {Li_percentage}% ({Li})")
print(f"O'Tooley: {O_Tooley_percentage}% ({O_Tooley})")
print("----------------------------------------------------------")
print(f"Winner: {Winner}")
#Print results to text file:
f=open("C:/Users/sarak/OneDrive/Documents/DU Data Analytics Bootcamp/HW #3/Python-Challenge/PyPoll/Analysis/PyPoll_Analysis.txt", "w") #this is the absolute path of where I would like the txt file to be generated in
f.write("Election Results" + "\n") #\n will put a new line at the end of your f.write statement
f.write("----------------------------------------------------------" + "\n")
f.write("Total Votes:" + str(total_votes) +"\n")
f.write("----------------------------------------------------------" + "\n")
f.write("Khan:" + str(Khan_percentage) +"%" +" " + str(Khan)+ "\n") #+ " " puts once space in file
f.write("Correy:" + str(Correy_percentage) +"%" +" " + str(Correy)+ "\n")
f.write("Li:" + str(Li_percentage) +"%" +" " + str(Li)+ "\n")
f.write("O'Tooley:" + str(O_Tooley_percentage) +"%" + " " + str(O_Tooley)+ "\n")
f.write("----------------------------------------------------------" + "\n")
f.write("Winner:" + str(Winner) + "\n")
f.close() #always good practice to end f open method with f.close |
2f75ece734434751103d3109c3443d74949fdef4 | lorarjohns/python_code_challenges | /challenges/minimumSwaps.py | 732 | 4.1875 | 4 | import math
import os
import random
import re
import sys
"""
You are given an unordered array consisting of consecutive integers [1, 2, 3, ..., n] without any duplicates.
You are allowed to swap any two elements.
You need to find the minimum number of swaps required to sort the array in ascending order.
"""
def minimumSwaps(arr):
swaps = 0
for i in range(len(arr)):
# stay at this index until it contains the correct number
while i + 1 != arr[i]:
n = arr[i]
# put the out-of-order element in its correct index
arr[i], arr[n - 1] = arr[n - 1], arr[i]
swaps += 1
return swaps
if __name__ == "__main__":
print(minimumSwaps([7, 1, 3, 2, 4, 5, 6]))
|
e0ef6b02faf36a8c00b2699f6241c8dc449a0e85 | lyleRpalagar/sandbox | /Python/pig-latin-translator.py | 618 | 3.8125 | 4 | """
Simple Translator to use user input and translate the word into pig latin
version 1.0
date: 3/13/2017
"""
# assign variable to ay
pyg = 'ay'
#grab the users input
original = input('Enter a word:')
#force the user input to be lowercase
word = original.lower()
# variable contains first letter of the input
first = word[0]
# variable concats input + firstLetter + pyg variable
new_word = word + first + pyg
# remove first letter of the word and display the rest
new_word = new_word[1:len(new_word)]
if len(word) > 0 and word.isalpha():
print new_word
else:
print 'Error: Enter a word with no spaces'
|
e2bd48f427800ba4330a32b18e11206399eb6485 | alu-rwa-dsa/week-1-list-complexity-jules | /.github/q1.py | 220 | 3.6875 | 4 | import time
first_point = time.time()
n = 0
while True:
print("Hello")
n = n + 1
if n == 10000:
break
last_point = time.time()
time_n = last_point- first_point
print("Time taken is: ")
print(time_n) |
baf5128d0790e874863a79513db879e1e0d4d88e | tleonhardt/CodingPlayground | /python/dictionary_challenge/dictionary_challenge.py | 2,315 | 4.34375 | 4 | #!/usr/bin/env python3
"""
Given an English dictionary to search, create a program that will find all
words in the dictionary which match the following criteria:
The target word is exactly 7 letters long.
The target word contains all the vowels [aeiou] exactly once.
Two of the letters in the target word are not vowels.
So if '.' represents any single non-vowel character, possible matched words
would be:
aeiou..
aeio.u.
aei.ou.
ae.iou.
a.eiou.
.aeiou.
aeio..u
aei.o.u
ae.io.u
etc.
Use your program to find at least 5 words which match this criteria.
This example showcases the power of Python's built in set type and the
associated set theory operations it provides.
"""
DICTIONARY_FILE = "fulldictionary00.txt"
MAGIC_WORD_LENGTH = 7
VOWELS = frozenset("aeiou")
def matches_criteria(word: str) -> bool:
"""Determins if a word matches the criteria.
:param word: word to test
:return: True if it is a match, False otherwise
"""
letters = frozenset(word)
# If set of vowels is a proper subset of the letters and has consonants
return VOWELS < letters and has_correct_consonants(letters, word)
def has_correct_consonants(letters: frozenset[str], word: str):
"""Make sure the word contains exactly two letters that are not vowels.
:param letters_in_word: set of letters in word
:param word: word to test
:return (bool): True if words has exactly two consonants, False otherwise.
"""
# consonants is the difference between the set of letters and set of vowels
consonants = letters - VOWELS
num_unique_consonants = len(consonants)
return num_unique_consonants == 2 or (
num_unique_consonants == 1 and word.count(next(iter(consonants))) == 2
)
def main():
"""Main Execution - Parse through the dictionary file
:return (list): List of words which match the criteria
"""
with open(DICTIONARY_FILE) as cur_file:
# Read words and filter to those of desired length that match criteria
matches = []
for line in cur_file.readlines():
word = line.strip()
if len(word) == MAGIC_WORD_LENGTH and matches_criteria(word):
matches.append(word)
return matches
if __name__ == "__main__":
word_matches = main()
print(word_matches)
|
c829a11c7f8af7c03cebe8236c02ed02483a28f8 | jimdro/Election-Center | /voters_info.py | 1,501 | 3.9375 | 4 | """
Created by Dimitrios Drosos
email: dimitriss.drosos@gmail.com
"""
class Voter:
"""
At this class i initiate voters name and age and some ohter parameters
"""
def __init__(self, name,age, address = 0, identity=0):
self.name = name
self.address = address
self.identity = identity
self.age = age
print("Welcome to our election center: " + self.name + ' ' + str(self.age))
def name_eligibility(self):
while True:
if self.name == str:
print("You gave a valid name")
break
elif self.name == '':
print("Please try again")
def age_eligibility(self):
max_tries = 3
while max_tries < 0:
max_tries += 1
if self.age == '' or self.age < 0:
try:
if int(self.age < 18) or int(self.age > 65):
return False
else:
return True
except Exception as error:
error_string = str(error)
print(error_string)
continue
else:
break
# finally:
# print("Please try again!")
break
else:
print("Wrong, you have 3 tries in total\mPlease try again.")
print("Please try again!")
def identity(self):
pass
|
51f4751df1143b5eb75c891267b1b6a5eade4f57 | mbarlow12/treehouse-battleship | /validator.py | 2,398 | 3.921875 | 4 |
def validate_cell_choice(input_string, board_size):
columns = [chr(c) for c in range(ord('a'), (ord('a') + board_size))]
input_list = input_string.split(" ")
if len(input_list) != 2:
raise ValueError(
"Incorrect number of arguments. Please ensure there's a space between the row and column selection.")
if input_list[0] not in columns:
raise ValueError(
"First argument must be a letter between A and {}.".format(columns[-1].upper()))
try:
if int(input_list[1]) not in range(1, board_size + 1):
raise ValueError(
"Second argument must be an integer between 1 and {}".format(board_size))
except ValueError as ve:
raise ValueError(
"Second argument must be an integer between 1 and {}".format(board_size))
def validate_orientation(input_string):
if input_string not in ['h', 'v']:
raise ValueError(
"Ships must be placed either [V]ertically or [H]orizontally.")
# check if the player has already guessed that cell
# input has already been validated
def validate_guess(guess, player):
made_guesses = set(player.hits + player.misses)
if guess in made_guesses:
raise ValueError("You've already guessed that cell. Try again.")
# ensure that a ship is placed fully on the board (i.e. doesn't hang off
# edge) and that it doesn't overlap with any other ships
def validate_ship_placement(origin, orientation, ship, ship_list, board_size):
column, row = origin
check = 0
if orientation == 'h':
check = column + ship.length - 1
for col in range(column, column + ship.length):
validate_ship_cell((col, row), ship, ship_list)
elif orientation == 'v':
check = row + ship.length - 1
for r in range(row, row + ship.length):
validate_ship_cell((column, r), ship, ship_list)
if check > board_size:
raise ValueError(
"ERROR: Your {} must be placed fully on the board.".format(ship.name))
def validate_ship_cell(cell, ship, ship_list):
for existing_ship in ship_list:
if existing_ship.cells:
if cell in existing_ship.cells.keys():
raise ValueError("ERROR: Your {} overlaps with your {} at cell [{} {}]. Try again.".format(
ship.name, existing_ship.name, cell[0], cell[1]))
|
5518d952b5ec74fff6ae0711f0fb92bdbdde8881 | l-duan/python_basic | /day4/Decorator/Inner_Functions.py | 6,477 | 4.625 | 5 | # -*- coding:utf-8 -*-
__auth__ = 'christian'
def outer(num1):
def inner_increment(num1): # hidden from outer code
return num1 + 1
num2 = inner_increment(num1)
print (num1, num2)
'''
Encapsulation:
You use inner functions to protect them from anything happening outside of the function,
meaning that they are hidden from the global scope.
'''
#inner_increment(10)
outer(10)
'''
Keep in mind that this is just an example. Although this code does achieve the desired result,
it’s probably better to make the inner_increment() function a top-level “private” function
using a leading underscore: _inner_increment().
'''
'''The following recursive example is a slightly better use case for a nested function:'''
def factorial(number):
# error handling
if not isinstance(number, int):
raise TypeError("Sorry. 'number' must be an integer.")
if not number >= 0:
raise ValueError("Sorry. 'number' must be zero or positive.")
def inner_factorial(number):
if number <= 1:
return 1
return number*inner_factorial(number-1)
return inner_factorial(number)
# call the outer function
print(factorial(4))
'''
Test this out as well. One main advantage of using this design pattern is
that by performing all argument checking in the outer function,
you can safely skip error checking altogether in the inner function.
'''
'''
Keepin’ it DRY
Perhaps you have a giant function that performs the same chunk of code in numerous places.
For example, you might write a function which processes a file,
and you want to accept either an open file object or a file name:
'''
def process_1(file_name):
def do_stuff(file_process):
for line in file_process:
print(line)
if isinstance(file_name, str):
with open(file_name, 'r') as f:
do_stuff(f)
else:
do_stuff(file_name)
def process(file_name):
def do_stuff(file_process):
wifi_locations = {}
for line in file_process:
values = line.split(',')
# Build the dict, and increment values
wifi_locations[values[1]] = wifi_locations.get(values[1], 0) + 1
max_key = 0
for name, key in wifi_locations.items():
all_locations = sum(wifi_locations.values())
if key > max_key:
max_key = key
business = name
print('There are {0} WiFi hot spots in NYC and {1} has the most with {2}.'.format(
all_locations, business, max_key))
if isinstance(file_name, str):
with open(file_name, 'r') as f:
do_stuff(f)
else:
do_stuff(file_name)
process("NYC_Wi-Fi_Hotspot_Locations.csv")
'''Closures and Factory Functions'''
'''
What’s a closure?
A closure simply causes the inner function to remember the state of its environment when called. Beginners often think
that a closure is the inner function, when it’s really caused by the inner function.
The closure "closes" the local variable on the stack and this stays around after the the stack creation has finished executing.
'''
def generate_power(number):
"""
Examples of use:
>>> raise_two = generate_power(2)
>>> raise_three = generate_power(3)
>>> print(raise_two(7))
128
>>> print(raise_three(5))
243
"""
# define the inner function ...
def nth_power(power):
return number ** power
# ... which is returned by the factory function
return nth_power
raise_two = generate_power(2)
print(raise_two(7))
raise_three = generate_power(3)
print(raise_three(5))
'''
What’s happening here?
The ‘generate_power()’ function is a factory function – which simply means
that it creates a new function each time it is called and then returns the newly created function.
Thus, raise_two and raise_three are the newly created functions.
What does this new, inner function do? It takes a single argument, power, and returns number**power.
Where does the inner function get the value of number from? This is where the closure comes into play:
nth_power() gets the value of power from the outer function, the factory function. Let’s step through this process:
Call the outer function: generate_power(2)
Build the nth_power() function which takes a single argument power
Take a snapshot of the state of nth_power() which includes number=2
Pass that snapshot into the generate_power() function
Return the nth_power() function
Put another way, the closure functions to "initialize" the number bar in the nth_power() function and then returns it.
Now, whenever you call that newly returned function, it will always see its own private snapshot that includes number=2.
'''
def has_permission(page):
def inner(username):
if username == 'Admin':
return "'{0}' does have access to {1}.".format(username, page)
else:
return "'{0}' does NOT have access to {1}.".format(username, page)
return inner
current_user = has_permission('Admin Area')
print(current_user('Admin'))
random_user = has_permission('Admin Area')
print(current_user('Not Admin'))
'''
This is a simplified function to check if a certain user has the correct permissions to access a certain page.
You could easily modify this to grab the user in session to check if they have the correct credentials to access a certain route.
Instead of checking if the user is just equal to ‘Admin’, you could query the database to check the permission
then return the correct view depending on whether the credentials are correct or not.
'''
'''
Conclusion
The use of closures and factory functions is the most common, and powerful, use for inner functions. In most cases,
when you see a decorated function, the decorator is a factory function which takes a function as argument,
and returns a new function which includes the old function inside the closure. Stop. Take a deep breath. Grab a coffee.
Read that again.
Put another way, a decorator is just syntactic sugar for implementing the process outlined in the generate_power() example.
I’ll leave you with an example:
'''
def generate_power(exponent):
def decorator(f):
def inner(*args):
result = f(*args)
return exponent**result
return inner
return decorator
@generate_power(2)
def raise_two(n):
return n
print(raise_two(7))
@generate_power(3)
def raise_three(n):
return n
print(raise_two(5)) |
4e9946250707a924d4add08715fff4d1791dd0f4 | OnyisoChris/Python | /Numbers/mathsfunctions2.py | 407 | 4.15625 | 4 | # Number max()method - returns the largest of its arguments
print('max(79, 110, 678) : ', max(79, 110, 678))
print('max(-30, 89, 100) : ', max(-30, 89, 100))
print('max(0, 39, -70) : ', max(0, 39, -70))
# Number min() Method - returns the smallest of its arguments
print('min(79, 110, 678) : ', min(79, 110, 678))
print('min(-30, 89, 100) : ', min(-30, 89, 100))
print('min(0, 39, -70) : ', min(0, 39, -70)) |
0facfc4d546bfa4e2b95376e43edd5ee3c293059 | Gaurangsharma/guiv | /covid_cc.py | 656 | 3.5 | 4 | check_name=["ACov","BCov","CCov","DCov","ECov","FCov"]
check_letter=["A","B","C","D","E","F"]
name=[]
letter=[]
stack_name=[]
stack_letter=[]
main=[]
score=0
for _ in range(6):
k=input()
if(_!=5):
input()
main.append(k)
k=list(k)
name.append(k[-4::-1])
letter.append(k[-2])
for i in range(len(name)):
# n=i[-1:len(i)-1,:-1]
name[i].reverse()
s="".join(name[i])
if(s in check_name and s not in stack_name):
score+=0.5
stack_name.append(s)
k=name[i][0]
if(letter[i] not in stack_letter and letter[i]==k):
score+=0.5
stack_letter.append(letter[i])
print(score,"out of 6") |
6fd345c32acbfbbaf9119ae906f3b841626215b1 | X-21/DeepLearning.ai-Assignments | /4. Convolutional Neural Networks/Week2 Deep Convolutional Models:Case Studies/1_1_Keras Tutorial.py | 3,044 | 3.765625 | 4 | from keras.layers import Input, Dense, Activation, ZeroPadding2D, BatchNormalization, Flatten, Conv2D
from keras.layers import AveragePooling2D, MaxPooling2D, Dropout, GlobalMaxPooling2D, GlobalAveragePooling2D
from keras.models import Model
from kt_utils import *
import keras.backend as K
import keras
def HappyModel(input_shape):
"""
Implementation of the HappyModel.
Arguments:
input_shape -- shape of the images of the dataset
Returns:
model -- a Model() instance in Keras
"""
# Feel free to use the suggested outline in the text above to get started, and run through the whole
# exercise (including the later portions of this notebook) once. The come back also try out other
# network architectures as well.
# Define the input placeholder as a tensor with shape input_shape. Think of this as your input image!
X_input = Input(input_shape)
# Zero-Padding: pads the border of X_input with zeroes
X = ZeroPadding2D((1, 1))(X_input) # 66,66,3
# CONV -> BN -> RELU Block applied to X
X = Conv2D(8, (3, 3), strides=(1, 1), name='conv0')(X) # 64,64,8
X = BatchNormalization(axis=3, name='bn0')(X) # axis=3 because channels is 3th([batch, height, width, channel])
X = Activation('relu')(X)
# MAXPOOL
X = MaxPooling2D((2, 2), name='max_pool')(X) # 32,32,8
# FLATTEN X (means convert it to a vector) + FULLY CONNECTED
X = Flatten()(X)
X = Dense(1, activation='sigmoid', name='fc')(X)
# Create model. This creates your Keras model instance, you'll use this instance to train/test the model.
model = Model(inputs=X_input, outputs=X, name='HappyModel')
return model
if __name__ == '__main__':
K.set_image_data_format('channels_last')
X_train_orig, Y_train_orig, X_test_orig, Y_test_orig, classes = load_dataset()
# Normalize image vectors
X_train = X_train_orig / 255.
X_test = X_test_orig / 255.
# Reshape
Y_train = Y_train_orig.T
Y_test = Y_test_orig.T
print("number of training examples = " + str(X_train.shape[0]))
print("number of test examples = " + str(X_test.shape[0]))
print("X_train shape: " + str(X_train.shape))
print("Y_train shape: " + str(Y_train.shape))
print("X_test shape: " + str(X_test.shape))
print("Y_test shape: " + str(Y_test.shape))
'''
2 - Building a model in Keras
'''
# 2-1 Create the model by calling the function above
happyModel = HappyModel((64, 64, 3))
# 2-2 Compile the model by calling
happyModel.compile(optimizer=keras.optimizers.Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=0.0),
loss='binary_crossentropy', metrics=['accuracy'])
# 2-3 Train the model on train data by calling
happyModel.fit(x=X_train, y=Y_train, batch_size=16, epochs=20)
# 2-4 Test the model on test data by calling
preds = happyModel.evaluate(x=X_test, y=Y_test)
print("Loss = " + str(preds[0]))
print("Test Accuracy = " + str(preds[1]))
happyModel.summary()
|
1f83845d253317eef3a797fb17c63b03425dad02 | divyamtalreja/basic-python-program | /uplow.py | 299 | 3.859375 | 4 | def uplow(s):
uppercase=0
lowercase=0
for i in range(0,len(s)):
if (s[i].isupper()):
uppercase=uppercase+1
elif(s[i].islower()):
lowercase=lowercase+1
print(uppercase)
print(lowercase)
uplow("The boy is Good") |
015b5529980efbc4f88d7a0d595dadaf9c8ca95a | wgq1995/Data-Structures-and-Algorithms | /链表/链表.py | 1,472 | 4.375 | 4 | class Node:
"""
链表结点类
"""
def __init__(self, x):
self.val = x
self.next = None
def build_linked_list(val_list):
"""
从一个列表按顺序建立链表,返回头结点
:param val_list: list,存Node中的值
:return: Node, 头结点
"""
if not val_list:
return None
head_node = Node(0)
cur = head_node
for val in val_list:
cur.next = Node(val)
cur = cur.next
return head_node.next
def show_linked_list(head):
"""
按顺序显示链表
:param head: Node, 头结点
:return: list, 依次为每个node中的val
"""
res = []
while head:
res.append(head.val)
head = head.next
return res
def reverse_linked_list(head):
"""
反转链表
:param head:Node, 头结点
:return: Node,反转后的头结点
"""
if not head:
return None
pre = None
cur = head
nex = head.next
while nex:
cur.next = pre
pre = cur
cur = nex
nex = cur.next
cur.next = pre
return cur
if __name__ == '__main__':
a = [1, 3, 5, 2, 7]
head = build_linked_list(a)
res = show_linked_list(head)
print("原链表", res)
reversed_head = reverse_linked_list(head)
reversed_res = show_linked_list(reversed_head)
print("反转链表", reversed_res)
# 运行结果为
# 原链表[1, 3, 5, 2, 7]
# 反转链表[7, 2, 5, 3, 1]
|
ba10b2a53e3229f6ac481fe3097292e0895050fd | saumya-singh/CodeLab | /HackerRank/Sorting/Intro_To_Tutorial_Challenges.py | 533 | 3.984375 | 4 | #!/bin/python3
#https://www.hackerrank.com/challenges/tutorial-intro/problem
def binarySearch(v, n, ar):
first = 0
last = len(ar)
while first <= last:
mid = (last + first)//2
if v < ar[mid]:
last = mid
elif v > ar[mid]:
first = mid + 1
elif v == ar[mid]:
return mid
return -1
v = int(input().strip())
n = int(input().strip())
ar = [int(i) for i in input().strip().split(" ")]
index = binarySearch(v, n, ar)
print(index) |
78795d912121e76e533c9c9e6bfc0c56318fa537 | rkitzrow/MidTerm | /MidTermProj.py | 8,053 | 3.625 | 4 | #This flask asks users to select a coin, investment value, and investment date and will return the current worth
#This flask will also return a plot of the coin returns from the initial investment date to today
#I import all the packages and libraries needed for this app.
from flask import Flask, render_template, request
import time
import datetime
from datetime import datetime
import calendar
import requests
from money import Money
import pandas as pd
import matplotlib.pyplot as plt
plt.style.use('seaborn-whitegrid')
import numpy as np
import seaborn as sns
import base64
import io
import matplotlib
matplotlib.use('Agg')
#I set the app name
app = Flask(__name__)
#Here I am setting up the template for the data entry page
@app.route('/')
def my_form():
# Look in the templates folder for this html page which includes the input fields
return render_template('three_button_form.html')
#Here I am defining the operations of the app and what the app will return. Is accepts post only right now
@app.route('/', methods=['POST'])
def my_form_post():
# Here I create variables that align to form inputs from the three_button_form.html page
# I can then refer to these variables for return calculations and for use in the API
coin = request.form.get('selectCoin')
investment = request.form.get('investValue')
timeline = request.form.get('investDate')
#Now I need to change date format
timeline2 = datetime.strptime(timeline, "%Y-%m-%d").strftime("%m/%d/%Y")
#Here I need to change investment format
# I set the investmetn to an integer
investment2 = int(investment)
# I then convert the integer to a string with two decimals
investment2 = str(round(investment2, 2))
# I turn the investmetn into USD money format in english
investment2 = Money(investment2, 'USD')
investment2.format('en_US')
# Here I compare these inputs against historical data
# I need to convert timeline to datetime to unix
unixtime = calendar.timegm(time.strptime(timeline, "%Y-%m-%d"))
# I need to call the api to get previous and current values
# As noted above, I use the dynamic variable of coin for the GET API call
# I hardcode the currency to USE and return the max possible entries
d = requests.get(
"https://min-api.cryptocompare.com/data/histoday?fsym=" + coin + "&tsym=USD&limit=2000").json()
#I pull the data from the dictinary
df = pd.DataFrame.from_dict(d['Data'])
#I don't want all the fields and select only time, close, and open values to make my return calculations
df = df[['time', 'close', 'open']]
#I need to calc % change (current-original/original) then investment + (investment * % change) = investmentToday
# I select the origin date and identify it as unixtime
orig = df.loc[df['time'] == unixtime]
# I identify today's date which is the last date in the tale
today = df.tail(1)
#I make interim calculations for computing return (close-open)/open
calc1 = int(today["open"])
calc2 = int(orig["open"])
pct = ((calc1 - calc2) / calc2)
# I calculate the return and set to money format to USD and and language to english
investmentToday = int(investment) + ((int(investment)) * pct)
investmentToday = str(round(investmentToday, 2))
investmentToday = Money(investmentToday, 'USD')
investmentToday.format('en_US')
#Here I create the plot
# I need to convert timeline to datetime to unix
unixtime = calendar.timegm(time.strptime(timeline, "%Y-%m-%d"))
# I need to call the api to get previous and current values
d = requests.get(
"https://min-api.cryptocompare.com/data/histoday?fsym=" + coin + "&tsym=USD&limit=2000").json()
df = pd.DataFrame.from_dict(d['Data'])
df = df[['time', 'close', 'open']]
# I need to calc % change (current-original/original) then investment + (investment * % change) = investmentToday
orig = df.loc[df['time'] == unixtime]
today = df.tail(1)
calc1 = int(today["open"])
calc2 = int(orig["open"])
pct = ((calc1 - calc2) / calc2)
investmentToday = int(investment) + ((int(investment)) * pct)
investmentToday = str(round(investmentToday, 2))
investmentToday = Money(investmentToday, 'USD')
investmentToday.format('en_US')
print(investmentToday)
# Next I will plot a graph of returns to show the daily returns from the selected date
# Reduce the df to only dates on and after the selected date
df_return = df[df['time'] >= unixtime]
# select the original open price
df_orig = df_return.iloc[0, 2].copy()
# calculate daily returns based that open price
df_return['orig'] = df_orig
df_return['return'] = (df_return['open'] - df_return['orig']) / df_return['orig']
df_return['return'] = df_return['return']*100
# convert unix date back to standard date
df_return['time'] = pd.to_datetime(df_return['time'], unit='s')
# separate out the parts of the date
#df_return['time'] = df_return['time'].dt.year
# select only columns for graph
return_plot = pd.DataFrame(df_return, columns=["time", "return"])
# max return value for annotation
ymax_index = int((np.argmax(return_plot['return'])))
ymax = return_plot['return'].loc[ymax_index]
xpos_max = return_plot['time'].loc[ymax_index]
xmax = return_plot['time'].loc[ymax_index]
xmax = datetime.strftime(xmax, "%m/%d/%Y")
# min return value for annotation
ymin_index = int((np.argmin(return_plot['return'])))
ymin = return_plot['return'].loc[ymin_index]
xpos_min = return_plot['time'].loc[ymin_index]
xmin = return_plot['time'].loc[ymin_index]
xmin = datetime.strftime(xmin, "%m/%d/%Y")
# plot graph using seaborn
# this is required so we can return the image on the return_page.html
img = io.BytesIO()
plt.figure(figsize=(10,3))
# I annotate the graph with an arrow and statement of max and min value
plt.annotate('Max Value on\n%s' % xmax, xy=(xpos_max, ymax),
xycoords='data',
xytext=(40, 5), textcoords='offset points',
arrowprops=dict(arrowstyle="->"),
horizontalalignment='left', verticalalignment='top',
fontsize=10, fontweight="bold", color='r')
plt.annotate('Min Value on\n%s' % xmin, xy=(xpos_min, ymin),
xycoords='data',
xytext=(30, 60), textcoords='offset points',
arrowprops=dict(arrowstyle="->"),
horizontalalignment='left', verticalalignment='bottom',
fontsize=10, fontweight="bold", color='r')
# I return the plot and add my x and y labels and title
sns.lineplot(x='time', y='return', data=return_plot)
plt.title("Return of Your Investment Over Time")
plt.xlabel("Time of Investment")
plt.ylabel("Return of Investment (%)")
plt.savefig(img, format='png')
img.seek(0)
graph_url = base64.b64encode(img.getvalue()).decode()
plt.clf()
plt.cla()
plt.close('all')
#Here I combine the inputs with the comparision calculations to respond to the user
return render_template('return_page.html', what=coin, much=investment2, when=timeline2, moola=investmentToday, graph_url=graph_url)
#I created 404 and 500 errors (although using the same html message)
@app.errorhandler(404)
def page_not_found(e):
# note that we set the 404 status explicitly
return render_template('404.html'), 404
@app.errorhandler(500)
def internal_error(e):
# If we get a 500 error, I am returning the same generic error message as the 400 error
return render_template('404.html'), 500
# Issue:
# When running this locally on windows, an error will prevent a second call.
# This error is specifc to windows and does not appear when hosted on linux
# On aws linux instance the error does not appear and unlimited calls can be made
# Set port, host, and debug status for the flask app
if __name__ == "__main__":
app.run(debug=False, port=8004)
|
1287c57942faf60d12d03955509778cb830a3ce1 | Danny7226/MyLeetcodeJourney | /normal_order_python/206.ReverseLinkedList.py | 750 | 3.984375 | 4 | '''
206. Reverse Linked List
Easy
Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
Follow up:
A linked list can be reversed either iteratively or recursively. Could you implement both?
'''
class Solution:
# iteratively
def reverseList(self, head: ListNode) -> ListNode:
reverse = None
ptr = head
while ptr:
reverse, reverse.next, ptr = ptr, reverse, ptr.next
return reverse
class Solution:
# recursively
def reverseList(self, head: ListNode) -> ListNode:
if not head or not head.next:
return head
N = self.reverseList(head.next)
head.next.next = head
head.next = None
return N |
df15c52f70ba919734e53e109f679e220d475520 | ChrisKneller/fundamentals | /sorting/mergesort.py | 2,669 | 4.1875 | 4 | from collections import deque
import numpy as np
def mergesort(iterable, final_length=False):
'''
Return a new list containing all items from the iterable in ascending order.
This uses a custom implementation of mergesort that utilises a deque.
final_length should not be input and is there to ensure the final deque
produced gets converted to a list.
'''
if not final_length:
final_length = len(iterable)
if len(iterable) <= 1:
return iterable
l1 = iterable[:len(iterable)//2]
l2 = iterable[len(iterable)//2:]
ml1 = mergesort(l1, final_length)
ml2 = mergesort(l2, final_length)
ml = amerge(ml1, ml2)
return ml if len(ml) < final_length else list(ml)
def amerge(l1, l2):
'''
Return a sorted, merged deque of two input values or deques.
'''
l3 = deque()
if len(l1) == 1:
l1 = deque(l1)
if len(l2) == 1:
l2 = deque(l2)
while l1 and l2:
if l1[0] <= l2[0]:
l3.append(l1.popleft())
else:
l3.append(l2.popleft())
while l1 and not l2:
l3.append(l1.popleft())
while l2 and not l1:
l3.append(l2.popleft())
return l3
def altmergesort(mylist):
'''
Return a new list containing all items from the iterable in ascending order.
This is an in-place version which relies on using pointers. It was created to
reduce the space complexity to O(n) i.e. to use one common extra array for all merges.
'''
l = len(mylist)
holdlist = [None] * l
if l <= 1:
return mylist
else:
submergesort(mylist,holdlist,0,l-1)
return mylist
def submergesort(mylist,holdlist,left,right):
if left == right:
return (left,right)
mid = (left + right) // 2
ml1 = submergesort(mylist,holdlist,left=left,right=mid)
ml2 = submergesort(mylist,holdlist,left=mid+1,right=right)
ml = bmerge(mylist, holdlist, ml1, ml2)
return ml
def bmerge(mylist, holdlist, l1, l2):
# for i in range(l1[0], l1[1] + 1):
# holdlist[i] = mylist[i]
holdlist[l1[0]:l1[1]+1] = mylist[l1[0]:l1[1]+1]
l1curr = l1[0]
l2curr = l2[0]
curr = l1[0]
while l1curr <= l1[1] and l2curr <= l2[1] and curr <= l2[1]:
if holdlist[l1curr] <= mylist[l2curr]:
mylist[curr] = holdlist[l1curr]
l1curr += 1
curr += 1
else:
mylist[curr] = mylist[l2curr]
l2curr += 1
curr += 1
while l1curr <= l1[1] and curr <= l2[1]:
mylist[curr] = holdlist[l1curr]
l1curr += 1
curr += 1
return (l1[0], l2[1]) |
e0637c28db4eec20241c1543e00b5b10aa08d872 | Paruyr31/Basic-It-Center | /Basic/Homework.5/649_.py | 269 | 3.546875 | 4 | n = input("input the text: ")
z1 = 0
z2 = -1
for i in range(len(n)):
if n[i] == "z":
z1 += i
break
for i in range(z1 + 1, len(n)):
if n[i] == "z":
z2 += i
break
count = z2 - z1 # count of simvols, from 'z' to 'z'
print(count) |
0627bc29400b783ed5bf32bd83ba5de53b3e152d | bjarki88/Projects | /prof1.py | 525 | 4.15625 | 4 | #secs = int(input("Input seconds: ")) # do not change this line
#hours = secs//(60*60)
#secs_remain = secs % 3600
#minutes = secs_remain // 60
#secs_remain2 = secs % 60
#seconds = secs_remain2
#print(hours,":",minutes,":",seconds) # do not change this line
max_int = 0
num_int = int(input("Input a number: ")) # Do not change this line
while num_int >= 0:
if num_int > max_int:
max_int = num_int
num_int = int(input("Input a number: "))
print("The maximum is", max_int) # Do not change this line
|
e01e7b007f7041fccc232fc3e9ab9ecacb44dec4 | kradical/ProjectEuler | /p9.py | 467 | 4.15625 | 4 | # A Pythagorean triplet is a set of three
# natural numbers, a < b < c, for which,
# a2 + b2 = c2
# For example, 32 + 42 = 9 + 16 = 25 = 52.
# There exists exactly one Pythagorean triplet
# for which a + b + c = 1000.
# Find the product abc.
def test():
for a in range(1, 333):
for b in range(1000-a):
c = 1000-b-a
if a**2 + b**2 == c**2:
print(a*b*c)
return
if __name__ == "__main__":
test() |
ee7a4a17a11e14be07256224feb495e51a6125d9 | rajat00420/sandbox | /activity02.py | 222 | 3.671875 | 4 | __author__ = 'jc441938'
scores = []
score = int(input("Score: "))
while scores >= 0:
scores.append(scores)
score = int(input("Score: "))
if scores !=[]:
print("Your highest score is", max(scores))
|
d561371e0f6c240cc7bf7c2b9a27be937cb4e3e4 | GuangkunYu/python | /数据分析/NumpyPro/3.2数组的基本操作1.py | 281 | 3.5 | 4 | import numpy as np
# 数组操作的算术运算符会应用到元素级别
a = np.array([20, 30, 40, 50])
b = np.arange(4)
print(a)
print(b)
# 减法操作
c = a - b
print(c)
# 乘方操作
print(b ** 2)
# sin操作
print(10 * np.sin(a))
# 比较大小操作
print(a < 35)
|
2f377125ce3efe3515353417d9168d49f514ef43 | Krondini/CSCI-3104 | /Assignments/Assignment_PS7b/Rondini-Konlan-PS7b-Q3.py | 774 | 3.9375 | 4 | '''
# Takes in a list and its bounds as parameters
# Function will split the list in half recursively
# in order to search for the maximum h-index
# Will return the maximum h-index of the list
'''
def calcIndex(N, left, right):
median = len(N)//2
if (len(N)%2) == 0: #Even number of elements, adjust median
median -= 1
if N[median+1] >= median+2: #h-index is larger than the median
return calcIndex(N, median+1, right)
elif(N[median] >= median+1):
return median + 1
else:
return calcIndex(N, left, median-1)
def main():
lst = [7, 6, 4, 3, 1, 0] #Even elements test
print(lst)
print(calcIndex(lst, 0, len(lst)-1))
lst2 = [6, 5, 3, 1, 0] #Odd elements test
print(lst2)
print(calcIndex(lst2, 0, len(lst2)-1))
if __name__ == '__main__':
main() |
ef2f528fb3f7a3641e261b3b6d9236943829086b | MirkoNardini/tomorrowdevs | /Workbook - cap7/Exercise_152_Number_the_Lines_in_a_File.py | 678 | 3.515625 | 4 | name1 = input("Inserire il nome del file: ")
name2 = input('Inserire un nome per il nuovo file:')
name1 = 'C:\\Users\\Mirco\\Desktop\\es python\\Files\\' + name1
name2 = 'C:\\Users\\Mirco\\Desktop\\es python\\Files\\' + name2
try:
t = open(name1, "r")
line = t.readline()
count = 0
TFile_res = open(name2, 'a')
while count <= len(line)+1 and line != "":
count = count + 1
line = line.rstrip()
line = str(count) + ': ' + line + ' ' + '\n'
TFile_res.write(line)
line = t.readline()
inf.close()
except FileNotFoundError:
print("Non è stato possibile aprire il file. Uscire...")
quit()
|
555525fc583ceb3f1a49f2bf535079a354b19d78 | renanaquinno/python3 | /#ATIVIDADES_FABIO/#Atividade_Fabio_04_Repeticao_While/#Atividade_Fabio04_Repeticao_04_divisao_por_dois.py | 176 | 4.1875 | 4 | #entrada
numero = int(input("Informe o Numero: "))
#processamento
def divisao (numero):
while numero > 1:
numero = numero / 2
print(numero)
divisao(numero) |
0a0359597566f949b42b833b0e231563eba2fa71 | yeshayaa/Projects | /makeArray.py | 1,689 | 3.90625 | 4 | from random import randint
class SimpleMatrix:
"""
Two dimensionmatrix. Default matrix 3 x 3
represented as an N x N list of lists.
The Matrix is initialized with random integers (0, 1000)
"""
def __init__(self, n=3):
"""
initializes random integers.
"""
self.size = n
self.mat = []
for i in range(self.size):
new_row = []
for j in range(self.size):
new_row.append(randint(0, 1000))
self.mat.append(new_row)
def matrix_print(self, get_coords=None):
"""
Print a nice looking matrix.
"""
for i in range(len(self.mat)):
for j in range(len(self.mat[i])):
if get_coords:
i, j = get_coords(i, j)
print("%4d" % (self.mat[i][j])),
print
print
def mirror_image_print(self):
"""
matrix[0][0] -> matrix[n-1][n-1]
matrix[1][0] -> matrix[n-2][n-1]
"""
def coords(i, j):
i_idx = len(self.mat[i]) -1 -i
j_idx = len(self.mat[j]) -1 -j
return (i_idx, j_idx)
self.matrix_print(coords)
def left_rotate_print(self):
"""
Rotate the matrix leftwards
"""
def coords(i, j):
n = self.size -1
return (j, n-i)
self.matrix_print(coords)
def test_self(num_elements):
mat = SimpleMatrix(num_elements)
mat.matrix_print()
mat.mirror_image_print()
mat.left_rotate_print()
if __name__ == '__main__':
test_self(3)
|
4fde8dc290b8396b1b693d6cb5791cd01412bf53 | cshintov/Integer-Sequences | /Fibonacci Sequence/fibonacci.py | 577 | 4.4375 | 4 | # This code will return the nth element of the Fibonacci sequence
def fibonacci(n):
n += 1
i=1
num1,num2=0,1
if n==1:
return 0
elif n==2:
return 1
else:
while i<n-1:
sum=num1+num2
num1,num2=num2,sum
i += 1
return sum
while True:
try:
my_num=int(input("Enter a number:"))
if my_num >-1 :
break
except:
print("Enter a positive integer: ")
print(f"The {my_num}th element of fibonacci series is:",fibonacci(my_num))
|
1b6e7c7232625eae14c07f1776cd4f2eaa8beb43 | skanin/NTNU | /Informatikk/Bachelor/V2018/TTM4100/Skeleton UDPPingerClient.py | 1,702 | 3.59375 | 4 | # This skeleton is valid for both Python 2.7 and Python 3.
# You should be aware of your additional code for compatibility of the Python version of your choice.
import time
from socket import *
# Get the server hostname and port as command line arguments
host = '127.0.0.1' # FILL IN END
port = 12000 # FILL IN END
timeout = 1 # in seconds
# Create UDP client socket
# FILL IN START
client = socket(AF_INET, SOCK_DGRAM)
# Note the second parameter is NOT SOCK_STREAM
# but the corresponding to UDP
# Set socket timeout as 1 second
client.settimeout(timeout)
# FILL IN END
# Sequence number of the ping message
ptime = 0
# Ping for 10 times
while ptime < 10:
ptime += 1
# Format the message to be sent as in the Lab description
# data = ('Ping' + str(ptime))# FILL IN START # FILL IN END
data = "Ping " + str(ptime) + " " + str(time.asctime())
try:
# FILL IN START
# Record the "sent time"
sentTime = time.time()
# Send the UDP packet with the ping message
client.sendto(data, (host, port))
# Receive the server response
message, address = client.recvfrom(1024)
# Record the "received time"
recvTime = time.time()
# Display the server response as an output
print("Address: " + address[0])
print("Port: " + str(address[1]))
# Round trip time is the difference between sent and received time
print("RTT: " + str(recvTime - sentTime))
# FILL IN END
except:
# Server does not response
# Assume the packet is lost
print("Request timed out.")
continue
# Close the client socket
client.close()
|
4d95331c8f69700dc0e14fa00aca28f61ada83b7 | deepaktester365/Project_euler | /projects/project_7.py | 1,228 | 3.828125 | 4 | import numpy as np
problem_title = "10001st prime"
problem_lines = [
"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?"
]
def problem_statement():
print("Problem Statement:")
print("\t", problem_title)
for problem_line in problem_lines:
print("\t\t", problem_line)
print("\n\n")
def check_prime(ck_num):
max_val = int(ck_num**(1 / 2)) + 1
for i in range(2, max_val):
if (ck_num / i).is_integer():
return False
return True
def check_prime_np(ck_num):
max_val = int(ck_num**(1 / 2)) + 1
ck_np = np.arange(2, max_val)
ck_num_np = np.ones(len(ck_np))
ck_num_np *= ck_num
ck_div_np = ck_num_np / ck_np
ck_div_np_int = ck_div_np.astype(int)
ck_div_ck = (ck_div_np_int / ck_div_np).astype(int)
if np.sum(ck_div_ck) > 0:
return False
else:
return True
def run():
prime_num_loc = 10000
prime_num_list = []
num = 2
while len(prime_num_list) < prime_num_loc:
if check_prime(num):
prime_num_list.append(num)
num += 1
print("The 10001st prime number is", prime_num_list[-1])
|
2836e923be98ce460600b4d1f602633f1e11d7de | RogerNoel/Python_workshop | /01 Introduction/syntaxe.py | 515 | 3.84375 | 4 | # est le signe pour commenter le code
# assignation de variables :
n = 7
message = « Welcome to our workshop »
# Affichage avec print()
# bloc conditionnel : l’utilisation des deux points « : »
# conjuguée à l’indentation permet de délimiter les blocs :
a = 0
if a > 0:
print(« a est positif »)
elif a < 0:
print(« a est négatif »)
else :
print(« a est nul »)
# de la même manière, le système des blocs pour un while
a = 0
while (a < 7):
a = a + 1
print(a) |
c1b92a86eb647ac13f9b7535d46f4ed3a7b01ff4 | A01374974/Tarea-07-2 | /TareaListas.py | 12,324 | 3.796875 | 4 | #encoding UTF-8
#Alejandro Chávez Campos, A01374974
#Este programa tiene distintas funciones que actúan sobre distintas listas ya asignadas en el programa.
def resolverListaValoresPares(): #Esta función regresa los valores pares de listas ya dadas
lista1= [1, 2, 3, 2, 4, 60, 5, 8, 3, 22, 44, 55]
x=0
listaNueva = []
while not (x>=(len(lista1))):
if lista1[x]%2==0:
valorPar=lista1[x]
listaNueva.append(valorPar)
x+=1
lista2 = [5,7,3]
x = 0
listaNueva2 = []
while not (x >= (len(lista2))):
if lista2[x] % 2 == 0:
valorPar = lista2[x]
listaNueva2.append(valorPar)
x += 1
lista3 = [4]
x = 0
listaNueva3 = []
while not (x >= (len(lista3))):
if lista3[x] % 2 == 0:
valorPar = lista3[x]
listaNueva3.append(valorPar)
x += 1
lista4 = []
x = 0
listaNueva4 = []
while not (x >= (len(lista4))):
if lista4[x] % 2 == 0:
valorPar = lista4[x]
listaNueva4.append(valorPar)
x += 1
print ("Problema 1. Regresa una lista con los valores pares de la lista original")
print ("Con la lista {} regresa {}".format(lista1,listaNueva))
print("Con la lista {} regresa {}".format(lista2,listaNueva2))
print("Con la lista {} regresa {}". format(lista3,listaNueva3))
print("Con la lista {} regresa {}".format(lista4,listaNueva4))
def resolverValoresMayores():#Esta función regresa los valores mayores a su valor anterior en una nueva lista
lista1= [1,2,3,2,4,60,5,8,3,22,44,55]
listaNueva=[]
x=1
while not x>=len(lista1):
if lista1[x]>lista1[x-1]:
listaNueva.append(lista1[x])
x+=1
lista2 = [5,4,3,2]
listaNueva2 = []
x = 1
while not x >= len(lista2):
if lista2[x] > lista2[x - 1]:
listaNueva2.append(lista2[x])
x += 1
lista3 = [5]
listaNueva3 = []
x = 1
while not x >= len(lista3):
if lista3[x] > lista3[x - 1]:
listaNueva3.append(lista3[x])
x += 1
lista4 = []
listaNueva4 = []
x = 1
while not x >= len(lista4):
if lista4[x] > lista4[x - 1]:
listaNueva4.append(lista4[x])
x += 1
print("Problema 2. Regresa una lista con los valores que son mayores al valor anterior.")
print("Con la lista {} regresa {}".format(lista1,listaNueva))
print("Con la lista {} regresa {}".format(lista2,listaNueva2))
print("Con la lista {} regresa {}". format(lista3,listaNueva3))
print("Con la lista {} regresa {}". format(lista4,listaNueva4))
def resolverListaParejasCambiadas(): #Esta función regresa las parejas de números en orden invertido
lista1=[1,2,3,2,4,60,5,8,3,22,44,55]
nuevaLista=[]
x=1
if len(lista1)%2==0:
while not x>=(len(lista1)) :
nuevaLista.insert((x-1),lista1[x])
nuevaLista.insert((x),lista1[x-1])
x+=2
elif len(lista1)%2==1:
while not x>=(len(lista1)-1):
nuevaLista.insert((x-1),lista1[x])
nuevaLista.insert((x),lista1[x-1])
x+=2
nuevaLista.insert(len(nuevaLista),lista1[len(lista1)-1])
nuevaLista2=[]
lista2=[1,2,3]
x=1
if len(lista2) % 2 == 0:
while not x >= (len(lista2)):
nuevaLista2.insert((x - 1), lista2[x])
nuevaLista2.insert((x), lista2[x - 1])
x += 2
elif len(lista2) % 2 == 1:
while not x > (len(lista2) - 1):
nuevaLista2.insert((x - 1), lista2[x])
nuevaLista2.insert((x), lista2[x - 1])
x += 2
nuevaLista2.insert(len(nuevaLista2), lista2[len(lista2) - 1])
nuevaLista3 = []
lista3 = []
x=1
if len(lista3) % 2 == 0:
while not x >= (len(lista3)):
nuevaLista3.insert((x - 1), lista3[x])
nuevaLista3.insert((x), lista3[x - 1])
x += 2
elif len(lista3) % 2 == 1:
while not x > (len(lista3) - 1):
nuevaLista3.insert((x - 1), lista3[x])
nuevaLista3.insert((x), lista3[x - 1])
x += 2
nuevaLista3.insert(len(nuevaLista3), lista3[len(lista3) - 1])
nuevaLista4 = []
lista4 = [7]
x = 1
if len(lista4) % 2 == 0:
while not x >= (len(lista4)):
nuevaLista4.insert((x - 1), lista4[x])
nuevaLista4.insert((x), lista4[x - 1])
x += 2
elif len(lista4) % 2 == 1:
while not x > (len(lista4) - 1):
nuevaLista4.insert((x - 1), lista4[x])
nuevaLista4.insert((x), lista4[x - 1])
x += 2
nuevaLista4.insert(len(nuevaLista4), lista4[len(lista4) - 1])
print("Problema 3. Intercambia el orden de las parejas de los datos de la lista.")
print("Con la lista {} regresa {}".format(lista1, nuevaLista))
print("Con la lista {} regresa {}".format(lista2, nuevaLista2))
print("Con la lista {} regresa {}".format(lista3, nuevaLista3))
print("Con la lista {} regresa {}".format(lista4, nuevaLista4))
def resolverListaIntercambiarMinimosYMaximos(): #Esta función intercambia el orden de los valores mínimos y máximos
nuevaLista1= []
lista1= [5,9,3,22,19,31,10,7]
x=0
while not x>=(len(lista1)):
nuevaLista1.append(lista1[x])
if lista1[x]==max(lista1):
valorMax= x
if lista1[x]==min(lista1):
valorMin= x
x+=1
if len(lista1)>0:
nuevaLista1.remove(nuevaLista1[valorMax])
nuevaLista1.insert(valorMax, min(lista1))
nuevaLista1.remove(nuevaLista1[valorMin])
nuevaLista1.insert(valorMin, max(lista1))
else:
nuevaLista1=[]
nuevaLista2 = []
lista2 = [1,2,3]
x = 0
while not x >= (len(lista2)):
nuevaLista2.append(lista2[x])
if lista2[x] == max(lista2):
valorMax = x
if lista2[x] == min(lista2):
valorMin = x
x += 1
if len(lista2)>0:
nuevaLista2.remove(nuevaLista2[valorMax])
nuevaLista2.insert(valorMax, min(lista2))
nuevaLista2.remove(nuevaLista2[valorMin])
nuevaLista2.insert(valorMin, max(lista2))
else:
nuevaLista2=[]
nuevaLista3 = []
lista3 = [7]
x = 0
while not x >= (len(lista3)):
nuevaLista3.append(lista3[x])
if lista3[x] == max(lista3):
valorMax = x
if lista3[x] == min(lista3):
valorMin = x
x += 1
if len(lista3)>0:
nuevaLista3.remove(nuevaLista3[valorMax])
nuevaLista3.insert(valorMax, min(lista3))
nuevaLista3.remove(nuevaLista3[valorMin])
nuevaLista3.insert(valorMin, max(lista3))
else:
nuevaLista3=[]
nuevaLista4 = []
lista4 = []
x = 0
while not x >= (len(lista4)):
nuevaLista4.append(lista4[x])
if lista4[x] == max(lista4):
valorMax = x
if lista4[x] == min(lista4):
valorMin = x
x += 1
if len(lista4)>0:
nuevaLista4.remove(nuevaLista4[valorMax])
nuevaLista4.insert(valorMax, min(lista4))
nuevaLista4.remove(nuevaLista4[valorMin])
nuevaLista4.insert(valorMin, max(lista4))
else:
nuevaLista4=[]
print("Problema 4. Intercambia el lugar del valor mínimo y máximo.")
print("Con la lista {} regresa {}".format(lista1,nuevaLista1))
print("Con la lista {} regresa {}".format(lista2,nuevaLista2))
print("Con la lista {} regresa {}".format(lista3,nuevaLista3))
print("Con la lista {} regresa {}". format(lista4, nuevaLista4))
def resolverListaNumerosMayoresAlPromedio(): #Esta función regresa el número de valores mayores al promedio, de los valores de la lista.
lista1=[70, 80, 90]
nuevaLista1=[]
promedio=sum(lista1)/len(lista1)
print("Problema 5. Regresa de una lista el número de datos mayores o iguales al promedio")
x=0
while not x>=len(lista1):
if lista1[x]>=promedio:
nuevaLista1.append(lista1[x])
x+=1
print("Si recibe {} regresa {}. Porque el promedio es {} y hay {} valores mayores o iguales a {}, {}".format((lista1),len(nuevaLista1), promedio, len(nuevaLista1), promedio,nuevaLista1))
lista2 = [95,21,73,24,15,69,71,80,49,100,85]
nuevaLista2 = []
promedio = sum(lista2) / len(lista2)
x = 0
while not x >= len(lista2):
if lista2[x] >= promedio:
nuevaLista2.append(lista2[x])
x += 1
print("Si recibe {} regresa {}. Porque el promedio es {} y hay {} valores mayores o iguales a {}, {}".format((lista2),len(nuevaLista2), promedio, len(nuevaLista2), promedio,nuevaLista2))
lista3 = [3]
nuevaLista3 = []
promedio = sum(lista3) / len(lista3)
x = 0
while not x >= len(lista3):
if lista3[x] >= promedio:
nuevaLista3.append(lista3[x])
x += 1
print(
"Si recibe {} regresa {}. Porque el promedio es {} y hay {} valores mayores o iguales a {}, {}".format((lista3),len(nuevaLista3),promedio,len(nuevaLista3),promedio,nuevaLista3))
lista4 = []
nuevaLista4 = []
if not len(lista4)>0:
promedio =0
else:
promedio = sum(lista4) / len(lista4)
x = 0
while not x >= len(lista4):
if lista4[x] >= promedio:
nuevaLista4.append(lista4[x])
x += 1
print("Si recibe {} regresa {}. Porque el promedio es {} y hay {} valores mayores o iguales a {}, {}".format(( lista4),len(nuevaLista4), promedio,len(nuevaLista4),promedio,nuevaLista4))
def resolverPromedioYDesviaciónEstándar(): #Esta función da el promedio y la desviación estándar.
lista1= [1,2,3,4,5,6]
nuevaLista1=[]
promedio=0
desviacion =0
for x in range (0,len(lista1)):
promedio=promedio+ lista1[x]
promedio=promedio/len(lista1)
nuevaLista1.append(promedio)
for x in range (0, len(lista1)):
desviacion= desviacion+(lista1[x]-promedio)**2
desviacion=((desviacion)/(len(lista1)-1))**0.5
nuevaLista1.append(desviacion)
lista2 = [95,21,73,24,15,69,71,80,49,100,85]
nuevaLista2 = []
promedio = 0
desviacion = 0
for x in range(0, len(lista2)):
promedio = promedio + lista2[x]
promedio = promedio / len(lista2)
nuevaLista2.append(promedio)
for x in range(0, len(lista2)):
desviacion = desviacion + (lista2[x] - promedio) ** 2
desviacion = ((desviacion) / (len(lista2) - 1)) ** 0.5
nuevaLista2.append(desviacion)
lista3 = [3]
nuevaLista3 = []
promedio = 0
desviacion = 0
for x in range(0, len(lista3)):
promedio = promedio + lista3[x]
promedio = promedio / len(lista3)
nuevaLista3.append(promedio)
if len(lista3)>1:
for x in range(0, len(lista3)):
desviacion = desviacion + (lista3[x] - promedio) ** 2
desviacion = ((desviacion) / (len(lista3) - 1)) ** 0.5
nuevaLista3.append(desviacion)
else:
desviacion =0
nuevaLista3.append(desviacion)
lista4 = []
nuevaLista4 = []
promedio = 0
desviacion = 0
if len(lista4)>0:
for x in range(0, len(lista4)):
promedio = promedio + lista4[x]
promedio = promedio / len(lista4)
else:
promedio=0
nuevaLista4.append(promedio)
if len(lista4) > 1:
for x in range(0, len(lista4)):
desviacion = desviacion + (lista4[x] - promedio) ** 2
desviacion = ((desviacion) / (len(lista4) - 1)) ** 0.5
nuevaLista4.append(desviacion)
else:
desviacion = 0
nuevaLista4.append(desviacion)
print("Problema 6. Regresa el promedio y la desviación estándar")
print("Si recibe {} regresa {}".format(lista1,nuevaLista1))
print("Si recibe {} regresa {}".format(lista2, nuevaLista2))
print("Si recibe {} regresa {}".format(lista3, nuevaLista3))
print("Si recibe {} regresa{}".format(lista4,nuevaLista4))
def main(): #Programa principal
resolverListaValoresPares()
print ()
resolverValoresMayores()
print()
resolverListaParejasCambiadas()
print()
resolverListaIntercambiarMinimosYMaximos()
print()
resolverListaNumerosMayoresAlPromedio()
print()
resolverPromedioYDesviaciónEstándar()
main() |
23d496fe14d911ec967b20b9f3791e67b66f22b6 | sonnyfuture/Ch.05_Looping | /Test.py | 197 | 4.15625 | 4 | for i in range(5):
print("I love Python!")
for i in range(5):
print("Please,")
print("Help me learn Python!")
for i in range(1,11):
print(i)
for i in range (2,12,2):
print(i) |
2b963e12f547ed95eb9b4e8523a02f498f594033 | yonwu/thinkpython | /Strings/8.3.py | 237 | 3.84375 | 4 |
def is_palindrome(s):
if len(s) <= 1:
return True
elif len(s) > 2:
if s == s[::-1]:
return True
return False
if __name__ == "__main__":
result = is_palindrome('emme')
print(result)
|
78edc1e932090625704084dc68cb0a27defedad6 | kwatts/interview_practice | /algorithms/scripts/incr_decimal_number.py | 1,385 | 3.953125 | 4 | #!/usr/bin/python
def incr_decimal(num):
"""Increment a decimal coded number.
[1,2,3] -> [1,2,3] # 123 -> 124.
"""
for idx in range(len(num) - 1, -1, -1):
incremented = num[idx] + 1
num[idx] = incremented % 10
if incremented < 10:
return num
return [1] + [0] * len(num)
def encode_decimal_list(num):
"""Encode a number as a decimal list"""
if num == 0:
return [ 0 ]
rv = []
while num:
rv.insert(0, num % 10)
num = num / 10
return rv
def decode_decimal_list(lst):
"""Decode a decimal list into a number"""
num = 0
for i, l in enumerate(reversed(lst)):
num += l * 10**i
return num
def test_encode():
assert [1, 0, 0] == encode_decimal_list(100)
assert [1, 2, 3] == encode_decimal_list(123)
assert [0] == encode_decimal_list(0)
assert [9, 5] == encode_decimal_list(95)
def test_decode():
assert 100 == decode_decimal_list([1,0,0])
assert 123 == decode_decimal_list([1,2,3])
assert 99 == decode_decimal_list([9,9])
def test_increment():
assert [1,2,4] == incr_decimal([1,2,3])
assert [1,0,0] == incr_decimal([9,9])
assert [6] == incr_decimal([5])
assert [1] == incr_decimal([0])
assert [1,2,0] == incr_decimal([1,1,9])
assert [2,0,0] == incr_decimal([1,9,9])
test_encode()
test_decode()
test_increment()
|
aad9ca401681db24374833e657c0041e36c2bd3c | zhangzongyan/python20180319 | /day0a/m5.py | 1,712 | 3.5625 | 4 |
# 高阶函数:函数通过参数传入的方式称为高阶函数
def sum2abs(a, b, f):
return f(a) + f(b)
n = abs(-10)
print(n)
# abs 函数名
xiaopang = abs
print(xiaopang(-100))
'''
abs = 10 #这是允许的 但不要这么做
print(abs + 100)
'''
print(sum2abs(5, -6, abs))
print(sum2abs(100, 120, str))
# 常用的高阶函数之 map
def mypow(x, y = 2):
return pow(x, y)
import collections
r = map(mypow, [1,2,3,4,5,6])
print(isinstance(r, collections.Iterator))
#l = list(r)
#print(l)
# r是一个迭代器,只能遍历一次
while True:
try:
print(next(r))
except:
break
#print(next(r))
# 练习1:将整型数列表[1,2,3,4,5,6]转换为字符串列表['1', '2', '3', '4', '5', '6']
print(list(map(str,[x for x in range(1,7)])))
# reduce
from functools import reduce
r = reduce(lambda x, y : x + y, (1,3,5,7,9))
print(r)
# 练习2:将字符串"12345"转换为整型数12345
# 1,2,3,4,5
print(reduce(lambda x, y : x*10 + y, map(lambda x : ord(x) - ord('0'), "12345")))
# reduce(f, (1,2,3,4,5)) f(f(f(f(1, 2), 3), 4), 5)
# filter:过滤所有调用给定的函数为False
def isEven(x):
return x % 2 == 0
f = filter(isEven, [x for x in range(1, 101)])
print(list(f))
# 练习3:有一个列表["helo", "", "1", "2", " ", "\n"]
# " abc".strip() "abc"
def not_emptystr(s):
return s and s.strip()
print(list(filter(not_emptystr, ["helo", "", "1", "2", " ", "\n"])))
# sorted 排序
l = [5, 2, -1, -4, 10, 6]
print(sorted(l))
#绝对值排序
print(sorted(l, key=abs))
#练习4:将["hello", "good", "study", "alice", "Petter", "HANMEIMEI"] 忽略大小写排序
print(sorted(["hello", "good", "study", "alice", "Petter", "HANMEIMEI"], key = str.lower, reverse=True))
|
76a9797e9c01e9640937a1a00efa4dec9dfc198d | scissorsneedfoodtoo/automate-the-boring-stuff-coursework | /7-pattern-matching-with-regular-expressions/find-number-regex.py | 246 | 3.546875 | 4 | import re
message = 'Call me at 415-555-1011 tomorrow. 415-555-9999 is my office.'
phoneNumRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')
# matchObj = phoneNumRegex.search(message)
# print(matchObj.group())
print(phoneNumRegex.findall(message))
|
2dd4aa314fd6dae0eafdb4ba75df3511260e532b | holzru/examples | /Meters_converter.py | 1,226 | 3.6875 | 4 | def meters(x):
print x
if x >= 10**24:
print "{}Ym".format(int(x)/10**24 if float(x)/10**24 == int(x)/10**24 else float(x)/10**24)
elif 10**24 > x >= 10**21:
print "{}Zm".format(int(x)/10**21 if float(x)/10**21 == int(x)/10**21 else float(x)/10**21)
elif 10**21 > x >= 10**18:
print "{}Em".format(int(x)/10**18 if float(x)/10**18 == int(x)/10**18 else float(x)/10**18)
elif 10**18 > x >= 10**15:
print "{}Pm".format(int(x)/10**15 if float(x)/10**15 == int(x)/10**15 else float(x)/10**15)
elif 10**15 > x >= 10**12:
print "{}Tm".format(int(x)/10**12 if float(x)/10**12 == int(x)/10**12 else float(x)/10**12)
elif 10**12 > x >= 10**9:
print "{}Gm".format(int(x)/10**9 if float(x)/10**9 == int(x)/10**9 else float(x)/10**9)
elif 10**9 > x >= 10**6:
print "{}Mm".format(int(x)/10**6 if float(x)/10**6 == int(x)/10**6 else float(x)/10**6)
elif 10**6 > x >= 10**3:
print "{}km".format(int(x)/10**3 if float(x)/10**3 == int(x)/10**3 else float(x)/10**3)
else:
print "{}m".format(x)
meters(7000000000000000000000000)
meters(1000000000000)
meters(1230000000000)
meters(1230000000)
meters(1230000)
meters(1230)
meters(123)
|
5853fc0df29ab99e09b99a456e15d2c245ef9b93 | wlsouza/pysnakegame | /pysnakegame/sprites/snake.py | 3,890 | 3.703125 | 4 | import pygame
class Snake(pygame.sprite.Sprite):
def __init__(self, screen, color, body_part_size):
super().__init__()
self.screen = screen
self.color = color
self.body_part_size = body_part_size
self.current_direction = None
self.body = [(0, 0)]
self.rects = []
@property
def head(self):
return self.body[-1]
@property
def tail(self):
return self.body[0]
@property
def head_rect(self):
return self.rects[-1]
@property
def body_rects(self):
return self.rects[0:-1]
def update(self):
self.move()
self.draw()
def move(self):
if self.current_direction:
# adiciona a parte da frente do corpo (a cabeça)
pos_x, pos_y = self.head
if self.current_direction == "up":
pos_y -= self.body_part_size
elif self.current_direction == "down":
pos_y += self.body_part_size
elif self.current_direction == "left":
pos_x -= self.body_part_size
elif self.current_direction == "right":
pos_x += self.body_part_size
self.body.append((pos_x, pos_y))
# remove a primeira parte do corpo da cobra (a cauda)
self.body.pop(0)
def increase_body(self):
# adiciona mais uma parte do corpo na mesma posição que a cauda
self.body.insert(0,self.tail)
def reset(self):
self.body = [(0, 0)]
self.current_direction = None
def draw(self):
self.rects = []
for body_part in self.body:
rect = pygame.Rect(
body_part, (self.body_part_size, self.body_part_size)
)
if body_part == self.head:
self._draw_tong(rect)
self._draw_body(rect)
self.rects.append(rect)
def _draw_body(self, rect):
pos_x, pos_y = rect.x, rect.y
pygame.draw.rect(self.screen, self.color, rect)
pygame.draw.rect(
self.screen,
(self.color[2], self.color[1], self.color[0]), # mix color values
(
pos_x + (self.body_part_size // 4),
pos_y + (self.body_part_size // 4),
self.body_part_size // 2,
self.body_part_size // 2,
),
)
def _draw_tong(self, rect):
pos_x, pos_y = rect.x, rect.y
if self.current_direction == "up":
pygame.draw.line(
self.screen,
(255, 0, 0),
(pos_x + self.body_part_size // 2, pos_y),
(pos_x + self.body_part_size // 2, pos_y - self.body_part_size // 4),
3,
)
elif self.current_direction == "down":
pygame.draw.line(
self.screen,
(255, 0, 0),
(pos_x + self.body_part_size // 2, pos_y + self.body_part_size),
(
pos_x + self.body_part_size // 2,
int(pos_y + self.body_part_size * 1.25),
),
3,
)
elif self.current_direction == "left":
pygame.draw.line(
self.screen,
(255, 0, 0),
(pos_x, pos_y + self.body_part_size // 2),
(pos_x - self.body_part_size // 4, pos_y + self.body_part_size // 2),
3,
)
elif self.current_direction == "right":
pygame.draw.line(
self.screen,
(255, 0, 0),
(pos_x + self.body_part_size, pos_y + self.body_part_size // 2),
(
int(pos_x + self.body_part_size * 1.25),
pos_y + self.body_part_size // 2,
),
3,
)
|
bc2bbd7212daa63a9bf03850f750761648bbb8ec | vrvelasco/Python-Programming | /[Exams]/victorExam3.py | 3,391 | 4.21875 | 4 | # Victor Velasco (Exam 3) 12/2/19
def main():
MAX = 10 # Constant for size of the list
userNum = 0 # Number from the user
numberList = [] # Holds numbers
choice = 0 # User's menu option
name = {1:'First', 2:'Second', 3:'Third', 4:'Fourth', 5:'Fifth', 6:'Sixth', \
7:'Seventh', 8:'Eighth', 9:'Ninth', 10:'Tenth'} # Formatting
# Intro
print('Welcome!\n\nYou will be working with a list of ten numbers. Please enter them below.\n')
# Get ten numbers
for i in range(MAX):
print(name[i + 1], 'number', end='')
try: # Try to get a valid integer from the user
userNum = int(input(' ► Enter an integer between 1 and 100: '))
except:
userNum = -1 # Error
# Check range of number
while userNum < 1 or userNum > 100:
try: # Try to get a valid integer from the user
userNum = int(input('\nInvalid integer. Please try again: '))
except:
userNum = -1 # Error
numberList.append(userNum) # Add the number to the list
# Loop while the user doesn't want to exit
while choice != 4:
# Print list
print('\n\tList of numbers:', numberList,'\n', sep=' ')
# Display the menu and get the user's choice
choice = displayMenu()
# Match choice to menu options
if choice == 1:
largest = find_largest(numberList)
print('The largest number is:', largest)
elif choice == 2:
smallest = find_smallest(numberList)
print('The smallest number is:', smallest)
elif choice == 3:
result = sumList(numberList)
print('The sum of all of the numbers is:', result)
print('\nGoodbye!')
def displayMenu():
# Menu options
print('*** MENU ***')
print('Enter 1 to find the largest number')
print('Enter 2 to find the smallest number')
print('Enter 3 to sum the list of numbers')
print('Enter 4 to exit')
# Try to get a valid choice from the user
try:
selection = int(input('Selection: '))
except:
selection = -1 # Error
# Verify that the selection is in range
while selection < 1 or selection > 4:
try:
selection = int(input('\nInvalid selection. Please try again: '))
except:
selection = -1 # Error
# Return the option selected now that it's correct
return selection
def findLargest(numList):
n = len(numList)
if n == 1: # If the length is 1, then it's the only number in there
return numList[0]
else:
temp = findLargest(numList[0:n - 1]) # [0:n-1] means goes from 0 to last element
if numList[n - 1] > temp:
return numList[n - 1]
else:
return temp
def findSmallest(numList):
n = len(numList)
if n == 1: # If the length is 1, then it's the only number in there
return numList[0]
else:
temp = findSmallest(numList[0:n - 1]) # [0:n-1] means goes from 0 to last element
if numList[n - 1] < temp:
return numList[n - 1]
else:
return temp
def sumList(numList):
n = len(numList)
if len(numList) ==1:
return numList[0]
else:
return numList[n - 1] + sumList(numList[0:n - 1])
# Call main
main()
|
304dbce11fa6de5dced7c50842bae6452edab07e | secondtonone1/python- | /爬虫/output.py | 11,462 | 3.5 | 4 | #-*-coding:utf-8-*-
import re
'''
from datetime import datetime
now = datetime.now()
print(now)
print(type(now))
from datetime import datetime
dt = datetime(2017,12,13,13,7)
# 把datetime转换为timestamp
print( dt.timestamp() )
from datetime import datetime
t = 1429417200.0
print(datetime.fromtimestamp(t))
#根据时间戳转化为本地时间和utc时间
from datetime import datetime
t = 1429417200.0
# 本地时间
print(datetime.fromtimestamp(t))
# UTC时间
print(datetime.utcfromtimestamp(t))
from datetime import datetime
cday = datetime.strptime('2017-6-1 18:22:22','%Y-%m-%d %H:%M:%S')
print(cday)
from datetime import datetime
now = datetime.now()
print(now.strftime('%a,%b %d %H:%M'))
from datetime import datetime , timedelta
now = datetime.now()
print( now )
print(now + timedelta(hours = 10))
print(now + timedelta(days = 1))
print(now + timedelta(days = 2, hours = 12))
from datetime import datetime, timedelta, timezone
# 创建时区UTC+8:00
timezone_8 = timezone(timedelta(hours = 8) )
now = datetime.now()
print(now)
# 强制设置为UTC+8:00
dt = now.replace(tzinfo=timezone_8)
print(dt)
from datetime import datetime, timedelta, timezone
# 拿到UTC时间,并强制设置时区为UTC+0:00:
utc_dt = datetime.utcnow().replace(tzinfo=timezone.utc)
print(utc_dt)
bj_dt = utc_dt.astimezone(timezone(timedelta(hours = 8) ))
print(bj_dt)
tokyo_dt = utc_dt.astimezone(timezone(timedelta(hours = 9) ) )
print(tokyo_dt)
tokyo_dt2 = bj_dt.astimezone(timezone(timedelta(hours = 9) ) )
print(tokyo_dt2)
#可命名tuple
from collections import namedtuple
Point = namedtuple('Point', ['x','y'])
p = Point(1,2)
print(p.x)
from collections import deque
q = deque(['a','b','c'])
q.append('x')
q.appendleft('y')
print(q)
from collections import defaultdict
dd = defaultdict(lambda:'N/A')
dd['key1']='abc'
print(dd['key1'])
print(dd['key2'])
from collections import OrderedDict
d = dict([ ['a',1], ['b',2],['c',3]])
print(d)
od = OrderedDict([('a',1),('b',2),('c',3)])
print(od)
od2 = OrderedDict([['Bob',90],['Jim',20],['Seve',22]])
print(od2)
from collections import Counter
c = Counter()
for ch in 'programming':
c[ch]=c[ch]+1
'''
'''
#itertools.count(start , step)
import itertools
natuals = itertools.count(1)
for n in natuals:
print(n)
'''
'''
import itertools
cs = itertools.cycle('ABC') # 注意字符串也是序列的一种
for c in cs:
print(c)
'''
'''
import itertools
ns = itertools.repeat('A',5)
for n in ns:
print(n)
natuals = itertools.count(1)
ns = itertools.takewhile(lambda x: x <= 10, natuals)
print(ns)
print(list(ns) )
for c in itertools.chain('ABC','XYZ'):
print(c)
print(list(itertools.chain('ABC','XYZ')) )
for key, group in itertools.groupby('AAABBBCCAAA'):
print(key, list(group))
print(key, group)
for key, group in itertools.groupby('AaaBBbcCAAa', lambda c: c.upper() ):
print(key,list(group))
#open 返回的对象才可用with
# 在类中实现__enter__和__exit__可以使该类对象支持with用法
class Query(object):
def __init__(self, name):
self.name = name
def __enter__(self):
print('Begin')
return self
def __exit__(self, exc_type, exc_value, traceback):
if exc_type:
print('Error')
else:
print('End')
def query(self):
print('Query info about %s...' %self.name)
with Query('BBBB') as q:
if q:
q.query()
'''
'''
with EXPR as VAR:
实现原理:
在with语句中, EXPR必须是一个包含__enter__()和__exit__()方法的对象(Context Manager)。
调用EXPR的__enter__()方法申请资源并将结果赋值给VAR变量。
通过try/except确保代码块BLOCK正确调用,否则调用EXPR的__exit__()方法退出并释放资源。
在代码块BLOCK正确执行后,最终执行EXPR的__exit__()方法释放资源。
'''
#通过python提供的装饰器contextmanager,作用在生成器函数,可以达到with操作的目的
'''
from contextlib import contextmanager
class Query(object):
def __init__(self, name):
self.name = name
def query(self):
print('Query info about %s ...' %self.name)
@contextmanager
def create_query(name):
print('Begin')
q = Query(name)
yield q
print('End')
with create_query('aaa') as q:
if q:
print(q.query())
'''
#contextmanager源码
'''
class GeneratorContextManager(object):
def __init__(self, gen):
self.gen = gen
def __enter__(self):
try:
return self.gen.next()
except StopIteration:
raise RuntimeError("generator didn't yield")
def __exit__(self, type, value, traceback):
if type is None:
try:
self.gen.next()
except StopIteration:
return
else:
raise RuntimeError("generator didn't stop")
else:
try:
self.gen.throw(type, value, traceback)
raise RuntimeError("generator didn't stop after throw()")
except StopIteration:
return True
except:
# only re-raise if it's *not* the exception that was
# passed to throw(), because __exit__() must not raise
# an exception unless __exit__() itself failed. But
# throw() has to raise the exception to signal
# propagation, so this fixes the impedance mismatch
# between the throw() protocol and the __exit__()
# protocol.
#
if sys.exc_info()[1] is not value:
raise
def contextmanager(func):
def helper(*args, **kwds):
return GeneratorContextManager(func(*args, **kwds))
return helper
'''
'''
from contextlib import closing
from urllib.request import urlopen
with closing(urlopen('https://www.python.org')) as page:
for line in page:
print(line)
'''
##closing 实现原理
'''
@contextmanager
def closing(thing):
try:
yield thing
finally:
thing.close()
'''
'''
@contextmanager
def tag(name):
print("<%s>" % name)
yield
print("</%s>" % name)
with tag("h1"):
print("hello")
print("world")
'''
'''
上述代码执行结果为:
<h1>
hello
world
</h1>
代码的执行顺序是:
with语句首先执行yield之前的语句,因此打印出<h1>;
yield调用会执行with语句内部的所有语句,因此打印出hello和world;
最后执行yield之后的语句,打印出</h1>。
'''
'''
from urllib import request
with request.urlopen('http://www.limerence2017.com/') as f:
data = f.read()
print('Status:', f.status, f.reason)
for k, v in f.getheaders():
print('%s: %s' %(k,v))
print('Data:', data.decode('utf-8') )
'''
'''
from urllib import request
req = request.Request('http://www.douban.com/')
req.add_header('User-Agent', 'Mozilla/6.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/8.0 Mobile/10A5376e Safari/8536.25')
with request.urlopen(req) as f:
print('Status:', f.status, f.reason)
for k, v in f.getheaders():
print('%s: %s' %(k,v))
print('Data:', f.read().decode('utf-8'))
from urllib import request, parse
print('Login to weibo.cn...')
email = input('Email: ')
passwd = input('Password: ')
login_data = parse.urlencode([
('username', email),
('password', passwd),
('entry', 'mweibo'),
('client_id', ''),
('savestate', '1'),
('ec', ''),
('pagerefer', 'https://passport.weibo.cn/signin/welcome?entry=mweibo&r=http%3A%2F%2Fm.weibo.cn%2F')
])
req = request.Request('https://passport.weibo.cn/sso/login')
req.add_header('Origin', 'https://passport.weibo.cn')
req.add_header('User-Agent', 'Mozilla/6.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/8.0 Mobile/10A5376e Safari/8536.25')
req.add_header('Referer', 'https://passport.weibo.cn/signin/login?entry=mweibo&res=wel&wm=3349&r=http%3A%2F%2Fm.weibo.cn%2F')
with request.urlopen(req, data=login_data.encode('utf-8')) as f:
print('Status:', f.status, f.reason)
for k, v in f.getheaders():
print('%s:%s' %(k,v))
print('Data: ', f.read().decode('utf-8'))
proxy_handler = urllib.request.ProxyHandler({'http': 'http://www.example.com:3128/'})
proxy_auth_handler = urllib.request.ProxyBasicAuthHandler()
proxy_auth_handler.add_password('realm', 'host', 'username', 'password')
opener = urllib.request.bulid_opener(proxy_handler, proxy_auth_handler)
with opener.open('http://www.example.com/login.html') as f:
pass
proxy_auth_handler = urllib.request.ProxyBasicAuthHandler()
proxy_auth_handler.add_password('realm', 'host', 'username', 'password')
opener = urllib.request.build_opener(proxy_handler, proxy_auth_handler)
with opener.open('http://www.example.com/login.html') as f:
pass
'''
'''
from urllib import request, parse
url = 'https://www.zhihu.com/question/28591246/answer/276466494'
user_agent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.221 Safari/537.36 SE 2.X MetaSr 1.0'
refer = 'https://www.zhihu.com/question/28591246/answer/276466494'
req = request.Request(url)
req.add_header('User-Agent',user_agent)
req.add_header('Referer', refer)
with request.urlopen(req) as f:
print(f.read().decode('utf-8'))
'''
#先将数据读入文件
'''
from urllib import request, parse
from urllib import error
page = 1
url = 'https://www.qiushibaike.com/hot/page/'+str(page)
user_agent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.221 Safari/537.36 SE 2.X MetaSr 1.0'
try:
req = request.Request(url)
req.add_header('User-Agent', user_agent)
response = request.urlopen(req)
#bytes变为字符串
content = response.read().decode('utf-8')
print(type(content))
#uf-8编码方式打开
file = open('file.txt', 'w',encoding='utf-8')
file.write(content)
except error.URLError as e:
if hasattr(e,'code'):
print (e.code)
if hasattr(e,'reason'):
print (e.reason)
finally:
file.close()
'''
#从文件中读取并用正则表达式解析
'''
import re
with open('file.txt','r', encoding='utf-8') as f:
data = f.read()
pattern = re.compile(r'<div.*?<h2>(.*?)</h2>.*?<span>(.*?)</span>.*?number">(.*?)</i>.*?'+
r'"number">(.*?)</i>', re.S )
result = re.search(pattern, data)
#print(result)
#print(result.group())
print(result.group(1))
print(result.group(2))
print(result.group(3))
print(result.group(4))
'''
#利用findall批量爬取段子
from urllib import request, parse
from urllib import error
page = 1
url = 'https://www.qiushibaike.com/hot/page/'+str(page)
user_agent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.221 Safari/537.36 SE 2.X MetaSr 1.0'
try:
req = request.Request(url)
req.add_header('User-Agent', user_agent)
response = request.urlopen(req)
#bytes变为字符串
content = response.read().decode('utf-8')
pattern = re.compile(r'<div.*?<h2>(.*?)</h2>.*?<span>(.*?)</span>.*?number">(.*?)</i>.*?'+
r'"number">(.*?)</i>', re.S )
result = re.findall(pattern, content)
files = open('findfile.txt','w+', encoding='utf-8')
for item in result:
author = item[0]
contant = item[1]
vote = '赞:'+item[2]
commit = '评论数:'+item[3]
infos = vote +' '+commit+' '+'\n\n'
print(author)
print(contant)
print(infos)
files.write(author)
files.write(contant)
files.write(infos)
except error.URLError as e:
if hasattr(e,'code'):
print (e.code)
if hasattr(e,'reason'):
print (e.reason)
finally:
files.close() |
ed09abc19e382297d78c02e5ff9a5174243bf679 | shankar7791/MI-10-DevOps | /Personel/Elankavi/python/practice/feb25/terninary_add.py | 139 | 4.0625 | 4 | a =int(input("Enter the frst number : "))
b = int(input("Enter the second number : "))
print("The largest number is : " , a if a>b else b) |
f9b107989ae96ed51b33688f655b4c2003ff29f4 | ViVaHa/Encryption_And_Hashing | /Task4.py | 2,549 | 3.5 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 30 23:42:54 2018
@author: varshath
"""
import base64
from timeit import default_timer as timer
from Crypto.Hash import SHA256,SHA512
from Crypto.Hash import SHA3_256
def writeFile(data,fileName):
with open(fileName, 'w+') as f:
f.write(data)
def writeFileInBytes(data,fileName):
with open(fileName, 'wb+') as f:
f.write(data)
def generateFiles():
with open('kbfile.txt', 'w+') as f:
num_chars = 256
f.write("abcd" * num_chars)
#f.write("\n"*1)
with open('mbfile.txt', 'w+') as f:
num_chars = 256 * 1024
f.write("abcd" * num_chars)
f.write("\n"*1)
def getData(fileName):
x=""
with open(fileName,'r') as file:
x=file.read()
return x
def getDataInBytes(fileName):
x=""
with open(fileName,'rb') as file:
x=file.read()
return x
def generateHashUsingSHA256(fileName):
print("SHA_256")
data=getData(fileName)
data=bytes(data,"utf-8")
start = timer()
h = SHA256.new()
h.update(data)
#Because this looks better when viewed instead of h.digest()
digest=h.hexdigest()
end = timer()
#print(digest)
print("Time Taken to generate Hash is ",(end-start))
print("Time Taken to Hash per byte is ",(end-start)/len(data))
def generateHashUsingSHA512(fileName):
print("SHA_512")
data=getData(fileName)
data=bytes(data,"utf-8")
start = timer()
h = SHA512.new()
h.update(data)
#Because this looks better when viewed instead of h.digest()
digest=h.hexdigest()
end = timer()
#print(digest)
print("Time Taken to generate Hash is ",(end-start))
print("Time Taken to Hash per byte is ",(end-start)/len(data))
def generateHashUsingSHA3_256(fileName):
print("SHA3_256")
data=getData(fileName)
data=bytes(data,"utf-8")
start = timer()
h = SHA3_256.new()
h.update(data)
#Because this looks better when viewed instead of h.digest()
digest=h.hexdigest()
end = timer()
#print(digest)
print("Time Taken to generate Hash is ",(end-start))
print("Time Taken to Hash per byte is ",(end-start)/len(data))
generateFiles()
generateHashUsingSHA256("kbfile.txt")
generateHashUsingSHA256("mbfile.txt")
generateHashUsingSHA512("kbfile.txt")
generateHashUsingSHA512("mbfile.txt")
generateHashUsingSHA3_256("kbfile.txt")
generateHashUsingSHA3_256("mbfile.txt")
|
da7d64f8af6bfea5b017a19124438d56585fcffe | magicyu90/LeetCode | /easy/array/baseBallGame.py | 1,375 | 3.65625 | 4 | # coding :utf-8
class Solution:
"""
682. Baseball Game
You're now a baseball game point recorder.
Given a list of strings, each string can be one of the 4 following types:
Integer (one round's score): Directly represents the number of points you get in this round.
"+" (one round's score): Represents that the points you get in this round are the sum of the last two valid round's points.
"D" (one round's score): Represents that the points you get in this round are the doubled data of the last valid round's points.
"C" (an operation, which isn't a round's score): Represents the last valid round's points you get were invalid and should be removed.
Each round's operation is permanent and could have an impact on the round before and the round after.
You need to return the sum of the points you could get in all the rounds.
"""
def calPoints(self, ops):
"""
:type ops: List[str]
:rtype: int
"""
ans = []
for step in ops:
if step == "C":
ans.pop()
elif step == "D":
ans.append(ans[-1] * 2)
elif step == "+":
ans.append(ans[-1] + ans[-2])
else:
ans.append(int(step))
return sum(ans)
solution = Solution()
solution.calPoints(["5", "2", "C", "D", "+"])
|
f72cc738ae70bbcb1bf0003f01500ed0405b8369 | meena29/Python_Assignments | /arrays/maxsum_subarray.py | 903 | 3.875 | 4 | # Given an array of integers, find the contiguous subarray with the maximum sum. The array can contain both negative and positive integers.
def maxsum_subarray(arr):
maxSum = 0
currMax = 0
#start and end holds the maxSum subarray
start = 0
end = 0
#begin is for current traversal
begin = 0
for i in range(0,len(arr)):
currMax = currMax + arr[i];
#reset the values if curr max sum hits negative
if currMax < 0:
currMax = 0
begin = i + 1
#update if a new higher sum is found
if (maxSum < currMax):
maxSum = currMax
start = begin
end = i
if(maxSum == 0):
maxSum = sum(arr[start:end+1])
print(maxSum)
print(arr[start:end+1])
arr = [-2,1,-3,4,-1,2,1,-5,4]
arr1 = [8,-7,-3,5,6,-2,3,-4,2]
arr2 = []
arr3 = [-1,-2,-3]
arr4 = [-1,0,1]
maxsum_subarray(arr)
maxsum_subarray(arr1)
maxsum_subarray(arr2)
maxsum_subarray(arr3)
maxsum_subarray(arr4)
|
b1aba086196f9f0de02d22e5b6395d8770a1d1c2 | yashjaiswal1/CTCI-DSA | /ds/stacks-and-queues/priorityQueueUsingLinkedLists.py | 1,612 | 3.953125 | 4 | from typing import Sized
class Item:
def __init__(self, priority, data):
self.priority = priority
self.data = data
self.next = None
class PriorityQueue:
def __init__(self):
self.header_node = None
def enqueue(self, item):
if self.header_node == None:
self.header_node = item
else:
current = self.header_node
last = Item(None, None)
while current != None:
if current.priority < item.priority:
last.next = item
item.next = current
if current == self.header_node:
self.header_node = item
return
last = current
current = current.next
last.next = item
def dequeue(self):
if self.header_node == None:
print("Priority Queue is empty!")
else:
temp = self.header_node
self.header_node = self.header_node.next
return temp.data
def printQueue(self):
current = self.header_node
while current != None:
print(current.data)
current = current.next
pq = PriorityQueue()
pq.dequeue()
pq.enqueue(Item(10, 10))
pq.enqueue(Item(20, 20))
pq.enqueue(Item(30, 30))
pq.enqueue(Item(15, 15))
pq.enqueue(Item(0, 0))
pq.printQueue()
print("Popped = ", pq.dequeue())
print("Popped = ", pq.dequeue())
print("Popped = ", pq.dequeue())
pq.printQueue()
print("Popped = ", pq.dequeue())
print("Popped = ", pq.dequeue())
print("Popped = ", pq.dequeue())
|
e2db3823e910dc4bc452fb2e363d499e9359c5fd | yangjingScarlett/pythonlearning | /a_basicPython/3datatypes/number.py | 1,178 | 3.8125 | 4 | # coding=utf-8
import math
import random
# create a object whose type is number
num_var1 = 13
num_var2 = 0
# delete number objects
del num_var1, num_var2
# number has four different types: create int, long integers, float, complex
int_var = -13
long_int_var = 13L
float_var = 13.24
complex_var = 3.14j
print "========== Math Functions =========="
print "abs(%d) = %d" % (int_var, abs(int_var))
print "math.ceil(%f) = %d" % (float_var, math.ceil(float_var))
print "math.cmp(%d, %f) = %d" % (int_var, float_var, cmp(int_var, float_var))
print "exp(1) = %f" % math.exp(1)
print "math.fmod(%f, 2) = %d" % (float_var, math.fmod(float_var, 2))
print "pow(2, 3) = %d" % pow(2, 3)
print "round(%f) = %f" % (float_var, round(float_var))
print "math.sqrt(16) = %f" % math.sqrt(16)
print "\r"
print "========== Random Functions =========="
print "random.choice(range(1,10)) = ", random.choice(range(1, 10))
print "random.random() = ", random.random()
print "random.randrange(0, 100, 2) = ", random.randrange(0, 100, 2)
print "random.uniform(0, 100) = ", random.uniform(0, 100)
print "\r"
print "========== Constants =========="
print "math.e = ", math.e
print "math.pi = ", math.pi
|
60d67202707b434c96bcc28e0da14cf90b57418e | lteu/alg | /dp/editdist.py | 1,012 | 3.625 | 4 | import numpy as np
# Edit Distance 3.3
# https://www.geeksforgeeks.org/dynamic-programming-set-5-edit-distance/
# Given two strings str1 and str2 and below operations that can performed on str1.
# Insert
# Remove
# Replace
# 1
# str1 = "geek"
# str2 = "gesek"
# 1
# str1 = "cat"
# str2 = "cut"
# 3
str1 = "sunday"
str2 = "saturday"
R = [[0 for j in range(len(str2))] for i in range(len(str1))]
# initialize
R[0][0] = 0 if str1[0] == str2[0] else 1
for i in range(1,len(str2)):
score = 0 if str1[0] == str2[i] else 1
score_in = R[0][i-1] + score
score_out = R[0][i-1] + 1
R[0][i] = min(score_in,score_out)
for i in range(1,len(str1)):
score = 0 if str1[0] == str2[i] else 1
score_in = R[i-1][0] + score
score_out = R[i-1][0] + 1
R[i][0] = min(score_in,score_out)
# calculate
for i in range(1,len(str1)):
for j in range(1,len(str2)):
score = 0 if str1[i] == str2[j] else 1
score_in = R[i-1][j-1] + score
R[i][j] = min(R[i][j-1]+1,R[i-1][j]+1,score_in)
print(np.matrix(R))
print R[-1][-1]
|
319d6c1c5232d01e895666835550c1b5e0baf054 | xzf199358/Leetcode-practice | /04两个排序数组的中位数.py | 972 | 3.921875 | 4 | #codding=UTF-8
'''
题目: 给定两个大小为m 和n 的 有序数组nums1和nums2 请找出两个有序数组的中位数
示例:nums1 = [1,3]
nums2 = [2]
中位数是2
示例: nums1 = [1,2]
nums2 = [3,4]
中位数是2.5
'''
'''
本题目的解法 可看做就是寻找中位数 因此需要将两个有序数组进行合并 并进行重新排序
重新排序之后 在进行中位数的寻找
'''
class solution:
def __init__(self,nums1,nums2):
self.nums1 = nums1
self.nums2 = nums2
def findmediansortedArrays(self):
a = []
a.extend(self.nums1)
a.extend(self.nums2)
a = sorted(a)
length = len(a)
if length % 2 == 0:
num = int(length / 2)
return (a[num] + a[num+1])/2
else:
num = int(length/2)
return a[num]
n1 = [1,2,3,4]
n2 = [5,6,7,8]
medianelement = solution(n1,n2)
print(medianelement.findmediansortedArrays())
|
529f2e0220752b389e1ea726642e0cd4c78ebf56 | TheDycik/algPy | /les1/les_1_task_5.py | 289 | 3.984375 | 4 | # 5. Пользователь вводит номер буквы в алфавите. Определить, какая это буква.
n = int(input("Введите номер буквы: "))
n = ord("a") + n - 1
print("Этот номер пренадлежит букве: ", chr(n)) |
18cda87023f634d62cf76ce538f9d57bdccfb490 | tylerkuper11/ICS2019_2020 | /Assignment05_HiLo/Program.py | 475 | 3.8125 | 4 | import random
print("Welcome. I will give you a random number between 1 and 100 and your job is to guess it.\nPlease use only integers.")
randnum = random.randint(1,100)
def hiLo(n):
if n == True:
return
if n == False:
g =int(input("What's your guess?"))
if g < randnum:
print("Too low.")
hiLo(False)
if g > randnum:
print("Too high.")
hiLo(False)
if g == randnum:
print("Congratulations! You got it!")
hiLo(True)
hiLo(False)
print("Done")
|
76c10438a341764037038a4c668216d972483b9e | cool-RR/python_toolbox | /python_toolbox/binary_search/functions.py | 7,190 | 3.921875 | 4 | # Copyright 2009-2017 Ram Rachum.
# This program is distributed under the MIT license.
'''Module for doing a binary search in a sequence.'''
# Todo: wrap all things in tuples?
#
# todo: add option to specify `cmp`.
#
# todo: i think `binary_search_by_index` should have the core logic, and the
# other one will use it. I think this will save many sequence accesses, and
# some sequences can be expensive.
#
# todo: ensure there are no `if variable` checks where we're thinking of None
# but the variable might be False
from python_toolbox import misc_tools
from .roundings import (Rounding, roundings, LOW, LOW_IF_BOTH,
LOW_OTHERWISE_HIGH, HIGH, HIGH_IF_BOTH,
HIGH_OTHERWISE_LOW, EXACT, CLOSEST, CLOSEST_IF_BOTH,
BOTH)
def binary_search_by_index(sequence, value,
function=misc_tools.identity_function,
rounding=CLOSEST):
'''
Do a binary search, returning answer as index number.
For all rounding options, a return value of None is returned if no matching
item is found. (In the case of `rounding=BOTH`, either of the items in the
tuple may be `None`)
You may optionally pass a key function as `function`, so instead of the
objects in `sequence` being compared, their outputs from `function` will be
compared. If you do pass in a function, it's assumed that it's strictly
rising.
Note: This function uses `None` to express its inability to find any
matches; therefore, you better not use it on sequences in which None is a
possible item.
Similiar to `binary_search` (refer to its documentation for more info). The
difference is that instead of returning a result in terms of sequence
items, it returns the indexes of these items in the sequence.
For documentation of rounding options, check `binary_search.roundings`.
'''
my_range = range(len(sequence))
fixed_function = lambda index: function(sequence[index])
result = binary_search(my_range, value, function=fixed_function,
rounding=rounding)
return result
def _binary_search_both(sequence, value,
function=misc_tools.identity_function):
'''
Do a binary search through a sequence with the `BOTH` rounding.
You may optionally pass a key function as `function`, so instead of the
objects in `sequence` being compared, their outputs from `function` will be
compared. If you do pass in a function, it's assumed that it's strictly
rising.
Note: This function uses `None` to express its inability to find any
matches; therefore, you better not use it on sequences in which `None` is a
possible item.
'''
# todo: i think this should be changed to return tuples
### Preparing: ############################################################
# #
get = lambda number: function(sequence[number])
low = 0
high = len(sequence) - 1
# #
### Finished preparing. ###################################################
### Handling edge cases: ##################################################
# #
if not sequence:
return (None, None)
low_value, high_value = get(low), get(high)
if value in (low_value, high_value):
return tuple((value, value))
elif low_value > value:
return tuple((None, sequence[low]))
elif high_value < value:
return (sequence[high], None)
# #
### Finished handling edge cases. #########################################
# Now we know the value is somewhere inside the sequence.
assert low_value < value < high_value
while high - low > 1:
medium = (low + high) // 2
medium_value = get(medium)
if medium_value > value:
high, high_value = medium, medium_value
continue
if medium_value < value:
low, low_value = medium, medium_value
continue
if medium_value == value:
return (sequence[medium], sequence[medium])
return (sequence[low], sequence[high])
def binary_search(sequence, value, function=misc_tools.identity_function,
rounding=CLOSEST):
'''
Do a binary search through a sequence.
For all rounding options, a return value of None is returned if no matching
item is found. (In the case of `rounding=BOTH`, either of the items in the
tuple may be `None`)
You may optionally pass a key function as `function`, so instead of the
objects in `sequence` being compared, their outputs from `function` will be
compared. If you do pass in a function, it's assumed that it's strictly
rising.
Note: This function uses `None` to express its inability to find any
matches; therefore, you better not use it on sequences in which None is a
possible item.
For documentation of rounding options, check `binary_search.roundings`.
'''
from .binary_search_profile import BinarySearchProfile
binary_search_profile = BinarySearchProfile(sequence, value,
function=function)
return binary_search_profile.results[rounding]
def make_both_data_into_preferred_rounding(
both, value, function=misc_tools.identity_function, rounding=BOTH):
'''
Convert results gotten using `BOTH` to a different rounding option.
This function takes the return value from `binary_search` (or other such
functions) with `rounding=BOTH` as the parameter `both`. It then gives the
data with a different rounding, specified with the parameter `rounding`.
'''
# todo optimize and organize: break to individual functions, put in
# `BinarySearchProfile`
if rounding is BOTH:
return both
elif rounding is LOW:
return both[0]
elif rounding is LOW_IF_BOTH:
return both[0] if both[1] is not None else None
elif rounding is LOW_OTHERWISE_HIGH:
return both[0] if both[0] is not None else both[1]
elif rounding is HIGH:
return both[1]
elif rounding is HIGH_IF_BOTH:
return both[1] if both[0] is not None else None
elif rounding is HIGH_OTHERWISE_LOW:
return both[1] if both[1] is not None else both[0]
elif rounding is EXACT:
results = [item for item in both if
(item is not None and function(item) == value)]
return results[0] if results else None
elif rounding in (CLOSEST, CLOSEST_IF_BOTH):
if rounding is CLOSEST_IF_BOTH:
if None in both:
return None
if both[0] is None: return both[1]
if both[1] is None: return both[0]
distances = [abs(function(item)-value) for item in both]
if distances[0] <= distances[1]:
return both[0]
else:
return both[1]
|
7b040d19220030647c8445f96814c8dc9fcd2495 | Quinton-10/Finance_Calculator | /Finance_calculater.py | 2,307 | 4.3125 | 4 | #Import math for math problems
import math
#Print user must choose investment or bond and print explenation of both
print("Choose either 'investment' or 'bond' from the menu below to proceed:")
print("\ninvestment -to calculate the amount of interest you'll earn on interest.")
print("bond -to calculate the amount you'll have to pay on a home loan.")
#User input investment or bond
finance=input("\nPlease enter your option 'investment' or 'bond': ")
#If user input is investment ask user to input amount of money the will invest, interest rate, years they are planning on investing and if they want simple or compouned interst
#If user input simple or compound use given formula and print total interest
#if user does not input valid input then print error message
if finance == "investment":
deposit = int(input("\nPlease enter the amount of money you are depositing: "))
rate= int(input("Please enter the iterest rate (as a persentage): "))
years= int(input("Please enter the number of year you are planning on investing: "))
interest=input("Please enter if you want simple or compound interest(enter 'simple' or 'compound'): ")
rate= rate/100
if interest == "simple":
investment=round(deposit * (1 + rate * years),2)
print(f"\nYour total interest is {investment}!")
elif interest== "compound":
investment=round(deposit * math.pow(1 + rate,years),2)
print(f"\nYour total interest is {investment}!")
else:
print("\nERROR not a valid option")
#if user input "bond" ask user to input the value of their house, interest rate and total months the are going to repay
#use given formula to wokrout total interest repayment and print the total interest repayment amount
#if user input not valid print error message
elif finance == "bond":
value=int(input("\nPlease enter the present value of your house: "))
rate=int(input("Please enter the interest rate: "))
months=int(input("Please enter the number of months you plan on repaying the bond: "))
rate= rate/12
bond=round((rate*value)/(1 - (1+rate)**(-months)),2)
print(f"\nYour total interest repayment on your bond is {bond}.")
else:
print("\nERROR not a valid option")
|
e85e6eee3225913b9a9fa84460b0b9abba1f5004 | Yumingyuan/algorithm_lab | /polygon_divide.py | 2,022 | 3.546875 | 4 | # -*- coding: utf-8 -*-
#构造最优解
def print_solution(i,j,optim_k):#打印i->k->j三角形
if i+1==j:#如果不能形成三角形则返回
return
else:
print("(V"+str(i+1)+"V"+str(optim_k[i][j]+1)+"V"+str(j+1)+")",end='')
print_solution(i,optim_k[i][j],optim_k)#递归多边形打印(Vi->Voptim_k[i][j])
print_solution(optim_k[i][j],j,optim_k)#递归打印(Voptim_k[i][j]->Vj)
#计算并返回三角形周长(i,j,k这三个点形成的)
def triangle(edge_data,i,j,k):
#print("i",i,"j",j,"k",k)
#print("triangle",edge_data[i][k],edge_data[k][j],edge_data[i][j])
return edge_data[i][k]+edge_data[k][j]+edge_data[i][j]
#最优值计算函数
def calc_optimal(edge_data,edges_num):
distance=[[0 for i in range(edges_num)] for j in range(edges_num)]#最优子权重
optim_k=[[0 for i in range(edges_num)] for j in range(edges_num)]#最优的分割点
for m in range(1,edges_num):#问题规模
for i in range(0,edges_num-m):
j=i+m
#print("i:",i,"j:",j,"m:",m)
min_num=65535
min_k=0
#print("distance:",distance)
for k in range(i+1,j):#k是断开位置从i+1到j-1
#print("distance[i][k]:",distance[i][k],"distance[k][j]",distance[k][j],"triangle(i,j,k)",triangle(edge_data,i,j,k),i,j,k)
#print("triangle",edge_data[i][k],edge_data[k][j],edge_data[i][j],i,j,k)
if min_num>distance[i][k]+distance[k][j]+triangle(edge_data,i,j,k):
min_num=distance[i][k]+distance[k][j]+triangle(edge_data,i,j,k)
min_k=k
distance[i][j]=min_num
#print("update dis",distance)
optim_k[i][j]=min_k
#print("update optimum",optim_k)
print("optimum weight:",distance[0][edges_num-1])
print("optimal divide solution:",end='')
print_solution(0,7,optim_k)#构造最优结果函数调用
if __name__=="__main__":
edge_data=[[0,14,25,27,10,11,24,16],
[0,0,18,15,27,28,16,14],
[0,0,0,19,14,19,16,10],
[0,0,0,0,22,23,15,14],
[0,0,0,0,0,14,13,20],
[0,0,0,0,0,0,15,18],
[0,0,0,0,0,0,0,27],
[0,0,0,0,0,0,0,0]]#上三角形
edges=8#八边形
calc_optimal(edge_data,edges)
|
cac8f966ff1fe78313c333f5ee95c3fcfcce6ac8 | bluerubic/pythonScripts | /anagrams.py | 2,039 | 4.4375 | 4 | #!/usr/bin/python
'''Python Program to find all the anagrams in a file on disk with one line per word.
Example input:
python anagram.py <filename.txt>
Example output:
[emit, item, mite, time]
[merit, miter, mitre, remit, timer]
'''
import argparse
from argparse import RawTextHelpFormatter
import os
import os.path
def findAnagrams(inputFile):
from collections import defaultdict
sortedTuple = []
result = defaultdict(set)
if os.path.exists(inputFile):
with open(inputFile, 'r') as fobj:
#Strip the '\n' at the end of each line and store the words as a list
words = [word.rstrip() for word in fobj.readlines()]
#For each word in the above list, create a list of tuples as (X,Y)
#where X = word and Y = the word sorted alphabetically
for word in words:
sortedTuple.append((word, "".join(sorted([char for char in word]))))
#Sort the list of tuples based on the second parameter i.e the alphabetically sorted word
#All words that are anagrams would appear next to each other
sortedTuple.sort(key=lambda x: x[1])
for word, sortedWord in sortedTuple:
result[sortedWord].add(word)
#Group the anagrams found and store them in a set ( to remove duplicate entries)
print "Anagrams found:"
for k, values in result.items():
print "{0}".format(list(values))
else:
print "File not found"
def main():
parser = argparse.ArgumentParser(description='''Program to find anagrams in a file
Input: <Filename>
Output: List of anagrams found in the file ''', formatter_class=RawTextHelpFormatter)
parser.add_argument('-f', '--file', type=str, help='Filename to search for anagrams', required=True )
args = parser.parse_args()
print findAnagrams(args.file)
if __name__ == "__main__":
main()
|
fe70a733c4cc6d914c730fa221d1ce21ecf92c31 | akimi-yano/algorithm-practice | /lc/714.BestTimeToBuyAndSellStockw.py | 1,556 | 3.859375 | 4 | # 714. Best Time to Buy and Sell Stock with Transaction Fee
# Medium
# 2311
# 69
# Add to List
# Share
# You are given an array prices where prices[i] is the price of a given stock on the ith day, and an integer fee representing a transaction fee.
# Find the maximum profit you can achieve. You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction.
# Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
# Example 1:
# Input: prices = [1,3,2,8,4,9], fee = 2
# Output: 8
# Explanation: The maximum profit can be achieved by:
# - Buying at prices[0] = 1
# - Selling at prices[3] = 8
# - Buying at prices[4] = 4
# - Selling at prices[5] = 9
# The total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8.
# Example 2:
# Input: prices = [1,3,7,5,10,3], fee = 3
# Output: 6
# Constraints:
# 1 < prices.length <= 5 * 104
# 0 < prices[i], fee < 5 * 104
# This solution works:
class Solution:
def maxProfit(self, prices: List[int], fee: int) -> int:
@lru_cache(None)
def helper(i, can_buy):
if i > len(prices)-1:
return 0
if can_buy:
# buy vs not buy
return max(-prices[i] + helper(i+1, False), helper(i+1, True))
else:
# sell vs not sell
return max(prices[i]-fee + helper(i+1, True),helper(i+1, False))
return helper(0, True)
|
2bb3a9b4b3725590a016d7e15ebe4706879e9065 | MUSKANJASSAL/PythonTraining2019 | /Session5B.py | 526 | 4.125 | 4 | # String Formatting
name = "Fionna"
age = 31
print("Welcome to our club %s"%(name))
print("Your age is %d"%(age))
print("Hey. %s You are %d years old"%(name, age))
print("Hey",name,"You are",age,"years old")
print("Hey" +name)
print("Hey " +name)
print("Hey, {} You are {} years old".format(name, age))
# Table of a number
num = int(input("Enter a number:"))
for i in range(1,11):
print("{} * {} = {}".format(num, i, (num*i)))
number = 7
for i in range(1, 11):
print("{} {}'s are {}".format(number, i, number*i)) |
207d11c46caa0e5de02ef2ef6e9f7a1342bb22f7 | Uche-Clare/python-challenge-solutions | /neoOkpara/Phase-1/Day7/sumNumbers.py | 158 | 3.734375 | 4 | def sum_of_n_numbers(num):
full_sum = 0
for i in range(1, num + 1):
full_sum = full_sum + i
return full_sum
print (sum_of_n_numbers(5))
|
8a1d3472c1ad4f9dca9956f75696b48a25ba3bd3 | jasonlingo/RoadSafety | /Database/InsertHospitalData.py | 2,429 | 3.5625 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
@author: Jason, Li-Yi Lin
"""
import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
import sqlite3 as lite
from zipfile import ZipFile
def ParseHospital(filename):
"""
Parse hospitals' information from a kmz file produced
by "Google My MAP" service. Extract hospitals' name and
GPS location.
Args:
(String) filename: the file name of a kmz file.
Return:
(dictionary) hospitals: a linked list of GPS points.
"""
# Open kmz file.
kmz = ZipFile(filename, 'r')
# Open the kml file in a kmz file.
kml = kmz.open('doc.kml','r')
# Extract names and coordinates from the kmz file.
hospitals = {}
name = None
coordinates = None
start = False # True: start to record the information of hospitals.
for i, x in enumerate(kml):
if "<Placemark>" in x:
start = True
if start:
if "<name>" in x:
name = x.replace("<name>", "").replace("</name>", "").replace("\t","").replace("\n","")
if "<coordinates>" in x:
[lng, lat, _] = x.replace("<coordinates>","").replace("</coordinates>","").replace("\t","").replace("\n","").split(",")
coordinates = (float(lat), float(lng))
if "</Placemark>" in x:
hospitals[name] = coordinates
start = False
return hospitals
def InsertHospitalData(filename, DB):
"""
Extract hospitals' information and then store it in a database.
Args:
(String) filename: the file name of a kmz file that stores
the information of hospitals.
(String) DB: the file name of the target database.
"""
# Connect DB.
conn = lite.connect(DB)
c = conn.cursor()
# Delete all the old data.
c.execute('delete from Hospital')
# Parse kmz file and get hospitals' information.
hospitals = ParseHospital(filename)
# Insert data into database.
i = 1 # The counter for hospital id.
for hos in hospitals:
(lat, lng) = hospitals[hos]
command = '''
insert into Hospital values(%d, "%s", %f, %f)
''' % (i, hos, lat, lng)
print command
c.execute(command)
i += 1
conn.commit()
conn.close()
# Start the process.
InsertHospitalData("Data/Hospital.kmz", "Database/taxi_ems.db")
|
b706ea78e42e35f3bd3d3ffc59c2253d490801a1 | AmonMcDuul/ProjectEuler | /euler9.py | 400 | 4.0625 | 4 | #A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
#a2 + b2 = c2
#For example, 32 + 42 = 9 + 16 = 25 = 52.
#There exists exactly one Pythagorean triplet for which a + b + c = 1000.
#Find the product abc.
nummer = 1000
for a in range(int(nummer/2)):
for b in range(a+1,(int(nummer/2))):
c=nummer-(a+b)
if a**2+b**2==c**2:
print(a * b * c) |
2259634738c2bbfeffdccda8464274622a2c418f | saad-ahmed/Udacity-CS-101--Building-a-Search-Engine | /unit_2_25-factorial.py | 287 | 4 | 4 | #Define a procedure, factorial, that
#takes one number as its input
#and returns the factorial of
#that number.
def factorial(k):
i = 1
fact = 1
while i<k:
n = k * (k - 1)
k = k-2
fact = n * fact
return fact
print factorial(4)
print factorial(5) |
de610132460295e17b7e3fe58b8ea836943891f2 | sernst/airplane_boarding | /boarding/ops/queue/grouping.py | 3,041 | 3.5 | 4 | import math
import random
import typing
import pandas as pd
def chunks(
settings: dict,
passengers: pd.DataFrame,
queue: pd.DataFrame
) -> typing.List[typing.Tuple[int]]:
"""
Creates a list of start and end aisle pairings for the population groups as
specified in the configuration settings
:param settings:
:param passengers:
:param queue:
:return:
"""
group_count = settings['populate']['groups']
aisle_count = queue['aisle'].max() + 1
out = []
if group_count < 2:
out.append((0, passengers.shape[0]))
return out
for index in range(group_count):
delta = math.floor(aisle_count / group_count)
start_aisle = index * delta
end_aisle = max(
start_aisle + 1,
(index + 1) * delta
)
if index == (group_count - 1):
end_aisle = aisle_count
out.append((start_aisle, end_aisle))
return out
def order_by(
groups: typing.List,
order_type: typing.Union[str, list, tuple],
default_type: str = None
) -> typing.List:
"""
Orders a list of groups by the specified order type, or the default type if
the order type is 'DEFAULT' or unrecognized
:param groups:
A list of aisle or passenger index groups to sort by the specified
order
:param order_type:
The enumerated order type, such as 'RANDOM', 'FORWARD', or 'BACKWARD'
:param default_type:
A default order type to use if the order_type is 'DEFAULT' or the
order type is not recognized
:return:
The list of groups that has been sorted
"""
order_type = order_type.upper()
if isinstance(order_type, (list, tuple)):
ordering = [order_type.index(x + 1) for x in range(len(groups))]
return [x for (y, x) in sorted(zip(ordering, groups))]
if order_type == 'BACKWARD':
groups.reverse()
return groups
if order_type == 'FORWARD':
return groups
if order_type == 'RANDOM':
random.shuffle(groups)
return groups
if default_type:
return order_by(groups, default_type)
raise ValueError(
'Invalid configuration setting populate.group_order of "{}"'.format(
order_type
)
)
def to_passenger_indexes(
aisle_groups: typing.List[typing.Tuple[int]],
passengers: pd.DataFrame
) -> typing.List[typing.List[int]]:
"""
Converts a list of aisle groups into a list of passenger index groups
:param aisle_groups:
A list of aisle start and aisle end indexes to be converted into
passenger indexes
:param passengers:
The passenger manifest data frame
:return:
A list of groups where each group contains a list of the passenger
indexes in that group
"""
out = []
for group in aisle_groups:
query = 'aisle >= {} and aisle < {}'.format(*group)
out.append(list(passengers.query(query).index))
return out
|
59ab9b2a37fe7409141f7b4395c5ca39a566304b | kinegratii/PySnippet | /projects/py_pack/tk_demo.py | 659 | 4 | 4 | #coding=utf-8
"""
简单的tkGUI程序
Note:只在python2下有效
"""
from Tkinter import *
import tkMessageBox
class ConfigWindow(Frame):
def __init__(self, ):
Frame.__init__(self)
self.master.title('Tk Demo')
self.master.geometry('500x300')
self.master.resizable(False, False)
self.pack(side = TOP,expand = YES,fill = BOTH)
bt = Button(self,text='hello',command=self.hello)
bt.pack(side=TOP,expand=NO,fill=Y,pady=20,padx=20)
def hello(self):
tkMessageBox.showinfo('Info','Hello,This is a demo for tkinter');
if __name__ == '__main__':
ConfigWindow().mainloop()
|
b5044cc8ed1fb2542fc8a4b9003254d6f7a82455 | anubhav-shukla/Learnpyhton | /list_vs_gen.py | 406 | 3.921875 | 4 | import time
# list vs generator
# memory usage , time
# when to use list , when to use generator
# list
t1=time.time()
l=[i**2 for i in range(10000000)] #10 million #it uses near 400 mb
print(f"{time.time()-t1} second")
# generator
t2=time.time()
g = (i**2 for i in range(10000000)) #10 million #too less time
print(f"{time.time()-t2} second")
# see the differnce
# hope it clear
|
9ae7822f3d90633db317c75405dce60a79f899df | AdrianMulawka/Udemy-Course | /savings.py | 506 | 4.1875 | 4 | #This program will help you calculate how much money you will save depending on the amount of funds deposited, the interest rate of the deposit and time.
initialCapital = 20000
interest = 0.03
maxTimeYear = 10
capital = initialCapital
i = 0
for i in range(i, maxTimeYear):
capital = round((1 + interest) * capital, 2)
print("In % s year you saved %s money" % (i, capital))
i+=1
yourSavedMoney = capital-initialCapital
print("By 10 years economize you saved %s money " % (yourSavedMoney))
|
3cc4052ab4a6c8e61dee7025b2ec83bbbea0fe40 | awshx/blind_people | /pts_communs.py | 6,467 | 3.65625 | 4 | import cv2
import numpy as np
import matplotlib.pyplot as plt
def my_function():
print("Hello from a function")
#cropImageLeft
#Desc : return an img of the top left of an img
#Params :
# img : picture (from a cv.imread(...) )
#Return :
# croppedImg : picture of the top left of the img in param
def cropImageLeft(img):
#height of the cropped picture
#we take the height of the param img and we divide by 2
heightCropped = int(np.size(img, 0)/2)
#width of the cropped picture
#we take the width of the param img and we divide by 3
widthCropped = int(np.size(img, 1)/3)
#we crop the img at the top left
#(0,0) is the top left of the picture in opencv
#we cut the param img from (0,0) to (height,width)
croppedImg = img[0:0+heightCropped, 0:0+widthCropped]
return(croppedImg)
#cropImageRight
#Desc : return an img of the top right of an img
#Params :
# img : picture (from a cv.imread(...) )
#Return :
# croppedImg : picture of the top right of the img in param
def cropImageRight(img):
#height of the cropped picture
#we take the height of the param img and we divide by 2
heightCropped = int(np.size(img, 0)/2)
#width of the cropped picture
#we take the width of the param img and we divide by 3
widthCropped = int(np.size(img, 1)/3)
#we crop the img at the top left
#(0,0) is the top right of the picture in opencv
#we cut the param img from (0, 2*widthCropped) (half of the img) to ()
croppedImg = img[0:0+heightCropped, widthCropped*2:widthCropped*3]
return(croppedImg)
#CompareLogo
#Desc : Compare a picture to another (logo) and return the number of matches
#Params :
# img: cropped image of the street where a logo can be
# imgLogo: image of a logo
#Return :
# number of matches
def compareLogo(img, imgLogo):
#We take keypoints and descriptor of the picture
kp1, des1 = sift.detectAndCompute(img, None)
#We take keypoints and descriptor of the logo
kp2, des2 = sift.detectAndCompute(imgLogo, None)
# BFMatcher with default params
# It's the tool to have matches
bf = cv.BFMatcher()
#We take the matches
matches = bf.knnMatch(des1,des2,k=2)
#Array to stock the best matches
good = []
for m,n in matches:
# Apply ratio test to select the best matches
if m.distance < 0.75*n.distance:
good.append([m])
#We return the number of good matches
return(len(good))
#lengthLetter
#Desc : Calculate approximatively the length of a word in pixels to show the label of the logo
# It can be a word or a sentence
#Param :
# word : a word in string
#Return
# wordLength : the number of pixel corresponding to the length of the label
def lenghtLetter(word):
#Length of the word
wordLength = 0
#Length of a standard letter (low case and not a double letter like m or w)
lenghtLetter = 17
#We cut the word into a list of letters
letters = list(word)
#for every letter of the word
for letter in letters:
#We check if it's a 'm' or a 'w'
if (letter == 'm' or letter == 'w' or letter == 'M' or letter == 'W'):
#If so, we increase the length even more than if it was a standard letter
wordLength = wordLength + 5
#If the letter is in uppercase
if (letter.isupper()):
#we increase the length even more than if it was a standard letter
wordLength = wordLength + 3
#We increase the length of the word each at each letter
wordLength = wordLength + lenghtLetter
#We return the final number corresponding to the length of the word
return wordLength
def coef(number, scale):
return (scale * number)
#label
#Desc : put a label on the picture to the indicated coordonate
#Params :
# img : picture (from a cv.imread(...) )
# labelName : name of the label, a string of characters
# coord : coordinate where we want to put the labe
# the coordinate correspond to the bottom left of the label
# the coordinate have to be in a tuple: (x,y)
#Return: nothing, the label is put directly on the img of param
def label(img, labelName, coord):
sizeLetter=2
#We extract the coordinates
x,y = coord
xPosition=x-150
yPosition=y-150
#Number of letter of the name
nbLetter = len(labelName)
#length in pixels of the label
lengthLabel = lenghtLetter(labelName)
#Coordinates of the letters
xRect1 = int(xPosition-coef(lengthLabel/2,sizeLetter))
#print("xRect1")
#print(xRect1)
yRect1 = int(yPosition+coef(20,sizeLetter))
#print("yRect1")
#print(yRect1)
xRect2 = int(xPosition+coef(lengthLabel/2,sizeLetter))
#print("xRect2")
#print(xRect2)
yRect2 = int(yPosition-coef(13,sizeLetter))
#print("yRect2")
#print(yRect2)
#image's width
heightImg = (np.size(img, 0))
#image's height
widthImg = (np.size(img, 1))
#width of the rectangle
widthRect = abs(xRect2 - xRect1)
#height of the rectangle
heightRect = abs(yRect1 - yRect2)
#We calculate the margin needed to create the frame
marginRect = coef(3,sizeLetter)
#All the cases
if(xRect1 < 0):
#print("oui1")
xRect1 = 0
xRect2 = xRect1 + widthRect
if (xRect2 > widthImg):
#print("oui2")
xRect2 = widthImg
xRect1 = int(xRect2-widthRect)
if(yRect2 < 0):
#print("oui3")
yRect2 = 0
yRect1 = int(yRect2 + heightRect)
if(yRect1 > heightImg):
#print("oui4")
yRect1 = heightImg
yRect2 = int(yRect1 - heightRect)
#Coordinate of the labels
xLabel = xRect1
yLabel = yRect1 - 8
#We create the location of the (red) frame
xFrame1 = xRect1-marginRect
yFrame1 = yRect1+marginRect
xFrame2 = xRect2+marginRect
yFrame2 = yRect2-marginRect
#We draw the white rectangle at the coordinate of the label
cv2.rectangle(img, (xRect1,yRect1), (xRect2, yRect2), (0,0,0), thickness=-1, lineType=8, shift=0)
#We draw the red frame
cv2.rectangle(img, (xFrame1,yFrame1), (xFrame2, yFrame2), (255,255,255), thickness=3, lineType=8, shift=0)
cv2.line(img, (x,y), (xRect2, yRect2+30), (0,0,0), thickness=3, lineType=8, shift=0)
#params of the label's text
font = cv2.FONT_HERSHEY_SIMPLEX
bottomLeftCornerOfText = (xLabel, yLabel)
fontScale = sizeLetter
fontColor = (255,255,255)
lineType = 2
#We put the text on the white rectangle
cv2.putText(img, labelName,
bottomLeftCornerOfText,
font,
fontScale,
fontColor,
lineType)
|
c0d4172e1dbd0128c405eb2db40f267fbe6319b8 | erickclasen/PMLC | /lin-reg-basic/multivariate_lr.py | 4,947 | 3.921875 | 4 | import numpy as np
def normalize(features):
'''
features - (10, 3)
features.T - (3, 10)
We transpose the input matrix, swapping
cols and rows to make vector math easier
'''
for feature in features.T:
fmean = np.mean(feature)
frange = np.amax(feature) - np.amin(feature)
#Vector Subtraction
feature -= fmean
#Vector Division
feature /= frange
return features
''' This is just here to see how it would work, an experiment. '''
def de_normalize(targets,train_targets):
'''
features - (10, 3)
features.T - (3, 10)
We transpose the input matrix, swapping
cols and rows to make vector math easier
To de-normalize we have to first normalize off the
targets that we trained with and then use the fmean and frange
to de-normalize to result targets to scale the predictor results.
'''
for train_targets in train_targets.T:
fmean = np.mean(train_targets)
frange = np.amax(train_targets) - np.amin(train_targets)
#Vector Multiplication First. Opposite order of normalization.
targets *= frange
#Vector Addition Second. Opposite order of normalization.
targets += fmean
return targets
def predict(features, weights):
'''
features - (10, 3)
weights - (3, 1)
predictions - (10,1)
'''
predictions = np.dot(features, weights)
return predictions
def update_weights_vectorized(X, targets, weights, lr):
'''
gradient = X.T * (predictions - targets) / N
X: (10, 3)
Targets: (10, 1)
Weights: (3, 1)
'''
N = len(X)
#1 - Get Predictions
predictions = predict(X, weights)
#2 - Calculate error/loss
error = targets - predictions
#3 Transpose features from (10, 3) to (3, 10)
# So we can multiply w the (10,1) error matrix.
# Returns a (3,1) matrix holding 3 partial derivatives --
# one for each feature -- representing the aggregate
# slope of the cost function across all observations
gradient = np.dot(-X.T, error)
#4 Take the average error derivative for each feature
gradient /= N
#5 - Multiply the gradient by our learning rate
gradient *= lr
#6 - Subtract from our weights to minimize cost
weights -= gradient
return weights
def cost_function(features, targets, weights):
'''
features:(10,3)
targets: (10,1)
weights:(3,1)
returns average squared error among predictions
'''
N = len(targets)
predictions = predict(features, weights)
# Matrix math lets use do this without looping
sq_error = (predictions - targets)**2
# Return average squared error among predictions
return 1.0/(2*N) * sq_error.sum()
''' Main Code '''
# Weights
W1 = 0.0
W2 = 0.0
W3 = 0.0
biasw = 0.0
# Convert to an array (no transpose)
weights = np.array([
[biasw],
[W1],
[W2],
[W3]
])
print("weights")
print(weights)
# Features as lists
x1 = [1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0]
x2 = [1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0]
x3 = [1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0]
#bias = [1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0]
#bias = [1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0]
# Convert features to array and transpose
features = np.array([
# bias,
x1,
x2,
x3
])
features = features.T
print("features")
print(features)
# Normalize the features to bring them into a -1 to 1 range,centered around the mean
#1 Subtract the mean of the column (mean normalization)
#2 Divide by the range of the column (feature scaling)
features = normalize(features)
# Put a bias of one into the first row of features. This will work with the biasw (weight) for a bias.
bias = np.ones(shape=(len(features),1))
features = np.append(bias, features, axis=1)
print("Normalized Features wih the bias column added.")
print(features)
# y is the target, must be the same length and shape as all the x's, so transpose it.
y = [1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0]
targets = np.array([
y
])
# Traspose the targets.
targets = targets.T
print("orig targets transposed")
print(targets)
# Set a learning rate
lr = 0.01
epochs = 2000
print("Start...")
# Epochs = loops. Run the update weights function over and over as long as needed for convergence.
# Occasionally, once per 1000 loops display the loss to get an idea how it is progressing.
for i in range(epochs):
#Run the weights update once to backpropigate.
update_weights_vectorized(features, targets, weights, lr)
if i%1000 ==0:
print("Iteration:",i)
print("Updated Weights")
print(weights)
print("cost:",cost_function(features, targets, weights))
print("")
print("...Done!")
# Run a prediction to show the results. The targets will still be in a normalized state.
predictions = predict(features, weights)
print("predictions",predictions)
print("error: targets - predictions",targets - predictions)
|
4e403624a90f323d18012966dbbfb5e80ac8904c | tsushiy/competitive-programming-submissions | /AtCoder/ABC/ABC001-050/abc023/abc023b.py | 224 | 3.640625 | 4 | n = int(input())
s = input()
t = "b"
if s==t:
print(0)
exit()
for i in range(1, n+1):
if i%3==1:
t = "a"+t+"c"
elif i%3==2:
t = "c"+t+"a"
else:
t = "b"+t+"b"
if s==t:
print(i)
exit()
print(-1) |
e6d5f3e2cd8e245cc8422689a4459bacccf4fb4b | wileyj/public-python | /z-re.py | 737 | 3.671875 | 4 | from operator import itemgetter
import re
class Solution(object):
def test_email(self, email):
try:
x=re.search('(\w+[.|\w])*@(\w+[.])*\w+[.][a-z].*',email)
return x.group()
except:
pass
list = [
"santa.banta@gmail.co.in",
"adsf@yahoo",
"bogusemail123@sillymail.com",
"santa.banta.manta@gmail.co.in",
"santa.banta.manta@gmail.co.in.xv.fg.gh",
"abc.dcf@ghj.org",
"santa.banta.manta@gmail.co.in.org",
"zzzzztop@email.com",
]
this = sorted(
list,
key=itemgetter(0,1),
reverse=True
)
for item in this:
# print item
if Solution().test_email(item):
print "%s is valid email" % (item)
else:
print "Invalid email: %s" % (item)
string = "atestz"
print string[0]
print string[-1]
print string[0:len(string)-1:]
|
5d5ab4ca1e6b5a0119ae8ac7a7ab0c64c1f92441 | python-programming-1/homework-3-awesome-k | /collatz.py | 458 | 4.34375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 16 21:04:45 2019
@author: awesome_k
"""
def collatz(num):
while num != 1:
if (num % 2 == 0):
num = num // 2
print (num)
elif (num % 2 == 1):
num = ((num * 3) +1)
print (num)
try:
print ('Enter an integer value ')
collatz(int(input()))
except:
print ('Re-enter an integer value only!') |
00c1fe6c002fafedfdbadd6455a2953f18a28fbf | yamscha/repo_class | /03-Python/2/Activities/05-Ins_BasicRead/ReadFile.py | 637 | 4.15625 | 4 | # Store the file path associated with the file (note the backslash may be OS specific)
file_name = 'Resources/input.txt'
# Open the file in "read" mode ('r') and store the contents in the variable "text"
with open(file_name, 'r') as file_object:
print("what is file_object var?")
print(file_object)
print("read all lines")
# Store all of the text inside a variable called "lines"
lines = file_object.read()
# Print the contents of the text file
print(lines)
print("\nread one line at a time\n")
with open("Resources/accounting.csv", 'r') as f:
for line in f.readlines():
print(line,end='')
|
df6add4cdc398907c53ce1482dc2abd7d2f711a6 | ejohnso9/programming | /AoC/2022/2022-04.py | 3,162 | 3.828125 | 4 | #!/usr/bin/env python
"""
Advent of Code solution for Day 3: Rucksack Reorganization
https://adventofcode.com/2022/day/3
THOUGHTS/IDEAS/DISCUSSION:
As on the previous two days, the general pattern is mapping a value function over
rows of input, then aggregating (as sum) for all the inputs.
That's a pretty clean and familiar pattern: just copy previous day's solution,
write new value function. The logic for one range completely overlapping another
range is easy enough.
HISTORY
2023Aug07 ej created
"""
from typing import Callable
from functools import partial
# GLOBAL DATA
DAY = 4
FILENAME = f"2022-{DAY:02d}.input.txt"
PROBLEM = f"Aoc 2022 Day {DAY},"
def contains(range_1: tuple, range_2: tuple) -> bool:
"""
Predicate for whether 'range_1' is wholly contained within 'range_2' OR vice versa
:parameter range_1: 2-tuple of ints
:parameter range_2: 2-tuple of ints
"""
a, b = range_1
x, y = range_2
return (x >= a and y <= b) or (a >= x and b <= y)
def overlaps(range_1: tuple, range_2: tuple) -> bool:
"""
Predicate for whether 'range_1' overlaps 'range_2' at all.
Logically, either endpoint of one range is on or between the endpoints of the other,
or vice verse (swapping the two pairs).
:parameter range_1: 2-tuple of ints
:parameter range_2: 2-tuple of ints
:return: True if any overlap, else False
"""
a, b = range_1
x, y = range_2
return (
(x <= a <= y) or (x <= b <= y) # one of endpoints of 1st range "inside" bounds of 2nd range
or (a <= x <= b) or (a <= y <= b) # or vice-versa
)
def f_part1Value(line: str, f_logic: Callable) -> int:
"""
Convert a line of input to either 0 or 1
:param line: the input line as string (need not be stripped)
:return: 1 if one range is contained within the other, else 0
"""
try:
a, b = line.split(',')
r1 = tuple([int(w) for w in a.split('-')])
r2 = tuple([int(w) for w in b.split('-')])
return 1 if f_logic(r1, r2) else 0
except ValueError:
print(f"ValueError on line {line_index}")
def main():
"""Implements AoC Day 4"""
# read input file
with open(FILENAME, 'r') as fd:
lines = fd.readlines()
# Part 1: number of completely-overlapping pairs
f_value = f_part1Value
total = sum([f_value(line, f_logic=contains) for line in lines])
exp = 573
print(f"{PROBLEM} Part 1: count of contained pairs: {total} (should be {exp})")
assert total == exp
# 573 submitted and accepted 2023Aug07 (first try! ;)
# Part 2: number of pairs that overlap at all
# let's now make both parts "extra DRY"...
part = 2
f_value = partial(f_part1Value, f_logic=overlaps)
total = sum([f_value(line) for line in lines])
exp = 867
print(f"{PROBLEM} Part {part}: count of overlapping pairs: {total} (should be {exp})")
assert total == exp
# 1440 is too high :( (not sure why I got this, but diff answer after cleanup)
# 867 submitted and accepted on 2023Aug07 (2nd try)
# ENTRY POINT
if __name__ == '__main__':
main()
# EOF
|
c615d66707c5d5f69d404845df38c38562060c04 | vladn90/Algorithms | /Divide_and_conquer/count_inversions/count_inversions_dc.py | 2,243 | 4 | 4 | """ Count inversions in an array. Divide and conquer algorithm based
on merge sort.
Algorithm description:
1) Base case: length(array) <= 1, i.e. only 1 element in the array,
no need to sort and no need to count inversions.
2) Divide array in two halves: left array and right array.
3) Sort recursively and count inversions in left and right array.
4) Combine sorted arrays and count inversions between elements from different
arrays.
5) Return total number of inversions in left array, right array and in-between.
"""
def sort_count_split(left_arr, right_arr):
# pointers to the beginning of the left and right arrays
i, j = 0, 0
comb_arr = [] # resulting sorted array
inv = 0 # inversions count
# choose the minimum element from left and right array,
# count inversions if needed
while i < len(left_arr) and j < len(right_arr):
# min element in the left array, no inversions needed
if left_arr[i] <= right_arr[j]:
comb_arr.append(left_arr[i])
i += 1
# min element in right array, number of inversions needed is equal to
# number of elements left in the left array, including current element
else:
comb_arr.append(right_arr[j])
j += 1
inv += len(left_arr) - i
# add whatever's left from left or right array to resulting sorted array
while i < len(left_arr):
comb_arr.append(left_arr[i])
i += 1
while j < len(right_arr):
comb_arr.append(right_arr[j])
j += 1
return comb_arr, inv
def sort_count(array):
""" Returns sorted array and number of inversions.
"""
# base case, empty array or an array with 1 element
if len(array) <= 1:
return array, 0
mid = len(array) // 2
# recursively sort left and right array and count inversions
left_arr, left_inv = sort_count(array[:mid])
right_arr, right_inv = sort_count(array[mid:])
# merge sorted arrays and count inversions between elements in arrays
array, split_inv = sort_count_split(left_arr, right_arr)
return array, (left_inv + right_inv + split_inv)
def count_inv(array):
""" Returns number of inversions in array.
"""
return sort_count(array)[1]
|
5043495400a4456097e917f15066c5d6163a9a3e | sunnyyeti/Leetcode-solutions | /1147 Longest Chunked Palindrome Decomposition.py | 1,580 | 3.734375 | 4 | # Return the largest possible k such that there exists a_1, a_2, ..., a_k such that:
# Each a_i is a non-empty string;
# Their concatenation a_1 + a_2 + ... + a_k is equal to text;
# For all 1 <= i <= k, a_i = a_{k+1 - i}.
# Example 1:
# Input: text = "ghiabcdefhelloadamhelloabcdefghi"
# Output: 7
# Explanation: We can split the string on "(ghi)(abcdef)(hello)(adam)(hello)(abcdef)(ghi)".
# Example 2:
# Input: text = "merchant"
# Output: 1
# Explanation: We can split the string on "(merchant)".
# Example 3:
# Input: text = "antaprezatepzapreanta"
# Output: 11
# Explanation: We can split the string on "(a)(nt)(a)(pre)(za)(tpe)(za)(pre)(a)(nt)(a)".
# Example 4:
# Input: text = "aaa"
# Output: 3
# Explanation: We can split the string on "(a)(a)(a)".
# Constraints:
# text consists only of lowercase English characters.
# 1 <= text.length <= 1000
class Solution:
def longestDecomposition(self, text: str) -> int:
ans = 0
st = []
start = 0
end = len(text)-1
while start<=end:
tar = text[start]
st.append(text[end])
if st[-1]==tar:
#print(st)
ts,te = start,-1
while te>=-len(st) and ts<len(text) and text[ts]==st[te]:
ts+=1
te-=1
#print(ts,te)
if te<-len(st):
ans+=2
ans-=(end==start)
st = []
start=ts
end-=1
return ans
|
b602a3567cb777635b95880396a7ee5ded16b4f3 | schultzjack95/Project_Euler | /Problem2/problem2.py | 359 | 3.6875 | 4 | class FibonacciComputer:
prev = 0
current = 1
iteration = 0
def advance(self):
self.prev, self.current = self.current, self.prev + self.current
self.iteration += 1
fc = FibonacciComputer()
total = 0
while (fc.current <= 4000000):
fc.advance()
if fc.current % 2 == 0:
total += fc.current
print(total)
|
135b2c11ce77f7b346c5d9de236f41b055f9fafc | kan2016/mylibrary | /library/algorithm/bipartiteMatching.py | 1,093 | 3.90625 | 4 | # written by Kazutoshi KAN, 2018
# -*- coding: utf-8 -*-
from algorithm.graph import Edge
# Ford-Fulkerson algorithm
def augment(g, u, matchTo, visited):
if u < 0: return True
for e in g[u]:
if not visited[e.dst]:
visited[e.dst] = True
if augment(g, matchTo[e.dst], matchTo, visited):
matchTo[e.src] = e.dst
matchTo[e.dst] = e.src
return True
return False
# g: bipartite graph
# L: size of the left side
def bipartiteMatching(g, L, matching):
n = len(g)
matchTo = [-1 for n in range(n)]
match = 0
for u in range(L):
visited = [False]*n
if augment(g, u, matchTo, visited):
match+=1
for u in range(L):
if matchTo[u] >= 0:
matching.append(Edge(u, matchTo[u]))
return match
# -*- sample code -*-
if __name__=='__main__':
from algorithm.graph import Edge
matching = []
L = 3
g = [[Edge(0,3), Edge(0,4)],
[Edge(1,4), Edge(1,5)],
[Edge(2,5)],
[Edge(3,0)],
[Edge(4,0), Edge(4,1)],
[Edge(5,1), Edge(5,2)]
]
bipartiteMatching(g, L, matching)
for e in matching: print(e)
|
c999758a2e39e5ac18fbaa1deeb253a23c235eb7 | VivekPatel15/Intro-to-Programming | /circle practice.py | 465 | 4.28125 | 4 | center = input('Enter the center point of the circle as x,y (no parenthesis): ')
point = input('Enter a point of the circle as x,y (no parenthesis): ')
#center = (x1, y1)
#point = (x2, y2)
x1 = float(center.split(',')[0])
x2 = float(point.split(',')[0])
y1 = float(center.split(',')[1])
y2 = float(point.split(',')[1])
def radius(x1, y1, x2, y2):
r = (((x2-x1)**2)+((y2-y1)**2))**(1/2)
print("radius = " + str(r))
radius(x1, y1, x2, y2)
|
73ccfe6b45c22ad913948c36f25eeebf8d09c671 | Built00/Leetcode | /3Sum.py | 4,295 | 3.5625 | 4 | # -*- encoding:utf-8 -*-
# __author__=='Gan'
# Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0?
# Find all unique triplets in the array which gives the sum of zero.
# Note: The solution set must not contain duplicate triplets.
# For example, given array S = [-1, 0, 1, 2, -1, -4],
# A solution set is:
# [
# [-1, 0, 1],
# [-1, -1, 2]
# ]
# Here it's my first solution.It's failed.
# I think if a + b < 0 that should abandon the b.And judge a + (b-1) if still less 0.
# For example, b = -5, a = 4 and then abandon the b.If nums have 1,then find the answer.
# But if the nums still have 3 and 2, they also right. [-5, 4, 1] and [-5, 3, 2].
# So -5 is can't be abandoned.
# class Solution(object):
# def threeSum(self, nums):
# """
# :type nums: List[int]
# :rtype: List[List[int]]
# """
# left, right = 0, len(nums) - 1
# transition_dict = {}
# dummy_list = []
# res__list_list = []
#
# nums.sort()
# for num in nums:
# if transition_dict.get(num):
# transition_dict[num] += 1
# else:
# transition_dict[num] = 1
# print(transition_dict)
# while left < right:
# if (max(nums[right], nums[left]) < 0) or (min(nums[right], nums[left]) > 0):
# break
# dummy = 0 - (nums[left] + nums[right])
# if transition_dict.get(dummy):
# dummy_list.append([dummy, nums[left], nums[right]])
#
# if nums[left] + nums[right] < 0:
# left += 1
# else:
# right -= 1
#
# print(dummy_list)
# for i in range(len(dummy_list) - 1):
# res__list_list.append(dummy_list[i])
# for res__list in dummy_list[i]:
# if transition_dict[res__list] < dummy_list.count(res__list):
# res__list_list.pop()
# break
# return res__list_list
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
res_list = []
nums.sort()
for i in range(len(nums) - 2):
if i > 0 and nums[i] == nums[i - 1]: # i > 0 guarantee that len(nums) > 3.Can handle [0, 0, 0].
continue # Avoid to handle the same value.Because if value is same, it will get the same groups too.
left, right = i + 1, len(nums) - 1
while left < right:
dummy = nums[i] + nums[left] + nums[right]
if dummy < 0:
left += 1
elif dummy > 0:
right -= 1
else:
res_list.append([nums[i], nums[left], nums[right]])
while left < right and nums[left] == nums[left + 1]: # avoid to handle the same group.
left += 1
while left < right and nums[right] == nums[right -1]:
right -= 1
left += 1
right -= 1
return res_list
if __name__ == '__main__':
print(Solution().threeSum([1,2,-1,-1]))
print(Solution().threeSum([-1,0,1,2,-1,-4]))
# 313 / 313 test cases passed.
# Status: Accepted
# Runtime: 972 ms
# Your runtime beats 76.59 % of python submissions.
# Here is the fastest solution in leetcode.
class Solution(object):
def threeSum(self, nums):
result, counter = [], {}
for num in nums:
if num not in counter:
counter[num] = 0
counter[num] += 1
uniques = counter.keys()
positives = [num for num in uniques if num >= 0]
negatives = [num for num in uniques if num < 0]
if 0 in counter and counter[0] > 2:
result.append([0, 0, 0])
for p in positives:
for n in negatives:
inverse = -(p + n)
if inverse in counter:
if (inverse == p or inverse == n) and counter[inverse] > 1:
result.append([p, n, inverse])
elif inverse > p or inverse < n:
result.append([p, n, inverse])
return result
|
d26db5f0f7742b61c5da643a5854c24d9c93fc58 | Prakruthi94/Pylearning | /Simple interest.py | 120 | 3.75 | 4 | p=int(input("Principal Amount"))
r=float(input("Rate of interest"))
t=int(input("Time period"))
si=p*r*t/100
print(si)
|
6aad85fd1475a9d1207d411cf4bc65858a3cbf97 | coryrc/interview-problem-n | /gen_random.py | 619 | 3.6875 | 4 | import random
num_sellers = 13
num_buyers = 6
fb = open('buyers.csv','w')
remaining_sellers = num_sellers
for i in range(num_buyers):
print("On buyer %d, remaining sellers %d, how many sellers?" % (i,remaining_sellers))
sellers = int(input())
remaining_sellers -= sellers
seller_priority = list(range(num_sellers))
random.shuffle(seller_priority)
fb.write(",".join(map(str,[i,sellers]+seller_priority)) + "\n")
print("sellers:")
for i in range(num_sellers):
buyer_priority = list(range(num_buyers))
random.shuffle(buyer_priority)
print(",".join(map(str,[i]+buyer_priority)))
|
13b94c94b3e939d895284cdb5d98b753c3d8715d | amkelso1/module-6 | /more_functions/string_functions.py | 258 | 3.5 | 4 | """
Author: Alex Kelso
program: function_parameter.py
date: 10/6/2020
purpose:
"""
def multiply_string(message, n):
"""return a message a certain number of times"""
return message * n
if __name__ == '__main__':
print(multiply_string('alex', 7))
|
1c659894c152eb35db37edd1e76645f683b1510f | DenBlacky808/--Python | /3. salary data.py | 624 | 3.515625 | 4 | sum_sal = 0
workers_list = []
salary_list = []
with open("text_3.txt", 'r', encoding='utf-8') as fi_1:
words_list = sum([word.split() for word in [line.rstrip() for line in fi_1.readlines()]], [])
for i in range(1, len(words_list), 2):
salary_list.append(words_list[i])
workers_list.append(words_list[i - 1])
for name in [workers_list[b] for b in range(len(salary_list)) if float(salary_list[b]) < 20000]:
print(name, end=' ')
for price in salary_list:
sum_sal += float(price)
print(f'\n------ Средняя величина дохода: {sum_sal / len(salary_list)}')
|
7bbdf30cb8c193d84bb3065b296907950ad0d869 | otmane-chaibe/TCP | /Client.py | 905 | 3.96875 | 4 | import sys
from socket import*
# Get the server hostname, port and data length as command line arguments
argv = sys.argv
host = argv[1]
port = argv[2]
count = argv[3]
# Command line argument is a string, change the port and data length into integer
port = int(port)
count = int(count)
# Initialize and print data to be sent
data = 'X' * count
# Create TCP client socket. Note the use of SOCK_STREAM for TCP packet
clientSocket= socket(AF_INET, SOCK_STREAM)
# Create TCP connection to server
print("Connecting to " + host + ", " + str(port))
clientSocket.connect((host, port))
# Send data through TCP connection
print("Sending data to server: " + data)
clientSocket.send(data.encode())
# Receive the server response
dataEcho= clientSocket.recv(count)
# Display the server response as an output
print("Receive data from server: " + dataEcho.decode())
# Close the client socket
clientSocket.close()
|
4001bc48352c8730bfea44916541ed4cb19bbb9d | wisvem/holbertonschool-higher_level_programming | /0x0A-python-inheritance/11-square.py | 553 | 4 | 4 | #!/usr/bin/python3
"""Square module"""
Rect = __import__('9-rectangle').Rectangle
class Square(Rect):
"""Square class"""
def __init__(self, size):
"""[summary]
Args:
size (int): size of square
"""
self.integer_validator("size", size)
super().__init__(size, size)
self.__size = size
def __str__(self):
"""overloading str method
Returns:
str: square data
"""
sr = "[Square] {}/{}".format(self.__size, self.__size)
return sr
|
0f651b7ce7c9361d5bd480f473d69d51da5acab3 | utsav7011/python-prg | /atm card.py | 2,427 | 3.953125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
print ("welcome to bank kanjoos")
restart = 'Y'
chances = 3
balance=67.14
while chances>=0:
pin=int(input("\n enter the pin of you kanjoos bank card"))
if pin == (1234):
print("\n you have entered the correct pin \n")
while restart not in ('n','no','NO','N'):
print("please press 1 to check your balance \n")
print('please press 2 for withdrawl \n')
print('please press 3 to deposit \n')
print ('please press 4 to return card')
option = int (input('enter the choice'))
if option ==1:
print ('balance of your kanjoos account is', balance)
restart=input('would you like to start over')
if restart ==('n','no','N','NO'):
print('thank you')
break
if option ==2:
option2='Y'
withdrawl=float(input('enter the value to be withdrawn \n 10,20,40,60,80,100 \n'))
if withdrawl in [10,20,40,60,80,100]:
balance = balance-withdrawl
print('\n your balance is :', balance)
if restart ==('n','no','N','NO'):
print('thank you')
break
elif withdrawn not in [10,20,40,60,80,100]:
print ('invalid value entered \n please retry kanjoos')
restart =('Y')
elif withdrawl ==1:
withdrawl =float (input('\n please enter the desired amount : '))
elif option ==3:
payin=float(input('\n how much would you like to pay in'))
balance=balance+payin
print('\n your balance is ', balance)
restart = input ('would you like to go back')
if restart ==('n','no','N','NO'):
print ('thank you')
break
elif option==4:
print ('\n please wait your card is returned..........')
restart='Y'
elif pin!=(1234):
print ('\n incorrect password \n')
chances =chances-1
if chances==0:
print ('\n no more attempts!!!!!!')
break
# In[ ]:
# In[ ]:
|
96723a3364c1dbbb4bec94c78f53011cfa1fff7d | Mike-droid/CursoPythonIntermedio | /proyecto_2/lists_and_dicts.py | 724 | 3.859375 | 4 | def run():
my_list = [1, "Hello", True, 4.5] #!Lista
my_dict = {"firstname": "Miguel" , "lastname": "Reyes"} #!Diccionario
super_list = [ #!Lista de diccionarios
{"firstname": "Miguel" , "lastname": "Reyes"},
{"firstname": "Facundo" , "lastname": "García"},
{"firstname": "Oscar" , "lastname": "Guerra"},
{"firstname": "Ximena" , "lastname": "Ruíz"},
]
super_dict = { #! Diccionario de listas
"natural_nums": [1,2,3,4,5],
"integer_nums": [-1, -2 ,0 ,1 ,2],
"floating_nums": [1.1, 4.5, 6.43]
}
for key, value in super_dict.items():
print(key, "-" , value)
for item in super_list:
print(item["firstname"] , "-" , item["lastname"])
if __name__ == '__main__':
run() |
75d2b7cab197fe15fda53d6189cefb4b2157d68e | ignaciorosso/Practica-diaria---Ejercicios-Python | /Listas - Mayor y menor elemento/Problema4.py | 718 | 3.671875 | 4 | # Cargar una lista con 5 elementos enteros. Imprimir el mayor y un mensaje si se repite dentro de la lista (es decir si dicho valor se encuentra en 2 o más posiciones en la lista)
entero = []
for f in range(5):
entero.append(int(input('Ingrese valor: ')))
entero_mayor = entero[0]
cont = 0
for x in range(len(entero)-1):
if (entero[x] > entero_mayor):
entero_mayor = entero[x]
for x in range(len(entero)): #Aqui debemos recorrer toda la lista
if (entero[x] == entero_mayor):
cont+=1
print('El mayor valor es: {}'.format(entero_mayor))
if (cont > 1):
print('Se repite {} veces'.format(cont))
else:
print('El valor no se repite ninguna vez en la lista') |
5c2a41d3acc0f7dd078608d780a4137a5baa83d3 | Nickruti/HackerRank-Python-Problems- | /Validating_phone_numbers.py | 467 | 4.03125 | 4 | #https://www.hackerrank.com/challenges/validating-the-phone-number/problem?isFullScreen=true
# Enter your code here. Read input from STDIN. Print output to STDOUT
import re
n = int(input())
for i in range(0, n):
mobNum = str(input())
if len(mobNum) != 10:
print("NO")
elif len(re.findall("^(7|8|9)", mobNum)) == 0:
print("NO")
elif len(re.findall("\d", mobNum)) != 10:
print("NO")
else:
print("YES")
|
960a433ea11af052e6200efbc60cc5bbf8d3be14 | Future-Aperture/Python | /exercícios_python/exercíciosMiguel/Curso_Em_Vídeo/Exercícios_61-75/Mundo_2_Ex_64.py | 315 | 4 | 4 | num, soma, count = 0, 0, 0
print("Digite o número '999' para parar o programa.\n")
num = int(input("Digite um número inteiro: "))
while num != 999:
soma += num
count += 1
num = int(input("Digite um número inteiro: "))
print(f"\nVocê digitou {count} números, e\na soma total deles é: {soma}.") |
bc6cefcc7cad726d225cbb06c4acf929ee40946c | uneeth/Map-Reduce | /Task2/mapperTask2_1.py | 135 | 3.578125 | 4 | #!/usr/bin/env python3
import sys
for line in sys.stdin:
words, count=line.strip().lower().split(":")
print("%s\t%s"%(words,count))
|
15cf5a9ef1a1d97a83430ea9a167f5042080d819 | lldingding/Python_note | /01-认识python/hm_05_格式化输出.py | 344 | 3.96875 | 4 | #格式化输出 我爱小明
#定义变量
name="小明"
#输出
print("我爱%s" % name)
#输出float
num=12.9764357473536805357821353
print("数值为%.02f" % num) #%.2f同%.02f
#输出百分比 25.00%
a=25
print("数值为 %.2f%%" % a)
print("数值为 %.2f%%" % a*10) #重复十次
print("数值为 %.2f%%" % (a*10)) #输出a*10
|
552ecb145a836a53c1d7dea17ab8e0f841631f85 | mreishus/leetcode | /2020-02/1143.py | 2,273 | 4.09375 | 4 | #!/usr/bin/env python
"""
Given two strings text1 and text2, return the length of their longest common
subsequence.
A subsequence of a string is a new string generated from the original string
with some characters(can be none) deleted without changing the relative order
of the remaining characters. (eg, "ace" is a subsequence of "abcde" while "aec"
is not). A common subsequence of two strings is a
subsequence that is common to both strings.
If there is no common subsequence, return 0.
Example 1:
Input: text1 = "abcde", text2 = "ace" Output: 3 Explanation: The longest
common subsequence is "ace" and its length is 3.
Example 2:
Input: text1 = "abc", text2 = "abc" Output: 3 Explanation: The longest common
subsequence is "abc" and its length is 3.
Example 3:
Input: text1 = "abc", text2 = "def" Output: 0 Explanation: There is no such
common subsequence, so the result is 0.
"""
import functools
class Solution:
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
"""
DP is much faster than recursive here, even with LRU_Cache..
"""
len1 = len(text1)
len2 = len(text2)
DP = []
for i in range(len1 + 1):
DP.append([0] * (len2 + 1))
for i in range(len1):
for j in range(len2):
if text1[i] == text2[j]:
DP[i + 1][j + 1] = 1 + DP[i][j]
else:
DP[i + 1][j + 1] = max([DP[i][j + 1], DP[i + 1][j]])
return DP[-1][-1]
def longestCommonSubsequence2(self, text1: str, text2: str) -> int:
@functools.lru_cache(None)
def helper(i, j):
if i < 0 or j < 0:
return 0
if text1[i] == text2[j]:
return 1 + helper(i - 1, j - 1)
return max([helper(i - 1, j), helper(i, j - 1)])
return helper(len(text1) - 1, len(text2) - 1)
if __name__ == "__main__":
cases = [
("abcde", "ace", 3),
("abc", "abc", 3),
("abc", "def", 0),
("bl", "yby", 1),
]
for (s1, s2, want) in cases:
got = Solution().longestCommonSubsequence(s1, s2)
print(f"Pass? {want == got} | got {got} | want {want} | s1 {s1} | s2 {s2}")
|
b5aa146e3d74d45e2cf46df153b4b038bf0302e8 | nick-newton2/python_implementations | /topological_sort/passcode.py | 1,421 | 4.03125 | 4 | #!/usr/bin/env python3
import sys
import collections
### CHALLENGE 19
Graph = collections.namedtuple('Graph', 'edges degrees')
#read from stdin
def read_graph():
# Store edges and degrees
edges = collections.defaultdict(set)
degrees = collections.defaultdict(int)
for line in sys.stdin:
nums=[]
for num in line.rstrip():
nums.append(num)
for i in range(len(nums)-1):
source = nums[i]
target = nums[i+1]
#check
if target in edges[source]:
continue
#update graph
edges[source].add(target)
degrees[target] += 1
degrees[source]
return Graph(edges, degrees)
# Topological Sort
def topological_sort(graph):
frontier = [v for v, d in graph.degrees.items() if d == 0]
visited = []
while frontier:
vertex = frontier.pop()
visited.append(vertex)
for neighbor in graph.edges[vertex]:
graph.degrees[neighbor] -= 1
if graph.degrees[neighbor] == 0:
frontier.append(neighbor)
return visited
def main():
#read in input and do topo sort
graph= read_graph()
vertices= topological_sort(graph)
#display
if len(vertices) == len(graph.degrees):
print(''.join(vertices))
else:
print('There is a cycle')
if __name__ == '__main__':
main()
|
726427de3aa8d0ad15a5ce7e0b5becb928109400 | muzindahub-2018-01/Tarie | /report_card.py | 1,892 | 3.90625 | 4 | import random
import os
report_book = []
def clear_screen():
os.system("cls" if os.name == "nt" else "clear")
def show_help():
clear_screen()
print("Would you care to enter a new subject? ")
print("""
Enter 'DONE' to stop adding subjects.
Enter 'HELP' for help.
Enter 'SHOW' to see your subjects .
Enter 'REMOVE' to delete a subject from your report_book.
""")
def add_to_report_book(subject):
show_report_book()
if len(report_book):
position = input("Where should i add {}?\n"
"Press ENTER to add to the end of the report_book\n"
"> ".format(subject))
else:
position = 0
try:
position = abs(int(position))
except ValueError:
position = None
if position is not None:
report_book.insert(position-1, subject)
else:
report_book.append(new_subject)
show_book()
def show_report_book():
clear_screen()
print("Here's your book:")
for index, item in enumerate(report_book, start = 1):
print("{}. {}".format(index, subject))
print("-"*10)
def remove_from_report_book():
show_list()
what_to_remove = input("What would you like to remove?\n> ")
try:
report_book.remove(what_to_remove)
except ValueError:
pass
show_report_book()
show_help()
while True:
new_subject = input("> ")
if new_subject.upper() == 'DONE' or new_subject.upper() == 'QUIT':
break
elif new_subject.upper() == 'HELP':
show_help()
continue
elif new_subject.upper() == 'SHOW':
show_list()
continue
elif new_subject.upper() == 'REMOVE':
remove_from_report_book()
else:
add_to_report_book(new_subject)
show_report_book() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.