blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
237d4b5597562a6fd1daef1fab074a8e496ada5e | pawwahn/python_practice | /regular_exp_search_concepts_1/search_word_positions.py | 531 | 3.765625 | 4 | import re
content = """This method either returns None
(if the pattern doesn’t match), or a re.MatchObject that
contains information about the matching part of the string.
This method stops after the first match, so this is best suited
for testing a regular expression more than extracting data."""
search_word = 'match'
search_word_list=[]
search_word_positions = re.finditer(search_word, content)
print(search_word_positions)
for i in search_word_positions:
search_word_list.append(i.span())
print(search_word_list) |
49b160f0a772354389d62ef9b54f1c5e6143c30b | gunit84/Code_Basics | /Code Basics Beginner/ex13_modules.py | 483 | 3.953125 | 4 | #!python3
"""Learning Modules... """
__author__ = "Gavin Jones"
import sys
import functions as f
# Add the current directory to your Python Systems PATH so it can locate the file aka Module
sys.path.append("D:\PycharmProjects\Projects\Projects_Learning\Code Basics")
squareArea = f.calculate_square_area(5)
triangleArea = f.calculate_triangle_area(5, 10)
# Print the results
print("The Triangle Area is: {}".format(triangleArea))
print("The Square Area is: {}".format(squareArea))
|
33829702bf31d0136782224dc51c7ceb568c14d0 | dante092/Mega-Bus-Web-Crawler | /citicodes.py | 2,927 | 3.5 | 4 | """ Small Script to find citi destinations codes for MEGABUS"""
from urllib.request import urlopen
from bs4 import BeautifulSoup
number = 89 # First city.
while True:
try:
url = 'http://us.megabus.com/JourneyResults.aspx?originCode={0}&destinationCode=143&outboundDepartureDate=4%2f16%2f2016&inboundDepartureDate=4%2f16%2f2016&passengerCount=2&transportType=0&concessionCount=0&nusCount=0&outboundWheelchairSeated=0&outboundOtherDisabilityCount=0&inboundWheelchairSeated=0&inboundOtherDisabilityCount=0&outboundPcaCount=0&inboundPcaCount=0&promotionCode=&withReturn=1'.format(number)
html = urlopen(url)
soup = BeautifulSoup(html)
places = []
for place in soup.findAll("strong"):# City name is in between a strong tag
places.append(place.getText())
print("'"+places[0].upper()+"'"+' : '+"'"+str(number)+"'"+',') # formats the city into a dictionary to be used later.
number += 1
except IndexError: #Some cities skip a digit or two, this code stops the indexerror from stopping the program.
number +=1
continue
else:
if number > 145: # This is the numerical code for the last city.
print('Done')
break
""""
Sample Output :
'ALBANY, NY' : '89',
'AMHERST, MA' : '90',
'ANN ARBOR, MI' : '91',
'ATLANTIC CITY, NJ' : '92',
'BINGHAMTON, NY' : '93',
'BOSTON, MA' : '94',
'BUFFALO, NY' : '95',
'BURLINGTON, VT' : '96',
'CAMDEN' : '97',
'CHAMPAIGN, IL' : '98',
'CHARLOTTE, NC' : '99',
'CHICAGO, IL' : '100',
'CHRISTIANSBURG, VA' : '101',
'CINCINNATI, OH' : '102',
'CLEVELAND, OH' : '103',
'COLUMBIA, MO' : '104',
'COLUMBUS, OH' : '105',
'DES MOINES, IA' : '106',
'DETROIT, MI' : '107',
'ERIE, PA' : '108',
'FREDERICK, MD' : '109',
'HAMPTON, VA' : '110',
'HARRISBURG, PA' : '111',
'HARTFORD, CT' : '112',
'HOLYOKE, CT' : '113',
'HYANNIS, MA' : '114',
'INDIANAPOLIS, IN' : '115',
'IOWA CITY, IA' : '116',
'KANSAS CITY, MO' : '117',
'KNOXVILLE, TN' : '118',
'MADISON, WI' : '119',
'MEMPHIS, TN' : '120',
'MILWAUKEE, WI' : '121',
'NEW HAVEN, CT' : '122',
'NEW YORK, NY' : '123',
'NIAGARA FALLS, ON' : '124',
'NORMAL, IL' : '125',
'OMAHA, NE' : '126',
'PHILADELPHIA, PA' : '127',
'PITTSBURGH, PA' : '128',
'PORTLAND, ME' : '129',
'PROVIDENCE, RI' : '130',
'DURHAM, NC' : '131',
'RICHMOND, VA' : '132',
'RIDGEWOOD, NJ' : '133',
'ROCHESTER, NY' : '134',
'SECAUCUS, NJ' : '135',
'ST LOUIS, MO' : '136',
'STATE COLLEGE, PA' : '137',
'STORRS, CT' : '138',
'SYRACUSE, NY' : '139',
'TOLEDO, OH' : '140',
""""
|
ae322d5dab25616f4bad2fb1cc085166136a5a60 | gin2010/work | /data_train/basic1.py | 404 | 3.734375 | 4 | # -*- coding: utf-8 -*-
# File : 01-basic1.py
# Author: water
# Date : 2019/7/31
for i in range(1,4):
email = input ('email:')
index = email.find("@")
if index>0:
name = email[:index]
email_sort = email[index+1:]
print(f'邮箱名:{name} 类型:{email_sort}')
break
else:
print("input wrong")
else:
print(f"输入{i}次错误,锁定") |
8e32ecc9c3a4799548dca4e8f887bd79ed139984 | dchapp/blind75 | /python/17_letter_combinations_of_a_phone_number.py | 938 | 3.5625 | 4 | num_to_letters = {
'2': ['a', 'b', 'c'],
'3': ['d', 'e', 'f'],
'4': ['g', 'h', 'i'],
'5': ['j', 'k', 'l'],
'6': ['m', 'n', 'o'],
'7': ['p', 'q', 'r', 's'],
'8': ['t', 'u', 'v'],
'9': ['w', 'x', 'y', 'z'],
}
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
if len(digits) == 0:
return []
return self.recursive(digits)
def recursive(self, digits):
words = set()
digit_idx = 0
def worker(digits, digit_idx, current_word):
candidates = num_to_letters[digits[digit_idx]]
for c in candidates:
if digit_idx == len(digits)-1:
words.add(current_word + c)
else:
worker(digits, digit_idx+1, current_word + c)
worker(digits, 0, "")
return list(words)
|
a648c7badc895501112ac747aef0bc9fb6011c28 | anjali-kundliya/Hactoberfest-2022 | /Python/Graph Algorithms/DFS.py | 1,669 | 3.953125 | 4 | '''
The purpose of the algorithm is to mark each vertex as visited while avoiding cycles.
Algorithm:
* We will start by putting any one of the graph's vertex on top of the stack.
* After that take the top item of the stack and add it to the visited list of the vertex.
* Next, create a list of that adjacent node of the vertex. Add the ones which aren't in the visited list of vertexes to the top of the stack.
* Lastly, keep repeating steps 2 and 3 until the stack is empty.
This program is to print DFS traversal
from a given source vertex.
'''
from collections import defaultdict
class DFS:
# create default dictionary to store graph
def __init__(self):
self.graph = defaultdict(list)
# add edge to graph
def addEdge(self, u, v):
self.graph[u].append(v)
# traverse and print DFS of graph
def DFSTraversel(self, node, visited):
if node not in visited:
print(node)
visited.append(node)
for neighbour in self.graph[node]:
self.DFSTraversel(neighbour, visited)
def getDFS(self, node):
visited = []
self.DFSTraversel(node, visited)
# main funciton
if __name__ == '__main__':
bfs = DFS()
total_edges = int(input('Enter the no of edges you want: '))
for i in range(total_edges):
u,v = map(int, input(f'Enter edge {i+1}: ').split())
bfs.addEdge(u,v)
node = eval(input('Enter the node node: '))
bfs.getDFS(node)
'''
Enter the no of edges you want: 6
Enter edge 1: 1 4
Enter edge 2: 5 7
Enter edge 3: 5 4
Enter edge 4: 3 5
Enter edge 5: 1 2
Enter edge 6: 2 6
Enter the node node: 1
1
4
2
6
'''
|
1fc5b807a370eaf2c85357e1b7abdf3dc3801bc8 | Yoshioki311/Python-basics | /trim.py | 303 | 3.828125 | 4 | # Trims a given word with extra spaces
def trim(s):
if s == '':
return s
else:
i = 0
j = len(s) - 1
while s[i] == ' ' and i < len(s) - 1:
i += 1
while s[j] == ' ' and j > 0:
j -= 1
j += 1
s = s[i:j]
return s |
894e96cb347e1df6c79f4acb38b758d472cae769 | BrianMillsJr/alan | /learning/learn.py | 7,008 | 3.828125 | 4 | import nltk
import re
import alan
"""
This file handles learning tasks for alan.
A task is something that can be dictated by the user and Alan turns that dictation into python code.
Note:
You need to add Alan's main directory to your python path for this script to work due to importing alan.
Example command run from the alan directory:
> export PYTHONPATH=$(pwd)
TODO: Write proper documentation for this file!! Very experimental
"""
command_list = ['while', "if", "until", "for", "say", "otherwise", "get"]
dependencies = []
defined_variables = []
def lemmatize_phrase(output_list):
"""
Takes list of commands and adjusts tense
"""
from nltk.stem.wordnet import WordNetLemmatizer
# List of words we do not want to change
no_changes = ["is", "be"]
lem = [(WordNetLemmatizer().lemmatize(word[0], 'v'), word[1]) if 'VB' in word[1] and word[0] not in no_changes else word for word in output_list]
return lem
def newline_characterization(input):
"""
Tries to break the dictation into lines based on keywords and verbs.
If the special word "get" exists we know a variable assignment exists and
we add the next verb phrase to the line.
"""
output_list = []
word_list = nltk.pos_tag(nltk.word_tokenize(input))
variable_assignment = False
lemmatize = lemmatize_phrase(word_list)
for word in lemmatize:
if (word[0] in command_list or word[1] == 'VB') and not variable_assignment:
if word[0] == "get":
variable_assignment = True
output_list.append(word[0])
else:
if word[0] in command_list:
output_list.append(word[0])
continue
if 'VB' in word[1]:
variable_assignment = False
if len(output_list) > 0:
output_list[-1] += " " + word[0]
else:
output_list.append(word[0])
return output_list
def replace_keyphrases(output_list):
"""
Replaces some common operators, need to add to the list.
"""
swapped_keyphrases = []
for phrase in output_list:
# The word get denotes variable assignment.
if phrase.split()[0] == "get" and "by" in phrase:
phrase = phrase.replace("get ", "")
phrase_list = phrase.split("by")
# TODO needs lemmatization before surrounding with alan.think()
phrase_list[-1] = "alan.think(\"" + phrase_list[-1] + "\")"
defined_variables.append(phrase_list[0].strip().replace(" ", "_"))
swapped_keyphrases.append(phrase_list[0] + "= " + phrase_list[-1])
continue
elif phrase.split()[0] == "get":
phrase = phrase.replace("get ", "").strip()
swapped_keyphrases.append(phrase)
continue
if phrase.split()[0] != "say" and phrase.split()[0] in command_list:
if "is divisible by" in phrase:
phrase += " == 0"
swapped_keyphrases.append(phrase.replace("is greater than", ">").replace("is less than", "<")\
.replace("is divisible by", "%")\
.replace("is equal to", "==").replace("is in", "in")\
.replace("until", "while not")\
.replace("otherwise", "else").replace("equals", "=="))
else:
anded = False
tokenized_phrase = phrase.split()
if tokenized_phrase[0] == "say":
if tokenized_phrase[-1] == "and":
tokenized_phrase.pop()
anded = True
phrase = " ".join(tokenized_phrase)
phrase = phrase.replace("say ", "alan.speak(\"")
phrase += "\")"
if anded:
phrase += " and"
else:
if phrase.split()[-1] == "and":
# Adding an and will keep the current indentation
phrase = phrase.split()
phrase.pop()
phrase = " ".join(phrase)
phrase = "alan.speak(alan.think(\"" + phrase.strip().lower() + "\"))"
swapped_keyphrases.append(phrase)
return swapped_keyphrases
def create_blocks(keyphrase_lines):
"""
Create the logic blocks based on the inputted format. Used indentation to form the blocks.
"""
indentation = 0
block_starters = ["while", "if", "else", "for"]
code_string = ""
for phrase in keyphrase_lines:
if phrase.split()[0] in block_starters:
code_string += (" " * indentation) + phrase + ":\n"
indentation += 1
else:
if phrase.split()[-1] == "and":
# Adding an and will keep the current indentation
phrase = phrase.split()
phrase.pop()
phrase = " ".join(phrase)
code_string += (" " * indentation) + phrase + "\n"
else:
code_string += (" " * indentation) + phrase + "\n"
if (indentation > 0):
indentation -= 1
return code_string
def get_dependencies(code_string):
"""
Function to find likely variables and take of them.
"""
formatted_string = re.sub(r"\".*\"", '', code_string)
matches = re.findall(r"the [a-z, ]*", formatted_string)
matches = [match.strip() for match in matches]
variables = [match.replace(" ", "_") for match in matches]
for index, match in enumerate(matches):
code_string = code_string.replace(match, variables[index])
return code_string, list(set(variables))
def substitute_variables(code_string):
"""
This function uses a regex to look for variables and subs them in to functions.
Example:
"This is the_variable example" --> "This is " + the_variable + "example"
"""
return re.sub(r'(\")(.*?(?=the_))(the_[^ ,^\"]*)([^\"]*)(\")', r'\1\2"+str(\3)+"\4\5', code_string)
def start_learning(sentence):
"""
Function to parse a given sentence into python and run through alan.think()
"""
import language.questions
import memory.store_memories
task = " ".join([word[0] for word in sentence if word[0].lower() != "learn" and word[0] != "how" and word[0] != "to"])
alan_response = "How do I "
if "respond" in task:
alan_response += "respond to"
task = task.replace("respond", "")
indentation = 0
alan.speak(alan_response + task)
instructions = language.questions.ask_for_long_text()
lines = newline_characterization(instructions)
keyphrase_lines = replace_keyphrases(lines)
blocked_lines = create_blocks(keyphrase_lines)
code_string, dependencies = get_dependencies(blocked_lines)
for dependency in dependencies:
if dependency not in defined_variables:
code_string = dependency + " = " + "alan.listen()\n" + code_string
code_string = "alan.speak(\"What is " + dependency.replace("_", " ") + "?\")\n" + code_string
code_string = "import alan\n" + code_string
alan.speak("I'll try to do that now.")
code_string = substitute_variables(code_string)
print code_string
try:
exec (code_string)
should_remember = language.questions.binary_question("Should I remember how to do this?")
if should_remember:
memory.store_memories.store_task(task.strip(), instructions, code_string)
return "Learned to " + task
return "I will not remember how to do that"
except:
return "I failed to learn the task"
|
bcb61861490db4e81d6c98c98cfb6ea1099a9aa4 | 2ashishs/LearningPython | /pyNotes.py | 4,166 | 4 | 4 | Points to note in Python
Python,
is simple to use
allows you to split your program into modules that can be reused in other Python programs
is an interpreted language, which can save you considerable time during program development
enables programs to be written compactly and readably
is extensible: it is easy to add a new built-in function or module to the interpreter,
Interpreter,
python -c command [arg] : executes the statement(s) in command
python -m module [arg] : executes the source file for module as if you had spelled out its full name on the command line
Argument Passing,
import sys
sys.argv : is a list of strings - the script name and additional arguments thereafter
sys.argv[0] : is the script name
Interactive Mode,
>>> Primary prompt, prompts for the next command
... Secondary prompt, prompts for continuation lines
Error Handling,
When an error occurs, the interpreter prints an error message and a stack trace (and may cause a nonzero exit)
All error messages are written to the standard error stream
Exceptions may be handled by an except clause in a try statement
Executable Python Scripts,
Python scripts can be made directly executable, by putting the line,
#! /usr/bin/env python
at the beginning of the script and giving the file an executable mode
Source Code Encoding,
It is possible to use encodings different than ASCII in Python source files, by putting the special comment line,
right after the '#!' line,
# -*- coding: encoding -*-
where, encoding = utf-8 or iso-8859-15 or etc.
Using non-ASCII characters in identifiers is not supported
Python as a Calculator
The interpreter acts as a simple calculator: you can type an expression at it and it will write the value.
Operators:
+, -, *, /, %, >, >=, <, <=, ==
Operands:
Integers: -20...,-1,0,1,2...,int(n),long(n)
RealNumbers: 4.85, 5.21, float(x)
Complex: complex(real,imag) or <real>+<imag>J or <real>+<imag>j
eg. x=2+3j or complex(4,3), x.real=4, x.imag=3, abs(x)=5 (magnitude of x, sq.rt. of sum of real^2 & imag^2)
Variable(s): One or more alphanumeric(a-z,A-Z,0-9,_) characters, starting with (a-z,A-Z,_), used to represent/store value(s)
eg. tax=12.5/100, Income=50000, _Pay=tax*Income
_ : _ is a variable representing last evaluated value. Can be overwritten (but avoid).
int(x),long(x),float(x): Convert operand x to int, long or float value
abs(x): Absolute/Magnitude value of operand x.(+ve value in case of Ints or Reals,Magnitude in case of complex)
round(x,d): Round operand x to d decimal places, eg. round(22/7.0,3)=3.143
Strings:
Expressed in single ' or double " quotes
eg. 'this is a string', "t'is string"
String literals can span multiple lines in several ways,
#1. Using \
"this string literal \
span over multiple\n\
lines for fun"
#2. MultiLine Comments """ or '''
"""This is really
a multi-line string
spread over 3 lines"""
or
'''
this is also
a mutliline string
'''
Raw strings, ignore escape sequences
r'this is a raw\n\
spread over 2 lines'
prints 'this is a raw\n\ spread over 2 lines'
Strings can be,
Concatenated (glued together) with the + operator,
>>>'hello'+'World'
helloWorld
Repeated with *,
>>>'hello'*2
hellohello
Subscripted (indexed), like in C,
>>>y="hello"
>>>y[0]
'h'
>>>y[4]
'o'
Sliced to form substrings, using slice notation: two indices separated by a colon,
>>> word = 'Hello'
>>> word[0:2]
'He'
>>> word[2:4]
'll'
>>> word[:2] #omitted first index defaults to zero
'He'
>>> word[2:] #omitted second index defaults to the size of the string being sliced
'llo'
>>> word[0]='x' #Unlike a C string, Python strings cannot be changed
File I/O functions
-open(fname [,mode [,buffering ] ] ) -> Returns file object
mode = ( r-read , w-write , a-append )
+ [ + :Simultaneous read & write , U :Universal Newline i.e.line endings seen as \n in read mode, b :mode for BinaryFiles ]
buffering = 0 for unbuffered, 1 for line buffered, >1 specifies bufferSize
|
989b95b86a60078d41a5d50488531ea4a64d1138 | DuyguCiftci/lettergrade | /lettergradecalculator.py | 845 | 4.1875 | 4 | text = """
Letter Grade Calculation
"""
print(text)
num1 = int(input("Type your first midterm score: "))
num2 = int(input("Type your second exam score: "))
num3= int(input("Type your final exam score: "))
result = (num1*0.3)+(num2*0.3)+(num3*0.4)
print(result)
if result>=90:
print("Your letter grade is AA,excellent")
elif result>=85:
print("Your letter grade is BA,good")
elif result>=80:
print("Your letter grade is BB,good")
elif result>=75:
print("Your letter grade is CB,satisfactory")
elif result>=70:
print("Your letter grade is CC,satisfactory")
elif result>=65:
print("Your letter grade is DC,marginal pass")
elif result>=60:
print("Your letter grade is DD,marginal pass")
elif result>=50:
print("Your letter grade is FD,inadequate")
elif result>=0:
print("Your letter grade is FF,inadequate)
|
f449a89aaffc6e2395a1855dab842d8d5cced229 | RoboPlusPlus/Div-Python--JW | /HowTos/Import funcs/funcpy.py | 917 | 3.53125 | 4 |
#Takes two iterables, and makes a dictionary with them.
#If the two dicts are of different lenghts, the dict will be ass long as the shortest of the inputs
#inputs may be any combination of tuple, set, string or list.
def two_iters_dict(key_iter, value_iter):
dic={}
if len(key_iter) < len(value_iter):
dic_lenght = len(key_iter)
else:
dic_lenght = len(value_iter)
for i in range(0, dic_lenght):
dic.update({key_iter[i] : value_iter[i]})
return(dic)
##############################################################
"""
Ideer
Merge_iters: tar verdier fra to iterables, setter de inn på en string eller tuple sammen som en entry, og så returnerer liste med alle
list_a_column: Henter ut en kolonne fra input iterable. som
listIn = [(1,2,3),("a", "b", "c", "d"), (4, 5, 6, 7, 8, 9)]
listOut = list_a_column(listIn, 2)
print(listOut) ##prints [3, "c", 6]
"""
|
78b28dab5d2c7b79020ff93b17bbc4e0d73eefbd | Ankele/python_code | /algo/test_quick_sort.py | 845 | 3.953125 | 4 |
# -*- coding:utf-8 -*-
def quick_sort(li):
n = len(li)
if n < 2:
return
_quick_sort(li, 0, n-1)
def partition(li, left, right):
tmp = li[left]
while left < right:
while left < right and tmp <= li[right]:
right -= 1
li[left] = li[right]
while left < right and tmp > li[left]:
left += 1
li[right] = li[left]
li[left] = tmp
return left
def _quick_sort(li, left, right):
if left < right:
mid = partition(li, left, right)
_quick_sort(li, left, mid-1)
_quick_sort(li, mid+1, right)
def main():
# li = [5, 3, 2, 7, 9, 1, 8, 4, 6]
# quick_sort(li)
# print li
import random
li = list(range(100))
random.shuffle(li)
print li
quick_sort(li)
print li
if __name__ == '__main__':
main()
|
dbc4fde14b7035af0ea55ea3019ab6144b2452cd | KShih/workspaceLeetcode | /python/Mathwork_MaxValAmongShortestDisInAMatrix.py | 579 | 3.765625 | 4 | """
Given a grid with w as width, h as height.
Each cell of the grid represents a potential building lot and we will be adding "n" buildings inside this grid.
The goal is for the furthest of all lots to be as near as possible to a building.
Given an input n, which is the number of buildings to be placed in the lot,
determine the building placement to minimize the distance of the most distant empty lot is from the building.
https://stackoverflow.com/questions/52562585/maximal-value-among-shortest-distances-in-a-matrix
https://ideone.com/ix1nh8
"""
def find_loc(w, h, n):
|
b685e5091b6eec6dda0f14772c0729821911faea | Jonnylazzeri/hangman | /script.py | 1,054 | 4 | 4 |
import random
import hangman_words
import hangman_art
stages = hangman_art.stages
logo = hangman_art.logo
word_list = hangman_words.word_list
word = word_list[random.randint(0, len(word_list) - 1)]
word = list(word)
empty_word = ['_' for i in range(len(word))]
lives = 6
print(logo)
print(stages[lives])
print(' '.join(empty_word))
while '_' in empty_word:
letter_choice = input('Pick a letter: ')
if letter_choice in empty_word:
print(f"You've already used the letter {letter_choice}")
for index, letter in enumerate(word):
if letter_choice.lower() == letter:
empty_word[index] = letter_choice
print(' '.join(empty_word))
if ''.join(word).find(letter_choice) == -1:
print(f"You guessed {letter_choice}. {letter_choice} is not in the word. You lose a life!")
lives -= 1
print(stages[lives])
print(' '.join(empty_word))
if lives == 0:
joined_word = ''.join(word)
print('You Lose!')
print(f'The word was: {joined_word}')
break
if '_' not in empty_word:
print('You win!')
break
|
7130bea7baad8b27931ecb239c2b3e7bda67beec | SafonovMikhail/python_000403 | /000403_01_10_ex03_Div.py | 580 | 3.921875 | 4 | #000403_01_10_ex03_Div.py
a = int(input())
b = int(input())
if b != 0:
print(a/b)
else:
print("Деление невозможно, b = ", b)
# дополняем условие: просим еще раз ввести "b" (если произошел случай "else", просим еще раз ввести "b")
if b != 0:
print(a/b)
else:
# print("Деление невозможно, b = ", b)
b = int(input("Введите число, отличное от нуля: "))
if b == 0:
print("Неверно")
else:
print(a/b)
|
69d6c052d5c8669417bccb0f1509379e29b59abe | jacquelineramos8/567HW01 | /HW01_JacquelineRamos.py | 3,667 | 4.15625 | 4 | """
Author: Jacqueline Ramos
Assignment: HW01
Description: The code below receives triangle side input using the if __name__ == '__main__' function and classifies that triangle as:
equilateral, isosceles, scalene, right, or not a triangle. I left the code intentionally with bugs to demonstrate how
proper unit testing can catch these bugs.
"""
import unittest
def classify_triangle(a, b, c):
""" This function is meant to classify the triangle by its side lengths a, b, c and return that classification.
The triangle can be equilateral (all sides equal),
isosceles (two sides equal),
right (a^2 + b^2 = c^2),
scalene (all sides different lengths,
or not a triangle. """
if a == b and a == c:
return 'Equilateral Triangle'
elif a == b or b == c or c == a:
return 'Isosceles Triangle'
elif ((a ** 2) + (b ** 2)) == (c ** 2):
return 'Right Triangle'
elif (a + b <= c) or (b + c <= a) or (a + c <= b):
return 'Not a triangle!'
else:
return 'Scalene Triangle'
def run_classification(a, b, c):
""" This function prints the triangle classification. """
print('Triangle (',a,',',b,',',c,') classification:',classify_triangle(a,b,c))
class TestTriangles(unittest.TestCase):
""" This class holds the test cases for the classify_triangle function. """
def test_set1(self) -> None:
""" This first test set deomonstrates that appropriate side length inputs are classified correctly. """
self.assertEqual(classify_triangle(3,3,3), 'Equilateral Triangle')
self.assertEqual(classify_triangle(3,3,5), 'Isosceles Triangle')
self.assertEqual(classify_triangle(3,4,5), 'Right Triangle')
self.assertEqual(classify_triangle(3,5,7), 'Scalene Triangle')
self.assertEqual(classify_triangle(3,5,8), 'Not a triangle!')
def test_set2(self) -> None:
""" This test set ensures that triangles aren't accidentally labeled as isosceles or
that isosceles triangles aren't accidentally labeled as scalene """
self.assertNotEqual(classify_triangle(9,9,9), 'Isosceles Triangle')
self.assertNotEqual(classify_triangle(3,9,9), 'Scalene Triangle')
self.assertNotEqual(classify_triangle(9,3,9), 'Scalene Triangle')
def test_set3(self) -> None:
""" This test set is to see if right triangle side lengths input in various orders are still labeled as right triangles.
This test set should fail because my code classifies right triangles only as a^2 + b^2 = c^2 and does not take into account
the hypotenuse side being input as side a or b """
self.assertEqual(classify_triangle(5,4,3), 'Right Triangle') # the buggy code will label this triangle as scalene
def test_set4(self) -> None:
""" This test set tests invalid side lengths like 0 or negative numbers.
These tests should also fail because my code did not safeguard against invalid inputs with a try/except block """
self.assertEqual(classify_triangle(0,0,0), 'Not a triangle!') # the buggy code will label this triangle as equilateral
self.assertEqual(classify_triangle(-3,4,5), 'Not a triangle!') # the buggy code will label this triangle as right
if __name__ == '__main__':
""" Below I just print out some of the triangle classifications that I will be testing """
run_classification(3,3,3)
run_classification(3,3,5)
run_classification(3,4,5)
run_classification(3,5,7)
run_classification(3,5,8)
""" Below the unittest functions are called """
unittest.main(exit=False)
|
579c079561564841a91084ed9134ee971bd34e22 | BornRiot/Python.Udemy.Complete_Python_BootCamp | /methods_and_functions/scribbles/transform.py | 326 | 3.953125 | 4 | """This is my module docstring"""
# https://bit.ly/2CiRBog
the_list = [1,3,5,7,9,11,13,15,17,19,21]
the_tuple = tuple(the_list)
y = list(enumerate(the_tuple))
print("Here is Y:", y)
print(the_tuple)
for i, v in enumerate(the_tuple):
print("Here is the non enumerate", the_tuple[i])
print(type(the_tuple))
print(the_tuple)
|
62fafbe7e3b9d8f717103844722f6d774d12bb6c | tlxxzj/leetcode | /19. Remove Nth Node From End of List.py | 610 | 3.78125 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
h1, h2 = head, head
while n != 0:
n -= 1
h2 = h2.next
if not h2:
return head.next
while h2.next:
h1 = h1.next
h2 = h2.next
if h1.next:
h1.next = h1.next.next
else:
h1.next = None
return head
|
3b5f48d1b8ed72cb82509f52c86c3d3c5a53d220 | Yirogu/EasyPython | /python zajecia AI/zaj1/zad3.py | 953 | 3.609375 | 4 | import random
import statistics
import numpy
numbers = []
for x in range(0, 30):
randomNumber = random.randrange(100)
numbers.append(randomNumber)
print ("Wektor: ",numbers)
minimum = min(numbers)
maximum = max(numbers)
print ("Min: ", minimum)
print ("Max: ", maximum)
newNumbers = sorted(numbers)
print ("Posortowany wektor: ",newNumbers)
srednia = numpy.average(newNumbers)
print ("Średnia: ",srednia)
odchylenieStandardowe = statistics.stdev(numbers)
print("Odchylenie standardowe: ",odchylenieStandardowe)
#wektorZnormalizowany
wektorZnormalizowany = []
for x in range(0, 30):
wZ = (newNumbers[x]-minimum)/(maximum-minimum)
wektorZnormalizowany.append(wZ)
#Wektor standaryzowany
wektorStanryzowany =[]
for x in range(0, 30):
wS = (newNumbers[x]-srednia)/odchylenieStandardowe
wektorStanryzowany.append(wS)
print("Wektor znormalizowany: ", wektorZnormalizowany)
print("Wektor standaryzowany: ", wektorStanryzowany)
|
61c71a9b429f7d7f42e48e26b070b0d80204e363 | liviaasantos/curso-em-video-python3 | /mundo-1/ex013.py | 267 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun May 30 19:45:35 2021
@author: Livia Alves
"""
salário = float(input('Qual é o seu salário? R$'))
print('O funcionário que recebia R${:.2f}, com aumento de 15%, passará a receber R${:.2f}'.format(salário, salário*1.15))
|
114bded8d8bc98a945976ff5adcd890e393b0421 | taitujing123/my_leetcode | /333_largestBSTtree.py | 1,721 | 4.25 | 4 | """
给定一个二叉树,找到其中最大的二叉搜索树(BST)子树,其中最大指的是子树节点数最多的。
注意:
子树必须包含其所有后代。
示例:
输入: [10,5,15,1,8,null,7]
10
/ \
5 15
/ \ \
1 8 7
输出: 3
解释: 高亮部分为最大的 BST 子树。
返回值 3 在这个样例中为子树大小。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/largest-bst-subtree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def largestBSTSubtree(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root is None:
return 0
if root.left is None and root.right is None:
return 1
if self.validBST(root):
return countNode(root)
return max(self.largestBSTSubtree(root.left), self.largestBSTSubtree(root.right))
def validBST(node):
def helper(node, small, large):
if node is None:
return True
if node.val >= large or node.val <= small:
return False
return helper(node.left, small, node.val) or helper(node.right, node.val, large)
return helper(root, float('-inf'), float('inf'))
def countNode(node):
if node is None:
return 0
if node.left is None and node.right is None:
return 1
return self.countNode(node.left) + self.countNode(node.right) + 1 |
fd88625209ceb6fd6d80e07d70eca2b27cdd7cee | 17BTECO36/Tejeswini-kolekar | /program.py | 68 | 3.796875 | 4 | a=input("enter a value")
print(a)
int a,b,c;
a=10
b=20
print(c=a+b)
|
8bebab64cc70a010eca0112826864f4eb29d0bd2 | NirajPatel07/Data-Structures-Python | /Binary Tree/BinaryTree.py | 4,880 | 4.03125 | 4 | #Binary Tree Traversal
#1. Depth First Search
#2. Breadth First Search
#
#Depth First search is futher classified as
#1.1 PreOrder Traversal
#1.2 PostOreder Traversal
#1.3 InOrder Traversal
class stack(object):
def __init__(self):
self.items=[]
def push(self, value):
self.items.append(value)
def pop(self):
if not self.isEmpty():
return self.items.pop()
def isEmpty(self):
return len(self.items)==0
def __len__(self):
return self.size()
def size(self):
return len(self.items)
def peek(self):
if not self.isEmpty():
return self.items[-1].value
class Queue(object):
def __init__(self):
self.items=[]
def enqueue(self, value):
self.items.insert(0, value)
def dequeue(self):
if not self.isEmpty():
return self.items.pop()
def isEmpty(self):
return len(self.items)==0
def __len__(self):
return self.size()
def size(self):
return len(self.items)
def peek(self):
if not self.isEmpty():
return self.items[-1].value
class Node(object):
def __init__(self, value):
self.value=value
self.left=None
self.right=None
class BinaryTree(object):
def __init__(self,root):
self.root=Node(root)
def preorder(self, start, traversal):
""" root->left->right """
if start!=None:
traversal += (str(start.value)+"-")
traversal=self.preorder(start.left, traversal)
traversal=self.preorder(start.right, traversal)
return traversal
def inOrder(self, start, traversal):
"""left->root->right"""
if start!=None:
traversal=self.inOrder(start.left, traversal)
traversal += (str(start.value)+"-")
traversal=self.inOrder(start.right, traversal)
return traversal
def postorder(self, start, traversal):
if start!=None:
traversal=self.postorder(start.left, traversal)
traversal=self.postorder(start.right, traversal)
traversal += (str(start.value)+"-")
return traversal
def levelOrder(self, start):
if start is None:
return
q = Queue()
q.enqueue(start)
traversal=""
while len(q)>0:
traversal+=str(q.peek()) + "-"
node = q.dequeue()
if node.left:
q.enqueue(node.left)
if node.right:
q.enqueue(node.right)
return traversal
def reverseLevelOrder(self, start):
if start is None:
return
q=Queue()
s=stack()
q.enqueue(start)
while len(q)>0:
node=q.dequeue()
s.push(node)
if node.right:
q.enqueue(node.right)
if node.left:
q.enqueue(node.left)
traversal=""
while len(s)>0:
node=s.pop()
traversal+=str(node.value)+"-"
return traversal
def height(self, node):
if node is None:
return -1
left_height=self.height(node.left)
right_height=self.height(node.right)
return 1+max(left_height, right_height)
def size(self):
if self.root is None:
return 0
size=1
s=stack()
s.push(self.root)
while s:
node=s.pop()
if node.left:
size+=1
s.push(node.left)
if node.right:
size+=1
s.push(node.right)
return size
def printTree(self, traversal_type):
if traversal_type=="preorder":
return self.preorder(bt.root, "")
elif traversal_type=="inorder":
return self.inOrder(bt.root, "")
elif traversal_type=="postorder":
return self.postorder(bt.root, "")
elif traversal_type=="levelOrder":
return self.levelOrder(bt.root)
elif traversal_type=="reverseLevelOrder":
return self.reverseLevelOrder(bt.root)
else:
print("Wrong Traversal input")
bt=BinaryTree(1)
bt.root.left=Node(6)
bt.root.right=Node(5)
bt.root.left.left=Node(0)
bt.root.left.right=Node(4)
bt.root.right.left=Node(9)
bt.root.right.right=Node(7)
print(bt.printTree("preorder"))
print(bt.printTree("inorder"))
print(bt.printTree("postorder"))
print(bt.printTree("levelOrder"))
print(bt.printTree("reverseLevelOrder"))
print(bt.height(bt.root))
print(bt.size())
|
f01618ea94ce90c88c3a525ca0701452d9b38b59 | MuhiaKevin/Data-Structures-and-Algorithims | /Algorithims/Sort/bubblesort/bubblesort.py | 747 | 4.28125 | 4 | def bubblesort(array):
listlen = len(array)
swapped = True
while swapped:
swapped = False
for i in range(listlen - 1):
if array[i] > array[i + 1]:
temp = array[i] # save the current element of the array in a temporary element
array[i] = array[i + 1] # replace the position of the element with the next element of the list
array[i + 1] = temp # set the next element as the element of the current position
swapped = True
return array
array = [23,34,1,267,23,189,13,3,2,136,5,23]
print(bubblesort(array)) |
405d442ca55d9fd8a68a82dfbe3ce3ce7b848e4a | CCW22/Projects | /velocity_maker/combinations_std.py | 686 | 3.84375 | 4 | import itertools
import numpy as np
def lowest_std_comb(list_of_values, n):
"""
When a list is inputted, returns the lowest std calculation of a combination of 3 items
"""
list_of_std = []
y = list(itertools.combinations(list_of_values, n))
#print(y)
y = [t for t in y if 0 not in t]
for n in range (0,len(y)):
x = np.std(y[n])
list_of_std.append(x)
#print(list_of_std)
min_values = np.min(list_of_std)
#print(min_values)
index_std = list_of_std.index(min_values)
#print(index_std)
#print(y[index_std])
return y[index_std]
#x = lowest_std_comb([8.1,4.6,7.8,19.5],3)
#print(x)
|
c602339a6b868133afa95a9937f7a953443e5817 | ZayJob/OS-and-N | /Tasks/task1/task1.py | 761 | 3.765625 | 4 | import os
def search_files(search_dir, search_assignment):
result = []
for root, dirs, files in os.walk(search_dir):
for file_name in files:
if file_name.endswith(search_assignment):
result.append(file_name)
return result
def dump_to_file(result, file_to_write):
if not os.path.isfile(file_to_write):
file_to_write = 'result.txt'
with open(file_to_write, 'a') as wf:
wf.write('\n'.join(result))
def main():
search_dir = input('Enter the dir: ')
search_assignment = input('Enter the extension: ')
file_to_write = input('Enter file: ')
result = search_files(search_dir, search_assignment)
dump_to_file(result, file_to_write)
if __name__ == '__main__':
main() |
5dc7e4a56d290c3c7f5e9474d0b0a4960a70e837 | Glitchad/test | /Primes/Prime - Final.py | 515 | 4.125 | 4 | # define input variable
inputNum = int(
input("This program checks whether an integer is a prime. Please enter a number: ")
)
isPrime = None
if inputNum > 2:
for item in range(2, inputNum):
if (inputNum % item) == 0:
print(item, "*", inputNum // item, "=", inputNum)
isPrime = False
break
else:
isPrime = True
elif inputNum == 2:
isPrime = True
if isPrime:
print(inputNum, "is a prime!")
else:
print(inputNum, "is not a prime!")
|
2c7c1680effdeb6e2c94835de1a9fd3e5ea8b155 | varunbpatil/udemy_algorithms_python | /bst/bst.py | 2,218 | 3.828125 | 4 | class Node():
def __init__(self, data):
self.data = data
self.leftChild = None
self.rightChild = None
def traverse_inorder(self):
if self.leftChild:
self.leftChild.traverse_inorder()
print(self.data)
if self.rightChild:
self.rightChild.traverse_inorder()
def insert(self, data):
if data < self.data:
if not self.leftChild:
self.leftChild = Node(data)
else:
self.leftChild.insert(data)
else:
if not self.rightChild:
self.rightChild = Node(data)
else:
self.rightChild.insert(data)
def delete(self, data, parentNode):
if self.data == data:
if self.leftChild and self.rightChild:
self.data = self.rightChild.getMin()
self.rightChild.delete(self.data, self)
elif self == parentNode.leftChild:
tmp = self.leftChild if self.leftChild else self.rightChild
parentNode.leftChild = tmp
else:
tmp = self.leftChild if self.leftChild else self.rightChild
parentNode.rightChild = tmp
elif data < self.data:
if self.leftChild:
self.leftChild.delete(data, self)
else:
if self.rightChild:
self.rightChild.delete(data, self)
def getMin(self):
if self.leftChild:
return self.leftChild.getMin()
else:
return self.data
class BST():
def __init__(self):
self.root = None
def insert(self, data):
if not self.root:
self.root = Node(data)
return
self.root.insert(data)
def delete(self, data):
if self.root:
if self.root.data == data:
tempNode = Node(None)
tempNode.leftChild = self.root
self.root.delete(data, tempNode)
self.root = tempNode.leftChild
else:
self.root.delete(data, None)
def traverse_inorder(self):
if self.root:
self.root.traverse_inorder()
|
6a235270d14c37ae74c560ed3f9ad82f3d9c4e3a | Himanshu-jn20/PythonNPysparkPractice | /Practise_beginner/list.py | 275 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Sep 18 11:38:22 2020
@author: Himanshu
"""
numbers=[2,4,5,120,3,122]
print(len(numbers))
num2=numbers
print(num2)
lnum=numbers[0]
for num in numbers:
if lnum < num :
lnum=num
print(lnum)
|
8dd25ec3d9550ec6e3e0fcb253eddf8e6dc05303 | amanprodigy/cab-booking | /cabs/models/address.py | 827 | 3.671875 | 4 | from enum import Enum
class Country(Enum):
INDIA, USA = 'IND', 'USA'
class State(object):
def __init__(self, name: str, state_code: str, country: Country):
self.name = name
self.state_code = state_code
self.country = country
def __repr__(self):
return self.state_code
class City(object):
def __init__(self, name, state: State):
self.name = name
self.state = state
def __repr__(self):
return f"{self.name} ({self.state})"
class Address(object):
def __init__(self, street: str, city: City, zip_code: int):
self.__street_address = street
self.__city = city
self.__zip_code = zip_code
def getCity(self):
return self.__city
def __repr__(self):
return f"{self.__street_address} {self.__city}"
|
cf36d6217d9081a3f9d4bc309d462c228246fb86 | liudaoqiangtj/fuzzy-spoon | /python进阶.py | 3,605 | 3.796875 | 4 | #! /usr/bin/env python
# -*- coding:utf-8 -*-
#函数名和变量没有什么区别,只不过函数名是指向函数的变量名
from math import sqrt
def add(x,y,f):
return f(x)+f(y)
print(add(4,9,sqrt))
z = lambda x,y:x+y
import re
def format_name(s):
st0 = re.sub(r'.*',s[0].upper(),s)
st = re.sub(r'.*',s[1:].lower(),s)
return st0+st
print(list(map(format_name,['adam','LISA','barT'])))
#判断奇偶数
list(filter(lambda x:x%2==1,[1,4,6,7,9,12]))
#剔除为空的字符 \t \n \r
list(filter(lambda s:s and len(s.strip()) > 0, ['test',None,' ','str','\t','\n']))
#过滤掉1~100中平方根是整数的数
# list(filter(lambda x:isinstance(sqrt(x),int),range(1,101))) 这个不行因为sqrt()返回的值是float
list(filter(lambda x: int(sqrt(x)) ** 2 == x, range(1, 101)))
#自定义排序函数
sorted([1,3,2])
#定义返回函数的函数,这其实是个闭包
def calc_prod(lst):
def in_prod():
def f(x,y):
return x*y
return(reduce,f,lst)
return in_prod
f = calc_prod([1,2,3,4])
print(f())
#Closure外部函数返回内部函数的情况,内部函数引用外部函数变量,内部函数的参数是外部函数参数(是一个函数)的参数
def count():
fs = []
for i in range(1, 4):
def f():
return i*i
fs.append(f)
return fs
f1, f2, f3 = count()
print(f1(), f2(), f3())#将打印出9,9,9
#闭包内部函数定义不要引用任何外部函数的循环变量
#正确写法
def count():
print('count()')
fs = []
for i in range(1,4):
def f(j):
def g():
return j*j
print(j*j)
return g
r = f(i)#f内部函数不要引用循环变量
fs.append(r)
print(fs)
return fs
f1, f2, f3 = count()#此时f1,f2,f3返回的是
print(f1(),f2(),f3())#1,4,9
#无参数参数的装饰器函数
import time
def log(f):
def fn(*args,**kwargs):
t1 = time.clock()
r = f(*args,**kwargs)
t2 = time.clock()
print('call %s call time:%d' %(f.__name__(),t2-t1))
return r
return fn
@log
def factorial(n):
return reduce(lambda x,y:x+y,range(1, n))
print(factorial(6))
#装饰器 封装性,不改变原有代码新增功能,
#缺点:装饰器返回的函数已经不是原有的函数,所以依赖原有函数名的代码会失效,而且装饰器还改变了原有函数的__doc__属性
#如果要让调用者看不出一个函数经过装饰器的”改造“,就需要把原函数的一些属性复制到新函数中,functools
import functools
def log(f):
@functools.wraps(f)
def wrapper(*args,**kwargs):
print('call ...')
return f(*args,**kwargs)
return wrapper
@log
def f2(x):
pass
print(f2.__name__)#将会打印f2
#如果没有用functools来复制
import functools
def log(f):
#@functools.wraps(f)
def wrapper(*args,**kwargs):
print('call ...')
return f(*args,**kwargs)
return wrapper
@log
def f2(x):
pass
print(f2.__name__)#将会打印wrapper,依赖f2函数名的代码会失效,而且wrapper不会有f2的属性
#带参数的装饰器函数
#实现带参数的装饰器函数就需要三层嵌套的函数
import time,functools
def performance(unit):
def perf_decorator(f):
@functools.wraps(f)
def wrapper(*args,**kwargs):
t1 = time.time()
r = f(*args,**kwargs)
t2 = time.time()
t = (t2 - t1)*1000 if unit=='ms' else (t2-t1)
print('call %s() in %f %s' %(f.__name__,t,unit))
return r
return wrapper
return perf_decorator
@performance('ms')
def factorial(n):
return reduce(lambda x,y:x*y,range(1,n+1))
print(factorial(10))
#返回结果
#call factorial() in 0.000000 ms
# 3628800
#偏函数
import functools
int2 = funtools.partial(int,base=2)
int2('1000000')
#返回64 |
5aeacfe2ec0ec3213f96f632e1af30abf4da0f72 | abugasavio/mitx600.1x | /week1/05ps2.py | 339 | 3.609375 | 4 | s = 'jmeocobdobvjbb'
bob_count = 0
for index, letter in enumerate(s):
if letter == 'b':
try:
o, b = s[index + 1], s[index + 2]
except IndexError:
pass
else:
if o == 'o' and b == 'b':
bob_count += 1
print('Number of times bob occurs is: ' + str(bob_count))
|
9a639c345411ddd7ed6160403ad0373451c9305b | andrew-walsh-dev/practice-algorithms | /Algorithmic Interview Prep/longest_substring.py | 320 | 3.90625 | 4 | def longest_substring(str):
unique = ""
length = 0
for char in str:
if char not in unique:
unique += char
else:
#peel off the part of unique with the duplicate
unique = unique[unique.index(c)+1:] + c
length = max(length, len(unique))
return length
|
9ba56e95f6168350755dd97f6f2a0e1098bb9bde | UdhaikumarMohan/Strings-and-Pattern | /freq of char/sec_most.py | 809 | 4.03125 | 4 | # Write code to find the second most repeated word in a given sentence
def sec_rep(String):
freq = {}
Sentence = String.split()
for a in Sentence:
if a in freq:
freq[a]+=1
else:
freq[a]=1
max=0
sec_max=0
word=0
sec_max=0
li=[]
for a in freq:
if freq[a]>max:
sec_max=max
sec_word=word
max = freq[a]
word=a
for a in freq:
if freq[a]==sec_max:
li.append(a)
return li
String = """Indian Goverment cancelled the special status of jammu and kashmir,
and divided it into two union territories named kashmir and ladakh. These partition
was opposed by the state leaders of jammu and kashmir"""
print(sec_rep(String)) |
ee3d1d44f91ea6582ec28114874e68a49187100f | itb-ie/step-by-step-gui | /sixth.py | 1,233 | 3.890625 | 4 | import sys
import tkinter as tk
from tkinter.ttk import *
from ttkthemes import ThemedTk
def get_text():
entered_text = et_text.get()
lb2.config(text=entered_text)
# create a window, make it prettier, add functionality
window = ThemedTk(screenName="This is a title", theme="radiance")
# with ttk we need to configure styles:
style = Style()
style.configure("TButton", font=("Helvetica", 15, 'bold'), width=25)
style.configure("TLabel", font=("Arial", 25), anchor=tk.W, width=30, foreground="darkblue")
style.configure("TEntry", font=("Arial", 15), anchor=tk.W)
# a label
lb = Label(master=window, text="Enter a text")
lb.grid(row=0, column=0, padx=30, pady=20)
# an input field
et_text = tk.StringVar()
et = Entry(master=window, width=30, textvariable=et_text, font=("Helvetica", 25))
et.grid(row=0, column=1, padx=30, pady=20)
# anoter label to print into
lb2 = Label(master=window, text="")
lb2.grid(row=1, column=0, columnspan=3)
# a button
bt = Button(master=window, text="Get Text", command=get_text)
bt.grid(row=0, column=2, padx=50, pady=10)
# a button
bt2 = Button(master=window, text="EXIT", command=sys.exit)
bt2.grid(row=2, column=0, padx=30, pady=50, columnspan=3)
# the main loop
window.mainloop()
|
cbb6f4f7886ea6283d223a4de56e7701efea18c5 | nchristina2001/School-Projects | /Quadratic.py | 650 | 4.0625 | 4 | import math
def qudeq(a, b, c):
d = b ** 2 - 4 * a * c
if d >= 0:
print("The equation has real solutions")
x_2 = (-b - math.sqrt(b ** 2 - 4 * a * c)) / (2 * a)
x_1 = (-b + math.sqrt(b ** 2 - 4 * a * c)) / (2 * a)
print("x_1 = ", x_1)
print("x_2 = ", x_2)
else:
print("The equation does not have real solutions")
count = "y"
while count =="y":
a = float(input("Enter the value of a :"))
b = float(input("Enter the value of b :"))
c = float(input("Enter the value of c :"))
qudeq(a, b ,c)
count = input(" Enter y if continue, or n if not")
exit()
|
ad74e86a636f68a32f3f55f62aed0a3ab76588e6 | kdyskin/AdventOfCode | /2020/11/seatsPart2.py | 4,356 | 3.515625 | 4 | def readInput():
text_file = open("input.txt", "r")
lines = text_file.readlines()
#start with 0 -> charging outlet
input = []
for line in lines:
row = []
for c in line.strip():
row.append(c)
input.append(row)
text_file.close()
return input
def changeSeat(seatLayout,r,c):
n = 0
rows = len(seatLayout)
cols = len(seatLayout[0])
#NW direction
ir = r
ic = c
canMove = ((r-1)>=0 and (c-1)>=0)
while canMove:
ir -= 1
ic -= 1
if seatLayout[ir][ic] == "#":
n += 1
break
if seatLayout[ir][ic] == "L":
break
canMove = ((ir-1)>=0 and (ic-1)>=0)
#N direction
ir = r
ic = c
canMove = ((r-1)>=0)
while canMove:
ir -= 1
if seatLayout[ir][ic] == "#":
n += 1
break
if seatLayout[ir][ic] == "L":
break
canMove = ((ir-1)>=0)
#NE direction
ir = r
ic = c
canMove = ((r-1)>=0 and (c+1)<cols)
while canMove:
ir -= 1
ic += 1
if seatLayout[ir][ic] == "#":
n += 1
break
if seatLayout[ir][ic] == "L":
break
canMove = ((ir-1)>=0 and (ic+1)<cols)
#W direction
ir = r
ic = c
canMove = ((c-1)>=0)
while canMove:
ic -= 1
if seatLayout[ir][ic] == "#":
n += 1
break
if seatLayout[ir][ic] == "L":
break
canMove = ((ic-1)>=0)
#E direction
ir = r
ic = c
canMove = ((c+1)<cols)
while canMove:
ic += 1
if seatLayout[ir][ic] == "#":
n += 1
break
if seatLayout[ir][ic] == "L":
break
canMove = ((ic+1)<cols)
#SW direction
ir = r
ic = c
canMove = ((r+1)<rows and (c-1)>=0)
while canMove:
ir += 1
ic -= 1
if seatLayout[ir][ic] == "#":
n += 1
break
if seatLayout[ir][ic] == "L":
break
canMove = ((ir+1)<rows and (ic-1)>=0)
#S direction
ir = r
ic = c
canMove = (r+1)<rows
while canMove:
ir += 1
if seatLayout[ir][ic] == "#":
n += 1
break
if seatLayout[ir][ic] == "L":
break
canMove = ((ir+1)<rows)
#SE direction
ir = r
ic = c
canMove = ((r+1)<rows and (c+1)<cols)
while canMove:
ir += 1
ic += 1
if seatLayout[ir][ic] == "#":
n += 1
break
if seatLayout[ir][ic] == "L":
break
canMove = ((ir+1)<rows and (ic+1)<cols)
if seatLayout[r][c]=="#" and n>=5:
return True
if seatLayout[r][c]=="L" and n==0:
return True
return False
def shuffle(seatLayout):
rows = len(seatLayout)
cols = len(seatLayout[0])
shuffledSeatLayout = []
for row in seatLayout:
shuffledSeatLayout.append(row.copy())
for r in range(rows):
for c in range(cols):
if seatLayout[r][c] == ".":
continue
if changeSeat(seatLayout,r,c):
if seatLayout[r][c] == "L":
shuffledSeatLayout[r][c] = "#"
else:
shuffledSeatLayout[r][c] = "L"
drawMap(seatLayout)
print("Changes to:")
drawMap(shuffledSeatLayout)
print("")
return shuffledSeatLayout
def drawMap(seatLayout):
for row in seatLayout:
r = ""
for seat in row:
r += seat
print(r)
def compareLayouts(l1,l2):
rows = len(l1)
cols = len(l1[0])
for r in range(rows):
for c in range(cols):
if l1[r][c] != l2[r][c]:
return True
return False
def countOccupied(seatLayout):
rows = len(seatLayout)
cols = len(seatLayout[0])
count = 0
for r in range(rows):
for c in range(cols):
if seatLayout[r][c] == "#":
count += 1
return count
def main():
seatLayout = readInput()
changed = True
while changed:
newLayout = shuffle(seatLayout)
changed = compareLayouts(seatLayout,newLayout)
if changed:
seatLayout = newLayout
print(countOccupied(seatLayout))
if __name__ == "__main__":
main()
|
2249d5730e30d42ced6342065c1e1831a46e99dc | Sultansharav/08-31 | /Дасгалууд/d14.py | 895 | 4.09375 | 4 | # Өгөдсөн n тоо анхны /prime nubmer/ тоо мөн үү?
# анхны тоо гэж зөвхөн 1 болон өөртөө хуваагддаг эерэг тоог хэлнэ
'''
num = 11
# If given number is greater than 1
if num > 1:
# Iterate from 2 to n / 2
for i in range(2, num//2):
# If num is divisible by any number between
# 2 and n / 2, it is not prime
if (num % i) == 0:
print(num, "is not a prime number")
break
else:
print(num, "is a prime number")
else:
print(num, "is not a prime number")
'''
n = int(input())
if n > 1:
for i in range(2, n // 2):
if (n % i) == 0:
print(n, "бол анхны тоо биш")
break
else: print(n, "бол анхны тоо мөн")
else: print(n, "бол анхны тоо биш") |
3e179717f18781cc23993c9db7831dc982fe3628 | stickhog/non-programmers_tutorial_for_python_3 | /password1.py | 337 | 4.21875 | 4 | # asks for a name and a password
# checks them and determines if user is allowed in
name = input("Name?")
password = input("Password?")
if name == "Howard" and password == "douche123":
print("Welcome Howard")
elif name == "Spongebob" and password == "patrick":
print("Welcome Spongebob")
else:
print("I don't know you.") |
2dd8bcd97c9fc5030214d933c55c38f49e2b0a35 | konjakuc/python | /python-basic/经典算法案例/杨辉三角/杨辉三角test.py | 519 | 3.515625 | 4 | def triangles1(n):
a=[1]
print(' '*(n-1)+"1")
while len(a)<=n-1:
ar = [0] + a + [0]
a = [ar[x-1] + ar[x] for x in range(1,len(ar))]
for j in range(n-len(a)):
print(" ",end="")
for i in a:
print("%-2d"%i,end=" ")
print()
triangles1(8)
print("-"*30)
def triangles2(n):
a=[1]
while len(a)<=n-1:
ar = [0] + a + [0]
a = [ar[x-1] + ar[x] for x in range(1,len(ar))]
for i in a:
print(i,end=" ")
triangles2(8) |
16e50eb7ceebc68c8fca010b9ed9558ed53968f4 | isaaq1235/multipage_streamlit | /data.py | 1,479 | 3.828125 | 4 | import streamlit as st
def app(car_data):
st.header("Car Price Dataset")
with st.expander("Car Price Data"):
st.dataframe(car_data)
st.subheader("Columns Description:")
if st.checkbox("Show summary"):
st.table(car_data.describe())
beta_col1, beta_col2, beta_col3 = st.columns(3)
# Add a checkbox in the first column. Display the column names of 'car_df' on the click of checkbox.
with beta_col1:
if st.checkbox("Show all column names"):
st.table(list(car_data.columns))
# Add a checkbox in the second column. Display the column data-types of 'car_df' on the click of checkbox.
with beta_col2:
if st.checkbox("View column data-type"):
dtypes_list = list(car_data.dtypes)
dtypes = {
list(car_data.columns)[0] : dtypes_list[0],
list(car_data.columns)[1] : dtypes_list[1],
list(car_data.columns)[2] : dtypes_list[2],
list(car_data.columns)[3] : dtypes_list[3],
list(car_data.columns)[4] : dtypes_list[4]
}
st.write(dtypes)
# Add a checkbox in the third column followed by a selectbox which accepts the column name whose data needs to be displayed.
with beta_col3:
if st.checkbox("View column data"):
column_data = st.selectbox('Select column', tuple(car_data.columns))
st.write(car_data[column_data])
|
e5e87b0ab8bfec3e9adcd0005af65f43bda3b8b3 | diningphills/eulerproject | /problems/01~09/4/dy.py | 476 | 3.5625 | 4 | def GetRadixList(n):
list = []
if n < 10: return [n]
else:
radix = n % 10
list = GetRadixList(n/10)
list.append(radix)
return list
def isPalindrome(list):
for i in range(0, len(list)/2):
if list[i] != list[-(i+1)]: return False
return True
biggestPalindrome = 0
for i in range(100, 1000):
for j in range(i, 1000):
result = i*j
if isPalindrome(GetRadixList(result)) and biggestPalindrome < result:
biggestPalindrome = result
print(biggestPalindrome) |
8f2d0c8da7fd42d38a91ec095c1660de76acf975 | abditaresadabela/holbertonschool-higher_level_programming-1 | /0x07-python-test_driven_development/5-text_indentation.py | 1,128 | 4.46875 | 4 | #!/usr/bin/python3
"""
prints text in special format
"""
def text_indentation(text):
"""prints a text with 2 new lines after each of these characters: . ? :
Args:
text (str): a string
Raises:
TypeError: if text is not a string
"""
new = ""
substring = ""
temp = [] * 2
flag = 0
if type(text) is not str:
raise TypeError("text must be a string")
for i in range(len(text)):
if i < len(text) and text[i] == '.' or text[i] == '?'\
or text[i] == ':':
if flag == 0:
temp = text.split(text[i], 1)
flag = 1
else:
temp = substring.split(text[i], 1)
new += temp[0].lstrip(' ') + text[i]
substring = temp[1]
print("{:s}".format(new))
print()
new = ""
if flag == 0:
text = text.lstrip(' ')
text = text.rstrip(' ')
print("{:s}".format(text), end="")
else:
substring = substring.lstrip(' ')
substring = substring.rstrip(' ')
print("{:s}".format(substring), end="")
|
3ee6b6c0ca91b80db5e04f64223a2c289c25385c | HonourZhan/python_train | /sort algorithm/bubble sort.py | 740 | 3.515625 | 4 | from time import perf_counter
def bubble_sort_op(sequence):
for i in range(len(sequence)-1,0,-1):
flag=True
for j in range(i):
if sequence[j]>sequence[j+1]:
sequence[j],sequence[j+1]=sequence[j+1],sequence[j]
flag=False
if flag==True:
break
return sequence
def bubble_sort(sequence):
for i in range(len(sequence)-1,0,-1):
for j in range(i):
if sequence[j]>sequence[j+1]:
sequence[j],sequence[j+1]=sequence[j+1],sequence[j]
return sequence
if __name__=='__main__':
# li = [6,1,2,3,4,5]
li = [20,15,17,13,11,23,22,27]
print(li)
beg1=perf_counter()
bubble_sort(li)
end1=perf_counter()
beg2=perf_counter()
bubble_sort_op(li)
end2=perf_counter()
print(1000*(end1-beg1),1000*(end2-beg2))
# print(beg1) |
663d3a58a3f2c11cd2c96af665014b3dd2b14158 | yzl232/code_training | /mianJing111111/Google/ugly_numbers_Design an algorithm to find the kth number such that the only prime factors are 3,5, and 7.py | 2,724 | 3.828125 | 4 | # encoding=utf-8
'''
Design an algorithm to find the kth number such that the only prime factors are 3,5, and 7
'''
#G家最近考过
class Solution: #思想简单。 就是每次比较3, 5, 7的倍数哪个最小。 然后每次更新pointer
def primeN(self, n): #用了3个pointer来记录
c3 = c5 = c7 = 0
ret = [1]
for i in range(n):
m = min(ret[c3]*3, ret[c5]*5, ret[c7]*7)
ret.append(m)
if m == ret[c3]*3: c3+=1
if m == ret[c5]*5: c5+=1
if m== ret[c7]*7: c7+=1 #print '%d th element, %d, c3:%d, c5:%d, c7: %d' % (i, ret[i], c3, c5, c7)
return ret[-1]
s = Solution()
print s.primeN(15)
'''
Ugly numbers are numbers whose only prime factors are 2, 3 or 5. The sequence
1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, …
shows the first 11 ugly numbers. By convention, 1 is included.
Write a program to find and print the 150’th ugly number.
initialize
ugly[] = | 1 |
i2 = i3 = i5 = 0;
First iteration
ugly[1] = Min(ugly[i2]*2, ugly[i3]*3, ugly[i5]*5)
= Min(2, 3, 5)
= 2
ugly[] = | 1 | 2 |
i2 = 1, i3 = i5 = 0 (i2 got incremented )
Second iteration
ugly[2] = Min(ugly[i2]*2, ugly[i3]*3, ugly[i5]*5)
= Min(4, 3, 5)
= 3
ugly[] = | 1 | 2 | 3 |
i2 = 1, i3 = 1, i5 = 0 (i3 got incremented )
Third iteration
ugly[3] = Min(ugly[i2]*2, ugly[i3]*3, ugly[i5]*5)
= Min(4, 6, 5)
= 4
ugly[] = | 1 | 2 | 3 | 4 |
i2 = 2, i3 = 1, i5 = 0 (i2 got incremented )
Fourth iteration
ugly[4] = Min(ugly[i2]*2, ugly[i3]*3, ugly[i5]*5)
= Min(6, 6, 5)
= 5
ugly[] = | 1 | 2 | 3 | 4 | 5 |
i2 = 2, i3 = 1, i5 = 1 (i5 got incremented )
Fifth iteration
ugly[4] = Min(ugly[i2]*2, ugly[i3]*3, ugly[i5]*5)
= Min(6, 6, 10)
= 6
ugly[] = | 1 | 2 | 3 | 4 | 5 | 6 |
i2 = 3, i3 = 2, i5 = 1 (i2 and i3 got incremented )
Will continue same way till I < 150
'''
#G家这么考的。
'''
Given an equation in the form 2^i * 3^j * 5^k * 7^l where i,j,k,l >=0 are integers.write a program to generate numbers from that equation in sorted order efficiently.
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12
'''
class Solution2:
def primeN(self, n): #用了3个pointer来记录
c2 = c3 = c5 = c7 = 0
ret = [1]
for i in range(1, n+1):
m = min(ret[c2]*2, ret[c3]*3, ret[c5]*5, ret[c7]*7)
ret.append(m)
if m== ret[c2]*2: c2+=1
if m == ret[c3]*3: c3+=1
if m == ret[c5]*5: c5+=1
if m== ret[c7]*7: c7+=1
return ret
s = Solution2()
print s.primeN(10) |
f27f0cd95d853c6a397104c8df1a00b53dc41ecc | stormshadowcr7/python-sample-for-jenkins | /pyeg.py | 65 | 3.5625 | 4 |
for i in range(1,6):
print ("The loop number is: " + str(i)) |
211789bddd83b39afb76eaed515e5b944c7b06bb | dieg0palma/IntroPython | /string.py | 1,172 | 4.375 | 4 | # -*- coding: utf-8 -*-
# Para concatenar strings, usa-se o sinal de + :
ladoA = "Diego";
ladoB = "José";
nome = ladoA + " " + ladoB + "\n";
# Através da operação len, é possível checar o tamanho de uma string:
contar = len(nome);
print (contar);
# Há a possibilidade de se exibir certa posição de um item de um vetor;
# Deve-se atentar para o número de itens do vetor, para não chamar um item inexistente.
# É possível, também, imprimir parcialmente uma string:
print(ladoA[0] + ladoB[0]);
print(nome[0:2]);
#Como strings são objetos, strings são passiveis de serem atribuidas a métodos.
#P. ex, os métodos lower e upper, que deixam as letras em caixa baixa ou alta, respectivamente:
print(nome.lower());
print(nome.upper());
# A função strip também pode ser usada, neste caso para remover espaços e/ou caracteres especiais:
corte = nome.strip();
print (corte);
# Com a função split, é possível converter uma string em uma lista:
FIFA = "Janco Tiano";
FIFA = FIFA.split();
print(FIFA);
# Com a função find, posso fazer buscar dentro da minha string
busca = FIFA.find("T");
print(FIFA[busca:]); |
5ea440dba1e6d2ffafb7d588904b1bebef35e826 | RohanPankaj/FibonacciSequence | /CraigReverseFib.py | 367 | 3.515625 | 4 | # Code by Craig (The best)
# Copyright © 2019, Craig A Kelley, All Rights Reserved
# Free for commercial use
# Story boarded by Sai
def fSeq(n):
a = 0
b = 1
i = 0
while not (a == n):
i += 1
ph = a
a = b
b = ph + b
if (a > n):
print("Error")
break
print(i + 1)
fSeq(int(input("Number: "))) |
293c8d665dacf4206e365d9539fda51ec19ad132 | sidduGIT/Hacker-Rank- | /numpy_maths.py | 2,687 | 4 | 4 | '''
Basic mathematical functions operate element-wise on arrays. They are available both as operator overloads and as functions in the NumPy module.
import numpy
a = numpy.array([1,2,3,4], float)
b = numpy.array([5,6,7,8], float)
print a + b #[ 6. 8. 10. 12.]
print numpy.add(a, b) #[ 6. 8. 10. 12.]
print a - b #[-4. -4. -4. -4.]
print numpy.subtract(a, b) #[-4. -4. -4. -4.]
print a * b #[ 5. 12. 21. 32.]
print numpy.multiply(a, b) #[ 5. 12. 21. 32.]
print a / b #[ 0.2 0.33333333 0.42857143 0.5 ]
print numpy.divide(a, b) #[ 0.2 0.33333333 0.42857143 0.5 ]
print a % b #[ 1. 2. 3. 4.]
print numpy.mod(a, b) #[ 1. 2. 3. 4.]
print a**b #[ 1.00000000e+00 6.40000000e+01 2.18700000e+03 6.55360000e+04]
print numpy.power(a, b) #[ 1.00000000e+00 6.40000000e+01 2.18700000e+03 6.55360000e+04]
Task
You are given two integer arrays,
and of dimensions X
.
Your task is to perform the following operations:
Add (
+
)
Subtract (
-
)
Multiply (
*
)
Integer Division (
/
)
Mod (
%
)
Power (
**
)
Input Format
The first line contains two space separated integers,
and .
The next lines contains space separated integers of array .
The following lines contains space separated integers of array
.
Output Format
Print the result of each operation in the given order under Task.
Sample Input
1 4
1 2 3 4
5 6 7 8
Sample Output
[[ 6 8 10 12]]
[[-4 -4 -4 -4]]
[[ 5 12 21 32]]
[[0 0 0 0]]
[[1 2 3 4]]
[[ 1 64 2187 65536]]
Use // for division in Python 3.
'''
import numpy
#A=numpy.array([1,2,3,4,5],float)
#A=numpy.array([1,2,3,4,5],float)
A=numpy.array((3,2),float)
B=numpy.array((3,2),float)
print('printing both arrays')
print(A)
print(B)
print('addition of arrays')
print(A+B)
print(numpy.add(A,B))
print('substration of arrays')
print(A-B)
print(numpy.subtract(A,B))
print('multiplication of arrays')
print(A*B)
print(numpy.multiply(A,B))
print('devision of arrays')
print(A/B)
print(numpy.divide(A,B))
print('modul0 of arrays')
print(A%B)
print(numpy.add(A,B))
print('power of arrays')
print(A**B)
print(numpy.power(A,B))
n,m=map(int,input().split())
A=[[input().split() for j in range(n)] for i in range(n)]
B=[[input().split() for j in range(n)] for i in range(n)]
A=numpy.array(A,int)
B=numpy.array(B,int)
print(numpy.add(A,B))
print(numpy.subtract(A,B))
print(numpy.multiply(A,B))
print(A/B)
print(numpy.mod(A,B))
print(numpy.power(A,B))
print(A+B)
print(A-B)
print(A*B)
print(A/B)
print(A%B)
print(A**B)
|
c542dc69a1a65ebf0e25b06702add34ac69fa2ec | colinchambachan/GroceryMayhem | /main.py | 16,363 | 4.0625 | 4 | ##
# Grocery Collector game for CPT
#
# @author Colin Chambachan
# @course ICS3U
# @date June 8th, 2020
"""
Sample Python/Pygame Programs
Simpson College Computer Science
http://programarcadegames.com/
http://simpson.edu/computer-science/
Explanation video: http://youtu.be/4W2AqUetBi4
"""
import pygame
import random
import time
## Model
# Define some colors
BLACK = ( 0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
BLUE = (16, 140, 201)
class Player(pygame.sprite.Sprite):
""" Create a class for the main character of the game, that will be controlled by the user"""
## Methods
def __init__(self, x, y):
"""Constructor function"""
# Call the parent's constructor
super().__init__()
# Import the Image to be used as the main character
self.image = pygame.image.load("Player.png").convert()
self.image.set_colorkey(WHITE)
self.image = pygame.transform.scale(self.image, (67, 133))
# Make the image mappable
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
# Have an attrbute as to where the user is facing, this way the image can be flipped if they want to move the other way
self.direction_facing = "Left"
# Set speed vectors
self.change_x = 0
self.change_y = 0
def update(self):
"""Update the location of the player"""
self.rect.x += self.change_x
self.rect.y += self.change_y
def draw(self):
""" Blits the player onto the screen, and checks for the orientation inputted by the user, """
if self.direction_facing == "right":
screen.blit(pygame.transform.flip(self.image, True, False), [self.rect.x, self.rect.y])
else:
screen.blit(self.image, [self.rect.x, self.rect.y])
class FallingItem(pygame.sprite.Sprite):
""" Creating a class for the fruits in the game and bacteria, this will make it easier to animate and check for collision detection"""
## Methods
def __init__(self,filename,x,y):
"""Constructor Function"""
# inherites pygame.sprite.Sprite attributes
super().__init__()
## Attributes about the fruit
# Allows the fruits image to be chosen (or rather generated randomly)
self.image = pygame.image.load(filename).convert()
self.image.set_colorkey(BLACK)
self.image = pygame.transform.scale(self.image, (20, 20))
# Fetch the rectangle object that has the dimensions of the image.
self.rect = self.image.get_rect()
# Assign the beginning x and y values based off of the inputted values
self.rect.x = x
self.rect.y = y
def update(self,fallspeed):
# Update the sprite to look as though it is falling
self.rect.y += fallspeed
# Check to see if the item went off of the screen, and set it back to the top with a random x location
if self.rect.y > 350:
self.rect.y= random.randrange(-1000,0)
self.rect.x = random.randrange(screen_width)
def draw(self):
screen.blit(self.image, self.rect)
class TravellingBaby(pygame.sprite.Sprite):
""" Creating a class for the travlling baby that could take away points from the user"""
def __init__(self):
"""constructor function that inherites the attributes of the pygame.sprite.Sprite class"""
super().__init__
## Attributes about the traveling baby
# Declare the image used for the travelling baby, and transforming its scale so its not as big
self.image = pygame.image.load("BabyShoppingCart.png").convert()
self.image.set_colorkey(WHITE)
self.image = pygame.transform.scale(self.image, (50,50) )
# Fetch the rectangly that has the dimensions of the image
self.rect = self.image.get_rect()
# Since the baby is only travelling horizontally, the baby only need an x coordinate to deal with
# Assign a random coordinate off of the screen, so that the baby coming onto the screen seem to have a random change
self.rect.x = random.randrange(-1000,0)
def update(self):
""" Update the location of the baby as it travels horizontally"""
self.rect.x += 4
def draw(self):
"""Blit the image of the baby onto the screen, thus allowing for it take part in the game"""
screen.blit(self.image, (self.rect.x, 283))
def ScoreboardUpdate(score, timeLeft):
# Select the font to be used for score and timer
font = pygame.font.SysFont('Calibri', 25, True, False)
## Adjusting the score the user has
# Render the text to be printed
scoreText = font.render("Score: " + str(score), True, BLACK)
# Draw a rectangle on the screen under the score to make it more astheically pleasing
pygame.draw.rect(screen, BLUE, [595,320, 102, 28])
# Given the rectangle a slight outline
pygame.draw.rect(screen, BLACK, [595,320, 102, 28], 1)
# Drawing the score on the screen
screen.blit(scoreText, [600, 325])
## Adjusting the time left
timeRemainingText = font.render("Time: " + str(timeLeft), True,BLACK)
# Draw a rectangle on the screen under the score to make it more astheically pleasing
pygame.draw.rect(screen, BLUE, [0,0, 90, 28])
# Given the rectangle a slight outline
pygame.draw.rect(screen, BLACK, [0,0, 90, 28], 1)
# Drawing the time left onto the screen
screen.blit(timeRemainingText, [0,0])
# Create text to say that there are 30 seconds left
if timeLeft == 30:
warningfont = pygame.font.SysFont('Calibri', 45, True, True)
# Render the font for the text
ThirtySecondsLeft = warningfont.render("30 SECONDS REMAINING!", True, BLUE)
# Bliting the warning onto the screen
screen.blit(ThirtySecondsLeft, [125, 150])
def EndGameScreen(score):
# Create a computer reaction depending on the score of the user, and ouput the score dependantly
if score > 30:
# Playing the winning sound
game_won.play()
# Create the font to be used for the end game screen
endGameFont = pygame.font.SysFont("Calibri", 45, True, False)
computerReaction = "nice!"
# Render the text to be put onto the end game screen
endGameText = endGameFont.render("Your score was "+ str(score) + ", "+ str(computerReaction), False, BLACK )
# Create a rectangle that the text of the end game screen will be on
pygame.draw.rect(screen, BLUE, [100,125, 497, 75])
pygame.draw.rect(screen, BLACK, [100,125, 497, 75], 5)
# blit the text onto the screen
screen.blit(endGameText, (110, 135))
else:
# Playing the losing sound
game_lost.play()
# Create the font to be used for the end game screen
endGameFont = pygame.font.SysFont("Calibri", 39, True, False)
computerReaction = "better luck next time :("
# Render the text to be put onto the end game screen
endGameText = endGameFont.render("Your score was "+ str(score) + ", "+ str(computerReaction), False, BLACK )
# Create a rectangle that the text of the end game screen will be on
pygame.draw.rect(screen, BLUE, [0,125, 700, 75])
pygame.draw.rect(screen, BLACK, [0,125, 700, 75], 5)
# blit the text onto the screen
screen.blit(endGameText, (10, 135))
# Initialize Pygame
pygame.init()
# Open and Create Window
screen_width = 700
screen_height = 350
screen = pygame.display.set_mode([screen_width, screen_height])
pygame.display.set_caption("Grocery Mayhem!")
## Creating the sound of the game
# Music that going to played throughout the game
game_music = pygame.mixer.Sound("GameMusic.wav")
# Ambient music for the effect of being in a grocery store
ambient_noise = pygame.mixer.Sound("GroceryAmbience.wav")
# Adjusting the volume of the ambient noise to be quieter
ambient_noise.set_volume(0.5)
# Music to signify the end of the game and the user got a good score
game_won = pygame.mixer.Sound("GameWon.wav")
# Music to signify the end of the game and the user got a bad score
game_lost = pygame.mixer.Sound("GameLost.wav")
# Music that plays when either the fruit is caught or the bacteria is hit
fruit_hit = pygame.mixer.Sound("FruitCollected.wav")
bacteria_hit = pygame.mixer.Sound("BacteriaHit.wav")
# playing both the game music and the ambient music
game_music.play()
ambient_noise.play()
## Creating the images seen in the game
# Importing the backround image for the game
background_image = pygame.image.load("BackgroundImage.jpg").convert()
# Create the instance of the main character
main_character = Player(350,200)
# Create instance of the travelling baby
travelling_baby = TravellingBaby()
# Create a list of fruits so that the fruits generated a randomly chosen
possibleFruits = ["Apple.png","Banana.png","Melon.png","Orange.png", "Pear.png"]
# Use the pygame.sprite.group() to put all the falling fruits into one list and the bacteria in one list
fruits_list = pygame.sprite.Group()
bacteria_list = pygame.sprite.Group()
# Create a for loop that will create all the instances of the fruits
for i in range(100):
# Creates a random item selector which will pick (as an index parameter) which fruit is being loaded
itemSelector = random.randrange(5)
# Setting a random x location of the fruit and a random y location above the screen
GroceryFruit_x = random.randrange(screen_width)
GroceryFruit_y = random.randrange(-7500,0)
# Create the instance of the fruit
GroceryFruit = FallingItem(possibleFruits[itemSelector], GroceryFruit_x, GroceryFruit_y)
# Add the fruit to the list of objects
fruits_list.add(GroceryFruit)
# Create a for loop that will create all the instances of the bacteria
for i in range(20):
# Creates instances of the of the FallingItems
Bacteria_x = random.randrange(screen_width)
Bacteria_y = random.randrange(-9000,0)
bacteria = FallingItem("Bacteria.png",Bacteria_x, Bacteria_y)
# Add the instance to a list of all the bacteria
bacteria_list.add(bacteria)
# Create a counter that will be used as the 'timer' of the game
secondsLeft = 60
# Updates the pygame.USEREVENT every 1000 milliseconds, the equivalent of one second in the game, design used from https://stackoverflow.com/questions/30720665/countdown-timer-in-pygame
pygame.time.set_timer(pygame.USEREVENT, 1000)
# Create a variable that depicts the fall speed of the items, which can then be adjusted if the if the time is below a certain amount
fruitFallSpeed = 1
# Have a score variable that will be blit'd onto the screen
score = 0
# Loop until the user clicks the close button.
done = False
# Used to manage how fast the screen updates
clock = pygame.time.Clock()
# -------- Main Program Loop -----------
while not done:
## Control
# Check to see if any user action has occurred
for event in pygame.event.get():
# Check to the see if the user wants to quit the game
if event.type == pygame.QUIT:
done = True
# Check to see if any event as occured, and subtract one from the number of seconds left
if event.type == pygame.USEREVENT:
secondsLeft-= 1
# Check to see if the user wants to move a certain direction, including jumping, and adjust the attributes accrodingly
elif event.type == pygame.KEYDOWN:
# User wants to jump
if event.key == pygame.K_UP:
# Change the value of the characters y value to rise on the screen, and then eventually fall
main_character.change_y = -10
# User wants to move left
if event.key == pygame.K_LEFT:
main_character.change_x = -4
# change the orientation of the character, so that it will be drawn accordingly in the draw() method
main_character.direction_facing = "left"
# User wants to move right
elif event.key == pygame.K_RIGHT:
main_character.change_x = 4
# change the orientation of the character, so that it will be drawn accordingly in the draw() method
main_character.direction_facing = "right"
# Check tto see if the user wants to stop moving, and adjust the attributes accrodingly
elif event.type == pygame.KEYUP:
# User wants to stop jumping
if event.key == pygame.K_UP:
main_character.change_y = 10
# User wants to stop moving left
if event.key == pygame.K_LEFT:
main_character.change_x = 0
# User wants to stop moving right
elif event.key == pygame.K_RIGHT:
main_character.change_x = 0
# Check to see if the game ended (the timer ran out) and then break out of the while loop the game is running within
if secondsLeft <= 0:
done = True
# Check to see if the player went off of the screen and bring them back on the other side
if main_character.rect.x < 0:
main_character.rect.x = screen_width
if main_character.rect.x > screen_width:
main_character.rect.x = 0
# Check to see if the user jumped too high or is falling too far down and adjust accordingly
if main_character.rect.y < 150:
main_character.rect.y = 150
elif main_character.rect.y > 200:
main_character.rect.y = 200
# Check to see if it is the last 20 seconds of the game, and if it is, increase the fall speed of the items
if secondsLeft <= 30:
fruitFallSpeed = 2
# Check to see if the baby went off of the screen, and if so reassign its x coordinate
if travelling_baby.rect.x > screen_width:
travelling_baby.rect.x = random.randrange(-1000,0)
# Update the location of the player, fruits and the baby
main_character.update()
fruits_list.update(fruitFallSpeed)
bacteria_list.update(fruitFallSpeed)
travelling_baby.update()
# Check to see if the play hit any of the fruits, and if so reward them with a point
fruits_hit_list = pygame.sprite.spritecollide(main_character, fruits_list, True)
for GroceryFruit in fruits_hit_list:
# Play the good sound FX noise for hitting the fruit
fruit_hit.play()
# Increasing the score by one if the player gets the fruit
score += 1
bacteria_hit_list = pygame.sprite.spritecollide(main_character, bacteria_list, True)
# Check to see if the play hit any of the bacteria, and if so deduct a point
for Bacteria in bacteria_hit_list:
# Play the bad sound FX noise for hitting the bacteria
bacteria_hit.play()
# Decrease the score by one if the player gets the fruit
score -= 1
babyPlayerCollision = pygame.sprite.collide_rect(main_character,travelling_baby)
# Check for collision detection between the baby and the character
if babyPlayerCollision == True:
# Decrease the score by 5 if the character hits the baby
score -= 5
## View
# Clear the screen
screen.fill(WHITE)
# Blit the Backround onto the screen
screen.blit(background_image,[0,0])
# Draw the character, fruits, bacteria, and baby onto the given location
main_character.draw()
fruits_list.draw(screen)
bacteria_list.draw(screen)
travelling_baby.draw()
# Update and output the scoreboard and time left to the user
ScoreboardUpdate(score, secondsLeft)
# Go ahead and update the screen with what we've drawn.
pygame.display.flip()
# Limit to 60 frames per second
clock.tick(60)
# Blit the final score onto the screen using the EndGameScreen function
EndGameScreen(score)
pygame.display.flip()
# Make the window pause long enough for the user to read the end screen
time.sleep(5)
# Exit the window
pygame.quit() |
091ca401d76fb2a7b95edb4d85e5e03b302bb325 | aakashjha001/helloworld | /dictionary.py | 640 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jan 10 22:05:57 2019
@author: Aakash Jha
"""
#attributes of a song with dictionary
dictionary={}
dictionary["Genre"]="Pop"
dictionary["Artist"]="Shawn Mendes"
dictionary["Year"]=2017
print(dictionary)
def fun(key,value):
if key in dictionary:
if(dictionary[key]==value):
print("Correct guess")
return True
else:
print("Incorrect guess")
return False
else:
print("Incorrect guess")
return False
fun("Genre","Pop")
fun("Artist","Justin")
fun("Artist","Shawn Mendes")
|
839ee05f1596027f2541940995707fec59e3892a | Dustin461/projects | /various/iap_5_iteration.py | 12,511 | 4.375 | 4 | #! /usr/bin/env python2
"Interactive Python Part 5: Iteration and Repetition"
import random
from lib import cImage as image
def wandering_turtle():
"""Modify the walking turtle program so that rather than a 90 degree left or
right turn the angle of the turn is determined randomly at each step.
Modify the turtle walk program so that you have two turtles each with a random
starting location. Keep the turtles moving until one of them leaves the screen.
Modify the previous turtle walk program so that the turtle turns around when
it hits the wall or when one turtle collides with another turtle."""
u = turtle.Turtle()
u.shape("turtle")
u.color("green")
t.color("red")
for i in [t, u]:
i.penup()
i.setpos(random.randrange(-300,300), random.randrange(-300,300))
i.pendown()
while True:
for t1, t2 in [(t, u), (u, t)]:
coin = random.randrange(2)
angle = random.randrange(360)
if coin:
t1.left(angle)
else:
t1.right(angle)
t1.forward(50)
if t1.distance(0,0) > 390 or t1.distance(t2) < 25:
t1.setpos(0,0)
def turtlebar_3n(n, old_n):
colors = ("green", "blue", "red", "purple")
color = random.choice(colors)
t.fillcolor(color)
wn.setworldcoordinates(0, 0, 400, 200)
if t.distance(0,0) > 390:
return
t.begin_fill()
t.write(old_n)
t.left(90)
t.forward(n)
t.right(90)
t.write(n)
t.forward(10)
t.right(90)
t.forward(n)
t.left(90)
t.end_fill()
def sequence_3n(n=97):
count = 0
old_n = n
while n != 1:
if n % 2:
n = n * 3 + 1
else:
n /= 2
count += 1
print old_n, "to", n, "after", count, "iterations"
turtlebar_3n(count, old_n)
return (count, old_n)
def highest_count(start=100, end=200):
max_iters = 0
for i in range(start, end):
result = sequence_3n(i)
if result[0] > max_iters:
max_iters = result[0]
max_value = result[1]
print "Highest in range %s to %s was %s iterations for %s." % (start, end-1,
max_iters, max_value)
def sqrt_newton(n):
count = 0
guess = 0.5 * n
betterguess = 0.5 * (guess + n/guess)
while betterguess != guess:
guess = betterguess
betterguess = 0.5 * (guess + n/guess)
count += 1
print count, "iterations for",
return betterguess
def triangular(n=5):
num = 0
for i in range(1, n+1):
num += i
print num,
def isprime(n=936):
"""Write a function, is_prime, that takes a single integer argument and
returns True when the argument is a prime number and False otherwise."""
if n < 3: return False
for i in range(2, n):
if n % i == 0:
return False
return True
#########################
# Image Setup Functions #
#########################
def setup_image(img_file):
"Initialize image, get its size, draw a canvas and return these values"
# Read the image from the file.
oldimg = image.Image(img_file)
# And create a duplicate under newimg.
newimg = oldimg.copy()
# Map out width and height to display our image in.
width, height = oldimg.getWidth(), oldimg.getHeight()
win = image.ImageWin(img_file, width, height)
return oldimg, newimg, width, height, win
def write_image(img_file, newimg, win, func_name):
"Draw and save a processed image"
# This order will only save if the window gets clicked on.
newimg.draw(win)
win.exitonclick()
img_name, img_ext = strip_name(img_file)
newimg.save(img_name+func_name+img_ext)
def strip_name(img_file):
"Strips the name of a file into (pathname, extension)"
from os.path import splitext
return splitext(img_file)
##############################
# Image Standalone Functions #
##############################
def invert_image(img_file="cy.png"):
oldimg, newimg, width, height, win = setup_image(img_file)
for col in range(newimg.getWidth()):
for row in range(newimg.getHeight()):
p = newimg.getPixel(col,row)
p.red = 255 - p.red
p.green = 255 - p.green
p.blue = 255 - p.blue
newimg.setPixel(col,row,p)
write_image(img_file, newimg, win, "_inv")
def greyscale_image(img_file="cy.png"):
"Write a function to convert the image to grayscale."
oldimg, newimg, width, height, win = setup_image(img_file)
for col in range(newimg.getWidth()):
for row in range(newimg.getHeight()):
p = newimg.getPixel(col,row)
avg = (p[0]+p[1]+p[2])/3
p.red = p.green = p.blue = avg
newimg.setPixel(col,row,p)
write_image(img_file, newimg, win, "_grey")
def blackwhite_image(img_file="cy.png"):
"Write a function to convert an image to black and white."
oldimg, newimg, width, height, win = setup_image(img_file)
for col in range(newimg.getWidth()):
for row in range(newimg.getHeight()):
p = newimg.getPixel(col,row)
avg = (p[0]+p[1]+p[2])/3
if avg >= 128:
avg = 255
else:
avg = 0
p.red = p.green = p.blue = avg
newimg.setPixel(col,row,p)
write_image(img_file, newimg, win, "_bw")
def remred_image(img_file="cy.png"):
"Write a function to remove all the red from an image."
oldimg, newimg, width, height, win = setup_image(img_file)
for col in range(newimg.getWidth()):
for row in range(newimg.getHeight()):
p = newimg.getPixel(col,row)
p.red = 0
newimg.setPixel(col,row,p)
write_image(img_file, newimg, win, "_nored")
def sepia_image(img_file="cy.png"):
"""Sepia Tone images are those brownish colored images that may remind you
of times past. The formula for creating a sepia tone is as follows:
newR = (R × 0.393 + G × 0.769 + B × 0.189)
newG = (R × 0.349 + G × 0.686 + B × 0.168)
newB = (R × 0.272 + G × 0.534 + B × 0.131)
Write a function to convert an image to sepia tone. Hint: Remember that rgb
values must be integers between 0 and 255."""
oldimg, newimg, width, height, win = setup_image(img_file)
for col in range(newimg.getWidth()):
for row in range(newimg.getHeight()):
try:
p = newimg.getPixel(col,row)
p.red = int(p.red * 0.393 + p.green * 0.769 + p.blue * 0.189)
p.green = int(p.red * 0.349 + p.green * 0.686 + p.blue * 0.168)
p.blue = int(p.red * 0.272 + p.green * 0.534 + p.blue * 0.131)
newimg.setPixel(col,row,p)
except:
continue
write_image(img_file, newimg, win, "_sepia")
def double_image(img_file="cy.png"):
"Write a function to uniformly enlarge an image by a factor of 2 (double the size)."
# FIXME: Need to assign two values to unused_ here as this function needs
# two different (*2) values in their place.
oldimg, unused_newimg, width, height, unused_win = setup_image(img_file)
newimg = image.EmptyImage(width*2, height*2)
win = image.ImageWin(img_file, width*2, height*2)
for row in range(height):
for col in range(width):
oldpixel = oldimg.getPixel(col,row)
newimg.setPixel(2*col,2*row, oldpixel)
newimg.setPixel(2*col+1, 2*row, oldpixel)
newimg.setPixel(2*col, 2*row+1, oldpixel)
newimg.setPixel(2*col+1, 2*row+1, oldpixel)
write_image(img_file, newimg, win, "_double")
def smooth_image(img_file="cy_double.png"):
"""After you have scaled an image too much it looks blocky. One way of reducing
the blockiness of the image is to replace each pixel with the average values
of the pixels around it. This has the effect of smoothing out the changes in
color. Write a function that takes an image as a parameter and smooths the
image. Your function should return a new image that is the same as the old
but smoothed."""
oldimg, newimg, width, height, win = setup_image(img_file)
for col in range(newimg.getWidth()):
for row in range(newimg.getHeight()):
p = newimg.getPixel(col, row)
neighbors = []
# Put the 8 surrounding pixels into neighbors
for i in range(col-1, col+2):
for j in range(row-1, row+2):
try:
neighbor = newimg.getPixel(i, j)
neighbors.append(neighbor)
except:
continue
nlen = len(neighbors)
# Average out the RBG values
if nlen:
# Uncommented, the following line would leave most of the white
# untouched which works a little better for real photographs, imo.
#~ if nlen and p[0]+p[1]+p[2] < 690:
p.red = sum([neighbors[i][0] for i in range(nlen)])/nlen
p.green = sum([neighbors[i][1] for i in range(nlen)])/nlen
p.blue = sum([neighbors[i][2] for i in range(nlen)])/nlen
newimg.setPixel(col,row,p)
write_image(img_file, newimg, win, "_smooth")
#################################
# Functions belonging to pixmap #
#################################
def nored(p, *args):
p = image.Pixel(0, p.green, p.blue)
return p
def grey(p, *args):
avg = (p.red + p.green + p.blue)/3
p = image.Pixel(avg, avg, avg)
return p
def median(p, col, row):
"""When you scan in images using a scanner they may have lots of noise due
to dust particles on the image itself or the scanner itself, or the images
may even be damaged. One way of eliminating this noise is to replace each
pixel by the median value of the pixels surrounding it."""
neighbors = []
# Put the 8 surrounding pixels into neighbors
for i in range(col-1, col+2):
for j in range(row-1, row+2):
try:
neighbor = newimg.getPixel(i, j)
neighbors.append(neighbor)
except:
continue
nlen = len(neighbors)
if nlen:
red = [neighbors[i][0] for i in range(nlen)]
green = [neighbors[i][1] for i in range(nlen)]
blue = [neighbors[i][2] for i in range(nlen)]
# Sort the lists so we can later find the median.
for i in [red, green, blue]:
i.sort()
# If the list has an odd number of items in it.
if nlen % 2:
p.red = red[len(red)/2]
p.green = green[len(green)/2]
p.blue = blue[len(blue)/2]
else:
p.red = (red[len(red)/2] + red[len(red)/2-1])/2
p.green = (green[len(green)/2] + green[len(green)/2-1])/2
p.blue = (blue[len(blue)/2] + blue[len(blue)/2-1])/2
return p
def pixmap(img_file="cy.png", func=nored):
"""Write a general pixel mapper function that will take an image and a pixel
mapping function as parameters. The pixel mapping function should perform a
manipulation on a single pixel and return a new pixel."""
oldimg, blank, width, height, win = setup_image(img_file)
newimg = image.EmptyImage(width,height)
for col in range(width):
for row in range(height):
p = oldimg.getPixel(col, row)
new_p = func(p, col, row)
newimg.setPixel(col, row, new_p)
newimg.draw(win)
img_name, img_ext = strip_name(img_file)
# Func.__name__ probably will produce unwanted results here if using
# decorators or mocking the function but for now, we're leaving it.
newimg_name = img_name + "_" + func.__name__ + img_ext
newimg.save(newimg_name)
win.exitonclick()
#############
# Main Body #
#############
if __name__ == "__main__":
#~ print sqrt_newton(25)
#~ highest_count(100, 10000)
#~ triangular(10)
#~ for i in range(20):
#~ print i, isprime(i)
#~ import turtle
#~ wn = turtle.Screen()
#~ t = turtle.Turtle()
#~ t.shape("turtle")
#~ wandering_turtle()
#~ for i in range(150,200):
#~ sequence_3n(i)
#~ invert_image()
#~ greyscale_image()
#~ remred_image()
#~ blackwhite_image()
#~ sepia_image()
#~ smooth_image()
double_image()
pixmap("cy_double.png", grey)
|
51d481305b8cb97611cb7a1a426f69337ee144e8 | Sathyasree-Sundaravel/sathya | /Program_to_print_all_the_permutations_of_the_string_in_a_separate_line.py | 256 | 3.9375 | 4 | #Program to print all the permutations of the string in a separate line
from itertools import permutations
a=list(input())
p= permutations(a)
L=[]
for i in list(p):
s=''
for j in i:
s+=j
if s not in L:
L.append(s)
print(s)
|
7d386fb87918811363f8852540f0a1ecd5602fca | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_199/3442.py | 1,069 | 3.53125 | 4 | import csv
count = 1
length = 0
data = []
with open('problem_1_input.txt', 'rb') as csvfile:
reader = csv.reader(csvfile, delimiter= ' ')
for row in reader:
if count == 1:
length = row[0]
else:
data.append(row)
count += 1
def flip(array, start_index, num_flip):
#print "array: ", array, " start_index ", start_index, " num_flip ", num_flip
for i in range(num_flip):
if array[start_index + i] == '-':
array[start_index + i] = '+'
else:
array[start_index + i] = '-'
def check(array):
for i in array:
if i == '-':
return 0
return 1
case_num = 0
status = ''
for row in data:
case_num += 1
string = row[0]
num_flip = row[1]
array = list(string)
count = 0
for i in range(len(array) - int(num_flip) + 1):
if array[i] == '-':
flip(array, i, int(num_flip))
count += 1
if check(array) == 1:
status += 'Case #' + str(case_num) + ': ' + str(count) + '\n'
else:
status += 'Case #' + str(case_num) + ': IMPOSSIBLE' + '\n'
print status
with open('problem_1_output.txt', 'w') as out:
out.write(status)
|
22966d059bd2a8a436c8c65500b0136e36e3ace4 | davidadamojr/diary_of_programming_puzzles | /recursion_and_dynamic_programming/child_steps.py | 682 | 4.4375 | 4 | """
A child is running up a staircase with n steps, and can hope either 1 step,
2 steps, or 3 steps at a time. Implement a method to count how many possible
ways the child can run up the stairs.
"""
def count_ways(number_of_steps):
"""
The total number of ways of reaching the last step is therefore the
sum of the number of ways of reaching the last three steps
This solution is O(3^N) since there are three recursive calls at each level
"""
if number_of_steps < 0:
return 0
if number_of_steps == 0:
return 1
return count_ways(number_of_steps - 1) + count_ways(number_of_steps - 2) + \
count_ways(number_of_steps - 3)
|
73be1dfa59ad0d9871cc35badbb68d12fb5fb1b5 | Milstein-Corp/exercises | /reorder-log-files/main.py | 1,267 | 3.5625 | 4 | # Definition for singly-linked list.
def exam(x):
a = x.split(" ")
identifier = a[0]
firstentry = a[1]
if firstentry.isdigit():
metric = tuple([True])
else:
# metric = (False, len(a)) + tuple(a[1:]) + tuple(identifier)
metric = (False, len(a), a[1:]) + tuple(identifier)
print(metric)
return metric
class Solution(object):
def reorderLogFiles(self, lf):
lf.sort(key=exam)
return lf
if __name__ == '__main__':
logFiles = ["a1 9 2 3 1", "g1 act car", "zo4 4 7", "ab1 off key dog", "a8 act zoo"]
actual = Solution.reorderLogFiles(Solution, logFiles.copy())
desired = ["g1 act car", "a8 act zoo", "ab1 off key dog", "a1 9 2 3 1", "zo4 4 7"]
print("logFiles: " + str(logFiles))
print("desired : " + str(desired))
print("actual : " + str(actual))
assert actual == desired
print()
# a = ["mo"]
# b = ["mz"]
# print(str(a) + "<" + str(b) + ": " + str(a<b))
#
# a = ["ma"]
# b = ["mo"]
# print(str(a) + "<" + str(b) + ": " + str(a<b))
#
# a = ["mo"]
# b = ["mo", "a"]
# print(str(a) + "<" + str(b) + ": " + str(a<b))
#
# a = ["m", "w"]
# b = ["mo"]
# print(str(a) + "<" + str(b) + ": " + str(a<b))
|
abe1211d505721bce3bf37cd5633cf31097c56d7 | DarshanaPorwal07/Python-Programs | /%Calc.py | 532 | 4.03125 | 4 | total=int(input("enter the total marks:"))
sub1=int(input("enter the marks of 1st subject:"))
sub2=int(input("enter the marks of 2ns subject:"))
sub3=int(input("enter the marks of 3rd subject:"))
sub4=int(input("enter the marks of 4th subject:"))
sub5=int(input("enter the marks of 5th subject:"))
marks_obtained=sub1+sub2+sub3+sub4+sub5
print("---------------------------------------------")
print("Total marks obtained is: ",marks_obtained)
percentage=(marks_obtained/total)*100
print("Percentage is :",percentage)
|
02bf22a8b39ccd9e273780c22e32dfc7251031a4 | Susmit141/tusk | /pss.py | 536 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Jul 20 00:56:04 2019
@author: SUSHMIT
"""
def is_palindrome_v1(s):
""" (str) -> bool
Return True if and only if s is a palindrome.
>>> is_palindrome_v1('noon)
True
>>> is_palindrome_v1('dented')
False
"""
def reverse(s):
""" (str) -> str
Return a revered version of s.
>>> reverse('hello')
'olleh'
>>>reverse('a')
'a'
"""
rev= ''
# For each character in s,
|
4cdadd8f921a93b36e8e88a078ec5319d78c2ff4 | rodolphorosa/desafio-intelie | /schemaFacts.py | 7,765 | 3.75 | 4 | class SchemaFacts:
"""
This class provides the tools to visualize and manipulate facts and schema.
The constructor input comprises two lists of tuples: schema and facts.
"""
def __init__(self, schema, facts):
self.__schema = schema
self.__facts = facts
@staticmethod
def __retrieve_facts_by_entity(facts, entity):
"""
Given a list of facts and an entity, returns the facts that related to this entity.
:param facts: List of facts
:param entity: Entity's name
:return: Facts of the entity
"""
return list(filter(lambda f: f[0] == entity, facts))
@staticmethod
def __retrieve_facts_by_attribute(facts, attribute):
"""
Given a list of facts and an attribute, returns all the facts related to this attribute.
:param facts: List of facts
:param attribute: Attribute's name
:return: Facts of the attribute
"""
return list(filter(lambda f: f[1] == attribute, facts))
@staticmethod
def __retrieve_deleted_facts(facts):
"""
Given a list of facts, returns the ones whose field 'added' has value False
:param facts: List of facts
:return: Facts with added False
"""
return list(filter(lambda f: f[3] is False, facts))
@staticmethod
def __retrieve_non_deleted_facts(facts):
"""
Given a list of facts, returns the ones whose field 'added' has value True
:param facts: List of facts
:return: Facts with added True
"""
return list(filter(lambda f: f[3] is True, facts))
@staticmethod
def __retrieve_attribute_by_name(schema, attribute):
"""
Given a schema and an attribute, returns the tuple corresponding to this attribute
:param schema: List of attributes
:param attribute: Attribute's name
:return: Tuple of attribute
"""
return list(filter(lambda a: a[0] == attribute, schema))[0]
@staticmethod
def __drop_facts_by_attribute(facts, attribute):
"""
Given a list of facts and an attribute, deletes the facts related to this attribute
:param facts: List of facts
:param attribute: Attribute's name
:return: None
"""
for fact in facts:
if fact[1] == attribute:
facts[facts.index(fact)] = (fact[0], fact[1], fact[2], False)
@staticmethod
def __drop_facts_by_entity(facts, entity):
"""
Given a list of facts and an entity, deletes the facts related to this entity
:param facts: List of facts
:param entity: Entity's name
:return: None
"""
for fact in facts:
if fact[0] == entity:
facts[facts.index(fact)] = (fact[0], fact[1], fact[2], False)
def get_schema(self):
"""
Returns the list of all attributes (schema).
:return: Schema
"""
return self.__schema
def get_facts(self):
"""
Returns the list of all facts (current or not).
:return: All facts.
"""
return self.__facts
def get_attribute(self, attribute):
"""
Returns the tuple corresponding to an attribute.
:param attribute: Attribute's name
:return: Attribute's corresponding tuple.
"""
return self.__retrieve_attribute_by_name(self.__schema, attribute)
def get_current_facts(self):
"""
This method is responsible for retrieving all current facts.
:return: list of all current fats.
"""
deleted_facts = self.__retrieve_deleted_facts(self.__facts)
non_deleted_facts = self.__retrieve_non_deleted_facts(self.__facts)
current_facts = []
for attribute in self.__schema:
facts_by_attribute = self.__retrieve_facts_by_attribute(non_deleted_facts, attribute[0])
if attribute[2] == 'one':
for entity in set([f[0] for f in facts_by_attribute]):
current_facts.append(self.__retrieve_facts_by_entity(facts_by_attribute, entity)[-1])
else:
current_facts += facts_by_attribute
for df in deleted_facts:
for cf in current_facts:
if cf[0:3] == df[0:3]:
current_facts.remove(cf)
return current_facts
def insert_attribute(self, attribute, cardinality):
"""
Verifies if attribute already exists in the schema, and then inserts it to it if it does not.
:param attribute: Attribute to be inserted.
:param cardinality: Attribute's cardinality ('one' or 'many')
:return: None
"""
if attribute in [s[0] for s in self.__schema]:
raise Exception("Attribute already exists")
else:
self.__schema.append((attribute, 'cardinality', cardinality))
def insert_fact(self, entity, attribute, value):
"""
First verifies if attribute exists, and then inserts the fact into the fact list.
:param entity: Entity of the fact.
:param attribute: Attribute of the entity.
:param value: Value of the attribute.
:return: None
"""
if attribute not in [s[0] for s in self.__schema]:
raise Exception("Attribute \'{0}\' not in schema".format(attribute))
else:
self.__facts.append((entity, attribute, value, True))
def update_attribute(self, attribute, cardinality):
"""
Verifies if attribute exists, and the update its cardinality.
:param attribute: Attribute's name.
:param cardinality: New cardinality.
:return: None
"""
if attribute not in [s[0] for s in self.__schema]:
raise Exception("Attribute not found")
else:
for attr in range(len(self.__schema)):
if self.__schema[attr][0] == attribute:
self.__schema[attr] = (attribute, 'cardinality', cardinality)
def delete_attribute(self, attribute):
"""
Deletes an attribute of schema, if it exists.
:param attribute: Attribute's name.
:return: None
"""
attr = [attr for attr in self.__schema if attr[0] == attribute]
if len(attr) == 0:
raise Exception("Attribute \'{0}\' not in schema".format(attribute))
else:
self.__schema.remove(attr[0])
self.__drop_facts_by_attribute(self.__facts, attribute)
def delete_fact(self, entity, attribute, value):
"""
Deletes a fact of the fact list.
:param entity: Entity of the fact.
:param attribute: Attribute of the fact.
:param value: Value of the attribute.
:return: None
"""
self.__facts.append((entity, attribute, value, False))
if __name__ == '__main__':
facts = [
('entity/1', 'name', 'gabriel', True),
('entity/1', 'address', 'av rio branco, 109', True),
('entity/2', 'address', 'rua alice, 10', True),
('entity/2', 'name', 'joão', True),
('entity/2', 'address', 'rua bob, 88', True),
('entity/2', 'phone', '234-5678', True),
('entity/2', 'phone', '91234-5555', True),
('entity/2', 'phone', '234-5678', False),
('entity/1', 'phone', '98888-1111', True),
('entity/1', 'phone', '56789-1010', True),
('entity/2', 'address', 'rua bob, 88', False)
]
schema = [
('name', 'cardinality', 'one'),
('address', 'cardinality', 'one'),
('phone', 'cardinality', 'many')
]
sf = SchemaFacts(schema, facts)
for fact in sf.get_current_facts():
print(fact)
|
0e1703d1b0dee1492b2626faffc82f691130a605 | anishLearnsToCode/python-workshop-7 | /day_1/complex_list.py | 249 | 3.9375 | 4 | a = [True, False, 10, 3.14, 'hello', [1, 4, 5, 6, 7, 100, -45], print, range(1, 10, 2)]
# print(a[5])
# numbers = a[5]
a[6]('hello', end='-----')
print()
b = print
b('this is also print', end=' hello there')
# for item in a[5]:
# print(item)
|
cffce6cbbdbe718964df1ac741fdda974f8f1fe7 | duoarc/basecamp_basic_tasks | /tech_trial/Task_3.py | 1,087 | 4.375 | 4 | #! /usr/bin/env python3
import Task_2
def list_primes(list_of_num):
"""
Returns a list of prime numbers
Parameters:
list_of_num (list): List of positive integers
Returns:
list_prime (list): List of prime numbers in list_of_num
"""
# Check if the list of integers has any negative numbers
for num in list_of_num:
if num < 0:
return "Please provide positive numbers only and try again"
# Handle Zeroes
if 0 in list_of_num:
return "Please provide positive numbers only and try again. Zero is not a positive number!"
# Initialise variable to hold prime numbers
list_prime = []
# Loop over list numbers in list
for num in list_of_num:
# Check number is a prime number
if Task_2.is_prime(num):
# Append number to prime number list if it is prime
list_prime.append(num)
# Return prime number list
return list_prime
"""
# Tests
print(list_primes([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25]))
""" |
f41651b02602482dbc0fdeded16b2eb3497a4640 | chukgu/Algorithm | /LeetCode/344_Reverse String.py | 323 | 3.78125 | 4 | class Solution:
def reverseString(self, s: list[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
s.reverse()
print(s)
if __name__ == "__main__":
s = Solution()
s.reverseString(["h","e","l","l","o"])
s.reverseString(["H","a","n","n","a","h"]) |
ec1f8a73ab4bd037fa2b2a05b0f39079f5799e14 | MariaBet/EstudosPython | /aulas/Classe/Desafio/banco/conta.py | 488 | 4 | 4 | from abc import ABC, abstractmethod
class Conta(ABC):
def __init__(self, agencia, conta, saldo):
self.agencia = agencia
self.conta = conta
self.saldo = saldo
def depositar(self, valor):
self.saldo += valor
self.detalhes()
def detalhes(self):
print(f'Agência: {self.agencia}', end=" ")
print(f'Conta: {self.conta}', end=" ")
print(f'Saldo: {self.saldo}')
@abstractmethod
def sacar(self, valor): pass |
0abe64186ac98b3f7fc9c1542e085f41c7a07d92 | mcole22266/pythonTutorial | /Exercise02-Strings/strings.py | 2,138 | 4.3125 | 4 | #----------------------------------------------------------------------
#
# Problem 1
#
# In Robert McCloskey’s book Make Way for Ducklings, the names of the
# ducklings are Jack, Kack, Lack, Mack, Nack, Ouack, Pack, and
# Quack. This loop tries to output these names in order.
#
# prefixes = "JKLMNOPQ"
# suffix = "ack"
#
# for p in prefixes:
# print(p + suffix)
#
# Of course, that’s not quite right because Ouack and Quack are
# misspelled.
#
# Create a function, called ducklings, that prints out the correct
# names for the ducklings
def ducklings():
prefixes = "JKLMNOPQ"
suffix = "ack"
#----------------------------------------------------------------------
#
# Problem 2
#
# Create a function, called twelve_table, that prints out a neatly
# formatted multiplication table, up to 12 x 12.
#
def twelve_table():
#----------------------------------------------------------------------
#
# Problem 3
#
# Write a function, called reverse_string, that reverses its string
# argument.
#
def reverse_string(string):
#----------------------------------------------------------------------
#
# Problem 4
#
# Write a function, remove_letter, that removes all occurrences of a
# given letter from a string.
#
def remove_letter(string, removeChar):
#----------------------------------------------------------------------
#
# Problem 5
#
# Write a function, count_substring, that counts how many
# non-overlapping occurences of a substring appear in a string. Takes
# two parameters, a string and a substring to count
def count_substring(string, substring):
# FOR TESTING ---------------------------------------------------------
# ---------------------------------------------------------------------
# Problem 1:
assert ducklings() == 'Jack Kack Lack Mack Nack Ouack Pack Quack'
# Problem 2:
print('Should be a multiplication table: 12x12')
twelve_table()
# Problem 3:
assert reverse_string('Hello World') == 'dlroW olleH'
assert reverse_string('12345') == '54321'
# Problem 4:
assert remove_letter('Hello World', 'l') == 'Heo Word'
# Problem 5:
assert count_substring('Bippity Boppity Boo', 'pity') == 2
|
fc4c783cc026f19ce5f2e40c154c11d052d8e1ed | RyanUkule/Python_Demo | /01.py | 119 | 3.84375 | 4 | # -*- coding: UTF-8 -*-
# Python
num = input('请输入数字:')
if num == 1:
pass
else:
print('not equal to 1')
|
55c2f96a64984a2df8962f5dc65136172df188ef | Zufru/Blackjack__ | /project_2.py | 2,494 | 4 | 4 | import random
suits = ('Hearts', 'Diamonds', 'Clubs', 'Spades')
ranks = ['Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight',
'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace']
values = {'Two': 2, 'Three': 3, 'Four': 4, 'Five': 5, 'Six': 6, 'Seven': 7, 'Eight': 8,
'Nine': 9, 'Ten': 10, 'Jack': 11, 'Queen': 11, 'King': 11, 'Ace': 11}
class Card:
"""
CARD CLASS, DESCRIBES CARDS AND SETS THEM
"""
def __init__(self, suit, rank):
self.suit = suit
self.rank = rank
self.value = values[rank]
def __str__(self):
return self.rank + " of " + self.suit
class Deck:
"""
DECK CLASS SHUFFLY, STAY, DEAL CARDS
"""
def __init__(self):
self.all_cards = []
self.new_cards = []
for suit in suits:
for rank in ranks:
created_cards = Card(suit, rank)
self.all_cards.append(created_cards)
def shuffle(self):
return random.shuffle(self.all_cards)
def stay(self):
pass
def deal_one(self):
return self.all_cards.pop()
def __str__(self):
return self.rank + " of " + self.suit
class Player:
"""
PLAYER CLASS DEFINING BET AND SAVING IT TO PLAYER_BET IF PLAYER WINS
"""
player_bet = int(0)
def __init__(self, player, balance):
self.player = player
self.balance = balance
def betchips(self):
how_much_bet = int(input("How much would you like to bet? "))
if self.balance > how_much_bet:
player_bet = how_much_bet
self.balance -= player_bet
print(f"You have bet ${player_bet} on this hand!")
elif self.balance < how_much_bet:
print(f"You only have ${self.balance} you can not bet more than that!")
def __str__(self):
return self.player + ' has a balance of ' + str(self.balance)
def information():
"""
JUST AN INFORMATION SECTION
"""
info2 = print("************************************|HOW TO PLAY|********************************************")
info3 = print("**** All cards are equivalent to their stated value. ****")
info4 = print("**** Face cards hold a value of 11. ****")
info5 = print("**** A face card with a ACE on your first two cards is a blackjack. ****")
info6 = print("**** Blackjack doubles your bet. ****")
info7 = print("*********************************************************************************************")
|
9072d786fa2326cd7995ac3dcd4cba060c96ba11 | Castaldo/US-Mortgage-Analysis | /Data/Pre_Processing.py | 804 | 3.515625 | 4 | import pandas as pd
Mortgage = pd.read_csv('Data/Unprocessed/hmda_2017_nationwide_all-records_labels.csv')
Mortgage = Mortgage[(Mortgage['loan_purpose_name'] == 'Refinancing')]
Mortgage = Mortgage[(Mortgage['action_taken'] <= 3)]
Mortgage.drop(Mortgage.columns[[0, 1, 2, 3, 5, 7, 9, 10, 11, 14, 15, 16, 18, 26, 28, 32, 33, 34, 35, 36, 37,
38, 39, 40, 42, 43, 44, 45, 46, 47, 48, 49, 52, 55, 57, 58, 59, 60, 61, 62, 63, 64,
65, 66, 68, 69, 70, 77]], axis=1, inplace=True)
def f(row):
if row['action_taken'] < 3:
val = 1
else:
val = 0
return val
Mortgage['Loan_Accepted'] = Mortgage.apply(f, axis=1)
del Mortgage['action_taken']
Mortgage.to_csv(r'Data/Processed/Mortgage.csv', index=False)
print('Mortgage Data Processed')
|
4c77444af8e976b71936c870895662e017499650 | bindingofisaac/projecteuler | /python/problem_15.py | 199 | 3.828125 | 4 | """
Lattice Paths
Number of paths from (0,0) to (a,b) -> (20, 20) = (a+b)!/(a!*b!)
"""
def fac(n):
ans = 1
for i in range(2, n+1): ans = ans*i
return ans
print (fac(40))/(fac(20)**2)
|
640fe33acec1444f949e67eb5c1b28a84212992e | InonCohen/Mtm | /ex3/gradesCalc.py | 4,941 | 4.09375 | 4 | #### PART 1 ####
# final_grade: Calculates the final grade for each student, and writes the output (while eliminating illegal
# rows from the input file) into the file in `output_path`. Returns the average of the grades.
# input_path: Path to the file that contains the input
# output_path: Path to the file that will contain the output
def final_grade(input_path: str, output_path: str) -> int:
"""
final_grade: Calculates the final grade for each student, and writes the output (while eliminating illegal
rows from the input file) into the file in `output_path`.
:param input_path: Path to the file that contains the input
:param output_path: Path to the file that will contain the output
:return: Average final grades if legal rows were found, zero otherwise.
"""
avg_final_grades = 0
grades_data = create_grades_data(input_path)
grades_to_file(output_path, grades_data)
if grades_data:
final_grades = list(map(lambda data: data["student_final_grade"], grades_data.values()))
avg_final_grades = int(sum(final_grades) / len(grades_data))
return avg_final_grades
def create_grades_data(input_path: str) -> dict:
"""
create_grades_data: Do the following foreach student in input file:
- Eliminating illegal rows from the input file (see: `is_valid_input`).
- If row is legal, creates grades data of student, consisted of:
- unique id (last record in file)
- homework_avg
- student_final_grade
:param input_path:
:return: grades_data
"""
separator = ','
student_data_keys = ['name', 'semester', 'homework_avg']
grades_data = dict()
with open(input_path) as input_file:
lines = input_file.readlines()
for line in lines:
input_data_values = list(filter(lambda char: char != separator, line.split(separator)))
input_data_values = list(map(str.strip, input_data_values))
student_id = input_data_values[0].strip()
student_data_values = input_data_values[1:]
student_data = dict(zip(student_data_keys, student_data_values))
if is_legal_line_data(student_id, student_data):
homework_avg = int(student_data["homework_avg"])
student_final_grade = calculate_final_grade(student_id, homework_avg)
grades_data[student_id] = {"homework_avg": homework_avg,
"student_final_grade": student_final_grade}
return grades_data
def grades_to_file(output_path: str, grades_data: dict):
"""
grades_to_file: Writes grades data into txt file.
:param output_path: Path of file to write into
:param grades_data: Grades data dict to write from
:return:
"""
with open(output_path, 'w') as output_file:
for student_id, grades_data in sorted(grades_data.items()):
student_str = "{student_id}, {homework_avg}, {student_final_grade}\n". \
format(student_id=student_id,
homework_avg=grades_data["homework_avg"],
student_final_grade=grades_data["student_final_grade"])
output_file.write(student_str)
def is_legal_line_data(student_id: str, student_data: dict) -> bool:
"""
is_legal_line: Check if a given data of line if it's legal, as follows:
- Id has 8 digits and can't start with 0.
- Name is consisted of [A-Za-z] and spaces only
- Semester is bigger or equal to 1
- Average grades is bigger than 50 and at most 100
:param student_id: Id of the student to check
:param student_data: Data of student: <name (string)>, <semester (int)>, <homework avg (int)>
:return:
"""
valid_min_grade = 50
valid_max_grade = 100
valid_id_len = 8
valid_min_semester = 1
return all([
len(str(student_id)) == valid_id_len,
int(str(student_id)[0]) != 0,
student_data.get('name').replace(' ', '').isalpha(),
int(student_data.get('semester')) >= valid_min_semester,
valid_min_grade < int(student_data.get('homework_avg')) <= valid_max_grade
])
def calculate_final_grade(student_id: str, homework_avg: int) -> int:
"""
calculate_final_grade: Calculate final grade for a given student:
(two last digits of id + homework_avg) / 2.
:param homework_avg: Average homework of the student
:param student_id: Id of the student
:return: final grade
"""
return int((int(student_id[-2:]) + homework_avg) / 2)
#### PART 2 ####
# check_strings: Checks if `s1` can be constructed from `s2`'s characters.
# s1: The string that we want to check if it can be constructed
# s2: The string that we want to construct s1 from
def check_strings(s1: str, s2: str) -> bool:
letters = list(char for char in s2.lower())
for letter in s1.lower():
if letter in letters:
letters.remove(letter)
else:
return False
return True
|
5775ebf5a84658fc28aaba65a548a0db3e8a1ef5 | bettinson/programming-assignments | /235assignment1.py | 652 | 3.765625 | 4 | #Matt Bettinson
#10138240
def algorithmA(lis, target):
for x in lis:
if x == target:
return True
return False
def algorithmB(lis, target):
sortedLis = quickSort(lis)
def quickSort(lis):
less = []
equal = []
greater = []
size = len(lis)
if size > 1:
pivot = lis[size // 2]
for i in lis:
if i > pivot:
less.append(i)
if i == pivot:
equal.append(i)
if i < pivot:
greater.append(i)
less = quickSort(less)
greater = quickSort(greater)
lis = greater + equal + less
return lis
|
fabfb3f5e9d6c7f2bc2368f84ce0b5773147b19b | enmalik/Spam-Filter | /src/filter.py | 3,392 | 3.9375 | 4 | """
filter.py has several functionalities: all, indie or range.
all: the filter returns a list of tuples containing the email id (email name)
as well as its classification (ham or spam) for all emails in the files/emails directory.
indie: the filter returns a list of tuples containing the email id (email name)
as well as its classification (ham or spam) for the specified emails.
range: the filter returns a list of tuples containing the email id (email name)
as well as its classification (ham or spam) for the specified email and the number of emails after it as specified.
For example, if the arguments are <email1> and <3>, the classifications for <email1> as well as <email2> and <email3>
as is present in the files/emails directory will be returned.
For all emails:
python filter.py all
For individual emails:
python filter.py indie <email1> <email2> <email3> ...
The <email> refer to the file names in files/email/*
For a range of emails:
python filter.py range <email> <number>
"""
from nltk import NaiveBayesClassifier, classify
import os, glob
from aux import emailFeatures, loadClassifier
import sys
# Set the email directory.
emailDir = os.path.abspath("../files/emails")
# Classify all emails in the email directory.
def filterEmailAll():
classifier = loadClassifier("full-classifier.pickle")
classifications = []
emailList = glob.glob(emailDir + '/*')
for i in range(len(emailList)):
emailPath = emailList[i]
classifications.append(filterEmail(classifier, emailPath))
return classifications
# Classification of a single email, called by both filterIndies and filterRange.
def filterEmail(classifier, path):
f = open(path)
email = f.read()
f.close()
return (path.rsplit('/')[-1], classifier.classify(emailFeatures(email)))
# Classifies individual emails. Can classify as many emails as specified.
def filterIndies(emailIDs):
global emailDir
classifier = loadClassifier("full-classifier.pickle")
classifications = []
for i in range(len(emailIDs)):
emailIDs[i] = emailDir + "/" + emailIDs[i]
emailPath = emailIDs[i]
if not os.path.exists(emailPath):
print "Email '%s' does not exist." %emailPath.rsplit('/')[-1]
continue
classifications.append(filterEmail(classifier, emailPath))
return classifications
# Classifies a range of emails following the specified email.
def filterRange(emailID, num):
global emailDir
emailList = os.listdir(emailDir)
emailIndex = emailList.index(emailID)
emailRange = emailList[emailIndex : emailIndex + int(num)]
classifier = loadClassifier("full-classifier.pickle")
classifications = []
for i in range(len(emailRange)):
emailRange[i] = emailDir + "/" + emailRange[i]
emailPath = emailRange[i]
if not os.path.exists(emailPath):
print "Email '%s' does not exist." %emailPath.rsplit('/')[-1]
continue
classifications.append(filterEmail(classifier, emailPath))
return classifications
if __name__ == "__main__":
if sys.argv[1] == "all":
print "All emails!"
print filterEmailAll()
elif len(sys.argv) < 2:
print "Please indicate indie or range along with the emails."
elif sys.argv[1] == "indie" and len(sys.argv) >= 3:
print "Individual emails!"
print filterIndies(sys.argv[2:])
elif sys.argv[1] == "range" and len(sys.argv) == 4:
print "Range of emails!"
print filterRange(sys.argv[2], sys.argv[3])
else:
print "Please enter the corrent arguments." |
7c5e2d0ad5d36eab2e5c8808738de7b5b5739c08 | chloeward00/CA117-Computer-Programming-2 | /labs/main_words_041.py | 827 | 3.703125 | 4 | import sys
import string
def builddictionary():
dictionary = {}
for line in sys.stdin:
thewords = line.lower().strip().split()
for aword in thewords:
aword = aword.strip(string.punctuation)
if aword == '':
continue
if aword not in dictionary:
dictionary[aword] = 1
else:
dictionary[aword] += 1
return dictionary
def main():
dictionary = builddictionary()
newdictionary = {}
for (x, y) in sorted(dictionary.items()):
if len(x) > 3 and int(y) >= 3:
newdictionary[x] = y
width = len(max(newdictionary.keys(), key=len))
for (x, y) in sorted(newdictionary.items()):
print('{:>{:d}} : {:>2d}'.format(x, int(width), y))
if __name__ == '__main__':
main()
|
f7c332f14e479dadb8b3d758dfdf15d015fa3616 | zhouyzhao/Python_Test | /Python2_test/ex33.py | 261 | 4.0625 | 4 | # -*- coding: utf-8 -*-
# ex33.py
i = 0
number=10
numbers = []
while i < number:
print "At the top i is %d " % i
numbers.append(i)
i= i+1
print "Numbers now:", numbers
print "At the bottom i is %d" %i
print "The numbers:"
for num in numbers:
print num |
659287c9503355a52338d1ee40cb41113b69093f | antonio00/blue-vscode | /MODULO 01/AULA 11/rascunho.py | 593 | 3.515625 | 4 | galera = list()
dados = list()
totalMaior = TotalMenor = 0
for c in range(0,3):
# dados = list() pode ser usada assim tambem em substituicao do dados.clear
dados.append(str(input('Nome: ')))
dados.append(int(input('Idade: ')))
galera.append(dados[:])
dados.clear() # apos add dados em galera, limpa os dados e refaz o range.
for g in galera:
if g[1] >= 18:
print(f'{g[0]} é maior de idade')
totalMaior += 1
else:
print(f'{g[0]} é menor de idade')
TotalMenor +=1
print(f'Temos{totalMaior} maiores e {TotalMenor} menores de idade') |
62932fbbe566ec8e8222ead01b97b5af654f9548 | gaurava45/PythonProjectRepo | /revision1.py | 1,377 | 3.5 | 4 | #print numbers 1 to n in one line
# [print(i, end = " ") for i in range(1, int(input("upto?:")) + 1)]
# print([i for i in range(1, int(input("upto?:")) + 1)])
print(r"C:\Users\harry\Desktop")
print("C:\\Users\\harry\\Desktop")
# Oh soldier Prettify my Folder
# path, dictionary file, format
# def soldier("C://", "harry.txt", "jpg")
# import os
# def soldier(path, file, format):
# os.chdir(path)
# i = 1
# files = os.listdir(path)
# with open(file) as f:
# filelist = f.read().split("\n")
#
# for file in files:
# if file not in filelist:
# os.rename(file, file.capitalize())
#
# if os.path.splitext(file)[1] == format:
# os.rename(file, f"{i}{format}")
# i +=1
#
# soldier(r"C:\Users\Haris\Desktop\testing",
# r"C:\Users\Haris\PycharmProjects\PythonTuts\ext.txt", ".png" )
# a = input("What is your name")
# b = input("How much do you earn")
# if int(b)==0:
# raise ZeroDivisionError("b is 0 so stopping the program")
# if a.isnumeric():
# raise Exception("Numbers are not allowed")
#
# print(f"Hello {a}")
# 1000 lines taking 1 hour
# Task - Write about 2 built in exception
c = input("Enter your name")
try:
print(a)
except Exception as e:
if c =="harry":
raise ValueError("Harry is blocked he is not allowed")
print("Exception handled")
|
84153f583e7368b7fb3ea7f4cb2d359699d25b89 | Akbhobhiya/Algorithms-DSA | /lab0/prob4.py | 579 | 4.125 | 4 | n=int(input('Enter the size of Array:'))
list=[]
for i in range(n):
a=int(input())
list.append(a)
def bubble(list):
for i in range(n):
for j in range(n):
if list[j]>list[i]:
x=list[i]
list[i]=list[j]
list[j]=x
def selection(list):
for i in range(n):
p=list[i]
for j in range(n):
if list[j]>list[i]:
x=list[i]
list[i]=list[j]
list[j]=x
def main():
q=int(input('Enter 1 for bubble and 2 for selection sort:'))
if q==1:
bubble(list)
print(list)
elif q==2:
selection(list)
print(list)
else:
print('enter a correct choice')
main() |
8e3b0c763f9508b0a82b412e02eac1cbe7adf0b2 | DmitryAristarhov/lesson_9 | /main.py | 1,330 | 3.546875 | 4 | # -*- coding: utf-8 -*-
import card_game_fool as fool
game=fool.Game()
print(game.hello()) # Приветствие - отобразит текст "Добро пожаловать в игру".
print(game.command_commands()) # Список команд.
print('Козырь: ', end='')
print(game.command_trump(), end='') # Козырь - отобразит последнюю карту колоды задающую козырную масть.
print('Рука: ', end='')
print(game.command_hand()) # Рука - отобразит ваши карты.
while True: # Основной цикл.
cmd = input('> ')
if cmd == 'Выход':
break
if cmd == '':
continue
string = game.command(cmd)
split = string.find('GameOver:')
if split != -1: # Если игра окончена.
print(string[:split])
result = string[split:]
if result == 'GameOver:None':
print('Ничья. Не плохо сыграно!')
if result == 'GameOver:Gamer':
print('Поздравляю! Вы выиграли.')
if result == 'GameOver:Dummy':
print('Вы выиграли проиграли. Вы дурак!')
break
print(string)
print('Спасибо за игру. Приходите ещё!\n')
|
4846ab559e6fc65a635ad390608f89720ba88328 | fnov/learn_python3 | /specialist/homework/home7-07.py | 1,002 | 3.71875 | 4 | #!/usr/bin/python
#На вход подаётся целое число N - количество строк подаваемых на вход.
#Далее, подаются N строк из слов. Если слов в строке несколько, они разделяются пробелом.
#Для каждого слова напечатайте его количество. Список слов выведите по частоте.
#Пример ввода
#9
#hi
#hi
#what is your name
#my name is bond
#james bond
#my name is damme
#van damme
#claude van damme
#jean claude van damme
#Пример вывода
#damme 4
#is 3
#name 3
#van 3
#bond 2
#claude 2
#hi 2
#my 2
#james 1
#jean 1
#what 1
#your 1
N = int(input())
d = {}
for _ in range(N):
lst = [s for s in input().split()]
for word in lst:
if word not in d:
d[word] = 1
else:
d[word] += 1
sorted_d = [(k, d[k]) for k in sorted(d, key=d.get, reverse=True)]
for k, v in sorted_d:
print(k, v)
|
fc1fd46b3af4c7221b1b09c3bc182674fb1d0069 | kevinislas2/Iprep | /python/heaps/wave.py | 1,796 | 3.546875 | 4 | class MinHeap(object):
def __init__(self):
self.heap = list()
def push(self, value):
self.heap.append(value)
self.heapify(len(self.heap)-1)
def heapify(self, i):
continueFlag = True
while (i > 0 and continueFlag):
if(self.heap[i] < self.heap[(i-1)//2]):
self.heap[i], self.heap[(i-1)//2] = self.heap[(i-1)//2], self.heap[i]
i = (i-1)//2
else:
continueFlag = False
def pop(self):
if(not self.isEmpty()):
minVal = self.heap[0]
self.heap[0] = self.heap[len(self.heap)-1]
self.heap.pop()
self.rebalance(0)
return minVal
else:
return None
def rebalance(self, position):
leftIndex = None
rightIndex = None
minIndex = None
if((position*2)+1 < len(self.heap)):
leftIndex = (position*2)+1
minIndex = leftIndex
if(leftIndex+1 < len(self.heap)):
rightIndex = leftIndex + 1
if(self.heap[rightIndex] < self.heap[leftIndex]):
minIndex = rightIndex
if(minIndex):
self.heap[position], self.heap[minIndex] = self.heap[minIndex], self.heap[position]
self.rebalance(minIndex)
def isEmpty(self):
return len(self.heap) == 0
def wave(A):
heap = MinHeap()
for i in range(len(A)):
heap.push(A[i])
arr = []
while(not heap.isEmpty()):
arr.append(heap.pop())
print(arr)
stop = len(arr)
if(stop & 1):
stop -= 1
for i in range(0, stop, 2):
arr[i], arr[i+1] = arr[i+1], arr[i]
return arr
print(wave([5,1,3,2,4])) |
3aa6e99e7fe394d9cf26d1326c474daadca9c11e | diegun99/proyectos | /listas.py | 422 | 3.84375 | 4 | #lista vacia
lista_vacia = []
#lista con elementso
lista_numeros = [1,3,5]
#imprimir listas
print(lista_vacia)
print(lista_numeros)
print(lista_numeros[0])
#solicitaremos una posicion
#probando try catch except
try:
print(lista_numeros[10])
except IndexError as err:
print("ha ocurrido un error", err)
#Solicitar el último elemento de la lista
print("el último elemento es ", lista_numeros[-1])
|
48af51eecf446f14e5d145e4882877d9ca9c245d | AniketCS10/first_git_project | /cube_list.py | 554 | 3.796875 | 4 | # n = int(input("Enter the number of elements for list:"))
# a = []
# b = []
# sum = 0
# for i in range(1, n + 1):
# el = int(input("Enter element:"))
# a.append(el)
# sum = el * el * el
# b.append(sum)
# print("list elements",a)
# print("cube of list elements",b)
# faulty program
# nums = [1, 2, 5, 10, 3, 100, 9, 24]
# for i in nums:
# if i < 5:
# nums.remove(i)
# print(nums)
#solution of faulty program
# nums = [1, 2, 5, 10, 3, 100, 9, 24]
# a = []
# for i in nums:
# if i >= 5:
# a.append(i)
# print(a)
|
c896d12a9fdfc9849cfb5dae02e5cda16f5030a3 | TD0401/pythonsamples | /src/io/myacademy/pythontut/66.py | 354 | 4.03125 | 4 | #Create an English to Portuguese translation program.
#The program takes a word from the user as input and translates it using the following dictionary as a vocabulary source.
d = dict(weather = "clima", earth = "terra", rain = "chuva")
#Expected Result
#Enter word: earth
#terra
#Sol
i = input("Enter word: ")
i.strip(" ").strip("\n")
print(d[i])
|
77d457edeb1e34616469ced4b682d9fe5d196506 | BlancaRiveraCampos/Project_Euler | /Pb02_fibonacci.py | 266 | 3.515625 | 4 | #Find the sum of the even numbers in the Fibonacci sequence between 1 and 4M.
fib_list = [1, 2]
def fib(list_f, i):
x = 0
y = 2
while x < i:
x = list_f[-1] + list_f[-2]
if x % 2 == 0:
y = y + x
list_f.append(x)
return y
print(fib(fib_list,4000000))
|
2e36be4d4eee398f8a6939ef6c2ec2713420b6e2 | akurilov92/coding-test-django | /letter_digit/api/letter_case_permutation.py | 1,719 | 4.28125 | 4 | import itertools
from typing import List, Tuple
def generate_upper_lower_pairs(input_string: str) -> List[Tuple[str, str]]:
"""
Given an input string ("ab"), return a list of pairs of the form (c.lower(), c.upper()) for every c in input_string.
"""
return [
(c.lower(), c.upper()) if c.isalpha() else (c, ) for c in input_string
]
def letter_case_permutation(input_string) -> List[str]:
"""
:type input_string: str
:rtype: List[str]
Example:
input = 'ab'
1. create a list of pairs of the form (c.lower(), c.upper()): [ ('a', 'A'), ('b', 'B') ]
2. create a product(list of all possible combinations):
[ ('a', 'b'), ('a', 'B'), ('A', 'b'), ('A', 'B' ]
3. finally, apply ''.join to all the elements of this list to create strings
[ 'ab', 'aB', 'Ab', 'AB' ]
"""
upper_lower_pairs = generate_upper_lower_pairs(input_string)
all_combinations = itertools.product(*upper_lower_pairs)
return list("".join(comb) for comb in all_combinations)
def letter_case_permutation_dfs(input_string):
"""
A "Depth-first search" approach to the problem. Here we explore different "branches"(each alphabetic character
produces a new branch). We basically traverse the "tree" and stop at each "leaf" to add it to the solution.
(should
"""
res = []
def dfs(S, sol, i):
if len(sol) == len(S):
print(f'adding {sol}')
res.append(sol)
return
if S[i].isalpha():
dfs(S, sol + S[i].upper(), i+1)
dfs(S, sol + S[i].lower(), i+1)
else:
dfs(S, sol + S[i], i+1)
dfs(input_string, '', 0)
return res
|
2eceb382c507eef37b05df29d944ba68fe62a802 | sanchitkalra/Classes | /more_on_loops/assignment_number_pyramid.py | 588 | 3.625 | 4 | size = int(input())
for k in range(1, size):
flag = False
x = 0
for j in range(k-1, 0, -1):
if j == size-1:
continue
print(" ", end = "")
for j in range(k, size+1):
if j == k == size:
flag = True
continue
print(j, end = "")
x = j
if not flag:
print("")
# if flag:
# continue
# else:
# print("")
for k in range(size):
for j in range(size-k, 1, -1):
print(" ", end = "")
for j in range(size-k, size+1):
print(j, end = "")
print("") |
0017cd9d7f3f3d8706cfef26cc17d4c16146f4f2 | Alan3058/python-study | /src/cypher/randomPassword.py | 624 | 3.65625 | 4 | '''
Created on 2017年8月16日
随机密码生产
@author: liliangang
'''
import random
class RandomPassword:
def __init__(self, length=8):
self.factor = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ~!@#$%^&*()_+=-'
self.length = length
def next(self, length=0):
length = length if length > 0 else self.length
array = []
for i in range(length) :
array.append(self.factor[random.randint(0, len(self.factor) - 1)])
return ''.join(array)
if __name__ == '__main__':
for i in range(10) :
print(RandomPassword().next());
|
645b9db944025a7cb9a81505b184ba6503119c84 | ajrichards/notebook | /archive/python/working_with_generators.py | 287 | 3.53125 | 4 |
import numpy as np
from itertools import islice
x = np.arange(0,100)
def split_every(n, iterable):
i = iter(iterable)
piece = list(islice(i, n))
while piece:
yield piece
piece = list(islice(i, n))
for chunk in split_every(5, x):
print(chunk)
|
27c5e988090e247bb8ccab8b4bb859cb75855bf2 | rewingchow1/LeetCode | /Python/TwoSum.py | 454 | 3.53125 | 4 | def twoSum(nums, target):
for i in range(0, len(nums), 1):
sum = None
if nums[i] < target:
for j in range(0, len(nums), 1):
if nums[j] < target:
sum = nums[i] + nums[j]
if sum == target:
break
if sum == target:
break
return [i, j]
nums = [11, 25, 4, 5]
target = 9
x = twoSum(nums, target)
print(x)
|
3664e6a814dd950adc45a67115493c49a80ff456 | RavinderSinghPB/data-structure-and-algorithm | /bst/Print leaf nodes from preorder traversal of BST.py | 814 | 3.671875 | 4 | def leafNodePre(bst,size):
leaves = []
nodes = [bst[0]]
for pos in range(1, size - 1):
if bst[pos] > bst[pos + 1]:
nodes.append(bst[pos])
else:
found = False
while len(nodes) and nodes[-1] < bst[pos]:
found = True
nodes.pop()
if (len(nodes) == 0 or
nodes[-1] > bst[pos + 1] and nodes[-1] > bst[pos] or
nodes[-1] < bst[pos + 1] and nodes[-1] < bst[pos]):
nodes.append(bst[pos])
else:
leaves.append(bst[pos])
leaves.append(bst[-1])
print(*leaves)
# Driver Code
if __name__ == '__main__':
for _ in range(int(input())):
n = int(input())
bst = list(map(int, input().split()))
leafNodePre(bst,n)
|
1b8350375ce5463bdaa3001f2645e6c1aca14f05 | santoshsr19/Python-DS | /Array/arraysort.py | 1,257 | 4.125 | 4 | def sort012(arr,n):
return arr.sort()
#{
# Driver Code Starts
#Initial Template for Python 3
if __name__ == '__main__':
t=int(input())
for _ in range(t):
n=int(input())
arr=[int(x) for x in input().strip().split()]
sort012(arr,n)
for i in arr:
print(i, end=' ')
print()
# } Driver Code Ends
#repeated problem in geeks for geeks
def nearlysorted(arr, n, k):
arr.sort()
for i in arr:
print(i,end=" ")
print()
t = int(input())
for _ in range(t):
n, k = map(int, input().split())
arr=[int(x) for x in input().strip().split()]
nearlysorted (arr, n, k)
"""
Given an array of n elements, where each element is at most k away from its target position. The task is to print array in sorted form.
Input:
First line consists of T test cases. First line of every test case consists of two integers N and K, denoting number of elements in array and at most k positions away from its target position respectively. Second line of every test case consists of elements of array.
Output:
Single line output to print the sorted array.
Constraints:
1<=T<=100
1<=N<=100
1<=K<=N
Example:
Input:
2
3 3
2 1 3
6 3
2 6 3 12 56 8
Output:
1 2 3
2 3 6 8 12 56
""" |
7da1605bb366ed1284afc1558d16319d26fe7f9f | lefty06/pgm06 | /python_code/argparse/argsparse_tutorial.py | 8,934 | 3.921875 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#to avoid error: syntaxError: Non-ASCII character '\xc2' in file
import argparse
'''
parser.add_argument('-s','--serie',help='Store a simple value',required=True)
By default all argument are optional except if you mention required=True
-s or --serie can be used and must be followed an value ie -s value_of_arg
parser.add_argument('-s','--serie', action='store', dest='simple_value',default=333,help='Store a simple value',type=int,required=True)
default will be the default value of simple_value is -s|--serie is not used
dest='simple_value' will determine the name of variable where the argument is stored ie args.simple_value
type=int is the type of the variable simple_value
parser.add_argument('-e',dest='desp',nargs='+')
-e must have 1 or more values that will be stored in a list called desp. the default=whatever will be ignored
parser.add_argument('-p',dest='desp2',nargs='*',default='Hello') or default=['Hello']
-P can have 0 or more values that will be stored in a list called desp. the default=whatever can be used
--------------------
dest: You will access the value of option with this variable
help: This text gets displayed whey someone uses --help.
default: If the command line argument was not specified, it will get this default value.
action: Actions tell optparse what to do when it encounters an option on the command line. action defaults to store.
These actions are available:
store: take the next argument (or the remainder of the current argument), ensure that it is of the correct type, and store it to your chosen destination dest.
store_true: store True in dest if this flag was set.
store_false: store False in dest if this flag was set.
store_const: store a constant value
append: append this option’s argument to a list
thecount: increment a counter by one
callback: call a specified function
nargs: ArgumentParser objects usually associate a single command-line argument with a single action to be taken. The nargs keyword argument associates a different number of command-line arguments with a single action.
required: Mark a command line argument as non-optional (required).
choices: Some command-line arguments should be selected from a restricted set of values. These can be handled by passing a container object as the choices keyword argument to add_argument(). When the command line is parsed, argument values will be checked, and an error message will be displayed if the argument was not one of the acceptable values.
type: Use this command, if the argument is of another type (e.g. int or float).
'''
def Main(): #simple argpase example
parser = argparse.ArgumentParser()
parser.add_argument('-s', action='store', dest='simple_value',
help='Store a simple value')
parser.add_argument('-c', action='store_const', dest='constant_value',
const='value-to-store',
help='Store a constant value')
parser.add_argument('-t', action='store_true', default=False,
dest='boolean_switch',
help='Set a switch to true')
parser.add_argument('-f', action='store_false', default=False,
dest='boolean_switch',
help='Set a switch to false')
parser.add_argument('-a', action='append', dest='collection',
default=[],
help='Add repeated values to a list',
)
parser.add_argument('-A', action='append_const', dest='const_collection',
const='value-1-to-append',
default=[],
help='Add different values to list')
parser.add_argument('-B', action='append_const', dest='const_collection',
const='value-2-to-append',
help='Add different values to list') #Clever, it adds a constant to an existing array ie const_collection
parser.add_argument('-v','--version', action='version', version='%(prog)s 1.0')
#to test from terminal with input
# results = parser.parse_args()
# print 'simple_value =', results.simple_value
# print 'constant_value =', results.constant_value
# print 'boolean_switch =', results.boolean_switch
# print 'collection =', results.collection
# print 'const_collection =', results.const_collection
#to test from script parsing the arguments
print parser.parse_args(['-sbla']) #there's different ways to parse args for testing, no need to use terminal
print parser.parse_args(['-s','bli']) #there's different ways to parse args for testing, no need to use terminal
print parser.parse_args(['-s=blo']) #there's different ways to parse args for testing, no need to use terminal
print parser.parse_args(['-s=blo','-c']) #there's different ways to parse args for testing, no need to use terminal
print parser.parse_args(['-s=blo','-c','-t']) #there's different ways to parse args for testing, no need to use terminal
print parser.parse_args(['-s=blo','-c','-t','-aHello','-a',' Its me']) #there's different ways to parse args for testing, no need to use terminal
print parser.parse_args(['-s=blo','-c','-t','-aHello','-a',' Its me','-A','-B']) #there's different ways to parse args for testing, no need to use terminal
print parser.parse_args(['-s=blo','-c','-t','-aHello','-a',' Its me','-A','-B']) #there's different ways to parse args for testing, no need to use terminal
print parser.parse_args(['-s=blo','-c','-t','-aHello','-a',' Its me','-A','-B','-A']) #there's different ways to parse args for testing, no need to use terminal
print parser.parse_args(['-v']) #there's different ways to parse args for testing, no need to use terminal
def fib(n):
a,b=0,1
for i in range(n):
a,b=b,a+b
return a
def Main2(): #simple argpase example
#python script -f 8 -d 'blabla'
parser = argparse.ArgumentParser()
# parser.add_argument('--fibo') #the argument will be a string by default if not specified
parser.add_argument('-d','--disclaimer')
parser.add_argument('-f','--fibo',type=int)
args = parser.parse_args()
# print parser.parse_args(['-f','8','-d','bla']) #to parse values equivalent of executing the script python script -f 8 -d bla
print 'disclaimer: {}'.format(args.disclaimer)
print 'Fib: {}'.format(fib(args.fibo))
print 'args:{}'.format(args) #Displays everything, good for debugging
def Main3():
#python script -f 8 -v
parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group()
group.add_argument('-v','--verbose',action="store_true")
group.add_argument('-q','--quiet',action="store_true")
# parser.add_argument('num',help="Calculates Fibonacci number",type=int)
parser.add_argument('-n','--num',help="Calculates Fibonacci number",type=int)
parser.add_argument('-e','--email')
args = parser.parse_args()
res=fib(args.num)
if args.verbose:
print 'The finbonacci suite of {} is {}'.format(args.num,res)
elif args.quiet:
print '{}'.format(res)
else:
print '{}:{}'.format(args.num,res)
if args.email:
print args.email
print 'args:{}'.format(args)
def Main4():
parser = argparse.ArgumentParser()
# parser.add_argument('-e',action='store',dest='desp',default=333,type=int)
parser.add_argument('-e',dest='desp',nargs='+',type=int) #nargs +: 1 or more args
parser.add_argument('-p',dest='desp2',nargs='*',default=['Hello']) #nargs *: 0 or more args
args = parser.parse_args()
if args.desp:
print 'desp'
print '{}'.format(args.desp)
if args.desp2:
print 'desp2'
print '{}'.format(args.desp2)
def PD_Main():
parser = argparse.ArgumentParser(description='Get bets from a list of IDs or a file with IDs')
#you can create as many groups as needed
group = parser.add_mutually_exclusive_group()
group.add_argument('-f','--file',type=argparse.FileType('r'),help='Um fecheiro caralho')
group.add_argument('-l','--list',nargs='+',type=int,help='uma lista de INTs caralho')
parser.add_argument('-b','--bets',action="store_true",required=True)
#to test from terminal: python -b -f abspath/file
args=parser.parse_args()
if args.file:
print args.file.readlines()
if args.list:
print args.list
#TO TEST ARGPARSE from atom crtl+shift+b
# print parser.parse_args(['-h']) #correct
# print parser.parse_args(['-b']) #correct
# print parser.parse_args(['-b','-l=12']) #correct
# print parser.parse_args(['-b','--file=/home/pat/Documents/python_scripts/argparse/f.txt']) #correct
# print parser.parse_args(['-b','-l=2','--file=/home/pat/Documents/python_scripts/argparse/f.txt']) #FDS
if __name__ == '__main__':
PD_Main()
|
4ea266d4f4c18efbba4204d7301652f8966c18a5 | Kegs30/sheepwolves.github.io | /Development/Animation/Animation.py | 3,262 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
Animation practical output
The code that follows builds on the "Communications.py" file
Additional code that follows has in part been modified from that of
https://www.geog.leeds.ac.uk/courses/computing/practicals/python/agent-framework/part8/index.html
https://www.geog.leeds.ac.uk/courses/computing/practicals/python/agent-framework/part8/examples/animatedmodel.py
https://www.geog.leeds.ac.uk/courses/computing/practicals/python/agent-framework/part8/examples/animatedmodel2.py
"""
import random
import operator
import matplotlib.pyplot
import matplotlib.animation
import agentframeworkanimate
import csv
# Reading the in.txt file to create the environment.
with open("in.txt", newline="") as raster:
dataset = csv.reader(raster, quoting=csv.QUOTE_NONNUMERIC)
environment = []
for row in dataset:
rowlist = []
for value in row:
rowlist.append(value)
environment.append(rowlist)
# Setting initial parameters.
num_of_agents = 10
num_of_iterations = 100
neighbourhood = 20
agents = []
# Variables to animate the model.
fig = matplotlib.pyplot.figure(figsize=(7, 7))
ax = fig.add_axes([0, 0, 1, 1])
ax.set_autoscale_on(False)
# Make the agents.
# Addition of environment as argument for Agent class to allow interaction between agents and environment.
# Addition of agents as argument for Agent class to allow agents to interact with each other.
for i in range(num_of_agents):
agents.append(agentframeworkanimate.Agent(environment, agents))
carry_on = True
# Creating model animation.
def update(frame_number):
fig.clear()
global carry_on
# Move the agents and store what they eat
for j in range(num_of_iterations):
# Shuffle function used to randomise the order agents are processed with each iteration.
random.shuffle(agents)
for i in range(num_of_agents):
agents[i].move()
agents[i].eat()
agents[i].share_with_neighbours(neighbourhood)
# Stopping condition for animation when all agents have 100 in their store.
if agents[i].store == 100:
carry_on = False
print("Stopping condition met")
# Generate scatterplot of agents after model iterations.
matplotlib.pyplot.xlim(0, 99)
matplotlib.pyplot.ylim(0, 99)
matplotlib.pyplot.imshow(environment)
for i in range(num_of_agents):
matplotlib.pyplot.scatter(agents[i].x,agents[i].y)
# Generator function to stop animation.
# Will stop animation after 10 iterations unless carry_on variable is set to False.
def gen_function(b = [0]):
a = 0
global carry_on
while (a < 100) & (carry_on):
yield a
a = a + 1
# Animation will run until generator function condition is met
#animation = matplotlib.animation.FuncAnimation(fig, update, interval=1, repeat=False, frames=10)
animation = matplotlib.animation.FuncAnimation(fig, update, frames=gen_function, repeat=False)
matplotlib.pyplot.show()
# Writing the final environment to a text file.
with open("out.txt", "w", newline="") as finalenviron:
writer = csv.writer(finalenviron, delimiter=",")
for row in environment:
writer.writerow(row)
|
4422c0f11178dc73a539b8a153b0241e7a7b43bd | bruteforce1/cryptopals | /set2/ch09/implement_pkcs7.py | 1,612 | 4.3125 | 4 | #!/usr/bin/python3
"""
A block cipher transforms a fixed-sized block (usually 8 or 16 bytes)
of plaintext into ciphertext. But we almost never want to transform a
single block; we encrypt irregularly-sized messages.
One way we account for irregularly-sized messages is by padding,
creating a plaintext that is an even multiple of the blocksize. The
most popular padding scheme is called PKCS#7.
So: pad any block to a specific block length, by appending the number
of bytes of padding to the end of the block. For instance,
"YELLOW SUBMARINE"
... padded to 20 bytes would be:
"YELLOW SUBMARINE\x04\x04\x04\x04"
"""
import argparse
import sys
from utils.cpset2 import pkcs7_padding
def main(message, bl):
print('Line: ' + str(message))
print('block length: ' + str(bl))
ret = pkcs7_padding(message, bl, 1)
if ret:
print('PKCS#7 padded: ')
print(ret)
unret = pkcs7_padding(ret, bl, 0)
if unret:
print('PKCS#7 unpadded: ')
print(unret)
return 0
print('Error.')
return -1
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description='Implements PKCS#7 padding of a message to a block \
length of 20.'
)
parser.add_argument('-m', '--message', help='opt. message to pad',
default='YELLOW SUBMARINE')
parser.add_argument('-b', '--blocklength', help='opt. block length \
in bytes, between 1-32',
default='20')
args = parser.parse_args()
sys.exit(main(args.message, args.blocklength))
|
34f32303fb4e85ef516b860de53ef3eb347ec8f7 | gsbhardwaj27/datastructure-algorithms-related-problems-python | /coursera_algorithms_part2/week1/hamiltonian_path_DAG.py | 1,943 | 3.625 | 4 | # Digraph: Design a linear-time algorithm to determine whether a
# digraph has a vertex that is reachable from every other vertex,
# and if so, find one.
import unittest
from digraph import DiGraph
class HamiltonPathDag:
def __init__(self, g):
self.g = g
self.done = [False]*self.g.V
self.topo_order = []
self.populate_topo_order()
self.has_hamilton_path = self._has_hamilton_path()
def populate_topo_order(self):
for i in range(self.g.V):
if not self.done[i]:
self.topo_util(i)
def get_reverse_topo_order(self):
return list(reversed(self.topo_order))
def topo_util(self, v):
self.done[v] = True
for each in self.g.adj(v):
if not self.done[each]:
self.topo_util(each)
self.topo_order.append(v)
def _has_hamilton_path(self):
rto = self.get_reverse_topo_order()
for i in range(len(rto)-1):
if not (rto[i+1] in self.g.adj(rto[i])):
return False
return True
class TestHamiltonPathDag(unittest.TestCase):
def test_topo_order(self):
g = DiGraph(6)
g.add_edge(2, 1)
g.add_edge(1, 0)
g.add_edge(0, 4)
g.add_edge(4, 3)
g.add_edge(3, 5)
self.assertTrue(HamiltonPathDag(g).has_hamilton_path)
def test_topo_order(self):
g = DiGraph(4)
g.add_edge(0, 1)
g.add_edge(0, 2)
g.add_edge(1, 3)
g.add_edge(2, 3)
self.assertFalse(HamiltonPathDag(g).has_hamilton_path)
def test_topo_order(self):
g = DiGraph(7)
g.add_edge(2, 1)
g.add_edge(1, 0)
g.add_edge(0, 4)
g.add_edge(4, 3)
g.add_edge(3, 5)
g.add_edge(6, 5)
self.assertFalse(HamiltonPathDag(g).has_hamilton_path)
if __name__ == '__main__':
unittest.main()
|
fa95eda673239625f2e3cde410cfe1d28f8549c5 | minus-plus/ocr_project | /classification/testInvert.py | 544 | 4.28125 | 4 |
def arrayInvert(array):
"""
Inverts a matrix stored as a list of lists.
"""
result = [[] for i in array]
for outer in array:
for inner in range(len(outer)):
result[inner].append(outer[inner])
return result
def testInvert():
count = 1
l = []
for i in range(0,3):
l2 = []
for j in range(0, 3):
l2.append(count)
count = count + 1
l.append(l2)
print l
l3 = arrayInvert(l)
print l3
if __name__ == "__main__":
testInvert() |
1fa65db1a79db44510a476e0e030636df2602e93 | carv-silva/cursoemvideo-python | /Mundo01/exercsMundo01/ex031.py | 521 | 3.984375 | 4 | ''' Faca um programa que pergunte a distancia de uma viagem em km.Calcule o preco da passagem cobrando R$0.50
por km para viagens de ate 200km e R$0.45 para viajens mais longas'''
dist = float(input('Entre com a distancia da viagem em Km: '))
'''if dist <= 200:
t = dist * 0.50
print(f'O preco total é: R${t:.2f}')
else:
t = dist * 0.45
print(f'O preco total é: R${t:.2f}')'''
# segundo metodo
preco = dist * 0.50 if dist <= 200 else dist * 0.45
print(f'O preco total é: R${preco:.2f}')
|
d2f3ca9424cdbf042c68c0b08a085ee90abd366a | Dioclesiano/Estudos_sobre_Python | /Exercícios/ex080 - Organizando Lista.py | 2,586 | 4.3125 | 4 | '''
Crie um programa onde o usuário possa digitar cinco valores numéricos e cadastre-os em uma lista,
já na posição correta de inserção (sem usar o sort()). No final, mostre a lista ordenada na tela.
lista = []
for c in range(0,5):
n = int(input('Digite um valor » '))
if c == 0:
lista.append(n) # C = 0 significa o 1º valor. Portanto o primeiro valor digitado ficará na primeira posição.
elif n > lista[-1]: # Foi usado len(lista)-1, para indicar o último ítem da lista. Deve-se ter em mente que quando
# uso a função 'len(lista)' é para saber a quantidade de ítens da lista. Enquanto 'lista[-1]'
# é para mostrar o valor ou dado que está na última posição dalista.
lista.append(n) # Esse comando irá adicionar o número e, através da lógica criada no ELIF, este número será
# armazenado depois do último número.
else:
posicao = 0
while posicao < len(lista): # Essa função while especifica que o laço ira acontecer
# enquanto o contador 'posicao' indicar um valor menor
# que a quantidade de ítens da lista, ou seja, sendo que a
# lista tem 5 ítens, enquanto o contador for menor que 5
# o programa funcionará, e parará quando for igual a 5.
if n <= lista[posição]
lista.insert(posicao, n) # Este comando irá adicionar o número digitado pelo cliente (n)
# na posição indicada pelo contador 'posicao'
break
posicao += 1
'''
# Abaixo toda estrutura organizada
lista = []
for c in range(1, 6):
n = int(input('Digite um valor » '))
if c == 1 or n > lista[-1]:
lista.append(n)
print('Adicionado ao final da lista...')
else:
indice = 0
while indice < len(lista):
if n <= lista[indice]:
lista.insert(indice, n)
print(f'Adicionado na posição {indice+1} da lista...')
break
indice += 1
print()
print(' * '*20)
print(f'Os valores digitados em ordem foram {lista}')
print(' * '*20)
'''
Exemplo de Organização com Lógica
num = [10, 5, 6, 3, 8, 1, 0, 9, 7, 2, 4]
for i in range(0, len(num)):
for j in range(0, len(num)):
if num[i] < num[j]:
aux = num[i]
num[i] = num[j]
num[j] = aux
print(num)
'''
|
dece306105ff7939c9dea206d64f92fc2f86f8b7 | msingh55-asu/madhaterz | /user_int.py | 1,410 | 3.671875 | 4 | from subprocess import call
import os
print("Hello, How are you? Let us make Cloud Computing great again! ")
return_typ = input("Please enter return type expected ")
func_name = input("Please enter the file name ")
fobj = open(func_name, 'w')
fobj.write("import sys\n")
fobj.write("print( \'Number of arguments:\', len(sys.argv), \'arguments.\')\n")
fobj.write("print(\'Argument List:\', str(sys.argv))\n")
print("Enter the code line by line or enter $ to exit")
prog_src = []
prog_src_ln = input()
while prog_src_ln != "$":
prog_src.append(prog_src_ln)
temp = prog_src_ln + "\n"
fobj.write(temp)
prog_src_ln = input()
print("Please enter the arguements or press $ to end ")
args = []
val = input()
while val != "$":
args.append(val)
val = input()
print(return_typ)
for n in prog_src:
print(n)
print(args)
fobj.close()
fobj1 = open(func_name)
print(fobj1.read())
fobj1.close()
str1 = ' '.join(args)
#print(str1)
#chk_prog = "Error:"
command_call = 'python ./' + func_name + ' ' + str1
#print(command_call)
chk_prog2 = os.system(command_call + ' | cat > temp_file ')
#print(chk_prog)
if os.stat("temp_file").st_size == 0:
chk_prog2 = 1
else:
fobj2 = open('temp_file','r')
chk_prog = fobj2.read()
fobj2.close
#print("CheckProgram " + chk_prog)
print(chk_prog2)
if chk_prog2:
print("Syntax Error")
else:
print("The Program has compiled successfully")
|
e0bb0c48cf5be2359ea5c0f79e05bc635b700783 | Ayur12/python_basic | /Home_works/les_1/task_3.py | 204 | 3.671875 | 4 | user_number = input('Введите число: ')
user_number_2 = user_number + user_number
user_number_3 = user_number_2 + user_number
print(int(user_number) + int(user_number_2) + int(user_number_3))
|
52b1f389ca074c96f513dc7556f0542799a80341 | JoshuaBelden/hacking-ciphers | /transpositionDecrypt.py | 624 | 3.53125 | 4 | import math
def main():
message = 'Cenoonommstmme oo snnio. s s c'
key = 8
plain_text = decryptMessage(key, message)
print(plain_text + '|')
def decryptMessage(key, message):
ncols = math.ceil(len(message) / key)
nrows = key
shades = (ncols * nrows) - len(message)
plain_text = [''] * ncols
col = 0
row = 0
for symbol in message:
plain_text[col] += symbol
col += 1
if (col == ncols) or (col == ncols - 1 and row >= nrows - shades):
col = 0
row += 1
return ''.join(plain_text)
if __name__ == '__main__':
main(); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.