blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
fb7190e9e371fb513bd4379b6f74ac848eb2c538 | SurekshyaSharma/Variables | /sum.range.py | 217 | 4.125 | 4 | # inputs from the user
start = int(input("Enter the first number:"))
stop = int(input("Enter the second number:"))
# loop for
product = 0
for i in range(start, stop+1):
product = product + (i ** 2)
print(product)
|
e69bf8b729cb69258978d8aefc49a7afa92ab900 | PaulMFleming/Python3-For-Systems-Administrators | /ex1_creating_and_displaying_variables.py | 215 | 3.96875 | 4 | #!/usr/bin/env python3.7
first_name = "Paul"
last_name = "Fleming"
age = 31
birth_date = "24/08/1987"
print(f"My name is {first_name} {last_name}.")
print(f"I was born on {birth_date}, and I'm {age} years old.")
|
e8b7f83d85d00b02595bcf5024bbac90964a213f | ellisonbg/py4science | /book/examples/wordfreqs.py | 1,409 | 4.5625 | 5 | #!/usr/bin/env python
"""Word frequencies - count word frequencies in a string."""
def word_freq(text):
"""Return a dictionary of word frequencies for the given text."""
freqs = {}
for word in text.split():
freqs[word] = freqs.get(word, 0) + 1
return freqs
def print_vk(lst):
"""Print a list of value/key pairs nicely formatted in key/value order."""
# Find the longest key: remember, the list has value/key paris, so the key
# is element [1], not [0]
#longest_key = max(map(lambda x: len(x[1]),lst))
longest_key = max([len(word) for count, word in lst])
# Make a format string out of it
fmt = '%'+str(longest_key)+'s -> %s'
# Do actual printing
for v,k in lst:
print fmt % (k,v)
def freq_summ(freqs,n=10):
"""Print a simple summary of a word frequencies dictionary.
Inputs:
- freqs: a dictionary of word frequencies.
Optional inputs:
- n: the number of """
words,counts = freqs.keys(),freqs.values()
# Sort by count
items = zip(counts,words)
items.sort()
print 'Number of words:',len(freqs)
print
print '%d least frequent words:' % n
print_vk(items[:n])
print
print '%d most frequent words:' % n
print_vk(items[-n:])
if __name__ == '__main__':
import gzip
text = gzip.open('HISTORY.gz').read()
freqs = word_freq(text)
freq_summ(freqs,20)
|
1fea816d774db09f4145bb5384b3c82eb0831af1 | AnnieJeez/Pythons | /mean3.py | 202 | 3.765625 | 4 | data = [6,4,3,7,2]
size = len(data) #6
# Median for even numbers
if (size %2 == 1):
print(data[int(size/2)])
else:
x= (data[int(size/2)] + data[int(size/2 -1)])/2
print(x)
|
36044d1822a2af6699de229a9e9eab6cedaade4a | vina19/SQLite-DB | /record_holder.py | 4,183 | 3.9375 | 4 | import sqlite3
# Create connection to database
con = sqlite3.connect('chainsaw_juggling_db.sqlite')
# Create variable for database
db = 'chainsaw_juggling_db.sqlite'
# Create a table name records if it doesn't exist
con.execute('CREATE TABLE IF NOT EXISTS records (name TEXT, country TEXT, number_catches INTEGER)')
# Adding record to the database
def add_record_holder(name, country, number_catches):
insert_data = 'INSERT INTO records (name, country, number_catches) VALUES (?, ?, ?)'
with sqlite3.connect(db) as con:
con.execute(insert_data, (name, country, number_catches))
con.commit()
# Search record holder by their name from database
def search_record_holder(name):
search_data = 'SELECT * FROM records WHERE name = ?'
with sqlite3.connect(db) as con:
con.execute(search_data, (name, ))
# http://www.mysqltutorial.org/python-mysql-query/
record_rows = con.fetchall()
# Display record from database
for record in record_rows:
print('Name: ', record[0], ' | ', 'Country: ', record[1], ' | ', 'Number Catches: ', record[2])
con.close()
# Update the number of catches by their name in database
def update_record_holder(number_catches, name):
update_data = 'UPDATE records SET number_catches = ? WHERE name = ?'
with sqlite3.connect(db) as con:
updated = con.execute(update_data, (number_catches, name))
row_updated = updated.rowcount # Show how many rows affected
con.commit()
# Raise RecordError if there is no record
if row_updated == 0:
raise RecordError('Record cannot be found')
# If the number of cathces input is not number raise RecordError
if not isinstance(number_catches, (int)) or number_catches < 0:
raise RecordError('Please enter a valid number and positive number.')
# Delete record in database by record holder's name
def delete_record_holder(name):
delete_data = 'DELETE FROM records WHERE name = ?'
with sqlite3.connect(db) as con:
deleted = con.execute(delete_data, (name, ))
deleted_count = deleted.rowcount # Show how many row affected
con.close()
# Raise RecordError if there is no record
if deleted_count == 0:
raise RecordError('Record cannot be found')
# Display of the menu options for the user
def menu_options():
print('-Chainsaw Juggling Record Holders July 2018- \n')
print('1. Add Record Holder')
print('2. Search record holder name')
print('3. Update the number of catches')
print('4. Delete record by name')
print('5. Quit')
user_input = int(input('Enter choice: '))
# if the user enter number outside 1-6 print error message
if not 1 <= user_input < 6:
print('Error: please enter a number between 1-5.')
else:
return user_input
# Main method
def main():
running = True
while running:
# Display the menu
user_choices = menu_options()
# Get the user input, depend on the number option they choose
if user_choices == 1:
name = input('Enter the record holder name: ')
country = input('Enter the country where the record holder from: ')
number_catches = int(input('Enter the number of catches: '))
add_record_holder(name, country, number_catches)
elif user_choices == 2:
search_name = input('Enter the name that you would like to find: ')
search_record_holder(search_name)
elif user_choices == 3:
update_name = input('Enter the name of the record holder that need to be updated: ')
number_catches = int(input('Enter the new number of catches: '))
update_record_holder(number_catches, update_name)
elif user_choices == 4:
delete_name = input("Enter the name of the person in the record that you want to delete: ")
delete_record_holder(delete_name)
elif user_choices == 5:
running = False
print('Thank you and goodbye!')
return user_choices
# Record Errors
class RecordError(Exception):
pass
if __name__ == '__main__':
main() |
94f4bfc936687609aeaad19d5066af726aa41d58 | Null78/KAU-CPIT-Labs | /Lab 8/8-3.py | 1,402 | 4.3125 | 4 | # Ask the user for the number of students
number = eval(input("Enter the number of students: "))
# Get the first student name and score
# Highest score
name1 = input("Enter a student name: ")
score1 = eval(input("Enter a student score: "))
# Get the second student name and score
# Second highest score
name2 = input("Enter a student name: ")
score2 = eval(input("Enter a student score: "))
if score2 > score1:
# If score2 is higher than score1
# Swap the variables
score1, score2 = score2, score1
name1, name2 = name2, name1
# Ask the user for student names and scores
# loop one time less than number entered by the user
for i in range(number - 2):
# Ask the user for the next student name and score
name = input("Enter a student name: ")
score = eval(input("Enter a student score: "))
# Check the score of the entered student with the highest score
if score > score1:
# the highest student became the second highest
name2, score2 = name1, score1
# And the new one is the highest
name1 = name
score1 = score
# Check the new student score with the second highest score
elif score > score2:
name2 = name
score2 = score
# when the loop stopes
# Display the output
print() # Empty line
print("Top two students: ")
print(f"{name1}'s score is {score1}")
print(f"{name2}'s score is {score2}")
|
d4a6fcb66f9a4bf0aa93638ba2a1f98e7274fc98 | LyudmilaTretyakova/AppliedPythonAtom | /homework_01/hw1_calcadv.py | 928 | 3.53125 | 4 | # import operator
# import re
# ops = { '+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.truediv}
# def eval_expression(tokens, stack):
# _rex=re.compile(r'^[-+]?[0-9]*[.,]?[0-9]+(?:[eE][-+]?[0-9]+)?$')
# for token in tokens:
# if _rex.match(token):
# stack.append(float(token))
# elif token in ops:
# if len(stack) < 1:
# return None
# elif len(stack)==1:
# return stack.pop()
# else:
# a = stack.pop()
# b = stack.pop()
# op = ops[token]
# stack.append(op(b,a))
# else:
# return None
# return stack.pop()
#
# def advanced_calculator (expr):
# expression=expr
# stack = []
# if len(expression)==0:
# return None
# else:
# return eval_expression(expression.split(' '), stack) |
ffe511c1c563bb2f95e17313a97e9614bfa813c3 | brandoneng000/LeetCode | /easy/917.py | 703 | 3.5625 | 4 | class Solution:
def reverseOnlyLetters(self, s: str) -> str:
s = list(s)
start = 0
end = len(s) - 1
while start < end:
while start < len(s) and not s[start].isalpha():
start += 1
while end >= 0 and not s[end].isalpha():
end -= 1
if start >= end:
break
temp = s[start]
s[start] = s[end]
s[end] = temp
start += 1
end -= 1
return "".join(s)
def main():
sol = Solution()
print(sol.reverseOnlyLetters("ab-cd"))
print(sol.reverseOnlyLetters("a-bC-dEf-ghIj"))
if __name__ == '__main__':
main() |
29cd91041c46d4966651e951b4a9acad5ed85c9b | 786930/python-basics | /translate.py | 550 | 3.75 | 4 | # Program name: translate.py
# Your Name: Aerin Schmall
# Python Version: 3.7.8
# Date Started - Date Finished: 12/8/2020 - //2020
# Description:
import gettext
print(_("original"))
print (_( "===+++===&&&---"))
print (_("Good morning"))
print ("Good night")
print(_("please enter 3 numbers"))
Sum = 0
for i in range(0,3,1):
num = float ( input ( _( "Please enter number ") +str(i+1) +":") )
Sum += num
print("The sum of the numbers you entered" + str(Sum))
'''
============= RESTART: C:\\Users\\aerin\\Documents\\Python\\
'''
|
4e547d65d37191c64c456221bf3d2c45881efd11 | utkarsh-dubey/Codeforces | /1326A.py | 213 | 3.90625 | 4 | t=int(input())
for _ in range(t):
n=int(input())
if(n==1):
print(-1)
else:
print("2",end="")
for i in range(n-1):
print("3",end="")
print() |
31560552345647a05319cc127f4bc4852f2dc7f2 | xiaotuzixuedaima/PythonProgramDucat | /python_program/without_use_another_num_swap.py | 240 | 3.921875 | 4 | #3. Exchange the Values of Two Numbers Without Using a Temporary Variable ..??
a = int(input("enter the 1st no:"))
b = int(input("enter the 2nd no:"))
b = (a+b)-a
a = (a+b)-b
print("swap the value a =",b)
print("swap the value b =",a)
|
6d78f9c97a0a2280b03123d7706ae3e7a80ce7e6 | JCharlieDev/Python | /Python Programs/Lists/Lists.py | 162 | 3.828125 | 4 |
friends = ["Kevin", "Karen", "Bob"]
# Using negative indexes starts from the reverse of the list.
print(friends[2])
# Specifies a range
print(friends[1:]) |
4a0e1961b861b77576190f1349d2b467bb2e015c | ZFudge/Project-Euler-Python | /project13.py | 559 | 3.953125 | 4 | def collatz(num,count=0):
if num != 1:
if num % 2 == 0: return collatz(num/2,count+1)
else: return collatz(num*3+1,count+1)
else: return count + 1
largestCollatz = [0,0]
for n in range(100,1000000):
col = collatz(n)
if col > largestCollatz[0]: [largestCollatz[0],largestCollatz[1]] = [col,n]
print """The largest collatz sequence made from a starting
number under one million is {0} steps long.
The starting number to produce this chain is {1}.""".format(largestCollatz[0],largestCollatz[1])
|
35901063022c4604ffc4d4ff97ccfd57cef892bb | nmanor/TextClassificationScript | /terms_frequency_counts.py | 3,747 | 3.65625 | 4 | import os
from sklearn.feature_extraction.text import CountVectorizer
def get_top_n_words(corpus, ngrams1=2, ngrams2=2, n=None, filtering=True):
"""
:param filtering: filter the words by the 3% filter before returning the result
:param n: [the number of words needed]
:param ngrams2: [ngrams upper bound]
:param corpus: list of strings
:param ngrams1: [ngrams lower bound]
:return: List the top n words in a vocabulary according to occurrence in a text corpus
:rtype: list
get_top_n_words(["I love Python", "Python is a language programming", "Hello world", "I love the world"]) ->
[('python', 2),
('world', 2),
('love', 2),
('hello', 1),
('is', 1),
('programming', 1),
('the', 1),
('language', 1)]
"""
vec = CountVectorizer(ngram_range=(ngrams1, ngrams2)).fit(corpus)
bag_of_words = vec.transform(corpus)
sum_words = bag_of_words.sum(axis=0)
words_freq = [(word, sum_words[0, idx]) for word, idx in vec.vocabulary_.items()]
words_freq = sorted(words_freq, key=lambda x: x[1], reverse=True)
return lower_bound_test(words_freq, corpus)[:n] if filtering else words_freq[:n]
def lower_bound_test(top_words, corpus, threshold=0.03, minimum_posts=3):
"""
:param top_words: list of most common words in the corpus in order
:param corpus: the corpus itself
:param threshold: only words that appear in at least 'threshold' percent of posts will enter
:param minimum_posts: the minimum number of posts a words must appear in
:return: Returns a list of the n most common words provided that each of the
words appears in at least 3% of the posts in the corpus and in 3 different posts
"""
# split the corpus from string to list
# corpus = str(corpus).split('\n')
# the list of words to return
new_list = []
# for each words in the most common sequence of words:
for word in top_words:
repetition = 0
# for each post in the corpus:
for post in corpus:
# if the words appears in the post, update the number of repetitions
if word[0] in post:
repetition += 1
# if so far the words has been repeated more than #threshold percent in the database,
# and the words also appeared in at least #minimum_posts different posts in the database,
# then the words passed the tests successfully: add the words to the final list and stop the inner loop
if repetition / len(corpus) >= threshold and repetition >= minimum_posts:
new_list += [word]
break
# return the final list of words
return new_list
def word_freq(corpus_path, out_path, ngrams, show_amaount=True):
# read the content of the file
text = open(corpus_path, "r", encoding="utf8", errors='replace').readlines()
# collect the words in order of importance
result = ''
i = 1
for tup in lower_bound_test(get_top_n_words(text, ngrams, ngrams), text)[:1000]:
result += '\n' + str(i) + ": " + tup[0]
if show_amaount:
result += ' - ' + str(tup[1])
i += 1
# save the words into the output path
title = "\\" + corpus_path.split('\\')[-1].split('.')[0] + " most freq words " + {2:"bigrams", 1:"unigrams", 3:"trigrams"}[ngrams] + ".txt"
with open(out_path + title, "w", encoding="utf8", errors='replace') as file:
file.write(result[1:])
if __name__ == '__main__':
in_path = r"C:\Users\user\Documents\test\dataset\training"
out_path = r"C:\Users\user\Documents\test\מילים"
for file in os.listdir(in_path):
for num in [1, 2]:
word_freq(in_path + '\\' + file, out_path, num)
|
29bcb620ec75a93f13d88254737db6a6a998f321 | Kripperoo/Genetic-Programming-for--Snake- | /snakePlay.py | 2,575 | 3.984375 | 4 | # This version of the snake game allows you to play the same yourself using the arrow keys.
# Be sure to run the game from a terminal, and not within a text editor!
import curses
from curses import KEY_RIGHT, KEY_LEFT, KEY_UP, KEY_DOWN
import random
curses.initscr()
XSIZE,YSIZE = 18,18
NFOOD = 1
win = curses.newwin(YSIZE, XSIZE, 0, 0)
win.keypad(1)
curses.noecho()
curses.curs_set(0)
win.border(0)
win.nodelay(1)
def placeFood(snake, food):
for last in food:
win.addch(last[0], last[1], ' ')
food = []
while len(food) < NFOOD:
potentialfood = [random.randint(1, (YSIZE-2)), random.randint(1, (XSIZE-2))]
if not (potentialfood in snake) and not (potentialfood in food):
food.append(potentialfood)
win.addch(potentialfood[0], potentialfood[1], '*')
return( food )
def playGame():
score = 0
key = KEY_RIGHT
snake = [[4,10], [4,9], [4,8], [4,7], [4,6], [4,5], [4,4], [4,3], [4,2], [4,1],[4,0] ] # Initial snake co-ordinates
food = []
food = placeFood(snake,food)
win.timeout(150)
wasAhead = []
ahead = []
A = "NO"
while True:
win.border(0)
prevKey = key # Previous key pressed
event = win.getch()
key = key if event == -1 else event
if key not in [KEY_LEFT, KEY_RIGHT, KEY_UP, KEY_DOWN, 27]: # If an invalid key is pressed
key = prevKey
# Calculates the new coordinates of the head of the snake. NOTE: len(snake) increases
# This is taken care of later at [1] (where we pop the tail)
snake.insert(0, [snake[0][0] + (key == KEY_DOWN and 1) + (key == KEY_UP and -1), snake[0][1] + (key == KEY_LEFT and -1) + (key == KEY_RIGHT and 1)])
# Game over if the snake goes through a wall
if snake[0][0] == 0 or snake[0][0] == (YSIZE-1) or snake[0][1] == 0 or snake[0][1] == (XSIZE-1): break
ahead = [ snake[0][0] + (key == KEY_DOWN and 1) + (key == KEY_UP and -1), snake[0][1] + (key == KEY_LEFT and -1) + (key == KEY_RIGHT and 1)]
if ahead in snake:
A = "YES"
# Game over if the snake runs over itself
if snake[0] in snake[1:]: break
if snake[0] in food: # When snake eats the food
score += 1
food = placeFood(snake,food)
else:
last = snake.pop() # [1] If it does not eat the food, it moves forward and so last tail item is removed
win.addch(last[0], last[1], ' ')
win.addch(snake[0][0], snake[0][1], '#')
curses.endwin()
print(A)
print("\nFinal score - " + str(score))
print(wasAhead)
playGame()
|
2552d45a81e2d6c4354359c6c7ce55504fed6d1b | DaniG2k/ProjectEuler | /3.py | 493 | 3.765625 | 4 | #! /usr/bin/env python
def isPrime(n):
if n < 1:
return False
elif n == 1:
return True
else:
l = [i for i in range(1, n+1) if n % i == 0]
if l[0] == 1 and l[1] == n:
return True
return False
def primeFactors(num):
l = []
i = 2
while i <= num:
if isPrime(i) and num % i == 0:
l.append(i)
num = num / i
#print 'num:',num
#print 'i:',i
#print '(num/i)',(num/i)
else:
i += 1
#print 'incrementing i to',i
return l
print primeFactors(600851475143)
|
d438993324572adf689d0b911ff9394b54035d72 | picuzzo2/Lab101and103 | /Lab9/Lab09_5.1.py | 583 | 3.53125 | 4 | def main():
code_table = 'aceiklmr-'
text = '''
3
5 3 4 2
3 1 2 8 1 7 2 0 86
'''
decode(code_table,text)
def decode(code_table,text):
x=0
column = text.strip()
while x!= len(column):
#if len(column[x])!=0:
y = column[x].split(' ')
for i in range(len(y)):
if int(y[i]) <= len(code_table):
print(code_table[int(y[i])],end='')
else:
print('_',end='')
print('')
i=0
#else:
# print('',end='')
x=x+1
if __name__ == '__main__':
main()
|
6b0006215fa7dd9345759d7a7360f703b0029d8f | stacygo/2021-01_UCD-SCinDAE-EXS | /12_Introduction-to-Deep-Learning-in-Python/12_ex_3-03.py | 662 | 3.78125 | 4 | # Exercise 3-03: Specifying a model
import pandas as pd
df = pd.read_csv('input/hourly_wages.csv')
target = df['wage_per_hour'].values
predictors = df.drop(['wage_per_hour'], axis=1).values
# Import necessary modules
from tensorflow import keras
from tensorflow.keras.layers import Dense
from tensorflow.keras.models import Sequential
# Save the number of columns in predictors: n_cols
n_cols = predictors.shape[1]
# Set up the model: model
model = Sequential()
# Add the first layer
model.add(Dense(50, activation='relu', input_shape=(n_cols,)))
# Add the second layer
model.add(Dense(32, activation='relu'))
# Add the output layer
model.add(Dense(1))
|
bf2bc411ff305ef7c4f07ce77b13201d2d1fc180 | hawlette/intesivepython | /Aug21/EssentialPythonWorkshop/documentation/commentsdemo.py | 265 | 4.53125 | 5 | # In this python file we will be calculating the area of circle
# We accept radius input from user
radius = int(input('Enter radius: '))
# Set the value of pi to a variable
pi = 3.14
area = pi * radius ** 2
print(f"Area of circle with radius {radius} is {area}")
|
08a780d109c07b712e864130cb2bfdddce8fe700 | pandeypro/sem-3-python-lab | /question17.py | 211 | 4.0625 | 4 | n=int(input("enter the number to be checked : "))
cuberoot=round(n**(1/3))
if cuberoot*cuberoot*cuberoot==n :
print("“the number is perfect cube")
else :
print("“the number is not perfect cube") |
0edaee4be37fddf8f6a5c85e257a27919796153b | phaneendra-bangari/python-scripts | /Python Learning Scripts/Data_Structures/tuples.py | 1,292 | 4.34375 | 4 | '''
Tuples - An empty tuples boolean value is False.
You can add a list in a tuples.
Tuples are immutable, we cannot change a part of the tuple data. Its same like strings.
Hence, Lenght, count and index are only available for Tuple.
Use tuple for the data which needs not to be changed.
'''
MY_FAMILY="Father","Mother","Brother","Sister" # This is also a tuple declaration.
print(f"The content of MY_FAMILY are {MY_FAMILY} and the type is {type(MY_FAMILY)}")
EVEN_NUMBERS=(2,4,6,8,10) # This is another type of tuple declaration.
print(f"The content of EVEN_NUMBERS are {EVEN_NUMBERS} and the type is {type(EVEN_NUMBERS)}")
STOCK_VALUES=(1,2,3,[4,4.5,4.7,4.9],4,9,10) # We can even add a list in a tuple.
print(f"The content of STOCK_VALUES are {STOCK_VALUES} and the type is {type(STOCK_VALUES)}")
print(f"Accessing the list part of the tuple STOCK_VALUES i.e Second element of the list in the tuple. \n{STOCK_VALUES[3][1]}")
# Length operation on tuples
print(f"Length of the STOCK_VALUES is {len(STOCK_VALUES)}")
# Count operation on Tuples
print(f"Count of the value \'4\' in STOCK_VALUES is {STOCK_VALUES.count(4)}") #The value inside the list is not counted as value 4.
# Index operation on tuples
print(f"Index of the value \'10\' in STOCK_VALUES is {STOCK_VALUES.index(10)}")
|
0f0f212032e70e1f6c9be077960e58d9c39bd057 | eldonato/Estrdados_Uniesp | /avaliacao 2/exerciciob.py | 270 | 4.03125 | 4 | '''
Num programa python, crie um array com os seguintes valores
"uniesp”, "2020.2”, "SI”, "ED”.
Em seguida, imprima apenas o segundo valor do array (é o valor 2020.2).
'''
def main():
lista = ['uniesp', 2020.2, 'SI', 'ED']
print(lista[1])
main()
|
eda4f37ac1c015e592626f1c5afa26127a7d64fc | sigkarmoil/python-challenge | /PyPoll/main.py | 2,083 | 3.53125 | 4 | import os
import csv
import statistics
import itertools
poll_voters= []
poll_candidate = []
#1. opening the file
#Remember to fix the csv path later
csvpath= os.path.join('Resources','election_data.csv')
#csvpath= (r'C:\Users\haeze\OneDrive\Documents\GitHub\python-challenge\PyPoll\Resources\election_data.csv')
with open(csvpath, 'r') as csvfile:
csvreader = csv.reader(csvfile, delimiter=',')
#object type
csv_header = next(csvreader)
for rows in csvreader:
poll_voters.append(rows[0])
poll_candidate.append(rows[2])
total_votes = len(poll_voters)
#2. Printing the candidates
#2.1 finding unique candidate name
candidate_name = []
for person in poll_candidate:
if person not in candidate_name:
candidate_name.append(person)
#2.2 totalling candidate vote at each_cand_votes
##create receptacle to store candidate votes. This receptacle will automatically change if new candidates join, or if candidate decrease
each_cand_votes= list(itertools.repeat(0,len(candidate_name) ) )
#2.3 add unique candidates
##automatically add number of votes, based on matching name.
for x in poll_candidate:
each_cand_votes[candidate_name.index(x)]=each_cand_votes[candidate_name.index(x)]+1
#2.4 For Loop to print the candidates performances
def myformat(x):
return ('%.2f' % x).rstrip('0').rstrip('.')
#csv_output=(r"C:\Users\haeze\OneDrive\Documents\GitHub\python-challenge\PyPoll\analysis\analysis.csv")
csv_output=os.path.join('analysis','analysis.csv')
with open(csv_output,'w', newline='') as csv_writer:
csv_writer = csv.writer(csv_writer, delimiter=',')
csv_writer.writerow([ f"Election Results" ])
csv_writer.writerow([ f"----------------------------------- " ])
csv_writer.writerow([ f" Total Votes: {total_votes} " ])
for x in range(len(candidate_name)):
csv_writer.writerow( [f"{candidate_name[x]}: { myformat( (each_cand_votes[x]/total_votes)*100 ) }% ({each_cand_votes[x]})"])
csv_writer.writerow([ f"Winner: {candidate_name[ each_cand_votes.index( max(each_cand_votes) ) ] } " ])
|
46dc32db17162ad598f99e9acb88527f801aa115 | nishaagrawal16/Datastructure | /Problems/two_players.py | 2,443 | 3.59375 | 4 | # ****************************************************************************
# There are two players which are playing a game in which each player has
# assign a character. He needs to remove the character which are more than
# one in a adjacent sequence and get the hightest score. Suppose P1 has 'a'
# and P2 has 'x'. P1 needs to delete aa and aaa and save only one character.
# Simlarly P2 needs to do this for x character.
# O(n)
# Boston Consulting group (BCG)
# ****************************************************************************
class Solution(object):
# O(n2)
def count_max_score(self, str1):
p1_score = 0
p2_score = 0
i = 0
j = 0
while(i < len(str1)):
if str1[i] == 'a':
# if i == 15:
# import pdb; pdb.set_trace()
j = i + 1
count = 0
while(j < len(str1)):
if str1[j] == 'a':
count = count + 1
else:
i = j
break
j = j + 1
if count != 0:
p1_score = p1_score + 1
# Needs to break here otherwise it will become the infinite loop.
if (j == len(str1)):
break
count = 0
if str1[i] == 'x':
j = i + 1
while(j < len(str1)):
if str1[j] == 'x':
count = count + 1
else:
i = j
break
j = j + 1
if count != 0:
p2_score = p2_score + 1
print('P1 score= {} \nP2 score= {}'.format(p1_score, p2_score))
# O(n) Here we need two flags, one for 'a' and another for 'x'.
def count_max_score_optimize(self, str1):
p1_score = 0
p2_score = 0
a_flag = 0
x_flag = 0
i = 1
while(i < len(str1)):
if str1[i] == 'a':
if str1[i-1] == 'a':
a_flag = 1
else:
p2_score = p2_score + x_flag
x_flag = 0
if str1[i] == 'x':
if str1[i-1] == 'x':
x_flag = 1
else:
p1_score = p1_score + a_flag
a_flag = 0
i = i + 1
p1_score = p1_score + a_flag
p2_score = p2_score + x_flag
print('P1 score= {} \nP2 score= {}'.format(p1_score, p2_score))
def main():
s = Solution()
s.count_max_score('axaaaxxxaxaxaaaaaaxaxaxa')
s.count_max_score_optimize('axaaaxxxaxaxaaaaaaxaxaxa')
if __name__ == '__main__':
main()
# Output:
# -------
# P1 score= 2
# P2 score= 1
# P1 score= 2
# P2 score= 1
|
c47d4fd7e60b168bdc3d528f17b56d3dc9460cf3 | dylcruz/Python_Crash_Course | /chapter 3/lists.py | 1,147 | 4.375 | 4 | bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles)
print(bicycles[0])
print(bicycles[0].title())
print(bicycles[-1]) # Returns the last element in a list
print(bicycles[-2]) # Returns second to last and so on
print()
message = 'My first bicycle was a ' + bicycles[1].title() + '.'
print(message)
print()
motorcycles = ['hona', 'yamaha', 'suzuki']
print(motorcycles)
motorcycles[0] = 'ducati' # Changes element 0 to new data
print(motorcycles)
motorcycles.append('honda') # Adding to a list
print(motorcycles)
motorcycles.insert(0, 'bmw')
print(motorcycles)
del motorcycles[-1] # Delete last element of the list
print(motorcycles)
print()
last_owned = motorcycles.pop() # Removes last item from list into a new var
print(motorcycles)
print("The last motorcycle I owned was a " + last_owned.title() + ".")
first_owned = motorcycles.pop(0)
print("The first motorcycle I owned was a " + first_owned.title() + '.')
print(motorcycles)
print()
too_expensive = 'ducati'
motorcycles.remove(too_expensive) # Removes by name rather than index
print(motorcycles) # !Removes first occurence of value!
print(too_expensive) |
7715c3801ffee655aadd929a37b42de488065e58 | hhheegunnn/Algorithm_Snippets | /Math/factorial.py | 602 | 4.03125 | 4 |
# n! = 1 * 2 * 3 * (n-1) * n
# 수학적으로 0!과 1!의 값은 1
# 반복적으로 구현한 n!
def factorial_iterative(n):
result = 1
# 1 부터 n까지의 수를 차례대로 곱하기
for i in range(1,n+1):
result *= i
return result
# 재귀적으로 구현한 n!
def factorial_recursive(n):
# n이 1 이하인 경우 1을 반환
if n <= 1:
return 1
# n! = n * (n-1)!를 그대로 코드로 작성
return n * factorial_recursive(n-1)
print("iterative 5! = ", factorial_iterative(5))
print("recursive 5! = ", factorial_recursive(5))
|
9bfeffef617948ea9c6dfb92e605450c5e19a688 | brenj/solutions | /hacker-rank/python/date-and-time/calendar_module.py | 358 | 4.1875 | 4 | # Calendar Module Challenge
"""
You are given the date of the day. Your task is to find what day it is on
that date.
"""
import calendar
WEEKDAYS = (
'MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY',
'FRIDAY', 'SATURDAY', 'SUNDAY')
month, day, year = map(int, raw_input().split())
weekday = calendar.weekday(year, month, day)
print WEEKDAYS[weekday]
|
40e232a84f1d97d6fc280c8b010a0cb501304802 | sandeepyadav10011995/Data-Structures | /Pattern-Two Heaps/4. Next Interval.py | 4,587 | 3.984375 | 4 | """
In many problems, where we are given a set of elements such that we can divide them into two parts. We are interested
in knowing the smallest element in one part and the biggest element in the other part. The Two Heaps pattern is an
efficient approach to solve such problems.As the name suggests, this pattern uses two Heaps;
Min Heap ---> smallest element
Max Heap ---> biggest element
Problem Statement: Given an array of intervals, find the next interval of each interval. In a list of intervals, for
an interval ‘i’ its next interval ‘j’ will have the smallest ‘start’ greater than or equal to the
‘end’ of ‘i’.
Write a function to return an array containing indices of the next interval of each input interval. If
there is no next interval of a given interval, return -1. It is given that none of the intervals have the
same start point.
Algo: We can utilize the Two Heaps approach. We can push all intervals into two heaps: one heap to sort the intervals
on maximum start time (let’s call it maxStartHeap) and the other on maximum end time (let’s call it maxEndHeap).
We can then iterate through all intervals of the maxEndHeap to find their next interval. Our algorithm will have
the following steps:
1. Take out the top (having highest end) interval from the maxEndHeap to find its next interval. Let’s call
this interval topEnd.
2. Find an interval in the maxStartHeap with the closest start greater than or equal to the start of topEnd
Since maxStartHeap is sorted by ‘start’ of intervals, it is easy to find the interval with the highest
‘start’. Let’s call this interval topStart.
3. Add the index of topStart in the result array as the next interval of topEnd. If we can’t find the next
interval, add ‘-1’ in the result array.
4. Put the topStart back in the maxStartHeap, as it could be the next interval of other intervals.
5. Repeat steps 1-4 until we have no intervals left in maxEndHeap.
Example 1:
Input: Intervals [[2,3], [3,4], [5,6]]
Output: [1, 2, -1]
Explanation: The next interval of [2,3] is [3,4] having index ‘1’. Similarly, the next interval of [3,4] is [5,6]
having index ‘2’. There is no next interval for [5,6] hence we have ‘-1’.
Example 2:
Input: Intervals [[3,4], [1,5], [4,6]]
Output: [2, -1, -1]
Explanation: The next interval of [3,4] is [4,6] which has index ‘2’. There is no next interval for [1,5] and [4,6].
"""
from heapq import *
class Interval:
def __init__(self, start: int, end: int) -> None:
self.start = start
self.end = end
class NextInterval:
@staticmethod
def find_next_interval(intervals: list[Interval]) -> list[int]:
n = len(intervals)
# heaps for finding the maximum start and en
max_start_heap, max_end_heap = [], []
result = [0 for _ in range(n)]
for end_index in range(n):
heappush(max_start_heap, (-intervals[end_index].start, end_index))
heappush(max_end_heap, (-intervals[end_index].end, end_index))
# go through all the intervals to find each interval's next interval
for _ in range(n):
# let's find the next interval of the interval which has the highest 'end'
top_end, end_index = heappop(max_end_heap)
result[end_index] = -1 # default to -1
if -max_start_heap[0][0] >= -top_end:
top_start, start_index = heappop(max_start_heap)
# find the the interval that has the closest 'start'
while max_start_heap and -max_start_heap[0][0] >= -top_end:
top_start, start_index = heappop(max_start_heap)
result[end_index] = start_index
# put the interval back as it could be the next interval of other intervals
heappush(max_start_heap, (top_start, start_index))
return result
def main():
ni = NextInterval()
result = ni.find_next_interval([Interval(2, 3), Interval(3, 4), Interval(5, 6)])
print("Next interval indices are: " + str(result))
result = ni.find_next_interval([Interval(3, 4), Interval(1, 5), Interval(4, 6)])
print("Next interval indices are: " + str(result))
main()
|
078b365c02fc9623cb29e1664b862e46a4d9e6dd | hector81/Aprendiendo_Python | /CursoPython/Unidad3/Ejemplos/max_int.py | 566 | 4.03125 | 4 | # max(), recibe más de un argumento, devuelve el mayor de ellos.
print("max(23, 12, 145, 88) ==> " , max(23, 12, 145, 88))
print("type(max(23, 12, 145, 88)) ==> " , type(max(23, 12, 145, 88)))
# min() tiene un comportamiento similar a max(), pero devuelve el mínimo.
print("min(23, 12, 145, 88) ==> " , min(23, 12, 145, 88))
print("type(min(23, 12, 145, 88)) ==> " , type(min(23, 12, 145, 88)))
# Con String da error
print('min(23, "12", 145, 88) ==> ' , min(23, "12", 145, 88))
print('type(min(23, "12", 145, 88)) ==> ' , type(min(23, "12", 145, 88))) |
ca2029094d00bd1eb81cc5825dc05066644e110c | ddenizakpinar/Practices | /Viral Advertising.py | 313 | 3.65625 | 4 | # https://www.hackerrank.com/challenges/strange-advertising/problem
# 28.07.2020
def viralAdvertising(n):
ans ,shared = 0, 5
ans += shared // 2
for _ in range(n-1):
shared = (shared // 2) * 3
ans += shared // 2
return ans
n = int(input())
print(viralAdvertising(n))
|
54c9d5401e05c5e41821a118ef55c9c856515a1d | Moeen-Farshbaf/assignment1-_- | /calc.py | 1,251 | 4.0625 | 4 | from math import factorial
while True:
import math
actions = ['sin','cos','sqroot','cot','tan','factorial','sum','sub','divide','multiply','expo']
ind = 1
for action in actions:
print(ind, '. ',action)
ind = ind + 1
op=int(input("Please enter the number of action from list above."))
if op==1 or op==2 or op==3 or op == 6:
a=float(input('Enter the number.'))
else:
a=float(input('Enter the first number'))
b=float(input('Enter the second number'))
if op ==7 :
result=a+b
elif op==8:
result=a-b
elif op==10 :
result=a*b
elif op ==9:
if b==0 :
result='can not divide by zero'
else:
result=a/b
elif op == 6:
result = math.factorial(a)
elif op==11:
result=a**b
elif op==3:
result=math.sqrt(a)
elif op==1:
result=math.sin(a)
elif op ==2:
result=math.cos(a)
elif op ==4:
result=math.tan(a)
elif op ==5:
result=1/math.tan(a)
else:
result='error!operator not found'
print(result)
if input("done?") == 'done':
break
|
9fcda7c855392fa0dd58eeaa6abb7b458db60bd3 | afroebel/bootcamp | /codons.py | 289 | 4.09375 | 4 | codon = input('Input your codon, please:')
codon_list = ['UAA', 'UAG', 'UGA']
codon_tuple = tuple(codon_list)
if codon == 'AUG':
print('This codon is the start codon.')
elif codon in codon_tuple:
print('This is a stop codon.')
else:
print('This codon is not the start codon.')
|
0ce4a7c6ab21abb7c6b5fde7f971ad1494c807aa | anandanubhav/python-bootcamp | /rock_paper_scissor_v3.py | 892 | 4.03125 | 4 | #rock beats scissor
#scissor beats paper
#paper beats rock
print("Rock ... Paper ... Scissors...")
from random import randint
computer_options=["rock","paper","scissor"]
random = randint(0,2)
player = input("Player, Enter your move: ")
if(player):
player = player.lower()
computer = computer_options[random]
print(f"Computer plays {computer}")
if player == computer:
print("Clash, its a tie!");
elif player == "rock":
if computer == "scissor":
print("Rock crushes scissor, Player wins!");
else:
print("Paper covers Rock, Computer wins!");
elif player == "paper":
if computer == "rock":
print("Paper covers Rock, Player wins!");
else:
print("Scissor cuts paper, Computer wins!");
elif player == "scissor":
if computer == "paper":
print("Scissor cuts paper, Player wins!");
else:
print("Rock crushes scissor, Computer wins!");
else:
print("Please enter a valid move!") |
e4aa5b8d191835821d38dbf81b38ac51b94da06c | drfiresign/pythonCollections | /zippy.py | 568 | 4.1875 | 4 | # Create a function named combo() that takes two iterables and returns
# a list of tuples. Each tuple should hold the first item in each list,
# then the second set, then the third, and so on. Assume the iterables
# will be the same length.
# combo([1, 2, 3], 'abc')
# Output:
# [(1, 'a'), (2, 'b'), (3, 'c')]
# If you use .append(), you'll want to pass it a tuple of new values.
def combo1(a, b):
return list(zip(a, b))
def combo2(a, b):
c = []
for i in range(0, len(a)):
c.append((a[i], b[i]))
return c
print(combo2([1, 2, 3], 'abc'))
|
b076539f9a69b783687a4171fb8855f2c50a57e0 | aliyahyaaamir/practice | /spiral_order.py | 1,677 | 3.71875 | 4 | """
Input:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
Output: [1,2,3,6,9,8,7,4,5]
I don't know why this question is tripping me up so much
First row, then last column, then last row, then first column
Repear process moving inwards, ok!
"""
def one_spiral(matrix: list) -> list:
matrix_len = len(matrix)
num_cols = len(matrix[0])
if matrix_len == 1 and num_cols == 1:
return [matrix[0][0]]
elif matrix_len == 1:
return matrix[0]
elif num_cols == 1:
return [matrix[i][0] for i in range(matrix_len)]
first_row = matrix[0]
last_column = [matrix[i][num_cols-1] for i in range(1, matrix_len - 1)]
last_row = matrix[matrix_len-1][::-1]
first_column = [matrix[i][0] for i in range(1, matrix_len - 1)][::-1]
return first_row + last_column + last_row + first_column
def spiral_order(matrix: list) -> list:
matrix_len = len(matrix)
# We'll consider other base cases later once we have the spiral functionality working
if matrix_len < 2:
return matrix[0]
spiral_output = []
# We should call a function that does this
spiral_matrix = [row[::] for row in matrix]
while True:
spiral = one_spiral(spiral_matrix)
spiral_output += spiral
num_cols = len(spiral_matrix[0])
num_rows = len(spiral_matrix)
spiral_matrix = [row[1: num_cols-1] for row in spiral_matrix][1: num_rows - 1]
if len(spiral_matrix) < 1 or num_cols - 2 <= 0:
break
return spiral_output
if __name__ == "__main__":
input = [[1,11],[2,12],[3,13],[4,14],[5,15],[6,16],[7,17],[8,18],[9,19],[10,20]]
spiral_output = spiral_order(input)
|
db31e6b67b01d2972b8c236f35b8747d883084d6 | sohamroy70/phy_lab | /lab2.py | 1,222 | 4.09375 | 4 | def List():
List = []
print(List)
List = ['sohamroy']
print(List)
List = ["soham", "roy", "soham"]
print(List[0])
print(List[2])
List = [['soham', 'roy'] , ['soham']]
print(List)
List = [1, 2, 4, 4, 3, 3, 3, 6, 5]
print(List)
List = [1, 2, 'Soham', 4, 'For', 6, 'Soham']
print(List)
def typ():
Tuple1 = ()
print (Tuple1)
Tuple1 = ('Soham', 'Roy')
print(Tuple1)
list1 = [1, 2, 4, 5, 6]
print(tuple(list1))
Tuple1 = ('Soham')
n = 5
for i in range(int(n)):
Tuple1 = (Tuple1,)
print(Tuple1)
Tuple1 = tuple('Soham')
print(Tuple1)
Tuple1 = (5, 'Welcome', 7, 'Soham')
print(Tuple1)
Tuple1 = (0, 1, 2, 3)
Tuple2 = ('python', 'soham')
Tuple3 = (Tuple1, Tuple2)
print(Tuple3)
Tuple1 = ('Soham',) * 3
print(Tuple1)
def set():
set1 = set()
print(set1)
set1 = set("SohamRoy")
print(set1)
String = 'SohamRoySoham'
set1 = set(String)
print(set1)
set1 = set(["Soham", "Roy", "Soham"])
print(set1)
set1 = set([1, 2, 4, 4, 3, 3, 3, 6, 5])
print(set1)
set1 = set([1, 2, 'Geeks', 4, 'For', 6, 'Geeks'])
print(set1)
set()
|
618ed28f3c21c7a14abd419e198400976904dd59 | krish5989/FilePatternCopy | /filepatterncopy.py | 1,328 | 3.78125 | 4 | #!/usr/bin/python
"""
@version: 1.0
@author: Krishnan
@summary: This python script will search files of given pattern from src dir and copy it to given destination path
"""
"""
import the necessary libraries
"""
import sys
import glob
import shutil
import argparse
""" util methods:"""
def patternsrchcopy(srcdir, dstdir, pattern='*'):
src_dir=srcdir
dest_dir=dstdir
pattern=pattern
listfiles=glob.iglob(src_dir+'/'+pattern)
#iterate the files in listfiles
for f in listfiles:
shutil.copy(f, dest_dir)
"""main program starts from here:"""
try:
parser = argparse.ArgumentParser()
parser.add_argument("-s","--src", help="provide the src folder path")
parser.add_argument("-d","--dst", help="provide the destination folder path")
parser.add_argument("-p","--pattern", help="pattern to be searched needs to be provided")
args=parser.parse_args()
if args.src:
srcdir = args.src
else:
raise Exception
if args.dst:
dstdir = args.dst
else:
raise Exception
if args.pattern:
pattern = args.pattern
else:
raise Exception
#call the pattern search method:
patternsrchcopy(srcdir,dstdir,pattern)
except Exception as msg:
print(msg)
sys.exit(0)
|
cc7aede8659c47ebc703f8a893f06b4fc108b19c | VictorCodes/PythonInventory | /program.py | 593 | 3.75 | 4 | #Code for game inventory/item list
#Sets a number to each item
iN = ['Pocket Lint', 'Dagger', 'Potion', 'Ragged Clothes']
#Sets a sell amount to each item
iNW = {'iN(0)': 0, 'iN(1)': 12, 'iN(2)': 24, 'iN(3)': 30}
#Sets a buy amount to each item
iNB = {'iN(0)': 2, 'iN(1)': 32, 'iN(2)': 35, 'iN(3)': 45}
money = 500
inventory = ['iN(1)']
#Prints what you have in your inventory and how much each item is worth wether buying or selling, and how much money you have
for key in inventory:
print key
print "Your money: " money
print "Sell: %s" % iNW[key]
print "Buy: %s" % iNB[key]
|
47e9bffcdc411a4cd28f5f4e0e4ff7c3c55d7262 | toshikish/atcoder | /abc/abc105_c.py | 301 | 3.515625 | 4 | N = int(input())
res = N
S = ''
divisor = 1
i = 0
while res != 0:
divisor *= 2
remainder = abs(res) % divisor
bit = 0 if remainder == 0 else 1
S = str(bit) + S
if i % 2 == 0:
res -= divisor * bit // 2
else:
res += divisor * bit // 2
i += 1
print(S or '0')
|
5c016803f888674a5d6c367ddc4e4de1fb2318c0 | reshma-jahir/GUVI | /reshresh6.py | 148 | 3.640625 | 4 | chx=input()
fit=0
for i in range(len(chx)):
if(chx[i].isdigit() or chx[i].isalpha() or chx[i]==(" ")):
continue
else:
fit+=1
print(fit)
|
b33de3d72e5abb71479725513f9500f176a10399 | fahadaleem/Python-Basics | /while_loop.py | 119 | 4.0625 | 4 | ## syntax of while
## while condition:
## statements
i=0
while i<=5:
print(i)
i+=1
print("Program End!") |
c16807c1771ab5d1a3ef2c119637bc11966c8a19 | Saurabh-2608/Py | /Python/Pattern3.py | 264 | 3.890625 | 4 | # Program to print triangle with nos. as in pattern 2
n = int(input(" Enter the no. of rows : "))
for i in range(n):
count = 0
for j in range(n-i):
print(" ",end="")
for k in range(n):
if(k<=i):
count = count + 1
print(count,"",end="")
print("\r") |
339be83e3bcb62298fa7b598c38dbe5f29cf325c | TUM-SCHOOL/Pachaqutec1 | /Semana_1/listas.py | 404 | 3.65625 | 4 | mi_lista = [20,3,'Alex',1.4,7]
print(mi_lista)
mi_lista.append(10)
print(mi_lista)
mi_lista.append([100,23])
print(mi_lista)
mi_lista.remove('Alex')
print(mi_lista)
l3=mi_lista.index(7)# Saca la posición del num 7
print(l3)
l1=mi_lista.pop(1) # Saca el valor de la posición 1
print(l1)
print("Hola no me caes, no avisas")
lst = [12,"hola", "ay", 23]
x = lst.pop(1)
f = f"{x} YA PUES NO LEES"
print(f) |
4e7f535c75c86e80c7b8ed0ec829f83522a09494 | HebertFB/Curso-de-Python-Mundo-1-Curso-em-Video | /Curso de Python 3 - Mundo 1 - Curso em Video/ex022.py | 499 | 4.4375 | 4 | """Crie um programa que leia o nome completo de uma pessoa e mostre:
– O nome com todas as letras maiúsculas e minúsculas.
– Quantas letras tem o nome completo sem considerar espaços.
– Quantas letras tem o primeiro nome."""
nome = input('Digite seu nome completo: ')
print(f'\nMAIÚSCULO: {nome.upper()}')
print(f'minúsculo: {nome.lower()}')
separado = nome.split()
print(f"O nome completo tem {len(''.join(separado))} letras.")
print(f'O primeiro nome tem {len(separado[0])} letras.')
|
c7e41af5b1d21975788508749e1085fafa05b1bd | GarionR/cp1404 | /Prac_03/password_check.py | 369 | 4.03125 | 4 | MINIMUM_LENGTH = 5
def main():
password = get_password()
print_password(password)
def print_password(password):
print("*" * len(password))
def get_password():
password = input("Enter password: ")
while len(password) < MINIMUM_LENGTH:
print("Invalid password")
password = input("Enter password: ")
return password
main()
|
2b4a58286af8a1cf4e10a9cd117bad981c6571e6 | Jsagisi/CST205Proj1 | /main.py | 1,290 | 3.625 | 4 | from PIL import Image
import statistics
myImage = [0] * 9
for i in range (1,10):
myImage[i - 1]=Image.open("Project1Images/%d.png" %i)
#prints the height of an image from the array and the width
print (myImage[0].height)
print (myImage[0].width)
newImage = Image.new("RGB", (myImage[0].width, myImage[0].height))
#Goes through each x and each y and when combined it goes through every pixel
#nested loop
for x in range(0, myImage[0].width):
for y in range(0, myImage[0].height):
#Sets up red and green blue list and filling them up of the values of all the pixels
#Empty out the list
redPixelList = []
greenPixelList = []
bluePixelList = []
#Goes through every image and grabs the red green and blue pixel
#and filling out the list with all the RGB values
for thisImage in myImage:
myRed, myGreen, myBlue = thisImage.getpixel((x,y))
redPixelList.append(myRed)
greenPixelList.append(myGreen)
bluePixelList.append(myBlue)
#Once you get the values you take the median and then
#you put median into the new image at that pixel location.
myTuple = (statistics.median(redPixelList),
statistics.median(greenPixelList),
statistics.median(bluePixelList))
newImage.putpixel((x, y), myTuple)
newImage.show()
#height = image[1,9].height
|
b26e6dd9349f40eb9560f9ac8a3510baa916201d | Felipe-Ferreira-Lopes/Programas-sala-aula | /codes/list4.py | 159 | 3.734375 | 4 | dicionario = {i: i ** 2 for i in range(0, 100)if i % 2 == 0}
for chave, valor in dicionario.items():
print("numero: {}, quadrado: {}".format(chave, valor)) |
9ed825d50fbd226a3a2e6a0c69f1a1f43edd73df | tammtt1/practice_git | /Task_1.py | 856 | 3.828125 | 4 | import math
class Triangle:
try:
def __init__(self,a,b,c):
self.a = a
self.b = b
self.c = c
def peremeter_triangle(self):
P=(self.a+self.b+self.c)/2
return P
def area_triangle(self):
S= math.sqrt((self.a+self.b+self.c)/2*((self.a+self.b+self.c)/2-self.a)
*((self.a+self.b+self.c)/2-self.b)*((self.a+self.b+self.c)/2-self.c))
return S
except: Exception
def main():
try:
a = int(input("Nhap canh a:"))
b= int(input("Nhap canh b: "))
c= int(input("Nhap canh c: "))
new_trangle = Triangle(a,b,c)
print("P = {}".format(new_trangle.peremeter_triangle()))
print(("S = {}".format(new_trangle.area_triangle())))
except: Exception
if __name__ == '__main__':
main()
|
6349a319d795a51bcca7695014ae538622c5378a | ArturoRuge/python-exercises | /condicionales/3-2.py | 235 | 3.625 | 4 | genero = input("masculino(M) o femenino(F)??")
edad = int(input("Edad?"))
if genero == "M":
pulsaciones = (210 - edad) / 10
else:
pulsaciones = (220 - edad) / 10
print("tus pulsaciones son " + str(pulsaciones) + " cada 10 segundos") |
e7b42b460551b6958a7b7f73edd4f0be5e6e0d8f | souradeepta/PythonPractice | /code/12-16/linear-search.py | 1,135 | 3.84375 | 4 | from typing import List, Any
def linear_search(input: List, target: Any) -> Any:
"""Linear Search with Time: O(n) and Space O(1)F"""
if not input:
return None
for index in range(len(input)):
if input[index] == target:
return index + 1
return None
if __name__ == "__main__":
input_integers = [1, 2, 3, 4]
input_integer_repeats = [2, 3, 4, 5, 1, 2]
input_strings = ["who", "what", "where"]
input_floats = [0.222, 0.44444444444444444444444444444, 0.9]
print(
f"target 2 on list {input_integers} is at {linear_search(input_integers, 2)}")
print(
f"target 2 on list {input_integer_repeats} is at {linear_search(input_integer_repeats, 2)}")
print(
f"target 'where' on list {input_strings} is at {linear_search(input_strings, 'where')}")
print(
f"target 2 on list {input_strings} is at {linear_search(input_strings, 2)}")
print(
f"target 0.9 on list {input_floats} is at {linear_search(input_floats, 0.9)}")
print(
f"target (2, 3) on list {input_integers} is at {linear_search(input_integers, (2,3))}")
|
f6911d793060950dfbd4174ff37f33bf3fdc6eec | mboker/HackerrankProblems | /CrackingCode/code/BFS.py | 1,642 | 3.65625 | 4 | from collections import defaultdict, OrderedDict
class Graph:
def __init__(self, num_nodes):
self.nodes = defaultdict(set)
self.max = num_nodes
def connect(self, node1, node2):
self.nodes[node1].add(node2)
self.nodes[node2].add(node1)
def find_all_distances(self, source_node):
distances = []
for idx in range(self.max):
dest_node = idx + 1
if dest_node != source_node:
distances.append(self.find_distance(source_node, dest_node))
print(' '.join(list(map(str, distances))))
def find_distance(self, source_node, dest_node):
searched = set()
current_node = source_node
searched.add(source_node)
searching = OrderedDict()
searching.update({node: 1 for node in self.nodes[source_node]})
searched.update(self.nodes[source_node])
while len(searching) > 0:
if dest_node in searching.keys():
return searching[dest_node] * 6
current_node = list(searching.keys())[0]
current_dist = searching.pop(current_node) + 1
searching.update({node: current_dist for node in self.nodes[current_node] if node not in searched})
searched.update(self.nodes[current_node])
return -1
file = open('../tests/BFS.txt')
t = int(file.readline())
for i in range(t):
n, m = [int(value) for value in file.readline().split()]
graph = Graph(n)
for i in range(m):
x, y = [int(x) for x in file.readline().split()]
graph.connect(x, y)
s = int(file.readline())
graph.find_all_distances(s) |
67cb89380134ff0118b2d7847a535f6b7f34abb1 | DannyM1chael/Python | /countingsort.py | 334 | 3.6875 | 4 | def countingsort(values, max_value):
counts = [0] * (max_value + 1)
for value in values:
counts[value] += 1
index = 0
for i in range(max_value + 1):
for j in range(counts[i]):
values[index] = i
index += 1
data = [8, 9, 10, 1, 0, 23, 58]
countingsort(data, 58)
print(data) |
dc08ee0ba84e81e29c9f20b23c02cd8c7859e58e | codefellows/seattle-python-401d15 | /class-30/demos/hashtable/hashtable.py | 1,449 | 3.96875 | 4 | from linked_list import LinkedList
class Hashtable:
def __init__(self, size=1024):
self._size = size
self._buckets = size * [None]
def _hash(self, key):
sum = 0
for ch in key:
sum += ord(ch)
primed = sum * 19
index = primed % self._size
return index
def set(self, key, value):
hashed_key_index = self._hash(key) # silent same as listen => 167
if not self._buckets[hashed_key_index]:
self._buckets[hashed_key_index] = LinkedList()
self._buckets[hashed_key_index].add((key, value)) # what about listen vs silent?
# listen : to me
# silent : so quiet
# both hash to 167
# self._buckets[167] contains ("to me") -> ("so quiet")
# how to "get" listen vs silent
def get(self, requesting_key):
hashed_key_index = self._hash(requesting_key) # silent same as listen => 167
bucket = self._buckets[hashed_key_index]
current = bucket.head
while current:
# if all we had was value
# to me, so quiet
#inspect each item in the bucket
# if correct item found return
pair = current.data # (key, value)
stored_key = pair[0]
stored_value = pair[1]
if stored_key == requesting_key:
return stored_value
current = current.next
|
afc2b8d18b0ea12c70f575954bda78e6ebad5f1c | erisanolasheni/contact-monitor | /monitor_app/start.py | 1,084 | 3.609375 | 4 | import argparse
import re
import sys
parser = argparse.ArgumentParser(description='Monitor app streams.')
parser.add_argument('--column',
help='an option for the table column')
parser.add_argument('--max_count',
help='an option for the maximum count')
parser.add_argument('--max_value',
help='an option for the maximum value')
args = parser.parse_args()
# print(args.column, args.max_count, args.max_value)
limit_count = 0
max_count = int(args.max_count)
max_value = int(args.max_value)
columns = int(args.column)
while True:
input_val = str(input()).strip()
# first remove unnecessary spaces
input_val = re.sub(r'\W+', ' ',input_val)
# split to arrays to get the number of columns
input_val_arr = input_val.split(' ')
try:
# check if the value has passed the max_value
if int(input_val_arr[columns-1]) > max_value:
limit_count += 1
if limit_count > max_count:
print('Gone out!!!')
limit_count = 0
except:
pass
|
29a4ff314e787f7e57c3828eb9400b11f0ccec2c | GraceDurham/coding_challenges_coding_bat | /sum67.py | 886 | 3.671875 | 4 |
def sum67(nums):
""" Return the sum of the numbers in the array, except ignore
sections of numbers starting with a 6 and extending to the
next 7 (every 6 will be followed by at least one 7). Return 0
for no numbers."""
skip = False
sums = 0
for num in nums:
if (num == 6):
skip = True
continue
if (num == 7 and skip is True):
skip = False
continue
if (skip is False):
sums = sums + num
return sums
print(sum67([1,2,2]))
print(sum67([1, 2, 2, 6, 99, 99, 7]))
print(sum67([1, 1, 6, 7, 2]))
print(sum67([1,6,2,2,7,1,6,99,99,7]))
print(sum67([1,6,2,6,2,7,1,6,99,99,7]))
print(sum67([2,7,6,2,6,7,2,7]))
print(sum67([2,7,6,2,6,2,7]))
print(sum67([1,6,7,7]))
print(sum67([6,7,1,6,7,7]))
print(sum67([6,8,1,6,7]))
print(sum67([]))
print(sum67([6,7,11]))
print(sum67([11,6,7,11]))
print(sum67([2,2,6,7,7])) |
b001bf2573cc7511812a075b67a52ec304c29559 | mageshwarant/Sample-Progs | /Dummy.py | 1,163 | 3.59375 | 4 |
#
#i = 0
#j = 1
#print(0)
#print(1)
#n=10
#for k in range(1,n-1):
# sum =i+j
# i=j
# j= sum
# print(sum,"\t")
# # k=k+1
# import math
# def primeFactors(n):
# # Print the number of two's that divide n
# while n % 2 == 0:
# print(2),
# n = n / 2
# # n must be odd at this point
# # so a skip of 2 ( i = i + 2) can be used
# for i in range(3,int(math.sqrt(n))+1,2):
# # while i divides n , print i ad divide n
# while n % i== 0:
# print(i),
# n = n / i
# # Condition if n is a prime
# # number greater than 2
# if n > 2:
# print(n)
# n =30
# primeFactors(n)
##def add(add1,add2):
## sum = add1+add2
## return sum
#def add(*args):
# sum =0
# for i in args:
# sum = sum+i
# return sum
#
#sum =add(1,1,1,1,1,1,1,1,1)
#print(sum)
#
#import math
#print(math.factorial(5))
#
##from functools import reduce
##lister =[1,2,3,4,5,6,7,8,9,10]
##
##x= filter(lambda x:x%2==0 , lister)
##
##print()
#
#import glob
#
#x= glob.glob("E:\\Magesh\\Camera\\*.jpg")
#
#print(len(x))
|
3f89e7f825f07fef75c5e521e375ea2b0e2e2f85 | CleitonFurst/Exercicios_Python_Blue | /Exercicios_para_entregar/Exercicio_06.py | 1,736 | 4.25 | 4 | # 06 - Utilizando listas faça um programa que faça 5 perguntas para uma pessoa sobre um crime. As perguntas são:
# "Telefonou para a vítima?"
# "Esteve no local do crime?"
# "Mora perto da vítima?"
# "Devia para a vítima?"
# "Já trabalhou com a vítima?"
# O programa deve no final emitir uma classificação sobre a participação da pessoa no crime.
# Se a pessoa responder positivamente a 2 questões ela deve ser classificada como "Suspeita",
# Entre 3 e 4 como "Cúmplice" e 5 como "Assassino".
# Caso contrário, ele será classificado como "Inocente".
#declaração de uma lista com as perguntas
perguntas = ['Telefonou para a vítima?',
'Esteve no local do crime?',
'Mora perto da vítima?',
'Devia para a vítima?',
'Já trabalhou com a vítima?']
# declarando o contador
cont = 0
#declarando o laço de repetição for para percorrer a litas de perguntas
for i in perguntas:
#perguntando ao usuario utilizando strip, upper e [0] para filtras a string digitada e garantir que retorne apenas S ou N
resposta = str(input(f'{i} (S/N):').strip().upper()[0])
#validando a condição se for S
if resposta == 'S':
#contando quantas respostas foram S
cont += 1
else:
#para apenas continuar o programa
continue
#condicionais para vereficar quantas respostas foram sim e imprimier o resultado de cada caso
if cont == 2:
print('2 respostas foram sim pessoa considerada Suspeita !!!')
elif cont == 3 or cont == 4:
print(f'{cont} resposatas sim pessoa considerada Cúmplice !!!')
elif cont == 5:
print('5 Respostas sim pessoa considerada Assassina> Você esta preso!!!!')
else:
print('Pessoa inocente !!!') |
095ff133bd0633b7f2554f9592a1b721bb21158e | jeremiedecock/snippets | /python/scipy/discrete_random_with_distribution.py | 1,160 | 3.875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# see http://stackoverflow.com/questions/11373192/generating-discrete-random-variables-with-specified-weights-using-scipy-or-numpy
import numpy as np
from scipy.stats import rv_discrete
# IF VALUES ARE INTEGERS ########################
values = [1, 2, 3]
probabilities = [0.2, 0.5, 0.3]
num_samples = 1000
# A Scipy probability distribution
distrib = rv_discrete(values=(values, probabilities))
# One sample
value = distrib.rvs()
print("value =", value)
# Multiple samples
values = distrib.rvs(size=num_samples)
print(values)
print("Percentage of 1:", float(values.tolist().count(1)) / num_samples)
print("Percentage of 2:", float(values.tolist().count(2)) / num_samples)
print("Percentage of 3:", float(values.tolist().count(3)) / num_samples)
# IF VALUES ARE FLOATS ##########################
print()
values = np.array([1.1, 2.2, 3.3])
probabilities = [0.2, 0.5, 0.3]
# A Scipy probability distribution (values have to be integers)
distrib = rv_discrete(values=(range(len(values)), probabilities))
# Samples
indexes = distrib.rvs(size=100)
print(indexes)
print(values[indexes])
|
122e8d8c83d347b1215525f0349a3621cee23f61 | SagittariuX/Interview_Ex | /LeetCodePython/CountNumberOfTeams.py | 680 | 3.828125 | 4 | # https://leetcode.com/problems/count-number-of-teams/
def count_teams(rating):
"""
:type rating: List[int]
:rtype: int
"""
leng = len(rating)
great = [0] * leng
less = [0] * leng
for i in range(leng-1):
for j in range(i+1, leng):
if rating[i] > rating[j]:
great[i] += 1
elif rating[i] < rating[j]:
less[i] += 1
res = 0
for i in range(leng-2):
for j in range(i+1, leng):
if rating[i] < rating[j]:
res += less[j]
elif rating[i] > rating[j]:
res += great[j]
return res
print(count_teams([2,1,3])) |
05c201c692b5b7100d12ce01ae709683abb58a7d | Schnikonos/pythonSandbox | /module/tests/test_mock.py | 705 | 3.703125 | 4 | from unittest import TestCase
from unittest.mock import Mock
class ComplexClass:
def do_stuff(self, name: str, age: int) -> str:
return '{} {}'.format(name, age)
class Person:
def __init__(self, name: str, age: int):
self.name = name
self.age = age
def my_function(self) -> str:
return ComplexClass().do_stuff(self.name, self.age)
class TestWithMock(TestCase):
def test_mock_do_stuff(self):
ComplexClass.do_stuff = Mock(return_value='this is mocked !')
person = Person('john', 24)
res = person.my_function()
self.assertEqual('this is mocked !', res)
ComplexClass.do_stuff.assert_called_once_with('john', 24)
|
08330146e994f6d55272b41892f22d932e013014 | VamsiKumarK/Practice | /_00_Assignment_Programs/_02_Functions/_03_Factorial.py | 555 | 4.125 | 4 | '''
Created on Nov 20, 2019
@author: Vamsi
'''
'''
finding factorial of a given number using while loop
'''
num = 5
def factorial(n):
num = 1
while n >= 1:
num = num * n
n = n - 1
return num
print('The factorial of given number: ', factorial(num))
print("__________________________________________________")
'''
using recursive
'''
def fact(num1):
if num1 == 0 or num1 == 1:
return 1
else:
num1 = num1 * factorial(num1 - 1)
return num1
print('The factorial of given number: ', fact(5))
|
640b8d1916a60242ff77bd57aa105e11fbd39c22 | ResolveWang/algorithm_qa | /basic_algrithms/sort_algrithms/heap_sort.py | 2,550 | 3.671875 | 4 | """
堆排序.
(1)堆排序的常数项比较大,适用于大型数组排序。
(2)时间复杂度是O(Nlog(N)),空间复杂度是O(1)。
(3)堆排序是不稳定的排序。
"""
from basic_algrithms.sort_algrithms.benchmark import Comparator
class HeapSort:
@classmethod
def heap_sort(cls, arr):
if not arr or len(arr) < 2:
return arr
cls.heap_sort_detail(arr)
@classmethod
def heap_sort_detail(cls, arr):
# 建立大顶堆,这里会遍历所有元素,不用担心左右孩子有会漏掉的情况
# heap_insert的时间复杂度是O(log(N)),log(1)+log(2)+...+log(N)在N收敛
# 所以时间复杂度是N
size = len(arr)
for i in range(size):
cls.heap_insert(arr, i)
size -= 1
# 交换第一个和最后一个元素,因为是大顶堆,所以交换后,最后一个元素是最大的
arr[0], arr[size] = arr[size], arr[0]
# 交换后需要调整堆
while size > 0:
cls.heapify(arr, 0, size)
size -= 1
arr[0], arr[size] = arr[size], arr[0]
@classmethod
def heap_insert(cls, arr, index):
# 这里不能用位运算,即index - 1 >> 1,因为当index=0的时候,index-1>>1 的结果是-1,而不是0
# int((index-1)/2)可以保证小数向零取整
while arr[index] > arr[int((index-1) / 2)]:
arr[index], arr[int((index-1) / 2)] = arr[int((index-1) / 2)], arr[index]
index = int((index-1) / 2)
@classmethod
def heapify(cls, arr, index, size):
left = index * 2 + 1
while left < size:
if left + 1 < size and arr[left] < arr[left+1]:
largest = left + 1
else:
largest = left
largest = index if arr[largest] <= arr[index] else largest
if largest == index:
break
arr[index], arr[largest] = arr[largest], arr[index]
index = largest
left = 2 * index + 1
if __name__ == '__main__':
max_times = 1000
max_size = 100
max_value = 100
res = True
for _ in range(max_times):
arr1 = Comparator.gen_random_array(max_size, max_value)
arr2 = Comparator.copy_arr(arr1)
HeapSort.heap_sort(arr1)
sorted_arr2 = sorted(arr2)
if not Comparator.is_equal(arr1, sorted_arr2):
res = False
break
if not res:
print('Failed ')
else:
print('Success') |
6a8ce3963550964c0e116dd65a286d41ee6b7509 | jugshaurya/Learn-Python | /2-Programs-including-Datastructure-Python/7 - Binary Tree/BinaryTree.py | 3,283 | 3.65625 | 4 | from BTNode import BinaryTreeNode
def printTree_preorder(root):
if root==None:
return
print(root.data, ' : ', end = '')
if root.left != None:
print('L' , root.left.data, end = ',')
if root.right != None:
print('R' , root.right.data, end = ' ')
print()
printTree_preorder(root.left)
printTree_preorder(root.right)
def printTree_postorder(root):
if root == None:
return
printTree_postorder(root.left)
printTree_postorder(root.right)
print(root.data)
def printTree_inorder(root):
if root == None:
return
printTree_postorder(root.left)
print(root.data)
printTree_postorder(root.right)
def buildTree():
# li = [int(x) for x in input().split()] # given input in a line only, data is seperated by space
root = None
node1 = BinaryTreeNode(1)
node2 = BinaryTreeNode(2)
node3 = BinaryTreeNode(3)
node4 = BinaryTreeNode(4)
node5 = BinaryTreeNode(5)
node1.left = node2
node1.right = node3
node2.left = node4
node2.right = node5
root = node1
return root
def userBuiltTree():
rootData = int(input())
# -1 is used to stop continuing over the current branch - so taking input in depth-first Style
if rootData == -1:
return None
root = BinaryTreeNode(rootData)
root.left = userBuiltTree()
root.right = userBuiltTree()
return root
def nodesInTree(root):
if root is None:
return 0
leftCount = nodesInTree(root.left)
rightCount = nodesInTree(root.right)
return 1 + leftCount + rightCount
def largest_node(root):
if root==None:
return -2**31 # returing -inf
leftMax = largest_node(root.left)
rightMax = largest_node(root.right)
rootData = root.data
return max(rootData, leftMax,rightMax)
def nodes_gt_x(root,x):
if root==None:
return
nodes_gt_x(root.left,x)
nodes_gt_x(root.right,x)
if root.data > x:
print(root.data)
def sumOfAllNodes(root):
if root==None :
return 0
leftSum = sumOfAllNodes(root.left)
rightSum = sumOfAllNodes(root.right)
return root.data + leftSum + rightSum
def treeHeight(root):
if root is None:
return 0
leftHeight = treeHeight(root.left)
rightHeight = treeHeight(root.right)
return 1+ max(leftHeight, rightHeight)
def numberOfLeaveNodes(root):
if root is None:
return 0
leftans = numberOfLeaveNodes(root.left)
rightans = numberOfLeaveNodes(root.right)
result = leftans + rightans
if result == 0 :
result+=1
return result
print('Enter the data of tree : ')
# Given input: 1 2 4 -1 -1 5 -1 -1 3 -1 7 -1 -1
root = userBuiltTree()
print('Preorder Print : ')
printTree_preorder(root)
print('Numbers of Nodes are : ', nodesInTree(root))
print('Postorder Print : ')
printTree_postorder(root)
print('Inorder Print : ')
printTree_inorder(root)
print('Max Node Data is : ', largest_node(root) )
print('Sum of All nodes is : ', sumOfAllNodes(root))
print('Height of tree is : ', treeHeight(root))
print('Number of leaves nodes are : ', numberOfLeaveNodes(root))
x=int(input('Enter x '))
print('Values greater than %d are : '%x)
nodes_gt_x(root,x)
|
ea5384605b2fd02fcf8f8ed4b268230a578a21d3 | nikhillondhe9/CS6112017 | /PythonExercise/exercise6d.py | 313 | 3.765625 | 4 | def find_n_primes(N):
prime_list = []
n = 2
while len(prime_list) < N:
prime_test = []
for i in prime_list:
if n % i == 0:
prime_test.append(i)
prime_list += [] if prime_test else [n]
n += 1
return prime_list
print(find_n_primes(10))
|
46fe1e54a0874dc389c46e01425dd9a06c94cac5 | onigoetz/halloween-jagerbomber | /halloween.py | 1,513 | 3.65625 | 4 | #!/usr/bin/python
import time
import datetime
from Adafruit_7Segment import SevenSegment
# ===========================================================================
# Countdown
# ===========================================================================
segment = SevenSegment(address=0x70)
print "Press CTRL+Z to exit"
countdown = 60 * 20 # 20 minutes
ticks = 12
current = countdown
current_tick = ticks
# Continually update the time on a 4 char, 7-segment display
while(True):
# if there is no blinkin 0 and the time is up
# return to the start
if (current == 0 and current_tick == 0):
current = countdown
current_tick = ticks
# When the countdown is a 0, blink between zeros and eights
if (current == 0 and current_tick % 2):
minute = 88
second = 88
# or simply show the time
else:
minute = current / 60
second = current % 60
# Set minutes
segment.writeDigit(0, int(minute / 10)) # Tens
segment.writeDigit(1, minute % 10) # Ones
# Set seconds
segment.writeDigit(3, int(second / 10)) # Tens
segment.writeDigit(4, second % 10) # Ones
# Toggle colon
segment.setColon(second % 2) # Toggle colon at 1Hz
# while the countdown is still
# running, decrement and wait 1 sec
if (current > 0):
current -= 1
time.sleep(1)
# when the countdown is done, decrement ticks
# but sleep only .2 secs
else:
current_tick -= 1
time.sleep(.2)
|
8c6819be41e711f7ee6193d691334caf218fc6c4 | allanlealluz/Python-First-tests | /ex076.py | 443 | 3.53125 | 4 | listagem = ('Pão',1,'Leitinho',1.99,'Frango',10.50)
c = 0
print('-------------------\nListagem de Preços\n-------------------')
while c < len(listagem):
if(c == 0):
print(f'{listagem[c]:.<20}R${listagem[c+1]}')
elif(c == 2):
print(f'{listagem[c]:.<20}R${listagem[c+1]}')
elif (c == 4):
print(f'{listagem[c]:.<20}R${listagem[c + 1]}')
elif (c == 5):
print(f'{listagem[c-1]:.<20}R${listagem[c]}')
c += 1 |
a585123c4912e0a2b0cc7ee825fd25012f6355d2 | SRFowler/project-euler-python | /solutions/problem_4.py | 1,494 | 4.3125 | 4 | """ Largest palindrome product
Show HTML problem content
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
ANSWER: 906609
"""
# Get all 3 digit numbers
def get_values():
arr = []
for i in range(100, 1000):
arr.append(i)
return arr
# Determine if a number is a palindrome
def is_palindrome(value):
return str(value) == str(value)[::-1]
# Get the product of all pairs in a list
def get_all_products(input_numbers):
products = []
while len(input_numbers) > 1:
for number in input_numbers:
products.append(input_numbers[0] * number)
del input_numbers[0]
return products
# Get the largest palindrome
def get_largest_palindrome(products):
# Reverse sort the products list so we start with the largest number
# We can return the first palindrome because it will be the largest too
products.sort(reverse = True)
for i in products:
if is_palindrome(i):
return i
""" EXTRA BONUS::
Get all of the palindromes!
"""
def get_all_palindromes(numbers):
palindromes = []
numbers.sort()
for value in numbers:
if is_palindrome(value):
palindromes.append(value)
return palindromes
#print(get_all_palindromes(get_all_products(get_values())))
print(get_largest_palindrome(get_all_products(get_values()))) |
058cefeaa4f7eedaaa4abbb69cf22079520ca614 | Martin-Ruggeri-Bio/lab | /alumnos/58003-Martin-Ruggeri/socket/servidores/servidor.py | 940 | 3.609375 | 4 | import socket
#esta funcion va a jenerar un nuevo socket con los valores por default
mi_socket = socket.socket()
#voy a establecer la conexion
#el primer valor sera el host, y el segundo en que puerto estara escuchando el socket
mi_socket.bind(('localhost', 8000))
# vamos a establecer la cantidad de peticiones que puede manejar nuestro socket en cola
mi_socket.listen(5)
while True:
# vamos a aceptar las peticiones del cliente
# nos va a retornar 2 valores (la conexion y la direccion)
conexion, addr = mi_socket.accept()
print("Nueva conexion establecida")
print(f"la direccion de la cual se ha hecho la peticion", addr)
# obtenemos lo que el cliente nos esta enviando
peticion = conexion.recv(1024)
print(peticion)
#vamos a enviar un mensaje al cliente
conexion.send(bytes("Hola, te saludo desde el servidor", encoding = "utf-8"))
#cerramos la conexion con el cliente
conexion.close()
|
7cb06e9a8d3a96fc4e76a63edb4270ef7c28bf6f | chenlifeng283/learning_python | /5-Dates/date_functions.py | 477 | 4.21875 | 4 | # To get current date and time you need to use the datetime library
from datetime import datetiem, timedelta
# The now function returns the current date and time
today = datetime.now()
print('Today is:' + str(today))
# You can use timedelta add or remove days, or weeks to a date
one_day = timedelta(days=1)
yestoday = today - one_day
print('Yestoday was:' + str(yestoday))
one_week = timedelta(weeks=1)
last_week = today - one_week
print('Last week was:' + str(last_week))
|
147e5f84784470d5e12b9c7d9243afd72df643dd | zero0011/-offer | /基本数字运算/一个数的n次方/index.py | 480 | 4.15625 | 4 | '''
计算一个数的 n 次方
给定一个数 d 和 n , 如何计算 d 的 n 次方? 例如: d = 2 , n =3 的 n c次方位 为 8
'''
# 说白了 , 就是实现 Math.pow()
def power (d , n):
if n == 0: return 1
if n == 1: return d
res = 1
if n > 0:
i = 1
while (i <= n):
res *= d
i+=1
return res
else:
i = 1
while i <= abs(n):
res = res / d
i+=1
return res
|
21b5a5dd2a92917e3585c0bba2fcb77ea6e66376 | Sgt-Forge/Coursera-ML-Python | /machine-learning-ex2/main.py | 7,672 | 4.09375 | 4 | """ Programming exercise two for Coursera's machine learning course.
Run main.py to see output for Week 3's programming exercise #2
"""
import os
import numpy as np
from matplotlib import pyplot
from mpl_toolkits.mplot3d import Axes3D
from typing import List
from scipy import optimize
from sigmoid import sigmoid
from logistic_cost import cost_function
from regularized_cost_function import regularized_cost_function
def print_section_header(section: str) -> None:
"""Prints a section header to STDOUT
Args:
section: Name of the section to print
Returns:
None
"""
spacing = 50
blank_space = ' ' * ((spacing - len(section)) // 2 - 1)
print('='*spacing)
print('{}{}'.format(blank_space, section))
print('='*spacing)
def visualize(X: List[List[float]], y: List[int]) -> None:
"""Plot data.
Generates scatter plot
Args:
X: A matrix of scores for exams 1 and 2 for each student
y: Binary vector to track admittance for each student
Returns:
None
"""
pos = y == 1
neg = y == 0
_fig = pyplot.figure()
pyplot.plot(X[pos, 0], X[pos, 1], 'k+', lw=2, ms=10)
pyplot.plot(X[neg, 0], X[neg, 1], 'ko', mfc='y', ms=8, mec='k', mew=1)
pyplot.xlabel('Exam Score 1')
pyplot.ylabel('Exam Score 2')
pyplot.legend(['Admitted', 'Rejected'])
def optimize_theta(cost_function, initial_theta, X, y,
options={'maxiter': 400}):
"""Optimize theta parameters using a cost function and initial theta
Args:
cost_function: Cost function used to calculate error
initial_theta: Starting values for theta parameters
X: Input features
y: Labels for training set
Returns:
"""
res = optimize.minimize(cost_function,
initial_theta,
(X, y),
jac=True,
method='TNC',
options=options)
return res
def plot_decision_boundary(theta, X, y):
"""Plot data and draw decision boundary with given theta parameters.
Generates scatter plot with decision boundary.
Args:
visualize: Plotting function to create a scatter plot
theta: Theta parameters for the decision boundary
X: A matrix of scores for exams 1 and 2 for each student
y: Binary vector to track admittance for each student
Returns:
None
"""
visualize(X[:, 1:3], y)
'''
If you want to figure out _how_ to plot the decision boundary, you have to
understand the following links:
https://statinfer.com/203-5-2-decision-boundary-logistic-regression/
https://en.wikipedia.org/wiki/Logistic_regression
Basically we have to plot the line when our probability is 0.5. You can
recover the theta paremeters from the equation by calculating the odds of
classifying 0.5 (yes, the literal definition of odds: {p / 1-p} )
'''
X_points = np.array([np.min(X[:, 1]), np.max(X[:, 1])])
y_points = (-1 / theta[2]) * (theta[1] * X_points + theta[0])
pyplot.plot(X_points, y_points)
def predict(theta, X):
"""Make predictions for test set with trained theta parameters
Args:
theta: Trained theta parameters
X: Test set
Returns:
array-like of predictions
"""
predictions = sigmoid(X.dot(theta)) >= 0.5
return predictions
def map_features(X1, X2):
"""Maps two features to a 6 degree polynomial feature set
Args:
X: initial feature set without bias feature
Returns:
Mapped feature set with added bias feature
"""
degree = 6
if X1.ndim > 0:
mapped_features = [np.ones(X1.shape[0])]
else:
mapped_features = [(np.ones(1))]
for i in range(1, degree + 1):
for j in range(i + 1):
mapped_features.append((X1 ** (i - j)) * (X2 ** j))
if X1.ndim > 0:
return np.stack(mapped_features, axis=1)
else:
return np.array(mapped_features, dtype=object)
def plot_non_linear_boundary(theta, X, y):
visualize(X, y)
u = np.linspace(-1, 1.5, 50)
v = np.linspace(-1, 1.5, 50)
z = np.zeros((u.size, v.size))
for i, ui in enumerate(u):
for j, vj in enumerate(v):
z[i, j] = np.dot(map_features(ui, vj), theta)
z = z.T
pyplot.contour(u, v, z, levels=[0], linewidths=2, colors='g')
pyplot.contourf(u, v, z, levels=[np.min(z), 0, np.max(z)], cmap='Greens',
alpha=0.4)
def part_one():
"""Driver function for part one of the exercise
Visualize the data, compute cost and gradient and learn optimal theta
paramaters
Returns:
None
"""
print_section_header('Section 1')
data = np.loadtxt(os.path.join('data/ex2data1.txt'), delimiter=',')
X, y = data[:, 0:2], data[:, 2]
visualize(X, y)
pyplot.show()
m = y.size
X = np.concatenate([np.ones((m, 1)), X], axis=1)
theta = np.array([-24, 0.2, 0.2])
cost, gradient = cost_function(theta, X, y)
print("Cost:\n\t{:.3f}".format(cost))
print("Gradient:\n\t{:.3f}, {:.3f}, {:.3f}".format(*gradient))
optimized = optimize_theta(cost_function, theta, X, y)
optimized_cost = optimized.fun
optimized_theta = optimized.x
print('Optimized cost:\n\t{:.3f}'.format(optimized_cost))
print('Optimized theta:\n\t{:.3f}, {:.3f}, {:.3f}'.
format(*optimized_theta))
plot_decision_boundary(optimized_theta, X, y)
pyplot.show()
test_scores = np.array([1, 45, 85])
probability = sigmoid(test_scores.dot(optimized_theta))
print('Probability for student with scores 45 and 85:\n\t{:.3f}'.
format(probability))
print('Expected value: 0.775 +/- 0.002')
predictions = predict(optimized_theta, X)
print('Training accuracy:\n\t{:.3f}'.
format(np.mean(predictions == y) * 100))
print('Expected accuracy: 89.00%')
def part_two():
"""Driver function for part two of the exercise
Visualize the data, compute regularized cost and gradient, and learn
optimal theta parameters
Returns:
None
"""
print_section_header('Section 2')
data = np.loadtxt(os.path.join('data/ex2data2.txt'), delimiter=',')
X, y = data[:, 0:2], data[:, 2]
visualize(X, y)
pyplot.show()
X_mapped = map_features(X[:, 0], X[:, 1])
m = y.size
theta = np.zeros(X_mapped.shape[1])
cost, gradient = regularized_cost_function(theta, X_mapped, y, 1)
print("Cost:\n\t{:.3f}".format(cost))
print('Gradient:\n\t{:.4f}, {:.4f}, {:.4f}, {:.4f}, {:.4f}'.
format(*gradient))
theta = np.ones(X_mapped.shape[1])
cost, gradient = regularized_cost_function(theta, X_mapped, y, 10)
print('Set initial thetas to 1, and lambda to 10')
print("Cost:\n\t{:.3f}".format(cost))
print('Gradient:\n\t{:.4f}, {:.4f}, {:.4f}, {:.4f}, {:.4f}'.
format(*gradient))
optimized = optimize_theta(cost_function, theta, X_mapped, y,
options={'maxiter': 100})
optimized_cost = optimized.fun
optimized_theta = optimized.x
plot_non_linear_boundary(optimized_theta, X, y)
pyplot.show()
def main():
"""Main driver function.
Runs the sections for programming exercise two
Returns:
None
"""
part_one()
part_two()
if __name__ == '__main__':
main()
|
e1682fa971e858a5b8d8bc95d2517977460a9964 | Hani1-2/All-codes | /oop practices sem2/exceptions.py | 1,598 | 4.0625 | 4 | ###Slide 10
##
##amount=int(input('Enter amount to be shared: '))
##sharers=int(input('Enter number of sharers: '))
##print('Each one will get Rs. ',amount/sharers)
##print('Have a blessed day')
###Slide 11
##
##try:
## amount=int(input('Enter amount to be shared: '))
## sharers=int(input('Enter number of sharers: '))
## print('Each one will get Rs. ',amount/sharers)
##except:
## print('Enter inputs in digits!')
##print('Have a blessed day')
###Slide 12
##
##try:
## amount=int(input('Enter amount to be shared: '))
## sharers=int(input('Enter number of sharers: '))
## print('Each one will get Rs. ',amount/sharers)
##except ValueError:
## print('Enter inputs in digits!')
##except ZeroDivisionError:
## print('Number of sharers must be >=1')
##print('Have a blessed day')
###Slide 13
##
##try:
## amount=int(input('Enter amount to be shared: '))
## sharers=int(input('Enter number of sharers: '))
## print('Each one will get Rs. ',amount/sharers)
##except ValueError:
## print('Enter inputs in digits!')
##except ZeroDivisionError:
## print('Number of sharers must be >=1')
##except:
## print('Something went wrong!')
##print('Have a blessed day')
###Slide 14
##
try:
amount=int(input('Enter amount to be shared: '))
sharers=int(input('Enter number of sharers: '))
print('Each one will get Rs. ',amount/sharers)
except ValueError as e:
print('Problem with value:',type(e),e)
except ZeroDivisionError as e:
print('Problem with value:',type(e),e)
except:
print('Cannot identify the problem')
print('Have a blessed day') |
ca560f0349adfb407c4e17222d510367d1551ee6 | arturrossi/formais | /arquivo.py | 1,509 | 3.8125 | 4 | def extrai_listas_linha1(string, lista_original):
linha1 = string[0]
quant = 0
for indice in range(0, len(linha1)): #passa sobre os caracteres da primeira linha ate achar '{', onde começam as informações do automato
if linha1[indice] == '{':
comeco = indice + 1
quant += 1
while linha1[indice] != '}':
indice = indice + 1
lista_original.append(list(linha1[comeco:indice].split(",")))
if quant == 2:
estado_inicial = list(linha1[indice + 2:indice + 4].split(" "))
lista_original.append(estado_inicial)
return lista_original
def extrai_listas_transicoes(linha):
lista_final = []
for indice in range(2, len(linha)):
i = 1
tamanho = len(linha[indice])
while linha[indice][i] != ")":
i += 1
lista = list(linha[indice][1:i].split(",")) # pega as informações de dentro da transição sem os parentesis e a virgula. (q0,a) fica 'q0', 'a'
j = i + 2 #se o i para um caractere antes do ")", e após isso há um "=", como por exemplo "(q0,a)=q1", entao deve-se pular 2 caracteres para chegar no estado de destino
estado_destino_transicao = linha[indice][j:tamanho]
lista.append(estado_destino_transicao)
lista_final.append(lista)
return lista_final
def extrai_palavras(reader):
lista_palavras = []
for coluna in reader:
lista_palavras.append(coluna)
return lista_palavras |
110f2e62806fd5cdaec6d61d5c59861faed67840 | ratnania/splitri | /splitri/utils/triangle.py | 503 | 3.640625 | 4 | # -*- coding: UTF-8 -*-
import numpy as np
import numpy.linalg as la
# ...
def barycentric_coords(vertices, point):
"""
computes the barycentric coordinates of the point (2d) with respect to the
triangle defined by vertices
returns a 2d array
the 3rd component is given by 1-v.sum()
"""
T = (np.array(vertices[:-1])-vertices[-1]).T
v = np.dot(la.inv(T), np.array(point)-vertices[-1])
# v.resize(len(vertices))
# v[-1] = 1-v.sum()
# print v
return v
# ...
|
9960f81d3e549d700ff78c39dfb9b06097c6fb55 | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_75/593.py | 2,126 | 3.578125 | 4 | #!/usr/bin/python2.6
import re
from itertools import chain
class Element():
def __init__(self, name):
self.opposing = set()
self.combining = {}
self.name = name
def addOpposingElement(self, element):
self.opposing.add(element)
def addCombiningElement(self, element, result):
self.combining[element] = result
class ElementList():
def __init__(self):
self.lst = []
def add(self, element):
for combiningElement, result in element.combining.iteritems():
if len(self.lst) > 0 and self.lst[-1] == combiningElement:
self.lst[-1] = result
return
for key in element.opposing:
if key in self.lst:
self.lst = []
return
self.lst.append(element)
def getList(self):
out = []
for element in self.lst:
out.append(element.name)
return out
def solve(combinationsCount, combinations, oppositionsCount, oppositions, conjuresCount, conjures):
allElements = dict()
for letter in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":
allElements[letter] = Element(letter)
lst = ElementList()
i = 0
while i < combinationsCount:
combination = combinations[i]
allElements[combination[0]].addCombiningElement(allElements[combination[1]], allElements[combination[2]])
allElements[combination[1]].addCombiningElement(allElements[combination[0]], allElements[combination[2]])
i += 1
i = 0
while i < oppositionsCount:
opposition = oppositions[i]
allElements[opposition[0]].addOpposingElement(allElements[opposition[1]])
allElements[opposition[1]].addOpposingElement(allElements[opposition[0]])
i += 1
i = 0
while i < conjuresCount:
lst.add(allElements[conjures[i]])
i += 1
return lst.getList()
def flatten(zippedList):
return [item for pair in zippedList for item in pair]
if __name__ == "__main__":
lineCount = input()
i = 0
outputs = []
while i < lineCount:
line = raw_input()
data = flatten(re.findall("([0-9]+) ([^0-9]*)", line))
output = solve(int(data[0]), data[1].split(' '), int(data[2]), data[3].split(' '), int(data[4]), data[5])
outputs.append(output)
i += 1
for i, output in enumerate(outputs):
print "Case #%i: %s" % (i + 1, repr(output).replace("'", ""))
|
5c9994702670477b1a7e2b1c2bed7e732ed41ee6 | pylangstudy/201708 | /03/03/rjust.py | 1,076 | 3.6875 | 4 | s = b'abc'; print(b'>' + s.rjust(8) + b'<')
s = b'abc'; print(b'>' + s.rjust(8, b'-') + b'<')
s = b'abc'; print(b'>' + s.rjust(8) + b'<')
s = b'abc'; print(b'>' + s.rjust(8, b'-') + b'<')
s = b'abc'; print(b'>' + s.center(8) + b'<')
s = b'abc'; print(b'>' + s.center(8, b'-') + b'<')
s = b'abc'; print(b'>' + s.center(2) + b'<')
s = b'abc'; print(b'>' + s.center(2, b'-') + b'<')
s = bytearray(b'abc'); print(bytearray(b'>') + s.rjust(8) + bytearray(b'<'))
s = bytearray(b'abc'); print(bytearray(b'>') + s.rjust(8, bytearray(b'-')) + bytearray(b'<'))
s = bytearray(b'abc'); print(bytearray(b'>') + s.rjust(8) + bytearray(b'<'))
s = bytearray(b'abc'); print(bytearray(b'>') + s.rjust(8, bytearray(b'-')) + bytearray(b'<'))
s = bytearray(b'abc'); print(bytearray(b'>') + s.center(8) + bytearray(b'<'))
s = bytearray(b'abc'); print(bytearray(b'>') + s.center(8, bytearray(b'-')) + bytearray(b'<'))
s = bytearray(b'abc'); print(bytearray(b'>') + s.center(2) + bytearray(b'<'))
s = bytearray(b'abc'); print(bytearray(b'>') + s.center(2, bytearray(b'-')) + bytearray(b'<'))
|
58ff596be5fd68dfc4f9161bdca45ebec9e3f875 | iblackcat/leetcode | /17.py | 1,131 | 3.640625 | 4 | def dic(ch):
if(ch=='0'):
return [' ']
elif (ch=='1'):
return ['1']
elif (ch=='2'):
return ['a','b','c']
elif (ch=='3'):
return ['d','e','f']
elif (ch=='4'):
return ['g','h','i']
elif (ch=='5'):
return ['j','k','l']
elif (ch=='6'):
return ['m','n','o']
elif (ch=='7'):
return ['p','q','r','s']
elif (ch=='8'):
return ['t','u','v']
elif (ch=='9'):
return ['w','x','y','z']
else:
return [ch]
def letterCombinations(digits):
ans=[[],[]]
tag=1
for le in digits:
tag = not tag
letters = dic(le)
ans[tag] = []
for ch in letters:
l = len(ans[not tag])
if (l == 0):
a = ""+ch
ans[tag] += a
else:
for i in range(0,l):
a = ans[not tag][i]+ch
ans[tag]+='a'
ll = len(ans[tag])
ans[tag][ll-1] = a
return ans[tag]
print(letterCombinations('2034'))
|
8c609955e91f3648813dbab60af93fad443e984e | sowrab-sahini/NLP | /ICE-1/ICE1.py | 1,484 | 3.671875 | 4 | import urllib.request
from bs4 import BeautifulSoup
import nltk
nltk.download('stopwords')
from nltk.corpus import stopwords
import matplotlib.pyplot as plt
#Using urllib library to read SpaceX wikipedia page
response = urllib.request.urlopen('https://en.wikipedia.org/wiki/SpaceX')
html = response.read()
#Using Beautiful Soup to parse raw html data
soup = BeautifulSoup(html, "html5lib")
text = soup.get_text(strip = True)
tokens = [t for t in text.split()]
clean_tokens = tokens[:]
#Using NLTKs Frequency Distribution to count the word frequency
frequency = nltk.FreqDist(tokens)
keys =[]
values = []
for key,val in frequency.items():
#Printing Values whose frequency is greater than 5
if val>5:
print(str(key) + ':' +str(val))
keys.append(key)
values.append(val)
else:
tokens.remove(key)
#Plotting graph without removing stopwords
frequency.plot(20,cumulative= False)
#After removal of stop words
for token in tokens:
#Removing Tokens which have digits
if str(token).isdigit():
clean_tokens.remove(token)
#Removing English language Stopwords
if token in stopwords.words('english'):
clean_tokens.remove(token)
#Calculating Frequency after removing stopwords
final = nltk.FreqDist(clean_tokens)
#Plotting first 10 high distribution words
final.plot(10,cumulative= False)
#Plotting Bar graph as other form of frequency visualization
plt.bar(keys[0:10], values[0:10], color='green')
plt.show()
|
932f7adad45f3cc91229bc876613fe81bd531e77 | chenxu0602/LeetCode | /1291.sequential-digits.py | 1,207 | 3.5 | 4 | #
# @lc app=leetcode id=1291 lang=python3
#
# [1291] Sequential Digits
#
# https://leetcode.com/problems/sequential-digits/description/
#
# algorithms
# Medium (51.49%)
# Likes: 97
# Dislikes: 10
# Total Accepted: 7.3K
# Total Submissions: 14.1K
# Testcase Example: '100\n300'
#
# An integer has sequential digits if and only if each digit in the number is
# one more than the previous digit.
#
# Return a sorted list of all the integers in the range [low, high] inclusive
# that have sequential digits.
#
#
# Example 1:
# Input: low = 100, high = 300
# Output: [123,234]
# Example 2:
# Input: low = 1000, high = 13000
# Output: [1234,2345,3456,4567,5678,6789,12345]
#
#
# Constraints:
#
#
# 10 <= low <= high <= 10^9
#
#
#
# @lc code=start
class Solution:
def sequentialDigits(self, low: int, high: int) -> List[int]:
# O(1)
sample = "123456789"
n = 10
nums = []
for length in range(len(str(low)), len(str(high)) + 1):
for start in range(n - length):
num = int(sample[start:start + length])
if low <= num <= high:
nums.append(num)
return nums
# @lc code=end
|
3ab3c17ff67cf8725452794d3c0e177e5f7b81e7 | TOKPE627/python_learning | /practicalList/program4.py | 397 | 4.625 | 5 | #Python program to find largest number in a list
#creation of empty list
arr1= []
print()
print("---Welcome in largest number finder program----")
print()
arrSize=int(input("Enter the number of elements of the list: "))
for i in range(1,arrSize+1):
element = int(input("Enter an element: "))
arr1.append(element)
print()
print("The largest element of the list is:", max(arr1))
|
ef745539d57f23f30960e356dee9bd744bc75857 | KaranRawlley/Python-Machine_LearningT | /Assignments/Assignment 1/Q5.py | 389 | 4.28125 | 4 | #program to convert KM to miles
import time
flag = -1
while flag == -1:
km = input('Enter the Km to convert to miles : ')
km = float(km)
m = km*0.62137
m = float(m)
print('\n',km,'Kilometers are',m,'Miles')
time.sleep(1.5)
choice = input('\nIf you wanna quit press 1 else any number to continue \n')
choice = int(choice)
if(choice==1):
flag = 1 |
e82f6cfe975ad6507644d3efd8a37dddc23b8230 | RAMMVIER/Data-Structures-and-Algorithms-in-Python | /Algorithm/11.Shell_sort.py | 995 | 3.65625 | 4 | # 希尔排序:一种分组插入排序算法
# 1. 取一个整数d1=n/2,将元素分为d1个组,每组相邻两个元素之间距离为d1,在各组内进行直接插入排序
# 2. 娶第二个整数d2=d1/2,重复上述分组排序过程,直到di=1,即所有元素在同一组内进行直接插入排序
# 希尔排序的每一次并不使得某些元素有序,而是使整体元素趋近于有序,最后一次排序是所有数据有序
# 希尔排序的时间复杂度讨论较为复杂,与所选取的gap序列相关
import random
def insert_sort_gap(li, gap):
for i in range(gap, len(li)):
tmp = li[i]
j = i - gap
while j >= 0 and li[j] > tmp:
li[j + gap] = li[j]
j -= gap
li[j + gap] = tmp
def shell_sort(li):
d = len(li) // 2
while d >= 1:
insert_sort_gap(li, d)
d //= 2
# test
test_list = list(range(1000))
random.shuffle(test_list)
shell_sort(test_list)
print(test_list)
|
e9dcccbf29afa578850227fa049f7388a5a66ef4 | sakshi978/Competitive-Platforms | /Hackerrank/Tuples.py | 739 | 4.15625 | 4 | '''
Question:
Task
Given an integer,n , and n space-separated integers as input, create a tuple,t , of those n integers. Then compute and print the result of hash(t).
Note: hash() is one of the functions in the __builtins__ module, so it need not be imported.
Input Format
The first line contains an integer, n, denoting the number of elements in the tuple.
The second line contains n space-separated integers describing the elements in tuple .
Output Format
Print the result of hash(t).
Sample Input 0
2
1 2
Sample Output 0
3713081631934410656
'''
if __name__ == '__main__':
tup = ()
n = int(input())
integer_list = list(map(int, input().split()))
tup = tuple(integer_list)
#print(tup)
print(hash(tup))
|
bbd5e85c820337af9c86d1e420e74f858eedd826 | patrickcanny/Challenges | /py/arrayLeftRotations.py | 598 | 3.9375 | 4 | #A left rotation denotes a movement of each element of an array to the left
#i.e. [1, 2, 3, 4] rotated once will become [4, 1, 2, 3]
#Given a starting array and a number of left rotations, return the final array
from collections import deque
def array_left_rotation(a, n, k):
d = deque(a, maxlen = n)
for _ in range (k):
d.append(d.popleft())
return d
n, k = map(int, raw_input().strip().split(' '))
a = map(int, raw_input().strip().split(' '))
answer = array_left_rotation(a, n, k);
print ' '.join(map(str,answer))
|
c564fb811c9f4c959deba3818ca413c10a41c053 | sumitjain0695/Data-Structures-and-Algorithms | /Tree/tree traversals.py | 717 | 3.671875 | 4 | class Node:
def __init__(self,data):
self.key=data
self.left=None
self.right=None
def inorder(root):
if root:
inorder(root.left)
print(root.key)
inorder(root.right)
def preorder(root):
if root:
print(root.key)
preorder(root.left)
preorder(root.right)
def postorder(root):
if root:
postorder(root.right)
postorder(root.left)
print(root.key)
root = Node(1)
root.left=Node(2)
root.right=Node(3)
root.left.left=Node(4)
root.left.right=Node(5)
print('inorder')
inorder(root)
print('preorder')
preorder(root)
print('postorder')
postorder(root)
|
b880335020b1cf26e92147fbbb045ab761292ffa | Hellofafar/Leetcode | /Medium/33.py | 1,598 | 4.09375 | 4 | # ------------------------------
# 33. Search in Rotated Sorted Array
#
# Description:
# Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
#
# (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
# You are given a target value to search. If found in the array return its index, otherwise return -1.
#
# You may assume no duplicate exists in the array.
#
#
# Version: 1.0
# 10/22/17 by Jianfa
# ------------------------------
class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if not nums:
return -1
if target not in nums:
return -1
left = 0
right = len(nums) - 1
while left < right:
mid = (left + right) / 2
if (nums[0] > target) ^ (nums[0] > nums[mid]) ^ (target > nums[mid]):
left = mid + 1
else:
right = mid
return left if target == nums[left] else -1
# Used for test
if __name__ == "__main__":
test = Solution()
nums = [3,4,5,1,2]
print(test.search(nums, 5))
# ------------------------------
# Summary:
# Idea from https://leetcode.com/problems/search-in-rotated-sorted-array/discuss/14419/Pretty-short-C%2B%2BJavaRubyPython
# There are three conditions need to be thought: nums[0] > target? nums[0] > nums[mid]? target > nums[mid]?
# If exactly two of them are true, then target should be at left side.
# Using XOR to distinguish. |
d737e3109bdee21be81fc03fd72c5ceb5f221d1c | Deepshikhasinha/CTCI | /Heap/heap_use.py | 338 | 3.65625 | 4 | import heapq
list1 = [[5,7,9],[1,4,8,10],[6,11,18]]
#list2 =
#list3 =
#list_all = list1+list2+list3
for i in range(len(list1)):
listk.append(list1[i][0])
del list1[i][0]
heapq.heapify(listk)
array = []
p1 = 0
p2 = 0
p3 = 0
while listk:
array.append()
heapq.heappush(listk,list1[p1])
print(heapq.nlargest(5, list_all))
|
206ffd1e2e4f1b8471bee51c40a41c2cb1cee120 | DTSMY96/Python-Games | /print('Hello world!').py | 247 | 3.875 | 4 | #print('Hello, world!')
#c = input('What is your favorite color?')
#print('I find it interesting that you like the color' + c)
#s = input('Which dessert do you prefer ?')
#print('I prefer 3.14 over' + s)
x = 5
x =+ 1
print(x) |
745c2948f4d27c6c6a3a8a388e4daeea494fe6dc | Dragon-Boat/PythonNote | /PythonCode/Python入门/Set/set基础.py | 1,285 | 4.03125 | 4 | #coding=utf-8
#author: sloop
'''
setʾ4λͬѧ
Adam, Lisa, Bart, Paul
'''
#
s = set(['Adam','Lisa','Bart','Paul'])
print s
'''
ʲôset
dictǽһ key һ value ӳϵdictkeyDzظġ
еʱֻҪ dict key key Ӧ valueĿľDZ֤ϵԪزظʱsetóˡ
set һϵԪأһ list setԪûظģ dict key
set ķʽǵ set() һ listlistԪؽΪsetԪأ
>>> s = set(['A', 'B', 'C'])
Բ鿴 set ݣ
>>> print s
set(['A', 'C', 'B'])
ע⣬ӡʽ list listϸԷ֣ӡ˳ԭʼ list ˳пDzͬģΪsetڲ洢Ԫġ
ΪsetܰظԪأԣǴظԪص list ôأ
>>> s = set(['A', 'B', 'C', 'C'])
>>> print s
set(['A', 'C', 'B'])
>>> len(s)
3
ʾsetԶȥظԪأԭlist4Ԫأsetֻ3Ԫء
''' |
c7ba7011c82bd74f867709c21ce09dd1dff530b2 | VinayHaryan/Array | /q26.py | 4,021 | 4.125 | 4 | '''
Given an array of positive and negative number, arrange them in an
alternate fasion such that every positive number is followed by negative
and vice-versa maintaining the order of appearance
Number of positive and negtive numbers need not be equal. if there are
more positive numbers they appear at the end of the array. if there are more
negative numbers, they too appear in the end of the array.
Examples :
Input: arr[] = {1, 2, 3, -4, -1, 4}
Output: arr[] = {-4, 1, -1, 2, 3, 4}
Input: arr[] = {-5, -2, 5, 2, 4, 7, 1, 8, 0, -8}
output: arr[] = {-5, 5, -2, 2, -8, 4, 7, 1, 8, 0}
this questin has been asked at many places the above probleam can be easily
solved if O(n) extra space is allowed. it become interesting due to the limitations that O(1)
extra space is allowed. it becomes interesting due to the limitation that O(1) extra space and order
of appearances
the idea is to process array from to right. while processing, find the
first out of place element in the remaining unprocessed array. an element is out
of place element in the remaining unprocessed array. an element is out of place if it is
negtive and at odd index, or it is positive and at even
index. Once we find an out of place element, we find the first element after
it with opposite sign. We right rotate the subarray between these two
elements (including these two).
Following is the implementation of above idea.
'''
# program to rearrange positive and negtive integers
# in alternate fashion and maintaining the order of positive
# and negative numbers
# def rightRotate(arr, n, outofplace, cur):
# temp = arr[cur]
# for i in range(cur, outofplace, -1):
# arr[i] = arr[i-1]
# arr[outofplace] = temp
# print(arr)
# return arr
# def rearrange(arr, n):
# outofplace = -1
# for index in range(n):
# if (outofplace >= 0):
# # if element at outofplace in
# # negative and if element at index
# # is positive we can rotate the
# # array to right or if element
# # at outofplace place in positive and
# # if element at index is negtive we
# # can rotate the array to right
# if (arr[index] >= 0 and arr[outofplace] < 0) or (arr[index] < 0 and arr[outofplace] >= 0):
# arr = rightRotate(arr,n,outofplace,index)
# if(index-outofplace >2 ):
# outofplace += 2
# else:
# outofplace = -1
# if (outofplace == -1):
# # conditions for A[index] to
# # be in out of place
# if (arr[index] >= 0 and index % 2 == 0) or (arr[index] < 0 and index % 2 == 1):
# outofplace = index
# print(arr)
# return arr
# # Driver code
# arr = [-5, -2, 5, 2, 4, 7, 1, 8, 0, -8]
# print("given array is: ")
# print(arr)
# print("\nRearranged array is: ")
# print(rearrange(arr, len(arr)))
# print('\n')
# for i in range(1,0,-1):
# print(i)
def RightRotate(arr, n, outofplace, cur):
Temp = arr[cur]
for i in range(cur,outofplace,-1):
arr[i] = arr[i-1]
arr[outofplace] = Temp
return arr
def Rearange(arr,n):
outofplace = -1
for index in range(n):
if outofplace >= 0:
if arr[index] >= 0 and arr[outofplace] < 0 or arr[index] < 0 and arr[outofplace] >= 0:
arr = RightRotate(arr,n,outofplace,index)
if index - outofplace > 2:
outofplace += 2
else:
outofplace = -1
if outofplace == -1:
if arr[index] >= 0 and index % 2 == 0 or arr[index] < 0 and index % 2 == 1:
outofplace = index
return arr
# driver mode
if __name__ == "__main__":
arr = [-5,-2,5,2,4,7,1,8,0,-8]
print(arr)
print("\n")
n = len(arr)
print(Rearange(arr,n))
|
f041e0ccb5382586b55e23d9c7ed71f0f464add9 | sparkle666/CSC-411 | /Bema_Smart_Kaddy.py | 143 | 3.859375 | 4 | #The Variables declared
myname = "Bema Smart Kaddy"
greetings = "Hello World!\n"
#This prints the values
print (greetings)
print ("My name is: ",myname) |
31e433dccc96511d0696a215340ef5d8908c8878 | xp562060315/Python--pandas-Excel | /006.py | 654 | 3.59375 | 4 | import pandas as pd
books = pd.read_excel('006Books.xlsx',index_col='ID',)
# books['Price']=books['ListPrice']*books['Discount']
#循环处理:很少用,一般尽量用上面的情况。但是不想从头计算的,用这种方式。
# for i in books.index:
# for i in range(5,16):
# books['Price'].at[i]=books['ListPrice'].at[i]*books['Discount'].at[i]
#给每本书提高2块钱
#方法一:
#books['ListPrice'] = books['ListPrice']+2
#方法二:
# def add_2(x):
# return(x+2)
# books['ListPrice'] = books['ListPrice'].apply(add_2)
#比较好的办法用lambda
books['ListPrice'] = books['ListPrice'].apply(lambda x:x+2)
print(books) |
9a446604e11009a201d3e697f05ba438fffdf297 | apalashkin/checkio-py | /elementary/number_base.py | 1,218 | 4.375 | 4 | """
Do you remember the radix and Numeral systems from math class? Let's practice with it.
You are given a positive number as a string along with the radix for it.
Your function should convert it into decimal form. The radix is less than 37 and greater than 1.
The task uses digits and the letters A-Z for the strings.
Watch out for cases when the number cannot be converted.
For example:
"1A" cannot be converted with radix 9. For these cases your function should return -1.
"""
import string
def checkio(str_number, radix):
mass = string.digits + string.ascii_letters
res = 0
for i, s in enumerate(str_number):
if mass.index(s.lower()) > radix - 1:
return -1
res += mass.index(s.lower()) * (radix**(len(str_number) - (i + 1)))
return res
# These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
# assert checkio("AF", 16) == 175, "Hex"
# assert checkio("101", 2) == 5, "Bin"
# assert checkio("101", 5) == 26, "5 base"
# assert checkio("Z", 36) == 35, "Z base"
assert checkio("AB", 10) == -1, "B > A = 10"
print("Coding complete? Click 'Check' to review your tests and earn cool rewards!")
|
a65c5f2d60e78fda18111cbf5498d5855d49bfc7 | hina-murdhani/python-project | /pythonProject3/demo/set.py | 1,391 | 4.375 | 4 | # set has no duplicate elements, mutabable
set1 = set()
print(set1)
set1 = set("geeksforgeeks")
print(set1)
string = 'geeksforgeeks'
set1 = set(string)
print(set1)
set1 = set(["geeks", "for", "geeks"])
print(set1)
set1 = set(['1', '2', '3', '4'])
print(set1)
set1 = set([1, 2, 'geeks', 'for', 3, 3])
# add() method is use for for addign element to the set
set1 = set()
set1.add(8)
set1.add(7)
set1.add(9)
set1.add((5, 8))
for i in range(1, 6):
set1.add(i)
print(set1)
# to add morethan one elemnet update() method is useful
set1 = set([ 4, 5, (6, 7)])
set1.update([10, 11])
print("\nSet after Addition of elements using Update: ")
print(set1)
# for accessing the element in set
for i in set1:
print(i, end=" ")
# check for element is present or not in set
print("Geeks" in set1)
# remove() and discard() method use for removing element of set
set1 = set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
set1.remove(5)
set1.remove(6)
print(set1)
set1.discard(2)
set1.discard(3)
print(set1)
# clear() is used for removing all the elements from the set
set1.clear()
print(set1)
# pop() methos is use for removing element its remove last element and return the last element
set1 = set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
print("Intial Set: ")
print(set1)
# Removing element from the
# Set using the pop() method
set1.pop()
print("\nSet after popping an element: ")
print(set1)
|
0355451c7c55a4c1e97874ff7f6ab4c33f13580d | SMKxx1/I.P.-Class-11 | /chapter 6/b 6.2.py | 287 | 3.9375 | 4 | s = input("Enter the string: ")
Sum = 0
digits = ''
for i in s:
if i.isdigit():
digits = digits + " " + i
Sum += eval(i)
else:
pass
if digits == '':
print(s,"has no digits")
else:
print(s,"has digits",digits,"and there sum is",Sum)
|
5cb6fb0cd65dd859d2e46e08eea6c737691443fb | R083rtKr01/PythonBasic | /Functions.py | 2,897 | 3.71875 | 4 | #funkcja zwraca liczbę kolejną liczbę pierwszą względem zadanej wartości
#piąta z kolei liczba pierwsza n=5 szukamy od zera
from datetime import date
def getPrimaryNumbers(n=5):
primaryNumbers = [1]
number=2
while(len(primaryNumbers) <n):
isPrimary=True
for div in range(2,number):
if(number % div==0): #sprawdzenie podzielności
isPrimary=False
if(isPrimary):
primaryNumbers.append(number)
number +=1
return primaryNumbers,primaryNumbers[len(primaryNumbers)-1]
#wywołanie funkci
element = 11
print("Lista: ",getPrimaryNumbers(element))
print("n-ty element: ",getPrimaryNumbers(element)[1])
def printParameters(login,password, email, status=True, registrationDate=date.today()):
return("%s %s %s %s %s" % (login,password,email, status, registrationDate))
#różne wywołania
print(printParameters("rk","rk","rk"))
print(printParameters("rk1","rk1","rk1",registrationDate= "2020-01-01"))
print(printParameters("rk2","rk2","rk2",registrationDate= "2020-01-01", status=False))
def nonDefinedParameter(*elements):
sum=0
for elem in elements:
sum+=elem
return sum/len(elements)
print(nonDefinedParameter(1))
print(nonDefinedParameter(5,4,6))
print(nonDefinedParameter(2,2,2,2))
def sortList(numbers):
numbers.sort()
return numbers
list=[3,2,5,4,6]
print(sortList(list))
def bubblesort(elements, asc=True):
noProbes=1
#pętla iterująca po kolejnych próbach sortowania
for probe in range(len(elements)-1): # determinujemy 5 prób w przypadku najgorszym
isSorted = True
for index,value in enumerate(elements):
if(index == (len(elements)-1)):
break
if((elements[index]>elements[index+1]and asc)): # porównanie sąsiednich komórek
isSorted=False
elem=elements[index+1] # wydobcie elementu na indeksie i+1 do zmienej
elements[index+1]=elements[index] # zamiana kolejności
elements[index] = elem
if((elements[index]<elements[index+1]and not asc)): # porównanie sąsiednich komórek
isSorted=False
elem=elements[index+1] # wydobcie elementu na indeksie i+1 do zmienej
elements[index+1]=elements[index] # zamiana kolejności
elements[index] = elem
#print(noProbes,elements)
if (isSorted):
break
noProbes+=1
return elements
print(bubblesort([1,3,2,5,4,6]))
print(bubblesort([34,45,1,3,87,56,9],asc=True))
from datetime import datetime
t_start=datetime.now().microsecond/1000
print(bubblesort([3,2,1,5,4,6,21,34,44,22,20,55,4,1,55,66,2,4,1,1,54,3,11],asc=False))
t_stop = datetime.now().microsecond/1000
print(t_start)
print(t_stop)
print("czas wykonania funkcji w ms:",t_stop-t_start)
|
732738f2b328b75f2c5ea064398fc13b9fa6c4b3 | mingyyy/crash_course | /week2/martes/6-10.py | 610 | 4.1875 | 4 | '''
6-10. Favorite Numbers: Modify your program from Exercise 6-2 (page 102)
so each person can have more than one favorite number .
Then print each person’s name along with their favorite numbers .
'''
FavNum = {"casey": [1,3,5],
"rob": 2,
"melissa": [7,8],
"daniel": 9,
"ben": [5,23,31,47]}
for name, n in FavNum.items():
if type(n) == list:
print(name.capitalize() + "'s favorite numbers are", end = " ")
for i in n:
print(i, end= " ")
print(".")
else:
print(f"{name.capitalize()}'s favorite number is {n}.")
|
845057019717a97542123b135b52bea060b5dd29 | tanyastropheus/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/0-square_matrix_simple.py | 176 | 3.640625 | 4 | #!/usr/bin/python3
def square_matrix_simple(matrix=[]):
matrix_squared = []
for i in matrix:
matrix_squared.append([j**2 for j in i])
return matrix_squared
|
d84b7bdb2b8a87671f413ef64eec94cefc93c20c | dotheright/mylovelycodes | /tensorflow/forfun/animation.py | 3,237 | 4.09375 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
#plt.cm.coolwarm
# first set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax1 = fig.add_subplot(2,1,1,xlim=(0, 2), ylim=(-4, 4))
ax2 = fig.add_subplot(2,1,2,xlim=(0, 2), ylim=(-4, 4))
line, = ax1.plot([], [], lw=2)
line2, = ax2.plot([], [], lw=2)
def init():
line.set_data([], [])
line2.set_data([], [])
return line,line2
# animation function. this is called sequentially
def animate(i):
x = np.linspace(0, 2, 100)
y = np.sin(2 * np.pi * (x - 0.01 * i))
line.set_data(x, y)
x2 = np.linspace(0, 2, 100)
y2 = np.cos(2 * np.pi * (x2 - 0.01 * i))* np.sin(2 * np.pi * (x - 0.01 * i))
line2.set_data(x2, y2)
return line,line2
anim1=animation.FuncAnimation(fig, animate, init_func=init, frames=50, interval=10)
plt.show()
"""
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig = plt.figure()
axes1 = fig.add_subplot(111)
line, = axes1.plot(np.random.rand(10))
#因为update的参数是调用函数data_gen,所以第一个默认参数不能是framenum
def update(data):
line.set_ydata(data)
return line,
# 每次生成10个随机数据
def data_gen():
while True:
yield np.random.rand(10)
ani = animation.FuncAnimation(fig, update, data_gen, interval=2*1000)
plt.show()
"""
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
start = [1, 0.18, 0.63, 0.29, 0.03, 0.24, 0.86, 0.07, 0.58, 0]
metric =[[0.03, 0.86, 0.65, 0.34, 0.34, 0.02, 0.22, 0.74, 0.66, 0.65],
[0.43, 0.18, 0.63, 0.29, 0.03, 0.24, 0.86, 0.07, 0.58, 0.55],
[0.66, 0.75, 0.01, 0.94, 0.72, 0.77, 0.20, 0.66, 0.81, 0.52]
]
fig = plt.figure()
window = fig.add_subplot(111)
line, = window.plot(start)
#如果是参数是list,则默认每次取list中的一个元素,即metric[0],metric[1],...
def update(data):
line.set_ydata(data)
return line,
ani = animation.FuncAnimation(fig, update, metric, interval=2*1000)
plt.show()
"""
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)
# initialization function: plot the background of each frame
def init():
line.set_data([], [])
return line,
# animation function. This is called sequentially
# note: i is framenumber
def animate(i):
x = np.linspace(0, 2, 1000)
y = np.sin(2 * np.pi * (x - 0.01 * i))
line.set_data(x, y)
return line,
# call the animator. blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=200, interval=20, blit=True)
#anim.save('basic_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264'])
plt.show()
|
cd5a31f0b76d36618c9c9badc04bd1c91e481f98 | smziegle/python | /triangle.pyw | 415 | 3.59375 | 4 | from graphics import *
win= GraphWin()
win.setCoords(0.0,0.0,10.0,10.0)
message=Text(Point(5.0,0.5),"Click on three points")
message.draw(win)
p1=win.getMouse()
p1.draw(win)
p2=win.getMouse()
p2.draw(win)
p3=win.getMouse()
p3.draw(win)
triangle=Polygon(p1,p2,p3)
triangle.setFill("peachpuff")
triangle.setOutline("cyan")
triangle.draw(win)
message.setText("Click anywhere to quit")
win.getMouse()
win.close()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.