blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
fb4576c358165780a8d1dc143b1948f5284c89b6 | solareenlo/python_practice | /01_Pythonの基本/lesson05.py | 605 | 4.25 | 4 | """This is a test program."""
word: str = 'python'
print(word[0]) # 1番目の文字を出力
print(word[1]) # 2番目の文字を出力
print(word[-1]) # 最後の文字を出力
print(word[0:2]) # 1番目から2番目まで出力
print(word[2:3]) # 3番目から3番目まで出力
print(word[:2]) # 1番目から2番目まで出力
print(word[2:]) # 2番目から最後まで出力
# word[0] = 'j' これはできないので, 1文字目を変えたときは,
word: str = 'j' + word[1:]
print(word)
print(word[:]) # 全部表示
n: int = len(word) # 文字列の長さを返してくれる
print(n)
| false |
9413a4e410b9505695284fa2b78c50e6bedaab37 | solareenlo/python_practice | /09_データベース/sqlite1.py | 1,514 | 4.1875 | 4 | """ sqliteです. """
import sqlite3
# CONN = sqlite3.connect('test_sqlite.db')
CONN = sqlite3.connect(':memory:') # メモリ上にdbを仮に作ってくれる.テストしたい時に重宝する.
CURS = CONN.cursor()
# persons はtable name
CURS.execute('CREATE TABLE persons(id INTEGER PRIMARY KEY AUTOINCREMENT, name STRING)')
CONN.commit() # dbのidとnameの様式を設定.
CURS.execute('INSERT INTO persons(name) values("Mike")')
CONN.commit() # name にMikeを入力. idは自動で割り振られる.
CURS.execute('SELECT * FROM persons')
print(CURS.fetchall()) # [(1, 'Mike')] と出力.
CURS.execute('INSERT INTO persons(name) values("Taro")')
CURS.execute('INSERT INTO persons(name) values("Jiro")')
CONN.commit() # TaroとJiroを入力. idは自動で割り振られる.
CURS.execute('SELECT * FROM persons')
print(CURS.fetchall()) # [(1, 'Mike'), (2, 'Taro'), (3, 'Jiro')]と出力.
CURS.execute('UPDATE persons set name = "Michel" WHERE name = "Mike"')
CONN.commit() # 既存のデータを変更する
CURS.execute('SELECT * FROM persons')
print(CURS.fetchall()) # [(1, 'Michel'), (2, 'Taro'), (3, 'Jiro')]と出力.
CURS.execute('DELETE FROM persons WHERE name = "Michel"')
CONN.commit() # 既存のデータを削除する
CURS.execute('SELECT * FROM persons')
print(CURS.fetchall()) # [(2, 'Taro'), (3, 'Jiro')]と出力.
CURS.close()
CONN.close()
""" $ sqlite3 test_sqlite.db
$ .tables で, persons と出力される.
$ SELECT * from persons; で, 1|Mike と出力される.
"""
| false |
c82e6d4feb26fec86aa3bf73c1ddee88f157a81c | solareenlo/python_practice | /03_制御フローとコード構造/if.py | 390 | 4.1875 | 4 | """This is a test program."""
x: int = 0
if x < 0:
print('negative')
elif x == 0:
print('zero')
else:
print('positive')
a: int = 5
b: int = 10
# Pythonではインデントでif文の中身がどこからどこまでかを認識している
# Pythonのインデントは基本スペース4つ
if a > 0:
print('a is positive')
if b > 0:
print('b is positive')
| false |
118b5b95935e0002ead29be79fe91f4612cc8c6c | Dqvvidq/Nauka | /listy[].py | 1,565 | 4.1875 | 4 | #metoda upper
print("Witaj")
print("Witaj".upper())
#metoda replace
print("Witaj".replace("j", "m"))
#tworzenie listy
fruit = ["mango", "banan", "gruszka"]
print(fruit)
#metoda append czyli dodawanie nowego elementu na koncu listy
fruit.append("pomelo")
fruit.append("figa")
print(fruit)
#w liscie mozna zapisywac dane dowolnego typu
fruit.append(100)
fruit.append(True)
fruit.append(20.0)
print(fruit)
#listy mają indeksy od 0 do ...
print(fruit[0])
print(fruit[1])
print(fruit[2])
print(fruit[3])
#listy są elementami modyfikowalnymi
colors = ["fioletowy", "czerwony", "niebieski", "zołty"]
print(colors)
colors[2] = "biały"
print(colors)
#usuwanie elementu z listy
farba = ["żółta","niebieska", "zielona"]
print(farba)
item = farba.pop()
print(item)
print(farba)
#listy mozna połaczyc dzieki operatorom dodawania
k = farba + colors
print(k)
# za pomocą in można sprawidzic czy element znajduje sie w liscie
colors1 = ["czarny", "biały", "pomaranczowy"]
print("czarny" in colors1)
# żeby sprawdzić czy nie ma elementu na liście trzeba napisac przed in not (not in)
print("różowy" not in colors1)
print("czarny" not in colors1)
# liczba elementów listy
print(len(colors))
print(len(colors1))
# praktyczne wykorzystanie listy
lista_zakupow = ["masło", "chleb", "jajka", "kisiel", "mąka"]
zgadnij = input("Zgadnij element z listy: ")
if zgadnij in lista_zakupow:
print("Zgadłeś!!")
else:
print("nie zgadłes!")
| false |
d8c571e90d7dd059c6822e3070af55c222013d40 | Monisha1892/Practice_Problems | /pounds to kg.py | 270 | 4.1875 | 4 | weight = float(input("enter your weight: "))
unit = input("enter L for pounds or K for Kg: ")
if unit.upper() == 'L':
print("weight in kg is: ", (weight*0.45))
elif unit.upper() == 'K':
print("weight in lbs is: ", (weight*2.205))
else:
print("invalid unit") | true |
f7b5f0ff26048662dc0f1f78774fa3de56c1a8c7 | agnesazeqirii/examples | /sorting_a_list.py | 642 | 4.34375 | 4 | # In this program I'm going to sort the list in increasing order,
# so that the numbers will be ordered from the smallest to the largest.
myList = []
swapped = True
num = int(input("How many elements do you want to sort: "))
for i in range(num):
val = int(input("Enter a list element: "))
myList.append(val)
while swapped:
swapped = False
for i in range(len(myList) - 1):
if myList[i] > myList[i + 1]:
swapped = True
myList[i], myList[i + 1] = myList[i + 1], myList[i]
print("\nSorted:")
print(myList)
# If you want Python to sort your list, you can do it like this:
# print(myList.sort()) | true |
d768b394c739caf10b87e8bbc743f9abdaeb400e | shoaib90/Python_Problems | /Sets_Mutation.py | 2,574 | 4.59375 | 5 | # We have seen the applications of union, intersection, difference and symmetric difference operations, but these operations do
# not make any changes or mutations to the set.
# We can use the following operations to create mutations to a set:
# .update() or |=
# .intersection_update() or &=
# .difference_update() or -=
# .symmetric_difference_update() or ^=
# TASK
# You are given a set A and N number of other sets. These N number of sets have to perform some specific mutation operations on set A.
# Your task is to execute those operations and print the sum of elements from set A.
# Input Format
# The first line contains the number of elements in set A.
# The second line contains the space separated list of elements in set A.
# The third line contains integer N, the number of other sets.
# The next 2*N lines are divided into N parts containing two lines each.
# The first line of each part contains the space separated entries of the operation name and the length of the other set.
# The second line of each part contains space separated list of elements in the other set.
# Contraints:
# 0<len(set(A))<1000
# 0<len(otherSets)<1000
# 0<N<100
# Output Format
# Output the sum of elements in set A.
# Sample Input
# 16
# 1 2 3 4 5 6 7 8 9 10 11 12 13 14 24 52
# 4
# intersection_update 10
# 2 3 5 6 8 9 1 4 7 11
# update 2
# 55 66
# symmetric_difference_update 5
# 22 7 35 62 58
# difference_update 7
# 11 22 35 55 58 62 66
# Sample Output
# 38
#Answer
# Enter your code here. Read input from STDIN. Print output to STDOUT
n = int(input())
A = set(map(int, input().split()))
num_other_sets = int(input())
for i in range(num_other_sets):
try:
#First getting the operation and length
operation = input().split()
if operation[0] == 'intersection_update':
#Second getting the other SET.
B = set(map(int, input().split()))
A.intersection_update(B)
elif operation[0] == 'update':
#Second getting the other SET.
B = set(map(int, input().split()))
A.update(B)
elif operation[0] == 'symmetric_difference_update':
#Second getting the other SET.
B = set(map(int, input().split()))
A.symmetric_difference_update(B)
elif operation[0] == 'difference_update':
#Second getting the other SET.
B = set(map(int, input().split()))
A.difference_update(B)
except KeyError:
pass
count = 0
for i in A:
count = count + i
print(count) | true |
cd0c4829ca166148b49ed27059b791e4aebbd147 | Fifthcinn/Pirple.com_py-projects | /New Clean Assignment 4.py | 1,442 | 4.21875 | 4 | """
# 1. guestName = enter name to check if permissable
# 2. name gets entered into input
# 3. function checks name
# 4. if function returns true, name gets added to myUniqueList
# 5. if function returns false, name gets added to myLeftovers
# 6. print both lists
# 7. user gets asked if they would like to enter another name
# 6. if yes back to 2
# 9. if no, break
myUniqueList = []
myLeftOvers = []
guestName = ""
guest = ""
def guestRefuse(guest):
if myUniqueList == []:
return ""
elif guestName in myUniqueList:
# myLeftOvers.append(guestName)
return False
def guestEntry(guest):
if myLeftOvers == []:
return ""
elif guestName not in myUniqueList:
# myUniqueList.append(guestName)
return True
userChoice = ""
while userChoice == "":
guestName = input("\nTYPE 'END' TO CLOSE \nPlease enter name: ")
if guestName == "end":
break
if guestName in myUniqueList:
myLeftOvers.append(guestName)
print("myLeftOvers: " + str(myLeftOvers))
print(guestRefuse(guestName))
if guestName not in myUniqueList:
myUniqueList.append(guestName)
print("myUniqueList: " + str(myUniqueList))
print(guestEntry(guestName))
#print(guestRefuse(guestName))
#print(guestEntry(guestName))
# userChoice = input("Try another name? yes or no: ")
# if guestName == "end":
# break
#print(guestEntry("john"))
""" | true |
93e97c5ea1e0b4316abe797dc587bffd35f85432 | GiliScharf/my_first_programs | /print_dict_in_a_chart.py | 468 | 4.15625 | 4 | #this function gets a dictionary of {student's_name:average_of_grades} and prints a chart of it
def formatted_print(my_dictionary):
list_of_students=list(my_dictionary.keys())
new_list=[]
for student in list_of_students:
new_list.append([my_dictionary[student],student])
new_list.sort(reverse=True)
chart=""
for item in new_list:
chart=chart+"{0: <10s} {1: >5.2f}\n".format(item[1],item[0])
chart=chart[:-1]
print(chart) | true |
af74ef0de38c1ac94a530d6b5cfabccc9fa3bca6 | hitenjain88/algorithms | /sorting/heapsort.py | 949 | 4.3125 | 4 | def heap_sort(array):
'''
Implementation of Heap Sort in Python.
:param array: A array or a list which is supposed to be sorted.
:return: The same array or list sorted in Ascending order.e
'''
length = len(array)
for item in range(length, -1, -1):
heapify(array, item, length)
for count in range(length - 1, 0, -1):
array[count], array[0] = array[0], array[count]
heapify(array, 0, count)
return array
def heapify(sorted_array, element, length):
largest = element
left = 2 * element + 1
right = 2 * element + 2
if left < length and sorted_array[largest] < sorted_array[left]:
largest = left
if right < length and sorted_array[largest] < sorted_array[right]:
largest = right
if largest != element:
sorted_array[largest], sorted_array[element] = sorted_array[element], sorted_array[largest]
heapify(sorted_array, largest, length)
| true |
61d1db983af95bd86e051adf5eca11506c72fffb | jonesmabea/Algorithms | /fibonnaci/memo_bottom_up_fibonacci.py | 823 | 4.1875 | 4 | #Author: Jones Agwata
import timeit
def fibonacci(n):
'''
This is a memoized solution using a bottom up approach to the fibonacci problem.
f(n) = f(n-1)+f(n-2)...+f(n-n)
where f(0) = 0, f(1) = 1
params:
--------
n : int
n values to calculate fibonacci numbers
returns:
--------
int
fibonacci value for n values
'''
assert(n>=0), "N should be >= 0"
memo={}
memo[0]=0
memo[1]=1
for i in range(2,n+1,1):
memo[i] = memo[i-1]+memo[i-2]
return memo[n]
# print(fibonacci(100))#Wrapper for function arguments before using timeit
def wrapper(func, *args, **kwargs):
def wrapped():
return func(*args, **kwargs)
return wrapped
wrapped = wrapper(fibonacci, 20)
print(timeit.timeit(wrapped,number=1000))
| true |
02a23d7c548e3ac9293194e60c98f247e1e826f0 | MineSelf2016/PythonInEconomicManagement | /Part 1/Chapter 3/example 3.1 List.py | 811 | 4.125 | 4 | """
通用列表:
列表元素可以是任何类型,且元素间可以没有任何关系
字符串列表:
全部列表元素均为字符串的我们简称为字符串列表,如 ['This', 'is', 'a', 'bike.']
数字列表:
全部列表元素均为数字的我们简称为数字列表,如 [62, 65, 65, 64, 64, 63, 62, 63, 63, 63, 63, 62]
"""
print(['A','B','C','D','E','F','G'])
print([1, 2, 3, 4, 5, 6, 7, 8, 9, 0])
print(['A', 'B', 'C', 7, 8, 9])
print([[1, 2, 3], 'hello', 88, True, False])
_str = "This is a bike."
str_list = _str.split(" ")
print("字符串为 ", _str)
print("字符串列表为 = ", str_list)
weight = [62, 65, 65, 64, 64, 63, 62, 63, 63, 63, 63, 62]
sales = [1000, 2100, 1500, 3400, 5600, 4000, 5000]
print("weigh = ", weight)
print("sales = ", sales)
| false |
771a449b8bc71ab78ff207c4169c894391b78c59 | Antonynirmal11/Translator-using-python | /translator.py | 450 | 4.21875 | 4 | from translate import Translator
#translate module gives us the translation of the required language
fromlanguage=input("Enter your input language:")
tolanguage=input("Enter the required language:")
#getting input from the user and storing in a variable
translator= Translator(from_lang=fromlanguage,to_lang=tolanguage)
sentence=input("Enter the words you want to translate:")
translation = translator.translate(sentence)
print(translation)
| true |
dd848606c2d3690a58b55afcf70015906d1327eb | Ibramicheal/Onemonth | /Onemonth/tip.py | 607 | 4.21875 | 4 | # this calculator is going to determines the perecentage of a tip.
# gets bills from custome
bill = float(input("What is your bill? ").replace("£"," "))
print("bill")
# calculates the options for tips.
tip_one = 0.15 * bill
tip_two = 0.18 * bill
tip_three = 0.20 * bill
# prints out the options avaible.
print(f"You bill is {bill} and you have 3 options for a tip, option 1 is {tip_one:.2f}, option 2 is {tip_two:.2f}, option 3 is {tip_three:.2f}. ")
option_for_tip = float(input("Which option would you like to choice? "))
print(f"Thank you for choicing option {option_for_tip:.0f} .Please come agian.")
| true |
53b71592594b6f205d087b55c2c0614b40874e31 | MrozKarol/Python | /back-to-basic/transformacje danych/wyrazenia slownikowe.py | 538 | 4.25 | 4 | """
wyrażenie słownikowe
"""
names = {"Arkadiusz", "Wioletta", "Karol", "Bartłomiej", "Jakub", "Ania"}
numbers = [1, 2, 3, 4, 5, 6]
celcius = {'t1': -20, 't2': -15, 't3': 0, 't4': 12, 't5': 24}
nameLength ={
name : len(name)
for name in names
if name.startswith("A")
}
print(nameLength)
"""
przemnozenie razy 6
"""
mulitpledNumbers ={
number : number * 6
for number in numbers
}
print(mulitpledNumbers)
fahrebheit = {
key: celcius*1.8+ 32
for key, celcius in celcius.items()
}
print(fahrebheit) | false |
b09be0cfe6021aaca3563e65264ff47a7dd3137b | HMGulzar-Alam/Python_Assignment | /ass3.py | 1,354 | 4.28125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
# Q:1 Program make a simple calculator
# This function adds two numbers
def add(x, y):
return x + y
# This function subtracts two numbers
def subtract(x, y):
return x - y
# This function multiplies two numbers
def multiply(x, y):
return x * y
# This function divides two numbers
def divide(x, y):
return x / y
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
# Take input from the user
choice = input("Enter choice(1/2/3/4): ")
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == '1':
print(num1,"+",num2,"=", add(num1,num2))
elif choice == '2':
print(num1,"-",num2,"=", subtract(num1,num2))
elif choice == '3':
print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == '4':
print(num1,"/",num2,"=", divide(num1,num2))
else:
print("Invalid input")
# In[14]:
#Question: 02
n = [1, 2, 3, 4,'str',5,'ab',6]
for num in n:
if type(num) == int:
print("It is numeric Value")
else:
print("It is a string")
# In[ ]:
#Question: 035
list = []
num = int(input("How many number"))
for n in range(num):
number = int(input("Enter number"))
list.append(number)
print("list =", list)
print("lenght of the list =",len(list))
# In[ ]:
| true |
80bbca4bf830c9f11d1a8e3805e48bfb6b7b3e29 | dantsub/holbertonschool-higher_level_programming | /0x0B-python-input_output/4-append_write.py | 460 | 4.375 | 4 | #!/usr/bin/python3
"""
append write module
"""
def append_write(filename="", text=""):
""" Function that appends a string at the end of
a text file (UTF8) and returns the number of
characters added
Args:
filename (str): filename.
text (str): text to append the file.
Return:
Numbers of characters added.
"""
with open(filename, mode='a', encoding='utf-8') as file:
return file.write(text)
| true |
5fff47e5d1428707dd39fe97ce34b077cc11b902 | dantsub/holbertonschool-higher_level_programming | /0x0B-python-input_output/7-save_to_json_file.py | 408 | 4.15625 | 4 | #!/usr/bin/python3
"""
save to json file module
"""
import json
def save_to_json_file(my_obj, filename):
""" Function that writes an Object to a text file,
using a JSON representation
Args:
my_obj (object): an object.
filename (str): filename.
Return:
Nothing
"""
with open(filename, mode='w', encoding='utf-8') as file:
json.dump(my_obj, file)
| true |
40438fd29ec71fba2828e959c9352a25880b5d04 | Lyric912/conditionals | /secondary.py | 2,419 | 4.59375 | 5 | # author: Lyric Marner
# date: july 22, 2021
# --------------- # Section 2 # --------------- #
# ---------- # Part 1 # ---------- #
print('----- Section 2 -----'.center(25))
print('--- Part 1 ---'.center(25))
# 2 - Palindrome
print('\n' + 'Task 1' + '\n')
#
# Background: A palindrome is a word that is the same if read forwards and backwards. Examples of palindromes include:
# - mom
# - dad
# - radar
# - deified
#
# Instructions
# a. Prompt input from the user in the form of a word.
# b. Determine if the word is a palindrome.
# a. If so, print that the word is a palindrome.
# b. Otherwise, print that the word is not a palindrome.
word = input('Enter a word: ')
word = word.lower
length = len(word)
for i in range(1):
if length % 3 == 1:
print('This word is a palindrome!')
else:
print('This word is not a palindrome.')
# Make sure to add colons after your if statements so they run correctly.
# 2 - for Loop Patterns
print('\n' + 'Task 2' + '\n')
#
#
# Instructions
# a. Create at least two of the following patterns using for loops and conditionals. One has been done for you as an
# example. You still have to do two more. You are free to choose which ones you do.
# b. Use the symbol specified by the user.
# $$$$$ | i = 0
# $ | i = 1
# $ | i = 2
# $$$$$ | i = 3
# $ | i = 4
# $ | i = 5
# $$$$$ | i = 6
# When i is evenly divisible by 3 --> 5 symbols. Otherwise, 1 symbol.
s = input('>> symbol | ')
for i in range(7):
if i % 3 == 0:
print(s * 5)
else:
print(s)
print()
#
s = input('Enter a symbol: ')
for i in range(6):
if i == 5:
print(s * 5)
else:
print(s)
s = input('Enter a symbol: ')
for i in range(7):
if i % 6 == 0:
print(s * 4)
else:
print(s + ' ' * 3 + s)
# Write out the position of i for the patterns so it's easier to find the pattern that you can make code to.
# I used the addition symbol to add together the spaces and the singular symbols on each side to get the spaces within the pattern.
print()
# **** i = 0
# * * i = 1
# * * i = 2
# * * i = 3
# * * i = 4
# * * i = 5
# **** i = 6
# & i = 0
# & i = 1
# & i = 2
# & i = 3
# & i = 4
# &&&&& i = 5
# @ @
# @ @
# @ @
# @
# @ @
# @ @
# @ @
# -------
# -
# -
# -
# -
# -
# -------
| true |
e6c7ac66a67510483e211f99140504732579fed1 | Lamhdbk/liamhoang | /day_of_week.py | 663 | 4.3125 | 4 | # Python to find day of the week that given date
import re # regular expression
import calendar # module of python to provide useful function related to calendar
import datetime # module of python to get the date and time
def process_date(user_input):
user_input = re.sub(r"/", " ", user_input) #substitube/ with space
user_input = re.sub (r"-"," ", user_input)
return user_input
def find_day(date):
born = datetime.datetime.strptime(date, '%d %m %Y').weekday()
return (calendar.day_name[born])
user_input = str(input("enter date "))
date = process_date(user_input)
print("Day on" + user_input + "is " + find_day(date)) | true |
9a1aecb6c84c9d2d743e72cd5770ea2305c34377 | mevorahde/FCC_Python | /caculator.py | 540 | 4.125 | 4 | # Seventh Excises: Building a Basic Calculator
# YouTube Vid: Learn Python - Full Course for Beginners
# URL: https://youtu.be/rfscVS0vtbw
# Ask the user for a number and store the value into the variable num1
num1 = input("Enter a number: ")
# Ask the user for a second number and store the value into the variable num2
num2 = input("Enter another number: ")
# Convert both variables num1 and num2 to an float, add the two numbers and set value to the variable result
result = float(num1) + float(num2)
# print the variable result
print(result)
| true |
157f152e4ae2c05ec74055e537c65ae17c44926f | mevorahde/FCC_Python | /shape.py | 294 | 4.21875 | 4 | # Second Excises: Draw out a little triangle
# YouTube Vid: Learn Python - Full Course for Beginners
# URL: https://youtu.be/rfscVS0vtbw
# Example on how print statements can show output by buidling a triangle from print statements.
print(" /|")
print(" / |")
print(" / |")
print("/___|")
| true |
be055d9f72ac8c00c3c4561b34b32a58e054b583 | mevorahde/FCC_Python | /mad_lib_game.py | 639 | 4.46875 | 4 | # Eighth Excises: Building a Mad Libs Game
# YouTube Vid: Learn Python - Full Course for Beginners
# URL: https://youtu.be/rfscVS0vtbw
# Ask the user to enter in a color and set the value to the variable color
color = input("Enter a Color: ")
# Ask the user to enter in a plural noun and set the value to the variable plural_noun
plural_noun = input("Enter a Plural Noun: ")
# Ask the user to enter in a celebrity and set the value to the variable celebrity
celebrity = input("Enter a Celebrity: ")
print("")
# Add in the variables to the Mad Lib
print("Roses are " + color)
print( plural_noun + " are blue")
print("I love " + celebrity) | true |
8d0ba54ed431fcce3052153bb0567fb3a288fa3f | Marshea-M/Tech-Talent-Course-2021 | /HLW1Task5.py | 815 | 4.125 | 4 | user_input_number_a=int(input("Please type a random number"))
user_input_number_b=int(input ("Please type in another number"))
input_a=int(user_input_number_a)
input_b=int(user_input_number_b)
user_input_operator=input("Enter a to add, t to take-away, d to divide, m to multiply, p to power of or square the numbers you entered.")
if user_input_operator=='a':
print(user_input_number_a + user_input_number_b)
elif user_input_operator=='t':
print(user_input_number_a-user_input_number_b)
elif user_input_operator=='d':
print(user_input_number_a/user_input_number_b)
elif user_input_operator=='m':
print(user_input_number_a*user_input_number_b)
elif user_input_operator=='p':
print(user_input_number_a**user_input_number_b)
else:
print("This function isn't possible")
| true |
aad595f0c3eafc41f7895625456cdd62e6ce6952 | algorithmrookie/Alan | /week7/232. 用栈实现队列.py | 2,655 | 4.375 | 4 | class Stack(object):
def __init__(self):
self.stack = []
def push(self, x): # 入栈
self.stack.append(x)
def pop(self): # 出栈
if self.is_empty: # 注意特殊情况
return None
return self.stack.pop()
@property
def length(self): # 获取栈中元素
return len(self.stack)
@property
def is_empty(self): # 获取栈的状态:是否为空
return self.length == 0
class MyQueue(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.stack1 = Stack() # 基本栈
self.stack2 = Stack() # 辅助栈
def push(self, x):
"""
Push element x to the back of queue.
:type x: int
:rtype: None
"""
self.stack1.push(x) # 入栈,即入队列
def pop(self):
"""
Removes the element from in front of queue and returns that element.
:rtype: int
"""
while self.stack1.length > 1: # 卡住要出栈的最后一个元素
self.stack2.push(self.stack1.pop()) # 其他元素倒进辅助栈
res = self.stack1.pop() # 那个被卡住的元素就是所需
while not self.stack2.is_empty: # 只要辅助栈不为空
self.stack1.push(self.stack2.pop()) # 辅助栈中的元素倒回基本栈
return res # 返回栈底元素即为出队队头
def peek(self):
"""
Get the front element.
:rtype: int
"""
while self.stack1.length > 1: # 卡住要出栈的最后一个元素
self.stack2.push(self.stack1.pop()) # 其他元素倒进辅助栈
res = self.stack1.pop() # 那个被卡住的元素就是所需
self.stack2.push(res) # 记得把被卡住的元素放回
while self.stack2.length > 0: # 只要辅助栈不为空
self.stack1.push(self.stack2.pop()) # 辅助栈中的元素倒回基本栈
return res # 返回栈底元素即为出队队头
def empty(self):
"""
Returns whether the queue is empty.
:rtype: bool
"""
return self.stack1.is_empty # 队列的状态即为基本栈的状态
| false |
32e49868f39a879034c63316aed946cfb4a9ff28 | SathvikPN/learn-Tkinter | /entry_widget.py | 381 | 4.15625 | 4 | # Write a complete script that displays an Entry widget that’s 40 text units wide
# and has a white background and black text. Use .insert() to display text in the widget
# that reads "What is your name?".
import tkinter as tk
window = tk.Tk()
txt = tk.Entry(
width=40,
bg="white",
fg="black",
)
txt.insert(0, "What is your name?")
txt.pack()
window.mainloop() | true |
5e13544932db20738d00d6d9687c1081398db02f | srk0515/Flask_1 | /Test1.py | 1,939 | 4.46875 | 4 |
fruits=['apples','oranges','banana','grapes']
vege=['potato' ,'carrot']
print(fruits)
print(len(fruits))
print(fruits[3])
#negative index to come from reverse
print(fruits[-4])
#select index
print(fruits[0:3])
print(fruits[2:])
#add to end of list
fruits.append('pineapple')
#add to a position
fruits.insert(1,'mango')
print(fruits)
#add another list
fruits.extend(vege)
print(fruits)
#remove values from list
fruits.pop()
print(fruits)
#reverse order
fruits.reverse()
print(fruits)
#sort a list
fruits.sort()
print(fruits)
fruits.sort(reverse=True)
print(fruits)
#sorted function used to not alter orgonal list
sorted_fruit=sorted(fruits)
print(sorted_fruit)
numbs=[1, 2, 3, 4]
print(sum(numbs))
#get index
print(fruits.index('mango'))
#in
print('apples' in fruits)
for item in fruits:
print(item)
for fruit in fruits:
print(fruit)
for index, fruit in enumerate(fruits):
print(index,fruit)
#concatenate
fruit_str=',' .join(fruits)
print(fruit_str)
new_fruit= fruit_str.split(',')
print(new_fruit)
#tuple -immutable
tuple_1=(1,2,3,4)
#Sets
set1={'car','bike','truck','train','car'}
print(set1)
print('car' in set1)
set2={'bike' ,'spaceship' ,'train'}
print(set1.intersection(set2))
print(set1.difference(set2))
print(set1.union(set2))
empty_list1={}
empty_list=list()
empty_set=set()
empty_tuple=tuple()
#dict
student={'name':'Jason','age':'20','courses':['math','science']}
print(student)
print(student['name'])
print(student['age'])
print(student['courses'])
print(student.get('name'))
student['phone']='610-952-5555'
print(student)
student['name']='jane'
print(student)
student.update({'name':'Queen','phone':'5555'})
print(student)
del(student['age'])
print(student)
phone=student.pop('phone')
print(student)
print(len(student))
print(student.keys())
print(student.values())
print(student.items())
for key in student:
print(key)
for key,value in student.items():
print(key,value) | true |
0e48ed8599543295330d3616dfeb12b40b8c5501 | MaximJoinedGit/Algorithms-and-data-structures-on-Python | /lesson_2/homework_2.7.py | 1,518 | 4.125 | 4 | # 7. Написать программу, доказывающую или проверяющую, что для множества натуральных чисел выполняется равенство:
# 1+2+...+n = n(n+1)/2, где n — любое натуральное число.
from random import randint
# Для решения задачи мы определяем две функции. Одна будет считать результат левой части уравнения, вторая - правой.
# В конце их просто сравниваем.
def left_side(num):
if num > 1:
return num + left_side(num - 1)
return 1
def right_side(num):
return num * (num + 1) / 2
print('Для того, чтобы проверить равенство, проведем вычисления, подставив вместо n конкретное значение и '
'сранив результаты. Проведем вычисления 5 раз с разными значениями n. Для выбора значений n воспользуемся '
'случайными числами от 10 до 1000.')
for _ in range(5):
n = randint(10, 1000)
left_res = left_side(n)
right_res = right_side(n)
if left_res == right_res:
print(f'При n = {n} правая часть равна левой')
else:
print(f'При n = {n} части уравнения не равны')
| false |
b503ed85131d5e92ff78e6d5bb7295a8828a5627 | MaximJoinedGit/Algorithms-and-data-structures-on-Python | /lesson_3/homework_3.7.py | 949 | 4.21875 | 4 | # 7. В одномерном массиве целых чисел определить два наименьших элемента.
# Они могут быть как равны между собой (оба минимальны), так и различаться.
from random import randint
# Массив и два значения для минимальных значений - для самого минимального и второго после него.
nums = [randint(1, 100) for _ in range(10)]
min_num = min_after_min = None
for num in nums:
if min_num is None:
min_num = num
elif num <= min_num:
min_after_min = min_num
min_num = num
elif min_after_min is None or num < min_after_min:
min_after_min = num
print(f'В исходном массиве {nums} минимальный элемент {min_num}, а второй минимальный {min_after_min}.')
| false |
39df6a139d93b14558dcac71b883d6e5f314f1cd | Dallas-Hays/TLEN-5410 | /hws/hw3/15.1.py | 530 | 4.21875 | 4 | """ Dallas Hays
Exercise 15.1
Homework 3
"""
import math
class Point(object):
""" Represents a point in 2-D space."""
def distance_between_points(P1, P2):
""" Simply does the distance formula using the Point class
c^2 = a^2 + b^2
"""
a = (P1.y-P2.y)**2
b = (P1.x-P2.x)**2
c = math.sqrt(a+b)
return c
def main():
point1 = Point()
point2 = Point()
point1.x = 3.0
point1.y = 4.0
point2.x = 6.0
point2.y = 8.0
print distance_between_points(point1, point2)
main()
| false |
4e759fb1f149c8f5e512f338a8be9ef085b72d22 | bokerwere/Python-data-stracture | /python_if stm.py | 265 | 4.21875 | 4 | is_male=False
is_tall= True
if is_male and is_tall:
print("you are male or tall o r both")
elif is_male and not (is_tall):
print('you are dwaf')
elif not(is_male) and is_tall:
print("you are female and tall")
else:
print("ur neither male nor tall") | false |
5cdadf056bff7aeef9ca0c59272d9c976353b435 | Ashish-Goyal1234/Python-Tutorial-by-Ratan | /ProgrammesByRatan/3_Python_Concatenation.py | 494 | 4.125 | 4 | # In python it is possible to concatenate only similar type of data
print(10 + 20) # possible
print("ratan" + "ratan") # Possible
print(10.5 + 10.5) # Possible
print(True + True) # Possible
# print(10 + "ratan") # Not possible : We will face type error because both are different type of data
print(10+True) # Possible : Because true is 1 so possible.
print(10.5+False) # Possible
print(10+20.5) # Possible | true |
7747df62d4d274760d8b4efcd47134c888a7e195 | krmiddlebrook/Artificial-Neural-Network-practice | /ANNs/ANNs.py | 927 | 4.15625 | 4 |
# takes the input vectors x and w where x is the vector containing inputs to a neuron and w is a vector containing weights
# to each input (signalling the strength of each connection). Finally, b is a constant term known as a bias.
def integration(x,w,b):
weighted_sum = sum(x[k] * w[k] for k in xrange(0,len(x)))
return weighted_sum + b
# correctly computes this magnitude given an input vector as a list
def magnitude(x):
return sum(k**2 for k in x)**0.5
# Given a function gradient that has computed the gradient for a given function (and the ability to do vector addition),
# pseudocode for gradient descent would look like this:
def gradient_descent(point,step_size,threshold):
value = f(point)
new_point = point - step_size * gradient(point)
new_value = f(new_point)
if abs(new_value - value) < threshold:
return value
return gradient_descent(new_point,step_size,threshold) | true |
ba03262015d0a05c4b1eeb2824987a29dcc2f8a7 | monybun/TestDome_Exercise | /Pipeline(H10).py | 944 | 4.53125 | 5 | '''
As part of a data processing pipeline, complete the implementation of the pipeline method:
The method should accept a variable number of functions, and it should return a new function that accepts one parameter arg.
The returned function should call the first function in the pipeline with the parameter arg,
and call the second function with the result of the first function.
The returned function should continue calling each function in the pipeline in order,
following the same pattern, and return the value from the last function.
For example, pipeline(lambda x: x * 3, lambda x: x + 1, lambda x: x / 2)
then calling the returned function with 3 should return 5.0.
'''
def pipeline(*funcs):
def helper(arg):
for function in funcs:
arg = function(arg)
return arg
return helper
fun = pipeline(lambda x: x * 3, lambda x: x + 1, lambda x: x / 2)
print(fun(3)) #should print 5.0
| true |
e2b4fea85d7b916ae8fc86e0886c1190e2055e9c | monybun/TestDome_Exercise | /Shipping(E15).py | 2,278 | 4.28125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
A large package can hold 5 items, while the small package can hold only 1 item.
The available number of both large and small packages is limited.
All items must be placed in packages and used packages have to be filled up completely.
Write a function that calculates the minimum number of packages needed to hold a given number of items.
If it's not possible to meet the requirements, return -1.
For example, if we have 16 items, 2 large and 10 small packages,
the function should return 8 (2 large packages + 6 small packages).
"""
def minimal_number_of_packages(items, available_large_packages, available_small_packages):
min_load = 0; large = 0; small = 0
if (5*available_large_packages+available_small_packages) >= items:
if items != 0:
if items % 5 == 0:
if items/5 <= available_large_packages:
large = items/5
small = 0
min_load = large + small
elif items/5 > available_large_packages and (items- 5*available_large_packages) <= available_small_packages: # available_large_packages not enough
small = items - 5*available_large_packages
large = available_large_packages
min_load = large + small
else: min_load = -1
else: #items % 5 != 0
if items > 5 and (items-5*available_large_packages) <= available_small_packages:
large = available_large_packages
small = items - 5*large
min_load = large + small
elif items > 5 and (items-5*available_large_packages) > available_small_packages:
min_load = -1
elif items ==5:
large = 1
small = 0
min_load = large + small
elif items < 5:
large = 0
small = items
min_load = large + small
else: #items == 0
min_load = 0
else:
min_load = -1
return min_load
print(minimal_number_of_packages(16, 2, 10))
| true |
238363a6a8c8c3491e2e0af331513088f330216a | monybun/TestDome_Exercise | /routeplanner(H30).py | 2,621 | 4.5 | 4 | '''As a part of the route planner, the route_exists method is used as a quick filter if the destination is reachable,
before using more computationally intensive procedures for finding the optimal route.
The roads on the map are rasterized and produce a matrix of boolean values
- True if the road is present or False if it is not.
The roads in the matrix are connected only if the road is immediately left, right, below or above it.
Finish the route_exists method so that it returns True if the destination is reachable or False if it is not.
The from_row and from_column parameters are the starting row and column in the map_matrix.
The to_row and to_column are the destination row and column in the map_matrix.
The map_matrix parameter is the above mentioned matrix produced from the map.
For example, for the given rasterized map, the code below should return True since the destination is reachable:
map_matrix = [
[True, False, False],
[True, True, False],
[False, True, True]
];
route_exists(0, 0, 2, 2, map_matrix)
'''
def route_exists(from_row, from_column, to_row, to_column, map_matrix):
# read the matrix --> will return strings
matrix = map_matrix
#matrix = [i.strip() for i in matrix]
#matrix = [i.split() for i in matrix]
# find out matrix size
row = len(map_matrix); col = len(map_matrix[0])
if dfs():
print("Success!")
else:
print("Failure!")
def dfs(current_path):
from_row, from_column = 0,0
# anchor
from_row, from_column = current_path[-1]
if (from_row, from_column) == (to_row, to_column):
return True
# try all directions one after the other
for direction in [(from_row, from_column + 1), (from_row, from_column - 1), (from_row + 1, from_column), (from_row - 1, from_column)]:
new_row, new_col = direction
if (0 <= new_row < row and 0 <= new_col < col and # stay in matrix borders
matrix[new_row][new_col] == "False" and # don't run in walls
(new_row, new_col) not in current_path): # don't run in circles
# try new direction
current_path.append((new_row, new_col))
if dfs(current_path): # recursive call
return True
else:
current_path.pop() # backtrack
# result a list of coordinates which should be taken in order to reach the goal
if __name__ == '__main__':
map_matrix = [
[True, False, False],
[True, True, False],
[False, True, True]
];
route_exists(0, 0, 2, 2, map_matrix)
| true |
c59b935019ab6a665dcbe1b6f6c3fe062b6bb9ce | monybun/TestDome_Exercise | /Paragragh(E30).py | 1,676 | 4.15625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
An insurance company has decided to change the format of its policy numbers from
XXX-YY-ZZZZ to XXX/ZZZZ/YY (where X, Y and Z each represent the digits 0-9).
Write a method that re-formats all policy numbers in a well-formatted paragraph ('-' may appear elsewhere in the text).
For example, change_format("Please quote your policy number: 112-39-8552.")
should return "Please quote your policy number: 112/8552/39.".
"""
#phonenumber= "(516)111-2222"
#regex= "\(\w{3}\)\w{3}-\w{4}"
#112-39-8552
#regex = r"\d{3}-\d{2}-\d{4}"
#regexing: https://dev.to/samcodesign/phone-number-email-extractor-with-python-12g2
'''
line = re.sub(r"""
(?x) # Use free-spacing mode.
< # Match a literal '<'
/? # Optionally match a '/'
\[ # Match a literal '['
\d+ # Match one or more digits
> # Match a literal '>'
""", "", line)
'''
#joining the strings to be replaced with | to a regex and delimiting it with \b word boundary characters,
#e.g. \b(a|b|c)\b in your case, and use a dictionary to look up the proper replacements.
import re
def change_format(paragraph):
original_format = re.findall("\d{3}-\d{2}-\d{4}", paragraph)
repalce_lst = []
for j in original_format:
number = re.findall(r'\d+', j)
regex_digits = '/'.join([number[0],number[2],number[1]])
repalce_lst.append(regex_digits)
d = dict(zip(original_format, repalce_lst))
p = r'\b(' + '|'.join(original_format) + r')\b'
reformed = re.sub(p, lambda m: d.get(m.group()), paragraph)
return reformed
print(change_format('Please quote your policy number: 112-39-8552 116-60-7623.'))
| true |
cbc8c2cec4729218bbccf1cdf6a78d9f74e26245 | PWynter/paper_scissors_stone | /paper_scissors_stone2.0.py | 1,164 | 4.25 | 4 | """Paper,scissors,stone game.player selects an option,computer option is random """
# import random and the randint function to generate random numbers
from random import randint
# assign player an user input
player = input("rock (r), paper (p) or scissor (s)? ")
# print the user input, end tells python to end with a space not new line
print(player, "vs ", end="")
# selects random num from range
chosen = randint(1, 3)
# print(chosen)
# uses chosen variable and assigns computer a letter
if chosen == 1:
computer = "r"
elif chosen == 2:
computer = "p"
else:
computer = "s"
# prints random letter thats been assigned to computer from using randint
print (computer)
# who wins
if player == computer:
print("Draw")
elif player == "r" and computer == "s":
print("Player wins!")
elif player == "r" and computer == "p":
print("Computer wins!")
# who wins
elif player == "p" and computer == "r":
print("Player wins!")
elif player == "p" and computer == "s":
print("Computer wins!")
# who wins
elif player == "s" and computer == "r":
print("Computer wins!")
elif player == "s" and computer == "p":
print("Player wins!")
| true |
0f02b53e49e2bfc742e22830db6b2e9d42423538 | archanakul/ThinkPython | /Chapter8-Strings/RotateString.py | 1,526 | 4.34375 | 4 | #PROGRAM - 18
"""
1. ORD() -> Given a string of length one, return an integer representing the
value of the byte
ord('a') -> 97
2. CHR()-> Return a character whose ASCII code is the integer i. The
argument must be in the range [0..255]
chr(97) -> 'a'
"""
def rotate_word(word, shift):
""" To rotate a letter means to shift it through the alphabets, wrapping
around to the beginning if necessary, so 'A' shifted by 3 is 'D' & 'Z'
shifted by 1 is 'A'. """
new_word = ''
while(shift >= 26):
shift = shift - 26
for c in word:
if c.islower():
z = ord('z')
a = ord('a')
else:
z = ord('Z')
a = ord('A')
if c.isalpha():
if ((ord(c) + shift) >= a ) and ((ord(c) + shift) <= z) :
new_word += chr(ord(c) + shift)
elif (ord(c) + shift) < a :
new_word += chr(z + (ord(c) - a) + shift + 1)
elif (ord(c) + shift) > z :
new_word += chr(ord(c) + shift - z)
else:
new_word += chr(ord(c) + shift)
return new_word
word = raw_input("Enter a word to be rotated: ")
shift = raw_input("Enter the number of shifts: ")
try:
shift = int(shift)
except:
print "Shift value need to be integer"
quit()
print '"' + word + '" shifted by ' + str(shift) + ' times is "' + rotate_word(word, shift) + '"' | true |
93a1ed0d22f242ddbdb099c2ac273bc741400b10 | archanakul/ThinkPython | /Chapter2-Variables/Arithmetics.py | 2,210 | 4.40625 | 4 | #PROGRAM - 2
# Operators are special symbols that represent computations
# There are basically two types of numeric data types - integer & floating point
# Comma separated sequence of data is printed out with spaces between each data
print 3,-5,56.98,-45.56
# Pre-defined function(type) prints out data type for the input parameters
print type(5.0), type (5)
# Python has pre-defined functions for EXPLICIT DATA TYPE CONVERSIONS - INT(truncates decimal part ),FLOAT(adds a decimal point followed by 0)
print int(56.98), float(4)
# Floating point numbers have 15 decimal digit accuracy in python
print 3.1415926535897932384626433832795028841971 #3.141592653589793
# Arithmetic Operators in Python include - +(Addition), -(Subtraction), * (Multiplication), / (Devision-Quotient), ** (Power to), % (Modulus -remainder)
print (1+3), (5-6), (5*2), (2**4)
#P ython 2 division varies for integer division & floating point divisions
print (25/4)
print (25.0/4), (25/4.0), (25.0/4.0)
# Operator - // is forced integer division(FLOOR DIVISION- chops off the fractional part) in python 2 but the output type depends on the data itself!!
print 25//4, type(25//4)
print (25.0//4), type(25.0//4)
# Modulus operator divides two numbers & returns the remainder & the output type again depends on the type of input types
print 25%4, type(25%4)
print 25.0%4.0, type (25.0%4.0)
# when SIGNED integer division is done then the values are rounded up(smallest negative number is a bigger figure) otherwise they are rounder down
print (-9/4), (9/4)
# Expression - Combination of operators & operands
# Arithmetic Operator precedence-PEMDAS or Left to Right-(),** , * & / , + & -
# Arithmetic operators that work on strings are + (concatenation) & *(repetition)
print "Arch" + "ana"
print "hola" * 2
print (4.0/3) * 3.14 * (5**3)
start_sec = (6*60+52)*60.0 # 6:52 am
easy_sec = (8*60+15)*2.0 # 2 miles, each with 8min,15 Secs
fast_sec = (7*60+12)*3.0 # 3 miles, each with 7 min, 12 secs
finish_hour = (start_sec + easy_sec + fast_sec)//(60*60)
finish_minute = (((start_sec + easy_sec + fast_sec)/(60*60)) - finish_hour)*60.0
print 'Finish time was', int(finish_hour) , ':', int(finish_minute) # 7:30 am return
| true |
aadd007d43366ef0d66700a55aa411dbb37c2f1c | archanakul/ThinkPython | /Chapter10-Lists/NonRepeatedWords.py | 708 | 4.40625 | 4 | #PROGRAM - 27
"""
Open the file & read it line by line. For each line, split the line into a list of words using the split() function. The program should build a list of words. For each word on each line check to see if the word is already in the list and if not append it to the list.
When program completes, sort & print the resulting words in alphabetical order.
"""
fname = raw_input("Enter file name: ")
if len(fname) < 1 :
fname = "romeo.txt"
fh = open(fname)
lst = list()
for line in fh:
line = line.rstrip()
words = line.split()
for word in words:
if word not in lst:
lst.append(word) # adds in an element at the end of a list
lst.sort()
print lst | true |
d259e7fc46a18ed2e34e87bf02599bdfdf71662d | archanakul/ThinkPython | /Chapter7-Iteration/NewtonsSquareRoot.py | 1,329 | 4.34375 | 4 | #PROGRAM - 16
"""
1. Suppose we need to compute square root of A with an estimate of x then a
new better estimate for root of A would be determined by Newtons formula:
y = (x + A/x)/2
2. Floating point values rae only approximately right; hence rational 1/3 &
irrational number root(2) can not be represented directly using floats.
3. abs() -> Buil-in function to compute the absolute value or magnitude of
difference between floating point values.
4. COMMA at the end of a print statement enable the result of next line also
to be printed on the same line which other wise comes on the new line as
each print statement introduces a new line at the end of it.
"""
import math
x = 1.0
epsilon = 0.0000001
def NewtonRoot(num):
global x, epsilon
while (True):
y = (x + num/x)/2
if (abs(y - x) < epsilon):
break
x = y
return y
while(True):
num = raw_input("Enter a number to compute Square Root: ")
try:
num = float(num)
break
except:
print "Enter a number!!"
continue
print str(num) + ' ',
print str(NewtonRoot(num)) + ' ',
print str(math.sqrt(num)) + ' ',
print str(abs(NewtonRoot(num) - math.sqrt(num)))
| true |
7c42789a83805552f67295596a668aa60ffdfc03 | archanakul/ThinkPython | /Chapter10-Lists/Anagram.py | 876 | 4.28125 | 4 | #PROGRAM - 30
"""
Two words are anagrams if you can rearrange the letters from one to
spell the other.
1. list.REMOVE(x): Removes the first appearance of x in the list.
ValueError if x is not found in the list.
2. list.POP([,index]): Removes an item at a specified location or at the end
of the list in 'index' is not provided.
3. LIST(): converts a string into a list of characters of the string
"""
def is_anagram(word1, word2):
""" It takes two strings and returns True if they are anagrams """
word1 = list(word1)
word2 = list(word2)
if len(word1) != len(word2):
return False
else:
for letter in word1:
if letter not in word2: # To avoid ValueError
return False
word2.remove(letter)
return True
print is_anagram("abcc","cbac") | true |
0dddfbb0e2d6d2a3e52258584021fbdc940cc6cf | hanzijun/python-OOB | /Useful records for __new(init)__ function.py | 830 | 4.375 | 4 | #!/usr/bin/python
"""
__new/init__ use case for python
"""
class Person(object):
def __new__(cls, age):
print "Person.__new__ called"
return super(Person, cls).__new__(cls, age)
def __init__(self, age):
print "Person.__init__ called"
self.age = age
def fn(self):
print "Person fn"
class Man(object):
def __new__(cls, age):
print "Man.__new__ called"
if age > 10:
return super(Man, cls).__new__(cls, age)
return Person(age)
def __init__(self, age):
print "Man.__init__ called"
self.age = age
def fn(self):
print "Man fn"
a = Man(5)
The results are :
#Man.__new__ called
#Person.__new__ called
#Person.__init__ called
a = Man(15)
The results are :
#Man.__new__ called
#Man.__init__ called
| false |
fc6bd938ae69394a075411a723b01db7f119e569 | varunbarole/cg_python_day2 | /test1.py | 252 | 4.15625 | 4 |
a= int(input("Enter any value :"))
b= int(input("Enter any value :")
if a<b :
print (" a is less value")
print("inside ifblock")
else:
print ("b is less")
print("inside else block")
print("outside else block")
| false |
14c6140f6a35591767c4d712c782d8235396995a | jhn--/mit-ocw-6.0001-fall2016 | /ps4/ps4a.py | 2,827 | 4.375 | 4 | # Problem Set 4A
# Name: <your name here>
# Collaborators:
# Time Spent: x:xx
def get_permutations(sequence):
'''
Enumerate all permutations of a given string
sequence (string): an arbitrary string to permute. Assume that it is a
non-empty string.
You MUST use recursion for this part. Non-recursive solutions will not be
accepted.
Returns: a list of all permutations of sequence
Example:
>>> get_permutations('abc')
['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
Note: depending on your implementation, you may return the permutations in
a different order than what is listed here.
'''
# pass #delete this line and replace with your code here
# base case
if len(sequence) == 1: # if there's only one letter in sequence
return [sequence] # return sequence (in a list!!!)
# remove one letter from the front of sequence (to be inserted)
# and pump the remaining letters back
# into permutations() whose results
# will be the permutations of the
# remaining letters
list_of_permutations = get_permutations(sequence[1:])
letter_to_insert = sequence[:1]
result = [] # results to hold permutations
# loop through each element in the list_of_permutations
for permutation in list_of_permutations:
# loop through each position of the permutation
for i in range(len(permutation)+1):
# inser the removed letter into the permutations
# in the positition (i) as (i) traverse across
result.append(permutation[:i] + letter_to_insert + permutation[i:])
return result
if __name__ == '__main__':
# #EXAMPLE
# example_input = 'abc'
# print('Input:', example_input)
# print('Expected Output:', ['abc', 'acb', 'bac', 'bca', 'cab', 'cba'])
# print('Actual Output:', get_permutations(example_input))
# # Put three example test cases here (for your sanity, limit your inputs
# to be three characters or fewer as you will have n! permutations for a
# sequence of length n)
# pass #delete this line and replace with your code here
input = 'abc'
print('Input: ', input)
print('Expected Output: ', ['abc', 'acb', 'bac', 'bca', 'cab', 'cba'])
print('Actual Output: ', get_permutations(input))
input = 'ab'
print('Input: ', input)
print('Expected Output: ', ['ab', 'ba'])
print('Actual Output: ', get_permutations(input))
input = 'abcd'
print('Input: ', input)
print('Expected Output: ', ['abcd', 'bacd', 'bcad', 'bcda', 'acbd', 'cabd', 'cbad', 'cbda', 'acdb', 'cadb',
'cdab', 'cdba', 'abdc', 'badc', 'bdac', 'bdca', 'adbc', 'dabc', 'dbac', 'dbca', 'adcb', 'dacb', 'dcab', 'dcba'])
print('Actual Output: ', get_permutations(input))
| true |
7d808f0e1adf7d613b2e2aa4112e70f4d6b8a4c9 | carol3/python_practice | /area.py | 468 | 4.46875 | 4 | #this program calculates the perimeter and area of a rectangle
print("calculate information about a rectangle")
length=float( input("length :"))#python 3.x,input returs a string so height and length are string you need to convert them to either integers or floa
width= float(input("width :"))
area=length * width
print("area" ,area)
perimeter=2 * length + 2 * width
print("perimeter",perimeter )
radius=float(input("radius :"))
area=radius*2*3.14
print("area" , area) | true |
daa12bc0019384815c57854b2eb2cdf43d89f39a | tutorial0/wymapreduce | /maprq.py | 1,165 | 4.125 | 4 | # email: ringzero@0x557.org
"""this is frequency example from mapreduce"""
def mapper(doc):
# input reader and map function are combined
import os
words = []
with open(os.path.join('./', doc)) as fd:
for line in fd:
for word in line.split():
if len(word) > 3 and word.isalpha():
words.append((word.lower(), 1))
return words
def reducer(words):
# we should generate sorted lists which are then merged,
# but to keep things simple, we use dicts
word_count = {}
for word, count in words:
if word not in word_count:
word_count[word] = 0
word_count[word] += count
# print('reducer: %s to %s' % (len(words), len(word_count)))
return word_count
word_count = {}
for f in ['doc1', 'doc2', 'doc3', 'doc4', 'doc5']:
words = mapper(f)
for word, count in reducer(words).iteritems():
if word not in word_count:
word_count[word] = 0
word_count[word] += count
# sort words by frequency and print
for word in sorted(word_count, key=lambda x: word_count[x], reverse=True):
count = word_count[word]
print(word, count)
| true |
5b664be18aef55007dc80dc42469355ba23df07b | mhmtnzly/Class5-Python-Module-Week5 | /q1.py | 1,597 | 4.5 | 4 | # Question 1:
# Create the class `Society` with following information:
# `society_name`, `house_no`, `no_of_members`, `flat`, `income`
# **Methods :**
# * An `__init__` method to assign initial values of `society_name`, `house_no`, `no_of_members`, `income`
# * `allocate_flat()` to allocate flat according to income using the below table -> according to income, it will decide to flat type
# * `show_data()` to display the details of the entire class.
# * Create one object for each flat type, for each object call `allocate_flat()` and `show_data()`
# | Income | Flat |
# | ------------- |:-------------:|
# | >=25000 | A Type |
# | >=20000 and <25000 | B Type |
# | >=15000 and <20000 | C Type |
# | <15000 | D Type |
class Society:
def __init__(self,society_name,house_no,no_of_members,income):
self.society_name=society_name
self.house_no=house_no
self.no_of_members=no_of_members
self.income=income
def allocate_flat(self):
if self.income>=25000:
flat='A Type'
elif 25000>self.income>=20000:
flat='B Type'
elif 20000>self.income>=15000:
flat='C Type'
else:
flat='D Type'
return flat
def show_data(self):
print(f'Society name: {self.society_name} \nHouse no: {self.house_no}\nNo of Members: {self.no_of_members}\nIncome: {self.income}\nFlat:{self.allocate_flat()}')
society_name1=Society('Test',25,6,22500)
society_name1.show_data()
society_name2=Society('Test2',12,4,16000)
society_name2.show_data() | false |
4803daa3f6b0403bcfa273453ff17a8a82c70aa1 | gsrini27/mit-intro-comp-sci | /hypotenuse-function.py | 237 | 4.21875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 19 09:56:50 2017
@author: aspen
"""
import math
def hypotenuse(a, b):
c_squared = a**2 + b**2
c = math.sqrt(c_squared)
return c
print(hypotenuse(2, 3)) | false |
14bbf3967879173105be97c07de88a9d5428f4c7 | deref007/python_crwal | /python_crawl/learn5.py | 1,645 | 4.25 | 4 | #面向对象的编程
#类:具有某种特征的事物的集合
#对象:群体(类)里面的分体
#类是抽象的,对象是具体的
'''
格式:
class 类名:
类里面的内容
'''
'''构造函数或者称为构造方法
__init__(self,参数)
在类中的方法必须加上self
其实际意义:初始化
'''
class cla():
def __init__(self):
print('I am deref')
a=cla()
'''
给类加上参数:给构造函数加上参数
'''
class cla1():
def __init__(self,name,job):
print('my name is ' + name+';'+' my job is '+job)
b=cla1('deref','student')
'''
属性和方法
属性:类里面的变量
'''
class cla2():
def __init__(self,name,job):
self.my_name=name
self.my_job=job
c=cla2('deref','student')
print(c.my_name)
print(c.my_job)
'''
方法:类里面的函数
def 函数名(self,参数):
'''
class cla3():
def fun1(self,name):
print('test a 方法:',name)
d = cla3()
d.fun1('python')
class cla4():
def __init__(self,name):
self.my_name=name
def fun2(self):
print('hello',self.my_name)
e= cla4('deref')
e.fun2()
'''
继承与重载
'''
#父类:格式:class(基类)
class father():
def speak(self):
print('I can speak')
#子类:
class son1(father):
pass
f=son1()
f.speak()
#母类:
class mother():
def write(self):
print('I can write')
#多继承:
class daughter(father,mother):
def leason(self):
print('I can leasoning')
g=daughter()
g.speak()
g.write()
g.leason()
#重载:
class son2(father):
def speak(self):
print('I can speak fastly')
h=son2()
h.speak()
| false |
793005bc597f60a2f2cc454371031ebfac601ee9 | amaranmk/comp110-21f-workspace | /lessons/iterating-through-a-collection.py | 326 | 4.125 | 4 | """Example of looping through all cahracters in a string."""
__author__ = "730484862"
user_string: str = input("Give me a string! ")
# The variable i is a common counter variable name
# in programming. i is short for iteration
i: int = 0
while i < len(user_string):
print(user_string[i])
i = i + 1
print("Done!")
| true |
ee18ee10aa7d4bae891647b8f256d62fab78913e | vintell/itea-py_cource | /hw_1_1.py | 1,498 | 4.28125 | 4 | # constants
DAYS_IN_MONTH = 30
MONTHS_IN_YEAR = 12
DAY_IS_NOW = 19
MON_IS_NOW = 11
YEAR_IS_NOW = 2018
# init
is_error = False
# inputs
f_name = input('What is your first name: ')
l_name = input('What is your last name: ')
print('Hey, ', f_name, ' ', l_name, '.')
# day_ = 3
# mon_ = 9
# year_ = 1982
day_ = int(input('Enter your day of birthday: '))
if day_ == 31:
day_ = 30
elif day_ > 31 or day_ < 1:
is_error = True
mon_ = int(input('Enter your month of birthday: '))
if mon_ > 12 or mon_ < 1:
is_error = True
year_ = int(input('Enter your year of birthday: '))
if year_ > YEAR_IS_NOW:
is_error = True
if is_error:
print('Wrong entered date.')
else:
# calculate days in totally
days_are_alive = (DAY_IS_NOW - day_)
days_are_alive = days_are_alive + ((MON_IS_NOW - mon_) * DAYS_IN_MONTH)
days_are_alive = days_are_alive + (YEAR_IS_NOW - year_) * MONTHS_IN_YEAR * DAYS_IN_MONTH
#
leaved_y = days_are_alive // (MONTHS_IN_YEAR * DAYS_IN_MONTH)
leaved_m = (days_are_alive - (leaved_y * (MONTHS_IN_YEAR * DAYS_IN_MONTH))) // DAYS_IN_MONTH
leaved_d = (days_are_alive - (leaved_y * (MONTHS_IN_YEAR * DAYS_IN_MONTH)) - (leaved_m * DAYS_IN_MONTH))
print(f_name, ' ', l_name, ' You have been live ', days_are_alive, ' days till ', DAY_IS_NOW, '.', MON_IS_NOW, '.', YEAR_IS_NOW, '.', sep='')
print('Or is totally: ', leaved_y, ' year(-s) and', leaved_m, ' month(-s) and ', leaved_d, ' day(-s).')
| false |
e2bbdc6f21dadd89fddbfc0bbc4c8149b8477143 | vintell/itea-py_cource | /exam/pyca.py | 1,943 | 4.40625 | 4 | from math import cos as mycos, sin as mysin
def plus(val_1, val_2):
"""
This is calculate a sum for two params
:param val_1: int or float
:param val_2: int or float
:return: int or float
"""
return val_1 + val_2
def minus(val_1, val_2):
"""
This is calculate a different for two params
:param val_1: int or float
:param val_2: int or float
:return: int or float
"""
return val_1 - val_2
def multi(val_1, val_2):
"""
This is calculate multiplication of two params
:param val_1: int or float
:param val_2: int or float
:return: int or float
"""
return val_1 * val_2
def divide(val_1, val_2):
"""
This is calculate a divide of two params
:param val_1: int or float
:param val_2: int or float
:return: int or float or None
"""
if val_2 == 0:
raise ZeroDivisionError('{} / {} = {}'.format(val_1, val_2, 'division by zero error'))
return val_1 / val_2
def power(value, power):
"""
This is calculate a power
:param value: int or float - number
:param power: int or float - in power
:return: int or float or None
"""
return value ** power
def modulus(val_1, val_2):
"""
This is calculate a divide of two params and return rest
:param val_1: int or float
:param val_2: int or float
:return: int or float or None
"""
if val_2 == 0:
raise ZeroDivisionError('{} % {} = {}'.format(val_1, val_2, 'division by zero error'))
return val_1 % val_2
def cos(var_1):
"""
Return a Cosine for angle.
:param var_1: int or float as "Angle in degrees"
:return: int or float
"""
return mycos(var_1)
def sin(var_1):
"""
Return a Sine for angle.
:param var_1: int or float as "Angle in degrees"
:return: int or float
"""
return mysin(var_1)
| true |
76d900d7761432964196dd76b30c739739ac9d4b | JunYou42/PY4E | /EX2_3.py | 276 | 4.15625 | 4 | # programm to promt the user for hours and rate per hour using
# input to compute gross pay
#get string type
hrs = input("Enter hours:")
rate = input("Enter rate per hour:")
#convert to floating points
hrs = float(hrs)
rate = float(rate)
print('Pay:',hrs*rate)
| true |
c07d520fd5a69db8729a6749d948ca475ee61c51 | deorelaLara/PythonPruebas | /PracticasLibro/moreGuests.py | 1,481 | 4.71875 | 5 | """ 3-6. More Guests: You just found a bigger dinner table, so now more space is available.
Think of three more guests to invite to dinner.
• Start with your program from Exercise 3-4 or Exercise 3-5. Add a print statement to
the end of your program informing people that you found a bigger dinner table.
• Use insert() to add one new guest to the beginning of your list.
• Use insert() to add one new guest to the middle of your list.
• Use append() to add one new guest to the end of your list.
• Print a new set of invitation messages, one for each person in your list."""
guests = ['Haru', 'Omar', 'Melissa', 'Rebeca']
print("Hi everybody i found a bigger dinner table!!! \n")
#Add to the bigining
guests.insert(0, 'Genesis')
#print(guests)
#Add to the middle
guests.insert(3, 'Frida')
#print(guests)
#Ue append to add one new guest
guests.append('Ana')
#print(guests)
print("-Hello dear " + guests[-2] + " i hope u' can join me at my birthday dinner." )
print("-Hi!!! " + guests[0] + " I wait for u' at my birthday dinner.")
print("-Hey "+ guests[-1] + " !!! Remember today's my birthday dinner")
print("-Sup " + guests[1] + " I hope you can joinme at my dinner")
print("-Hi!!! " + guests[2] + " I wait for u' at my birthday dinner.")
print("-Hey "+ guests[3] + " !!! Remember today's my birthday dinner")
print("-Hey "+ guests[4] + " !!! Remember today's my birthday dinner")
| true |
d2ad1c2858888cb06bf244becbf5b63bf67dadf8 | jeremymiller00/Intro-Python | /Strings/strings.py | 1,492 | 4.5625 | 5 | #!/usr/bin/env python
"""
Strings Examples
This week continues where we left off working with strings. This week we will
cover string slicing, and a little bit of string formatting.
"""
firstName = "Rose"
lastName = "Tyler"
areaCode = 212
exchange = 664
numSuffix = 7665
print "We can cancatinate strings with the + sign"
print "fullName = firstName + lastName"
fullName = firstName + lastName
print 'Full Name: ' + fullName
print ' '
print "You can't cancatinate numbers like string"
print "wrongNumber = areaCode + exchange + numSuffix"
wrongNumber = areaCode + exchange + numSuffix
print 'Wrong Number: %s' % wrongNumber
print ' '
print 'String can be sliced using slice notation'
print 'Slice Notation is [start:exclusive end]'
print 'firstName[0]'
print firstName[0]
print 'firstName[0:3] excludes last character'
print firstName[0:3]
print ' '
print 'We can print the last char of a string using negative numbers'
print 'firstName[-1]'
print firstName[-1]
print ' '
print "Skip first three characters"
print "fullName[3:]"
print fullName[3:]
print ' '
print "Print First 4 Characters"
print "fullName[:4]"
print fullName[:4]
# Format a phone number
print '({0}) {1}-{2}'.format(areaCode,exchange,numSuffix)
# First Initial Last name
print '{0}. {1}'.format(firstName[0],lastName)
# Left Aligned
print '*' + '{0:<30}'.format("Doctor Who") + '*'
# Centered
print '*' + '{0:^30}'.format("Doctor Who") + '*'
# Right Aligned
print '*' + '{0:>30}'.format("Doctor Who") + '*'
| true |
6b5c293acad498cf0b7f26e4d1977a211b3bd076 | chagan1985/PythonByExample | /ex077.py | 855 | 4.1875 | 4 | #####
# Python By Example
# Exercise 077
# Christopher Hagan
#####
attendees = []
for i in range(0, 3):
attendees.append(input('Enter the name of someone to invite to a party: '))
addAnother = 'y'
while addAnother.lower().startswith('y'):
addAnother = input('Would you like to add another guest: ')
if addAnother.startswith('y'):
attendees.append(input('Enter the name of another guest to invite to the party: '))
print('You have invited {} people to your party!'.format(len(attendees)))
print(attendees)
choosenAttendee = input('Enter the name of one of the party guests: ')
print('This guest has index {} in the list'.format(attendees.index(choosenAttendee)))
deleteAttendee = input('Would you still like this guest to attend the party? ')
if deleteAttendee.lower().startswith('n'):
attendees.remove(choosenAttendee)
print(attendees)
| true |
a603015ffb99493e82f42df18488b22ec4ec84b8 | chagan1985/PythonByExample | /ex041.py | 327 | 4.1875 | 4 | #####
# Python By Example
# Exercise 041
# Christopher Hagan
#####
name = input('Please enter your name: ')
repetitions = int(input('How many times should I repeat your name: '))
if repetitions < 10:
textToRepeat = name
else:
textToRepeat = 'Too high'
repetitions = 3
for i in range(0, repetitions):
print(textToRepeat)
| true |
57797f4406bea4c20b5c1927b0f1430e85bc2a07 | chagan1985/PythonByExample | /ex038.py | 283 | 4.15625 | 4 | #####
# Python By Example
# Exercise 038
# Christopher Hagan
#####
name = input('Please enter your name: ')
repetitions = int(input('How many times should I loop through the characters in'
' your name? '))
for i in range(0, repetitions):
print(name[i % len(name)])
| true |
5bb0caaa44ae8d6285d30914d98971a9c3a73ca7 | chagan1985/PythonByExample | /ex093.py | 431 | 4.125 | 4 | #####
# Python By Example
# Exercise 093
# Christopher Hagan
#####
from array import *
nums = array('i', [])
removedNums = array('i', [])
while len(nums) < 5:
newNum = int(input('Enter a number to append to the array: '))
nums.append(newNum)
nums = sorted(nums)
print(nums)
userChoice = int(input('Enter a number to move to the new array: '))
nums.remove(userChoice)
removedNums.append(userChoice)
print(nums)
print(removedNums)
| true |
3d7db392ce92cab8018a429e87054ff9f3f54e9a | chagan1985/PythonByExample | /ex142.py | 510 | 4.34375 | 4 | #####
# Python By Example
# Exercise 142
# Christopher Hagan
#####
import sqlite3
with sqlite3.connect("BookInfo.db") as db:
cursor = db.cursor()
cursor.execute("""SELECT * FROM Authors;""")
for author in cursor.fetchall():
print(author)
authorBirthPlace = input('Enter the place of birth of the author(s) you would like to search : ')
cursor.execute("SELECT * FROM Books WHERE Author IN (SELECT Name FROM Authors WHERE PlaceOfBirth='{}');".format(authorBirthPlace))
for x in cursor.fetchall():
print(x)
| true |
febdfec7639719ae6598e5c91a1e102382b091b4 | chagan1985/PythonByExample | /ex036.py | 214 | 4.21875 | 4 | #####
# Python By Example
# Exercise 036
# Christopher Hagan
#####
name = input('Please enter your name: ')
repetitions = int(input('How many times should I say your name: '))
for i in range(0, repetitions):
print(name)
| true |
b9c2acb11f8d955f59d111c5fad10ff639c5a852 | Jerrybear16/MyFirstPython | /main.py | 2,411 | 4.1875 | 4 |
#print your name
print("Jeroen")
#print the lyrics to a song
stairway = "There's a lady who's sure, all that glitters is gold, and she's buying a stairway to heaven"
print("stairway")
#display several numbers
x=1
print(x)
x=2
print(x)
x=3
print(x)
#solve the equation
print(64+32)
#same but with variables
x = 64
y = 32
z = x+y
print(z)
#print lucky in s
print("%s" % "lucky")
#print date
print("today is %d/%d/%d"% (2,2,2016))
#replace
string = "hello world"
print(string)
string =string.replace("hello","world")
print(string)
string =string.replace("world","hello")
print(string)
string = string.replace("world","hello world, this is Jeroen")
print(string)
string = "hello world, this is jeroen"
string =string.replace("hello world","suh dude")
print(string)
#find
print(string.find("Suh"))
string = string.replace("dude","suh")
print(string)
print(string.find("jeroen"))
#string join
strlist = ["one","two", "three"]
liststr = ","
liststr = liststr.join(strlist)
print(liststr)
#string split
liststr2 = liststr.split(",")
print(liststr)
#random numbers
import random
x = random.randint(0,9)
print(x)
x = random.randint(0,9)
print(x)
x = random.randint(0,9)
print(x)
#keyboard input
print("\na break in the output to make it look nice\n\n")
phoneNumber = input("Input a phone number: ")
print(phoneNumber)
language = input("Input your favorite language: ")
print(language)
#ifs
numInRange = int(input("Give me a number between 1 and 10: "))
if numInRange <1 or numInRange >10:
print("invalid number")
#for loops
clist = ['Canada','USA','Mexico','Australia']
for country in clist:
print(country)
#while loops
i =0
while i < len(clist):
print(clist[i])
i+=1
numList = [1,2,3,4,5]
def sum(nl):
s = 0
for int in nl:
s+=int
return s
print(sum(numList))
#lists
print("I'm not making a list of 50 items i'm sorry")
#list opperations
y = [6,4,2]
y.append(12)
y.append(8)
y.append(4)
print(y)
y[1] = 3
print(y)
#range function
longList = []
for x in range(1000):
longList.append(x)
#print(longList)
#dictionary
cDict = { "United States of America":"US", "Canada":"CAN"}
print(cDict)
#read File
"""
file = open("textfile.txt",'r')
print(file.read())
file = open("fakefile.txt",'r')
print(file.read())
file = open("textfile.txt",'w')
file.write("take it easy")
file.close()
"""
import datetime
date = datetime.datetime.now()
print(date)
| true |
e7901d6febac3de5dc79ea4048e791d3cd815f59 | HarshCasper/Rotten-Scripts | /Python/Encrypt_Text/encrypt_text.py | 1,237 | 4.34375 | 4 | # A Python Script which can hash a string using a multitude of Hashing Algorithms like SHA256, SHA512 and more
import hashlib
import argparse
import sys
def main(text, hashType):
encoder = text.encode("utf_8")
myHash = ""
if hashType.lower() == "md5":
myHash = hashlib.md5(encoder).hexdigest()
elif hashType.lower() == "sha1":
myHash = hashlib.sha1(encoder).hexdigest()
elif hashType.lower() == "sha224":
myHash = hashlib.sha224(encoder).hexdigest()
elif hashType.lower() == "sha256":
myHash = hashlib.sha256(encoder).hexdigest()
elif hashType.lower() == "sha384":
myHash = hashlib.sha384(encoder).hexdigest()
elif hashType.lower() == "sha512":
myHash = hashlib.sha512(encoder).hexdigest()
else:
print("[!] The script does not support this hash type")
sys.exit(0)
print("Your hash is: ", myHash)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Convert text to hash")
parser.add_argument("-t", "--text", dest="text", required=True)
parser.add_argument("-T", "--Type", dest="type", required=True)
args = parser.parse_args()
txt = args.text
hType = args.type
main(txt, hType)
| true |
25fd335354c8560bbd7e8442462292d8d34174fe | HarshCasper/Rotten-Scripts | /Python/Caesar_Cipher/decipher.py | 1,457 | 4.4375 | 4 | """
A Python Script to implement Caesar Cipher. The technique is really basic.
# It shifts every character by a certain number (Shift Key)
# This number is secret and only the sender, receiver knows it.
# Using Such a Key, the message can be easily decoded as well.
# This Script Focuses on the Decoding Part only.
"""
def decipher(encrypt_string, shift_key):
"""
Implementation of DeCipher Technique.
Params: encrypt_string (required), shift_key (required)
Returns: decrypted_string
"""
# Initialise str to store the decrypted message
decrypted_string = ""
for text in encrypt_string:
if text == " ":
# For Blank Space, encrypted as it is
decrypted_string += text
elif text.isupper():
# For Upper Case
decrypted_string = decrypted_string + chr(
(ord(text) - shift_key - 65) % 26 + 65
)
else:
# For Lower Case
decrypted_string = decrypted_string + chr(
(ord(text) - shift_key - 97) % 26 + 97
)
return decrypted_string
if __name__ == "__main__":
"""
Function Calling
"""
encrypted_string = input("Enter the text to be decrypted: ")
shift = int(input("Enter the shift key: "))
print("Text before Decryption: ", encrypted_string)
print("Shift Key: ", shift)
print("Decrypted text: ", decipher(encrypted_string, shift))
| true |
862212ea35de8f2a361e51bdd69a5cbbdea87f8c | HarshCasper/Rotten-Scripts | /Python/Countdown_Clock_and_Timer/countdown_clock_and_timer.py | 1,456 | 4.40625 | 4 | # import modules like 'os' and 'time'
import os
import time
os.system("clear")
# using ctime() to show present time
times = time.ctime()
print("\nCurrent Time: ", times)
print("\n Welcome to CountdownTimer!\n\n Let's set up the countdown timer...\n")
# User input for the timer
hours = int(input(" How many hours? "))
minutes = int(input(" How many minutes? "))
seconds = int(input(" How many seconds? "))
# To display message when the given value is not a number
if hours or minutes or seconds == "":
print("\n Invalid entry. You must enter a number.")
# Conversion of hours amd minutes into seconds
hrsToSec = (hours * 60) * 60
mnsToSec = minutes * 60
seconds = seconds
seconds = hrsToSec + mnsToSec + seconds
print("\n Timer has been set for " + str(seconds) + " seconds.")
# Loop for displaying the timer
for i in range(seconds, -1, -1):
displayHours = int(seconds / 3600)
displayMinutes = int(seconds / 60)
if displayMinutes >= 60:
displayMinutes = displayMinutes - (displayHours * 60)
else:
displayMinutes = displayMinutes
displaySeconds = int(seconds % 60)
print(
"\n Your time remaining is: {}:{}:{}".format(
str(displayHours).zfill(2),
str(displayMinutes).zfill(2),
str(displaySeconds).zfill(2),
)
)
seconds -= 1
time.sleep(1) # delays in the excution of a program for 1 second
print("\n Time is over.")
| true |
51821a5fbc8054ea90f724a790a5aca64af9ed68 | Rahmonova/Python | /src/material/hello_3.py | 2,779 | 4.1875 | 4 | """STRING"""
# greeting = "hello"
# print(greeting[0])
# print(greeting[-1])
# print(greeting[2:])
# print(greeting[2:4])
# Don't add character in string
# x greeting[0] = 'j'
# Satr o`lchamini aniqlash
# print(len(greeting))
# Satrda berilgan elementni sanash
# print(greeting.count('l'))
# print(greeting.count('l'))
# Text transform
# print(greeting.capitalize())
# print(greeting.upper())
# h = "HELLO"
# print(h.lower())
# Matn transformatsiyasini tekshirish
# print(h.isupper())
# print(greeting.islower())
# How to work find function
# izlanayotgan so`z birinchi uchragan o`rnini ko`rsatadi
# print(h.find('L'))
# Agar matnda izlayotgan elementimiz bo`lmasa -1 qaytaradi
# print(h.find('l'))
# Berilgan oraliqda izlash
# print(h.find('L', 3, 4))
# So`z izlash ham mumkin
# print(h.find('LL'))
# Berilgan satr faqat sonlar ekanini tekshirish
# print('22225548448'.isdigit())
# print('22225548448'.isnumeric())
# Berilgan satr son va harflardan tashkil topganini tekshirish
# print('21528absddnjdf'.isalnum())
# Berilgan satr faqat harflardan tashkil topganini tekshirish
# print('dsfs'.isalpha())
# Berilgan satrda probellar borligini aniqlash
# print(' '.isspace())
# Berilgan satr berilgan belgidan boshlangami yoki yo`qligini tekshirish
# print(h.startswith('HE'))
# Berilgan satr berilgan belgidan tugallangami yoki yo`qligini tekshirish
# print(h.endswith('O'))
# Satrni berilgan belgidan bo`lib list hosil qilish
# print(h.split('L'))
# f format in use print
name = "Cameron"
# age = 21
# print(f"My name is {name} and I\'m {age}")
# Mantiqiy operatorlar
# >
# print(1 > 3)
# print(1 > 2 > 3)
# <
# print(8 < 45)
# print(1 < 2 < 3)
# ==
# print(1 == 0)
# !=
# print(1 != 1)
# >=
# print(1 >= 1)
# <=
# print(0 <= 0)
# ROSTLIK JADVALI
'''
_______________AND_____________
| A | B | A and B |
| 0 | 0 | 0 |
| 1 | 0 | 0 |
| 0 | 1 | 0 |
| 1 | 1 | 1 |
_______________________________
______________OR______________
| A | B | A or B |
| 0 | 0 | 0 |
| 1 | 0 | 1 |
| 0 | 1 | 1 |
| 1 | 1 | 1 |
______________________________
_________NOT_________
| A | not A |
| 0 | 1 |
| 1 | 0 |
_____________________
'''
# and
# print((1 > 2) and (3 > 1))
# or
# print((1 > 2) or (3 > 1))
# not
# print(not (1 > 2))
# if else
# a = 10
# b = 3
# if a > b:
# print(f"{a} katta!")
# else:
# print(f"{b} katta!")
# Sonni musbat, manfiy yoki nolga teng ekanligini aniqlash
# print("Ixtiyoriy son kiriting: ")
# n = int(input())
# if n == 0:
# print(f"{n} soni nolga teng!")
# elif n > 0:
# print(f"{n} <- musbat son!")
# else:
# print(f"{n} <- manfiy son!") | false |
4a7b213cc577665d05961141dd2b30413182313d | anurag5398/DSA-Problems | /Misc/FormingMagicSquare.py | 1,987 | 4.3125 | 4 | """
We define a magic square to be an matrix of distinct positive integers from to where the sum of any row, column, or diagonal of length is always equal to the same number: the magic constant.
You will be given a matrix of integers in the inclusive range . We can convert any digit to any other digit in the range at cost of . Given , convert it into a magic square at minimal cost. Print this cost on a new line.
Note: The resulting magic square must contain distinct integers in the inclusive range .
"""
#Valid of 3X3
#only 8 possible magic squares of 8X8
#@param matrix : list of list of int
#@return list of list of int -> mirror image of matrix
def mirrorOfMatrix(matrix):
n, m = len(matrix), len(matrix[0])
newMatrix = [[0 for i in range(m)] for i in range(n)]
for i in range(n):
for j in range(m):
newMatrix[i][j] = matrix[i][m-j-1]
return newMatrix
#@param matrix : list of list of int
#@return list of list of int : right roatated
def rightRotate(matrix):
n, m = len(matrix), len(matrix[0])
newMatrix = [[0 for i in range(m)] for i in range(n)]
for j in range(m):
for i in range(n):
newMatrix[i][j] = matrix[n-j-1][i]
return newMatrix
#@param m1, m2 : list of list of int
#@return int -> diff in each cell
def differenceInMatrix(m1, m2):
cost = 0
for i in range(len(m1)):
for j in range(len(m1[0])):
cost+= abs(m1[i][j]-m2[i][j])
return cost
#@param A : list of list of int
#@return int -> min cost
def formingMagicSquare(A):
base = [
[4,3,8],
[9,5,1],
[2,7,6]
]
mincost = float('inf')
for i in range(4):
mirrorbase = mirrorOfMatrix(base)
mincost = min(differenceInMatrix(A, base),
differenceInMatrix(A, mirrorbase), mincost)
base = rightRotate(base)
return mincost
A = [
[4,9,2],
[3,5,7],
[8,1,5]
]
print(magicsquare(A))
| true |
875ac737696d41ca97141ba845ddfe832723e5d0 | jellive/pythonstudy | /Chap02. Python basic - Struct/02-6. Set.py | 1,146 | 4.25 | 4 | """
Set
파이썬 2.3에서부터 지원되기 시작한 자료형.
집합에 관련된 것들을 쉽게 처리하기 위해 만들어진 자료형.
특징
1. 중복을 허용하지 않는다.
2. 순서가 없다(Unordered).
"""
s1 = set([1,2,3])
print(s1) # {1, 2, 3}
s2 = set("Hello")
print(s2) # {'e', 'H', 'l', o'}, 중복되는 건 지우고 알파벳 순으로 나열한다.
# set을 list로 바꾸기
print(list(s1)) # [1, 2, 3]
# set을 tuple로 바꾸기
print(tuple(s1)) # (1, 2, 3)
# 교집합, 합집합, 차집합 구하기
s1 = set([1, 2, 3, 4, 5, 6])
s2 = set([4, 5, 6, 7, 8, 9])
# 교집합
print(s1 & s2) # {4, 5, 6}
print(s1.intersection(s2)) # {4, 5, 6}, 같은 함수.
# 합집합
print(s1 | s2) # {1, 2, 3, 4 ,5, 6, 7, 8, 9}
print(s1.union(s2)) # {1, 2, 3, 4, 5, 6, 7, 8, 9}, 같은 함수.
# 차집합
print(s1 - s2) # {1, 2, 3}
print(s1.difference(s2)) # {1, 2, 3}, 같은 함수.
# 값 1개 추가하기 (add)
s1.add(4)
print(s1) # {1, 2, 3, 4}
# 값 여러개 추가하기 (update)
s1.update([4, 5, 6])
print(s1) # {1, 2, 3, 4, 5, 6}
# 특정 값 제거하기 (remove)
s1.remove(2)
print(s1) # {1, 3, 4, 5, 6} | false |
b97586756284aaf8ea4644c4d74fdfbcde9fce0e | AndresHG/UCM | /Python/Ejercicio2Python.py | 1,098 | 4.28125 | 4 | #Pedimos el mes por primera vez al usuario
mes = input("Introduzca el nombre del mes: ")
#Utilizamos un bucle while ya que en el ejemplo, se hacen varias peticiones al usuario
#El bucle termina cuando pulsamos 0
while mes != "0":
#Utilizamos la función lower() que nos pasa un string a todo minúsculas
#Caso de los meses de 31 días
if mes.lower() == "enero" or mes.lower() == "marzo" or mes.lower() == "mayo" or mes.lower() == "julio" or mes.lower() == "agosto" or mes.lower() == "octubre" or mes.lower() == "diciembre":
print(mes, "tiene 31 días")
#Caso de los meses de 30 días
elif mes.lower() == "abril" or mes.lower() == "junio" or mes.lower() == "septiembre" or mes.lower() == "noviembre":
print(mes, "tiene 30 días")
#Caso de febrero que tiene 28 días
elif mes.lower() == "febrero":
print(mes, "tiene 28 días")
#Caso en el que se intriduzca un nombre incorrecto
else:
print("No conozco ese mes")
#Volvemos a pedir el mes al usuario
mes = input("Introduzca el nombre del mes: ") | false |
c715f587787e6e1a112cf654fedcb230b5977511 | fawpc/algoritmos2-2018-2 | /job(lista encadeada).py | 2,655 | 4.3125 | 4 | """Implementação de hoje."""
class No:
"""Define um no da lista encadeada."""
def __init__(self, valor):
"""Inicializa no."""
self.dado = valor
self.proximo = None
def recebe(self, valor):
"""bla bla bla."""
self.dado = valor
def prox(self, valor):
"""mostra quem é o proximo."""
return self.proximo
class lista():
"""Bla bla bla."""
def __init__(self):
"""Inicializa uma nova lista."""
self.head = None
self.tail = None
def recebe(self, valor):
"""bla bla bla."""
self.dado = valor
def size(self, valor):
"""Retorna o numero de elementos armazenados."""
def remove(self, valor):
"""Remove todos os elementoscom valor X."""
def append(self, valor):
"""Insere X no final da lista."""
"""descobrir quem é o ultimo elemento da
lista (tail) e inserir o proximo elemento
apos ele"""
new = No(valor)
if self.tail is None:
self.head = self.tail = new
else:
self.tail.proximo = new
self.tail = self.tail.proximo
def addFirst(self, valor):
"""Insere X no inicio da lista."""
new = No(valor)
if self.head is None:
self.head = self.tail = new
else:
new.self.proximo(new)
self.head = new
def pop(self):
"""Remove o elemento no final da lista e retora-o ao chamador."""
if self.head is self.tail:
self.head = self.tail = None
else:
era = self.head
while era.self.proximo is not self.tail:
era = era.self.prox()
era.self.tail = None
self.tail = era
return era
def removeFirst(self):
"""Remove o primeiro elemento da lista."""
if self.head is self.tail:
self.head = self.tail = None
else:
self.head = self.head.self.proximo
return self.head
def first(self, valor):
"""Retorna o primeiro elemento da lista."""
self.head = lista.first()
self.iterador = iterador
iterador = lista.first()
return lista.first()
def last(self, valor):
"""Retorna o ultimo elemento da lista."""
self.tail = lista.last()
self.iterador = iterador
iterador = lista.last()
return lista.last()
iterador = lista.first()
while iterador is not None:
print(iterador.value)
iterador = iterador.next
| false |
c8ec71ad18413c7a12d309d1a1747a391bca1cc6 | joshseyda/Python-CS | /lambda0.py | 413 | 4.15625 | 4 | # regular function
def is_even(x):
if x % 2 == 0:
return True
else:
return False
# lambda function
even = lambda x: x % 2 == 0
# results
print('is_even(4): {}'.format(is_even(4)))
print('is_even(3): {}'.format(is_even(3)))
print('even(4): {}'.format(even(4)))
print('even(3): {}'.format(even(3)))
# >>> is_even(4): True
# >>> is_even(3): False
# >>> even(4): True
# >>> even(3): False | false |
56e2e07ea84d6200924c1fb9d35cbead8f960e82 | Gyanesh-Mahto/Edureka-Python | /Class_Codes_Module_3&4/P9_07_Constructor_and_Destructor.py | 1,804 | 4.71875 | 5 | #Constructor and Destructor
'''
Construtor: __init__(self) is initiation method for any class. This is also called as contructor
Destructor: It is executed when we destroy any object or instance of the class. __del__(self) is destructor method for destrying the object.
'''
class TestClass:
def __init__(self): #The constructor is implemented using __init__(self) which you can define parameters that follows itself.
print("constructor")
def __del__(self): #The destrutor is defined using __del__(self). In the example, the obj is created and manually deleted, therefore
print("destructor") #both messages will be displayed.
if __name__=="__main__":
obj=TestClass()
del obj
'''
O/P:
constructor
destructor
'''
#Multiple Constructors:
#----------------------#
class Date:
def __init__(self, year, month, day): #Year-Month-Day
self.Year=year
self.Month=month
self.Day=day
print("Constructor Initialization")
@classmethod #Constructors
def dmy(self, day, month, year): #Day-Month-Year
self.Year=year
self.Month=month
self.Day=day
return self(self.Year, self.Month, self.Day) #order of return should be same as __init__
@classmethod #Constructors
def mdy(self, month, day, year): #Month-Day-Year
self.Year=year
self.Month=month
self.Day=day
return self(self.Year, self.Month, self.Day) #order of return should be same as __init__
a=Date(2016,8,19) #Constructor Initialization
print(a.Year) #2016
b=Date.dmy(4,8,1995) #Constructor Initialization
print(b.Year) #1995
c=Date.mdy(11,9,1998) #Constructor Initialization
print(c.Year) #1998 | true |
04230c130fceeca7db61dc11b2422b752981dedf | Gyanesh-Mahto/Edureka-Python | /Class_Codes_Module_3&4/P8_Variable_length_arguments.py | 1,246 | 4.75 | 5 | '''
Variable-length Arguments: When we need to process a function for more arguments than you have specified while defining the function,
So, variable-length arguments can be used.
'''
def myFunction(arg1, arg2, arg3, *args, **kwargs):
print("First Normal Argument: "+str(arg1))
print("Second Normal Argument: "+str(arg2))
print("Third Normal Argument: "+str(arg3))
print("Non-Keyworded Argument: "+str(args))
print("Keyworded Argument: "+str(kwargs))
myFunction(1,2,3,4,5, name="Mandar", country="India", age=25) #When a dictionary is passed in function, then it is collected in function using **kwargs
'''
O/P:
First Normal Argument: 1
Second Normal Argument: 2
Third Normal Argument: 3
Non-Keyworded Argument: (4, 5)
Keyworded Argument: {'name': 'Mandar', 'country': 'India', 'age': 25}
'''
'''
def info(user, *users):
print("Users of Python:")
print(user)
for var in users:
print("Users of Python")
print(var)
return()
info("Annie") #Single variable or multiple variables can be passed as an arguments to the same function.
info("Annie", "Dave")
'''
'''
O/P:
Users of Python:
Annie
Users of Python:
Annie
Users of Python
Dave
''' | true |
27dad1a58b341711371a79cc7815e97b19e1d6d2 | theChad/ThinkPython | /chap2/chap2.py | 1,008 | 4.125 | 4 | # 2.2.1
# Volume of a sphere with radius 5
r = 5 #radius of the sphere
volume = 4/3*3.14159*r**3
print("2.2.1 Volume of sphere:", volume)
# 2.2.2
# Textbook price
cover_price = 24.95
discount = 0.4
shipping_book_one = 3
shipping_extra_book = 0.75
num_books = 60
total_shipping = shipping_book_one + shipping_extra_book*(num_books-1)
total_wholesale = num_books*(cover_price*(1-discount)) + total_shipping
print("2.2.2: Textbook price:", total_wholesale)
# 2.2.3
# Breakfast time
easy_pace = 8 + 15/60
tempo = 7 + 12/60
easy_miles = 1
tempo_miles = 3
easy_miles += 1
start_hour = 6
start_minute = 52
run_time = easy_pace*easy_miles + tempo*tempo_miles
run_hours = run_time//60 # floor division, default with integers in python2
run_minutes = run_time - run_hours*60
breakfast_minute = start_minute + run_minutes
breakfast_hour = start_hour + run_hours + breakfast_minute//60
breakfast_minute = breakfast_minute - 60*(breakfast_minute//60)
print("2.2.3 Breakfast time:", breakfast_hour,":",breakfast_minute)
| true |
4519920c83d465d689e03c2adbba42f4b822ffd5 | theChad/ThinkPython | /chap12/most_frequent.py | 920 | 4.125 | 4 | # Exercise 12.1
# From Exercise 11.2, just to avoid importing
def invert_dict(d):
"""Return a dictionary whose keys are the values of d, and whose
values are lists of the corresponding keys of d
"""
inverse = dict()
for key in d:
val = d[key]
inverse.setdefault(val,[]).append(key)
return inverse
def most_frequent(s):
"""Return the letters in s in order of frequency, high to low.
I return the letters as a string.
s: string
"""
hist=dict()
# Create dictionary mapping letter to frequency
for c in s:
hist[c] = hist.get(c,0) + 1
# Create a dictionary mapping frequency to letter
freqs = invert_dict(hist)
# Return letters in order of frequency
frequent_letters = ''
for frequency in sorted(freqs, reverse=True):
for letter in freqs[frequency]:
frequent_letters += letter
return frequent_letters
| true |
531e4e63621e4b978f722c87b4c6a8759ebeb151 | theChad/ThinkPython | /chap9/ages.py | 1,358 | 4.28125 | 4 | # Exercise 9.9
# I think the child is 57, and they're 17-18 years apart
# I really shouldn't rewrite functions, but it's a short one and it's more convenient now.
def is_reverse(word1, word2):
return word1==word2[::-1]
# After looking at the solutions, this should really cover reversed numbers with two different
# differences, since people without the same birthday n+ years apart will have ages
# separated by n and n+1 every year. I added that into the if statement.
def find_num_reversals(diff):
"""Find all two digit reversed numbers with a certain difference, e.g. all
palindromes separated by 11.
"""
i = 0
count = 0
while i < 100-diff:
if is_reverse(str(i).zfill(2), str(i+diff).zfill(2)) or \
is_reverse(str(i).zfill(2), str(i+diff+1).zfill(2)):
count += 1
if count==6:
# Candidate could also refer to i and i+diff+1, but that'll be clear
# from the printout
print("Candidate:", i, "and", i+diff)
i += 1
return count
def find_age_diff():
"""Find an age difference with 8 reversals in it
"""
i = 1
while i < 100:
num_reversals = find_num_reversals(i)
if num_reversals>= 6:
print("Age difference of",i,"has", num_reversals, "reversals.")
i += 1
find_age_diff()
| true |
628fdde22ad8c5816048781d068959c68fc118f5 | umitkoc/python_lesson | /map.py | 423 | 4.25 | 4 | # map function
#iterable as list or array
#function as def or lambda
#map(function,iterable) or
numbers=[1,2,3,4,5,6]
#example
def Sqrt(number):
return number**2
a=list(map(Sqrt,numbers))
print(a)
#example
b=list(map(lambda number:number**3,numbers))
print(b)
#map(str,int,double variable as convert,iterable)
#example
str_numbers=["1","2","3","4","5","6"]
c=list(map(int,str_numbers))
print(c)
| true |
12ef8b9534255a1fd3844b5a4aa6598e55e49080 | bernardobruno/Methods_Python_Basics | /Methods_Python_Basics.py | 2,123 | 4.53125 | 5 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
# Method - append() --- Adds an element at the end of the list
names = ["Jim", "John", "Joey"]
names.append("Jason")
print(names)
# In[2]:
# Method - clear() --- Removes all the elements from the list
names = ["Jim", "John", "Joey"]
names.clear()
print(names)
# In[3]:
# Method - copy() --- Returns a copy of the list
fruits = ["apple", "banana", "cherry"]
x = fruits.copy()
print(x)
# In[4]:
# Method - count() --- Returns the number of elements
# with the specified value
names = ["Jim", "John", "Joey"]
x = names.count("Joey")
print(x)
# In[5]:
names = ["Jim", "John", "Joey", "Bruno", "Bruno"]
x = names.count("Bruno")
print(x)
# In[6]:
# Method - extend() --- Add the elements of a list (or any iterable),
# to the end of the current list
names = ["Jim", "John", "Joey"]
nums = [1, 2, 3]
names.extend(nums)
print(names)
# In[7]:
# Method - index() --- Returns the index of the first element
# with the specified value
names = ["Jim", "John", "Joey"]
x = names.index("Joey")
print(x)
# In[8]:
names = ["Jim", "John", "Joey"]
x = names.index("Jim")
print(x)
# In[9]:
# Method - insert() --- Adds an element at the specified position
names = ["Jim", "John", "Joey"]
names.insert(2, "Jack")
print(names)
# In[10]:
# Method - pop() --- Removes the element at the specified position
names = ["Jim", "John", "Joey"]
names.pop(-1)
print(names)
# In[11]:
# Method - remove() --- Removes the first item with the specified value
names = ["Jim", "John", "Joey"]
names.remove("Joey")
print(names)
# In[12]:
names = ["Jim", "John", "Joey"]
names.remove("Jim")
print(names)
# In[13]:
# Method - reverse() --- Reverses the order of the list
names = ["Jim", "John", "Joey"]
names.reverse()
print(names)
# In[14]:
# Method - sort() --- Sorts the list
names = ["Jim", "John", "Joey"]
names.sort()
print(names)
# In[17]:
names = ["Alexandre", "Bruno", "Jacob", "Yossef", "Abraham"]
names.sort()
print(names)
# In[18]:
names = ["Alexandre, Bruno, Jacob, Yossef, Abraham"]
names.sort()
print(names)
# In[ ]:
| true |
817009a19f56b2f896ab51df41542bae0c64b533 | dhautsch/etc | /jython/MyTreeFactory.py | 1,144 | 4.4375 | 4 | class MyTreeFactory:
"""
From http://www.exampleprogramming.com/factory.html
A factory is a software design pattern as seen in the
influential book "Design Patterns: Elements of Reusable
Object-Oriented Software". It's generally good programming
practice to abstract your code as much as possible to limit
what needs to be updated, when a change is required.
"""
class Oak:
def get_message(self):
return "This is an Oak Tree"
class Pine:
def get_message(self):
return "This is a Pine Tree"
class Maple:
def get_message(self):
return "This is a Maple Tree"
@staticmethod
def create_tree(tree):
if tree=="Oak":
return TreeFactory.Oak()
elif tree=="Pine":
return TreeFactory.Pine()
elif tree=="Maple":
return TreeFactory.Maple()
if __name__=="__main__":
def print_trees(tree_list):
for current in tree_list:
tree=TreeFactory.create_tree(current)
print tree.get_message()
tree_list=["Oak","Pine","Maple"]
print_trees(tree_list)
| true |
03ddc774d8ea887c8acd472096d8f211eb3ee367 | danny31415/project_euler | /src/problem1.py | 429 | 4.125 | 4 | """Project Euler Problem 1
If we list all the natural numbers below 10 that are multiples of
3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
"""
from __future__ import print_function
def main():
total = 0
for x in range(1000):
if x%3 == 0 or x%5 == 0:
total += x
return total
if __name__ == "__main__":
print(main())
| true |
32dbf5f4b0b91fd3ca02d4a9b7425bec2109f6de | BootcampersCollective/Coders-Workshop | /Contributors/AdamVinueza/linked_list/linked_list.py | 2,735 | 4.25 | 4 | class Node():
'''A simple node class for doubly-linked lists.'''
__slots__ = [ 'key', 'next', 'prev' ]
def __init__(self, value):
self.key = value
self.next = None
self.prev = None
class LinkedList():
'''A doubly-linked list, with iteration and in-place reverse and rotation.'''
__slots__ = [ 'head', 'tail', 'current' ]
def __init__(self):
self.head = None
self.tail = None
self.current = None
'''
The next two methods make LinkedList iterable, meaning you can go through
the list's items using a for-loop.
'''
def __iter__(self):
return self
def __next__(self):
if self.current is None:
self._resetIterator()
raise StopIteration
current = self.current
self.current = current.next
return current
def _resetIterator(self):
self.current = self.head
def insertfront(self, x):
'''Inserts a new node with the specified value at the front.'''
node = Node(x)
if self.head is None:
self.tail = node
else:
self.head.prev = node
node.next = self.head
self.head = node
self._resetIterator()
def insertback(self, x):
'''Inserts a new node with the specified value at the back.'''
if self.head is None:
self.insertfront(x)
else:
node = Node(x)
node.prev = self.tail
node.prev.next = node
self.tail = node
def remove(self, node):
'''Removes the specified node.'''
# reset head and tail if necessary
if node.prev is None:
self.head = node.next
if node.next is None:
self.tail = node.prev
# you have to stitch the hole before making the hole
if node.next is not None:
node.next.prev = node.prev
if node.prev is not None:
node.prev.next = node.next
# disconnect it from the list
node.next = None
node.prev = None
# if we removed the head, we have to reset
self._resetIterator()
return node
def reverse(self):
swap = self.head
self.head = self.tail
self.tail = swap
for node in self:
swap = node.prev
node.prev = node.next
node.next = swap
node = node.prev
def rotateright(self, count):
for i in range(count):
node = self.remove(self.head)
self.insertback(node.key)
def traverse(self):
values = []
for node in self:
values.append(node.key)
return values
| true |
a96fc5f29cdc10332358d2f9707e597b7a5c61da | Javierfs94/Modulo-Programacion | /Python/poo/excepciones/Ejercicio1.py | 937 | 4.15625 | 4 | '''
Realiza un programa que pida 6 números por teclado y nos diga cuál es el máximo. Si el usuario introduce un dato erróneo
(algo que no sea un número entero) el programa debe indicarlo y debe pedir de nuevo el número.
@author Francisco Javier Frías Serrano
@version 1.0
'''
print("Introduzca 6 números enteros...");
for i in range(1, 7):
numero = 0
datoValido = False
maximo = numero
while not datoValido:
try :
numero = int(input("Nº " + str(i) + ": "))
datoValido = True
if (numero > maximo):
maximo = numero
except:
print("Dato introducido inválido. Debe introducir un número entero.")
print("Vuelva a introducir el dato")
datoValido = False
if (numero > maximo):
maximo = numero
print("El número máximo es " , maximo);
| false |
5ab3c1fbdada734e9299656debd3db8f810924a5 | nt3rp/Project-Euler | /completed/q14.py | 1,642 | 4.1875 | 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.
from math import log
#n = 1
#length = 1
#limit = 13
#def even_function (x):
# return 2*x
#def odd_function (x):
# return (x-1) / 3
#def odd_check (x):
# return (x-1) % 3
#work from lowest number back to biggest?
#how do we know when to stop?
#want to maximize odd functions, as they reduce n
#while n < limit:
# if (odd_check(n) == 0) and (odd_function(n) % 2 == 1) and (odd_function(n) > 1):
# n = odd_function(n)
# else:
# n = even_function(n)
# length += 1
# print(n)
import sys
paths = []
limit = int(sys.argv[1])
n = 0
paths.append(0)
#Really dumb brute force method. Should have done a dynamic programming solution?
while n <= limit:
#do steps for this path
current_path = n
paths.append(0)
while current_path > 1:
is_power_of_two = log(current_path, 2)
if (is_power_of_two % 1) == 0:
paths[n] += is_power_of_two
break
elif (current_path % 2) == 0:
current_path /= 2
else:
current_path = 3 * current_path + 1
paths[n] += 1
n += 1
maxValue = max(paths);
maxIndex = paths.index(maxValue)
print(maxIndex, maxValue)
| true |
7605db9a9ea25bb5dd333dfbb7eafb0561916792 | Puhalenthi/-MyPythonBasics | /Python/Other/BubbleSort.py | 1,201 | 4.125 | 4 | class IncorrectItemEnteredError(BaseException):
pass
def BubbleSort():
nums = []
done = False
sorting = True
while done == False:
try:
num = int(input('Give me a number to add to the sorting list: '))
except:
print('Please enter a valid integer')
else:
nums.append(num)
finally:
useryesorno = input('Would you like to add another number? Type y or Y for yes and n or N for no: ')
if useryesorno == 'y' or useryesorno == 'Y':
done = False
elif useryesorno == 'n' or useryesorno == 'N':
done = True
else:
done = True
raise IncorrectItemEnteredError('An Invalid Response Was Entered')
length = len(nums)
while sorting == True:
newnums = nums.copy()
for i in range(1, len(nums)):
if newnums[i] < newnums[i - 1]:
newnums[i], newnums[i - 1] = newnums[i - 1], newnums[i]
print(newnums, '\n')
if newnums == nums:
sorting = False
else:
nums = newnums
return 'Done'
print(BubbleSort())
| true |
e2a21c706bfc25cc3dd5992095ed16ae54e16982 | misoi/python | /codeacademy/accessbyindex.py | 408 | 4.1875 | 4 | """
The string "PYTHON" has six characters,
numbered 0 to 5, as shown below:
+---+---+---+---+---+---+
| P | Y | T | H | O | N |
+---+---+---+---+---+---+
0 1 2 3 4 5
So if you wanted "Y", you could just type
"PYTHON"[1] (always start counting from 0!)
"""
fifth_letter = "MONTY"[4]
print fifth_letter
# Print the concatenation of "Spam and eggs" on line 3!
print "Spam " + "and " + "eggs"
| false |
48ae6b659509b290375de9f0f4b7528eb1a91121 | Mathew5693/BasicPython | /oldmcdonalds.py | 308 | 4.15625 | 4 | #Programming exercise 4
#Mathew Apanovich
#A program to out put the sum of all cubes of n natural numbers
def cude(n):
x = 0
for i in range(1,n+1,1):
x = x+ i**3
return x
def main():
n = eval(input("Please enter natural number:"))
z = cude(n)
print(z)
| true |
867485e8e1247a70f3f6a11b8ad93b21616ad507 | Mathew5693/BasicPython | /kilotomiles.py | 217 | 4.3125 | 4 | #A program to convert kilometers to miles
#Mathew Apanovich
#Kilo to miles.py
def main():
k = eval(input("Please enter distance in Kilometers: "))
m = k * .621371
print(k,"Kilometers is", m,"Miles!")
| false |
cba67abc8d0af5f4be041c5333719662298806bc | k/Tutorials | /Python/ex3.py | 773 | 4.375 | 4 | print "I will now count my chickens:"
# calculate and print the number of Hens
print "Hens", 25 + 30 / 6
# calculate and print the number of Roosters
print "Roosters", 100 - 25 * 3 % 4
print "Now I will count the eggs:"
# calculate the eggs
print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6
print "Is it true that 3 + 2 < 5 - 7?"
# returns a boolean of the math expression
print 3 + 2 < 5 - 7
# adds 3 and 2
print "What is 3 + 2?", 3 + 2
# subtracts 7 from 5
print "What is 5 - 7?", 5 - 7
print "Oh, that's why it's False."
print "How about some more?"
# checks if 5 is greater than -2
print "Is it greater?", 5 > -2
# checks if 5 is greater than or equal to -2
print "Is it greater or equal?", 5 >= -2
# checks if 5 is less or equal to -2
print "Is it less or equal?", 5 <= -2
| true |
1424c2432a573562eea0621166e1381f40ed36d5 | larafonse/exploring_linked_lists | /part1.py | 1,801 | 4.375 | 4 | # Initializing Linked List
class LinkedList:
# Function to initialize the linked list class
def __init__(self):
self.head = None # Initialize the head of linked list as
# Function to add passed in Node to start linked list
def addToStart(self, data):
tempNode = Node(data) # create a new Node with data passed in
tempNode.setNextNode(self.head) # set current list to to the next Node of temp node
self.head = tempNode # set new head as temp node
del tempNode
# method displays Linked List
def display(self):
start = self.head
# check is linked list is empty
if start is None:
print("Empty List!!!")
return False
# while start is not null print data in null
while start:
print(str(start.getData()), end=" ")
start = start.next # assign next node to print
# print arrows if start is not null
if start:
print("-->", end=" ")
print()
# Node class
class Node:
# Function to initialize the node object
def __init__(self, data):
self.data = data # Assign data
self.next = None # Initialize next as null
# Getter for data of node
def getData(self):
return self.data
# Setter for data
def updateData(self, data):
self.data = data # Assign data
# Setter for next node
def setNextNode(self, node):
self.next = node # Assign next node
# Getter for next node
def getNextNode(self):
return self.next
myList = LinkedList()
# adding some elements to the start of LinkedList
myList.addToStart(5)
myList.addToStart(4)
myList.addToStart(3)
myList.addToStart(2)
myList.addToStart(1)
myList.display() | true |
c6e1466fc73cbaef1481da95dd28bf8e72789382 | Laveenajethani/python_problemes | /count_word_lines_char.py | 398 | 4.28125 | 4 | # program for count the words,lines,chracter in text files
#!/usr/bin/python3
num_lines=0
num_words=0
num_chracter=0
with open('text.txt','r') as f:
for line in f:
wordlist=line.split()
num_lines +=1
num_words +=len(wordlist)
num_chracter +=len(line)
print("number of lines:")
print(num_lines)
print("number of words:")
print(num_words)
print("number of chracter")
print(num_chracter)
| true |
146d577959a3fffd95a7a04ee5f4b536927b171f | muhdnaveedkhan/module-one | /list-comprehension.py | 1,712 | 4.5 | 4 | # list comprehension
# with the help of list comprehension we can create of list in one line
# ---------------- Problem #1 : reverse the list's elements-----------
# ls = ['abc', 'xyz', 'vut', 'lms']
# new_ls = []
# for el in ls:
# new_ls.append(el[::-1])
# print(new_ls)
# Similary, we can do the same with list comprehension
# ls = ['abc', 'xyz', 'vut', 'lms']
# new_ls = [el[::-1] for el in ls ]
# print(new_ls)
# ---------------- Problem #2 : create a new list of even numbers from old one -----------
# list comprehension with if statement
list1 = list(range(1,11))
even_ls = []
odd_ls = []
# for el in list1:
# if el%2 == 0:
# even_ls.append(el)
# else:
# odd_ls.append(el)
# print(even_ls)
# print(odd_ls)
#Similarly, we can do the same by using list comprehension
even_ls = [el for el in list1 if el%2 == 0]
odd_ls = [el for el in list1 if el%2 != 0]
print(even_ls)
print(odd_ls)
# create a list of squres from 1 to 10
list1 = list(range(1,11))
list2 = [1,2,3,4,5,6,7,8,9,10]
sq_list = []
# for i in range(1,11):
# sq_list.append(i**2)
# print(sq_list)
# we can create the same with list comprehension
# sq_list = [ i**2 for i in range(1,11) ]
# print(sq_list)
# negative = []
# for cnt in range(1,11):
# negative.append(-cnt)
# print(negative)
# # Similarly, with the help of list comprehension
# negative = [-cnt for cnt in range(1,11) ]
# print(negative)
# names = ['Wasim', 'Ali' , 'Sohail', 'Faizan']
# list_name = []
# for item in names:
# list_name.append(item[0])
# print(list_name)
# Similary with list comprehension
# names = ['Wasim', 'Ali' , 'Sohail', 'Faizan']
# list_name = [item[0] for item in names]
# print(list_name)
| false |
059c5b50ad5631101544c5d0e397c77b7d14c3eb | mak2salazarjr/python-puzzles | /geeksforgeeks/isomorphic_strings.py | 1,337 | 4.4375 | 4 | """
http://www.geeksforgeeks.org/check-if-two-given-strings-are-isomorphic-to-each-other/
Two strings str1 and str2 are called isomorphic if there is a one to one mapping
possible for every character of str1 to every character of str2. And all occurrences
of every character in ‘str1’ map to same character in ‘str2’
"""
from collections import namedtuple
def are_isomorphic(str1, str2):
"""
Determines if two strings are 'isomorphic'
:param str1: a string
:param str2: a string
:return: True if isomorphic, False if they are not
"""
if len(str1) != len(str2):
return False
char_map = {}
mapped = set()
for c1, c2 in zip(str1, str2):
if c1 in char_map:
if c2 != char_map[c1]:
return False
elif c2 in mapped:
return False
else:
char_map[c1] = c2
mapped.add(c2)
return True
Test = namedtuple('Test', 's1 s2 expected')
tests = (
Test('aab', 'xxy', True),
Test('a', 'bb', False),
Test('aab', 'xyz', False),
)
if __name__ == '__main__':
for test in tests:
print(f'{test.s1}, {test.s2} -> {are_isomorphic(test.s1, test.s2)}')
print(f'{test.s2}, {test.s1} -> {are_isomorphic(test.s2, test.s1)}')
print(f'Expected {test.expected}')
| true |
856b2a53c2142f58a860ee7dbe59b8fa6a08b115 | 1337Python/StudyTime | /Objects.py | 1,369 | 4.15625 | 4 |
class NonObject:
None #This is Python syntax for noop aka no-op or 'no operation'
class Object:
def __init__(self):
self.name = "Unamed"
self.age = "-1"
print("Constructed Object!")
def __del__(self):
print("Destructed Object!")
class NamedObject:
def __init__(self, name, age):
self.name = name
self.age = age
print ("Constructed", name, " age ", age)
def __del__(self):
print ("Destructed", self.name, " age ", self.age)
def CreateNothing():
nothing = NonObject()
def CreateSomething():
something = Object()
def CreateJon():
named = NamedObject("Jon", 13)
#Enter Main here!
CreateNothing()
CreateSomething()
CreateJon()
print("----------------------")
print("Now notice the difference in order of constructor/destructor")
nothing = NonObject()
#print(nothing.name) ERROR! We never created any attribute on this object
something = Object()
print(something.name, ", ", something.age)
jon = NamedObject("Jon", 13)
brad = NamedObject("Brad", 172)
#jon and brad are the same object but have different member values. aka they are different instances of the same object.
#which you can see with their constructors/destructors
#Notice that objects are destructed in the order they are constructed. So Object is first, then Jon, then Brad.
| true |
ed2d57cd72eae4a20c40656fbedf75ffb60b4bef | Afshana123/eng88_task_19052021 | /Task_19052021.py | 901 | 4.40625 | 4 | # Promts User to enter their name and welcomes user
Name = str(input("Please enter your name: "))
print("Hello " + Name)
# Promts User to enter their age
Age = int(input("Please enter your age: "))
# Promts user to enter their month of birth
Month_of_birth = int(input("Please enter the month you were born in numerical format e.g '1': "))
# Calculatiom forth their date of birth based on the month they were born
Birthday_passed_this_year = 2021 - Age
Birthday_not_passed_this_year = 2021 - Age + 1
# An if, else statement which allows the correct calculation to be made based on their month of birth
if (Month_of_birth <= 6):
print("OMG " + Name + ", " + "you are " + str(Age) + " years old " + "so you were born in " + str(Birthday_passed_this_year))
else:
print("OMG " + Name + ", " + "you are " + str(Age) + " years old " + "so you were born in " + str(Birthday_not_passed_this_year)) | false |
5387e6e5ddbdd0679841add55d3c5a47899fc461 | MarkMikow/CodingBat-Solutions-in-Python-2.7 | /Logic-2/round_sum.py | 742 | 4.15625 | 4 | '''For this problem, we'll round an int value up to the next multiple
of 10 if its rightmost digit is 5 or more, so 15 rounds up to 20.
Alternately, round down to the previous multiple of 10 if its rightmost
digit is less than 5, so 12 rounds down to 10. Given 3 ints, a b c, return
the sum of their rounded values. To avoid code repetition, write a separate
helper "def round10(num):" and call it 3 times. Write the helper entirely
below and at the same indent level as round_sum().
'''
def round_sum(a, b, c):
return round10(a) + round10(b) + round10(c)
def round10(num):
if num > 10:
r = num % 10
if r >= 5:
return num + (10 - r)
return num - r
if num >= 5 and num <= 10:
return 10
return 0 | true |
512ccc51d8dde88dfd52450e50fba426ee175fae | MarkMikow/CodingBat-Solutions-in-Python-2.7 | /Logic-2/make_bricks.py | 844 | 4.21875 | 4 | '''
We want to make a row of bricks that is goal inches long.
We have a number of small bricks (1 inch each) and
big bricks (5 inches each). Return True if it is possible to make the
goal by choosing from the given bricks. This is a little harder
than it looks and can be done without any loops.
'''
def make_bricks(small, big, goal):
small_amount = small * 1
big_amount = big * 5
if big == 0:
if small_amount >= goal:
return True
return False
elif big > 0 and big_amount < goal:
leftover = goal - big_amount
if small_amount >= leftover:
return True
return False
elif big > 0 and big_amount >= goal:
for i in range(big + 1):
if (i * 5) <= goal and (i * 5) > (goal - 5):
result = i * 5
result_remainder = goal % result
if small_amount >= result_remainder:
return True
return False | true |
ba3fa9a21bed8e08360f9b39fbe3f30a63f78cfe | nolngo/Frequency-counter | /HashTable.py | 1,047 | 4.25 | 4 | from LinkedList import LinkedList
class HashTable:
def __init__(self, size):
self.size = size
self.arr = self.create_arr(size)
def create_arr(self, size):
""" Creates an array (list) of a given size
and populates each of its elements with a LinkedList object """
array = []
for i in range(size):
new_ll = LinkedList()
array.append(new_ll)
return array
def hash_func(self, key):
""" Hash functions are a function that turns each of these keys
into an word_len value that we can use to decide where in our list
each key:value pair should be stored. """
hash_key = hash(key)
index = (hash_key * 21) % self.size
return index
def insert(self, key, value):
hash_key = self.hash_func(key)
new_ll = self.arr[hash_key].find_update(key)
item = (key, value)
if new_ll == -1:
self.arr[hash_key].append(item)
def print_key_values(self):
for ll in self.arr:
ll.print_nodes()
print('Traverse finished') | true |
88ffa4e639f58584e943b7b78d5992701de6ed22 | basti42/advent_of_code_2017 | /day1/day1.py | 1,207 | 4.25 | 4 | #!/usr/bin/env python3
import sys
"""
Advent of Code - Day 1:
Part 1 --> SOLVED
Part 2 --> SOLVED
"""
def sum_of_matches(numbers):
"""calculate the sum of all numbers that match the next"""
matches = 0
for i,n in enumerate(numbers):
if n == numbers[i-1]:
matches += int(n)
return matches
def sum_of_matches_half_around(numbers):
"""Part 2 of the puzzle, calculate the sum of numbers that match the number half way through the sequence"""
matches = 0
# making indices for accessing the number at the position
step = int(len(numbers)/2)
for i,n in enumerate(numbers):
if n == numbers[(i+step)%len(numbers)]:
matches += int(n)
return matches
# Start the program with the sequence of numbers
# as a command line argument in sys.argv[1]
if __name__ == "__main__":
numbers = sys.argv[1]
print("Length of the input: {}".format(len(numbers)))
matches = sum_of_matches(numbers)
print("Sum of all numbers that match the next: {}".format(matches))
half_way_matches = sum_of_matches_half_around(numbers)
print("Sum of all numbers that match the half-way-round-number: {}".format(half_way_matches))
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.