blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
a6ed1818c3c9fd26128c5e1534679582d9b9e993 | kumarnishkarsh/rishiProgram | /Python/Interactive App.py | 1,697 | 4.25 | 4 | print('INTERACTIVE APP')
print('---------------')
print('Hi,I AM ROBOTHON')
print('I AM A ROBOT IN PYTHON, YOU WILL DEFINITELY HAVE FUN WITH ME.')
y_n = str(input('DO YOU WANT TO TALK WITH ME?'))
y_n = y_n.lower()
if y_n == 'yes':
print('Oh! that is nice of you.')
print('OK, let us first get introduced to each other!')
n_y = str(input('Is it ok if you tell your name?'))
n_y = n_y.lower()
if n_y == 'yes':
print('OK, let us start with my introduction.')
print('----------------')
print('NAME : ROBOTHON(ROBOT+PYTHON)')
print('AGE : UNKNOWN! :( ')
name_1 = str(input('What is you name? '))
age_1 = input('What is your age?')
print('----------------')
print('Your information:')
print('NAME : ' , name_1)
print('AGE : ' , age_1)
print('Nice to meet you' , name_1)
print('See this now...')
for letter in name_1:
print(letter)
print('OK... Bye, hope we will meet again')
elif n_y == 'no':
print('OK then, Bye :(')
else:
print('Sorry! Wrong input, please restart.')
elif y_n == 'no':
print('OK then, Bye :(')
else:
print('Sorry! Wrong input, please restart.')
print('PLEASE RATE :)')
rate = int(input('5, 4, 3, 2, 1'))
if rate == 5:
print('Thanks a lot for this :)')
elif rate == 4:
print('Thanks, will improve.')
elif rate == 3:
print('Thanks, will improve.')
elif rate == 2:
print(':(')
elif rate == 1:
print(':(')
else:
print('Wrong input')
i = 1
while i<rate+1:
print(i)
i = i+1
|
a5ac755fb77be130a9dcdbd5de510a3e83f4e8df | Ro7nak/python | /basics/regex/app2.py | 1,031 | 3.765625 | 4 | import re
flight_details="Flight Savana Airlines a2138"
if(re.search(r"Airlines",flight_details)!=None):
print("Match Found: Airlines")
else:
print("Match Not Found")
if(re.search(r"a2138$",flight_details)!=None):
print("Match Found: a2138")
else:
print("Match Not Found")
if(re.search(r"^F",flight_details)!=None):
print("Match Found: Message starts with 'F'")
else:
print("Match Not Found")
if(re.search(r"F..",flight_details)!=None):
print("Match Found: Word starts with F and two consecutive characters")
else:
print("Match Not Found")
if(re.search(r"\bSav\b",flight_details)!=None):
print("Match Found:Word with blank spaces on both sides")
else:
print("Match Not Found")
if(re.search(r"\d$",flight_details)!=None):
print("Match Found: Message ends with number")
else:
print("Match Not Found")
print("Word replaced in the message:")
print(re.sub(r"Flight","Plane",flight_details))
print("Word replaced in the message:")
print(re.sub(r"a(\d{4})",r"A\1",flight_details))
|
8adbda84552b7a489a41947ca7f39ad34a44c4ab | strawnp/ap-csp-20-21 | /unit3/divisible.py | 232 | 3.90625 | 4 | import cs50
x = cs50.get_int("Enter a number: ")
y = cs50.get_int("Enter another number: ")
remainder = x % y
if remainder == 0:
print(f"{x} is evenly divisible by {y}")
else:
print(f"{x} is not evenly divisible by {y}")
|
9012604259d98cd948590809a44e411dcba8af92 | LindaM14/Programming_Logic_and_Design | /LAB_11/WordBank_Word&Excel.py | 1,182 | 3.65625 | 4 | from openpyxl import Workbook
import requests
import docx
# API URL
word_bank = 'http://api.worldbank.org/v2/country?format=json&per_page=400'
response = requests.get(word_bank).json()
# Entering the page/index of the dictionary
country_info_list = response[1]
# creating the word docx sheet
document = docx.Document()
document.add_paragraph('Countries and their Capital Cities', 'Title')
# creating the excel sheet
capital_cities_workbook = Workbook()
worksheet = capital_cities_workbook.active
worksheet.title = 'Capital Cities'
worksheet.cell(1, 1,)
worksheet.cell(1, 2,)
# for loop to make data go into excel and word sheet in dictionary Name and CapitalCity
for country_info_dictionary, country_info_list in enumerate(country_info_list):
worksheet.cell(country_info_dictionary +2, 1, country_info_list['name'])
worksheet.cell(country_info_dictionary + 2, 2, country_info_list['capitalCity'])
document.add_paragraph(f'The capital of ' + country_info_list['name'] + ' is ' + country_info_list['capitalCity'])
# save documents - when print will copy/data transfer to sheets
capital_cities_workbook.save('capital_cities.xls')
document.save('Capital_Cities.docx') |
1d46918d74b051086b07877e91d1177de0b618ed | VINEETHREDDYSHERI/Python-Deep-Learning | /ICPLab3/src/Question2.py | 677 | 3.5625 | 4 | # Importing the packages
import requests
from bs4 import BeautifulSoup
html = requests.get("https://en.wikipedia.org/wiki/Deep_learning") # Getting the content of the site
bsObj = BeautifulSoup(html.content, "html.parser") # Parsing the html data
print("The Title of the page is: ", bsObj.title.string)
linksData = bsObj.find_all("a") # Getting all the <a> links details
outPutFile = open("WikiPageLinks.txt", "w") # Opening the file in write mode
for link in linksData:
if link.get('href') is not None:
outPutFile.write(str(link.get('href')) + "\n") # Writing the urls into the file.
print()
print("Writing the links information to the file is completed")
|
4ea079204139d8c5e13d32edb39a76e7efe93bbd | OliviaRW/group23 | /Exam/Migration/data_cleaning.py | 5,434 | 3.984375 | 4 | from dependencies import *
def remove_stopwords(lst):
with open('stopord.txt', 'r') as sw:
#read the stopwords file
stopwords = sw.read().split('\n')
return [word for word in lst if not word in stopwords]
def lemmatize_strings(body_text, language = 'da', remove_stopwords_ = True):
"""Function to lemmatize a string or a list of strings, i.e. remove prefixes. Also removes punctuations.
-- body_text: string or list of strings
-- language: language of the passed string(s), e.g. 'en', 'da' etc.
"""
if isinstance(body_text, str):
body_text = [body_text] #Convert whatever passed to a list to support passing of single string
if not hasattr(body_text, '__iter__'):
raise TypeError('Passed argument should be a sequence.')
lemmatizer = lemmy.load(language) #load lemmatizing dictionary
lemma_list = [] #list to store each lemmatized string
word_regex = re.compile('[a-zA-Z0-9æøåÆØÅ]+') #All charachters and digits i.e. all possible words
for string in body_text:
#remove punctuation and split words
matches = word_regex.findall(string)
#split words and lowercase them unless they are all caps
lemmatized_string = [word.lower() if not word.isupper() else word for word in matches]
#remove words that are in the stopwords file
if remove_stopwords_:
lemmatized_string = remove_stopwords(lemmatized_string)
#lemmatize each word and choose the shortest word of suggested lemmatizations
lemmatized_string = [min(lemmatizer.lemmatize('', word), key=len) for word in lemmatized_string]
#remove words that are in the stopwords file
if remove_stopwords_:
lemmatized_string = remove_stopwords(lemmatized_string)
lemma_list.append(' '.join(lemmatized_string))
return lemma_list if len(lemma_list) > 1 else lemma_list[0] #return list if list was passed, else return string
def count_occurences(body_text, dictionary = None, lemmatize = False, **kw):
"""Function to count occurences of words in either a string or list of strings present in dictionary.
Returns a list of dictionaries or a single dictionary.
-- body_text: string or list of strings.
-- dictionary: list of strings to be counted. If None every word is counted
-- lemmatize: bool that indicates wether the text should be lemmatized
-- **kw: keyword arguments for lemmatize_string()
"""
if lemmatize:
body_text = lemmatize_strings(body_text, **kw) #lemmatize if requested
if isinstance(body_text, str):
body_text = [body_text] #Convert whatever passed to a list to support passing of single string
if not hasattr(body_text, '__iter__'):
raise TypeError('Passed argument should be a sequence.')
if dictionary:
return [collections.Counter({key: string.count(key) for key in dictionary}) for string in body_text]
else:
return [collections.Counter(string.split(' ')) for string in body_text]
def get_frequent_articles(df, dictionary, n = 3):
"""Function to filter out articles that does not contain a certain amount of words in dictionary.
-- df: DataFrame containing articles. Must have a 'Text' column.
-- dictionary: words that should be counted as significant.
-- n: the minimum number of dictionary words an article should contain to be considered 'frequent'
"""
counts = count_occurences(df['Text'], dictionary = dictionary, lemmatize = True)
dr_frequent_articles = df[pd.Series(sum(count.values()) for count in counts) >= 3]
dr_frequent_articles.to_csv('dr_frequent_articles.csv', header = True, index = False)
def clean_article_counts(filename, categories, subcategories = None):
"""Function to remove articles from uninteresting categories.
-- filename: Path to file contaning articles and url
-- categories: list of categories that should be kept
"""
df = pd.read_csv(filename, header = 0)
categories_series = df['URL'].str\
.extract(r'https://www.dr.dk//(\w+/?\w+)/')[0]\
.apply(lambda x: x.split('/') if '/' in x else [x, np.nan]) #apply regex to extract categories
df['Category'] = categories_series.str[0].str.lower()
df['Subcategory'] = categories_series.str[1].str.lower()
df = pd.concat([df[df['Category'] == category] for category in categories]) #Remove categories not in list
if subcategories: #remove subcategories not in list
df = pd.concat([df[df['Subcategory'] == subcategory].copy() for subcategory in subcategories])
df['Date'] = pd.to_datetime(df['Date'])
df = df[df['Date'].dt.year >= 2010]
df.to_csv('cleaned_' + filename, header = True, index = False)
def clean_dr_articles():
#df = pd.read_csv('dr_contents.csv', header = 0)
#dictionary = ['flygtning', 'migrant', 'asylansøg', 'indvandre', 'immigrant']
#get_frequent_articles(df, dictionary)
#df = pd.read_csv('dr_frequent_articles.csv', header = 0, index_col = 0)
#df['Publish date'] = pd.to_datetime(df['Publish date'])
#df = df[df['Publish date'].dt.year >= 2010]
#df.to_csv('dr_frequent_articles.csv', header = True, index = False)
clean_article_counts('dr_article_counts.csv', ['nyheder'])
if __name__ == "__main__":
clean_dr_articles() |
8e892b4bb6f8a61828c9597e5ca6070b19cdd29a | NitishShandilya/CodeSamples | /generatePrimeFactors.py | 1,398 | 4.4375 | 4 | """
Given a number n, write an efficient function to print all prime factors of n.
Solution:
Following are the steps to find all prime factors.
1) While n is divisible by 2, print 2 and divide n by 2.
2) After step 1, n must be odd. Now start a loop from i = 3 to square root of n.
While i divides n, print i and divide n by i, increment i by 2 and continue.
3) If n is a prime number and is greater than 2, then n will not become 1 by above two steps.
So print n if it is greater than 2.
Based on concept: the smallest prime factor of a composite number N is less than or equal to N.
That is the reason, each time we divide the number by the prime factor and run only until the square
root of that number.
"""
import math
def generatePrimeFactors(n):
primeFactors = []
while n%2 == 0:
primeFactors.append(str(2))
n /= 2
# n must be odd since 2 is the only prime factor. Therefore, increment in steps of 2.
for i in range(3, int(math.sqrt(n))+1, 2):
while n%i == 0:
primeFactors.append(str(i))
n /= i
# This is to handle the case, when n is a prime number. If after all the reductions,
# it is still a prime number, then it has to be greater than 2. We print this as well.
if n > 2:
primeFactors.append(str(n))
return " ".join(primeFactors)
# Test
n = 276
print generatePrimeFactors(n) |
b8fe9077e12e664eafd51abd20cc1ee86c27076a | bainco/bainco.github.io | /course-files/lectures/lecture11-old/old/02_operator_functions.py | 467 | 4.15625 | 4 | from operator import add, mul, sub, truediv, mod, floordiv, pow
# for more info, see the docs: https://docs.python.org/3/library/operator.html
# Challenge:
# Using the functions above (no operators), write a program to
# calculate the hypotenuse of several right triangles with the
# following dimensions, and prints the results to the screen:
# triangle 1: side_a = 5, side_b = 12
# triangle 2: side_a = 3, side_b = 5
# triangle 3: side_a = 4, side_b = 4 |
d961b3286a52dc67b609c3c99db7dcc94e23fb4d | nandansn/pythonlab | /myworkouts/rent-calc.py | 753 | 3.5625 | 4 | def rentCalc(rent=0,years=0,increment=0):
totalRent=0
fromYearOne=1
prevYearRent = 0
for i in range(fromYearOne,years):
if (i == 1):
prevYearRent = prevYearRent + (12 * rent)
print('Rent for the year {} is {}:',i,prevYearRent)
totalRent = prevYearRent
else:
prevYearRent = prevYearRent + (prevYearRent * (increment /100))
print('Rent for the year {} is {}:',i,prevYearRent)
totalRent = totalRent + prevYearRent
print('Total rent for {} years is {}',years,totalRent)
rent = int(input('Enter rent:'))
years = int(input('Enter years:'))
increment = int(input('Enter increment:'))
rentCalc(rent,years,increment)
|
d10e86a993fc99c3e5d95e46b4a5f122567596f5 | holzschu/Carnets | /Library/lib/python3.7/site-packages/networkx/algorithms/isomorphism/isomorph.py | 6,646 | 3.515625 | 4 | """
Graph isomorphism functions.
"""
import networkx as nx
from networkx.exception import NetworkXError
__author__ = """\n""".join(['Aric Hagberg (hagberg@lanl.gov)',
'Pieter Swart (swart@lanl.gov)',
'Christopher Ellison cellison@cse.ucdavis.edu)'])
# Copyright (C) 2004-2019 by
# Aric Hagberg <hagberg@lanl.gov>
# Dan Schult <dschult@colgate.edu>
# Pieter Swart <swart@lanl.gov>
# All rights reserved.
# BSD license.
__all__ = ['could_be_isomorphic',
'fast_could_be_isomorphic',
'faster_could_be_isomorphic',
'is_isomorphic']
def could_be_isomorphic(G1, G2):
"""Returns False if graphs are definitely not isomorphic.
True does NOT guarantee isomorphism.
Parameters
----------
G1, G2 : graphs
The two graphs G1 and G2 must be the same type.
Notes
-----
Checks for matching degree, triangle, and number of cliques sequences.
"""
# Check global properties
if G1.order() != G2.order():
return False
# Check local properties
d1 = G1.degree()
t1 = nx.triangles(G1)
c1 = nx.number_of_cliques(G1)
props1 = [[d, t1[v], c1[v]] for v, d in d1]
props1.sort()
d2 = G2.degree()
t2 = nx.triangles(G2)
c2 = nx.number_of_cliques(G2)
props2 = [[d, t2[v], c2[v]] for v, d in d2]
props2.sort()
if props1 != props2:
return False
# OK...
return True
graph_could_be_isomorphic = could_be_isomorphic
def fast_could_be_isomorphic(G1, G2):
"""Returns False if graphs are definitely not isomorphic.
True does NOT guarantee isomorphism.
Parameters
----------
G1, G2 : graphs
The two graphs G1 and G2 must be the same type.
Notes
-----
Checks for matching degree and triangle sequences.
"""
# Check global properties
if G1.order() != G2.order():
return False
# Check local properties
d1 = G1.degree()
t1 = nx.triangles(G1)
props1 = [[d, t1[v]] for v, d in d1]
props1.sort()
d2 = G2.degree()
t2 = nx.triangles(G2)
props2 = [[d, t2[v]] for v, d in d2]
props2.sort()
if props1 != props2:
return False
# OK...
return True
fast_graph_could_be_isomorphic = fast_could_be_isomorphic
def faster_could_be_isomorphic(G1, G2):
"""Returns False if graphs are definitely not isomorphic.
True does NOT guarantee isomorphism.
Parameters
----------
G1, G2 : graphs
The two graphs G1 and G2 must be the same type.
Notes
-----
Checks for matching degree sequences.
"""
# Check global properties
if G1.order() != G2.order():
return False
# Check local properties
d1 = sorted(d for n, d in G1.degree())
d2 = sorted(d for n, d in G2.degree())
if d1 != d2:
return False
# OK...
return True
faster_graph_could_be_isomorphic = faster_could_be_isomorphic
def is_isomorphic(G1, G2, node_match=None, edge_match=None):
"""Returns True if the graphs G1 and G2 are isomorphic and False otherwise.
Parameters
----------
G1, G2: graphs
The two graphs G1 and G2 must be the same type.
node_match : callable
A function that returns True if node n1 in G1 and n2 in G2 should
be considered equal during the isomorphism test.
If node_match is not specified then node attributes are not considered.
The function will be called like
node_match(G1.nodes[n1], G2.nodes[n2]).
That is, the function will receive the node attribute dictionaries
for n1 and n2 as inputs.
edge_match : callable
A function that returns True if the edge attribute dictionary
for the pair of nodes (u1, v1) in G1 and (u2, v2) in G2 should
be considered equal during the isomorphism test. If edge_match is
not specified then edge attributes are not considered.
The function will be called like
edge_match(G1[u1][v1], G2[u2][v2]).
That is, the function will receive the edge attribute dictionaries
of the edges under consideration.
Notes
-----
Uses the vf2 algorithm [1]_.
Examples
--------
>>> import networkx.algorithms.isomorphism as iso
For digraphs G1 and G2, using 'weight' edge attribute (default: 1)
>>> G1 = nx.DiGraph()
>>> G2 = nx.DiGraph()
>>> nx.add_path(G1, [1,2,3,4], weight=1)
>>> nx.add_path(G2, [10,20,30,40], weight=2)
>>> em = iso.numerical_edge_match('weight', 1)
>>> nx.is_isomorphic(G1, G2) # no weights considered
True
>>> nx.is_isomorphic(G1, G2, edge_match=em) # match weights
False
For multidigraphs G1 and G2, using 'fill' node attribute (default: '')
>>> G1 = nx.MultiDiGraph()
>>> G2 = nx.MultiDiGraph()
>>> G1.add_nodes_from([1,2,3], fill='red')
>>> G2.add_nodes_from([10,20,30,40], fill='red')
>>> nx.add_path(G1, [1,2,3,4], weight=3, linewidth=2.5)
>>> nx.add_path(G2, [10,20,30,40], weight=3)
>>> nm = iso.categorical_node_match('fill', 'red')
>>> nx.is_isomorphic(G1, G2, node_match=nm)
True
For multidigraphs G1 and G2, using 'weight' edge attribute (default: 7)
>>> G1.add_edge(1,2, weight=7)
1
>>> G2.add_edge(10,20)
1
>>> em = iso.numerical_multiedge_match('weight', 7, rtol=1e-6)
>>> nx.is_isomorphic(G1, G2, edge_match=em)
True
For multigraphs G1 and G2, using 'weight' and 'linewidth' edge attributes
with default values 7 and 2.5. Also using 'fill' node attribute with
default value 'red'.
>>> em = iso.numerical_multiedge_match(['weight', 'linewidth'], [7, 2.5])
>>> nm = iso.categorical_node_match('fill', 'red')
>>> nx.is_isomorphic(G1, G2, edge_match=em, node_match=nm)
True
See Also
--------
numerical_node_match, numerical_edge_match, numerical_multiedge_match
categorical_node_match, categorical_edge_match, categorical_multiedge_match
References
----------
.. [1] L. P. Cordella, P. Foggia, C. Sansone, M. Vento,
"An Improved Algorithm for Matching Large Graphs",
3rd IAPR-TC15 Workshop on Graph-based Representations in
Pattern Recognition, Cuen, pp. 149-159, 2001.
http://amalfi.dis.unina.it/graph/db/papers/vf-algorithm.pdf
"""
if G1.is_directed() and G2.is_directed():
GM = nx.algorithms.isomorphism.DiGraphMatcher
elif (not G1.is_directed()) and (not G2.is_directed()):
GM = nx.algorithms.isomorphism.GraphMatcher
else:
raise NetworkXError("Graphs G1 and G2 are not of the same type.")
gm = GM(G1, G2, node_match=node_match, edge_match=edge_match)
return gm.is_isomorphic()
|
c60655bae8f75a2a514a945553805d6bed8d01aa | DanieleMagalhaes/Exercicios-Python | /Mundo3/Tuplas/analisaTupla.py | 787 | 3.875 | 4 | print('-'*50)
numeros = (int(input('Digite um número: ')),
int(input('Digite outro número: ')),
int(input('Digite mais um número: ')),
int(input('Digite o último número: ')))
print('-'*50)
print(f'\33[32mOs números digitados foram: \33[m{numeros}')
print(f'\33[32mO número 9 apareceu {numeros.count(9)} vez(es).\33[m')
if 3 in numeros:
print(f'\33[32mO número 3 apareceu na {numeros.index(3)+1}ª posição.\33[m')
else:
print('\33[32mO número 3 não foi digitado.\33[m')
print(f'\33[32mNúmeros pares foram: \33[m', end='')
pares = 0
for n in numeros: #para cada n em numeros
if n%2 == 0 and n != 0: #se pares e diferente de zero
print(f'{n}', end=' ')
pares +=1
if pares == 0: #se nao tiver nenhum par
print('Nenhum')
|
03eeb65c199d8bb0432123632f337d46e80b1a1a | Liang5757/Collaborators | /utils/Fraction.py | 1,887 | 3.8125 | 4 | # 把所有数当成分数
class Fraction(object):
# 支持 7 "8/6" "1'2/7" 及 "7"和"8"的构造
def __init__(self, molecular, denominator=1):
# 分子
self.molecular = molecular
# 分母
self.denominator = denominator
z = 0
if isinstance(self.molecular, str):
# 如果为带分数则分离整数部分
if '\'' in self.molecular:
# 整数部分
temp = self.molecular.split('\'')
z = int(temp[0])
self.molecular = temp[1]
if '/' in self.molecular:
self.molecular = self.molecular.split('/')
self.denominator = int(self.molecular[1])
self.molecular = int(self.molecular[0])
else:
self.molecular = int(self.molecular)
if z:
self.molecular += z * self.denominator
# 计算公约数
def gcd(self):
a = self.molecular
b = self.denominator
while a:
temp = b % a
b = a
a = temp
return b
# 约分
def fraction_reduction(self):
gcd = self.gcd()
self.denominator /= gcd
self.molecular /= gcd
# 将分子分母变为字符串形式
def to_string(self):
if self.denominator == 1 or self.molecular % self.denominator == 0:
operand = str(int(self.molecular / self.denominator))
elif self.molecular > self.denominator:
z = int(self.molecular / self.denominator)
self.fraction_reduction()
operand = str(z) + "\'" + str(int(self.molecular - z * self.denominator)) + "/" + str(int(self.denominator))
else:
self.fraction_reduction()
operand = str(int(self.molecular)) + "/" + str(int(self.denominator))
return operand
|
dc4effd7d74257438e16978270e4dc3fcdb7eb5a | dvgupta90/sept-10th---restaurant-ratings | /ratings.py | 2,101 | 4.125 | 4 | """Restaurant rating lister."""
# put your code here
import sys
import random
filename = sys.argv[1]
my_file = open(filename)
restaurants_dict = {}
for line in my_file:
words_list = (line.rstrip()).split(':')
restaurants_dict[words_list[0]] = int(words_list[1])
while True:
print("Please select one of these:\n\
See all the ratings (S)\n\
Add a new restaurant (A)\n\
Update ratings of an existing restaurant (U)\n\
Quit (Q)")
choice =input("S, A, U or Q: ")
if choice.upper() == "Q":
break
elif choice.upper() == 'A':
restaurant = input("Please enter the restaurant name: ")
rating = int(input("Please enter it's rating: "))
while rating < 1 or rating > 5:
print("Please enter a rating between 1 and 5.")
rating = int(input("Please enter it's rating: "))
restaurants_dict[restaurant.title()] = rating
elif choice.upper() == 'S':
for restaurant, rating in sorted(restaurants_dict.items()):
print("{} is rated at {}." .format(restaurant, rating))
elif choice.upper() == 'U':
selection = input("Do you want to choose the restaurant to update? Y/N ")
if selection.upper() == "Y":
print("Here is the list of restaurants: ")
for restaurant in restaurants_dict.keys():
print(restaurant)
new_rating_for_rest = input("Please enter your choice: ").title()
else:
restaurants_list = list(restaurants_dict.keys())
new_rating_for_rest = random.choice(restaurants_list)
print("Here is the restaurant to change the rating.")
print(new_rating_for_rest, restaurants_dict[new_rating_for_rest])
new_rating = int(input("Please enter new rating "))
while new_rating < 1 or new_rating > 5:
print("Please enter a rating between 1 and 5.")
new_rating = int(input("Please enter it's rating: "))
restaurants_dict[new_rating_for_rest] = new_rating
|
be5040ad3319831792f9c9655cead0b72035db3f | MartyVos/Les8 | /fa8_NS-kaartautomaat.py | 1,685 | 4 | 4 | def inlezen_beginstation(stations):
while 1:
start = input("Geef uw beginstation: ")
if start in stations:
return start
else:
print("Deze trein komt niet in", start)
def inlezen_eindstation(stations, beginstation):
while 1:
eindstation = input("Geef uw eindstation: ")
if eindstation in stations and stations.index(eindstation) > stations.index(beginstation):
return eindstation
elif eindstation not in stations:
print("Deze trein komt niet in", eindstation)
def omroepen_reis(stations, beginstation, eindstation):
begin = stations.index(beginstation) + 1
eind = stations.index(eindstation) + 1
afstand = eind - begin
prijs = afstand * 5
print("Het beginstation", beginstation, "is het", str(begin) + "e", "station in het traject.")
print("Het eindstation", eindstation, "is het", str(eind) + "e", "station in het traject.")
print("De afstand bedraagt", afstand, "station(s).")
print("De prijs van het kaartje is", prijs, "euro")
print("\nU stapt in de trein in:", beginstation)
for x in range(len(stations)):
if stations.index(beginstation) < x < stations.index(eindstation):
print(" - ", stations[x])
print("U stapt uit in:", eindstation)
stations = ["Schagen", "Heerhugowaard", "Alkmaar", "Castricum", "Zaandam", "Amsterdam Sloterdijk", "Amsterdam Centraal",
"Amsterdam Amstel", "Utrecht Centraal", "'s-Hertogenbosch", "Eindhoven", "Weert", "Roermond", "Sittard",
"Maastricht"]
a = inlezen_beginstation(stations)
b = inlezen_eindstation(stations, a)
omroepen_reis(stations, a, b)
|
8da648f0c73a75d25cda087ddc68dcc7c0e7ad4c | b4s1cst4rt3r/BWINF-JUNIORAUFGABEN17-18 | /BWINF17-J1-.py | 1,627 | 3.75 | 4 | deko = int(input()) # Sektion Eingabe
anzahl = int(input())
buecher = [] # Erstellen einer leeren Liste
for i in range(0, anzahl): # input in Liste einordnen
buecher.append(int(input())) # im Beispiel erwähnte Typ-Änderung des inputs
buecher.sort() # elemente der liste der Größe nach sortieren
# Sektion Programm
a = int(buecher[0]) #das erste(also kleinste) Element der Liste ist die erste Vergleichszahl (a genannt)
for i in buecher: # alle Elemente der Liste werden überprüft
if i == "X": # überspringen der Platzhalter
continue
if buecher[buecher.index(i) - 1] == "X": # die Zahl nach dem Platzhalter ist die neue Vergleichszahl
a = i
continue
if int(a) + 30 < int(i): # Ist die zu überprüfende Zahl weiter als 30mm von der Vergleichszahl entfert?
buecher.insert(buecher.index(i), "X") # Ja,-->einsetzen des Platzhalters
# falls keine Bedinung erfüllt wird, wird das nächste Element der Liste überprüft
# Sektion Ausgabe
if buecher.count("X") > deko: # Ausgabe: zu wenig deko
print("Die Aufstellung ist nicht möglich: Deko benötigt:", buecher.count("X"), "; Deko vorhanden:", deko)
print("Aufstellung mit ", buecher.count("X"), "Dekorationen:", buecher)
elif buecher.count("X") < deko: # "Sonderfall": zu viel deko
print("Aufstellung möglich, allerdings werden", deko - buecher.count("X"), "Dekorationen nicht benötigt")
print("Aufstellung:", buecher)
elif buecher.count("X") == deko: # Ausgabe: Aufstellung möglich
print("Es ist möglich!")
print("Aufstellung:", buecher)
|
79945554a0817a7b844e460669eedb6e66f0efdf | huiqi2100/searchingsorting | /quicksort.py | 401 | 3.859375 | 4 | # quicksort.py
def quicksort(array):
if array == []:
return []
else:
pivot = array[0]
less = []
great = []
for item in array[1:]:
if item < pivot:
less.append(item)
else:
great.append(item)
less = quicksort(less)
great = quicksort(great)
return (less + [pivot] + great)
|
20f7e310ec1e914d935eb96436ab5ffc659d6368 | stephane-robin/Mathematics | /new LU.py | 4,010 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Nov 20 17:34:28 2014
@author: stef
"""
# FEM METHOD FOR THE EQUATION u''=exp(x)
# Program written Python 3.3
# This program finds the solution of the equation u''=exp(x) using the FEM
# We claim to transform the problem into the resolution of the linear problem
# Auh=B which would give us an approximation of the solution
# DEFINING THE FUNCTION GIVEN BY THE EQUATION
def f(x):
return exp(x)
# ====================================================================
# DEFINING THE STEP OF THE METHOD
n=5
h=float(1/n)
# ====================================================================
# CREATING MATRIX A
A=-2*eye(n,n) # initialisation
for i in range(0,n-1): # calculating Aij
A[i,i+1]=1
for i in range(1,n):
A[i,i-1]=1
A=dot(n,A)
print(A) # TEST
# =====================================================================
# CREATING VECTOR B
B=zeros((n,1)) #list(range(0,n)) # initialisation
def F(y,k): # defining the function in the integral to calculate Bi
global h
return (y-k*h)*f(y)
def integrale(a,b,k): # calculating the integral of the function F
I1,I2=0.,0.
for i in range(0,10000):
I1=F(a+i*(b-a)/10000.,k)+I1
I1=I1*(b-a)/10000.
for i in range(1,10001):
I2=F(a+i*(b-a)/10000.,k)+I2
I2=I2*(b-a)/10000.
return (I1+I2)/2.
for i in range(1,n): # calculating Bi
B[i-1]=n*integrale((i-1)*h,i*h,i-1)-n*integrale(i*h,(i+1)*h,i+1)
print(B) # TEST
# ======================================================================
# SOLVING AX=B
# Calculating matrices L and S by iteration
L=eye(n,n) # we give a neutral value to L
for k in range(1,n): # k is defined between 1 and n-1 (n-1 iterations are necessary)
M=eye(n,n)
for i in range(k,n): # changing matrix Lk
M[i,k-1]=-(A[i,k-1])/(A[k-1,k-1])
A=dot(A,M) # defining the new value for A putting 0 under some terms of the diagonal after each iteration
invM=linalg.inv(M) # defining the inverse of Lk after each iteration
L=dot(L,invM) # defining L after each iteration as the product of inverse matrices Lk
S=A # defining S as A after n-1 iterations, i.e S is the product of matrices Lk and A
print("S=",S)
print("L=",L)
# solving LX=B by iteration climbing up
# initialisation
X=list(range(0,n))
X[0]=h*B[0]/2
for i in range(1,n):
X[i]=(h*B[i]-X[i-1])/2 # create X_i
print(X)
# solving Su=X by iteration climbing down
ut=list(range(0,n))
ut[n-1]=X[n-1]
for i in range(2,n+1):
# X=h*B-2*X
ut[n-i]=h*X[n-i+1]-ut[n-i+1]
uh=list(range(0,n+1)) # finding the approximated solution & fitting it to the end of interval
# uh is a vector size n+1 (useful for the graph to finish at the end of the interval)
for i in range(1,n+1):
uh[i]=ut[i-1]
def u(x): # Designing the theoretical solution
return exp(x)+(1-exp(1))*x-1
uh[0]=u(0)
for i in range(0,n+1): # printing the approximated solution uh
print("uh[",i,"]=",uh[i])
for i in range(0,n+1): # printing the solution u
print("u[x",i,"]=",u(i*h))
# ======================================================================
# PRINTING THE GRAPH
x=list(range(0,n+1)) # defining coordinates of the knots
for i in range(0,n+1):
x[i]=i*h
plt.figure(1) # Designing the background
plt.title("Resolution of $ \Delta u(x)=e^x $, by the FEM, step h=0.02")
plt.xlabel("x axis")
plt.ylabel("y axis")
plt.grid(True)
plt.xlim(0,1) # (the interval of study is [0,1])
plt.ylim(-0.3,0.3)
X1=np.linspace(0,1,50) # designing X axis
X2=np.zeros(50)
Y1=np.zeros(50) # designing Y axis
Y2=np.linspace(-0.3,0.3,50)
plt.plot(X1,X2,'k',Y1,Y2,'k',linewidth=1)# printing the axis
plt.plot(x,uh,'b',linewidth=2) # printing the graph of the approximated solution in blue
t=np.linspace(0,1,50) # printing the graph of the theoretical solution in red
plt.plot(t,u(t),'r',linewidth=2)
plt.show()
|
906e47938d25c1caa4d841f1e3b8a38d967bd110 | maturivinay/python_lee | /Lab_Assignment_2/Q_4.py | 912 | 3.5 | 4 | from sklearn.neighbors import KNeighborsClassifier
from sklearn import datasets, metrics
from sklearn.model_selection import train_test_split
# Loading the dataset
irisdataset = datasets.load_wine()
# getting the data and response of the dataset
x = irisdataset.data
y = irisdataset.target
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
# split the data for training and testing
model = KNeighborsClassifier(n_neighbors=10)
model.fit(x_train, y_train)
y_pred = model.predict(x_test)
print(metrics.accuracy_score(y_test, y_pred))
k_range = range(1, 50)
scores = []
for k in k_range:
knn = KNeighborsClassifier(n_neighbors=k)
knn.fit(x_train, y_train)
y_pred = knn.predict(x_test)
scores.append(metrics.accuracy_score(y_test, y_pred))
import matplotlib.pyplot as plt
plt.plot(k_range, scores)
plt.xlabel("value of k")
plt.ylabel("testing accuracy")
plt.show()
|
0e62ac96c52f2b7000114a076da5805b3dd18585 | FriggD/CursoPythonGGuanabara | /Mundo 1/Desafios/Desafio#34.py | 436 | 3.828125 | 4 | #Escreva um programa que pergunte o salário de um funcionário e calcule o valor de seu aumento
# 1. Para salários superiores a R$1250,00, calcule um aumento de 10%
# 2. Para inferiores ou iguais, o aumento é de 15%
#
salario = float(input('Digite seu salário: '))
if salario > 1250:
print ('seu novo salário é: {}'.format(salario + (salario*0.10)))
else:
print ('seu novo salário é: {}'.format(salario + (salario*0.15))) |
3db0f05820f7a293202f51f1e9951bd139289776 | vihangab/Webserver-Python-Flask | /webserver1/1 | 1,389 | 3.75 | 4 | #!/usr/env python
# Author :Vihanga Bare #
import socket
from threading import Thread
from SocketServer import ThreadingMixIn
# New thread created for evry connection #
class RequestThread(Thread):
def __init__(self,ip,port):
Thread.__init__(self)
self.ip = ip
self.port = port
print "[+] New server socket thread started for " + ip + ":" + str(port)
def run(self):
while True :
data = conn.recv(1024)
print "Server received data:", data
MESSAGE = raw_input("Multithreaded Python server : Enter Response from Server/Enter exit:")
if MESSAGE == 'exit':
break
conn.send(MESSAGE) # echo
# Open the socket and initialise the server #
TCP_IP = '127.0.0.1'
TCP_PORT = 8888
BUFFER_SIZE = 1024 #maximum size of the buffer
def Server(self):
tcpServer = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcpServer.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
tcpServer.bind((TCP_IP, TCP_PORT))
threads = []
while True:
tcpServer.listen(10)
print "Multithreaded Python server : Waiting for connections from TCP clients..."
(conn, (ip,port)) = tcpServer.accept()
newthread = ClientThread(ip,port)
newthread.start()
threads.append(newthread)
for t in threads:
t.join()
|
56bd8b77e501f66a82f7ae26dc469a3d5f3cee16 | sabrinaaraujoo/Python | /crime.py | 576 | 3.703125 | 4 | #crime
#entrada
p_a = int(input("Telefonou para a vítima? 1-SIM ou 0-NÃO: \n"))
p_b = int(input("Esteve no local do crime? 1-SIM ou 0-NÃO: \n"))
p_c = int(input("Mora perto da vítima? 1-SIM ou 0-NÃO: \n"))
p_d = int(input("Devia para a vítima? 1-SIM ou 0-NÃO: \n"))
p_e = int(input("Já trabalhou com a vítima? 1-SIM ou 0-NÃO: \n"))
soma_p = p_a + p_b + p_c + p_d + p_e
if (soma_p < 2):
print("\nInocente")
elif (soma_p == 2):
print("\nSuspeito")
elif (soma_p <=4 and soma_p >=3):
print("\nCúmplice")
elif (soma_p == 5):
print("\nAssassino")
|
95ed3f218561546b17a3aefade90b35428a48463 | JahnaviPC/Python-Workshop | /CentegrateToFarenheit.py | 295 | 4.125 | 4 | Convert centegrade to farenheit
#( f= 9/5*c+32)
c = float(input("Enter the centigrade value to be converted:"))
print("the converted value of centigrade to farenheit is:",(1.8*c)+32)
OUTPUT:
Enter the centigrade value to be converted:0
the converted value of centigrade to farenheit is: 32.0
|
ca232518f118beb13275bf104c7374ad3615a54c | kesfrance/textToHistogram | /textToHistogram.py | 3,734 | 4.25 | 4 | #1/usr/bin/python3
#
#
# by: Francis Kessie
#
#
"""
Process text from input file and implements a histogram creation algorithm.
This program takes input text file and counts all text in file.
symbols and punctuation marks are ignored. The program returns a table
with word size and corresponding word counts and implements a histogram creation
algorithm to draw a histogram of word size vrs word count.
"""
import string
import sys
def file_processor(myfile):
"""
reads and process input file and also removes all
punctuation symbols from text
"""
with open(myfile, "r") as inp:
filea = inp.read()
for punc in string.punctuation:
filea = filea.replace(punc, "")
return filea
def get_dict(wordlist, x):
"""
creates a dict with count of text as key and
and word size as values
"""
mylist = []
mydict = {}
for a, b in wordlist:
if b == x:
mylist.append(a)
mydict[x] = len(mylist)
return mydict
def get_countlist(words):
"""
returns a list containing all possible word sizes in text
"""
count_set = set()
for word in words:
count_set.add(len(word))
countlist = sorted(count_set)
return countlist
def histogram(dictx):
"""draw a histogram of word count and wordsize"""
#Get maximum x and Y values, plus two to help graph display
maxi_xval = max(dictx.keys())+2
maxi_yval = max(dictx.values())+2
#draw histogram by row
for inp in range(400, 0, -20):
###
if inp%100 == 0:
draw = str(inp)+"-|"
else:
draw = ' |'
for ind in range(1, maxi_xval):
if ind in dictx.keys() and dictx[ind] >= inp:
draw += '***'
else:
draw += ' '
print("{1} {0}".format(draw, ' '))
#format and print x-axis
x_axis = ' 0--+-'
for i in range(0, maxi_xval+2):
x_axis += '-+-'
print(x_axis)
#format and print scale of x-axis
x_scale = ' '
for j in range(1, maxi_xval):
space = ' '
if j < 10:
space = space + ' '
x_scale = x_scale + space
x_scale = x_scale + str(j)
print("{2}{0}{1}".format('', x_scale, ' '))
if __name__ == "__main__":
# Prompt user if no correct input supplied
# process file and store text with corresponding count as list of tuples
while True:
try:
mytextfile = sys.argv[1]
words = file_processor(mytextfile).split()
wordlist = []
for word in words:
wordbin = tuple([word, len(word)])
wordlist.append(wordbin)
#print table to screen in required format
print("Length", '\t', "Count")
countlist = get_countlist(words)
dictb = {}
for values in countlist:
table = get_dict(wordlist, values)
for key, value in table.items():
dictb[key] = value
print(key, '\t', value)
print(" ")
print(" ")
#draw histogram
histogram(dictb)
break
except IndexError:
print('Text file not supplied, (Type script name and name of text file(e.g textToHistogram.py sample_text.txt)')
break
except FileNotFoundError:
print('Cannot find text file, (Check and Provide correct text file name!)')
break
|
ac338ad0f44846e1cc79b4055b3975cddc3f5fa7 | luoxuele/ds | /python/linkList/linkList.py | 2,592 | 3.921875 | 4 | class Node(object):
def __init__(self, value=None, next=None):
self.value = value
self.next = next
def __str__(self):
"""方便打印调试"""
return '<Node: value = {}, next = {}'.format(self.value, self.next)
__repr__ = __str__
class LinkedList(object):
"""单链表类"""
def __init__(self, size = None):
"""
:param size: int or None, 如果是None,则没有容量限制
"""
self.size = size
self.root = Node()
# self.root = None
self.tailNode = None
self.length = 0
def __len__(self):
return self.length
def append(self, value):
# self.size 不等于None 说明这个单链表是有容量的
# self.length >= self.size 说明容量都装满了
if self.size is not None and len(self) >= self.size:
raise Exception('LinkedList is Full')
node = Node(value) # 构造节点
tail = self.tailNode
if tail is None: #说明list还没有节点
self.root.next = node
else:
tail.next = node # 添加新的节点到最后
self.tailNode = node
self.length += 1
def appendleft(self, value):
if self.size is not None and len(self) >= self.size:
raise Exception("Linked List is Full")
node = Node(value)
if self.tailNode is None: # 如果原链表为空,需要设置tailNode
self.tailNode = node
headnode = self.root.next
self.root.next = node
node.next = headnode
self.length += 1
def __iter__(self):
for node in self.iter_node():
yield node.value
def iter_node(self):
"""遍历 从head 到tail"""
curnode = self.root.next
while curnode is not self.tailNode:
yield curnode
curnode = curnode.next
if curnode is not None:
yield curnode
def remove(self, value):
prevnode = self.root
for curnode in self.iter_node():
if curnode.value == value:
prevnode.next = curnode.next
if curnode is self.tailnode:
self.tailNode = prevnode
del curnode
self.length -= 1
return 1 # 表明删除成功
else:
prevnode = curnode
return -1 # 表明删除失败
if __name__ == '__main__':
ll = Node()
print(ll)
|
84de1046a8fd6e65477e34f9379b0bb2dbeef60e | vishalnandanwar/Machine_Learnings | /src/LinearRegression/LinearRegrex.py | 1,993 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu May 30 12:11:04 2019
@author: vnandanw
"""
#import relevant libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
#Read the data set from file
FlatData = pd.read_csv('Price.csv')
#Separate features and labels from the data set
X = FlatData.iloc[:,:-1].values
y = FlatData.iloc[:,1].values
##Create train and test data
#from sklearn.model_selection import train_test_split
#X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)
#Linear regression approach with train data
from sklearn.linear_model import LinearRegression
regexAgent = LinearRegression()
regexAgent.fit(X, y)
from sklearn.preprocessing import PolynomialFeatures
polyFeature = PolynomialFeatures(degree = 3)
Poly_matrix = polyFeature.fit_transform(X)
regexAgent2 = LinearRegression()
regexAgent2.fit(Poly_matrix, y)
#Plot the data on the graph
plt.scatter(X,
y,
color='green')
plt.plot(X, regexAgent.predict(X), color = 'red')
plt.title('Compare Training result - Area/Price')
plt.xlabel('Area of Flat')
plt.ylabel('Price')
plt.show()
#Plot the data on the graph
plt.scatter(X,
y,
color='green')
plt.plot(X, regexAgent2.predict(polyFeature.fit_transform(X)), color = 'red')
plt.title('Compare Training result - Area/Price')
plt.xlabel('Area of Flat')
plt.ylabel('Price')
plt.show()
val = [[1500]]
linearPredict = regexAgent.predict(val)
polynomialPredict = regexAgent2.predict(polyFeature.fit_transform(val))
plt.scatter(X,
y,
color='green')
plt.plot(X, linearPredict, color = 'red')
plt.title('Compare Training result - Area/Price')
plt.xlabel('Area of Flat')
plt.ylabel('Price')
plt.show()
#Plot the data on the graph
plt.scatter(X,
y,
color='green')
plt.plot(X, polynomialPredict, color = 'red')
plt.title('Compare Training result - Area/Price')
plt.xlabel('Area of Flat')
plt.ylabel('Price')
plt.show()
|
a964e061e01b251c191f8415578a862fd5309ae5 | xingzhong/leetcode-python | /36.py | 802 | 3.546875 | 4 | class Solution:
# @param board, a 9x9 2D array
# @return a boolean
def isValidSudoku(self, board):
def test(xs):
t = [False]*9
for x in xs:
if x == '.': continue
elif t[int(x)-1]:
return False
else:
t[int(x)-1] = True
return True
t1 = all(map(test, board))
if not t1 : return False
b2 = [[board[j][i] for j in range(9)] for i in range(9)]
t2 = all(map(test, b2))
if not t2 : return False
for i in range(3):
for j in range(3):
b3 = [board[ii][jj] for ii in range(3*i, 3*(i+1)) for jj in range(3*j, 3*(j+1))]
if not test(b3): return False
return True
|
fe267cf7a025dfcd9c8ec382b4be9e679b562de7 | TinouWild/PythonBasique | /intermediaire/erreurs_debutant/get_list_variable.py | 239 | 3.578125 | 4 | liste = range(10)
index = 2
# premiere solution
try:
r = liste[index]
print(r)
except IndexError:
print("L'index {} n'existe pas.".format(index))
# deuxieme solution
r = liste[index] if len(liste) > index else None
print(r)
|
9a2d084f01c7a174ef2a9296337a957275103994 | HenDGS/Aprendendo-Python | /python/Exercicios/4.11.py | 288 | 3.859375 | 4 | pizzas=["Calabresa","Quatro-queijos","pepperoni"]
pizzas_do_amigo=pizzas[0:3]
pizzas.append("portuguesa")
pizzas_do_amigo.append("havaiana")
"""for pizza in pizzas:
print("Gosto de pizza " + pizza)"""
print(pizzas)
print(pizzas_do_amigo)
#print ("\nEu realmente gosto de pizza")
|
70fbaa1c4f067357bd27bae4421ce8b4c2a17c79 | cankutergen/hackerrank | /Missing_Numbers.py | 521 | 3.546875 | 4 | def missingNumbers(arr, brr):
dict_a = {}
dict_b = {}
missing = []
for i in arr:
if i not in dict_a:
dict_a[i] = 1
else:
dict_a[i] += 1
for i in brr:
if i not in dict_b:
dict_b[i] = 1
else:
dict_b[i] += 1
for key in dict_b:
if key in dict_a:
if dict_a[key] != dict_b[key]:
missing.append(key)
else:
missing.append(key)
missing.sort()
return missing
|
97c919d1535403fcba1a543ebb6668f326360968 | sleonardoaugusto/vrum | /core/carro.py | 739 | 3.609375 | 4 | import unittest
from core.direcao import Direcao, Direcoes
from core.motor import Motor
class Carro:
def __init__(self, motor, direcao):
self.motor = motor
self.direcao = direcao
def calcular_velocidade(self):
return self.motor.velocidade
def acelerar(self):
self.motor.acelerar()
def frear(self):
self.motor.frear()
def calcular_direcao(self):
return self.direcao.valor
class CarroTest(unittest.TestCase):
def setUp(self) -> None:
motor = Motor()
direcao = Direcao()
self.c = Carro(motor, direcao)
def test_instance(self):
self.assertIsInstance(self.c.motor, Motor)
self.assertIsInstance(self.c.direcao, Direcao)
|
29e4931cdd6563aa0bb3fbc4211709f6ecdfff65 | m21082/Practice-Work-Apps | /find job material.py | 606 | 3.6875 | 4 | # Find all instances of job name and show what material was ordered and on which date
# Info from CSV populated by material order script
import csv
import os
import sys
import time
from pathlib import Path
from time import gmtime, strftime
job = input (" Enter job name/ref: ")
for file_name in os.listdir():
if file_name.endswith(".csv"):
print ()
with open ((file_name), 'r') as f:
csv_reader = csv.reader(f, delimiter=",")
for row in csv_reader:
if job.upper() in row:
print ("".join(row))
print ()
|
c5e08310d57c902cf16efe142f75ceeb928dbae4 | pdhhiep/Computation_using_Python | /r8lib/r8_modp.py | 2,753 | 3.828125 | 4 | #!/usr/bin/env python
def r8_modp ( x, y ):
#*****************************************************************************80
#
## R8_MODP returns the nonnegative remainder of real division.
#
# Discussion:
#
# If
# REM = R8_MODP ( X, Y )
# RMULT = ( X - REM ) / Y
# then
# X = Y * RMULT + REM
# where REM is always nonnegative.
#
# The MOD function computes a result with the same sign as the
# quantity being divided. Thus, suppose you had an angle A,
# and you wanted to ensure that it was between 0 and 360.
# Then mod(A,360.0) would do, if A was positive, but if A
# was negative, your result would be between -360 and 0.
#
# On the other hand, R8_MODP(A,360.0) is between 0 and 360, always.
#
# Example:
#
# I J MOD R8_MODP R8_MODP Factorization
#
# 107 50 7 7 107 = 2 * 50 + 7
# 107 -50 7 7 107 = -2 * -50 + 7
# -107 50 -7 43 -107 = -3 * 50 + 43
# -107 -50 -7 43 -107 = 3 * -50 + 43
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 01 June 2013
#
# Author:
#
# John Burkardt
#
# Parameters:
#
# Input, real X, the number to be divided.
#
# Input, real Y, the number that divides X.
#
# Output, real VALUE, the nonnegative remainder when X is divided by Y.
#
from sys import exit
if ( y == 0.0 ):
print ''
print 'R8_MODP - Fatal error!'
print ' R8_MODP ( X, Y ) called with Y = %f' % ( y )
exit ( 'R8_MODP - Fatal error!' )
value = ( x % y )
if ( value < 0.0 ):
value = value + abs ( y )
return value
def r8_modp_test ( ):
#*****************************************************************************80
#
## R8_MODP_TEST tests R8_MODP.
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 01 June 2013
#
# Author:
#
# John Burkardt
#
from r8_uniform_ab import r8_uniform_ab
test_num = 10
print ''
print 'R8_MODP_TEST'
print ' R8_MODP returns the remainder after division.'
print ' Unlike the MATLAB MOD, R8_MODP ( X, Y ) is positive.'
print ''
print ' X Y MOD(X,Y) R8_MODP(X,Y)'
print ''
x_lo = -10.0
x_hi = +10.0
seed = 123456789
for test in range ( 0, test_num ):
[ x, seed ] = r8_uniform_ab ( x_lo, x_hi, seed )
[ y, seed ] = r8_uniform_ab ( x_lo, x_hi, seed )
z1 = ( x % y )
z2 = r8_modp ( x, y )
print ' %12f %12f %12f %12f' % ( x, y, z1, z2 )
#
# Terminate.
#
print ''
print 'R8_MODP_TEST'
print ' Normal end of execution.'
return
if ( __name__ == '__main__' ):
from timestamp import timestamp
timestamp ( )
r8_modp_test ( )
timestamp ( )
|
9a3e11dc97fe7f27a121011d107db72b300f6bd1 | santiago0072002/Python_stuff | /noneexplanationexamples.py | 1,074 | 4.03125 | 4 | # None is the return value of of functions without a return value
# None is an Object, a constant and a singleton.
# Singleton is a creational design pattern, which ensures that only one object of its kind exists and provides a single point of access to it for any other code.
# Singleton has almost the same pros and cons as global variables.
# Although they're super-handy, they break the modularity of your code.
# THIS IS VERY IMPORTANT All variables with a None value point to the same instance of the None, CHECK for None with is instead of ==. AGAIN!!! READ THIS LAST ONE AND EMBRACE IT!!
value = "testing for value"
print(value)
value = None
if value is not None:
print(value)# this is not going to execute becuase the value is set to None and we are testing to see if there is something
# if the value is not the object None then print the value, it is not going to going to print becuase right now the value is pointing to None
if value is None: # here it prints becuase the value is pointing to None.
print(value) |
58c01a4bc6e2c5bce0a25b828ae2d02dd7cca003 | lysevi/concret | /tools/dump2csv.py | 769 | 3.53125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Преобразует дамп к следующему виду:
# сренее значание фитнесса ; номер популяции
import sys
if(len(sys.argv)!=3):
print "usage:\n\t",sys.argv[0],"path_to_source_file dot_count"
sys.exit()
src=file(sys.argv[1])
lines=src.readlines()
cnt=int(sys.argv[2])
pos=0
while pos<len(lines):
splited=lines[pos].split(';')
splited=splited[:-1]
n=int(splited[0])
ftns=map(float,splited[1:])
r=reduce(lambda x,y: x+y,ftns)/len(ftns)
print r,';',n
pos+=int(len(lines)/cnt)
splited=lines[-1].split(';')
splited=splited[:-1]
n=int(splited[0])
ftns=map(float,splited[1:])
r=reduce(lambda x,y: x+y,ftns)/len(ftns)
print r,';',n
|
5c2bbd692883e36a6faab74212abc82e15ea27d2 | RonanD10/Hypergraphs-and-Orthoalgebras | /ps_hasse.py | 1,313 | 3.546875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[3]:
def powerset(s):
PS = []
x = len(s)
for i in range(1 << x):
PS.append([s[j] for j in range(x) if (i & (1 << j))])
PS = sorted(PS, key=len)
for i in range(1,len(s)+1):
PS[i] = i
return PS
print(powerset([1,2,3]))
# In[2]:
from graphviz import Graph
def ps_hasse(list, n):
g = Graph('G', filename='Power set.gv', node_attr={'height': '0.5'})
g.attr(rankdir = 'BT')
g.attr(size = '(%d,%d)!' %(6*n, 6*n))
g.attr(ratio = 'fill')
PS = powerset(list)
# Define EDGES:
# Join zero to atoms
for i in range(1,n+1):
g.edge('{}', '%d' %i)
# Join atoms to height 2 elements
for atom in PS[1:n+1]:
for SET in PS[n+1:]:
if len(SET) > 2:
break
if atom in SET:
g.edge("%d" %atom, " ".join(map(str,SET)))
# Join remaining elements
index = n+2
for SUB in PS[n+1:]:
for SET in PS[index:]:
if len(SET) > len(SUB) + 1:
break
if(all(x in SET for x in SUB)):
g.edge(" ".join(map(str,SUB)), " ".join(map(str,SET)))
index += 1
return g
# for example
list = [1,2,3]
ps_hasse(list,3)
|
54e27aaec173110fb4d831f5d90b45be9a507f6d | salvador-dali/algorithms_math | /training/05_geometry/07_stars.py | 1,186 | 3.59375 | 4 | # https://www.hackerrank.com/challenges/stars
# for every possible 2 points check the sum of the weights above and below the the line
# (not taking into the account these two points). Then also try different combinations with these
# points it can be 2 points above the line, 2 points below the line, 1 point above, one below
import itertools
def betterWeight(m_weight, a, b):
return max(m_weight, min(a, b))
def crossProduct(p1, p2, px):
return (p2[0] - p1[0]) * (px[1] - p1[1]) - (p2[1] - p1[1]) * (px[0] - p1[0])
def bestWeight(points):
w = 0
for p1, p2 in itertools.combinations(points, 2):
above, below = 0, 0
for px in points:
if px != p1 and px != p2:
if crossProduct(p1, p2, px) > 0:
above += px[2]
else:
below += px[2]
w = betterWeight(w, above + p1[2] + p2[2], below)
w = betterWeight(w, above + p1[2], below + p2[2])
w = betterWeight(w, above + p2[2], below + p1[2])
w = betterWeight(w, above, below + p1[2] + p2[2])
return w
points = [map(int, raw_input().split(' ')) for i in xrange(input())]
print bestWeight(points) |
0429fe5047f46d2bf97a5cf30079075dcb5c8027 | projetosparalelos/The-Complete-Python-Course-including-Django-Web-Framework | /Python 201/executable_user_files.py | 324 | 4.03125 | 4 | filename = input("What is the filename? ")
content = input("Enter the content: ")
with open(filename, 'w') as file:
file.write(content)
open_file = input("Would you like to read this file? ")
if open_file in ['y', 'n']:
if open_file == 'y':
with open(filename, 'r') as file:
print(file.read())
|
95f70691313da9a209a54f60b430d9c77fe0a483 | nirorman/FifteenPuzzle | /printer.py | 2,158 | 3.84375 | 4 | import texttable as tt
class Printer(object):
@staticmethod
def print_board(board):
tab = tt.Texttable()
tab.add_rows(board, header=False)
tab.set_cols_align(['c', 'c', 'c', 'c'])
print tab.draw()
@staticmethod
def print_illegal_move():
print("Sorry, that move is illegal in the current board state.")
@staticmethod
def print_illegal_char(user_input_char):
printable = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
print('Invalid input :(')
print(
'You pressed: "' + ''.join(
['\\' + hex(ord(i))[1:] if i not in printable else i for i in user_input_char]) + '"')
print("Sorry, please press an arrow key. to exit press 'q'.")
@staticmethod
def print_start_game():
print("************************************ Welcome to fifteen puzzle! ************************************\n"
"- A tile can be moved to a neighbour empty place.\n"
"- Use the arrow keys in your keyboard to move the tiles: \n"
" - left\n"
" - right\n"
" - up\n"
" - down \n"
"- Use the 'q' key to quit the game.\n"
"- Your number of moves is counted so think through your every move!\n"
"- To win the game you need to order tiles from 1 to 15, \n"
" where tile number 1 is at the top left corner and empty one is at the bottom right corner\n"
"********************************************* Good Luck! *******************************************\n")
@staticmethod
def print_winning_announcement(number_of_moves_taken):
print("Great job! you won! Number of moves taken: {}".format(number_of_moves_taken))
@staticmethod
def print_game_aborted(number_of_moves_taken):
print("Aborting game - Sorry to see you go, come back to try again! Number of moves taken = {}".format(number_of_moves_taken))
@staticmethod
def print_quiting_instructions():
print("press 'q' to exit the game")
|
bf71a77c724973143d6b33b4da92bad30844b01c | voidGlitch/Python-Development | /Day3/odd_even.py | 129 | 4.28125 | 4 | num = int(input("enter any number to check whether its odd or even\n"))
if(num % 2 ==0):
print("even")
else:
print("odd") |
057aeb07b23573e0a25a83ccf5ff549542623d79 | GabePZ/538-Riddler-Solutions | /2020-02-21/riddler_express.py | 438 | 3.875 | 4 | def fahrenheit_to_celsius(temp: int) -> int:
return int(round(((temp - 32) * 5)/9))
def same_backwards(fahrenheit_temp: int) -> None:
celsius_temp = fahrenheit_to_celsius(fahrenheit_temp)
if ''.join(reversed(str(celsius_temp))) == str(fahrenheit_temp):
print(f'F: {fahrenheit_temp}, C: {celsius_temp}')
for f in range(0, 100_000):
same_backwards(f)
## OUTPUT ##
# F: 61, C: 16
# F: 82, C: 28
# F: 7514, C: 4157
|
898bd2b2fbc96b6b65e79a44a4b1557fd806170a | dtu-02819-projects-fall2014/02819 | /topicmining.py | 7,362 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Topic Mining of Wikipedia literature using LDA method.
"""
from gensim import corpora, models
#from itertools import chain, izip_longest
#from urllib import urlopen
from operator import itemgetter
#import mongo_db
import csv
import numpy as np
from matplotlib import pyplot as plt
#from matplotlib import ticker
from collections import Counter
#import pandas as pd
import nltk.corpus
import Data
import stack_plot
import bars
# load complete papers information and abstracts seperately
papers, abstracts = Data.load_data()
# load the transformed documents
dictionary, corpus_tfidf, corpus = Data.prepare_data()
#number_of_topics = 50
def lda_function(number_of_topics):
"""Applies LDA model to the data.
Returns the first six terms of the topics as a list of strings,
the years of publication for the papers of each topic, and the LDA model.
"""
lda = models.LdaModel(corpus=corpus_tfidf, id2word=dictionary, num_topics=number_of_topics)
topics = []
#z = {}
publish_years = []
#count = 0
for i in range(0, number_of_topics):
temp = lda.show_topic(i, 6)
terms = []
for term in temp:
terms.append(term[1])
topics.append(" ".join(terms))
topic_terms = "TOPIC #" + str(i) + ": "+ ", ".join(terms)
print topic_terms
print "-"*80
print "The contribution of first three terms:"
print lda.print_topic(i,3)
year = []
for k in range(len(papers)) :
# maximally probable topic for paper k
if max(lda[corpus[k]],key=itemgetter(1))[0] == i :
#print 'Article:' + str(papers[k][''])
#print 'Manual Topic:' +str(papers[k]['Topic(s)'])
#print 'Year:' + papers[k]['Year']
#count += 1
year.append(int(papers[k]['Year']))
#z = Counter(la)
publish_years.append(year)
#la = dict(izip_longest(*[iter(topics)] * 2, fillvalue=papers[k]['Year']))
print
return topics,publish_years,lda
number_of_topics = 50
topics,publish_years,lda = lda_function(number_of_topics)
def save_results():
"""Saves the generated topics and the papers predicted to belong to each
topic in csv format for later interpretation"""
with open('topics.csv', 'wb') as csvfile:
write_results = csv.writer(csvfile, delimiter = ' ',
quotechar=' ', quoting=csv.QUOTE_MINIMAL)
for index,topic in enumerate(topics):
write_results.writerow("TOPIC#"+str(index)+" " + topic)
write_results.writerow(" ")
for k in range(len(papers)) :
if max(lda[corpus[k]],key=itemgetter(1))[0] == index :
write_results.writerow('- '+str(papers[k]['']) )
write_results.writerow(" ")
#print ha
def inspect_results():
"""Asks the user for a number of paper and prints the title of paper,
the manual topic and the terms of the predicted topic"""
Topics = [str(index) + ' ' +' '.join(tokenize_topics[index]) for index, i in enumerate(tokenize_topics)]
elements = []
for i in range(len(papers)) :
elements.append({'Article': str(papers[i]['']), 'Manual Topic': str(papers[i]['Topic(s)']), 'Predicted Topic': 'topic #'+Topics[max(lda[corpus[i]],key=itemgetter(1))[0]]})
print "Compare manual topic with predicted topic"
element = raw_input('Inspect article (choose a number between 0 and 499, press q to quit): ')
boundary = [str(i) for i in range(len(papers))]
while element != 'q':
if element in boundary:
print elements[int(element)]
element = raw_input('Choose another article or press q to quit: ')
else:
print 'Try again!'
element = raw_input('You should choose a number between 0 and 499: ')
#years =[]
#for i in publish_years:
# years.append(Counter(i))
#for x in range(2002, 2015):
# for i in range(len(years)):
# if years[i][x] == 0 :
# years[i][x] = 0
def fnx(j) :
"""Takes number of topic and returns a list of the number of papers
published from 2002 to 2014 for each topic"""
years =[]
for i in publish_years:
years.append(Counter(i))
for x in range(2002, 2015):
for i in range(len(years)):
if years[i][x] == 0 :
years[i][x] = 0
return years[j].values()
Y = [fnx(y) for y in range(number_of_topics)]
X = np.arange(2002, 2015)
tokenize_topics = [nltk.word_tokenize(topic) for topic in topics]
TopicTitles = [str(index) + ' ' +' '.join(tokenize_topics[index][:2]) for index, i in enumerate(tokenize_topics)]
num_of_papers = [sum(y) for y in Y]
i = 1
popular_topics = []
popular_papers = []
m = max(num_of_papers)
inl = num_of_papers.index(m)
popular_topics.append(num_of_papers.index(m))
popular_papers.append(m)
def la(m, i, inl):
k = max([ind,n] for n,ind in enumerate(num_of_papers) if n not in popular_topics)
popular_topics.append(k[1])
popular_papers.append(k[0])
# popular_papers.append(max(num_of_papers.index(n) for n in num_of_papers if n!=m))
i += 1
m = k[0]
inl = k[1]
if i == 5:
return popular_topics, popular_papers
else:
la(m,i, inl)
la(m,i,inl)
PopularTopicTitles = []
for popular in popular_topics:
for topic in topics:
if popular == topics.index(topic):
PopularTopicTitles.append(str(popular)+topic)
plt.figure(num=4,figsize=(18,16))
labels = PopularTopicTitles + ['other topics']
other = len(papers) - sum(popular_papers)
plt.pie(popular_papers + [other], labels=labels,
autopct='%1.1f%%', shadow=True, startangle=90)
## Set aspect ratio to be equal so that pie is drawn as a circle.
plt.axis('equal')
#
plt.show()
#
#
save_results()
#
stack_plot.stack(number_of_topics, TopicTitles, X, Y)
#
bars.bar_charts(number_of_topics, Y, TopicTitles)
#
inspect_results()
#print
#print 'Which LDA topic maximally describes a document?\n'
#print 'Article:'+ str(papers[i][''])
#print 'Original document: ' + abstracts[0]
#print 'Preprocessed document: ' + str(texts[0])
#print 'Matrix Market format: ' + str(corpus[0])
#print 'Topic probability mixture: ' + str(lda[corpus[i]])
#print 'Maximally probable topic: topic #' + str(max(lda[corpus[i]],key=itemgetter(1))[0])
#print 'TOPIC #0'
#for i in range(100):
#
# if max(lda[corpus[i]],key=itemgetter(1))[0] == 0 :
#
# print 'Article:' + str(papers[i][''])
#topic_main = [str(max(lda[corpus[i]],key=itemgetter(0))[0]) for i in range(0,100)]
#topic0 = [index for index, i in enumerate(topic_main) if i == '0']
#topic1 = [index for index, i in enumerate(topic_main) if i == '1']
#topic2 = [index for index, i in enumerate(topic_main) if i == '2']
#topic3 = [index for index, i in enumerate(topic_main) if i == '3']
#topic4 = [index for index, i in enumerate(topic_main) if i == '4']
#topic5 = [index for index, i in enumerate(topic_main) if i == '5']
|
f3cf38c25203fc92a5f71331877874f00c18bb94 | CoachMac78/user-signup | /test.py | 307 | 3.609375 | 4 |
def character_check(email):
total_at = 0
email = "amac78@gmail.com"
for char in email:
if char == "@":
total_at += 1
return total_at
#if total_at > 1 or total_at < 1:
# error = "Too many @'s. Not a valid email. Please try again."
character_check("amac78@gmail.com") |
52cd8b4c1ec31bd7cd2d109600ad03fcda56690e | Beishenalievv/python-week-sets_2020 | /6/L6-Problem-1: The largest element.py | 119 | 3.5 | 4 | a = input()
b = a.split(",")
list1 = [int(x) for x in b]
list1.sort()
max = len(list1)
max -= 1
print(list1[max])
|
7666d7a271fa60d657ba8c58cbff456788428bea | becdot/pydata-structures | /data_structures.py | 20,039 | 3.953125 | 4 | import random
import math
class Stack(object):
"""First-in, last-out data structure.
Elements can be pushed onto or popped off the stack; can also peek at the top element."""
# error handling?
# implementation with a linked list?
def __init__(self, array):
self.stack = array
def push(self, elem):
self.stack.append(elem)
def pop(self):
return self.stack.pop()
def peek(self):
return self.stack[-1]
# Queue
class Queue(object):
"""First-in, first-out data structure.
Elements can be pushed onto the end of the queue, and popped off the front of the queue."""
# error handling?
# implementation with a singly- or doubly-linked list?
def __init__(self, array):
self.queue = array
def push(self, elem):
self.queue.append(elem)
def pop(self):
elem = self.queue[0]
self.queue = self.queue[1:]
return elem
def peek(self):
return self.queue[0]
# Singly-linked list
class Node(object):
"Node with pointer/s and value -- self.prev used only for doubly-linked list"
def __init__(self, value):
self.value = value
self.next = None
self.prev = None
def __str__(self):
return str(self.value)
class SinglyLinkedList(object):
"""Collection of nodes, each with a value and a pointer to the next node.
Nodes can be inserted and removed after existing nodes."""
def __init__(self):
self.head = None
def __iter__(self):
node = self.head
while node:
yield node
node = node.next
def __str__(self):
return str([str(node) for node in self])
def __getitem__(self, index):
for i, item in enumerate(self):
if i == index:
return item
else:
raise IndexError
def __len__(self):
return sum(1 for i in self)
def insert(self, value, index):
if index == 0:
self._insert(Node(value))
return
for i, n in enumerate(self):
if i == index:
self._insert(Node(value), n)
break
else:
self._insert(Node(value), n)
def _insert(self, node, previous=None):
if previous:
node.next = previous.next
previous.next = node
else:
node.next = self.head
self.head = node
def remove(self, index):
if index == 0:
self._remove()
return
for i, n in enumerate(self):
if i == index - 1:
self._remove(n)
break
else:
raise IndexError, "list assignment index out of range"
def _remove(self, previous=None):
if previous:
previous.next = previous.next.next if previous.next else None
else:
self.head = self.head.next
# Doubly-linked list
class DoublyLinkedList(object):
def __init__(self):
self.head = None
self.tail = None
def __iter__(self):
node = self.head
while node:
yield node
node = node.next
def __len__(self):
return sum(1 for node in self)
def __str__(self):
return str([str(node) for node in self])
def __getitem__(self, index):
for i, n in enumerate(self):
if i == index:
return n
else:
raise IndexError
def insert(self, value, index):
"""Inserts Node(value) at the index -- iterates forward if index is in the first half of the list
and backwards if index is in the second half of the list"""
# to insert at the beginning, or when the list is empty
if not(len(self) and index):
self._insert(Node(value))
# to insert at the end of a list
elif index >= len(self):
self._rev_insert(Node(value))
# iterate forwards
elif len(self)/2.0 > index:
# iterate forwards
for i, n in enumerate(self):
if i == index:
self._insert(Node(value), n)
# iterate backwards
else:
for i, n in enumerate(reversed(self)):
if abs(i - len(self) + 1) == index:
self._rev_insert(Node(value), n)
break
def _insert(self, node, prev_node=None):
"""Inserts node after prev_node -- base implementation of insert().
If prev_node is not provided, inserts at the beginning"""
self.tail = node if self.tail == prev_node else self.tail
if prev_node:
node.next = prev_node.next
node.prev = prev_node
prev_node.next = node
if node.next:
node.next.prev = node
else:
if self.head:
self.head.prev = node
node.next = self.head
self.head = node
def _rev_insert(self, node, prev_node=None):
"""Inserts node after prev_node, moving in reverse.
e.g given a list [A, C], insert(B, C) -> [A, B, C]
If prev_node is not provided, inserts at the end of the list"""
self.head = node if self.head == prev_node else self.head
if prev_node:
node.prev = prev_node.prev
node.next = prev_node
prev_node.prev = node
if node.prev:
node.prev.next = node
else:
if self.tail:
self.tail.next = node
node.prev = self.tail
self.tail = node
# Binary Tree
## UNSORTED
class BinaryNode(object):
# always inserts to the left
def __init__(self, value):
self.value = value
self.parent = None
self.right = None
self.left = None
def __str__(self):
return str(self.value)
def __eq__(self, other):
return self.value == other.value if isinstance(other, BinaryNode) else False
def __ne__(self, other):
return self.value != other.value if isinstance(other, BinaryNode) else True
def __ge__(self, other):
return self.value >= other.value if isinstance(other, BinaryNode) else False
def __gt__(self, other):
return self.value > other.value if isinstance(other, BinaryNode) else False
def __le__(self, other):
return self.value <= other.value if isinstance(other, BinaryNode) else False
def __lt__(self, other):
return self.value < other.value if isinstance(other, BinaryNode) else False
@property
def empty(self):
return not(self.right or self.left)
def insert(self, node, child=None):
if child and (child.left or child.right):
raise AttributeError("Node cannot have any children.")
# we want to insert the node internally
if child:
direction = 'left' if self.left == child else 'right'
node.left = getattr(self, direction)
node.parent = self
child.parent = node
setattr(self, direction, node)
# we want to add the node externally
else:
# add node to self.left if self.left is currently unassigned
self.left = self.left if self.left else node
# add node to self.right if self.right is unassigned and you haven't just assigned self.left
self.right = self.right if self.right or self.left == node else node
node.parent = self
# def depth(self):
# yield self
# if self.left:
# for node in self.left.depth():
# yield node
# if self.right:
# for node in self.right.depth():
# yield node
class BinaryTree(object):
def __init__(self):
self.root = None
def __iter__(self):
"Iterates depthwise through the tree"
for node in self.depth_gen(self.root):
yield node
def __contains__(self, value):
"Returns True if value exists in the tree, else returns False"
for node in self:
if node.value == value:
return True
return False
def __getitem__(self, value):
"Value is the value of the node, NOT the index"
for node in self:
if node.value == value:
return node
def __eq__(self, other):
return self.value == other.value
def __ne__(self):
return self.value != other.value
def depth_gen(self, node):
"Generates nodes moving depthwise"
if node.empty:
yield node
else:
yield node
if node.left:
left = self.depth_gen(node.left)
for n in left:
yield n
if node.right:
right = self.depth_gen(node.right)
for n in right:
yield n
def breadth_gen(self, node_list):
"Just for fun -- semi-lazy implementation"
next = []
for node in node_list:
yield node
next.append(node.left) if node.left else None
next.append(node.right) if node.right else None
if next:
for n in self.breadth_gen(next):
yield n
def insert(self, value, parent_value=None, child_value=None):
"""Inserts the value between the parent node and the child node
If child node does not exist, tries to add the node as a leaf to the parent"""
new_node = BinaryNode(value)
child_node = self[child_value] if child_value else None
if parent_value:
for node in self:
if node.value == parent_value:
node.insert(new_node, child_node)
else:
self.root = BinaryNode(value)
# Binary Search Tree
class BinarySearchNode(BinaryNode):
def __contains__(self, value):
if self.search(value):
return True
return False
def __getitem__(self, value):
node = self.search(value)
if node:
return node
else:
raise AttributeError("{} does not exist".format(value))
def search(self, value):
"Traverses the tree -- average time of log(n)"
if self.value == value:
return self
elif value > self.value:
return self.right.search(value) if self.right else None
else:
return self.left.search(value) if self.left else None
def insert(self, value):
"Inserts a node with value in the appropriate place. Cannot have duplicate nodes."
if self.value == value:
raise IndexError("{} already exists".format(value))
elif self.right and value > self.value:
return self.right.insert(value)
elif self.left and value < self.value:
return self.left.insert(value)
elif value > self.value:
self.right = BinarySearchNode(value)
self.right.parent = self
else:
self.left = BinarySearchNode(value)
self.left.parent = self
def _delete(self, successor=None):
"Delete node by updating its parent and child/ren -- should not be called directly"
# successor is only used for testing purposes, to prevent the successor from being chosen randomly
if not(self.left and self.right):
# if node has one or fewer children, deletion is easy
# update parent to point to our child, if it exists
self.parent.left = self.left if self.parent.left == self else self.parent.left
self.parent.right = self.right if self.parent.right == self else self.parent.right
# update our child, if it exists, to point to our parent
if self.left:
self.left.parent = self.parent
if self.right:
self.right.parent = self.parent
else:
# if node has two children, have to choose which child replaces it
successor = successor or random.choice([self.left, self.right])
# update parent to point to successor
successor.parent = self.parent
successor.parent.left = successor if successor.parent.left == self else successor.parent.left
successor.parent.right = successor if successor.parent.right == self else successor.parent.right
# move our children to be children of successor (or of successor's children)
if successor == self.right:
ext_left = successor
while ext_left.left:
ext_left = ext_left.left
ext_left.left = self.left
self.left.parent = ext_left
else:
ext_right = successor
while ext_right.right:
ext_right = ext_right.right
ext_right.right = self.right
self.right.parent = ext_right
del self
def remove(self, value, successor=None):
"Removes the node with value. Successor is for testing purposes, since delete chooses the successor randomly"
if self.value == value:
self._delete(successor)
elif self.right and value >= self.value:
return self.right.remove(value, successor)
elif self.left and value <= self.value:
return self.left.remove(value, successor)
else:
raise AttributeError("{} does not exist".format(value))
# Heap
class HeapNode(BinaryNode):
pass
# can have duplicates in a heap
# def __eq__(self, other):
# return self == other
# def __ne__(self, other):
# return self == other
# @staticmethod
# def breadth(children):
# next = []
# for node in children:
# yield node
# next.append(node.left) if node.left else None
# next.append(node.right) if node.right else None
# if next:
# for n in Heap.breadth(next):
# yield n
# def depth(self, level=0):
# "Generator that yields (value, level) where root level = 0, root child level = 1, etc"
# yield self.value, level
# level = level if self.empty else level + 1
# if self.left:
# for node in self.left.depth(level):
# yield node
# if self.right:
# for node in self.right.depth(level):
# yield node
class Heap(object):
def __init__(self, root=None, array=None):
if array:
self.heapify(array)
else:
self.root = root
def __iter__(self):
"Uses breadth-first iteration to iterate through the nodes"
for node in self.breadth():
yield node
def __len__(self):
"Number of nodes"
return sum(1 for node in self)
def __getitem__(self, index):
"Supports positive and negative indexing -- does not support slicing"
if index >= 0:
for i, node in enumerate(self):
if i == index:
return node
elif index < 0:
for i, node in enumerate(reversed(self)):
if (-i - 1) == index:
return node
else:
raise IndexError
def flatten(self):
"Returns a list of node values, in heap order"
return [int(str(n)) for n in self]
def breadth(self, children=None):
"Generates nodes in a breadth-first fashion"
children = [self.root] if children == None else children
next = []
for node in children:
yield node
next.append(node.left) if node.left else None
next.append(node.right) if node.right else None
if next:
for n in self.breadth(next):
yield n
def find_open(self):
"""Finds the next open position for insertion
Returns a tuple of (parent_node, which_child_to_insert)"""
for node in self:
if node.right:
continue
elif node.left:
return (node, 'right')
else:
return (node, 'left')
def insert(self, value):
"""Inserts a node with value in the next open position,
and bubbles it upwards if necessary to preserve heapifiedness"""
node = HeapNode(value)
parent, place = self.find_open()
node.parent = parent
setattr(parent, place, node)
self.bubble(node)
def swap_parent(self, node):
"Given a node, updates all necessary pointers to swap the node with its parent, and returns the node"
# make sure the node needs to be swapped
if node.parent == None or node <= node.parent:
return node
old_parent = node.parent
grandparent = old_parent.parent
old_left = node.left
old_right = node.right
# attach node to its grandparent (new parent)
node.parent = grandparent
if grandparent and grandparent.right is old_parent:
grandparent.right = node
elif grandparent and grandparent.left is old_parent:
grandparent.left = node
# add old parent as a child of node
old_parent.parent = node
if old_parent.left is node:
node.left = old_parent
else:
node.right = old_parent
# if node had a sibling, add it as a child of node
if old_parent.right is node and old_parent.left:
node.left = old_parent.left
old_parent.left.parent = node
elif old_parent.left is node and old_parent.right:
node.right = old_parent.right
old_parent.right.parent = node
# add any of node's old children as the children of the swapped (old parent) node
old_parent.left = old_left
old_parent.right = old_right
if old_left:
old_left.parent = old_parent
if old_right:
old_right.parent = old_parent
# finally, if node has bubbled to the top of the heap, update self.root
if node.parent == None:
self.root = node
return node
def bubble(self, node):
"Bubbles a node upwards until it reaches heapifiedness"
while node.parent and node > node.parent:
node = self.swap_parent(node)
def heapify(self, arr):
"Builds a heap from a list"
self.root = HeapNode(arr[0])
for val in arr[1:]:
self.insert(val)
def delete_root(self):
"""Deletes the root node, replaces it with the last element,
and bubbles it down until heapifiedness is achieved"""
# if there is only a root node, delete it
if len(self) == 1:
del self.root
self.root = None
return
# otherwise, replace the node at the top of the heap with the last element
last = self[-1]
# remove old references to last
last.parent.right = None if last.parent.right is last else last.parent.right
last.parent.left = None if last.parent.left is last else last.parent.left
last.parent = None
# attach root's old children to last
last.left, last.right = self.root.left, self.root.right
if last.left:
last.left.parent = last
if last.right:
last.right.parent = last
# update self.root
del self.root
self.root = last
# while last is smaller than its children, swap it with the largest of its children
# until heapifiedness is achieved
while last < last.right or last < last.left:
to_swap = last.left if last.left > last.right else last.right
new_parent = self.swap_parent(to_swap)
last = new_parent.right if new_parent.right is last else new_parent.left |
fc5937e580fba89376ce9f6dc4cc2fdfc1a74e6c | xopapop/thermohome | /classes.py | 739 | 3.859375 | 4 | from datetime import datetime
class weather():
def __init__(self, weather_dict):
self.dt = ''
self.temp_k = float()
self.rh = int()
self.description = ''
self.wind_speed = float()
self.wind_angle = float()
# save everything in the weather dict as an attribute
# remove this once this data structures is nailed down
for attr_name in weather_dict:
setattr(self, attr_name, weather_dict[attr_name])
# calculated attributes
self.temp_c = float() # convert from farenheit
self.temp_f = float() # convert from celsius
self.wind_angle_compass = '' # convert wind angle in degrees to the closest 8-point compass direction
|
0cdbc1c9d038a42c71c65aaf7598e2ca28c99723 | humachine/AlgoLearning | /leetcode/Done/301_RemoveInvalidParentheses.py | 5,427 | 4.09375 | 4 | #https://leetcode.com/problems/remove-invalid-parentheses/
'''
Given a string, remove the minimal number of parentheses required to make the string valid again.
Inp: "()())()"
Out: ["()()()", "(())()"]
Inp: "(a)())()"
Out: ["(a)()()", "(a())()"]
Inp: ")("
Out: [""]
'''
class Solution(object):
'''
Checking if a string is valid is straightforward.
Now, we start with the base string s.
At each level, we generate all valid strings possible by deleting a single character from s.
Then we filter this list to see if we get any valid strings out of this.
If not, we repeat this process until we are done.
'''
def _isValid(self, s):
# A string is valid if it always has left parentheses count >= right count. And if there are equal number of both parentheses at the end of the string.
if not s:
return True
ctr = 0
for char in s:
if char == '(':
ctr +=1
elif char == ')':
ctr -= 1
if ctr < 0:
return False
return ctr == 0
def removeInvalidParentheses(self, s):
if not s: return ['']
# The strings we have at the current level (level 0) is just the input string s
currLevelStrings = {s}
while True:
# We filter all of currLevelStrings checking for valid strings
validStrings = filter(self._isValid, currLevelStrings)
# If we even find ONE valid string, then this is the list of valid strings with minimum number of removals
if validStrings:
return list(validStrings)
# Since we haven't had any valid strings at this level, we generate the next level of strings
# The next level of strings is generated by remove one letter at a time from each of the previous level's strings
currLevelStrings = {s[:i]+s[i+1:] for s in currLevelStrings for i in xrange(len(s))}
# ----------------------------------------------------------------------------------------------------------------
def _remove(self, s, res, last_i, last_j, par):
'''
Removes all invalid parentheses as per required and appends the valid ones to the result.
Inp:
s: str, input string
res: list, list containing the result strings
last_i: int, the last location at which the string became invalid
last_j: int, the last location at which we removed a parenthesis
par: str, string of length 2 which represents the order of parentheses that we are looking at. () means we are looking to remove extra ). () means we are looking to remove any extra (
'''
ctr = 0
for i in xrange(last_i, len(s)):
# Altering counter based on which parentheses we see
ctr += (s[i]==par[0]) - (s[i]==par[1])
# If counter is >=0, we are still having a valid string
if ctr >= 0:
continue
# If the code has reached this point, then ctr < 0 => We have more par[1] than par[0] at this point.
# We start looking ahead from the last location that we removed a parentheses and try to find another offending par[1].
# This par[1] should be such that it's either at the same location that we removed one the previous time (OR) it should not be the 2nd or 3rd or so of a series of parentheses (s[j-1]!=par[1])
for j in xrange(last_j, i+1):
if s[j] == par[1] and (j==last_j or s[j-1]!=par[1]): # We allow j==last_j because the current string was obtained by removing last_j from the previous string. So last_string[j+1] is currStr[j] which is still an unremoved/NOT previously deleted paren
self._remove(s[:j]+s[j+1:], res, i, j, par)
return
# If the code has reached this point, then i has reached len(s)
rev = s[::-1]
# If par[0] is ), then we have performed both L-R and R-L checks, thus eliminating both extra ) and extra (. Thus we can now append the reverse(s) (s itself is now reverse(the original input s))
if par[0] == ')':
res.append(rev)
# If par[0]!+')', then we have only completed the first L-R check. We now trigger the R-L check.
else:
self._remove(rev, res, 0, 0, ')(')
def removeInvalidParenthesesPruned(self, s):
#https://discuss.leetcode.com/topic/34875/easy-short-concise-and-fast-java-dfs-3-ms-solution/14
'''
In this beautiful solution, we try to adhere to a few principles.
First, we attempt to run through the array and remove any errant right parentheses to make it valid.
At the end of this first stage, we will have removed all the necessary ) to try and make it valid.
Since removal of ) does not just make the string a valid string, we next attempt to try and remove any extra ( that may exist.
The way we accomplish the second stage, is by reversing the string and reversing the order of parentheses we consider
'''
if not s: return ['']
res = []
self._remove(s, res, 0, 0, '()')
return res
s = Solution()
print s.removeInvalidParenthesesPruned('()())()')
print s.removeInvalidParenthesesPruned('(a)())()')
print s.removeInvalidParenthesesPruned(')(')
|
c7b9860819ad092e57f9e1fed7e668bfc2b6559a | melijov/course_python_essential_training | /string-functions.py | 1,073 | 4.09375 | 4 | def main():
string_functions()
class kitten:
def __init__(self, n):
self._n = n
class bunny:
def __init__(self, n):
self._n = n
def __repr__(self):
return f'repr: the number of bunnies is {self._n}'
def __str__(self):
return f'str: the number of bunnies is {self._n}'
def string_functions():
s = 'Hello, World.'
print(repr(s)) # __repr__ representation of the object
print(s) # __str__ representation of the object
k= kitten(47)
b = bunny(47)
print(repr(k)) # if no specific __repr__ method is defined the default value is returned
print(repr(b)) # __repr__ representation of the object
print(b) # __str__ representation of the object (if __str__ is not defined it will pick __repr__ value)
print(ascii(b)) # ascii works like __repr__ but converts any special characters into an escaped sequence
print(chr(128406)) # prints the character of a number
print(ord(chr(128406))) # prints the number of a character
if __name__ == '__main__':main() |
450953fcb856801906964cfa573a4f46d2166443 | sgalban/geoquiz | /db_files/country_code_dict.py | 284 | 3.609375 | 4 | import json
from pprint import pprint
data = json.load(open('all.json'))
code_dict = {}
for i in range(len(data)):
code = data[i]["Code"]
name = data[i]["Government"]["Country name"]["conventional short form"]["text"]
code_dict[name] = code
## Example
print(code_dict["Syria"]) |
5bc7e5bd89df06932027f0e237dacac34d221f71 | hanshuo11/my_python | /test/test13.py | 535 | 3.890625 | 4 | #!/user/bin/env python
# -*- coding: utf-8 -*-
# Author:HanShuo
# class Student(object):
# def set_age(self,age):
# self.age=age
# # s=Student()
# # s.set_age(26)
# # print(s.age)
# def set_name(self,name):
# self.name=name
# # 增加set_name函数
# Student.set_name=set_name
#
# s=Student()
# s.set_name("hanshuo")
# print(s.name)
# __slots__
# class Student():
# # 限制添加的属性
# __slots__ = ('name','age')
#
# s=Student()
# s.name="hanshuo"
# s.age=21
# # s.score=100
# print(s.name)
|
ff92463389ba25d5aa6a0df5f4ca6d3a398c94d7 | abhishekthukaram/Course-python | /Recursion/stringreverse.py | 803 | 4.46875 | 4 | """
Reverse a string using recursion
"""
def reverse_string(input):
"""
Return reversed input string
Examples:
reverse_string("abc") returns "cba"
Args:
input(str): string to be reversed
Returns:
a string that is the reverse of input
"""
if input=="":
return input
else:
print input[1:]
return reverse_string(input[1:])+input[0]
print reverse_string('abc')
def is_palindrome(input):
"""
Return True if input is palindrome, False otherwise.
Args:
input(str): input to be checked if it is palindrome
"""
if len(input)<=1:
return True
else:
first = input[0]
last = input[-1]
return first == last and is_palindrome(input[1:-1])
print is_palindrome('madame')
|
002cb6f70b2343b7a10e3064c21c43b045517f22 | parkerjacks/python-103-small.py | /square2.py | 322 | 4.09375 | 4 | #Create a square of astericks made up of a NxN characters decided by user
#Set it Up
square_length = int(input("Enter a number for the length of your square: "))
square_is_made_of = '*'
count = 0
#Work it Out
while count < square_length:
print (square_is_made_of * square_length)
count = count + 1
#Finish
|
07972b377c0895f67b2d51d3d6f6f1e598ad31e2 | lukexyz/Hadoop-MapReduce | /friends-by-age.py | 704 | 3.625 | 4 | from mrjob.job import MRJob
class MRFriendsByAge(MRJob):
""" MapReduce to find average number of friends by age"""
def mapper(self, _, line):
# break datafile in separate fields
(ID, name, age, numFriends) = line.split(',')
yield age, float(numFriends)
def reducer(self, age, numFriends):
total = 0
numElements = 0
# iterates list for find totals
for x in numFriends:
total += x
numElements += 1
# calculates average
yield age, round(total / numElements, 1)
if __name__ == '__main__':
MRFriendsByAge.run()
# Usage:
# python friends-by-age.py data/fakefriends.csv > friendsbyage.txt
|
f96755033703b349f5ea60530fceda85da27e139 | babuhacker/python_toturial | /hackerrank_last_15/Detect Floating Point Number.py | 135 | 3.546875 | 4 | import re
n = int(input())
pattern = r'^[+-]?[0-9]*\.[0-9]+$'
for i in range(n):
s = input()
print(bool(re.match(pattern, s)))
|
9e26b413223f30d2cb4b67c6f106fb9b054f17d4 | shivambhilarkar/Codevita-Solutions | /coindistribution.py | 2,319 | 4 | 4 | # Problem Statement
# Find the minimum number of coins required to form any value between 1 to N,both inclusive.Cumulative value of coins should not exceed N. Coin denominations are 1 Rupee, 2 Rupee and 5 Rupee.Let’s Understand the problem using the following example. Consider the value of N is 13, then the minimum number of coins required to formulate any value between 1 and 13, is 6. One 5 Rupee, three 2 Rupee and two 1 Rupee coins are required to realize any value between 1 and 13. Hence this is the answer.However, if one takes two 5 Rupee coins, one 2 rupee coin and two 1 rupee coin, then too all values between 1 and 13 are achieved. But since the cumulative value of all coins equals 14, i.e., exceeds 13, this is not the answer.
# Input Format:
# A single integer value.
# Output Format:
# Four space separated integer values.
# 1st – Total number of coins.
# 2nd – number of 5 Rupee coins.
# 3rd – number of 2 Rupee coins.
# 4th – number of 1 Rupee coins.
# Constraints:
# 0 < n < 1000
# Refer the sample output for formatting
# Sample Input
# 13
# Sample Output
# 6 1 3 2
# Explanation
# The minimum number of coins required is 6 with in it:
# minimum number of 5 Rupee coins = 1
# minimum number of 2 Rupee coins = 3
# minimum number of 1 Rupee coins = 2
# Using these coins, we can form any value with in the given value and itself, like below:
# Here the given value is 13
# For 1 = one 1 Rupee coin
# For 2 = one 2 Rupee coin
# For 3 = one 1 Rupee coin and one 2 Rupee coins
# For 4 = two 2 Rupee coins
# For 5 = one 5 Rupee coin
# For 6 = one 5 Rupee and one 1 Rupee coins
# For 7 = one 5 Rupee and one 2 Rupee coins
# For 8 = one 5 Rupee, one 2 Rupee and one 1 Rupee coins
# For 9 = one 5 Rupee and two 2 Rupee coins
# For 10 = one 5 Rupee, two 2 Rupee and one 1 Rupee coins
# For 11 = one 5 Rupee, two 2 Rupee and two 1 Rupee coins
# For 12 = one 5 Rupee, three 2 Rupee and one 1 Rupee coins
# For 13 = one 5 Rupee, three 2 Rupee and two 1 Rupee coins
number = int (input ())
five = int ((number - 4) / 5)
one=1
two = ((number - 5 * five - one)//2)
if ((number - 5 * five) % 2)== 0:
one = 2
else:
two = ((number - 5 * five - one)//2)
one = 1
two = ((number - 5 * five - one)//2)
print (one + two + five)
# print (one + two + five, five, two, one) |
98c0bf837ca7d21c988471f6334e4012ff0ffe32 | Ameema-Arif/Scientific-Calculator-using-Python | /Sub.py | 133 | 3.671875 | 4 |
def sub():
A=float(input("1st Value:"))
B=float(input("2nd Value:"))
C=A-B
print(C)
|
7bd9931f8bf36865ed1001dd46e232a74637bbd7 | carrickdb/CodingPractice | /partition_array.py | 1,356 | 3.890625 | 4 | def partition_array(nums):
greatest_left = nums[0]
greatest_right = -1
left_size = -1
for i in range(1, len(nums)):
if greatest_left <= nums[i]:
if left_size < 0:
left_size = i
if greatest_right <= nums[i]:
greatest_right = nums[i]
elif left_size > 0:
left_size = -1
greatest_left = greatest_right
return left_size
"""
806166225460393
[1,1,1,0,6,12]
greatest_left = 2
greatest_right = 6
left_size = 5
nums = [7, 6, 8, 4, 2, 9, 12, 11]
nums = [7, 6, 7, 9, 12, 11]
iterate through array
if largest_left is less than current number at i:
if partition has been set:
set greatest_right to this number
else:
partition = i
else:
if partition has been set:
partition = -1
greatest_left = greatest_right
else:
pass
hold on to greatest number x seen so far
when you see an even greater number at i, hold on to i
if you see a number less than x, set x to the even greater number
return i
naive: n^2
sort: out of order
sliding window?
"""
# nums = [7, 6, 8, 4, 2, 9, 9] # 5
nums = [7, 6, 7, 9, 12, 11] # 2
nums = [7, 6, 9, 12, 7, 15] # 2
nums = [1,1,1,0,6,12] # 4
nums = [5,0,3,8,6] # 3
nums = [1, 2]
nums = [1, 1]
print(partition_array(nums))
|
8db24652f3a1561504649d8154cefb3c4ab94e76 | Anjitha-Sivadas/luminarpythonprograms | /Advance python/EXAM.py | 5,077 | 4.5625 | 5 | # 1 create a child class bus that will inherit
# all of the variables and methods of vehicle class
"""
class Vehicle:
bus_name=""
def no_of_veh(self):
print("one")
class Color:
veh_color=""
def clr(self):
print("color of vehicle:",self.veh_color)
class Bus(Vehicle,Color):
def cbus(self):
print("Bus name:",self.bus_name)
print("Vehicle color:",self.veh_color)
obj=Bus()
obj.bus_name="ABC"
obj.veh_color="Blue"
obj.cbus()
"""
# 2 Create an example for three types of inheritance in one program
# by using Person as main class?
"""
class Person():
#single
person_name="ANIL"
def m1(self,age):
self.age = age
print("my name is",Person.person_name)
print(self.age)
class Sub(Person):
def m2(self,page):
self.page=page
print("name is", Person.person_name)
print(self.page)
print(self.age)
op=Sub()
op.m1(25)
op.m2(30)
#multiple
class Child(Sub,Person):
def m3(self,cage):
self.cage=cage
print("parent name is",Person.person_name)
print(self.cage)
print(self.page)
print(self.age)
obj=Child()
obj.m1(35)
obj.m2(68)
obj.m3(5)
#multilevel
class Subchild(Sub):
def m4(self):
print("inside subchild class")
m=Subchild()
m.m4()
m.m1(78)
m.m2(85)
"""
# 3 Create a Book class with instance Library_name, book_name, author, pages?
"""
class Book():
def __init__(self,library_name,book_name,author,pages):
self.library_name=library_name
self.book_name=book_name
self.author=author
self.pages=pages
def printval(self):
print(self.library_name,self.book_name,self.author,self.pages)
opj=Book("ABC","SECRET","Rhonda",100)
opj.printval()
"""
# 4 Create an Animal class using constructor and build a child class for Dog?
"""
class Animal():
animal_name="dog"
def __init__(self,num):
self.num= num
def name(self):
print(" name is",Animal.animal_name)
print(self.num)
class Dog(Animal):
def nameis(self):
print("animal name is", Animal.animal_name)
print(self.num)
op=Animal(2)
op.name()
boj=Dog(3)
boj.nameis()
"""
""""
class Animal:
def __init__(self,name,age):
self.name=name
self.age=age
def printval(self):
print("name",self.name)
print("age",self.age)
class Dog(Animal):
def __init__(self,color,name,age):
super().__init__(name,age)
self.color=color
def print(self):
print(self.color)
cr=Dog("brown","chottu",2)
cr.printval()
cr.print()
"""
# 5 What is method overriding give an example using Books class?
"""
class Books:
def color(self):
print("Blue color book ")
class Book(Books):
def color(self):
print("Green color book")
obj=Book()
obj.color()
"""
# 6 Create objects of the following file and print the details of student
# with maximum mark? anu,1,bca,200 rahul,2,bba,177 vinod,3,bba,187 ajay,4,
# bca,198 maya,5, bba,195
"""
f=open("student","r")
class student():
class student():
def __init__(self, rno, name, department,mark):
self.rno = rno
self.name = name
self.department = department
self.mark = mark
def __str__(self):
return self.name + " " + str(self.mark)
students = []
for lines in f:
rno, name, department,mark = lines.rstrip("\n").split(",")
students.append(student(rno, name, department, mark))
for data in students:
print(data)
marks= []
for stud in students:
marks.append(stud.mark)
print(max(marks))
"""
# 7 Create a valid phone numbers file from the following file?
# +915678905432 +914567890321 765432167 123450987765 +919976532456
"""
from re import *
f=open("pnum","r")
lst=[]
rule='[+]91[0-9]{10}'
for lines in f:
variablename=lines.rstrip("\n")
matcher = fullmatch(rule, variablename)
if matcher != None:
print('valid',variablename)
lst.append(variablename)
else:
print("invalid variable name",variablename)
print(lst)
"""
# 8 When is the finally block executed.Explain with example?
"""
no1=int(input("enter num1"))
no2=int(input("enter num2"))
try:
res=no1/no2
print(res)
except Exception as e:
print("exeception occured",e.args)
finally:
print("database is created")
"""
# 9 Write a Python program to find the sequences of
# one upper case letter followed by lower case letters?
"""
from re import *
rule='[A-Z]+[a-z]+$'
variable_name=input("enter variable name")
matcher=fullmatch(rule,variable_name)
if matcher!=None:
print("valid variable name")
else:
print("invalid variable name")
"""
# 10 Write a Python program that matches a string that has an 'a'
# followed by anything, ending in 'b'?
from re import *
pattern="a.*?b$"
string="addddhhhhrrrsssb"
matcher=finditer(pattern,string)
cnt=0
for match in matcher:
print(match.start())
print(match.group())
cnt=1
if cnt==1:
print(' found a match')
else:
print('not matched') |
00762117dca0fc0bfdbebdf61a7ebc1c42734ecb | shekher1997/Wipro-PBL | /dict.py | 890 | 3.5625 | 4 | # Hands-on Assignment 1
dict1 = {1:'A', 2:'B'}
dict1[3] = 'C'
print(dict1)
print(end="\n")
# Hands-on Assignment 2
dictA = {1:10, 2:20}
dictB = {3:30, 4:40}
dictC = {4:40, 5:50, 6:60}
for keys in dictB:
dictA[keys] = dictB[keys]
for keys in dictC:
dictA[keys] = dictC[keys]
print(dictA)
print(end="\n")
# Hands-on Assignment 3
if 4 in dictA:
print("Present")
print(end="\n")
# Hands-on Assignment 4
for keys in dictA:
print(keys, sep=" ", end=" ")
print(end="\n\n")
for keys in dictA:
print(dictA[keys], sep=" ", end=" ")
print(end="\n\n")
for keys in dictA:
print(keys, end=" = ")
print(dictA[keys], sep='', end='\n')
print(end="\n")
# Hands-on Assignment 5
dictD = {}
for keys in range(1,16,1):
dictD[keys] = keys**2
print(dictD, end="\n\n")
# Hands-on Assignment 6
sum = 0
for keys in dictD:
sum = sum + dictD[keys]
print(sum)
|
da0e0aaea16bfe1f28fb3312a7a0685ad8877cfa | litvinchuck/python-workout | /algorithms/binary_search.py | 1,311 | 4.25 | 4 | """Binary search implementation. Expected performance O(lg(n))"""
def search(array, element):
""" Searches array for an element and returns its index
Args:
array: searched array
element: element to search for
Returns:
int: element index if element is found, -1 otherwise
"""
return binary_search(array, element, 0, len(array) - 1)
def binary_search(array, element, min_index, max_index):
""" Searches array for an element using binary search algorithm and returns its index
Args:
array: searched array
element: element to search for
min_index: search range minimal index
max_index: search range maximal index
Returns:
int: element index if element is found, -1 otherwise
"""
if min_index > max_index:
return -1
middle_index = (max_index + min_index) // 2
if array[middle_index] < element:
return binary_search(array, element, middle_index + 1, max_index)
elif array[middle_index] > element:
return binary_search(array, element, min_index, middle_index)
else:
return middle_index
if __name__ == '__main__':
array = [0, 1, 2, 3, 4, 5, 6]
for element in array:
assert search(array, element) == element
assert search(array, 7) == -1
|
b141a1d420edda7050204f0eab963e84bd56b369 | tomki1/file-transfer-system | /ftclient.py | 11,902 | 3.75 | 4 | # Author: Kimberly Tom
# Project 2: File Transfer System
# Description: client side code written in Python. This program can request to get a listing from a server's directory or obtain a file from the server's directory.
# This program uses TCP connection to transfer data.
# CS372 Intro To Computer Networks
# Last Modified: 11/28/19
import sys
import os
from socket import *
# validateArgs verifies the user input valid arguments
# preconditions: user has entered arguments on the command line
# postconditions: validates arguments and displays error message if invalid argument
# with help from https://stackoverflow.com/questions/35491845/checking-the-number-of-command-line-arguments-in-python
def validateArgs():
# port numbers must be a number betwen 1024-65535
minPort = int(1024)
maxPort = int(65535)
# verify the number of arguments is not less than 5
if len(sys.argv) < 5:
print ("You have entered too few arguments. Exiting Program.")
sys.exit()
# verify the number of arguments is not greater than 6
if len(sys.argv) > 6:
print ("You have entered too many arguments. Exiting Program.")
sys.exit()
# verify that the 2nd argument is a valid flip server
if sys.argv[1] != "flip1" and sys.argv[1] != "flip2" and sys.argv[1] != "flip3":
print ("You have entered an incorrect server. It must be flip1 flip2 or flip3. Exiting Program.")
sys.exit()
# verify that the command is either -l or -g
if sys.argv[3] != "-l" and sys.argv[3] != "-g":
print ("The command must either be -l or -g. Exiting Program.")
sys.exit()
# verify that if user wants to use the command -l that there are 5 arguments
if sys.argv[3] == "-l" and len(sys.argv) != 5:
print ("You have entered the incorrect number of arguments to use the command -l. Exiting Program.")
sys.exit()
# verify that if user wants to use the command -g that there are 6 arguments
if sys.argv[3] == "-g" and len(sys.argv) != 6:
print ("You have entered the incorrect number of arguments to use the command -g. Exiting Program.")
sys.exit()
# verify the port number is not too small
if int(sys.argv[2]) < int(minPort):
print ("You entered a reserved port number. Enter a port number between 1024 and 65535. Exiting Program.")
sys.exit()
# verify the port number is not too big
if int(sys.argv[2]) > int(maxPort):
print ("You entered a port number that is too big. Enter a port number between 1024 and 65535. Exiting Program.")
sys.exit()
# verify the port number is 1024-65535
if sys.argv[3] == "-l" and (int(sys.argv[4]) < int(minPort) or int(sys.argv[4]) > int(maxPort)):
print ("You entered an invalid port number for the 5th argument for command -l. Enter a port number between 1024 and 65535. Exiting Program.")
sys.exit()
# verify the port number is 1024-65535
if sys.argv[3] == "-g" and (int(sys.argv[5]) < int(minPort) or int(sys.argv[5]) > int(maxPort)):
print ("You entered an invalid port number for the 6th argument for command -g. Enter a port number between 1024 and 65535. Exiting Program.")
sys.exit()
# clientSetup connects the client to the server by creating a new socket
# preconditions: user has entered a valid 2nd (flipx) and 3rd argument (port number)
# postconditions: returns socket with the server name and port number
# with help from 2.7 from Computer Networking - A Top-down Approach by James F. Kurose, Keith W. Ross, page 194
def clientSetup():
url = ".engr.oregonstate.edu"
serverHost = sys.argv[1] + url # the second argument is the flipX portion, add it to the rest of the url to get the name of the server host
serverPort = int(sys.argv[2]) # cast the port number (3rd argument) to an integer https://stackoverflow.com/questions/17383470/argv-string-into-integer
clientSocket = socket(AF_INET,SOCK_STREAM)
clientSocket.connect((serverHost, serverPort))
return clientSocket
# actionList sends the list command to the server and receives list of files in directory from server
# preconditions: clientSocket with valid flipX servername and port number must be provided, as well as a file name
# postconditions: returns a list of files in the directory to the console
# with help from 2.7 from Computer Networking - A Top-down Approach by James F. Kurose, Keith W. Ross, page 196
def actionList(clientSocket):
messageSize = 1024
transferPort1 = sys.argv[4]
# send the port number to the server (this is the 5th argument)
clientSocket.send(transferPort1)
# receive message that it is OK from server
clientSocket.recv(messageSize)
# Get the local host name
# with help from https://pythontic.com/modules/socket/gethostname
clientHostName = gethostname()
# send our host name to the server and receive OK from server
if clientHostName == "flip1.engr.oregonstate.edu":
clientSocket.send("flip1")
clientSocket.recv(messageSize)
elif clientHostName == "flip2.engr.oregonstate.edu":
clientSocket.send("flip2")
clientSocket.recv(messageSize)
else:
clientSocket.send("flip3")
clientSocket.recv(messageSize)
# send the command to the server letting server know we want list of files in directory
clientSocket.send("list")
# receive message that it is OK from server
clientSocket.recv(messageSize)
# obtain our IP address
# https://pythontic.com/modules/socket/gethostname
clientIPAddress = gethostbyname(clientHostName)
# send our IP address
clientSocket.send(clientIPAddress)
# receive the message from the server and check if there is an error. If error, exit program
if clientSocket.recv(messageSize) == "1":
print("You sent an invalid command to the server")
sys.exit()
# create socket
# with help from 2.7 from Computer Networking - A Top-down Approach by James F. Kurose, Keith W. Ross, page 196
serverport = int(transferPort1) # use the 5th argument
serversocket = socket(AF_INET, SOCK_STREAM)
serversocket.bind(('', serverport))
serversocket.listen(1)
connSocket, address = serversocket.accept()
print ("Receiving directory list from " + sys.argv[1] + ":" + transferPort1)
# receive the first file name in the directory
fileRecvd = connSocket.recv(100)
# print the name of the file received, then keep receiving file names and printing until server tells us it is at the end of the directory
while True:
print fileRecvd
fileRecvd = connSocket.recv(100)
if (fileRecvd == "noMore"):
break
# close the connection
connSocket.close()
# actionGet sends the get command to the server to get and receives a file from the server if it exists
# preconditions: clientSocket with valid flipX servername and port number must be provided, as well as a file name
# postconditions: creates a file in the client's current directory if file in server with provided filename exists, otherwise error message prints to console
# if there is no matching file name in the server's directory.
# with help from 2.7 from Computer Networking - A Top-down Approach by James F. Kurose, Keith W. Ross, page 196
# with help from https://github.com/TylerC10/CS372/blob/master/Project%202/ftserver.c
# with help from https://stackoverflow.com/questions/49981603/how-to-check-if-any-file-exists-in-a-certain-folder-with-python
def actionGet(clientSocket):
messageSize = 1024
fileWanted = sys.argv[4]
ourFileName = sys.argv[4]
transferPort2 = sys.argv[5]
# send the port number to the server (this is the 6th argument)
clientSocket.send(transferPort2)
# receive message that it is OK from server
clientSocket.recv(messageSize)
# checking if file already exists help from https://stackoverflow.com/questions/49981603/how-to-check-if-any-file-exists-in-a-certain-folder-with-python
someFile = os.path.exists(fileWanted)
# if file with the same name already exists, change name of the file name we will create so it doesn't overwrite previous file of same name
# use while loop to check that our new file name that we generated isn't alread
while (someFile):
if someFile:
print("There already exists a file with the name " + ourFileName)
ourFileName = "new" + ourFileName
someFile = os.path.exists(ourFileName)
# Get the local host name
# with help from https://pythontic.com/modules/socket/gethostname
clientHostName = gethostname()
# send our host name to the server and receive OK from server
if clientHostName == "flip1.engr.oregonstate.edu":
clientSocket.send("flip1")
clientSocket.recv(messageSize)
elif clientHostName == "flip2.engr.oregonstate.edu":
clientSocket.send("flip2")
clientSocket.recv(messageSize)
else:
clientSocket.send("flip3")
clientSocket.recv(messageSize)
# send the command to the server letting server know we want to get a file
clientSocket.send("get")
# receive message that it is OK from server
clientSocket.recv(messageSize)
# obtain our IP address
clientIPAddress = gethostbyname(clientHostName)
# send our IP address
clientSocket.send(clientIPAddress)
# receive the message from the server and check if there is an error. If error, exit program
# idea to receive a variable indicating error borrowed from https://github.com/TylerC10/CS372/blob/master/Project%202/ftserver.c
if clientSocket.recv(messageSize) == "1":
print("You sent an invalid command to the server")
sys.exit()
# send the name of the file to the server
clientSocket.send(fileWanted)
# get the response from the server on whether the file with that name was there or not
response = clientSocket.recv(messageSize)
# if file doesn't exist, inform user and exit program
# idea to receive text indicating whether file is present borrowed from https://github.com/TylerC10/CS372/blob/master/Project%202/ftserver.c
if response == "fileNotThere":
print(sys.argv[1] + ":" + transferPort2 + " says the file " + fileWanted + " was not found. Exiting Program.")
sys.exit()
# else if file is there, create the socket and connection for sending the file
elif response == "fileThere":
print("Receiving " + fileWanted + " from " + sys.argv[1] + ":" + transferPort2)
# create socket
# with help from 2.7 from Computer Networking - A Top-down Approach by James F. Kurose, Keith W. Ross, page 196
serverport = int(sys.argv[5]) # use the 6th argument
serversocket = socket(AF_INET, SOCK_STREAM)
serversocket.bind(('', serverport))
serversocket.listen(1)
connSocket, address = serversocket.accept()
# open new file for writing
# with help from https://www.pythonforbeginners.com/files/reading-and-writing-files-in-python
fileObj = open(ourFileName, "w")
# receive text from server
fileText = connSocket.recv(1000)
# while we have not encountered the phrase designated by the server indicating no more text lines, keep writing text to file
while True:
fileObj.write(fileText)
fileText = connSocket.recv(1000)
if fileText == "no!More!Text": # idea to receive text indicating no more text borrowed from https://github.com/TylerC10/CS372/blob/master/Project%202/ftserver.c
break
print("File transfer has been completed")
# close the connection
connSocket.close()
# else if the response was not the file was found or not, then exit the program as there was an error
else:
print("Error in response from server. Exiting Program.")
sys.exit()
if __name__ == "__main__":
# validate user's arguments
validateArgs()
# set up a connection to the server through a socket
clientSocket = clientSetup()
# if user sends -l command, user is requesting a list of files in the directory
if sys.argv[3] == "-l":
actionList(clientSocket)
# if user sends -g command, user is requesting to get a file
if sys.argv[3] == "-g":
actionGet(clientSocket)
|
cdc450b1db7c8b7a8e7e35f5e676ea0e4b0be3a4 | gonzalejandro/CC3501 | /Tarea2/characters.py | 3,156 | 3.859375 | 4 |
class Characters:
def __init__(self):
"""
Initializes different class parameters, to be added using the methods
above. Is important to add the different characters in the correct
order, because there are some characters whose initialization depends
on other characters.
"""
self.physics = None
self.bombermen = []
self.grid = None
self.enemies = []
self.bombs = []
self.fires = []
self.powerups = []
self.dblocks = []
self.exit = None
def add_bomberman(self, bomberman):
"""
Adds a bomberman of the list of bombermen.
:param bomberman: Bomberman character of Bomberman type.
:return:
"""
self.bombermen.append(bomberman)
def set_grid(self, grid):
"""
Sets the grid of the game where the Bomberman and the other
game characters will interact.
:param grid: Grid from the class Grid containing a distribution
of blocks, used to represent the path that can be
used by the characters.
:return:
"""
self.grid = grid
def set_physics(self, physics):
"""
Sets the physics grid of the game.
:param physics:
:return:
"""
self.physics = physics
def add_enemy(self, enemy):
"""
Adds an enemy to the list of enemies.
:param enemy: Enemy from the class TO DO
:return:
"""
self.enemies.append(enemy)
def add_bomb(self, bomb):
"""
Adds a bomb to the list of bombs created by the Bomberman.
:param bomb: Bomb from the class Bomb.
:return:
"""
self.bombs.append(bomb)
def add_fires(self, fire):
"""
Adds a fire created by a bomb in the list of bombs.
:param fire: Fire from the class Fire.
:return:
"""
self.fires.append(fire)
def add_powerup(self, powerup):
"""
Adds a powerup behind a destructive block.
:param powerup: Powerup from the class Powerup.
:return:
"""
self.powerups.append(powerup)
def add_dblock(self, dblock):
"""
Adds a destructive block to the dblocks, the list of destructive
blocks
:param dblock: Destructive Block from the DestructiveBlock class.
:return:
"""
self.dblocks.append(dblock)
def add_exit(self, exit):
"""
Adds an exit object to the set of characters.
:param exit:
:return:
"""
self.exit = exit
def update(self):
"""
Update the different elements of the model. Is used by the view.
:return:
"""
s = self
for bomberman in s.bombermen:
bomberman.update()
for enemy in s.enemies:
enemy.update()
for dblock in s.dblocks:
dblock.update()
for fire in s.fires:
fire.update()
for bomb in s.bombs:
bomb.update()
self.exit.update() |
1e585bbde1018c005147476b64a0465ad44592ff | TomasCespedes/Artificial_Intelligence | /LightsOutPuzzle/agents/human.py | 913 | 3.5625 | 4 | from LightsOutPuzzle.utils.framework import Player
# Class for the human player
class HumanPlayer(Player):
# Don't need any properties for the Human player
def __init__(self):
pass
# Define the move the player makes
def move(self, game):
"""
This is the human agent. No algorithm is being ran, it
presents the users with all possible moves.
:param game: a puzzle game in which is being played.
:return: the players choice for a move.
"""
# Get all the possible moves
moves = game.moves()
# Print all the possible moves
print("Possible moves:", moves)
# Initialize the move
move = None
# Run until we are given a legal move
while move not in moves:
# Save the move
move = eval(input("Your choice: "))
# Return the move
return move
|
bdb615689dc6cdd39a035fa04b8c54a8dfe6fef9 | Barbuseries/Gestionnaire-de-mots-de-passe | /generation/GenerateurMdp.py | 12,302 | 3.984375 | 4 | # coding: utf-8
import argparse
from random import SystemRandom
import math
import sys
import getpass
# We set a new random system
cryptogen = SystemRandom()
"""
Usage :
newDico() will create a dictionnary of dictionnarys of lists of strings (pretty simple isn't it ? But it is necessary and efficient). Where words are sorted by their first two characters.
Exemple with two words 'AABCDE','AARTYH' :
{'A':{'A':['AABCDE','AARTYH'],'B':...},'B':...,'C':...}
There is only upper cases and 6168039 different words and common password from 10 different countries.
This function is pretty slow but have to be used one time at every use of the program.
Parameters :
No parameter
Return :
A dictionnary of dictionnaries of lists of strings
"""
def newDico():
fichier = open("dico3.txt", "r")
mainDico = {}
for i in range(32,888):
if not ((i >= 127 and i <= 160) or i == 173 or (i >= 97 and i <= 122)):
mainDico[i] = {}
for j in range(32,888):
if not ((j >= 127 and j <= 160) or j == 173 or (i >= 97 and i <= 122)):
mainDico[i][j] = []
ligne = fichier.readline()
while (ligne != ""):
mainDico[ord(ligne[0])][ord(ligne[1])].append(ligne[:-1])
ligne = fichier.readline()
fichier.close()
return(mainDico)
"""
Usage :
testDico(word, dico) will return a mark from 0 to 5.
If the word is in the dictionnary "dico" then the mark will be 0.
The less the word looks like a string of the dictionnary the better the mark will be.
Parameters :
word = string (this is the word tested in the dictionnary)
dico = a dictionnary of dictionnaries of lists of strings (The dictionnary in which the word will be tested)
Return :
Float (between 0 and 5)
"""
def testDico(word, dico):
upperWord = ""
for i in range(len(word)):
if (ord(word[i]) >= 97 and ord(word[i]) <= 122):
upperWord = upperWord + word[i].upper()
else:
upperWord = upperWord + word[i]
maxSimil = 0
for i in range(len(word)-1):
for j in range(len(word),i+1,-1):
if (callDico(upperWord, dico, i, j)):
if (j-i > maxSimil):
maxSimil = j-i
wordLen = len(word)
del(word)
del(upperWord)
return((wordLen-maxSimil)*5/wordLen)
"""
Usage :
callDico(word, dico, i, j) will return True if the part of word between the character i and the character j is in the list of the dictionnary corresponding to the first two characters of the part of the word tested.
Parameters :
word = string (this is the word tested in the dictionnary)
dico = dictionnary of dictionnaries of lists of strings (The dictionnary in which the word will be tested)
i = integer (corresponding to the first character of the part of word tested)
j = integer (corresponding to the last character of the part of word tested)
Return :
Boolean
"""
def callDico(word, dico, i, j):
if word[i:j] in dico[ord(word[i])][ord(word[i+1])]:
del(word)
return True
del(word)
return False
"""
Usage :
passwordEntropy(key,characterRange) will return a mark from 0 to 5.
This mark will be baad if the characters of key are too close to each other.
Exemple :
-'123' will have a bad mark
-'925' will have a good mark
The mark depends of the range of character used
Exemple :
-'925' will have a good mark because the characters looks differents using only numbers
-'AAzz99' will have a bad mark because even if the password is in fact probably safer than '925' the characters are too close to each other. Regardless of the length of the password.
An other usage is to get the range of character used by the string key by setting characterRange to True.
Parameters :
key = string (this is the word tested)
characterRange = boolean (False by default)
Return :
Float (from 0 to 5)
Or Integer (If characterRange is set to True)
"""
def passwordEntropy(key,characterRange = False):
characters = [i for i in range(32,888) if not ((i >= 127 and i <= 160) or i == 173)]
typeOfChar = [False for i in range(6)]
for i in key:
if (i >= chr(65) and i <= chr(90)):
typeOfChar[0] = True
elif (i >= chr(97) and i <= chr(122)):
typeOfChar[1] = True
elif (i >= chr(48) and i <= chr(57)):
typeOfChar[2] = True
elif (i >= chr(192) and i <= chr(255)):
typeOfChar[3] = True
elif (i >= chr(256)):
typeOfChar[4] = True
else:
typeOfChar[5] = True
if typeOfChar[0] == False:
characters = [i for i in characters if (i < 65 or i > 90)]
if typeOfChar[1] == False:
characters = [i for i in characters if (i < 97 or i > 122)]
if typeOfChar[2] == False:
characters = [i for i in characters if (i < 48 or i > 57)]
if typeOfChar[3] == False:
characters = [i for i in characters if (i < 192 or i > 255)]
if typeOfChar[4] == False:
characters = [i for i in characters if (i < 256)]
if typeOfChar[5] == False:
characters = [i for i in characters if ((i >= 65 and i <= 90) or (i >= 97 and i <= 122) or (i >= 48 and i <= 57) or (i > 191))]
if (characterRange == True):
del(key)
return(len(characters))
if (key == ""):
del(key)
return(0)
keyLen = len(key)
previous = [0 for i in range(keyLen)]
previous[0] = key[0]
entropy = 0
for j in range(1,keyLen):
char = key[j]
entropyChar = 0.0
for i in range(j):
entropyChar += abs(characters.index(ord(char))-characters.index(ord(previous[i]))) / len(characters)
for i in range(keyLen - 1,0,-1):
previous[i] = previous[i - 1]
previous[0] = char
entropy += entropyChar / (j)
entropy = entropy / keyLen
noteEntropy = entropy*5/0.31
if (noteEntropy > 5):
noteEntropy = 10 - noteEntropy
del(key)
del(previous)
return(noteEntropy)
"""
Usage :
newPass(length, upperCase, lowerCase, number, accentMark, special, duplicate): will create a new password
Parameters :
length = integer (gives the length of the password)
upperCase = boolean (if set will allow upper cases in the password)
lowerCase = boolean (if set will allow lower cases in the password)
number = boolean (if set will allow numbers in the password)
accentMark = boolean (if set will allow characters with accent marks in the password)
special = boolean (if set will allow special characters in the password)
duplicate = boolean (if set will forbid duplicates in the password)
Return :
String (the password created)
"""
def newPass(length, upperCase, lowerCase, number, accentMark, special, duplicate):
characters = [i for i in range(32,888) if not ((i >= 127 and i <= 160) or i == 173)]
if (upperCase == None):
characters = [i for i in characters if (i < 65 or i > 90)]
if (lowerCase == None):
characters = [i for i in characters if (i < 97 or i > 122)]
if (number == None):
characters = [i for i in characters if (i < 48 or i > 57)]
if (accentMark == None):
characters = [i for i in characters if (i < 192)]
if (special == None):
characters = [i for i in characters if ((i >= 65 and i <= 90) or (i >= 97 and i <= 122) or (i >= 48 and i <= 57) or (i > 191))]
if (duplicate == True and length > len(characters)):
print("Not enought characters to avoid duplicate")
exit()
password = ""
for i in range(length):
alea = cryptogen.randrange(len(characters))
password += chr(characters[alea])
if (duplicate == True):
del characters[alea]
return password
# Here we set the parser and all the arguments
parser = argparse.ArgumentParser(description='A password generator')
parser.add_argument("length", metavar = "LENGTH", type = int, nargs = '?', default = 12)
parser.add_argument("-u", "--upperCase", dest = "upperCase", action = "store_const", const = True, help = "If given, capitals letters will be added to the password")
parser.add_argument("-l", "--lowerCase", dest = "lowerCase", action = "store_const", const = True, help = "If given, lowercases will be added to the password")
parser.add_argument("-n", "--number", dest = "number", action = "store_const", const = True, help = "If given, numbers will be added to the password")
parser.add_argument("-s", "--special", dest = "special", action = "store_const", const = True, help = "If given, special characters will be added to the password")
parser.add_argument("-d", "--duplicate", dest = "duplicate", action = "store_const", const = True, help = "If given, the password will not contain any duplicate")
parser.add_argument("-a", "--accentMark", dest = "accentMark", action = "store_const", const = True, help = "If given, the password will contain accent marks")
parser.add_argument("-t", "--testPassword", dest = "testPassword", type = str, nargs = "?", const = "", help = "The given password security will be tested then the program will end")
args = parser.parse_args()
# By default we allow every characters in the password
if (args.upperCase == None and args.lowerCase == None and args.number == None and args.special == None and args.accentMark == None):
args.upperCase, args.lowerCase, args.number, args.special, args.accentMark = True, True, True, True, True
# If no password is given when the user ask to test his password, then we ask for the password which will be hiden
if (args.testPassword == ""):
args.testPassword = getpass.getpass()
# We create a new dico in any case
dico = newDico()
# If we are testing a password:
if (args.testPassword != None):
# We calculate the marks and print the results
noteDico = round(testDico(args.testPassword,dico),2)
noteEntropy = round(passwordEntropy(args.testPassword),2)
print("Your password marks are "+str(noteEntropy)+"/5.0 for the entropy, "+str(noteDico)+"/5.0 for the dictionnary attack which gives "+str(round(noteEntropy/2 + noteDico/2,2))+"/5.0 as a total. Keep in mind that those marks don't depend of the length of your password neither of the range of characters you choosed.")
if (len(args.testPassword)<8):
print("We must warn you that choosing a password with less than 8 characters is not recommended.")
range = passwordEntropy(args.testPassword,True)
if (range<62):
print("We must warn you that choosing a password with a range of characters of less than 62 is not recommended. You are currently using a range of "+str(range)+" characters.")
del(args.testPassword)
# Then the program end here
exit()
# If we are creating a new password
newPassword = newPass(args.length, args.upperCase, args.lowerCase, args.number, args.accentMark, args.special, args.duplicate)
noteMax = 0
# We create 1000 different passwords and we keep the best one
for i in range(1000):
noteEntropy = passwordEntropy(newPassword)
noteDico = testDico(newPassword,dico)
note = noteEntropy/2 + noteDico/2
if (note > noteMax):
noteMax = note
bestPassword = newPassword
newPassword = newPass(args.length, args.upperCase, args.lowerCase, args.number, args.accentMark, args.special, args.duplicate)
noteMax = round(noteMax,8)
# We try to print the results (some shells can't print every characters)
try:
print("Here is the best password we found with the given conditions : \""+str(bestPassword)+"\". His mark is "+str(noteMax)+"/5.0")
except UnicodeEncodeError:
# If the shell can't print the password then we replace every problematic characters by '?' and we print the results
word = ""
for i in range(len(bestPassword)):
if (ord(bestPassword[i]) > 255):
word += '?'
else:
word += bestPassword[i]
print("Here is the best password we found with the given conditions : \""+str(word)+"\". His mark is "+str(noteMax)+"/5.0")
del(word)
del(bestPassword)
print("Keep in mind that those marks don't depend of the length of your password neither of the range of characters you choosed.") |
477d7a89e499fe95cdb7c4c44894d5ce64b9e55b | htl1126/leetcode | /23.py | 1,143 | 4 | 4 | # ref: https://leetcode.com/discuss/55662/108ms-python-solution-with
# -heapq-and-avoid-changing-heap-size
import heapq
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
# NOTE: this code must be run with Python not Python3
class Solution(object):
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
dummy = node = ListNode(None)
h = [(n.val, n) for n in lists if n]
heapq.heapify(h)
while h:
val, n = heapq.heappop(h)
if n.next:
heapq.heappush(h, (n.next.val, n.next))
node.next = n
node = node.next
return dummy.next
if __name__ == '__main__':
sol = Solution()
head_1 = ListNode(1)
head_1.next = ListNode(3)
head_1.next.next = ListNode(5)
head_2 = ListNode(2)
head_2.next = ListNode(4)
head_3 = ListNode(6)
head_3.next = ListNode(7)
result = sol.mergeKLists([])
while result:
print result.val
result = result.next
|
ce2d9a1d82a7af4e6bb25e905d1b008f4a186f36 | igorsobreira/playground | /problems/project_euler/13.py | 231 | 3.515625 | 4 | '''
Work out the first ten digits of the sum of the following one-hundred 50-digit
numbers. (numbers are in 13.in)
'''
with file('13.in') as file_obj:
s = sum( [ int(n) for n in file_obj.readlines() ] )
print str(s)[:10]
|
3ec20c584f97b13cbdae333c154651d1efa56e4c | eli-taylor/Challenge04 | /EliTaylor/CodeChallenge4.py | 4,022 | 4.21875 | 4 | ## Eli's Code Challenge 4 Submission
#- Run script using python 3.*
#- Enter a math expression that uses valid operators +, -, /, *, (, and )
import re
class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.insert(0,item)
def pop(self):
return self.items.pop(0)
def peek(self):
return self.items[0]
def size(self):
return len(self.items)
def is_number(s):
try:
float(s)
return True
except ValueError:
pass
return False
def ComparePrecedence(o1, o2):
if o1 == '+' and o2 == '*': # + has lower precedence than *
return False
if o1 == '*' and o2 == '-': # * has higher precedence over -
return True
if o1 == '+' and o2 == '/': # + has lower precedence than *
return False
if o1 == '/' and o2 == '-': # * has higher precedence over -
return True
if o1 == '+' and o2 == '-': # + has same precedence over -
return True
return True
def AddMultiplicationSymbol(expArr):
indexArr = list()
try:
index = expArr.index('(')
except:
index = -1
while index >= 0:
if index > 0:
if expArr[index - 1] == ')' or is_number(expArr[index - 1]):
expArr.insert(index, '*')
index += 1
try:
index = expArr.index('(', index + 1)
except:
index = -1
return expArr
def ApplyOperator(op1, op2, optr):
if optr == '+':
return float(op2) + float(op1);
if optr == '-':
return float(op2) - float(op1);
if optr == '*':
return float(op2) * float(op1);
if optr == '/':
return float(op2) / float(op1);
return -1;
def GetExpressionArray(mystr):
#remove if any spaces from the expression
mystr = mystr.replace("\\s+", "")
stack = Stack()
#we assume that the expression is in valid format
pattern = re.compile(u'(\\b\\w*[\\.]?\\w+\\b|[\\(\\)\\+\\*\\-\\/])')
expArr = re.findall(pattern, mystr)
expArr = AddMultiplicationSymbol(expArr)
return expArr
def ConvertToPostfix(infix):
length = len(infix)
stack = Stack()
postfix = list()
for val in infix:
if is_number(val):
postfix.append(val)# = postfix + (str(token))
elif val == '(':
stack.push(val)
elif val == '*' or val == '+' or val == '-' or val == '/':
while stack.size() > 0 and stack.peek() != '(':
if ComparePrecedence(stack.peek(), val):
postfix.append(stack.pop())
else:
break
stack.push(val)
elif val == ')':
while stack.size() > 0 and stack.peek() != '(':
postfix.append(stack.pop())
if stack.size() > 0:
stack.pop()
while stack.size() > 0:
postfix.append(stack.pop())
return postfix
def EvaluatePostfix(postfix):
resultStack = Stack()
length = len(postfix)
if length == 0:
return 'ERROR: Invalid format'
try:
for val in postfix:
if val == '*' or val == '+' or val == '-' or val == '/':
result = ApplyOperator(resultStack.pop(), resultStack.pop(), val)
resultStack.push(result)
elif is_number(val):
resultStack.push(val)
except:
return 'ERROR: Invalid format'
return resultStack.pop()
userInput = ''
while userInput == '':
userInput = input('Enter an expression to evaluate: ')
while userInput != 'q' and userInput != 'x':
infixArray = GetExpressionArray(userInput)
postfixArray = ConvertToPostfix(infixArray)
answer = EvaluatePostfix(postfixArray)
print(answer)
userInput = ''
while userInput == '':
userInput = input("Enter an expression to evaluate ('q' or 'x' to exit): ")
|
783b71484208447c0d914d9dbf616374ef4b140c | CScorpio/lxc_Project | /webdriver/unittest/assertFunction.py | 608 | 3.796875 | 4 | import unittest
class Test(unittest.TestCase):
def setUp(self):
number=input("Enter a number:")
self.number = int(number)
def testCase(self):
self.assertEqual(self.number, 10, "输入的数字不是10")
'''
try :
self.assertEqual(self.number,10,"输入的数字不是10")
except BaseException as msg:
print("++++++++++++++++++")
print(msg)
print("bababababbababababababababababab~wuwuwuwuwuwuwwu~yei")
'''
def tearDown(self):
pass
if __name__ == '__main__':
unittest.main() |
d7f94a3c06e7f728e7b9561de25a856cf4f6ef41 | MohamedMuzzamil05/Pysim- | /getcmnt.py | 2,969 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""Parse Python source code from file and get/print source code comments."""
__all__ = ('get_comments', 'get_comment_blocks')
import tokenize
from io import StringIO
def get_comments(source):
"""Parse Python source and yield comment tokens in the order of
appearance.
Each token is a tuple with the comment string, start and end.
start and end each are tuples with the line number and column of
the start and end of the comment.
`source` may be a file-like object with a `readline` method or
a string.
"""
if not hasattr(source, 'readline'):
source = StringIO(source)
tokenizer = tokenize.generate_tokens(source.readline)
for token in tokenizer:
if token[0] == tokenize.COMMENT:
yield token[1:4]
def get_comment_blocks(source):
"""Parse Python source code and yield a tuple of comment string,
start and end for each comment.
*source* may be a file-like object with a ``readline`` method or
a string.
Comments on consecutive lines, which start on the same column,
are returned as a single string with embedded newlines.
"""
comments = []
for comment, start, end in get_comments(source):
if (not comments or comments[-1][1][0] == start[0] - 1
and comments[-1][1][1] == start[1]):
comments.append((comment, start, end))
else:
yield "\n".join(c[0] for c in comments), comments[0][1], comments[-1][2]
comments = [(comment, start, end)]
if comments:
yield "\n".join(c[0] for c in comments), comments[0][1], comments[-1][2]
def cmt_input(f1,f2):
with open(f1) as fp:
cmnts1 = []
for comment, start, end in get_comment_blocks(fp):
cmnts1.append(comment)
with open(f2) as fp:
cmnts2 = []
for comment, start, end in get_comment_blocks(fp):
cmnts2.append(comment)
flag = 0
print()
print("----- Comment Analysis of " + f1 + " & " + f2 + " -----")
print()
print("Comments Identified in "+f1)
# print(cmnts1)
count = 1
flg = 0
for i in cmnts1:
print(str(count) + ". " + str(i))
count += 1
flg = 1
if (flg == 0): print("None found")
count = 1
print()
print("Comments Identified in " + f2)
# print(cmnts2)
count = 1
flg = 0
for i in cmnts2:
print(str(count) + ". " + str(i))
count += 1
flg = 1
if (flg == 0): print("None found")
count = 1
flag=0
print()
print("Comments Identified as Common : ")
for i in cmnts1:
for j in cmnts2:
if(i==j):
flag = 1
print(str(count) + ". ", end='')
print(i)
count += 1
print()
count =1
if(flag==0): print("None found")
|
2f4247305582297ad2ef852757ffa9536aa46ee4 | karthik-balaguru/MyPy | /prob6.py | 485 | 4 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Apr 1 02:31:12 2017
@author: bala635
"""
def sumofsquares(num):
n = 1
sum1 = 0
while (n<=num):
sum1 = sum1 + n**2
n = n+1
return(sum1)
def squareofsum(num):
n = 1
sum2 = 0
while (n<=num):
sum2 = sum2 + n
n = n+1
sum2 = sum2**2
return(sum2)
num = input("enter a number: ")
num = int(num)
diffsum = squareofsum(num) - sumofsquares(num)
print(diffsum)
|
858e4ad3cef25ba09a26e277a28d54dbe55071ff | hudefeng719/uband-python-s1 | /homeworks/A10518/checkin02/A10518-day6-homework.py | 1,465 | 4.125 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# @author: Fanyujie
# 今日的作业
# 有十种菜
# 白菜、萝卜、西红柿、甲鱼、龙虾、生姜、白芍、西柚、牛肉、水饺
#
# 1. 老妈来到了菜市场,从下标 0 开始买菜,遇到偶数的下标就买
# 遇到奇数的下标就不买,买的数量为下标 + 1 斤
# (请写程序模拟整个过程)
# (注意单一职责原则)
# (注意灵活使用 def 函数(代码块))
#
# 【提示】:
# 输出结果可能为
# ‘老妈来到菜市场
# 老妈看到白菜,买了 1 斤
# 老妈继续逛
# 老妈看到xxx, 不买
# 老妈继续逛
# ...
# '
# 2. 完成后,用今天的学到的列表知识,加 3 个菜
# 3. 完成后,用今天的学到的列表知识,让老妈只逛第 5~9 个菜
def print_list(lst):
for lst_item in lst:
print "Mom saw %s" % (list_item)
def homework():
lst = ["cabbages", "potatos", "tomatos", "cucumbers", "peppers", "broccoli", "carrots", "asparagus", "onions", "mushrooms"]
lst.append("celery")
lst.append("spinach")
lst.append("beans")
lst2 = lst[5:10]
buy_amount = 1
who = "Mom"
for index, item in enumerate(lst2):
print "%s saw %s on the market." % (who, item)
if index % 2 == 0:
even_num = True
buy_amount = index + 1
print "She bought %d/kg." % (buy_amount)
else:
print "She left."
#return who, lst
if __name__ == '__main__':
homework() |
c548dfdd9fea1329909de926c700e96184c490b7 | kuraisle/ABCG_Family_Analysis | /logo_functions.py | 4,430 | 3.578125 | 4 | # The functions for generating protein sequence logos summarising the sequence alignment
# protein_logo draws the sequence logo
# conserved_colours generates colours for the sequence logo
def protein_logo(positions):
"""Draws a sequence logo of the positions requested showing differences between ABCG family members
Arguments:
positions -- a list of positions within the sequence alignment
"""
ABCG1 = []
ABCG2 = []
ABCG4 = []
ABCG5 = []
ABCG8 = []
for seq in ABCG1_sequences:
tmp = ''
for i in positions:
tmp = tmp + seq[1][i]
ABCG1.append(tmp)
for seq in ABCG2_sequences:
tmp = ''
for i in positions:
tmp = tmp + seq[1][i]
ABCG2.append(tmp)
for seq in ABCG4_sequences:
tmp = ''
for i in positions:
tmp = tmp + seq[1][i]
ABCG4.append(tmp)
for seq in ABCG5_sequences:
tmp = ''
for i in positions:
tmp = tmp + seq[1][i]
ABCG5.append(tmp)
for seq in ABCG8_sequences:
tmp = ''
for i in positions:
tmp = tmp + seq[1][i]
ABCG8.append(tmp)
fig = plt.figure(figsize=[0.5*len(ABCG1[0]), 9])
ax = plt.subplot2grid((5, 1), (0,0))
ABCG1_logo = lm.Logo(lm.alignment_to_matrix(ABCG1), ax = ax, color_scheme='black')
ax.set_xticks(range(len(positions)))
ax.set_xticklabels(positions)
ax.xaxis.tick_top()
ax1 = plt.subplot2grid((5, 1), (1,0))
ABCG2_logo = lm.Logo(lm.alignment_to_matrix(ABCG2), ax = ax1, color_scheme='black')
ax1.set_xticks([])
ax2 = plt.subplot2grid((5, 1), (2,0))
ABCG4_logo = lm.Logo(lm.alignment_to_matrix(ABCG4), ax = ax2, color_scheme='black')
ax2.set_xticks([])
ax3 = plt.subplot2grid((5, 1), (3,0))
ABCG5_logo = lm.Logo(lm.alignment_to_matrix(ABCG5), ax = ax3, color_scheme='black')
ax3.set_xticks([])
ax4 = plt.subplot2grid((5, 1), (4,0))
ABCG8_logo = lm.Logo(lm.alignment_to_matrix(ABCG8), ax = ax4, color_scheme='black')
ax4.set_xticks(range(len(positions)))
plt.xticks(rotation = 70, ha = 'right')
this_conservation_pattern = []
for i in positions:
this_conservation_pattern.append(conservation_pattern[i])
ax4.set_xticklabels(this_conservation_pattern)
ax.set_yticks([])
ax1.set_yticks([])
ax2.set_yticks([])
ax3.set_yticks([])
ax4.set_yticks([])
ax.set_ylabel('ABCG1', rotation = 0, ha = 'right', fontsize = 20)
ax1.set_ylabel('ABCG2', rotation = 0, ha = 'right', fontsize = 20)
ax2.set_ylabel('ABCG4', rotation = 0, ha = 'right', fontsize = 20)
ax3.set_ylabel('ABCG5', rotation = 0, ha = 'right', fontsize = 20)
ax4.set_ylabel('ABCG8', rotation = 0, ha = 'right', fontsize = 20)
conservation_colours = conserved_colours(positions)
for pos in range(len(conservation_colours[0])):
ABCG1_logo.highlight_position(p = pos, color = conservation_colours[0][pos])
for pos in range(len(conservation_colours[0])):
ABCG2_logo.highlight_position(p = pos, color = conservation_colours[1][pos])
for pos in range(len(conservation_colours[0])):
ABCG4_logo.highlight_position(p = pos, color = conservation_colours[2][pos])
for pos in range(len(conservation_colours[0])):
ABCG5_logo.highlight_position(p = pos, color = conservation_colours[3][pos])
for pos in range(len(conservation_colours[0])):
ABCG8_logo.highlight_position(p = pos, color = conservation_colours[4][pos])
fig.tight_layout()
def conserved_colours(positions):
"""Generate colour palletes for positions in sequence logos according to their conservation
Arguments:
positions -- a list of positions within the sequence alignment
"""
patterns = []
for i in positions:
patterns.append(alignment_protein_conservation[i][1])
colour_scheme = []
for protein in ['ABCG1', 'ABCG2', 'ABCG4', 'ABCG5', 'ABCG8']:
prot_colours = []
for pos in patterns:
if pos == 'Gap':
prot_colours.append('grey')
elif pos == 'Totally Conserved':
prot_colours.append('darkslategray')
else:
pat_list = [x[1] for x in pos]
representative = [member for sublist in pat_list for member in sublist]
if protein in representative:
if len(pat_list) == 1:
prot_colours.append('green')
elif len(representative) == 5:
prot_colours.append('aqua')
else:
prot_colours.append('red')
else:
prot_colours.append('white')
colour_scheme.append(prot_colours)
return colour_scheme |
768fc2170ed8cfb8133e902e955438fb09284676 | shorya361/CP-Codes-DSA | /multithreading.py | 718 | 3.875 | 4 | #PF-Tryout
from threading import Thread
def func1():
result_sum=0
for i in range(10000001):#Write the code to find the sum of numbers from 1 to 10000000
result_sum+=i
print("Sum from func1:",result_sum)
def func2():
result_sum=0
for i in range(5):
p=int(input())
result_sum+=p
#Write the code to accept 5 numbers from user and find its sum
print("Sum from func2:",result_sum)
#Modify the code given below to execute func1() and func2() in two separate threads
thread1=Thread(target=func1())
thread1.start()
thread2=Thread(target=func2())
thread2.start() #starts the thread
thread1.join()
print("hello")
thread2.join()
print("damn") |
4b9cd9337efa808041791b6b71397ffa6818a45d | splattater/mypythonstuff | /mypythonstuff/myos.py | 335 | 3.515625 | 4 | def get_abs_files(dir_path):
"""Search all files in a given dir and its subdirs."""
import os
if not os.path.isdir(dir_path):
return []
found = []
for root, subdirs, files in os.walk(dir_path, topdown=True):
for file in files:
found.append(os.path.join(root, file))
return found
|
a6ca48fa6d250c46fc69b9f1864d8e200485fb47 | gunveen-bindra/OOP | /overriding.py | 393 | 4 | 4 | # Method overriding
class employee:
def add(self, salary, incentive):
print('total salary in base class=', salary+incentive)
class department(employee):
temp = 'i m member of dept cls'
def add(self, salary, incentive):
print(self.temp)
print('total salary in derived class=', salary+incentive)
dept = department()
dept.add(45000, 5000)
|
46dc064a1e708ccda5e29c3e8ad7e13d25236de4 | ConorODonovan/online-courses | /Udemy/Python/Data Structures and Algorithms/LinkedList/class_SingleLinkedList.py | 8,876 | 3.96875 | 4 | class SingleLinkedList:
def __init__(self):
self.start = None
def display_list(self):
if self.start is None:
print("List is empty")
return
else:
print("List is: ")
p = self.start
while p is not None:
print(p.info, " ", end="")
p = p.link
print()
def count_nodes(self):
p = self.start
n = 0
while p is not None:
n += 1
p = p.link
print("Number of nodes in the list = {}".format(n))
def search(self, x):
position = 1
p = self.start
while p is not None:
if p.info == x:
print(x, " is at position ", position)
return True
position += 1
p = p.link
else:
print(x, " not found in list")
return False
def insert_in_beginning(self, data):
from class_Node import Node
temp = Node(data)
temp.link = self.start
self.start = temp
def insert_at_end(self, data):
from class_Node import Node
temp = Node(data)
if self.start is None:
self.start = temp
return
p = self.start
while p.link is not None:
p = p.link
p.link = temp
def create_list(self):
n = int(input("Enter the number of nodes: "))
if n == 0:
return
for i in range(n):
data = int(input("Enter the element to be inserted: "))
self.insert_at_end(data)
def insert_after(self, data, x):
from class_Node import Node
p = self.start
while p is not None:
if p.info == x:
break
p = p.link
if p is None:
print(x, "not present in the list")
else:
temp = Node(data)
temp.link = p.link
p.link = temp
def insert_before(self, data, x):
from class_Node import Node
# If list is empty
if self.start is None:
print("List is empty")
return
# x is in first node, new node is to be inserted before first node
if x == self.start.info:
temp = Node(data)
temp.link = self.start
self.start = temp
return
# Find reference to predecessor of node containing x
p = self.start
while p.link is not None:
if p.link.info == x:
break
p = p.link
if p.link is None:
print(x, " not present in the list")
else:
temp = Node(data)
temp.link = p.link
p.link = temp
def insert_at_position(self, data, k):
from class_Node import Node
if k == 1:
temp = Node(data)
temp.link = self.start
self.start = temp
return
p = self.start
i = 1
while i < k - 1 and p is not None: # find a reference to k-1 node
p = p.link
i += 1
if p is None:
print("You can insert only upto position", i)
else:
temp = Node(data)
temp.link = p.link
p.link = temp
def delete_node(self, x):
if self.start is None:
print("List is empty")
return
# Deletion of first node
if self.start.info == x:
self.start = self.start.link
return
# Deletion in between or at the end
p = self.start
while p.link is not None:
if p.link.info == x:
break
p = p.link
if p.link is None:
print("Element ", x, "not in list")
else:
p.link = p.link.link
def delete_first_node(self):
if self.start is None:
return
self.start = self.start.link
def delete_last_node(self):
if self.start is None:
return
if self.start.link is None:
self.start = None
return
p = self.start
while p.link.link is not None:
p = p.link
p.link = None
def reverse_list(self):
prev = None
p = self.start
while p is not None:
next = p.link
p.link = prev
prev = p
p = next
self.start = prev
def bubble_sort_exdata(self):
end = None
while end != self.start.link:
p = self.start
while p.link != end:
q = p.link
if p.info > q.info:
p.info, q.info = q.info, p.info
p = p.link
end = p
def bubble_sort_exlinks(self):
end = None
while end != self.start.link:
r = p = self.start
while p.link != end:
q = p.link
if p.info > q.info:
p.link = q.link
q.link = p
if p != self.start:
r.link = q
else:
self.start = q
p, q = q, p
r = p
p = p.link
end = p
def has_cycle(self):
if self.find_cycle() is None:
return False
else:
return True
def find_cycle(self):
if self.start is None or self.start.link is None:
return None
slowR = self.start
fastR = self.start
while fastR is not None and fastR.link is not None:
slowR = slowR.link
fastR = fastR.link.link
if slowR == fastR:
return slowR
return None
def remove_cycle(self):
c = self.find_cycle()
if c is None:
return
print("Node at which the cycle was detected is ", c.info)
p = c
q = c
len_cycle = 0
while True:
len_cycle += 1
q = q.link
if p == q:
break
print("Length of cycle is: ", len_cycle)
len_rem_list = 0
p = self.start
while p != q:
len_rem_list += 1
p = p.link
q = q.link
print("Number of nodes not included in the cycle are: ", len_rem_list)
length_list = len_cycle + len_rem_list
print("Length of the list is: ", length_list)
p = self.start
for i in range(length_list - 1):
p = p.link
p.link = None
def insert_cycle(self, x):
if self.start is None:
return
p = self.start
px = None
prev = None
while p is not None:
if p.info == x:
px = p
prev = p
p = p.link
if px is not None:
prev.link = px
else:
print(x, " not present in list")
def merge2(self, list2):
merge_list = SingleLinkedList()
merge_list.start = self._merge2(self.start, list2.start)
return merge_list
def _merge2(self, p1, p2):
if p1.info <= p2.info:
startM = p1
p1 = p1.link
else:
startM = p2
p2 = p2.link
pM = startM
while p1 is not None and p2 is not None:
if p1.info <= p2.info:
pM.link = p1
pM = pM.link
p1 = p1.link
else:
pM.link = p2
pM = pM.link
p2 = p2.link
if p1 is None:
pM.link = p2
else:
pM.link = p1
return startM
def merge_sort(self):
self.start = self._merge_sort_rec(self.start)
def _merge_sort_rec(self, list_start):
# if list empty or has one element
if list_start is None or list_start.link is None:
return list_start
# if more than one element
start1 = list_start
start2 = self._divide_list(list_start)
start1 = self._merge_sort_rec(start1)
start2 = self._merge_sort_rec(start2)
startM = self._merge2(start1, start2)
return startM
def _divide_list(self, p):
q = p.link.link
while q is not None and q.link is not None:
p = p.link
q = q.link.link
start2 = p.link
p.link = None
return start2
|
4e460b51d9b3d13ecc061600274d3dc5e508346d | RAFAELSPAULA/Exercicios-introdutorio-Python | /Estrutura condicional/Problema_troco_verificado.py | 841 | 4.21875 | 4 | # Fazer um programa para calcular o troco no processo de pagamento de um produto de uma mercearia.
# O programa deve ler o preço unitário do produto, a quantidade de unidades compradas deste produto,
# e o valor em dinheiro dado pelo cliente. Seu programa deve mostrar o valor do troco a ser devolvido
# ao cliente. Se o dinheiro dado pelo cliente não for suficiente, mostrar uma mensagem informando o
# valor restante.
# Inserindo Valores
PrecoU = float(input('Preço unitário do produto: '))
Quantidade = int(input('Quantidade comprada: '))
DinheiroR = float(input('Dinheiro recebido: '))
# Cálculo dos Valores
ValorF = DinheiroR - PrecoU * Quantidade
# Estabelecendo condições do troco
if ValorF > 0:
print(f'TROCO: {ValorF:.2f}')
else:
print(f'DINHEIRO INSUFICIENTE. FALTAM {ValorF:.2f} Reais') |
da4458be1878bc3fe86bcd014a8c30ed6b3316a7 | junaid238/class_files | /python files/vehicle.py | 1,130 | 4.0625 | 4 | # car speed classifier
class car:
speed = 0
def __init__(self , name , wheels , bhp):
self.name = name
self.wheels = wheels
self.bhp = bhp
print("your " + self.name +" is of "+ self.bhp)
def start(self , start_speed):
# speed = 0
car.speed = car.speed + start_speed
print("your " + self.name +" has started")
def acc(self , acc_speed):
car.speed = car.speed + acc_speed
if car.speed > 120:
car.speed = 120
print("your " + self.name +" has exceeded speed " + str(car.speed))
else:
print("your " + self.name +" has speed of " + str(car.speed))
def brake(self , brake_speed):
car.speed = car.speed - brake_speed
print("your " + self.name +" has reduced to a speed of" + str(car.speed))
def stop(self):
car.speed = 0
print("your " + self.name +" has stopped")
v = car("verna " , 4 , "2 bhp")
v.start(30) # 30
print(v.speed)
v.acc(90) # 120
v.acc(30) # 150 --> 120
v.brake(50) # 70
c = car("city" , 4 , "3 bhp")
v.stop() # 0
print(v.speed) # 0
c.start(40)
v.start(50)
c.acc(40)
v.brake(20)
v.start(40)
# if car.speed == 0 :
# car.start()
# if car.speed !=0 :
# car.stop()
|
b83098ba67e9b906818d5bb625a4bff62f3e811a | Matteo-lu/holbertonschool-higher_level_programming | /0x01-python-if_else_loops_functions/12-fizzbuzz.py | 469 | 3.953125 | 4 | #!/usr/bin/python3
def fizzbuzz():
"""prints the numbers from 1 to 100 separated by a space"""
for i in range(1, 101):
if (i % 15) == 0:
print("FizzBuzz ", end="")
continue
elif (i % 5) == 0:
print("Buzz ", end="")
continue
elif (i % 3) == 0:
print("Fizz ", end="")
continue
print("{}".format(i), end="")
if i != 100:
print(" ", end="")
|
eb3d0cc3a414b0ad8a61b3036475de3723d2e93e | ekhtiar/Python_for_Informatics_Solutions | /Ex_2/Ex_2_2.py | 274 | 3.71875 | 4 | #!/usr/bin/env python
#adjust your shebang line
#Excercise 2.2: Write a program that uses raw_input to prompt a user for their name and then welcomes them.
#take input and store in name variable
name = raw_input("What is your name? \n");
#print name
print("Hello " +name);
|
1d50daa6110cc9553e82232d2fc74e449af86b60 | yangwenwei666/zero | /apps/getMovie/__init__.py | 187 | 3.59375 | 4 | import re
text = "◎片 名 狄仁杰之四大天王/狄仁杰3◎"
a = re.compile(r'[◎](.*?)[◎]',re.S)
result = a.findall(text)
for x in result:
print(x)
print(result)
|
f13cfec666bb5aa96d9361fecd679deac8981b16 | clarkmyfancy/Visual-Sorter | /ListGenerator.py | 354 | 3.71875 | 4 | import random
class Generator:
def __init__(self, maxLength, largestValue):
self.maxLength = maxLength
self.largestValue = largestValue
def generate_random_list(self):
random_list = []
for _ in range(self.maxLength):
random_list.append(random.randint(0, self.largestValue))
return random_list |
0b6fb5d2f72a47c1878e744f311245c88e02ebf0 | paniquex/ML_DS_practice | /PRACTICUM/HW_02/get_max_before_zero.py | 332 | 3.65625 | 4 | import numpy as np
def get_max_before_zero(x):
zero_positions = np.where(x == 0)[0]
if (len(zero_positions) == 0) | (zero_positions[0] == (len(x) - 1)):
return None
else:
if (len(x) - 1) == zero_positions[-1]:
zero_positions = zero_positions[:-1]
return np.max(x[zero_positions+1])
|
072d50e7f41d002ee657c2554eed353c41845899 | realm10890/LearningOpenCV | /ImgArithmeticAndLogic/imgArithmeticAndLogic.py | 2,332 | 3.671875 | 4 | import cv2
import numpy as np
import matplotlib.pyplot as plt
img1 = cv2.imread('3D-Matplotlib.png')
img2 = cv2.imread('mainsvmimage.png')
img3 = cv2.imread('mainlogo.png')
#Simple Addition of Both Images(not really ideal)
simpleAddition = img1 + img2
cv2.imshow('Simple Addition', simpleAddition)
cv2.waitKey(0)
cv2.destroyAllWindows()
#Built in additon operation(adds pixel values, (155,211,79) + (50, 170, 200) = 205, 381, 279...translated to (205, 255,255).)
addOp = cv2.add(img1, img2)
cv2.imshow('addOperation', addOp)
cv2.waitKey(0)
cv2.destroyAllWindows()
#Adding images using weight
weighted = cv2.addWeighted(img1, 0.6, img2, 0.4, 0)
cv2.imshow('Weighted', weighted)
cv2.waitKey(0)
cv2.destroyAllWindows()
#Adding a picture ontop of another transparently
img2 = cv2.imread('mainlogo.png')
#Creating a ROI to place logo on top left corner
#Getting the dimmensions of the python logo
rows, cols, channels = img2.shape
#rows = 126, cols = 126, channels = 3
#Setting the roi to that specific part of the graph img
roi = img1[0 : rows, 0 : cols]
#make a mask out of the python logo
pythonToGray = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
cv2.imshow('First Step of Mask', pythonToGray)
cv2.waitKey(0)
#cv2.destroyAllWindows()
#adding threshold to the python image(if above 220 it will become white, if below 220 then black)
#right here the snakes are black and the background is white
#Then flip it because of last argument so everything that becomes white is black and everything that is black will become white
#right here the snakes are white and the background is black because of binary inverse
ret, mask = cv2.threshold(pythonToGray, 220, 255, cv2.THRESH_BINARY_INV)
cv2.imshow('Mask', mask)
cv2.waitKey(0)
#cv2.destroyAllWindows()
#making the invisible part of the python image
#bitwise is saying the parts that there is no mask the black area
mask_inv = cv2.bitwise_not(mask)
#the background of the graph image
img1_bg = cv2.bitwise_and(roi, roi, mask = mask_inv)
cv2.imshow('img1_bg', img1_bg)
cv2.waitKey(0)
#cv2.destroyAllWindows()
img2_fg = cv2.bitwise_and(img2, img2, mask = mask)
cv2.imshow('img2_fg', img2_fg)
cv2.waitKey(0)
#cv2.destroyAllWindows()
dst = cv2.add(img1_bg, img2_fg)
img1[0 : rows, 0 : cols] = dst
cv2.imshow('res', img1)
cv2.waitKey(0)
#cv2.destroyAllWindows()
|
4cad335320a6973ce430bd12ed04034a87cf061d | mjohnkennykumar/csipythonprograms | /basic/listmethods.py | 614 | 4.15625 | 4 | # -*- coding: utf-8 -*-
# vowel list
vowel = ['a', 'e', 'i', 'u']
# inserting element to list at 4th position
vowel.insert(3, 'o')
print('Updated List: ', vowel)
# animal list
animal = ['cat', 'dog', 'rabbit', 'guinea pig']
# 'rabbit' element is removed
animal.remove('rabbit')
#Updated Animal List
print('Updated animal list: ', animal)
# If a list contains duplicate elements
# the remove() method removes only the first instance
# animal list
animal = ['cat', 'dog', 'dog', 'guinea pig', 'dog']
# 'dog' element is removed
animal.remove('dog')
#Updated Animal List
print('Updated animal list: ', animal) |
92f704d5dd65e5020a266857aeed9e2246e1f7d0 | lindonilsonmaciel/Curso_Python | /Python_Mundo01/desafios/desafio054.py | 501 | 3.953125 | 4 | """Crie um programa que leia o ano de nascimento de sete pessoas.
No final, mostre quantas pessoas ainda não atingiram a maioridade e
quantas já são maiores."""
from datetime import date
ano = 0
atual = date.today().year - 18
maior = 0
menor = 0
for i in range(0,7):
ano = int(input('Digite o ano de nascimento da {} pessoa: '.format(i+1)))
if ano < atual:
maior += 1
else:
menor += 1
print('Ao todo temos {} maiores de idade e {} menores de idade'.format(maior,menor)) |
33de6018477d592b7bdddecd9e15783b03b06eee | harrychy8/pig-latin-translator | /jack-ver.py | 587 | 3.546875 | 4 | def piglatintranslate(s):
s = s.split(); ns = ""
for w in s:
i = 0; sf = "yay";p = ""; a = False
if not w.isalpha(): ns += w + " "; a = True
if not w[len(w) - 1].isalpha(): p = w[len(w) - 1]; w = w[:len(w) - 1]
for c in w:
if c in "aeiouAEIOU":
if w[0].isupper(): ns += w[i].upper() + w[i + 1:] + w[:i].lower() + sf + p + " "; a = True; break
else: ns += w[i:] + w[:i] + sf + p + " "; a = True; break
else: sf = "ay"
i += 1
if not a: ns += w + sf + p + " "
return ns
|
243f8dde0b88dbf2490b2c2185363844be10cff3 | zjn0810/pythonL | /algorithm/SortAndSearch/selectSort/selectSort.py | 543 | 3.921875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 7 08:59:13 2021
@author: zhangjn
"""
def selectSort(items):
for fillslot in range(len(items)-1, 0, -1):
posepoint = 0
for location in range(1, fillslot + 1):
if items[location] > items[posepoint]:
posepoint = location
temp = items[fillslot]
items[fillslot] = items[posepoint]
items[posepoint] = temp
return items
items = [23,45,56,34,345,26,66,88,46]
print(selectSort(items)) |
86d6b537f52cc01858e088c68365665e554e61f4 | khdouglass/algorithms | /condensing_sentences.py | 397 | 4.09375 | 4 | def condense_sentences(sentence):
"""Combine words in a sentence if the last letter
matches the next word's first letter.
"""
word_list = sentence.split()
for i in range(len(word_list) - 1):
if word_list[i][-1] == word_list[i + 1][0]:
word_list[i] = str(word_list[i] + word_list[i + 1])
del word_list[i + 1]
return ' '.join(word_list)
|
d15682c092fd3fa6c3773b0bfff23445bee248bf | thomasbshop/pytutor | /DateNTime/pytz_usage.py | 941 | 3.765625 | 4 | import datetime
import pytz
country = 'US/Eastern'
tz_to_display = pytz.timezone(country)
local_time = datetime.datetime.now(tz=tz_to_display)
print("The time in {0} is {1}".format(country, local_time))
print("UTC is {0}".format(datetime.datetime.utcnow()))
# for x in sorted(pytz.all_timezones_set):
# print(x)
#
# for y in pytz.all_timezones:
# print(y)
# list timezones per country
for z in sorted(pytz.country_names):
print("{0}:{1}".format(z, pytz.country_names[z]), end=":")
if z in pytz.country_timezones:
for zone in sorted(pytz.country_timezones[z]):
tz_to_display = pytz.timezone(zone)
local_time = datetime.datetime.now(tz=tz_to_display)
print("\t\t{0} - {1}".format(zone, local_time))
print(zone)
else:
print("\t\t******NO TIMEZONE DEFINED******")
# remember to only work in UTC but convert the time when displaying to the user utcnow()
|
b8e2d70b8bc57d2dd16e223619f2dfd1aaad7f9f | Lucas-ns/Python-3-Curso-Em-Video | /PythonExercicios/ex088.py | 603 | 3.625 | 4 | from random import randint
from time import sleep
print('-' * 20)
print('JOGA NA MEGA SENA')
print('-' * 20)
jogos = int(input('Quantos jogos você quer que eu sorteie? '))
print()
print('-=' * 5, f'SORTEANDO {jogos} JOGOS', '=-' * 5)
print()
sorteados = []
lista = []
for j in range(1, jogos+1):
while len(lista) != 7:
r = randint(1, 60)
if r not in lista:
lista.append(r)
lista.sort()
sorteados.append(lista[:])
lista.clear()
for i, s in enumerate(sorteados):
sleep(1)
print(f'Jogo {i+1}: {s}')
print()
print('-=' * 5, f'< BOA SORTE! >', '=-' * 5)
|
b07e57af9c760944c49558b421528400d05e7148 | VictorHeDev/ATBS | /fiveTimes.py | 203 | 3.9375 | 4 | # for loop
print('My name is')
for i in range(5): # index starting from 0
print('Jimmy Five Times('+str(i)+')')
# while loop
print('My name is:')
i = 0
while i < 5:
print('Jimmy Five Times ('+str(i)+')')
i += 1 |
29b4c3c457a55660d571e402a8d9b60ad1c250c8 | TTKSilence/Educative | /GrokkingTheCodeInterview-PatternsForCodingQuestions/11.PatternModifiedBinarySearch/6.SearchInASortedInfiniteArray(med).py | 996 | 3.96875 | 4 | #Given an infinite sorted array (or an array with unknow size),
#find if a given number 'key' is present in the array.
#Write a function to return the index of the 'key' if it is present in the array, otherwise return -1.
def Search(array,key):
if array[0]>key:
return -1
start,end=0,1
size=2
while array[end]<key:
size=2*size
start=end+1
end=start+size
while start<=end:
mid=start+(end-start)//2
if array[mid]<key:
start=mid+1
else:
index=mid
end=mid-1
return index if array[index]==key else -1
def main():
print(Search([4,6,8,9,9,10,13,15,17,18,23,27,29,34,38,46,57],9))
print(Search([4,6,8,9,9,10,13,15,17,18,23,27,29,34,47,57,86],18))
print(Search([4,6,8,9,10,13,15,18,23,23,23,27,29,34,46,57,57,67],23))
print(Search([4,4,6,8,9,9,10,13,15,17,23,29,34,37,56,57,58,68,69],4))
print(Search([4,6,8,9,9,10,13,15,17,18,23,27,34,37,45,47,48,58,68],16))
main() |
50a88a67fffff3c5a46a6533347c3630638e606a | Thandiwe-Khalaki/ZuriTeam | /AutomatedTellerMachine.py | 1,406 | 3.921875 | 4 | import datetime
now = datetime.datetime.now()
print ("Current date and time : ")
print (now.strftime("%Y-%m-%d %H:%M:%S"))
print("WELCOME TO ABC ATM MACHINE")
print("PLEASE CHOOSE THE FOLLOWING OPTIONS")
print("\n1 - Withdraw \t 2 - Deposit \t 3 - Complain \t 4 - Exit ")
selection = int(input("\nEnter your selection: "))
#withdrawal amount
wamt = 0.00
#deposite amount
damt = 0.00
#account balance
net_amt = 0.00
if selection == 1:
# Withdraw
wamt = float(input("\nHow much would you like to withdraw: "))
ver_wamt = input("Is this the correct amount, Yes or No ? " + str(wamt) + " ")
if ver_wamt == "Yes":
print("Take your cash")
net_amt = net_amt + wamt
else:
print("Please start again")
if selection == 2:
# Deposit
damt = float(input("\nHow much would you like to deposit: "))
ver_damt = input("Is this the correct amount, Yes or No ? " + str(damt) + " ")
if ver_damt == "Yes":
net_amt = net_amt + damt
print("Current balance is " + str(net_amt))
else:
print("Please start again")
if selection == 3:
# complain
issue = input("\nWhat issue would you like to report: ")
ver_issue = input("Is this the issue correct, Yes or No ? " + issue + " ")
if ver_issue == "Yes":
print("Thank you for reporting this issue to us")
else:
print(" Please start again")
else:
print("Thank you") |
8d1e3fd745ca85f278a2765617c4ea3c7aab1a90 | mxu007/leetcode | /191_Number_of_1_Bits.py | 1,148 | 3.9375 | 4 | # Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight).
# Example 1:
# Input: 11
# Output: 3
# Explanation: Integer 11 has binary representation 00000000000000000000000000001011
# Example 2:
# Input: 128
# Output: 1
# Explanation: Integer 128 has binary representation 00000000000000000000000010000000
# https://leetcode.com/problems/number-of-1-bits/description/
# 1) convert to binary string and then sum individual bits
class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
n_bin = "{0:b}".format(n)
return sum(int(i) for i in n_bin)
# 2) built in bin function
class Solution(object):
def hammingWeight(self, n):
return bin(n).count('1')
# 3) bit operations
class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
c = 0
while n:
# n & operation with n-1 will cancel the left most available bit, so c gets updated by 1
n &= n - 1
c += 1
return c
|
0ff460ee013d9557a2a216ee8cef6b4fff939239 | gop50k/Python3 | /src/c3/func-animal-speed.py | 1,230 | 3.9375 | 4 | # coding: UTF-8
# 動物の最高時速を辞書型で定義
animal_speed_dict = {
'チーター': 110, 'トナカイ': 80,
'シマウマ': 60, 'ライオン': 58,
'キリン ': 50, 'ラクダ ': 30,
'新幹線 ': 300, '飛行機 ': 1000,
}
# 東京から各都市への距離を辞書型で定義
distance_dict = {
'静岡': 183.7,
'名古屋': 350.6,
'大阪': 507.5,
'福岡': 1000,
}
# 時間を計算する関数
def calc_time(dist, speed):
t = dist / speed
t = round(t, 1)
return t
# 動物の各都市までの時間を計算
def calc_animal(animal, speed):
res = '|' + animal
for city in sorted(distance_dict.keys()):
dist = distance_dict[city]
t = calc_time(dist, speed)
res += '|{0:>5}'.format(t)
return res + '|'
# 表のヘッダを作成
print('+--------+------+-------+---------+')
print('|動物の名前', end='')
for city in sorted(distance_dict.keys()):
print('|' + city, end='')
print('|')
print('+--------+------+-------+---------+')
# 各動物毎に結果を求めて表示
for animal, speed in animal_speed_dict.items():
s = calc_animal(animal, speed)
print(s)
print('+--------+------+-------+---------+')
|
f99281f898f92a757e040fa27972beb2f79fbe1b | branko-malaver-vojvodic/Python | /recurs_duplicate_elem.py | 209 | 3.734375 | 4 | #Recurssivity to have a list with all the original elements duplicated
def recDup(lst):
if lst == []:
return lst
else:
A = lst[0:1]
B = lst[1:]
return (A*2) + recDup(B)
|
e488f8d8c495f446d7486e5f39098802ad13bc42 | Dr-Ex/Cowbell | /Frontend/cloud_save.py | 5,217 | 4 | 4 | """
Created on Fri Jul 28 11:22:34 2017
@author: Lysenthia and dr-ex
"""
import sqlite3
class DropTablesError(Exception):
""" Somebody tried to drop tables us """
def create_database(db, cursor):
""" Creates the initial database """
cursor.execute('''CREATE TABLE users(
ID INTEGER PRIMARY KEY AUTOINCREMENT,
UID TEXT,
author_name TEXT)''')
cursor.execute('''CREATE TABLE songs(
ID INTEGER PRIMARY KEY AUTOINCREMENT,
song_notes TEXT,
creation_date TEXT,
project_name TEXT,
user_ID INTEGER,
FOREIGN KEY(user_ID) REFERENCES users(ID)
)''')
db.commit()
cursor.close()
db.close()
def add_user(db, cursor, uid, author_name="Anon"):
""" Creates a new table in the database containing a users projects """
if any('drop tables' in var for var in [uid]):
raise DropTablesError("Drop Tables command detected in input commands - Print Error Message")
cursor.execute("INSERT INTO users VALUES (NULL, ?,?)",(uid, author_name))
db.commit()
def add_project(db, cursor, user_ID, song_notes, creation_date, project_name):
""" Adds the data for a project to a users table in the database """
if any('drop tables' in var for var in [str(user_ID), song_notes, creation_date, project_name]):
raise DropTablesError("Drop Tables command detected in input commands - Print Error Message")
cursor.execute("INSERT INTO songs VALUES (NULL, ?,?,?,?)",(song_notes, creation_date, project_name, user_ID))
db.commit()
return True
def get_uids(db, cursor):
""" Gets all uids and returns them as a list """
import itertools
cursor.execute("SELECT UID FROM users")
all_uids = cursor.fetchall()
db.commit()
all_uids = list(itertools.chain(*all_uids))
return all_uids
def save_project(db, cursor, uid, song_ID, project_name, song_notes):
""" Saves an already existing page to the database """
if any('drop tables' in var for var in [uid]):
raise DropTablesError("Drop Tables command detected in input commands - Print Error Message")
cursor.execute("SELECT ID FROM users WHERE UID=?",(uid,))
user_ID = cursor.fetchall()
user_ID = user_ID[0][0]
cursor.execute("UPDATE songs SET song_notes = ?, project_name = ? WHERE user_ID=? AND ID=?",(song_notes, project_name, user_ID, song_ID,))
db.commit()
return True
def open_project(db, cursor, uid, song_ID):
""" Opens a project for use """
if any('drop tables' in var for var in [uid]):
raise DropTablesError("Drop Tables command detected in input commands - Print Error Message")
cursor.execute("SELECT songs.ID, song_notes, author_name, creation_date, project_name FROM songs INNER JOIN users ON users.ID = songs.user_ID WHERE songs.ID=? AND UID=?",(song_ID, uid,))
project_data = cursor.fetchall()
db.commit()
return project_data
def list_projects(db, cursor, UID):
""" Returns a list of tuple triplets of creation_date, project_name and song_ID for a users songs """
if any('drop tables' in var for var in [UID]):
raise DropTablesError("Drop Tables command detected in input commands - Print Error Message")
cursor.execute("SELECT ID FROM users WHERE UID=?",(UID,))
user_ID = cursor.fetchall()
user_ID = user_ID[0][0]
cursor.execute("SELECT creation_date, project_name, ID FROM songs WHERE user_ID=?",(user_ID,))
projects = cursor.fetchall()
db.commit()
return projects
def get_user_data(db, cursor, UID):
""" Gets the users data and returns it as a list """
if any('drop tables' in var for var in [UID]):
raise DropTablesError("Drop Tables command detected in input commands - Print Error Message")
cursor.execute("SELECT * FROM users WHERE UID=?",(UID,))
user_data = cursor.fetchone()
db.commit()
return user_data
def change_user_name(db, cursor, UID, name):
""" Gets the users data and returns it as a list """
if any('drop tables' in var for var in [UID, name]):
raise DropTablesError("Drop Tables command detected in input commands - Print Error Message")
cursor.execute("UPDATE users SET author_name=? WHERE UID=?",(name,UID,))
db.commit()
def change_song_name(db, cursor, song_id, song_name):
""" Changes the name of a song """
if any('drop tables' in var for var in [song_id, song_name]):
raise DropTablesError("Drop Tables command detected in input commands - Print Error Message")
cursor.execute("UPDATE songs SET project_name=? WHERE ID=?",(song_name,song_id,))
db.commit()
def close_database(db, cursor):
cursor.close()
db.close()
def open_database(DB_NAME, DB_DIRECTORY):
if any('drop tables' in var for var in [DB_NAME, DB_DIRECTORY]):
raise DropTablesError("Drop Tables command detected in input commands - Print Error Message")
db = sqlite3.connect('{}/{}'.format(DB_DIRECTORY, DB_NAME))
cursor = db.cursor()
return db, cursor
#print(open_project("cloud_save.db", "public/static/db", "thisismyuid", 1)[0][1])
#save_project("database.db", "server_side_storage", "thisistheuidomg12345", 3, "yser 1's cool project", "oldsongnotes")
|
b0f45dcfa2ac2dbef3f3708902da28b908e6be27 | ravi4all/PythonWeekendFeb | /07-GameDevelopment/03-FramesPerSecond.py | 1,203 | 3.53125 | 4 | import pygame
pygame.init()
red = (255,0,0)
speed = [2,2]
width = 900
height = 500
screen = pygame.display.set_mode((width,height))
rect_x = 0
rect_y = 0
move_x = 10
move_y = 10
lead_x = 0
lead_y = 0
clock = pygame.time.Clock()
FPS = 30
game = False
while not game:
for event in pygame.event.get():
#print(event)
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
rect_x = move_x
rect_y = 0
if event.key == pygame.K_LEFT:
rect_x = -move_x
rect_y = 0
if event.key == pygame.K_DOWN:
rect_y = move_y
rect_x = 0
if event.key == pygame.K_UP:
rect_y = -move_y
rect_x = 0
screen.fill((255,255,255))
# Screen, Color, x,y,width,height
pygame.draw.rect(screen, red, [lead_x,lead_y,100,100])
lead_x += rect_x
lead_y += rect_y
pygame.display.update()
clock.tick(FPS)
pygame.quit()
quit()
|
76ef400dfebf36e0a872bea8779516add0fdb2ac | lucasportella/learning-python | /python-codes/m2_curso_em_video_estruturas_de_controle/ex058.2.py | 354 | 3.75 | 4 | from random import randint
computador = randint(0,10)
print('Pensei num número de 0 a 10. Adivinhe.')
acertou = False
palpites = 0
print(computador)
while acertou == False:
jogador = int(input('Qual é seu palpite? '))
palpites += 1
if jogador == computador:
acertou = True
print('Você acertou com {} tentativa(s)'.format(palpites)) |
b84e68fc6db423213365c6303df30f88e3b5b3c2 | Lucas-Urbano/Python-for-Everybody | /Definite_loops_with_strings.py | 154 | 3.828125 | 4 | #A DEFINITE LOOPS WITH STRINGS
for i in['Lucas Urbano', 'ama a Jesus Cristo', 'sua glória durará para todo sempre']:
print('#DEUS:', i)
print('Aleluia a Jesus') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.