blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
6b7e0f85c6f2824c03f4828f22982f26af8c0190 | ConorChristensen/Various-Assembly-Programs | /Task1_a.py | 425 | 4.3125 | 4 | year = int(input("Please enter the year: "))
def is_leap_year(year):
if year % 4 == 0 :
if year % 100 != 0:
return True
elif year % 400 == 0:
return True
else:
return False
else :
return False
if is_leap_year(year) == True:
print("Is leap year.")
if is_leap_year(year) == False:
print("Is not leap year.")
| false |
4fb810313217d7bfdd66ebbcd0deec3b22ec995c | tvey/hey-python | /data_types/lists/list_methods.py | 1,062 | 4.46875 | 4 | """
Lists are mutable, and they have a lot of methods to operate on their items.
"""
# initializing a list with items
fellowship = ['Frodo', 'Gandalf', 'Aragorn']
# adding item to the end of the list
fellowship.append('Legolas') # you have my bow
fellowship.append('Gimli') # and my axe
# extending list — adding items from other
fellowship.extend(['Sam', 'Merry', 'Pippin'])
# insert item to a particula position (index)
fellowship.insert(5, 'Boromir')
# create a shallow copy of a list
members = fellowship.copy()
# get index of an item
gandalf_idx = fellowship.index('Gandalf')
# remove an item by its value
fellowship.remove('Boromir')
# remove an item by its index, return the value
fellowship.pop(gandalf_idx)
fellowship.insert(1, 'Gandalf')
# pop() removes an item and returns it
to_mordor = [fellowship.pop(0), fellowship.pop(-3)]
# sort list items in place
fellowship.sort()
# reverse items in place
fellowship.reverse()
# clear a list — remove all items
fellowship.clear()
print(members)
| true |
94b377ceb365f720fad2730683784a1e7a592ce3 | tvey/hey-python | /functions/parameters_arguments.py | 2,058 | 4.78125 | 5 | """
Functions become ever more useful when we can pass to them some information.
Creating a function, we specify the expected information with parameters.
On a function call we pass arguments that match these parameters.
(In general words “parameters” and “arguments” can be used interchangeably.)
There are 4 ways to pass arguments to functions:
- positional arguments (mandatory, and their order matters),
- keyword arguments (named args that have default values),
- argument list/tuple (usually called *args),
- argument dictionary (**kwargs).
"""
def get_everything(*args, **kwargs):
"""Explore the way parameters look in a function.
This function takes any number of positional and keyword arguments.
“args” and “kwargs” variable names are conventions and can be replaced
with other names.
"""
assert isinstance(args, tuple)
assert isinstance(kwargs, dict)
print(locals()) # args and kwargs are keys in the locals() dict
print('args:', args)
print('kwargs:', kwargs)
def get_nothing():
assert not locals() # such empty
def get_args(positional, keyword=None, *args, **kwargs):
"""Function parameters must be in a specific order.
Any other way to define and pass them will result in SyntaxError.
"""
pass
def add_participant(first_name, last_name):
"""
Positional arguments are used when there are few of them required.
Their order is natural and therefore easy to remember.
"""
return f'{first_name} {last_name} is added to a list.'
def collect_info(first_name, last_name, house=None, patronus=None):
"""
When more information needed, order of arguments is harder to remember.
And some pieces of information may not be mandatory.
In this case keyword arguments come in handy.
They are expected (opposite to arbitrary **kwargs) but not required.
"""
if house == 'Slytherin' and patronus:
print('No way')
if __name__ == '__main__':
get_everything(1979, 'otter', color='violet', occupation='dentist')
| true |
5727d09696de5d71d09e6f5850ab232dcca9dd2b | MauroBCardoso/pythonGame_Zenva | /classes and objects.py | 1,108 | 4.1875 | 4 | #Python (classes and objects)
class GameCharacter:
speed = 5 # the moment it is created it has the value
def __init__(self, name, width, height, x_pos, y_pos): #self is GameCharacter
self.name = name
self.width = width
self.height = height
self.x_pos = x_pos
self.y_pos = y_pos
def move(self, by_x_amount, by_y_amount):
self.x_pos += by_x_amount
self.y_pos += by_y_amount
character_0 = GameCharacter('char', 50, 100, 100, 100)
print(character_0.name)
character_0.name = 'changed'
print(character_0.name)
character_0.move(50, 100)
print(character_0.x_pos)
print(character_0.y_pos)
#Python subclasses, superclasses, and inheritance
class PlayerCharacter(GameCharacter):
speed = 10
def __init__(self, name, width, height, x_pos, y_pos):
super().__init__(name, width, height, x_pos, y_pos)
def move(self, by_y_amount):
super().move(0, by_y_amount)
player = PlayerCharacter('player', 100, 100, 500, 500)
print(player.name)
player.move(100)
print(player.x_pos)
print(player.y_pos)
| true |
a5247c0368bf734c5e9c5ddbd28abf0f7d5b1171 | carlogeertse/workshops | /workshop_1/exercise_5/exercise1-5-3.py | 220 | 4.3125 | 4 | string = "This is a string with multiple characters and vowels, it should contain all five possible vowels"
vowels = ["a", "e", "i", "o", "u"]
for vowel in vowels:
string = string.replace(vowel, "")
print(string)
| true |
9f4e572e6e78875019deb40f143cbe1a57703402 | shomrkm/python_study | /effective_python/4_comprehension_and_generator/using_list_comprehension.py | 331 | 4.3125 | 4 | # -*- coding:utf-8 -*-
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
squares = []
for x in a:
squares.append(x**2)
print(squares)
# リスト内表記
squares = [x**2 for x in a]
print(squares)
even_squares = [x**2 for x in a if x % 2 == 0]
print(even_squares)
three_cubed_set = {x**3 for x in a if x % 3 == 0}
print(three_cubed_set) | false |
22b6d88065cac062432597e4311b35e7574812ec | yosephog/INF3331 | /assignment5/diff.py | 2,162 | 4.21875 | 4 | import sys
import re
import itertools
def read_file(file_name):
"""
this method just read a file and return it
as a list spliting at new line
"""
sourcefile=open(file_name,'r')
file=sourcefile.read()
sourcefile.close()
return file.split('\n')
def diff(original_listinal,modified):
""" This method find the difference between two file that is
the original_listinal and the modifed of the original_listinal_lineinal version
"""
file=open("diff.txt",'w')
# this for loop just reads the two file at the same time
for (original_listinal_line,modified_line) in itertools.zip_longest(original_listinal,modified):
"""
spliting the original and modifed line in to list of word in order to
compare word by word if the two lines have the same lenght
and amount of word
for example end and our. two words different but same length
"""
original_list=original_listinal_line.split(' ')
modified_list=modified_line.split(' ')
"""
if the two line have the same amount of words then
compare if there are word difference
"""
if len(original_list) == len(modified_list):
if len(original_listinal_line) > len(modified_line):
tx='- ' + original_listinal_line
print(tx)
file.write(tx+'\n')
tx2='+ ' + modified_line
print(tx2)
file.write(tx2+'\n')
elif len(original_listinal_line) == len(modified_line):
tx='0 ' + original_listinal_line
print(tx)
file.write(tx+'\n')
else:
tx='+ ' + modified_line
print(tx)
file.write(tx+'\n')
"""
if the orginal list is greater then some word must
have been deleted
"""
elif len(original_list) > len(modified_list):
tx='0 ' + original_listinal_line
file.write(tx+'\n')
tx2='- ' + modified_line
file.write(tx2)
"""
if the orginal_list is smaller then words are added to the
modified version
"""
elif len(original_list) < len(modified_list):
tx='- ' + original_listinal_line
file.write(tx + '\n')
tx2='+ ' + modified_line
file.write(tx2 + '\n')
if __name__ == '__main__':
original_listinal=read_file(sys.argv[1])
modified=read_file(sys.argv[2])
diff(original_listinal,modified)
| true |
07e43d26d674d2bbf75ae303fc1ebe5feda09803 | suriyaganesh97/pythonbasicprogs | /basic/list.py | 535 | 4.3125 | 4 | fruits = ["Strawberries", "Nectarines", "Apples", "Grapes", "Peaches", "Cherries", "Pears"]
vegetables = ["Spinach", "Kale", "Tomatoes", "Celery", "Potatoes"]
dirty_dozen = [fruits, vegetables] #nested list
print(fruits)
print(fruits[1]) #nectarines is printed and not apples
fruits[2] = "guava"
print(fruits)
fruits.append("pomegranate")
print(fruits)
print(dirty_dozen)
print(dirty_dozen[0]) #this refers to first element which is list fruit in the list dirty dozen
print(dirty_dozen[1])
print(dirty_dozen[1][2]) | true |
df754421efc5146bc188b88c6ba70596b96d9b79 | suriyaganesh97/pythonbasicprogs | /d19/turtleRace.py | 1,016 | 4.1875 | 4 | from turtle import Turtle, Screen
import random
screen = Screen()
screen.setup(width=500,height=400)
user_bet = screen.textinput(title="make your bet", prompt = "which turetle will win the race, enter the colour")
colors = ["red", "orange", "yellow", "green", "blue", "purple"]
all_turtles = []
y_position = 0
for i in range(6):
tommy = Turtle(shape="turtle")
tommy.penup()
tommy.color(colors[i])
tommy.goto(x=-230, y=(-90 + y_position))
y_position += 30
all_turtles.append(tommy)
is_game_on = False
if user_bet:
is_game_on = True
while is_game_on:
for turtle in all_turtles:
move_forward = random.randint(0,10)
turtle.forward(move_forward)
if turtle.xcor() > 230:
is_game_on = False
winner_turtle = turtle.pencolor()
if user_bet == winner_turtle:
print(f"you won, the winner is {winner_turtle}")
else:
print(f"you lost, the winner is {winner_turtle}")
screen.exitonclick() | true |
08c2942c26d0c382b7ce410f434f638f1fad0704 | yukiko1929/python_scripts | /function_basic.py | 978 | 4.125 | 4 | # 関数に関する基本的な知識
# def sentence(name, department, years):
# print('%s is at %s for %s years' % (name, department, years))
# print(sentence())
#TypeError: sentence() missing 3 required positional arguments: 'name', 'department', and 'years'
# print(sentence('yuki'))
# print(sentence('yuki', 'MP', '5'))
# print(sentence('yuki', 'mass production', '5', 'yukiko'))
# print(sentence('miho', name='yuki', years='5', department='RD')) # got multiple values
# # print(sentence(years='5', department='RD', name='yuki'))
# print(sentence(years='5', 'RD', name='yuiko'))
#
# def func1(*args):
# print(args)
#
# def func2(**kwargs):
# print(kwargs)
#
# if __name__ == '__main__':
# print(func1('yuki',23,'tokyo'))
# print(func2(name = 'tom', age = 39, city = 'tokyo'))
# print(func1())
# print(func2())
def info(name, age):
print('%s : %s' % (name, age))
print(info(**{'name':'yuki', 'age':25}))
print(info(name='yuki', age=25)) | false |
c50603efec0026b7bbf28322d51b41371428a164 | AravKasliwal/Peerbuds-Innovation-Lab | /madlibs.py | 674 | 4.15625 | 4 | first_word = input("noun")
second_word = input("verb")
third_word = input("noun")
fourth_word = input("verb")
fifth_word = input("adjective")
sixth_word = input("noun")
seventh_word = input("verb")
print("I have " + first_word + " at my house. " "He is very " + second_word +"to me " " I have a brother his name is ")
print(third_word + "he is really rude " " 1 day he " + fourth_word + " on my friend " )
print(" he can be" + fifth_word + "like one time he gave us money for ice cream ")
print("sometimes brother can be " + sixth_word + "he is very nice to have around but sometimes brothers can be bullies ")
print("After all brothers " + seventh_word + "very nice " )
| false |
e2d6e3b915c43a5da85856eaf05ffbfb2ca9d102 | lch-howger/LichPythonTestProjects | /test13.py | 434 | 4.125 | 4 | is_male=True
is_tall=True
if is_male:
if is_tall:
print('you are male and you are tall')
else:
print('you are male and you are not tall')
else:
if is_tall:
print('you are not male and you are tall')
else:
print('you are not male and you are not tall')
if is_male or is_tall:
print('you are male or you are tall')
if is_male and is_tall:
print('you are male and you are tall') | false |
3d49d2a00a0bd0449df54c2448fcecd1d88a2d1e | lch-howger/LichPythonTestProjects | /test15.py | 379 | 4.28125 | 4 | num1 = input('Enter the first number: ')
operator = input('Enter the operator: ')
num2 = input('Enter the second number: ')
num1 = float(num1)
num2 = float(num2)
if operator == '+':
print(num1 + num2)
elif operator == '-':
print(num1 - num2)
elif operator == '*':
print(num1 * num2)
elif operator == '/':
print(num1 / num2)
else:
print('Invalid operator.')
| false |
cd49287248f1ad37be22352f9c038a49a360e6dc | acharyasant7/Bioinformatics-Algorithms-Coding-Solutions | /Chapter-1/1A_1B_RepeatPattern | 1,371 | 4.21875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 13 21:10:54 2020
@author: sandesh
"""
#Function that takes input the string and kmer, and returns all sub-strings of
#k-mer length which are repeated the most inside a string
def FrequentWords(string, kmer):
a = len(string) - kmer +1
Frequentword = set()
Counts = [None] * a
for i in range(0, a, 1):
Pattern = string[i:i+kmer]
Counts[i] = PatternFind(string, Pattern)
maxCount = max(Counts)
for i in range(0,a,1):
if Counts[i] == maxCount:
adds = ''.join(string[i: i+kmer])
Frequentword.add(adds)
return Frequentword
#Taking DNA String as input and changing it into list. Also, taking kmer as input.
DNA = input("Enter your DNA String in Capital: \n")
string = list(DNA)
kmer = int(input("Enter the k-mer of frequentwords:"))
print(FrequentWords(string, kmer))
#Function to return how many times a pattern is repeated in a string
def PatternFind(string, pattern):
a = len(string) - len(pattern) +1
count = 0
for i in range(0,a,1):
m = 0
for j in range(0, len(pattern), 1):
if pattern[j] == string[i]:
m = m+1
i = i+1
if m == len(pattern):
count = count +1
return count
| true |
9ab2b4d2a99a78a3b0ca82d3df26e6f4d9a44261 | purumalgi/Python-Codes | /Coordinate System.py | 523 | 4.375 | 4 | x = float(input("Enter x-coordinate: "))
y = float(input("Enter y-coordinate: "))
# To find which Quadrant the point lies in
if x>0:
if y>0:
# x is greater than 0, y is greater than 0
print("Quadrant 1")
else:
# x is greater than 0, y is less than 0
print("Quadrant 4")
else:
if y>0:
#x is less 0, y is greater than 0
print("Quadrant 2")
else:
#x is less than 0, y is less than 0
print("Quadrant 3")
| true |
14fa311c77f9734908730f8aadf29c99902cf323 | RedBeret/galvanize_prep_self_study | /Control_flow.py | 1,746 | 4.59375 | 5 | # Day 5: Comparisons and Conditionals
# Function to check if a number is equal to either 5 or 3
def five_or_three(num):
return num == 5 or num == 3
print(five_or_three(3)) # True
# Function to check if a number is divisible by the provided divisors
def is_divisible_by(num, divisor1, divisor2):
if num % divisor1 == 0 and num % divisor2 == 0:
return f'This number is divisible by {divisor1} and {divisor2}.'
elif num % divisor1 == 0:
return f'This number is divisible by {divisor1}.'
elif num % divisor2 == 0:
return f'This number is divisible by {divisor2}.'
else:
return f'This number is not divisible by either {divisor1} or {divisor2}.'
print(is_divisible_by(9, 3, 2)) # 'This number is divisible by 3.'
print(is_divisible_by(12, 5, 3)) # 'This number is divisible by 3.'
print(is_divisible_by(12, 3, 4)) # 'This number is divisible by 3 and 4.'
print(is_divisible_by(12, 5, 7)) # 'This number is not divisible by either 5 or 7.'
# Function to apply different operations based on the type of input
def depends_on_the_type(obj):
if type(obj) == int:
if obj == 0:
return 'Zero'
elif obj % 2 == 0:
return obj**2
elif obj % 2 == 1:
return obj**3
elif type(obj) == float:
return obj * 1.5
elif type(obj) == str:
return obj + obj
elif type(obj) == bool:
return not obj
else:
return None
print(depends_on_the_type(0)) # 'Zero'
print(depends_on_the_type(2)) # 4
print(depends_on_the_type(3)) # 27
print(depends_on_the_type(0.5)) # 0.75
print(depends_on_the_type('hello')) # 'hellohello'
print(depends_on_the_type(False)) # True
print(depends_on_the_type(None)) # None
| true |
b591ab88e04cdae85991e363957af3418b3a262f | yeduxiling/pythonmaster | /ex3.py | 867 | 4.46875 | 4 | #打印字符
print("I will now count my chickens:")
#打印字符,同时计算25 + 30/6 乘除的计算优先于加减法
# 打印的内容如果不是字符串时,以,隔开
print("Hens:", 25 + 30/6)
#打印文本,同时计算 %代表取余数部分 如4%2余数为0 3%2 余数为1
print("Roosters:", 100 - 25*3%4)
print("Now I will count the eggs:")
#计算
print(3 + 2 + 1- 5 + 4%2 -1/4 +6)
print("Is it ture that 3+2<5-7?")
#逻辑运算 输出结果为True 或 False
print(3 + 2 < 5 - 7)
print("What is 3+2?", 3 + 2)
print("What is 5-7?", 5 - 7)
print("Oh, that's why it's False.")
print("How about some more.")
print("Is it greater?", 5 > -2)
print("Is it greater or equal?", 5 >= -2)
print("Is it less or equal?", 5 <= -2)
#注意:代码中的换行在实际程序运行中并不生效,输出还是逐行产生,不会根据代码换行
| false |
169e7dd6a9fc743e4043c5c3c7095828bc5b0bdc | yeduxiling/pythonmaster | /ex4.py | 1,223 | 4.34375 | 4 | # 使用 变量名 = 值 的方式来定义变量,变量的值可以是数值,可以是字符串,也可以是其他变量的运算结果
cars = 100
space_in_a_car = 4.0
drivers = 30
passengers = 90
cars_not_driven = cars - drivers
cars_driven = drivers
carpool_capacity = cars_driven * space_in_a_car
average_passengers_per_car = passengers / cars_driven
print("There are", cars,"cars available.")
print("There are only", drivers,"drivers available.")
print("There will be", cars_not_driven,"empty cars today.")
print("We can transport", carpool_capacity,"people today.")
print("We have", passengers,"to carpool today.")
print("We need to put about", average_passengers_per_car,"in each car.")
print(cars / space_in_a_car)
#在打印的字符串中如果出现了变量,则在字符串前用f代表打印的字符串中会引用格式化变量
print(f"There are {cars} cars available.")
print(f"There are only {drivers} drivers available.")
print(f"There will be {cars_not_driven} empty cars today.")
print(f"We can transport {carpool_capacity} people today.")
print(f"We have {passengers} to carpool today.")
print(f"We need to put about {average_passengers_per_car} in each car.")
print(cars / space_in_a_car)
| false |
6a8b86d98cc2de4c6051970e3aabd158d61bb90c | roman-kachanovsky/checkio-python | /solutions/codeship/the_most_wanted_letter.py | 1,697 | 4.375 | 4 | """ --- The Most Wanted Letter --- Simple
You are given a text, which contains different english letters
and punctuation symbols.
You should find the most frequent letter in the text.
The letter returned must be in lower case.
While checking for the most wanted letter, casing does not matter,
so for the purpose of your search, "A" == "a".
Make sure you do not count punctuation symbols, digits and whitespaces,
only letters.
If you have two or more letters with the same frequency,
then return the letter which comes first in the latin alphabet.
For example -- "one" contains "o", "n", "e" only once for each,
thus we choose "e".
Input: A text for analysis as a string (unicode for py2.7).
Output: The most frequent letter in lower case as a string.
How it is used: For most decryption tasks you need to know
the frequency of occurrence for various letters
in a section of text.
For example: we can easily crack a simple addition or
substitution cipher if we know the frequency
in which letters appear.
This is interesting stuff for language experts!
Precondition: A text contains only ASCII symbols.
0 < len(text) <= 105
"""
def my_solution(text):
text = {c: text.lower().count(c) for c in text.lower() if c.isalpha()}
return max(sorted(text.keys()), key=text.get)
def bryukh_solution(text):
import string
text = text.lower()
return max(string.ascii_lowercase, key=text.count)
from string import ascii_lowercase as letters
veky_solution = lambda text: max(letters, key=text.lower().count)
| true |
f039d41d68c85faa1079725b859bf3740d241048 | roman-kachanovsky/checkio-python | /solutions/elementary/number_base.py | 1,050 | 4.5625 | 5 | """ --- Number Base --- Simple
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.
Input: Two arguments. A number as string and a radix
as an integer.
Output: The converted number as an integer.
How it is used: Here you will learn how to work with the various
numeral systems and handle exceptions.
Precondition: re.match("\A[A-Z0-9]\Z", str_number)
0 < len(str_number) <= 10
2 <= radix <= 36
"""
def my_solution(str_number, radix):
try:
return int(str_number, radix)
except:
return -1
def veky_solution(*a):
try: return int(*a)
except ValueError: return -1 | true |
c5d7dd44f402c052625bd949c8ec6ad98af22f5c | roman-kachanovsky/checkio-python | /solutions/scientific_expedition/the_best_number_ever.py | 1,262 | 4.34375 | 4 | """ --- The best number ever --- Elementary
It was Sheldon's version and his best number. But you have
the coding skills to prove that there is a better number,
or prove Sheldon sheldon right. You can return any number,
but use the code to prove your number is the best!
This mission is pretty simple to solve. You are given
a function called "checkio" which will return any number
(integer or float).
Let's write an essay in python code which will explain why
is your number is the best. Publishing the default solution
will only earn you 0 points as the goal is to earn points
through votes for your code essay.
Input: Nothing.
Output: A number as an integer or a float or a complex.
How it is used: This mission revolves around code and
math literacy.
"""
def my_solution(n):
def pi(precision):
"""Get pi constant with the Bailey-Borwein-Plouffe formula"""
from decimal import Decimal, getcontext
getcontext().prec = precision
return sum(1 / Decimal(16) ** k * (
Decimal(4) / (8 * k + 1) -
Decimal(2) / (8 * k + 4) -
Decimal(1) / (8 * k + 5) -
Decimal(1) / (8 * k + 6)) for k in xrange(precision))
return pi(n)
| true |
293fcc3afc4787ced510e2ccfd295f5e51dd515c | roman-kachanovsky/checkio-python | /solutions/electronic_station/restricted_sum.py | 1,022 | 4.125 | 4 | """ --- Restricted Sum --- Simple
Our new calculator is censored and as such it does not accept certain words.
You should try to trick by writing a program to calculate the sum of numbers.
Given a list of numbers, you should find the sum of these numbers.
Your solution should not contain any of the banned words, even as a part
of another word.
The list of banned words are as follows:
sum
import
for
while
reduce
Input: A list of numbers.
Output: The sum of numbers.
How it is used: This task challenges your creativity to come up
with a solution to fit this mission's specs!
Precondition: The small amount of data. Let's creativity win!
"""
def my_solution(data):
s = '%s ' * len(data)
return eval('+'.join((s % tuple(data)).split()))
def ciel_solution(data):
if len(data) == 0: return 0
return data[0] + ciel_solution(data[1:])
def erik_white_2014_solution(data):
d = map(str, data)
return eval('+'.join(d))
| true |
c3a2f0b420522c9fa33464dde937a1d42fed140a | roman-kachanovsky/checkio-python | /solutions/oreilly/i_love_python.py | 1,476 | 4.25 | 4 | """ --- I Love Python --- Elementary
Let's write an essay in python code which will explain
why you love python (if you don't love it, when we will make
an additional mission special for the haters). Publishing the default
solution will only earn you 0 points as the goal is to earn points
through votes for your code essay.
Input: Nothing.
Output: The string "I love Python!".
How it is used: This mission revolves around code literacy.
"""
import string
from itertools import product
def my_solution():
def is_correct_phrase(s):
return True if s == 'I love Python!' else False
def bruteforce(count_of_symbols):
"""
54^14 = 1.792720718*10^24 combinations
Over 2 million years to iterate all of them
We use all latin letters plus ' ' and '!' symbols:
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ !'
and got our list of combinations.
Each of them have length = 14 like the 'I love Python!' string.
"""
list_of_combinations = product(string.ascii_letters + ' ' + '!',
repeat=count_of_symbols)
list_of_combinations = [list('I love Python!'), ] # Comment this line for true search
for c in list_of_combinations:
phrase = ''.join(c)
if is_correct_phrase(phrase):
return phrase
return None
return bruteforce(14)
| true |
f9d2326d1aa842fc34e38236021e65e592777163 | roman-kachanovsky/checkio-python | /solutions/mine/call_to_home.py | 2,476 | 4.21875 | 4 | """ --- Call to Home --- Elementary
Nicola believes that Sophia calls to Home too much and
her phone bill is much too expensive. He took the bills
for Sophia's calls from the last few days and wants
to calculate how much it costs.
The bill is represented as an array with information about
the calls. Help Nicola to calculate the cost for each
of Sophia calls. Each call is represented as a string with date,
time and duration of the call in seconds in the follow format:
"YYYY-MM-DD hh:mm:ss duration"
The date and time in this information are the start of the call.
Space-Time Communications Co. has several rules on how to calculate
the cost of calls:
- First 100 (one hundred) minutes in one day are priced
at 1 coin per minute;
- After 100 minutes in one day, each minute costs 2 coins per minute;
- All calls are rounded up to the nearest minute.
For example 59 sec ~ 1 min, 61 sec ~ 2 min;
- Calls count on the day when they began. For example if a call
was started 2014-01-01 23:59:59, then it counted to 2014-01-01;
Input: Information about calls as a tuple of strings.
Output: The total cost as an integer.
How it is used: This mission will teach you how to parse and analyse
various types data. Sometimes you don't need the full
data and should single out only important fragments.
Precondition: 0 < len(calls) <= 30
0 < call_duration <= 7200
The bill is sorted by datetime.
"""
def my_solution(calls):
calls = [i.split() for i in calls]
curr_day, minutes = '', []
for c in calls:
if curr_day == c[0]:
minutes[-1] += int(c[-1]) // 60 + (int(c[-1]) % 60 > 0)
else:
minutes.append(int(c[-1]) // 60 + (int(c[-1]) % 60 > 0))
curr_day = c[0]
return sum([100 + (k - 100) * 2 if k >= 100 else k for k in minutes])
def sim0000_solution(calls):
from collections import Counter
db = Counter()
for call in calls:
day, time, duration = call.split()
db[day] += (int(duration) + 59) // 60
return sum(min if min < 100 else 2 * min - 100 for min in db.values())
def saklar13_solution(calls):
days = {}
for call in calls:
day, _, duration = call.split()
duration = (int(duration) + 59) // 60
days[day] = days.get(day, 0) + duration
return sum(max(x, x * 2 - 100) for x in days.values())
| true |
f0fd90d791ce8335c0f964334db2483c109c7fec | roman-kachanovsky/checkio-python | /solutions/home/cipher_map.py | 2,940 | 4.1875 | 4 | """ --- Cipher Map --- Simple
Help Sofia write a decrypter for the passwords that Nikola will
encrypt through the cipher map. A cipher grille is a 4x4 square
of paper with four windows cut out. Placing the grille on a paper
sheet of the same size, the encoder writes down the first four
symbols of his password inside the windows (see fig. below).
After that, the encoder turns the grille 90 degrees clockwise.
The symbols written earlier become hidden under the grille and
clean paper appears inside the windows. The encoder then writes
down the next four symbols of the password in the windows and
turns the grille 90 degrees again. Then, they write down
the following four symbols and turns the grille once more.
Lastly, they write down the final four symbols of the password.
Without the same cipher grille, it is difficult to discern
the password from the resulting square comprised of 16 symbols.
Thus, the encoder can be confident that no hooligan will easily
gain access to the locked door.
Write a module that enables the robots to easily recall their
passwords through codes when they return home.
The cipher grille and the ciphered password are represented
as an array (tuple) of strings.
Input: A cipher grille and a ciphered password
as a tuples of strings.
Output: The password as a string.
How it is used: Here you can learn how to work with 2D
arrays. You also get to learn about
the ancient Grille Cipher, a technique
of encoding messages which has been used
for half a millenium. The earliest known
description of the grille cipher comes
from the Italian mathematician,
Girolamo Cardano in 1550.
Precondition: len(cipher_grille) == 4
len(ciphered_password) == 4
all(len(row) == 4 for row in ciphered_password)
all(len(row) == 4 for row in cipher_grille)
all(all(ch in string.ascii_lowercase for ch in row)
for row in ciphered_password)
all(all(ch == "X" or ch == "." for ch in row)
for row in cipher_grille)
"""
def my_solution(grille, text):
result = ''
for _ in xrange(4):
result += ''.join(map(lambda x, y: y if x == 'X' else '',
''.join(grille), ''.join(text)))
grille = [''.join(r) for r in zip(*grille[::-1])]
return result
def veky_solution(grill, cypher):
password = ''
for _ in grill:
for grill_row, cypher_row in zip(grill, cypher):
for grill_letter, cypher_letter in zip(grill_row, cypher_row):
if grill_letter == 'X':
password += cypher_letter
row1, row2, row3, row4 = grill
grill = tuple(zip(row4, row3, row2, row1))
return password
| true |
db5673deefd527a8d6f54102f0b758fd00070777 | roman-kachanovsky/checkio-python | /solutions/mine/count_inversion.py | 942 | 4.4375 | 4 | """ --- Count Inversion --- Simple
You are given a sequence of unique numbers and you should count
the number of inversions in this sequence.
Input: A sequence as a tuple of integers.
Output: The inversion number as an integer.
How it is used: In this mission you will get to experience
the wonder of nested loops, that is of course,
if you don't use advanced algorithms.
Precondition: 2 < len(sequence) < 200
len(sequence) == len(set(sequence))
all(-100 < x < 100 for x in sequence)
"""
def my_solution(s):
return sum(x > y for x in s for y in s[s.index(x):])
def bukebuer_solutiin(sequence):
return sum(sum(m < n for m in sequence[i + 1:]) for i, n in enumerate(sequence))
def gyahun_dash_solution(sequence):
from itertools import combinations
return sum(x > y for x, y in combinations(sequence, 2))
| true |
254950299ae7315540091bbedb56187f2bee55f0 | aluramh/DailyCodingProblems | /DailyCodingProblems/problem29.py | 1,327 | 4.1875 | 4 | # This is your coding interview problem for today.
# This problem was asked by Amazon.
# Run-length encoding is a fast and simple method of encoding strings.
# The basic idea is to represent repeated successive characters as a single
# count and character.
# For example, the string "AAAABBBCCDAA" would be encoded as "4A 3B 2C 1D 2A".
# Implement run-length encoding and decoding.
# You can assume the string to be encoded have no digits and consists solely of alphabetic characters.
# You can assume the string to be decoded is valid.
def decode(chars):
final = ''
cumulative = 0
for i in enumerate(chars):
# Empty cumulative. Start a new one.
if (cumulative == 0):
cumulative += 1
else:
if chars[i] == chars[i - 1]:
cumulative += 1
else:
final += '{}{}'.format(cumulative, chars[i - 1])
cumulative = 1
# Handle final item
size = len(chars)
final += '{}{}'.format(cumulative, chars[size - 1])
return final
try:
assert decode('AAAABBBCCDAA') == '4A3B2C1D2A'
print('Success!')
assert decode('AAAABBBCCDAAZ') == '4A3B2C1D2A1Z'
print('Success!')
# INVALID CASE
# assert decode('') == ''
# print('Success!')
except AssertionError:
print('Failed!')
| true |
5a29934a4947933481f6c9ee009069639582ba46 | tangml961025/learn_python | /map.py | 419 | 4.25 | 4 | """
Map会将一个函数映射到一个输入列表的所有元素上。
规范:
map(function_to_apply, list_of_inputs)
"""
items = [1, 2, 3, 4, 5]
squared = []
for i in items:
squared.append(i**2)
print(squared)
# 可以进化为
def func_squared(x):
return x**2
squared_pre = list(map(func_squared, items))
print(squared_pre)
# 或者
squared_pre_1 = list(map(lambda x:x**2, items))
print(squared_pre_1) | false |
f469304deb48ba6bd2b07a713dc41909129a830e | cmjagtap/Algorithms_and_DS | /recursion/reverse.py | 220 | 4.125 | 4 | #Reverse using recursion
def Reverse(data,start,stop):
if start<stop-1:
data[start],data[stop-1]=data[stop-1],data[start]
Reverse(data,start+1,stop-1)
data=range(1,10)
print data
Reverse(data,0,len(data))
print data | true |
c4cb54f980a45f593d4fddbe66dd1dcff7a13848 | cmjagtap/Algorithms_and_DS | /strings/combinationsWithInbuilt.py | 369 | 4.125 | 4 | # You are given a string .
# Your task is to print all possible size replacement combinations of the string in lexicographic sorted order.
# Sample Input:
# HACK 2
from itertools import combinations_with_replacement
def combinations(string,k):
temp=[]
comb=combinations_with_replacement(sorted(string),k)
for x in comb:
print ("".join(x))
combinations("abc",3) | true |
fc26537be41ae42f62a2fbef28e09e4836b60599 | rodpoblete/practice_python | /decode_web_page_two.py | 1,541 | 4.375 | 4 | """Using the requests and BeautifulSoup Python libraries, print to the screen the full text of the article on this
website: http://www.vanityfair.com/society/2014/06/monica-lewinsky-humiliation-culture.
The article is long, so it is split up between 4 pages. Your task is to print out the text to the screen so that you
can read the full article without having to click any buttons.
(Hint: The post here describes in detail how to use the BeautifulSoup and requests libraries through the solution of
the exercise posted here.)
This will just print the full text of the article to the screen. It will not make it easy to read, so next exercise
we will learn how to write this text to a .txt file. """
import requests
from bs4 import BeautifulSoup
def run():
url = (
"http://www.vanityfair.com/society/2014/06/monica-lewinsky-humiliation-culture"
)
r = requests.get(url)
r_html = r.text
soup = BeautifulSoup(r_html, "html.parser")
article_container = soup.find_all("div", class_="article__body")
for index in range(0, len(article_container) + 1):
for content in range(0, len(article_container[index].contents)):
print(article_container[index].contents[content].get_text())
# for article_content in soup.find_all("div", class_="article__body"):
# if article_content.p:
# print(article_content.p.text)
# else:
# print(article_content.contents[0]) # Falta más anidamiento para llegar al contenido
if __name__ == "__main__":
run()
| true |
3822e6ce8e516a239ab39c06eb2298b7ab674729 | rodpoblete/practice_python | /reverse_word_order.py | 725 | 4.40625 | 4 | """Write a program (using functions!) that asks the user for a long string containing multiple words. Print back to
the user the same string, except with the words in backwards order. For example, say I type the string:
My name is Michele
Then I would see the string:
Michele is name My}
shown back to me."""
def run(words):
"""Ask the user for long string containing multiple words and print back the user in backwards order."""
split_words = words.split(" ")
reversed_words = [word for word in reversed(split_words)]
sentence = " ".join([str(word) for word in reversed_words])
return print(sentence)
if __name__ == "__main__":
user_string = input("Enter a words: ")
run(user_string)
| true |
e0dc6ce23c8da182cce5e6b6c87d48a23336ebf2 | EndaLi/exercise_inbook | /需要调试的文件/word_count.py | 769 | 4.21875 | 4 | def count_words(filename):
try:
with open(filename) as f_obj:
contents = f_obj.read()
except FileNotFoundError:
pass
#msg = "sorry,the file " + filename + " does not exist."
#print(msg)
else:
words = contents.split()
num_words = len(words)
print("\nThe file %s has about %d words." %(filename,num_words))
word_str = ''
word_name = 'sb'
for each_word in words:
word_str += each_word
count_words = word_str.lower().count(word_name)
print("The file has %d \"%s\"" % (count_words,word_name))
filenames = ['alice.txt','siddhartha.txt','moby_dick.txt','little_women.txt']
for filename in filenames:
count_words(filename)
| true |
25e02da61259ae477adbe6bf13ee214f71c4a8b0 | JacksonYu92/tip-calculator | /main.py | 362 | 4.28125 | 4 | print("Welcome to the tip calculator!")
bill = float(input("What was the total bill? $" ))
tip = int(input("How much tip would you like to give? 10, 12, or 15? "))
people = int(input("How many people to split the bill? "))
bill_for_individual = bill * ((tip/100)+1) / people
final = "{:.2f}".format(bill_for_individual)
print(f"Each person should pay: ${final}") | true |
346f61c266e60f57b4a42f189849ed7ca87f038b | yazzzz/MIT | /primes.py | 1,305 | 4.125 | 4 | #!/usr/bin/python
# file:///Users/ykhan/hackbright/code/mit/6-00-fall-2008/contents/assignments/pset1a.pdf
"""pset 1, problem 1: Write a program that computes and prints the 1000th prime number. """
import math
def prime1000():
possible_primes = [2, 3, 5, 7] + range (3, 1000)
for number in range (3, 1000):
if number % 2 == 0 or number % 3 == 0 or number % 7 == 0 or number % 5 == 0:
possible_primes.remove(number)
return possible_primes[-1]
#print "the 1000th prime number is", prime1000()
"""
pset1, problem 2: Write a program that computes the sum of the logarithms of all the primes from 2 to some
number n, and print out the sum of the logs of the primes, the number n, and the ratio of these
two quantities. Test this for different values of n.
"""
def primeProduct(n):
possible_primes = [2, 3, 5, 7] + range (3, n)
for number in range (3, n):
if number % 2 == 0 or number % 3 == 0 or number % 7 == 0 or number % 5 == 0 or number % 11 == 0 or number % 13 == 0:
possible_primes.remove(number)
#now have list of primes up to n
print len(possible_primes),possible_primes
result = 0
for number in possible_primes:
result += math.log(number)
print number, result/number
print primeProduct(300)
| true |
349b1ef2b3b1cbe3486f986022baaf1ee7186f2d | gunguard/EEKozhanova | /homework_3/Homework_3.py | 1,215 | 4.1875 | 4 | print("Введите числа:")
print("a=")
a=float(input())
print("b=")
b=float(input())
print("c=")
c=float(input())
if a==a//1 and b==b//1 and c==c//1:
if b == 0:
print("Действие \"Нахождение остатка от деления\" не имеет смысла")
else:
if a % b == c:
print("Числа обладают свойством: a даёт остаток c при делении на b")
else:
print("Числа не обладают свойством: a даёт остаток c при делении на b")
else: print("Действие \"Нахождение остатка от деления\" не имеет смысла")
if a==0:
print("Действие \"Нахождение решения линейного уравнения ax + b = 0\" не имеет смысла")
else:
if c==-b/a:
print("Числа обладают свойством: c является решением линейного уравнения ax + b = 0")
else:
print("Числа не обладают свойством: c является решением линейного уравнения ax + b = 0") | false |
18f3b0ee8f6cdcb94622d8e4397d2507c1e3dd7d | abarciauskas-bgse/code_kata | /cracking_the_coding_interview/chapter_8/8_1_fibonacci.py | 991 | 4.4375 | 4 | # Write a method to generate the nth Fibonacci number.
# Following the recommended approach:
# 1. What is the subproblem?
# Adding two numbers
# 2. Solve for f(0): fib(0): return None
# 3. Solve for f(1): fib(1): return 1
# 4. Solve for f(2): fib(2): return fib(1) + 1
# 5. Understand how to use f(2) for f(3): f(3) = f(2) + sum(all previous numbers)
# 6. Generalize: Need to keep a list of integers summed so far, and we measure the length of that list,
# so pass the list to every recursive call plus the last sum and the number we are looking for
#
def fibonacci(n):
if n == 0: return None
if n == 1: return [1]
numbers_so_far = [1, 1]
return add_fib_int(n, numbers_so_far, 0)
def add_fib_int(n, numbers_so_far, last_sum):
if n > len(numbers_so_far):
last_sum = numbers_so_far[-1] + numbers_so_far[len(numbers_so_far)-2]
numbers_so_far.append(last_sum)
add_fib_int(n, numbers_so_far, last_sum)
return numbers_so_far
print fibonacci(2)
| true |
7fb6ac0d86b25f138efe1a592cfd6746268c942c | Vostbur/cracking-the-coding-interview-6th | /python/chapter_3/01_three_stacks.py | 1,969 | 4.125 | 4 | # Опишите, как бы вы использовали один одномерный массив для реализации
# трех стеков
class MultiStack:
def __init__(self, stack_size):
self.number_of_stacks = 3
self.stack = [0] * (self.number_of_stacks * stack_size)
self.sizes = [0] * self.number_of_stacks
self.stack_size = stack_size
def __str__(self):
return (
f"number_of_stacks={self.number_of_stacks}\n"
f"stack={self.stack}\n"
f"sizes={self.sizes}\n"
f"stack_size={self.stack_size}\n"
)
def push(self, stack_num, value):
if self.is_full(stack_num):
raise Exception("Stack is full")
self.sizes[stack_num] += 1
self.stack[self.index(stack_num)] = value
def pop(self, stack_num):
if self.is_empty(stack_num):
raise Exception("Stack is empty")
ind = self.index(stack_num)
ret, self.stack[ind] = self.stack[ind], 0
self.sizes[stack_num] -= 1
return ret
def peek(self, stack_num):
if self.is_empty(stack_num):
raise Exception("Stack is empty")
return self.stack[self.index(stack_num)]
def is_empty(self, stack_num):
return self.sizes[stack_num] == 0
def is_full(self, stack_num):
return self.sizes[stack_num] == self.stack_size
def index(self, stack_num):
return stack_num * self.stack_size + self.sizes[stack_num] - 1
if __name__ == "__main__":
s = MultiStack(2)
s.push(0, 1)
s.push(0, 2)
print(s)
try:
s.push(0, 3)
except Exception as e:
print(e)
print(s.is_empty(1))
s.push(1, 10)
s.push(1, 20)
s.push(2, 100)
s.push(2, 200)
print(s)
print(s.peek(2))
print(s.pop(1))
print(s.pop(1))
try:
s.pop(1)
except Exception as e:
print(e)
print(s.is_empty(1))
print(s)
| false |
d4671867841e307994aaddb2bbec3faf5fd755e8 | JZY11/mypro01 | /mypython03.py | 1,384 | 4.1875 | 4 | '''
多分支选择结构:
if 条件表达式1:
语句1/语句块1
elif 条件表达式2:
语句2/语句块2
.
.
.
elif 条件表达式n:
语句n/语句块n
[else: 方括号表示可选的意思
语句n+1/语句块n+1
]
'''
# 练习: 输入一个学生色成绩,将其转化为简单描述:不及格(小于60)、及格(60-79)、良好(80-89)、优秀(90-100)
# 方法一(使用完整的条件表达式)
# scope = int(input("请输入考试的具体分数"))
# grade = ''
# if(scope < 60):
# grade = "不及格"
# if(60 <= scope < 80):
# grade = "及格"
# if(80 <= scope < 90):
# grade = "良好"
# if(90 <= scope <= 100):
# grade = "优秀"
# print("分数是{0},等级是{1}".format(scope,grade))
# 方法二(利用多分支结构) 多分支结构,几个分支之间是有逻辑关系的,不能随意颠倒顺序
scope = int(input("请输入考试的具体分数:"))
grade = ''
if scope < 60:
grade = "不及格"
elif scope < 80:
grade = "及格"
elif scope < 90:
grade = "良好"
elif scope <= 100:
grade = "优秀"
print("分数是{0},等级是{1}".format(scope,grade)) # {0}、{1} 是两个占位符,调用了字符串的format()方法来对字符串进行格式化
| false |
48ce3b1e37d0e6031e24ab1739933eae09024bc1 | RaphOfficial/CollatzConjecture | /main.py | 1,539 | 4.125 | 4 | # Includes
import matplotlib.pyplot as plt
from libs import utils
from libs import loops
def make_line_chart(x_list, y_list):
plt.plot(x_list, y_list)
plt.show()
def calculate_collatz_conjecture(seed):
if utils.is_positive(seed): # If is positive
numb_sequence = loops.positive_integer(seed)
else: # If is negative or 0
numb_sequence = loops.negative_integer(seed)
# Vars
sequence_details = loops.get_details(numb_sequence, True)
y_axis = sequence_details[2] # Just a list with growing numbers from 1 to final number (amount) e.g. If amount
# is 6 this will be x_axis: 1, 2, 3, 4, 5, 6.
biggest_number = sequence_details[1] # Biggest number inside x (ignoring negative signs)
numbers_amount = sequence_details[0] # amount of numbers inside x
# X is the numb sequence
chart_details = [numb_sequence, y_axis]
output = [numbers_amount, biggest_number, chart_details]
return output
if __name__ == "__main__":
numb = int(input('Please choose any integer: '))
result = calculate_collatz_conjecture(numb)
# Vars
chart_details_result = result[2]
x = chart_details_result[0]
y = chart_details_result[1]
biggest_result_number = result[1]
numbers_result_amount = result[0]
print('This is the biggest number in the sequence: ' + str(biggest_result_number))
print('This is the total amount of numbers in your sequence: ' + str(numbers_result_amount))
make_line_chart(y, x)
| true |
1a590e8eb9b830647121cd960611b3f959e83b9a | crazyuploader/Python | /calc.py | 1,795 | 4.40625 | 4 | #!/usr/bin/env python3
__author__ = "Jugal Kishore"
__version__ = "1.1"
print("///A Simple Calculator///")
while 1:
num_a = input("\nEnter First Number: ")
num_b = input("\nEnter Second Number: ")
print("\nOptions: -")
print("+ for Addition")
print("- for Substraction")
print("* for Multiplication")
print("/ for Division")
print("% for Modulus")
print("Anything else to exit!")
choice = input("\nChoice: ")
if choice == "+":
print(
"\nAddition of {0} and {1} is = {2}".format(
num_a, num_b, float(num_a) + float(num_b)
)
)
elif choice == "-":
print(
"\nSubtraction of {0} and {1} is = {2}".format(
num_a, num_b, float(num_a) - float(num_b)
)
)
elif choice == "*":
print(
"\nMultiplication of {0} and {1} is = {2}".format(
num_a, num_b, float(num_a) * float(num_b)
)
)
elif choice == "/":
if num_b == "0":
print("\nYou can't divide '{0}' by zero.".format(num_a))
else:
print(
"\nDivison of {0} and {1} is = {2}".format(
num_a, num_b, float(num_a) / float(num_b)
)
)
elif choice == "%":
if num_b == "0":
print("\nYou can't divide '{0}' by zero.".format(num_a))
else:
print(
"\nModulus of {0} and {1} is = {2}".format(
num_a, num_b, round(float(num_a) % float(num_b), 3)
)
)
else:
print("Uh-Oh, you decided to exit.")
print("Exiting!")
break
print("\nCreated by Jugal Kishore -- 2020")
# Run it online at https://python.jugalkishore.repl.run/
| false |
bb991f3af669693bc217da269475efee5389bd35 | klipanmali/datastructures | /py/datastructuresGraphDfsStack.py | 1,567 | 4.25 | 4 | # Python3 program to print DFS traversal
# from a given given graph, version using recursion
from collections import defaultdict
from queue import LifoQueue
class Graph:
def __init__(self):
self.graph = defaultdict(list)
def add_edge(self,begin_vertex, end_vertex):
self.graph[begin_vertex].append(end_vertex)
def dfs_util(self,start_vertex,visited_vertices):
stack = LifoQueue()
stack.put(start_vertex)
while not stack.empty():
vertex = stack.get()
if vertex not in visited_vertices:
print(vertex, end=" ")
visited_vertices.add(vertex)
edges = self.graph[vertex]
for end_vertex in edges:
if end_vertex not in visited_vertices:
stack.put(end_vertex)
def dfs_stack(self,start_vertex):
visited_vertices = set()
self.dfs_util(start_vertex,visited_vertices)
def main():
# solution using stack
# ---0------>1
# | |\ /
# | | /
# | | /
# -->2<- 3<---
# --------> | |
# ----
# Create a graph given in
# the above diagram
g = Graph()
g.add_edge(0, 1)
g.add_edge(0, 2)
g.add_edge(1, 2)
g.add_edge(2, 0)
g.add_edge(2, 3)
g.add_edge(3, 3)
start_vertex = 2
print("Following is DFS from (starting from vertex",start_vertex, ")")
g.dfs_stack(start_vertex)
if __name__ == '__main__':
main() | true |
c6807ddea7a7f85f610d03dc70da5135f02edf63 | klipanmali/datastructures | /py/datastructuresGraphEulerianDirectedHierholzer.py | 2,715 | 4.40625 | 4 | # Python3 program to print Eulerian circuit in given
# directed graph using Hierholzer algorithm
# The algorithm assumes that the given graph has a Eulerian cycle.
from collections import defaultdict
class Graph:
def __init__(self, num_of_v):
self.num_of_v = num_of_v
self.adjacents = defaultdict(list)
self.time = 0
def add_edge(self, start_v, end_v):
self.adjacents[start_v].append(end_v)
def print_circuit(self):
# adj represents the adjacency list of
# the directed graph
if len(self.adjacents) == 0:
return # empty graph
# Maintain a stack to keep vertices
# We can start from any vertex, here we start with 0
curr_path = [0]
# list to store final circuit
circuit = []
while curr_path:
curr_v = curr_path[-1]
# If there's remaining edge in adjacency list
# of the current vertex
if self.adjacents[curr_v]:
# Find and remove the next vertex that is
# adjacent to the current vertex
next_v = self.adjacents[curr_v].pop()
# Push the new vertex to the stack
curr_path.append(next_v)
# back-track to find remaining circuit
else:
# Remove the current vertex from the current path and
# put it in the curcuit
circuit.append(curr_path.pop())
# we've got the circuit, now print it in reverse
while(circuit):
i = circuit.pop()
print(i, end="")
if i:
print(" -> ", end="")
print()
if __name__ == "__main__":
# Input Graph 1
g1 = Graph(3)
# 0-->1
# A |
# | |
# 2<--+
g1.add_edge(0, 1)
g1.add_edge(1, 2)
g1.add_edge(2, 0)
print("graph1")
g1.print_circuit()
# Input Graph 2
g2 = Graph(7)
# +-------------------+
# | +-->6--------+ |
# v/ v |
# 0<---2--->3--->4--->5
# | > < |
# | / \ |
# v / +------+
# 1
#
g2.add_edge(0, 1)
g2.add_edge(0, 6)
g2.add_edge(1, 2)
g2.add_edge(2, 0)
g2.add_edge(2, 3)
g2.add_edge(3, 4)
g2.add_edge(4, 2)
g2.add_edge(4, 5)
g2.add_edge(5, 0)
g2.add_edge(6, 4)
print("graph2")
g2.print_circuit()
# uuupppssss,
# first you need to check if there is Eulerian path off eulerian cycle
g3 = Graph(4)
# 0--->1--->3
# A /
# | /
# 2<+
g3.add_edge(0, 1)
g3.add_edge(1, 2)
g3.add_edge(2, 0)
g3.add_edge(1, 3)
print("graph3")
g3.print_circuit()
| true |
791931eefee9ca2bd234c192872eaef33381aebc | quinn-dougherty/DS-Unit-3-Sprint-1-Software-Engineering | /tmp/aquarium.py | 1,701 | 4.5625 | 5 | #!/usr/bin/env python
'''python module for simulating aquariums'''
from collections import defaultdict
class Aquarium:
'''Example class to model an aquarium'''
def __init__(self, name="Pierre's Underwater World"):
self.name = name
self.fish = defaultdict(int)
def add_fish(self,fish_species):
'''incrementing the count for fish_species in fish dict'''
assert isinstance(fish_species, str)
self.fish[fish_species] += 1
pass
def generate_fish_report(self):
'''iterate over and summarize self.fish dict'''
for species, count in self.fish.items():
print(f'{species}: {count}')
class Habitat:
def __init__(self, name="some habitat"):
self.name = name
self.animals = defaultdict(int)
self.plants = defaultdict(int)
def generate_animal_report(self):
print('ANIMALS IN ' + self.name)
for species, count in self.animals.items():
print(f'{species}: {count}')
def generate_plant_report(self):
print('PLANTS IN ' + self.name)
for species, count in self.plants.items():
print(f'{species}: {count}')
def add_animals(self,animal_species):
'''incrementing the count for fish_species in fish dict'''
assert isinstance(animal_species, str)
self.animals[animal_species] += 1
pass
def add_plants(self,plant_species):
'''incrementing the count for plant_species in plants dict'''
assert isinstance(plant_species, str)
self.plants[plant_species] += 1
pass
class Zoo(Habitat):
'''Class to represent data and behavior of a zoo'''
pass
| true |
44d5481d6aa2663f0f1094807cad6c8591781007 | hankli2000/python-algorithm | /traversal.py | 1,427 | 4.15625 | 4 | class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def printInorder(root):
'''inorder (left, root, right) '''
if root:
printInorder(root.left)
print(root.val)
print(root.right)
def printPostOrder(root):
'''postorder (left, right, root)'''
if root:
printPostOrder(root.left)
printPostOrder(root.right)
print(root.val)
def printPreOrder(root):
'''preorder (root, left, right) '''
if root:
print(root.val)
printPreOrder(root.left)
printPreOrder(root.right)
def printLeverOrder(root):
'''BFS, print all nodes in one lever, then go to next level '''
if root:
q = deque()
q.append(root)
if q:
n = q.popleft()
print(n.val)
q.append(n.left)
q.append(n.right)
def printOneLevelNodes(root, level):
if root is None:
return
if level ==1:
print(root.val, end=' ')
elif level > 1:
printOneLevelNodes(root.left, level - 1)
printOneLevelNodes(root.right, level - 1)
def height(root):
if root is None:
return 0
lheight = height(root.left)
rheight = height(root.right)
height = max(lheight, rheight) + 1
# Driver code
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
print "Preorder traversal of binary tree is"
printPreorder(root)
print "\nInorder traversal of binary tree is"
printInorder(root)
print "\nPostorder traversal of binary tree is"
printPostorder(root)
| true |
aceec6a88d8143e10713ac4e8f6c142441c06d57 | mede0029/Python-Programs | /05 - Converting_Files/Lab9B.py | 725 | 4.25 | 4 | ## The two text files 2000_BoysNames.txt and 2000_GirlsNames.txt list the popularity of boys names and girls names in 2000.
## The format of the file is simple, one line per entry with the name followed by a space followed by the number of children
## carrying that name. You must write a python program that reads each text file then converts it into a csv format: "name",count
## then saves the entry in a csv file. The output csv file must include the following header as its first line:
## "First Name","Count"
import csv
texto=open("boys.txt", "r")
excel=open("boys.csv", "w")
excel.write("Coluna 1, Coluna 2\n")
for line in texto:
l=line.split(' ')
excel.write(l[0]+","+l[1])
texto.close()
excel.close()
| true |
835268e4003b840f08731c2a669bee84fceb3220 | zheng-shaojie/learn | /python/iterator/src/entrust.py | 874 | 4.1875 | 4 | # 委托迭代
# 使自定义容器也可以进行迭代操作,解决方法:定义一个__iter__()方法
class Node:
def __init__(self, value):
self.value = value
self.children = []
def __repr__(self):
return 'Node {!r}'.format(self.value)
def add_child(self, node):
self.children.append(node)
def __iter__(self):
return iter(self.children)
# 实现自定义对象的迭代协议
def depth_first(self):
yield self
for c in self:
yield from c.depth_first()
if __name__ == '__main__':
root = Node(0)
children1 = Node(1)
children2 = Node(2)
root.add_child(children1)
root.add_child(children2)
children2.add_child(Node(3))
children1.add_child(Node(4))
children2.add_child(Node(5))
for ch in root.depth_first():
print(ch, end='\n')
| false |
f7aee9c1478a8631c187efb4a5b69f576951cf2e | bkalcho/think-python | /print_hist.py | 392 | 4.15625 | 4 | # Author: Bojan G. Kalicanin
# Date: 17-Oct-2016
# Dictionaries have a method called keys that returns the keys of the
# dictionary, in no particular order, as a list. Modify print_hist to
# print the keys and their values in alphabetical order.
import histogram
def print_hist(d):
k = d.keys()
for c in sorted(k):
print(c, d[c])
a = histogram.histogram('banana')
print_hist(a) | true |
14be9204764bd2f8390e924f9967a3b35313255b | bkalcho/think-python | /czech_flag.py | 650 | 4.21875 | 4 | # Author: Bojan G. Kalicanin
# Date: 28-Oct-2016
# Write a program that draws the national flag of the Czech Republic.
# Hint: you can draw a polygon like this:
# points = [[-150,-100], [150, 100], [150, -100]]
# canvas.polygon(points, fill='blue')
from swampy.World import World
world = World()
canvas = world.ca(width=500, height=500, background='white')
points1 = [[-150,-100], [-150, 100], [0, 0]]
canvas.polygon(points1, fill='MidnightBlue')
points2 = [[0, 0], [-150, 100], [200, 100], [200, 0]]
canvas.polygon(points2, fill='white')
points3 = [[0, 0], [-150, -100], [200, -100], [200, 0]]
canvas.polygon(points3, fill='red')
world.mainloop() | true |
95f176f39becb47df908227c5721cfba59cece32 | bkalcho/think-python | /most_frequent.py | 702 | 4.21875 | 4 | # Author: Bojan G. Kalicanin
# Date: 18-Oct-2016
# Write a function called most_frequent that takes a string and prints
# the letters in decreasing order of frequency. Find text samples from
# several different languages and see how letter frequency varies
# between languages.
def histogram(string):
h = {}
for i in string:
h[i] = h.get(i, 0) + 1
return h
def most_frequent(string):
h = histogram(string)
t = []
for c, f in h.items():
t.append((f, c))
t.sort(reverse=True)
k = []
for f, c in t:
k.append(c)
return k
if __name__ == '__main__':
string = open('words.txt').read()
t = most_frequent(string)
for i in t:
print(i) | true |
502deea46276a5a0d7b96e4bb25c18937e9e99fb | IlyaSavitckiy/python-project-lvl1 | /brain_games/games/calc.py | 1,190 | 4.21875 | 4 | """Logic of the brain calc game."""
from operator import add, mul, sub
from random import choice, randint
DESCRIPTION = 'What is the result of the expression?'
OPERATORS = ('+', '-', '*')
def calculate(num_one, num_two, operator):
"""Calculate a result of an operation with 2 numbers using operator.
Args:
num_one: some number
num_two: some number
operator: some operator from OPERATORS
Returns:
result of the operation
"""
if operator == '+':
return add(num_one, num_two)
elif operator == '-':
return sub(num_one, num_two)
elif operator == '*':
return mul(num_one, num_two)
def prepare_question_and_calculate():
"""Prepare a question to user and calculate and return the correct answer.
Returns:
correct_answer: string-result of calculation with two ramdom numbers
question: string with prepared question
"""
num_one = randint(1, 100)
num_two = randint(1, 100)
operator = choice(OPERATORS)
correct_answer = str(calculate(num_one, num_two, operator))
question = '{0} {2} {1}'.format(num_one, num_two, operator)
return (correct_answer, question)
| true |
8be580780758466439bf4477e5b04c6bcaca9733 | FabianCaceresH/tarea_profundizacion_sesion_3 | /profundización/ejercicio2_profundización.py | 1,244 | 4.375 | 4 | # Condicionales [Python]
# Ejercicios de profundización
# Autor: Inove Coding School
# Version: 2.0
# NOTA:
# Estos ejercicios son de mayor dificultad que los de clase y práctica.
# Están pensados para aquellos con conocimientos previo o que dispongan
# de mucho más tiempo para abordar estos temas por su cuenta.
# Requiere mayor tiempo de dedicación e investigación autodidacta.
# IMPORTANTE: NO borrar los comentarios en VERDE o NARANJA
# Ejercicios de práctica con números
a = int(input("ingrese el primer numero:"))
b = int(input("ingrese el segundo numero:"))
c = int(input("ingrese el tercer numero:"))
if a % 2 == 0:
print("el primer numero es par")
else:
print("el primer numero es impar")
if b % 2 == 0:
print("el segundo numero es par")
else:
print("el segundo numero es impar")
if c % 2 == 0:
print("el tercer numero es par")
else:
print("el tercer numero es impar")
'''
Enunciado:
Realice un programa que solicite el ingreso de tres números
enteros, y luego en cada caso informe si el número es par
o impar.
Para cada caso imprimir el resultado en pantalla.
'''
print('Ejercicios de práctica con números')
# Empezar aquí la resolución del ejercicio | false |
9b58c06d0657d3bc3ff4043bbfee622c48c7cbb1 | XinyingWu/Data-Structure-in-Python | /RadixSort.py | 1,032 | 4.15625 | 4 |
from random import randint
def RadixSort(list1,d):
for k in range(d):# k is used to check each digit, ex, 987, k=0, check 7; k=1,check 80; k=2, check 900
s=[[] for i in range(10)]#because for each digit, there are 10 options from 0 to 9, so create 10 lists.
print(s)
for i in list1: #check each element in list1
index_s=int(i/(10**k)%10) # ex, k=0, i/(10**k) move i to the current check digit(个位)
# k=1, 10**k=10^1=10, move i to 十位数...
# %10 mod,keep the current digit.
## print(int(index_s))
s[index_s].append(i) #check each value of each digits
print(s)
list1=[j for i in s for j in i]
return list1
if __name__ == '__main__':
TestList=[randint(1,999) for i in range(10)]
print(TestList)
SortList=RadixSort(TestList,3) # 3 means how many digits for the largest value
print(SortList)
| false |
1d629f52543125762317447b89cf6e470f4ee3b7 | Jnrolfe/LearningPython | /ControlExercises.py | 800 | 4.25 | 4 | #ControlExercises.py
#by James Rolfe
#This program shows how to use various control statements in Python3
'''
userInput = input('Enter 1 or 2: ')
if userInput == "1":
print ("Hello World")
print ("How are you?")
elif userInput == "2":
print("Python3")
else:
print("stuff")
#declaring enum or list
pets = ['cats', 'dogs', 'rabbits', 'hamsters']
#for loop iterates through pets enum
for a in pets:
print(a)
#will print all integers from 0 to 20
for i in range(21):
print(i)
#will print all EVEN integers from 0 to 20
for i in range(0,21,2):
print (i)
#var declaration
j = 0
for i in range(5):
j += 2 #adds 2 to j
print ('\ni = ', i, ', j = ', j)
if j == 6:
continue #skips rest of block
print('I will be skipped if j = 6')
'''
try:
answer = 1/0
print(answer)
except:
print('ERROR') | true |
ba4b49d9dd7863d67aa7bc01a2c484c8083024cd | euridesoliv3iradasilveira/Exercicios | /oi.py | 805 | 4.21875 | 4 | #Escreva um Programa que faça o computador "pensar" em um número inteiro entre 0 e 5 e peça para o usuário tentar descobrir qual foi o número escolhido pelo computador.O progrma deverá escrever na tela se o usuário venceu ou perdeu
#codigo ansi para colocar cor ex:/033[0:ex:style,33ex:text,44back m
from time import sleep
from random import randint
computador = randint(0,100) #faz o computador fazer "pensar"
print("=="*20)
print('vou pensar em um número entre 0 e 5. Tente advinhar...')
print("=="*20)
jogador= int(input('em que número eu pensei? '))#Jogador tentar advinhar
print('\033[36mPROCESSANDO... \033]m ')
sleep(2)#para dar tempo antes do programa responder
if jogador == computador:
print('Vc ganhou!!')
else:
print('vc perdeu. eu pensei no número {}'.format(computador))
| false |
1be991ee0b91969bc8f30e071eea5fc6b8554761 | kingzLoFitness/pythonCrashCourse | /2023March20SpeedRun_pythonCrashCourseBook/chapter2_variablesAndSimpleDataTypes/ch2_tryItYourself/ch2_tiy_1.py | 623 | 4.375 | 4 | """
Write a separate program to accomplish each of these exercises. Save each program with a filename that follows standard Python conventions, using lowercase letters and underscores, such as simple_message.py and simple_messages.py.
"""
# 2-1. Simple Message: Assign a message to a variable, and then print that message.
myAlias = "kingzlofitness"
print(myAlias)
# 2-2. Simple Messages: Assign a message to a variable, and print that message.
# Then change the value of the variable to a new message, and print the new message.
myAlias2 = "kingzlofitness"
print(myAlias2)
myAlias2 = "racketink"
print(myAlias2)
| true |
06b5ef581bb9b12af640f0bc664cfd0088cf3d0c | kingzLoFitness/pythonCrashCourse | /firstTry/ch6_dictionaries/1_alien.py | 1,851 | 4.21875 | 4 | '''
# a simple Dictionary... am i able to write on iPad Pro 10.5 in pretty fast without my external keyboard?
- effectively they can model real-world situations
game featuring aliens with different colors and point values as stored information
'''
alien_0 = {'color': 'green', 'points': 5}
print(alien_0['color'])
print(alien_0['points'])
print()
print(alien_0)
print()
'''
# Working with Dictionaries
- a collection of key-value pairs
- each key is connected to a value
- and you can use a key to access the value associated with that key
- you can use any object as a value in a dictionary
# accessing value in a dictionary
'''
new_points = alien_0['points']
print(f"You just entered {new_points} points!")
print()
# Adding New Key-Value Pairs
alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)
print("\n")
# Starting with an Empty Dictionary
alien_0 = {}
alien_0['color'] = 'green'
alien_0['points'] = 5
print(alien_0)
print("\n")
# Modifying Values in a Dictionary
alien_0 = {'color': 'green'}
print(f"This alien is {alien_0['color']}.")
alien_0['color'] = 'yellow'
print(f"The alien is now {alien_0['color']}.")
print('\n')
alien_0 = {'x_position': 0, 'y_position': 25, 'speed': 'medium'}
print(f"Original position: {alien_0['x_position']}")
# Move the alien to the right.
# Determine how far to move the alien based on its current speed
if alien_0['speed'] == 'slow':
x_increment = 1
elif alien_0['speed'] == 'medium':
x_increment = 2
else:
# This must be a fast alien
x_increment = 3
# The new position is the old position plus the increment.
alien_0['x_position'] = alien_0['x_position'] + x_increment
print(f"New position: {alien_0['x_position']}")
print("\n")
# Removing Key-Value Pairs
alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
del alien_0['points']
print(alien_0)
| true |
800de065932f535271ca7f6cde0090ab266d69fb | kingzLoFitness/pythonCrashCourse | /firstTry/ch5_ifStatements/tryItYourself/1_tryitYourSelf_5-12.py | 2,673 | 4.21875 | 4 | # Try it Yourself
'''
5-1. Conditional Tests: Write a series of conditional test. Print a statement describing each test and your prediction for the result of each test. Your code should look something like this:
_______________________________________________
car = 'subaru'
print("Is car == 'subaru'? I predict True.")
print(car == 'subaru')
print("\nIs car == 'audi'? I predict False")
print(car == 'audi')
_______________________________________________
- Look closely at your results and make sure you understand why each line evaluates to True of False
- Create at least ten tests. Have at least five tests evaluate to True and another five tests evaluate to False.
'''
program = 'python'
# first test
print("Does program == 'python'? I perdict True.")
print(program == 'python')
# second test
print("Does program == 'javaScript'? I predict True.")
print(program == 'javaScript')
# 2nd Truth third test (4 true and 4 false left to create test)
currentTraining = 'GST'
print("Does my current training == 'GST'? I predict True.")
print(currentTraining == "GST")
# 3rd Truth fourth test
instrument = 'piano'
print("Does practice instrument == 'piano'? I konw it's True.")
print(instrument == 'piano')
# 4th Truth fifth test
instrument = 'guitar'
# 5th Truth sixth test
musicApp = 'yousician'
print("Does practice in musicApp == 'yousician'? This is definately True.")
print(musicApp == 'yousician')
# 2nd False seventh test
myWeightClass = 'lightWeight'
print("Does my weight class == 'heavyWeight'? This is difinately False.")
print(myWeightClass == 'heavyWeight')
# 3rd False eighth test
musicChoice = 'hipHop'
print("My music choice == 'heavyMetal'? This is False.")
print(musicChoice == 'heavyMetal')
# 4th False ninth test
kfwsStatus = 'nonDegreeHolder'
print("My status shows I am a degree holder. This is False.")
print(kfwsStatus == 'degreeHolder')
# 5th False tenth test
retroArch = '32bit'
print("I can run retroArch == 64bit. This is False within Retroid Pocket 2.")
print(retroArch == '64bit')
'''
5-2. More Conditional Tests: You don't have to limit the number of test you create.
- but it seems like there was more than enough to craete
'''
myHair = 'locks'
if myHair != 'bald':
print("You are clearly not bald.")
videoGames = 'missionImpossible'
if videoGames == 'missionImpossible':
print(f"So far you went over Mupen64 Plus and came out and went back in to get back to {videoGames}.")
womenIWannaLove = ['Shantel', 'Alexis', 'Suzette', 'Rosebie']
# Cashier met up with at Local Supermarket
womenJustMet = 'Wilney'
if womenJustMet not in womenIWannaLove:
print(f"{womenJustMet}, are you too young for me?")
| true |
811917b5fbcbde4100e7a3bc4a8da5b45c4fbd1b | kingzLoFitness/pythonCrashCourse | /firstTry/ch4_workingWithLists/3_even_numbers.py | 376 | 4.125 | 4 | '''
Using range() to Make a List of Numbers
- continue (last file is first_number.py)
'''
# pass a third argument to range() (as a stepsize when generating numbers)
# it adds 2 to that value (adding 2 repeatedly until it reaches or passes the end valeu, 11)
# and provide this result as the output: [2, 4, 6, 8, 10]
even_numbers = list(range(2, 11, 2))
print(even_numbers)
| true |
69948da74a24b04164206ae9a89a06b04b773a9f | kingzLoFitness/pythonCrashCourse | /2023March20SpeedRun_pythonCrashCourseBook/chapter2_variablesAndSimpleDataTypes/ch2_tryItYourself/ch2_tiy_3.py | 680 | 4.375 | 4 | '''
Try It Yourself
2-8. Number Eight: Write addition, subtraction, multiplication, and division
operations that each result in the number 8. Be sure to enclose your operations
in print() calls to see the results. You should create four lines that look like this:
print(5+3)
Your output should simply be four lines with the number 8 appearing once
on each line.
2-9. Favorite Number: Use a variable to represent your favorite number. Then,
using that variable, create a message that reveals your favorite number. Print
that message.
'''
# 2-8
print(5+3)
print(11-3)
print(2*4)
print(24/3) # this outputs 8.0 vs. 8
# 2-9
favNum = 9
print(f"My favorite number is {favNum}.")
| true |
f7e246c5ee79be880b0f8c3e415842ed264a4b56 | harishbharatham/Python_Programming_Skills | /Prob13_12.py | 672 | 4.1875 | 4 | from Triangle import Triangle, TriangleError
import sys
s1,s2,s3 = eval(input('Enter the three sides of a triangle:'))
t1 = Triangle(s1,s2,s3)
try:
if((s1+s2 < s3) or (s2+s3 < s1) or (s3+s1 < s2)):
raise TriangleError
except TriangleError:
print('The sides do not form a triangle')
sys.exit()
t1.setColor(input('Enter the color of the triangle:'))
t1.setFilled(bool(eval(input('Enter 1 if the triangle is to be filled else 0:'))))
print('The area of the triangle is', t1.getArea())
print('The perimeter of the triangle is', t1.getPerimeter())
print('The color of the triangle is', t1.getColor())
print('Is the triangle filled:', str(t1.isFilled()))
| true |
9d41b7460d3aadc17f460f05a869b7b16f93d57c | nhat2008/projecteuler-solutions | /pro_014_longest_collatz_sequence.py | 1,332 | 4.21875 | 4 | # The following iterative sequence is defined for the set of positive integers:
#
# n -> n/2 (n is even)
# n -> 3n + 1 (n is odd)
#
# Using the rule above and starting with 13, we generate the following sequence:
#
# 13 -> 40 -> 20 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1
# It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.
#
# Which starting number, under one million, produces the longest chain?
#
# NOTE: Once the chain starts the terms are allowed to go above one million.
history_data = {}
def chain(n):
if n in history_data:
return history_data[n]
if n == 1:
history_data[1] = [1]
return history_data[1]
else:
if n % 2 == 0:
history_data[n] = [n] + chain(n / 2)
return history_data[n]
else:
history_data[n] = [n] + chain(3 * n + 1)
return history_data[n]
def longest_collatz_sequence(limit):
start = 2
max_length = 1
max_num = 1
for i in xrange(limit, start, -1):
chain_list = chain(i)
if len(chain_list) > max_length:
max_length = len(chain_list)
max_num = i
return max_num
print longest_collatz_sequence(1000000)
| true |
d5881da3df86500cb9bc06f7cd226c33afee7dbc | elgeish/Computing-with-Data | /projects/py/chapter6/lists.py | 650 | 4.5 | 4 | a = [1, 2, 3] # list containing three integers
b = [a, "hello"] # list containing a list and a string
b.append(4) # modify existing list by appending an element
print(a)
print(b)
# Example: inserting, removing, and sorting elements
a = [1, 2, 3]
a.insert(1, 100) # insert 100 before index 1
print(a)
a.remove(2) # remove first occurrence of 2
print(a)
a.sort() # sort list
print(a)
a.extend([20, 21, 23]) # extend list with an additional list
print(a)
b = sorted(a)
print(b)
# Example: deleting an element
a = ['hello', ', ', 'world']
print(len(a))
del a[1]
print(len(a))
print(a)
# Example: the + operator
print([1, 2, 3] + [4, 5] + [6])
| true |
c3b0f9ec0681884cc9d6208f91685b4a8f1ca669 | elgeish/Computing-with-Data | /projects/py/chapter6/reading-and-writing-data-in-text-format.py | 579 | 4.53125 | 5 | # Example: read a text file line by line using a for-loop
f = open("mobydick.txt", "r") # open file for reading
words = []
for line in f: # iterate over all lines in file
words += line.split() # append the list of words in line
f.close()
# Example: the with statement
with open("mobydick.txt") as f: # "rt" is the default mode
words = [word for line in f for word in line.split()]
# Example: writing to a file
with open("output.txt", "w") as f:
f.write("first line\n")
f.writelines(["second line\n", "third line\n"])
with open("output.txt") as f:
print(f.read())
| true |
5fee63a5cd16b2a117284a269cc6fdb098720441 | elgeish/Computing-with-Data | /projects/py/chapter6/list-comprehensions.py | 775 | 4.46875 | 4 | from collections import Counter
# Example: a simple, mundane transformation to a list
words = ['apple', 'banana', 'carrot']
modes = []
for word in words:
counter = Counter(word)
# most_common(n) returns a list and the *
# operator expands it before calling append(x)
modes.append(*counter.most_common(1))
print(modes)
# Example: the Pythonic way (using a list comprehension)
print([Counter(w).most_common(1)[0] for w in words])
# Example: select and transform
print([Counter(w).most_common(1)[0] \
for w in words if len(w) > 5])
# Example: mimicing nested for loops and multiple conditionals
x = (0, 1, 2, 7)
y = (9, 0, 5)
print([(a, b) for a in x for b in y if a != 0 and b != 0])
# alternatively
print([(a, b) for a in x if a != 0 for b in y if b != 0])
| true |
e613cdb8563ba38312941d5b5e99877bdef92524 | Yiraneva/python-coding-practice | /Udacity_Python_CompoundDataStructure.py | 1,073 | 4.3125 | 4 | # Quiz: Adding Values to Nested Dictionaries
# Try your hand at working with nested dictionaries. Add another entry, 'is_noble_gas,' to each dictionary in the elements dictionary. After inserting the new entries you should be able to perform these lookups:
# >>> print(elements['hydrogen']['is_noble_gas'])
# False
# >>> print(elements['helium']['is_noble_gas'])
# True
elements = {'hydrogen': {'number': 1, 'weight': 1.00794, 'symbol': 'H'},
'helium': {'number': 2, 'weight': 4.002602, 'symbol': 'He'}}
# todo: Add an 'is_noble_gas' entry to the hydrogen and helium dictionaries
# hint: helium is a noble gas, hydrogen isn't
# hydrogen=elements['hydrogen']
# hydrogen.update({'is_noble_gas': False})
# helium=elements['helium']
# helium.update({'is_noble_gas': True})
# print(elements)
# print(elements['hydrogen']['is_noble_gas'])
# print(elements['helium']['is_noble_gas'])
elements['hydrogen']['is_noble_gas'] = False
elements['helium']['is_noble_gas'] = True
elements['oxgen'] = {"a":1,'b': 2}
# x=elements['hydrogen']\
# print(x)
print(elements) | true |
64e7cbd97a12b3db818622a02a46e89b7d96b46c | yashbhokare/cse576_project_2 | /src/data/formats.py | 1,031 | 4.625 | 5 | """This module contains functions for formatting data.
A formatting function generates a single sentence for the passed task, numbers,
and target. Each function accepts three arguments: the task (task_name) as
defined in config.TASKS, a list of input numbers, and the target value. The
function returns a single sentence as a formatted string. A sample definition
is as follows:
def format_N(task_name: str, nums: List[int], target: int) -> str:
...
"""
from typing import List
def format_1(task_name: str, nums: List[int], target: int) -> str:
"""Returns a sentence with format 1.
Example:
The maximum value among 1, 2, 3, 4, and 5 is 5.
"""
# Stringify the list.
nums_str = ", ".join([str(num) for num in nums[:-1]]) + ", and " + str(nums[-1])
# Generate the sentence
sentence = "The {task} value among {nums_str} is {target}.".format(
task=task_name, nums_str=nums_str, target=target
)
return sentence
# List of all formats
formats = {
'format_1': format_1,
}
| true |
701a16cae4cdc3c3b7c1e23e1b9b27a1e885d98b | Konrad-git-code/Aspp2021-exercises-day4 | /simple_math.py | 2,504 | 4.125 | 4 | """
A collection of simple math operations
"""
def simple_add(a,b):
"""
Addition of two numbers.
Parameters
----------
a : int, float
Number to be added.
b : int, float
Number to be added.
Returns
----------
int, float
The result of the addition.
"""
return a+b
def simple_sub(a,b):
"""
Subtraction of two numbers.
Parameters
----------
a : int, float
Number to be subtracted.
b : int, float
Number to be added.
Returns
----------
int, float
The result of the subtraction.
"""
return a-b
def simple_mult(a,b):
"""
Multiplication of two numbers.
Parameters
----------
a : int, float
Number to be multiplied.
b : int, float
Number to be multiplied.
Returns
----------
int, float
The result of the multiplication.
"""
return a*b
def simple_div(a,b):
"""
Division of two numbers.
Parameters
----------
a : int, float
Number to be divided.
b : int, float
Number to be divided.
Returns
----------
int, float
The result of the division.
"""
return a/b
def poly_first(x, a0, a1):
"""
First order polynomial
Parameters
----------
x : int,float
Variable in the polynomial.
a0 : int, float
Coefficient for the constant in the polynomial.
a1 : int, float
Coefficient for the first order variable in the polynonmial.
Returns
----------
int, float
The first order polynomial evaluated at `x` with the given coefficients.
"""
return a0 + a1*x
def poly_second(x, a0, a1, a2):
"""
Second order polynomial
Parameters
----------
x : int,float
Variable in the polynomial.
a0 : int, float
Coefficient for the constant in the polynomial.
a1 : int, float
Coefficient for the first order variable in the polynonmial.
a2 : int, float
Coefficient for the second order variable in the polynomial.
Returns
-----------
int, float
The second order polynomial evaluated at `x` with the given coefficients.
"""
return poly_first(x, a0, a1) + a2*(x**2)
# Feel free to expand this list with more interesting mathematical operations...
# ......
| true |
b04d9873a978bc8591c9091902de9b46de0a9f62 | clede/chemistry | /chemistry.py | 2,218 | 4.34375 | 4 | import initialization
class Unit(object):
"""A unit of measurement for a substance or supplement. e.g. capsule,
tablet, drop, or milligram, etc."""
# In the future we will need to track relationships between different units.
# e.g. a 'gram' consists of 1000 'milligrams'.
def __init__(self, singular, plural=None, abbrev=None):
self.singular = singular
if plural:
self.plural = plural
# If plural is not specified, just tack an 's' on to the singular.
else:
self.plural = singular + 's'
if abbrev:
self.abbrev = abbrev
else:
self.abbrev = self.plural
def __str__(self):
return self.abbrev
def __repr__(self):
return self.abbrev
class Amount(object):
"""An amount consists of a numeric qty and a unit.
This could be used to represent a dose (e.g. 2 tablets),
or a quantity of a substance in a dose (e.g. a pill contains 50 mg)"""
def __init__(self, qty, unit):
self.qty = float(qty)
assert unit.__class__.__name__ == 'Unit', 'Specified Unit is invalid.'
self.unit = unit
def __str__(self):
return str(self.qty) + ' ' + self.unit.abbrev
def __repr__(self):
return str(self.qty) + ' ' + self.unit.abbrev
class Substance(object):
"""A specific substance. e.g. Vitamin D, or Biotin."""
def __init__(self)
class Supplement(object):
"""A specific supplement product. e.g. """
# To start, this will be generic. We'll track a single object for 'Vitamin
# D'. However, ultimately, we'll want to track different brands, etc.
def __init__(self, name, brand, units, amt_per_unit=None):
self.name = name
self.brand = brand
assert units.__class__.name__ == 'Unit', units + ' is not a Unit object.'
self.units = units
self.description = ''
if amt_per_unit:
assert amt_per_unit.__class__.__name__ == 'Amount', """amt_per_unit
is not valid."""
self.amt_per_unit = amt_per_unit
else:
self.amt_per_unit = None
def __str__(self):
return self.name + ' ' + str(self.amt_per_unit)
| true |
483dfbcd3693bb16dbdb617c812a6eac5eacdcd7 | dcryptOG/pyclass-notes | /9-built-infunctions/2-built-func-hw.py | 2,153 | 4.15625 | 4 |
# Built-in Functions Test
# For this test, you should use built-in functions and be able to write the requested functions in one line.
# Problem 1
# Use map() to create a function which finds the length of each word in the phrase (broken by spaces) and returns the values in a list.
# The function will have an input of a string, and output a list of integers.
# In [1]:
# def word_lengths(phrase):
# pass
# In [2]:
# word_lengths('How long are the words in this phrase')
# Out[2]:
# [3, 4, 3, 3, 5, 2, 4, 6]
# Problem 2
# Use reduce() to take a list of digits and return the number that they correspond to. For example, [1, 2, 3] corresponds to one-hundred-twenty-three.
# Do not convert the integers to strings!
# In [3]:
# from functools import reduce
# def digits_to_num(digits):
# pass
# In [4]:
# digits_to_num([3,4,3,2,1])
# Out[4]:
# 34321
# Problem 3
# Use filter to return the words from a list of words which start with a target letter.
# In [5]:
# def filter_words(word_list, letter):
# pass
# In [6]:
# l = ['hello','are','cat','dog','ham','hi','go','to','heart']
# filter_words(l,'h')
# Out[6]:
# ['hello', 'ham', 'hi', 'heart']
# Problem 4
# Use zip() and a list comprehension to return a list of the same length where each value is the two strings from L1 and L2 concatenated together with connector between them. Look at the example output below:
# In [7]:
# def concatenate(L1, L2, connector):
# pass
# In [8]:
# concatenate(['A','B'],['a','b'],'-')
# Out[8]:
# ['A-a', 'B-b']
# Problem 5
# Use enumerate() and other skills to return a dictionary which has the values of the list as keys and the index as the value. You may assume that a value will only appear once in the given list.
# In [9]:
# def d_list(L):
# pass
# In [10]:
# d_list(['a','b','c'])
# Out[10]:
# {'a': 0, 'b': 1, 'c': 2}
# Problem 6
# Use enumerate() and other skills from above to return the count of the number of items in the list whose value equals its index.
# In [11]:
# def count_match_index(L):
# pass
# In [12]:
# count_match_index([0,2,2,1,5,5,6,10])
# Out[12]:
# 4
# Great Job!
| true |
810b6d03d9bc622dd166324958e4213ed86d13a8 | dcryptOG/pyclass-notes | /3Statments/2_if_elseif_else.py | 1,281 | 4.34375 | 4 | # =======================================================
#! if, elif, else Statements
# * CONTROL FLOW = use logic for async code execution
# elif and else statements, which allow us to tell the computer:
# if case1:
# perform action1
# elif case2:
# perform action2
# else:
# perform action3
if True:
print('It was true!')
x = False
if x:
print('x was True!')
else:
print('I will be printed in any case where x is not True')
print('/n')
if 3 > 2:
print("It's True!")
#
hungry = True
if hungry:
print('FEED ME!')
else:
print("I'm not hungry")
#! ELIF multiple branches
# loc stand for location
print('\n')
loc = 'Bank'
if loc == 'Auto Shop':
print('Welcome to the Auto Shop!')
elif loc == 'Bank':
print('Welcome to the bank, moneh is coo!')
elif loc == 'Store':
print('Welcome to the store!')
else:
print('Where are you?')
#######################################################################
person = 'George'
print('\n')
if person == 'Sammy':
print('Welcome Sammy')
elif person == 'George':
print('Welcome George')
else:
print("Welcome, what's your name?")
# INDENTATION - itis important to understand how indentation works for Python code structure
print('understand how indentation works in python')
| true |
15968bc019404dcdf37235069ab465d6fd3fca37 | abbeyperini/DC_Learning_Python | /Week1/Day4/Day4A2.py | 443 | 4.46875 | 4 | # Assignment: Write a program which finds the largest element in the array
words = ["apple", "banana", "orange", "apricot", "supercalifragilisticexpialidocious"]
numbers = [1, 4, 23, 103, 567, 1432, 40523, 1000000]
def find_largest(array):
length = 0
item = ""
for n in array:
if len(str(n)) > length:
length = len(str(n))
item = n
print(item)
find_largest(words)
find_largest(numbers) | true |
34b2f8d4b927027a075463d51974ccd34c2a6e10 | hunterruns/Project | /proj03/proj03.py | 1,178 | 4.25 | 4 | # Name: Hunter
# Date: 6/12/2017
"""
proj 03: Guessing Game
Generate a random number between 1 and 9 (including 1 and 9).
Ask the user to guess the number, then tell them whether they guessed too low, too high,
or exactly right. Keep the game going until the user types exit.
Keep track of how many guesses the user has taken, and when the game ends, print this out.
"""
user_input = int(raw_input("Guess a number, one through nine!: "))
#user_input2 = raw_input("Ding ding ding!!! You guessed right! ")
#user_input3 = raw_input("Gotta guess a little higher than that! Try again: ")
#user_input4 = raw_input("Guess lower next time! Try again: ")
import random
var = random.randint(1, 9)
print user_input
guess = 3
while guess > 0:
guess -= 1
if guess == 0:
print "You failed :<("
break
if user_input == var:
print "Home Run! You win!!"#user_input2
break
if user_input > var:
print "Airball! Too high!"#user_input3
if user_input < var:
print "Nothing but dirt! Too low!"#user_input4
user_input = int(raw_input("Guess a number, one through nine!: "))
print "The correct answer is..."
print var
| true |
d69904660072c40bc9262fa745ec213034c50241 | zhweiliu/learn_leetcode | /Top Interview Questions Easy Collection/Linked List/Merge Two Sorted Lists/solution.py | 1,694 | 4.25 | 4 | from typing import Tuple
'''
Merge two sorted linked lists and return it as a sorted list. The list should be made by splicing together the nodes of the first two lists.
Constraints:
- The number of nodes in both lists is in the range [0, 50].
- -100 <= Node.val <= 100
- Both l1 and l2 are sorted in non-decreasing order.
Example 1:
Input: l1 = [1,2,4], l2 = [1,3,4]
Output: [1,1,2,3,4,4]
Example 2:
Input: l1 = [], l2 = []
Output: []
Example 3:
Input: l1 = [], l2 = [0]
Output: [0]
'''
# Definition for singly-linked list.
class ListNode:
def __init__(self, x, next=None):
self.val = x
self.next = next
def mergeTwoLists(l1: ListNode, l2: ListNode) -> ListNode:
node = None
prev_node = None
root = None
while (l1 or l2):
if not l1:
prev_node, node, l2 = node, l2, l2.next
elif not l2:
prev_node, node, l1 = node, l1, l1.next
else:
if l1.val < l2.val:
prev_node, node, l1 = node, l1, l1.next
else:
prev_node, node, l2 = node, l2, l2.next
if prev_node:
prev_node.next = node
if not root:
root = node
return root
if __name__ == '__main__':
l1 = [1,3,4]
l2 = [0]
q1 = [ ListNode(ele) for ele in l1 ]
q2 = [ ListNode(ele) for ele in l2 ]
for i in range(0, len(q1) - 1, 1):
q1[i].next = q1[i + 1]
for i in range(0, len(q2) - 1, 1):
q2[i].next = q2[i + 1]
if len(q1) == 0:
q1.append(None)
if len(q2) == 0:
q2.append(None)
hl = mergeTwoLists(q1[0], q2[0])
while hl:
print(hl.val)
hl = hl.next
| true |
36cf62ebb2c03821fb3c2fa279ea27c242811d8a | zhweiliu/learn_leetcode | /Top Interview Questions Easy Collection/Strings/Reverse String/solution.py | 823 | 4.5 | 4 | from typing import List
'''
Write a function that reverses a string. The input string is given as an array of characters s.
Example 1:
Input: s = ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]
Example 2:
Input: s = ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]
Follow up:
Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1)
extra memory.
'''
def reverseString(s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
start, end = 0, len(s) - 1
# rotate elements by middle index
while start < end:
s[start], s[end] = s[end], s[start]
start, end = start + 1, end - 1
if __name__ == '__main__':
s = ["h", "e", "l", "l", "o"]
reverseString(s)
print(s)
| true |
498de0cff673823a8cf86583e35ce151430bc5b0 | zhweiliu/learn_leetcode | /Top Interview Questions Easy Collection/Dynamic Programming/Best Time to Buy and Sell Stock/solution.py | 1,455 | 4.125 | 4 | from typing import List
'''
You are given an array prices where prices[i] is the price of a given stock on the ith day.
You want to maximize your profit by choosing a single day to buy one stock and choosing a different day \
in the future to sell that stock.
Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.
Constraints:
- 1 <= prices.length <= 105
- 0 <= prices[i] <= 104
Example 1:
Input: prices = [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.
Example 2:
Input: prices = [7,6,4,3,1]
Output: 0
Explanation: In this case, no transactions are done and the max profit = 0.
'''
class Solution:
def maxProfit(self, prices: List[int]) -> int:
'''
using Kadane's Algorithm
https://zh.wikipedia.org/wiki/%E6%9C%80%E5%A4%A7%E5%AD%90%E6%95%B0%E5%88%97%E9%97%AE%E9%A2%98
:param prices:
:return:
'''
if len(prices) == 0:
return 0
profit = 0
buy = prices[0]
for p in prices[1:]:
buy = min(buy, p)
profit = max(profit, p - buy)
return profit
if __name__ == '__main__':
prices =[7,1,5,3,6,4]
sol = Solution()
print(f'max profit {sol.maxProfit(prices)} with prices {prices}')
| true |
ab5d37acfdf8bf8fda7b53fd82059ce78f690e8c | KiranDudhane/Python | /Dictionary.py | 2,947 | 4.3125 | 4 | from typing import Collection
# Dictionary ----> descriptive data Collection
# does not store the value by index
person = {
'firstName' : "Kiran",
'lastName' : "Dudhane",
'age' : 25
}
print(person['firstName']) # to fatch value
print(person['age'])
person['firstName'] = "Suraj" # to update value
print(person)
person['Skills'] = "Javascript","Python" # to update the dictionary
print(person)
for item in person: # for loop on dictionary
print(item,person[item])
for item in person.keys():
print(item)
for item in person.values():
print(item)
for x,y in person.items():
print(x,y)
print('------------------------------------------------>')
Students = [{
'firstName' : "Kiran",
'lastName' : "Dudhane",
'age' : 25,
'rollNo' : 125
},
{
'firstName' : "suraj",
'lastName' : "Dudhane",
'age' : 20,
'rollNo' : 145
},
{
'firstName' : "Tejal",
'lastName' : "Dudhane",
'age' : 16,
'rollNo' : 198
},
{
'firstName' : "Tushar",
'lastName' : "Dudhane",
'age' : 31,
'rollNo' : 98
}
]
# print(Students[0]['firstName'])
# print(Students[1]['age'])
# print(Students[2]['rollNo'])
for key in Students:
for x,y in key.items(): # using for loop to print all key and values in array with object elements
print(x,y)
print('------------------------------------------------>')
car =[ {
'CarName' : "BMW",
'carNo' : 31,
'Colour' : 'black'
}]
for item in car:
for a,b in item.items():
print(a,b)
store = {
'laptop':"HP",
'Mobile':"Samsung",
'EarPhone':'Boat',
'Powerbank':'Syska'
}
store['Mobile']="iPhone"
store1 = store
print(store)
print(store1)
store1['EarPhone']="MI"
print(store)
print(store1)
print(store.get('Mobile'))
print('------------------------------------------------>')
#Methods
kiran = {
'firstName':'Kiran',
'lastName':"Dudhane",
'age': 25,
'colour':'fair',
'skills':['javascript','python']
}
kiran.update({'age':'26'}) # to update the value
kiran.update({'colour':'brown'})
kiran.update({'mobile':'SAMSUNG'}) # to update add key and value to object
print(kiran)
kiran.popitem() # remove the last key value set
print(kiran)
kiran.pop('colour') # to remove the specific set with key name
print(kiran)
# kiran.clear() # to clear the dictionary
# print(kiran)
kiran.setdefault('car','Nexon') # to add default value in dictionary
print(kiran)
print('------------------------------------------------>')
a = ['name','Bdate','year','HEdu']
b = ['Kiran','20/02',1996,'BE']
print(dict.fromkeys(a,b)) # 1st array setv as keys...2nd full array set as value of every key
kiran = {
'firstName':'Kiran',
'lastName':"Dudhane",
'age': 25,
'colour':'fair',
'skills':['javascript','python']
}
for key in kiran:
print(key,kiran[key])
kiran.update({"salary":"4LPA"})
print(kiran)
| false |
8e3b843a4f3a1e062ae855ed7d9b4a156bdbf42a | tommymag/CodeGuild | /python/phone_number.py | 786 | 4.375 | 4 |
def pretty_print(phone_number):
return "({}){} - {}".format(phone_number[0:3], phone_number[3:6], phone_number[6:])
phone_number = input('Please enter an all digits phone number. ')
print(pretty_print(phone_number))
# # Lab: Fancy Phone Numbers
# ###### Delivery Method: Prompt Only
# ##### Goal
# Write a small app that asks the user for an all-digits phone number, Then 'pretty prints' it out.
# ##### Instructions
# Use the the `input()` builtin function.
# Here is an example of the program's expected output:
# ```
# > Please enter an all digits phone number. >> 5035551234
# > 503-555-1234
# or
# > (503) 555-1234
# ```
# -------------------
# #### Documentation
# ##### [Python Official Docs: input()](https://docs.python.org/3.6/library/functions.html#input) | true |
4282740cccc1be82217a72dc8c122e7b5570cb86 | harite/game-hack | /Misc Python Exercises/py1.py | 725 | 4.5 | 4 | from sys import argv #Imports the modules to allow the file to take arguments
script, filename = argv #defines the argument as a string
prompt = "test:" #sets the prompt
txt = open(filename) #Opens the file specified in the argument via line 3
print "Here's your file %r:" % filename #Statement, %r to substitute instead of hardcoded.
print txt.read() #Displays the text in the file
txt.close() #closes the file we no longer need.
print "I'll also ask you to type it again." #Print statement.
file_again = raw_input(prompt) #Asks for another filename
txt_again = open(file_again) #Defines the file as a string (Note not the contents)
print txt_again.read() #reads and prints the contents of the file.
txt_again.close()
| true |
0a540249daf51ad06257137a8ee0a7e79ab2c028 | alexyin2/Linear-Regression_Python_Not_Using_sklearn | /L2Regularization.py | 1,416 | 4.125 | 4 | import numpy as np
import matplotlib.pyplot as plt
"""
L2 Regularization is a way of providing data being highly affected by outliers.
We add squared magnitude of weigths times a constant to our cost function.
This is because large weights may be a sign of overfitting.
L2 Regularization is also called "Ridge Regression".
"""
N = 50
X = np.linspace(0, 10, N)
Y = 0.5 * X + np.random.randn(N)
# Create some outlier
Y[-1] += 100
Y[-2] += 100
# Plot our data
plt.scatter(X, Y)
plt.show()
X = np.vstack([np.ones(N), X]).T
# 1. Linear Regression
# Calculate weights by maximum likelihood
w_ml = np.linalg.solve(X.T.dot(X), X.T.dot(Y))
Yhat_ml = X.dot(w_ml)
# Plot the scatter plot and Yhat, we can notice that our linear regression is effected by outliers.
plt.scatter(X[:, 1], Y)
plt.plot(X[:, 1], Yhat_ml)
plt.show()
# 2. L2 Regularization
l2 = 1000.0
w_map = np.linalg.solve(l2 * np.eye(2) + X.T.dot(X), X.T.dot(Y)) # Here, np.eye(2) we use 2 is because we only have two parameters that needs to be calculated
# We can also write: w_map = np.linalg.inv(l2 * np.eye(2) + X.T.dot(X)).dot(X.T.dot(Y))
Yhat_map = X.dot(w_map)
# Plot the scatter plot with the comparison of two different methods.
# We can notice that L2 Regularization are less effected by outliers.l
plt.scatter(X[:, 1], Y)
plt.plot(X[:, 1], Yhat_ml, label='maximum likelihood')
plt.plot(X[:, 1], Yhat_map, label='map')
plt.legend()
plt.show()
| true |
bfcf71df2e0d088ac9390c06fdd979611f1559cf | joshurbandavis/Project-Euler-Problems | /Problem1.py | 229 | 4.28125 | 4 | #!/usr/bin/env python
"""Problem 1: Find the sum of all multiples of 3 or 5 between 0 and 1000
Solved in python"""
counter = 0
for x in range (0,1000):
if x%3 == 0 or x%5 == 0:
counter = counter + x
print counter
| true |
684b104df1d8cc8b4e4fef44f8c06e83ec9acd45 | ShrawanSai/DS-and-Algos-with-python-and-Java | /LinkedLists/seperate_odd_and_even.py | 1,917 | 4.1875 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
self.count = 0
def append(self,data):
new_node = Node(data)
if self.head is None:
self.head = new_node
return
cur_node = self.head
while cur_node.next is not None:
cur_node = cur_node.next
cur_node.next = new_node
self.count += 1
def printll(self):
if self.head is None:
print('Empty Linked List')
cur_node = self.head
print(cur_node.data, end = ' --> ')
while cur_node.next is not None:
print(cur_node.next.data, end = ' --> ')
cur_node = cur_node.next
print()
def seperate_odd_and_even(self):
ES, EE, OS, OE = None, None, None, None
cur = self.head
while cur is not None:
if cur.data %2 == 0:
if ES is None:
ES = cur
EE = ES
else:
EE.next = cur
EE = EE.next
else:
if OS is None:
OS = cur
OE = OS
else:
OE.next = cur
OE = OE.next
cur = cur.next
if OS is None or ES is None:
return
else:
EE.next = OS
self.head = ES
OE.next = None
return
LL1 = LinkedList()
LL1.append(4)
LL1.append(5)
LL1.append(6)
LL1.append(7)
LL1.append(8)
LL1.append(9)
LL1.append(10)
LL1.append(11)
LL1.printll()
LL1.seperate_odd_and_even()
print("printing")
LL1.printll()
| true |
41c95b42f006ab6ae9b81c9a4c430c8b8ab13a5b | ShreyaRawal97/data-structures | /Linked Lists/Max_Sum_Subarray.py | 1,611 | 4.34375 | 4 | #find and return largest sum in a contiguous subarray within input array
#KODANE'S ALGORITHM - the maximum subarray problem is the task of finding
#the contiguous subarray within a one-dimensional array of numbers which
#has the largest sum.
"""
O element array - if there is no element present in array then we can say that,
startIndex = -1, endIndex = -1, and maxSum = -1 (or some other suitable notation)
1 element array - if there is one element,
in this case, startIndex = 0, endIndex = 0 and maxSum = arr[0]
array having length greater than 1...
"""
def max_sum_subarray(arr):
if len(arr) == 0:
return -1
elif len(arr) == 1:
return arr[0]
elif len(arr) > 1:
sum_so_far = 0
sum_ending_here = 0
for i in range(0, len(arr)):
sum_ending_here = sum_ending_here + arr[i]
if sum_ending_here < 0:
sum_ending_here = 0
if sum_so_far < sum_ending_here:
sum_so_far = sum_ending_here
return sum_so_far
def test_function(test_case):
arr = test_case[0]
solution = test_case[1]
output = max_sum_subarray(arr)
if output == solution:
print("Pass")
else:
print("Fail")
arr= [1, 2, 3, -4, 6]
solution= 8 # sum of array
test_case = [arr, solution]
test_function(test_case)
arr = [1, 2, -5, -4, 1, 6]
solution = 7 # sum of last two elements
test_case = [arr, solution]
test_function(test_case)
arr = [-12, 15, -13, 14, -1, 2, 1, -5, 4]
solution = 18 # sum of subarray = [15, -13, 14, -1, 2, 1]
test_case = [arr, solution]
test_function(test_case)
| true |
76bfac88cec841875c5a8db59a23b8bdc0961bb3 | ParkerCS/ch18-19-exceptions-and-recursions-nsachs | /recursion_problem_set.py | 2,512 | 4.125 | 4 | '''
- Personal investment
Create a single recursive function (or more if you wish), which can answer the first three questions below. For each question, make an appropriate call to the function. (5pts each)
'''
#1. You have $10000 on a high interest credit card with an APR of 20.0% (calculated MONTHLY, so MPR is APR/12). Assuming you make no payments for 6 months, what is your new balance? Solve recursively.
def personal_investment(money, month, index):
money += money * (0.20/12)
index += 1
if index < month:
personal_investment(money, month, index)
else:
print("After", month, "months, your balance is: ", money)
personal_investment(10000, 6, 0)
#2. You have $5000 on a high interest credit card with an APR of 20.0% (calculated MONTHLY). You make the minimum payment of $100 per month for 36 months. What is your new balance? Solve recursively.
def personal_investment2(money, month, index):
money += money * (0.2/12)
money -= 100
index += 1
if index < month:
personal_investment2(money, month, index)
else:
print("After", month, "months, you balance is: ", money)
personal_investment2(5000, 36, 0)
#3. You have $10000 on a high interest credit card with an APR of 20.0% (calculated MONTHLY). If you make the minimum payment of $100 per month, how many months will it take to pay it off? Solve recursively.
#I'm not sure it is possible to pay off all 10,000 dollars.
def personal_investment3(money, month, done):
monthly_apr = 0.20 / 12
money += money * monthly_apr
money -= 100
#print(money)
if month < 100 and not done:
personal_investment(money, month +1, False)
if money < 0:
done = True
print("Your debt was paid off after" , month, "months")
personal_investment3(10000, 1, False)
print("You'll never pay off your debt.")
#4 Pyramid of Cubes - (10pts) If you stack boxes in a pyramid, the top row would have 1 box, the second row would have two, the third row would have 3 and so on. Make a recursive function which calculates the TOTAL NUMBER OF BOXES for a pyramid of boxes n high. For instance, a pyramid that is 3 high would have a total of 6 boxes. A pyramid 4 high would have 10.
def pyramid(height, boxes, index):
if index == 0:
boxes = 0
boxes += height
if height != 0:
pyramid(height-1, boxes, index + 1)
else:
print("There are", boxes, "boxes")
pyramid(int(input("Enter a positive, whole value: ")), 0, 0)
| true |
a67d420a766a00ec0810c310439988a9c0fc4505 | niavivek/D10 | /numbered_lines.py | 705 | 4.15625 | 4 | #!/usr/bin/env python3
"""Function to write line numbers to a file"""
import math
def numbered_lines(filename):
write_file(read_file(filename))
def read_file(filename):
list_lines = []
with open(filename,"r") as read_file:
for lines in read_file:
lines = lines.strip()
list_lines += lines.split("\n")
return list_lines
def write_file(list_lines):
with open("t_write.txt","w") as w_file:
#enumerate the read lines and write to file using index number
for idx,words in enumerate(list_lines):
if words == "":
pass
else:
words = str(idx+1) + " " + words
w_file.write(words +"\n")
def main():
numbered_lines("small.txt")
if __name__ == "__main__":
main()
| true |
227c964f312d4e96bb627100ce70f2de3d1e9f66 | Syssos/Holberton_School | /holbertonschool-higher_level_programming/0x03-python-data_structures/3-print_reversed_list_integer.py | 334 | 4.1875 | 4 | #!/usr/bin/python3
def print_reversed_list_integer(my_list=[]):
if my_list is not None:
length = len(my_list)
for i in range(length-1, -1, -1):
if i == length:
i -= 1
print('{:d}'.format(my_list[i]))
else:
print('{:d}'.format(my_list[i]))
| false |
afb13f26fb67cfb2c59f1704858638a7adf62b4a | Syssos/Holberton_School | /holbertonschool-higher_level_programming/0x0A-python-inheritance/11-square.py | 1,808 | 4.15625 | 4 | #!/usr/bin/python3
class BaseGeometry:
def integer_validator(self, name, value):
""" Function that validated value for name
Arguments:
name (str): name string
value (int): value to validate
Returns:
None
"""
if type(value) is not int:
raise TypeError("{:s} must be an integer".format(name))
if value <= 0:
raise ValueError("{:s} must be greater than 0".format(name))
class Rectangle(BaseGeometry):
def __init__(self, width, height):
""" initiates BaseGeometry
Arguments:
width (int)
height (int)
Returns:
None
"""
BaseGeometry.integer_validator(self, "width", width)
BaseGeometry.integer_validator(self, "height", height)
self.__width = width
self.__height = height
def area(self):
""" Write a function that raises type Error
Arguments:
self (self): passing self
Returns:
None
"""
return self.__width * self.__height
def __str__(self):
""" Write a function that raises type Error
Arguments:
self (self): passing self
Returns:
None
"""
return("[Rectanlge] {:d}/{:d}".format(self.__width, self.__height))
class Square(Rectangle):
def __init__(self, size):
""" fucntion that creates a square and adds a size
Argmunets:
size (int): size of square
Returns:
None
"""
self.integer_validator("size", size)
self.__size = size
super().__init__(self.__size, self.__size)
def __str__(self):
return ("[Square] {:d}/{:d}".format(self.__size, self.__size))
| true |
7f19d79f83e74756d31a16e1605e7105fcb8ce0b | jprajapat888/Python-Files | /Example 2 Python Break.py | 436 | 4.4375 | 4 | # The program below takes inputs from the user and calculates the sum until the user enters a negative number.
# When the user enters negative a number, the break statement is executed which terminates the loop.
sum = 0
# boolean expression is True
while True:
n = input("Enter a number: ")
n = float(n) # Converting to float
if n < 0: # check if number is negative
break
sum += n
print("sum =", sum)
| true |
e13b3a957f3778b57131d168426d302fbc23e1f9 | jprajapat888/Python-Files | /Python Program to Find the Square Root.py | 265 | 4.46875 | 4 | #Python Program to calculate the square root
#Note: change this value for a different result
num = 8
# To take the input from the user
# num = float(input('Enter a numbers: '))
num_sqrt = num ** 0.5
print("The Sqaure root of %0.3f is %0.3f" %(num ,num_sqrt))
| true |
767e6900f4abb2c048e425a85e0d7eca130b8c58 | Airmagic/Lab-1-new | /camelCase.py | 824 | 4.3125 | 4 | #found python code help from stackoverflow
#Showing the name of the program
print('Camel Casing a sentence')
# getting the sentence from user
sentence = input('Write a short sentence to camelCase :')
# converting the sentence all into lowercase
lowercase = sentence.lower()
# making all the first letter of word uppercase
sentenceTitle = lowercase.title()
# removing all the single spaces from the string
sentenceRemoveSpace = sentenceTitle.replace(' ', '')
# taking the first letter and making a lowercase varible of it
firstLetterLower = sentenceRemoveSpace[0].lower()
# removing the first letter from the sentence
sentenceNoFirstLetter = sentenceRemoveSpace[1:]
# adding the first letter to the sentence
camelCase = firstLetterLower + sentenceNoFirstLetter
# printing out the result in camelCase
print(camelCase)
| true |
fc4b653d39d90fa378bb0b545b7663f701b5ecb0 | dfeusse/2018_practice | /dailyPython/05_may/31_countingArrayElements.py | 698 | 4.25 | 4 | '''
Write a function that takes an array and counts the number of each unique element present.
count(['james', 'james', 'john'])
#=> { 'james' => 2, 'john' => 1}
'''
def count(array):
#your code here
outputDict = {}
for i in array:
if i not in list( outputDict.keys() ):
outputDict[i] = 1
else:
outputDict[i] += 1
return outputDict
print count(['a', 'a', 'b', 'b', 'b'])#, { 'a': 2, 'b': 3 })
print count(['james', 'james', 'john']) #=> { 'james' => 2, 'john' => 1}
'''
def count(array):
result = {}
for x in array:
result[x] = result.get(x, 0) + 1
return result
def count(array):
return {x: array.count(x) for x in array}
''' | true |
9633f3f420cab004965178873349b26356b8a380 | dfeusse/2018_practice | /dailyPython/06_june/16_roundUp5.py | 593 | 4.21875 | 4 | '''
Round to the next multiple of 5.
Given an integer as input, can you round it to the next (meaning, "higher") 5?
Examples:
input: output:
0 -> 0
2 -> 5
3 -> 5
12 -> 15
21 -> 25
30 -> 30
-2 -> 0
-5 -> -5
etc.
Input may be any positive or negative integer (including 0).
You can assume that all inputs are valid integers.
'''
def round5(num):
for i in range(num, num+6):
if i % 5 == 0:
return i
print round5(0)
print round5(2)
print round5(3)
print round5(12)
print round5(21)
print round5(30)
print round5(-2)
print round5(-5)
print round5(-7) | true |
c51f358b13d04606b0096ffa7062ffb1cae62491 | dfeusse/2018_practice | /dailyPython/07_july/26_countingDups.py | 1,208 | 4.28125 | 4 | '''
Counting Duplicates
Count the number of Duplicates
Write a function that will return the count of distinct case-insensitive alphabetic characters and numeric digits that occur more than once in the input string. The input string can be assumed to contain only alphabets (both uppercase and lowercase) and numeric digits.
Example
"abcde" -> 0 # no characters repeats more than once
"aabbcde" -> 2 # 'a' and 'b'
"aabBcde" -> 2 # 'a' occurs twice and 'b' twice (bandB)
"indivisibility" -> 1 # 'i' occurs six times
"Indivisibilities" -> 2 # 'i' occurs seven times and 's' occurs twice
"aA11" -> 2 # 'a' and '1'
"ABBA" -> 2 # 'A' and 'B' each occur twice
'''
def duplicate_count(text):
# get list of all items
# loop through the text
# for each, if count is only once, add 1 to a counter
counter = []
texts = list(text)
print texts
for i in text:
if texts.count(i.lower()) > 1:
print i
counter.append(i)
#return len(set(counter))
return len(set([ i for i in list(text) if list(text).count(i) > 1 ]))
print duplicate_count("abcde")#, 0)
print duplicate_count("abcdea")#, 1)
print duplicate_count("indivisibility")#, 1)
print duplicate_count("aabbcde")
print duplicate_count("indivisibility") | true |
fb73339f7683baf3a1d083b511799c8064310e09 | dfeusse/2018_practice | /dailyPython/07_july/03_sumOfSequence.py | 758 | 4.3125 | 4 | '''
Your task is to make function, which returns the sum of a sequence of integers.
The sequence is defined by 3 non-negative values: begin, end, step.
If begin value is greater than the end, function should returns 0
'''
def sequence_sum(begin_number, end_number, step):
startingNum = begin_number;
nums = []
while startingNum <= end_number:
nums.append(startingNum)
startingNum += step
return sum(nums)
print sequence_sum(2, 6, 2)#, 12)
print sequence_sum(1, 5, 1)#, 15)
print sequence_sum(1, 5, 3)#, 5)
print sequence_sum(0, 15, 3)#, 45)
print sequence_sum(16, 15, 3)#, 0)
print sequence_sum(2, 24, 22)#, 26)
print sequence_sum(2, 2, 2)#, 2)
print sequence_sum(2, 2, 1)#, 2)
print sequence_sum(1, 15, 3)#, 35)
print sequence_sum(15, 1, 3)#), 0) | true |
3639245b44c8c691441bc9f9d7b0381170529489 | dfeusse/2018_practice | /dailyPython/08_august/03_divisors.py | 886 | 4.15625 | 4 | '''
Find the divisors!
Create a function named divisors/Divisors that takes an integer n > 1 and returns an array with all of the integer's divisors(except for 1 and the number itself), from smallest to largest. If the number is prime return the string '(integer) is prime' (null in C#) (use Either String a in Haskell and Result<Vec<u32>, String> in Rust).
Example:
divisors(12); #should return [2,3,4,6]
divisors(25); #should return [5]
divisors(13); #should return "13 is prime"
'''
def divisors(integer):
# loop through list of ints starting with 1 lower than number to 2
# return list of all that are divisors
divisors = []
for i in range(2,integer):
if integer % i == 0:
divisors.append(i)
if len(divisors) == 0:
return str(integer) + " is prime"
return divisors
print divisors(15)#, [3, 5]);
print divisors(12)#, [2, 3, 4, 6]);
print divisors(13)#, "13 is prime"); | true |
8c84b7a5f28bb826d60d132a80bb0fd02b2a016b | dfeusse/2018_practice | /dailyPython/07_july/27_pigLatin.py | 813 | 4.34375 | 4 | '''
imple Pig Latin
Move the first letter of each word to the end of it, then add "ay" to the end of the word. Leave punctuation marks untouched.
Examples
pig_it('Pig latin is cool') # igPay atinlay siay oolcay
pig_it('Hello world !') # elloHay orldWay !
'''
def pig_it(text):
# loop through each word
# slice the word except for first letter
# slice the first letter
# add together and append 'ay' to end
# return string of all together
return " ".join([ i[1:] + i[0] + 'ay' for i in text.split() if i not in '!,."'])
print pig_it('Pig latin is cool')#,'igPay atinlay siay oolcay')
print pig_it('This is my string')#,'hisTay siay ymay tringsay')
print pig_it('Hello world !') # elloHay orldWay !
def pig_it(text):
return " ".join(x[1:] + x[0] + "ay" if x.isalnum() else x for x in text.split()) | true |
dca07c49ef843725a93b3178f9ff20b42aff5ffc | dfeusse/2018_practice | /dailyPython/05_may/09_descOrder.py | 754 | 4.21875 | 4 | '''
Your task is to make a function that can take any non-negative integer as a argument
and return it with its digits in descending order. Essentially, rearrange the digits
to create the highest possible number.
Examples:
Input: 21445 Output: 54421
Input: 145263 Output: 654321
Input: 1254859723 Output: 9875543221
'''
def Descending_Order(num):
return int("".join(sorted(list(str(num)), reverse=True)))
print Descending_Order(0)#, 0)
print Descending_Order(15)#, 51)
print Descending_Order(123456789)#, 987654321)
'''
def Descending_Order(num):
return int("".join(sorted(str(num), reverse=True)))
def Descending_Order(num):
s = str(num)
s = list(s)
s = sorted(s)
s = reversed(s)
s = ''.join(s)
return int(s)
''' | true |
1ab382088fb0752627746e4c28f5147482e57214 | dfeusse/2018_practice | /dailyPython/06_june/21_highestLowest.py | 569 | 4.21875 | 4 | '''
Highest and Lowest
In this little assignment you are given a string of space separated numbers, and have to return the highest and lowest number.
Example:
high_and_low("1 2 3 4 5") # return "5 1"
high_and_low("1 2 -3 4 5") # return "5 -3"
high_and_low("1 9 3 4 -5") # return "9 -5"
'''
def high_and_low(string):
listInts = sorted([int(i) for i in string.split()])
return str(listInts[-1]) + " " + str(listInts[0])
print high_and_low("1 2 3 4 5") # return "5 1"
print high_and_low("1 2 -3 4 5") # return "5 -3"
print high_and_low("1 9 3 4 -5") # return "9 -5" | true |
9a342ace56cd9f19f7d4fbcbb290df31630013ab | dfeusse/2018_practice | /dailyPython/07_july/23_scrambled.py | 781 | 4.125 | 4 | '''
Scramblies
Complete the function scramble(str1, str2) that returns true if a portion of str1 characters can be rearranged to match str2, otherwise returns false.
Notes:
Only lower case letters will be used (a-z). No punctuation or digits will be included.
Performance needs to be considered
Examples
scramble('rkqodlw', 'world') ==> True
scramble('cedewaraaossoqqyt', 'codewars') ==> True
scramble('katas', 'steak') ==> False
'''
def scramble(s1, s2):
if ''.join(sorted(s1)) == ''.join(sorted(s2)):
return True
return False
print scramble('rkqodlw', 'world')#, True)
print scramble('cedewaraaossoqqyt', 'codewars')#, True)
print scramble('katas', 'steak')#, False)
print scramble('scriptjava', 'javascript')#, True)
print scramble('scriptingjava', 'javascript')#, True) | true |
295dfb3f4151ec114a6825854422243fd5b0f0d6 | dfeusse/2018_practice | /dailyPython/07_july/26_firstNonRepeating.py | 1,196 | 4.21875 | 4 | '''
Write a function named firstNonRepeatingLetter that takes a string input, and returns the first character
that is not repeated anywhere in the string.
For example, if given the input 'stress', the function should return 't', since the letter t only
occurs once in the string, and occurs first in the string.
As an added challenge, upper- and lowercase letters are considered the same character,
but the function should return the correct case for the initial letter. For example, the input 'sTreSS' should
return 'T'.
'''
def first_non_repeating_letter(string):
# have characters in a list, normalize to lower
# loop through each character
# if it's in the list less than twice,return it
allChars = [i.lower() for i in string]
for i in string:
if allChars.count(i.lower()) < 2:
return i
return ""
print first_non_repeating_letter('hello world, eh?')#, 'w')
print first_non_repeating_letter('Go hang a salami, I\'m a lasagna hog!')#, ',')
print first_non_repeating_letter('abba')#, '')
print first_non_repeating_letter('aa')#, '')
print first_non_repeating_letter('a')#, 'a')
print first_non_repeating_letter('stress')#, 't')
print first_non_repeating_letter('moonmen')#, 'e') | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.