blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
9008970f01d43f3e60bba78c4ada5a0cc3c0847b | saraalrumih/100DaysOfCode | /day 017.py | 596 | 4.375 | 4 | # tuples 2
programming_languages = ("Java","Python","Ruby","C++","C")
print("The original tuple is: ",programming_languages)
# check if Python exists in the tuple
print("Check if Python exists in the tuple: ")
print("\tPython is in the tuple") if "Python" in programming_languages else print("\tPython is not in the tuple")
repeated_tuple=("swift",)*5
print("The repeated tuple is: ", repeated_tuple)
# add two tuples
print("After adding the two tuples: ",programming_languages+repeated_tuple)
print("There is ",len(programming_languages)," languages in the programming_languages tuple.")
| true |
7f5abc029205f8d0e1c29e0115e92b3597ac70ee | saraalrumih/100DaysOfCode | /day 015.py | 1,033 | 4.34375 | 4 | # list methods
programming_languages = ["Java","Python","Ruby","C++","C"]
print("The original list is: ",programming_languages)
print("There is ",len(programming_languages)," languages in the list.")
# add JavaScript to the end of the list
programming_languages.append("JavaScript")
print("The list after adding JavaScript: ",programming_languages)
# insert Kotlin at the forth position
programming_languages.insert(3,"Kotlin")
print("The list after inserting Kotlin at the forth position: ",programming_languages)
# deleting Java from the list
programming_languages.remove("Java")
print("The list after removing Java: ",programming_languages)
# deleting the item in index 2
programming_languages.pop(2) # Kotlin will be removed from the list
print("The list after removing item with index 2: ",programming_languages)
# copy the list
copied_list=programming_languages.copy()
print("The copied list: ",copied_list)
# clear the list and make it empty
programming_languages.clear()
print("The empty list: ",programming_languages)
| true |
a5b75f8c17bb60b5f6bf7d17358c0f26c225079b | Danielyan86/LeetcodePython3 | /stack_栈/Implement_Stack_using_Queues.py | 1,710 | 4.46875 | 4 | # 题目:
# 使用队列实现栈的下列操作:
#
# push(x) -- 元素 x 入栈
# pop() -- 移除栈顶元素
# top() -- 获取栈顶元素
# empty() -- 返回栈是否为空
# 注意:
#
# 你只能使用队列的基本操作-- 也就是 push to back, peek/pop from front, size, 和 is empty 这些操作是合法的。
# 你所使用的语言也许不支持队列。 你可以使用 list 或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。
# 你可以假设所有操作都是有效的(例如, 对一个空的栈不会调用 pop 或者 top 操作)。
class MyStack(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self._data = []
def push(self, x):
"""
Push element x onto stack.
:type x: int
:rtype: void
"""
self._data.append(x)
def pop(self):
"""
Removes the element on top of the stack and returns that element.
:rtype: int
"""
if not self.empty():
return self._data.pop()
def top(self):
"""
Get the top element.
:rtype: int
"""
if not self.empty():
return self._data[-1]
def empty(self):
"""
Returns whether the stack is empty.
:rtype: bool
"""
if self._data:
return False
else:
return True
# Your MyStack object will be instantiated and called as such:
if __name__ == '__main__':
obj = MyStack()
obj.push(1)
obj.push(2)
param_2 = obj.pop()
print(param_2)
param_3 = obj.top()
print(param_3)
param_4 = obj.empty()
| false |
5bbf4b3e6b2c1c5b659822f7b7fedc5f9dbb3725 | Danielyan86/LeetcodePython3 | /stack_栈/Valid_Parentheses.py | 1,164 | 4.125 | 4 | """ 给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
"""
class Solution:
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
p_list = []
for letter in s:
if letter in '({[':
p_list.append(letter)
else:
if p_list:
if letter == ')':
if p_list.pop() != '(':
return False
elif letter == ']':
if p_list.pop() != '[':
return False
elif letter == '}':
if p_list.pop() != '{':
return False
else:
return False
return False if p_list else True
if __name__ == '__main__':
parenthesis = "{[]}"
s_obj = Solution()
res = s_obj.isValid(parenthesis)
print(res)
| false |
4679fe71420c22433f37d50d1f081b2b93bf63a2 | srini-narasim/programming | /Python/collatz_hypothesis.py | 732 | 4.21875 | 4 |
#Steps of Collatz's hypothesis:
#1) Take any non-negative and non-zero
#integer number and name it c0;
#2) If c0 is even, evaluate a new c0 as c0 / 2;
#3) Otherwise, if odd, evaluate a new c0 as 3 * c0 + 1;
#4) If c0 is not equal to 1, skip to point 2.
#Write a program which reads one natural number
#and executes the above steps as long as c0 remains
#different from 1. We also want to count the
#steps needed to achieve the goal.
#Your code should ouput all the intermediate
#values of c0, too. (includng 1)
c0 = int(input())
steps = 0
while (c0 != 1):
print(c0)
# If n is odd
if c0 % 2 != 0:
c0 = 3 * c0 + 1
# If even
else:
c0 = c0 // 2
steps += 1
print(c0)
print("steps =", steps)
| true |
5b3fece499ccf8fae655cb94ff1f169a843bce11 | varshakohirkar/python-learning | /classes.py | 804 | 4.125 | 4 | class Person:
degree = "PhD"
def __init__(self,n,a,d="BTech"):
self.name = n
self.age = a
self.degree = d
def displayInstance(self):
print(self.name)
print(self.age)
print(self.degree)
person1=Person("varsha",24,"B.Tech")
person1.displayInstance()
"""
exit()
print("person 1")
Peson1 = Person("Varsha",24)
pint(Person1.name)
rint(Person1.age)
setattr(Person1,'sex',"female")
print(hasattr(Person1,"sex"))
print(Person1.degree)
print("-------------------------")
print("person 2")
Person2 = Person("Satish",27)
print(Person2.name)
print(Person2.age)
print(hasattr(Person1,"name"))
print(Person2.degree)
print("-------------------------")
print("person 3")
Person3 = Person("Varsha 2",24,"MS")
print(Person3.name)
print(Person3.age)
print(Person3.degree)"""
| false |
405339829f19c4a073fddf31130c118e3de59b59 | djtorel/python-crash-course | /Chapter 04/Try It/Try12/more_loops.py | 566 | 4.5 | 4 | # All versions of foods.py in this section have avoided using for loops when
# printing to save space. Choose a version of foods.py, and write two for loops
# to print each list of foods.
my_foods = ['pizza', 'falafel', 'carrot cake']
# This doesn't work
# friend_foods = my_foods
friend_foods = my_foods[:]
my_foods.append('cannoli')
friend_foods.append('ice cream')
print("My favorite foods are:")
for my_food in my_foods:
print(my_food)
print("\nMy friend's favorite foods are:")
for friend_food in friend_foods:
print(friend_food)
| true |
3594c63311086ea376558e82c02674a616df78fb | djtorel/python-crash-course | /Chapter 10/Try It/Try07/addition_calculator.py | 654 | 4.21875 | 4 | # Wrap your code from Exercise 10-6 in a while loop so the user can
# continue entering numbers even if they make a mistake and enter text
# instead of a number.
while True:
print("Enter two numbers and I will add them for you.")
print("Enter 'q' to quit.")
num1 = input("\nFirst number: ")
if num1 == 'q':
break
num2 = input("Second number: ")
if num2 == 'q':
break
try:
sum = int(num1) + int(num2)
except ValueError:
print("One of these is an invalid value.")
else:
print("The sum of " + num1 + " and " + num2 + " is: " +
str(sum) + "\n")
| true |
779a5d497bb8cbbe53ff3ad837b64b6a78377e33 | djtorel/python-crash-course | /Chapter 06/Try It/Try03/glossary.py | 1,219 | 4.71875 | 5 | # A Python dictionary can be used to model an actual dictionary.
# However, to avoid confusion, let’s call it a glossary.
# • Think of five programming words you’ve learned about in the previous
# chapters. Use these words as the keys in your glossary, and store
# their meanings as values.
# • Print each word and its meaning as neatly formatted output. You
# might print the word followed by a colon and then its meaning, or
# print the word on one line and then print its meaning indented on a
# second line. Use the newline character (\n) to insert a blank line
# between each word-meaning pair in your output.
glossary = {
'variable': 'Used to store some sort of data or information.',
'list': 'A collection of data or information that can be iterated.',
'struct': 'An immutable collection of data that can be iterated.',
'dictionary': 'A collection of data stored as key value pairs.',
'string': 'A series of text characters.'
}
print("Variable:\n\t" + glossary['variable'])
print("\nList:\n\t" + glossary['list'])
print("\nStruct:\n\t" + glossary['struct'])
print("\nDictionary:\n\t" + glossary['dictionary'])
print("\nString:\n\t" + glossary['string'])
| true |
1b2624e81e5632755830e4bba5c3bbbb005d7269 | djtorel/python-crash-course | /Chapter 13/Try02/main.py | 1,155 | 4.1875 | 4 | # Better Stars: You can make a more realistic star pattern by
# introducing randomness when you place each star. Recall that you can
# get a random number like this:
# from random import randint
# random_number = randint(-10,10)
# This code returns a random integer between –10 and 10. Using your code
# in Exercise 13-1, adjust each star’s position by a random amount.
# Imports
import pygame
from pygame.sprite import Group
from settings import Settings
import game_functions as gf
# Main function
def main():
"""Main game function"""
# Init pygame and settings
pygame.init()
g_settings = Settings()
# Create game window
screen = gf.new_window(g_settings.screen_width,
g_settings.screen_height,
g_settings.caption)
# Create stars group
stars = Group()
# Create star grid
gf.create_star_grid(g_settings, screen, stars)
# Game loop
while True:
# Check events
gf.check_events()
# Update screen
gf.update_screen(g_settings, screen, stars)
# Run game
main()
| true |
575f6b9e5168b7c0a0dc75cbf5c424ec677f8d14 | djtorel/python-crash-course | /Chapter 10/Try It/Try12/fav_number_remembered.py | 1,196 | 4.21875 | 4 | # Combine the two programs from Exercise 10-11 into one file. If the
# number is already stored, report the favorite number to the user. If
# not, prompt for the user’s favorite number and store it in a file.
# Run the program twice to see that it works.
import json
def get_favorite_number():
"""Get stored favorite number if it exists."""
filename = 'favorite_number.json'
try:
with open(filename) as f_obj:
number = json.load(f_obj)
except FileNotFoundError:
return None
else:
return number
def get_new_number():
"""Get a new favorite number and store it"""
filename = 'favorite_number.json'
number = input("What's your favorite number? ")
with open(filename, 'w') as f_obj:
json.dump(number, f_obj)
print("\nI will remember that " + number + " is your favorite number.")
def favorite_number():
"""
Print out favorite number if it exists,
if not call get_new_number()
"""
number = get_favorite_number()
if number:
print("Your favorite number is " + number + "!")
else:
get_new_number()
favorite_number()
| true |
dd95ca18c296abeeb653dd03c3c34ea0de518f42 | djtorel/python-crash-course | /Chapter 07/Try It/Try08/deli.py | 781 | 4.21875 | 4 | # Make a list called sandwich_orders and fill it with the names of
# various sandwiches. Then make an empty list called
# finished_sandwiches. Loop through the list of sandwich orders and
# print a message for each order, such as I made your tuna sandwich.
# As each sandwich is made, move it to the list of finished sandwiches.
# After all the sandwiches have been made, print a message listing each
# sandwich that was made.
sandwich_orders = ['tuna', 'club', 'blt', 'hamburger', 'roast beef', ]
finished_sandwiches = []
while sandwich_orders:
sandwich = sandwich_orders.pop(0)
print("Now making your " + sandwich + " sandwich.")
finished_sandwiches.append(sandwich)
print("\nList of finished sandwiches:")
for sandwich in finished_sandwiches:
print(sandwich)
| true |
5140ae8459fd0dadd5be7970bccb2b3e8cec8865 | djtorel/python-crash-course | /Chapter 07/Try It/Try03/multiples_of_ten.py | 310 | 4.40625 | 4 | # Ask the user for a number, and then report whether the number is a
# multiple of 10 or not.
number = input("Input a number: ")
number = int(number)
if number % 10 == 0:
print("The number " + str(number) + " is divisible by 10.")
else:
print("The number " + str(number) + " is not divisible by 10.")
| true |
dde931a0f1c837abd17f419140df09f7900079af | zstephens/neat-genreads | /source/input_checking.py | 2,298 | 4.15625 | 4 | """
This file contains several standard functions that will be used throughout the program. Each function checks input
and issues an error if there is something wrong.
"""
import pathlib
import sys
def required_field(variable_to_test: any, err_string: str) -> None:
"""
If required field variable_to_test is empty, issues an error. Otherwise this does nothing
:param variable_to_test: Any input type
:param err_string: A string with the error message
:return: None
"""
if variable_to_test is None:
print('\n' + err_string + '\n')
sys.exit(1)
def check_file_open(filename: str, err_string: str, required: bool = False) -> None:
"""
Checks that the filename is not empty and that it is indeed a file
:param filename: file name, string
:param err_string: string of the error if it is not a file
:param required: If not required, skips the check
:return: None
"""
if required or filename is not None:
if filename is None:
print('\n' + err_string + '\n')
sys.exit(1)
else:
try:
pathlib.Path(filename).resolve(strict=True)
except FileNotFoundError:
print('\n' + err_string + '\n')
sys.exit(1)
def check_dir(directory: str, err_string: str) -> None:
"""
Checks that directory exists and is a directory
:param directory: string of the directory path
:param err_string: string of the error in case it is not a directory or doesn't exist
:return: None
"""
if not pathlib.Path(directory).is_dir():
print('\n' + err_string + '\n')
raise NotADirectoryError
def is_in_range(value: float, lower_bound: float, upper_bound: float, err_string: str) -> None:
"""
Checks that value is between the lower bound and upper bound, and if not prints an error message
(err_string) and exits the program.
:param value: float for the value
:param lower_bound: float for the upper bound
:param upper_bound: float for the lower bound
:param err_string: string of the error message to print if the value is out of range
:return: None
"""
if value < lower_bound or value > upper_bound:
print('\n' + err_string + '\n')
sys.exit(1)
| true |
1f7bdeac42231c47fb16389c5da367c88045bb10 | yamato-creator/coding | /C/C086.py | 292 | 4.1875 | 4 | def anti_vowel(text):
vowels = ['a','e','i','o','u','A','I','U','E','O']
new_text =[]
for i in text:
new_text.append(i)
for j in vowels:
if i == j:
new_text.remove(j)
return ''.join(new_text)
text = input()
print(anti_vowel(text))
| false |
d6be5c638d34166d6c5c2771179688f0f3c2fd8e | jnguyen1563/interview-practice | /Algorithms/Sorting/algorithms/insertion_sort.py | 692 | 4.3125 | 4 | def insertion_sort(arr):
""" Performs a basic insertion sort """
# Iterate through every index beside the first
for i in range(1, len(arr)):
# Store the value of the current item
curr_value = arr[i]
# Get the index before the current
prev_idx = i-1
# Go backwards and check if the current value is less than
# any of the previous
while prev_idx >= 0 and curr_value < arr[prev_idx]:
# Push every other value up in the index
arr[prev_idx+1] = arr[prev_idx]
prev_idx -= 1
# Insert the current value into its appropriate place
arr[prev_idx+1] = curr_value
return arr | true |
b1798887f5fe4c97f0db56b5b541664b204df331 | chezRong/dev-challenge-django | /interest_calculator/calculator.py | 1,536 | 4.3125 | 4 | """
Interest Calculator functions.
"""
def calculate_payout(initial, monthly_deposit, interest_rate, frequency, duration):
"""
Calculates the monthly balance of a savings account given the initial
amount, the monthly deposit, the interest rate and the duration in
years
"""
# Interest with frequency taken into account
interest = (interest_rate / 100) / frequency
# Apply interest every n months
interest_frequency = 12 / frequency
# Number of months to calculate
duration_in_months = duration * 12
# Rolling Total
rolling = initial
# Average for current period
average = 0
# Total deposit
total_deposit = 0
# Local interest and total interest
local_interest = 0
total_interest = 0
# Result list
result = []
for month in range(1, duration_in_months + 1):
total_deposit += monthly_deposit
rolling += monthly_deposit
average += rolling
if month % interest_frequency == 0:
# Take average over period rather than end value.
local_interest = (average / interest_frequency) * interest
total_interest += local_interest
rolling += local_interest
average = 0
result.append({
'month': month,
'amount': round(rolling, 2),
'interestAmount': round(local_interest, 2),
'totalDeposit': round(total_deposit, 2),
'totalInterest': round(total_interest, 2)
})
return result
| true |
08f4fe460611469856d6a9f7bce0b04c5e6fba23 | Eako/datasciencecoursera | /py4inf/Assign5-2.py | 771 | 4.21875 | 4 | #loop program reads numbers to find min & max values
smallest = None
largest = None
while True:
input = raw_input ("Enter a number: ")
if input == "done" : break
if len(input) < 1 : break #checks for empty line to end
try:
num = float (input)
except:
print "Invalid input"
continue #restarts loop to get new data
for itervar in [input]:
if input is None or itervar > largest:
largest = itervar
#return largest
for itervar in [input]:
if smallest is None:
smallest = itervar
elif itervar < smallest:
smallest = itervar
print "Maximum is ",largest
print "Minimum is ",smallest
#enter ends the program to get min & max values
| true |
69eed6ca792062142efe0f5e53f7bdee6ae41ba7 | Eako/datasciencecoursera | /py4inf/Text4-7.py | 507 | 4.15625 | 4 | #enter score to get alpha grade per scale
def computegrade (s):
if s >= 1.0:
g = 'Bad Score'
elif s >= 0.9:
g = 'A'
elif s >= 0.8:
g = 'B'
elif s >= 0.7:
g = 'C'
elif s >= 0.6:
g = 'D'
elif s < 0.6:
g = 'F'
return g
try:
input = raw_input('Please enter score from 0.0 to 1.0: ')
numscore = float (input)
except:
print 'Error, invalid score'
quit ()
grade = computegrade (numscore)
print str(grade) | false |
45c678ee42a9e7ca80be6721069f351988880bd5 | SagarRameshPujar/pythonws | /prime.py | 375 | 4.28125 | 4 | #Program to find the given number is prime or not
num = int(input("Enter the number: "))
flag = True
if num > 1:
for i in range(2,num // 2+1):
if num % i == 0:
flag = False
break
else:
flag = False
if flag:
print(f"Given number is {num} is prime")
else:
print(f"Given number is {num} not prime")
| true |
5679c04aba625cc63abc6083caf5d1357521935e | olympiawoj/Hash-Tables | /dynamic_array.py | 2,245 | 4.3125 | 4 |
#Make our own array class
class DynamicArray:
#initialize array, make a constructor
#must track capacity and count, how many we're using inside array,
#need place to store or data - emulate allocating memory by allocating spaces or buckets in a python list
#capacity is number of empty spots
def __init__(self, capacity):
self.capacity = capacity
self.count = 0
self.storage = [None] * self.capacity
def __len__(self):
return self.count
#inserting into an array, what 2 things are relevant - value and place
#insert is non destrictuve, doesnt just overwrite, but check a few things before moving everything over
#check to make sure we have in the first place capacity/open space/ index in range
#
def insert(self, index, value):
#make sure we have open space
if self.count >= self.capacity:
#TO DO : make array dynamically resize
self.double_size()
#make sure index is in range
if index > self.count:
print("ERROR: Index out of range")
return
#shift everything over to right
#start with the last one, move it to the right, do a backwards for loop to start at end and go neative
for i in range(self.count, index, -1):
#self storage at i becomes w/e is to left of it
self.storage[i] = self.storage[i-1]
#insert our value
self.storage[index] = value
self.count +=1
def append(self, value):
self.insert(self.count, value)
def double_size(self):
self.capacity *= 2
new_storage = [None] * self.capacity
for i in range(self.count):
new_storage[i] = self.storage[i]
#replace self.storage with new storage
self.storage = new_storage
#Where is the initial value, we're initializing with Capacity, so we're doing my_array[4]
my_array = DynamicArray(4)
#index of 0
print(my_array.storage)
my_array.insert(0, 1)
my_array.insert(0, 2)
my_array.insert(1, 3)
my_array.insert(1, 3)
my_array.insert(0, 5)
my_array.append(20)
print(my_array.storage)
#[2, 3, 1, 4]
# after adding double capacity:
# [5, 2, 3, 1, 4, 20, None, None] | true |
d8e806e639ee745f81bd95c69999a93d7c040845 | Henry-the-junior/tictactoe_teaching_resource | /tictactoe_ep2.py | 2,696 | 4.125 | 4 | theBoard = [' '] * 10
def drawBoard(board):
# This function prints out the board that it was passed.
# "board" is a list of 10 strings representing the board (ignore index 0)
print(' | |')
print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9])
print(' | |')
print('-----------')
print(' | |')
print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6])
print(' | |')
print('-----------')
print(' | |')
print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3])
print(' | |')
input('這邊教一下while loop')
input('還有if-else')
input('教得很淺啦...熟python的就聽聽吧')
input('但也因為很簡單,所以初學者還是要記得多鑽研')
input('教之前,我們來觀察一下以下的程式')
drawBoard(theBoard)
#---------------------------------
input('第一手')
move = input('Make a move: ')
move = int(move)
theBoard[move] = 'O'
drawBoard(theBoard)
#---------------------------------
input('第二手')
move = input('Make a move: ')
move = int(move)
theBoard[move] = 'X'
drawBoard(theBoard)
#---------------------------------
input('第三手')
move = input('Make a move: ')
move = int(move)
theBoard[move] = 'O'
drawBoard(theBoard)
#---------------------------------
input('第四手')
move = input('Make a move: ')
move = int(move)
theBoard[move] = 'X'
drawBoard(theBoard)
#---------------------------------
input('第五手')
move = input('Make a move: ')
move = int(move)
theBoard[move] = 'O'
drawBoard(theBoard)
#---------------------------------
input('第六手')
move = input('Make a move: ')
move = int(move)
theBoard[move] = 'X'
drawBoard(theBoard)
#---------------------------------
input('第七手')
move = input('Make a move: ')
move = int(move)
theBoard[move] = 'O'
drawBoard(theBoard)
#---------------------------------
input('第八手')
move = input('Make a move: ')
move = int(move)
theBoard[move] = 'X'
drawBoard(theBoard)
#---------------------------------
input('第九手')
move = input('Make a move: ')
move = int(move)
theBoard[move] = 'O'
drawBoard(theBoard)
"""
思考這支程式有什麼問題?
"""
"""
!!!初始化棋盤!!!
while 遊戲正在進行:
if 玩家1的回合:
玩家1下棋
if 玩家1勝利:
遊戲結束
else:
if 棋盤下滿了:
遊戲結束
else:
換玩家2的回合
else:
玩家2下棋
if 玩家2勝利:
遊戲結束
else:
if 棋盤下滿了:
遊戲結束
else:
換玩家1的回合
""" | false |
c498f0df2300e2d95e48acc168d9fa555f684eaa | Guuzii/DA-Python-MacGyver-pygame | /component/position.py | 1,188 | 4.46875 | 4 | """
Position Object module
"""
class Position:
"""
Position Object
Initialize a position object
Parameters:
- posX (int): the X index (horizontal coordinate) of the position
- posY (int): the y index (vertical coordinate) of the position
Attributes:
- X (int): argument posX
- Y (int): argument posY
"""
def __init__(self, posX, posY):
self.X = posX
self.Y = posY
def __eq__(self, other_position):
if self.X == other_position.X and self.Y == other_position.Y:
return True
return False
def __hash__(self):
return hash((self.X, self.Y))
def move_up(self):
"""Return a new position with Y = Y-1"""
return Position(self.X, self.Y - 1)
def move_down(self):
"""Return a new position with Y = Y+1"""
return Position(self.X, self.Y + 1)
def move_left(self):
"""Return a new position with X = X-1"""
return Position(self.X - 1, self.Y)
def move_right(self):
"""Return a new position with X = X+1"""
return Position(self.X + 1, self.Y)
| true |
a952ee38b4e6d85f899944aad45d62a1e142af2c | cirrustype/bioinformatics | /Rosalind/python_village/variables_arithmetic.py | 906 | 4.1875 | 4 | #Austin Schenk
#Rosalind python village
#problem 2
from math import sqrt
####Variables & some Arithmetic####
####notes####
#you must indicate floating point or python will round down to the
#nearest whole number. float(#)
# == is equality
####problem####
""" Given: Two positive integers a and b, each less than 1000.
Return: The integer corresponding to the square of the hypotenuse of the right triangle whose legs have lengths a and b. """
####solution####
# a^2 + b^2 = c^2
# c = abs(sqrt(a^2 + b^2))
def hypo(a,b):
c = abs(sqrt(a**2 + b**2))
return(c)
#print(hypo(3, 5)) # 5.83...???
#print(sqrt((3**2) + (5**2)))
#print(3**2)
#print(5**2)
#this function works but the question is asking for the square. Reading the
#question does help.
def hypo(a,b):
c = a**2 + b**2
return(c)
print(hypo(3, 5)) # 34, bingo!
#sample given: 984, 964
print(hypo(984, 964))
#answer: 1897552, correct. | true |
4390ec6a5ac9f11c3a47d2c3f077d20130abc7a7 | mgs95/hackerrank | /practice/medium/2018/BiggerIsGreater.py | 1,328 | 4.15625 | 4 | """
https://www.hackerrank.com/challenges/bigger-is-greater/problem
Score: 35/35
Submitted: 2018
"""
"""
Steps:
1. Finds the first unsorted element traversing the word backwards.
2. Replace with the next higher letter in the actual traversed
section of the word.
3. Sort the remain elements of the traversed section.
"""
def bigger_is_greater(w):
w = list(w)
last = w[-1]
result = ''
for i in range(len(w) - 2, -1, -1):
act = w[i]
# 1. Is element sorted compared with last element?
if act >= last:
last = act
continue
# 2. Finds next higher letter
to_replace_list = sorted(list(set(w[i:])))
try:
to_replace = to_replace_list[to_replace_list.index(act) + 1]
except IndexError:
# Element to replace does not exist
return 'no answer'
replaced = w[i:].index(to_replace)
# 3. Sort the remain elements and join all sections
w[replaced + i] = act
following = sorted(w[i + 1:])
result = w[:i] + [to_replace] + following
return ''.join(result)
return 'no answer'
if __name__ == "__main__":
T = int(input().strip())
for a0 in range(T):
w = input().strip()
result = bigger_is_greater(w)
print(result)
| true |
e2632c6fc98c000304db97af5b41124950e8335d | dstmp/rosetta_sort | /python/quicksort.py | 1,946 | 4.34375 | 4 | def quicksort(sortable):
"""Return the sorted list
>>> quicksort(['zebra', 'aardvark', 'coyote', 'abalone', '123', '456'])
['123', '456', 'aardvark', 'abalone', 'coyote', 'zebra']
Given a list including duplicates
>>> quicksort(['12', '12', 'zebra', 'aardvark', 'cat', 'cat', 'abalone'])
['12', '12', 'aardvark', 'abalone', 'cat', 'cat', 'zebra']
Given a list that starts out already sorted
>>> quicksort(['aardvark', 'abalone', 'coyote', 'zebra'])
['aardvark', 'abalone', 'coyote', 'zebra']
Given a list that starts out reversed
>>> quicksort(['zebra', 'coyote', 'abalone', 'aardvark'])
['aardvark', 'abalone', 'coyote', 'zebra']
Given a single element list
>>> quicksort(['zebra'])
['zebra']
Given an empty list
>>> quicksort([])
[]
"""
__quicksort(sortable, 0, len(sortable) - 1)
return sortable
def __quicksort(sortable, first, last):
if first >= last:
return
pivot = __median_of_three(sortable, first, last)
sortable[pivot], sortable[last] = sortable[last], sortable[pivot]
left = first
right = last - 1
while left <= right:
while left <= last and sortable[left] < sortable[last]:
left += 1
while right >= first and sortable[last] < sortable[right]:
right -= 1
if left <= right:
sortable[left], sortable[right] = sortable[right], sortable[left]
left += 1
right -= 1
sortable[left], sortable[last] = sortable[last], sortable[left]
__quicksort(sortable, first, left - 1)
__quicksort(sortable, left + 1, last)
def __median_of_three(sortable, left, right):
center = (left + right)/2
small = left
large = right
if sortable[large] < sortable[small]:
small, large = large, small
if sortable[large] < sortable[center]:
return large
if sortable[center] < sortable[small]:
return small
return center
if __name__ == "__main__":
import doctest
doctest.testmod()
| true |
89d1ef3153ddf620deac4a6e19a7821de6c05cb5 | naymajahan/Lists-python | /List-methods.py | 688 | 4.28125 | 4 | # The LIst Methods
# The Index() Methods
PlacesVisited = ['India', 'Nepal', 'Malaysia', 'Bhutan', 'USA']
print(PlacesVisited.index('Nepal'))
# The Append method
PlacesVisited.append('Africa')
print(PlacesVisited)
# The Insert() method
PlacesVisited.insert(2, 'UK')
print(PlacesVisited)
#The Remove Method
PlacesVisited.remove('Bhutan')
print(PlacesVisited)
# The Sort() method
### Python itself sorting -Capital letter priority then alphabate
PlacesVisited.sort()
print(PlacesVisited)
### Python force sorting
# use key=str.lower
PlacesVisited.sort(key=str.lower)
print(PlacesVisited)
## the reverse sorting
PlacesVisited.sort(key=str.lower, reverse=True)
print(PlacesVisited)
| true |
a8c4c28f5ed30ad3ae20f2dbbfb9f63a91bc058d | Workgeek100/C98 | /function.py | 271 | 4.25 | 4 | def countwordsfromfile():
filename = input("Enter the file name")
file = open(filename,"r")
number_of_words = 0
for i in file :
words = i.split()
number_of_words = number_of_words+len(words)
print(number_of_words)
countwordsfromfile() | true |
0af1a884e77d3b1daf83b6705e464b61590ce1fa | yozaam/placementTraining | /day6_reverse_number_without_string.py | 372 | 4.21875 | 4 | # Required concepts: https://www.w3schools.com/python/python_intro.asp while loop and maths
print('Question: reverse number without using strings')
def getReverse(num):
res = 0
while num > 0:
# take last digit and put in the front of res
digit = num % 10
num //= 10
res = res * 10 + digit
return res
print(getReverse(1234))
| true |
6bea641922e0c166246303f3734ab252e218edaf | syndacks/nyu_advanced_python | /week1/homework_1.3.py | 565 | 4.3125 | 4 | """
Write a program that takes an integer as
user input and uses a while loop to generate a fibonacci
series (in which each number in the series is the sum of the previous two
numbers in the series (the series begins 1,
1, 2, 3, 5, 8, 13, etc.)) up to the user's number.
"""
def fibonacci_generator(user_input):
counter = 1
my_array = [1, 1]
while (my_array[counter] < user_input):
print my_array
difference = my_array[counter] + my_array[counter - 1]
my_array.append(difference)
counter += 1
fibonacci_generator(100)
| true |
6cffa280cb0fda77ad1999a2a61e5472d9f7bd9a | Tmk10/Excercises | /24.py | 606 | 4.125 | 4 | """Question 24
Level 1
Question:
Python has many built-in functions, and if you do not know how to use it, you can read document online or find some books. But Python has a built-in document function for every built-in functions.
Please write a program to print some Python built-in functions documents, such as abs(), int(), raw_input()
And add document for your own function
Hints:
"""
print(abs.__doc__)
print(int.__doc__)
print(input.__doc__)
def func(a : int) -> int:
"""This function does nothing except printing some info using builtin __doc__ function"""
print(func.__doc__)
| true |
dcdd4b96a6f42242926c8f93f4dbbc57b163a635 | Tmk10/Excercises | /39.py | 267 | 4.125 | 4 | """Question: 39
Define a function which can generate and print a tuple where the value are square of numbers between 1 and 20 (both included)."""
def squarelist():
squares = tuple([str(x ** 2) for x in range(1, 21)])
print(",".join(squares))
squarelist()
| true |
b8315a11ee57a3f6770be05d75c052e23f0e7e73 | Tmk10/Excercises | /16.py | 489 | 4.34375 | 4 | """Question 16
Level 2
Question:
Use a list comprehension to square each odd number in a list. The list is input by a sequence of comma-separated numbers.
Suppose the following input is supplied to the program:
1,2,3,4,5,6,7,8,9
Then, the output should be:
1,3,5,7,9
Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.
"""
data = input(" ")
data = data.split(",")
result = [x for x in data if int(x) % 2 != 0]
print(",".join(result)) | true |
0e2779cd42995b3cc74c9586e2aae2d882ea811b | chaebum-kim/algorithm-problems | /linkedlist/linkedlist03.py | 1,304 | 4.125 | 4 | ''' Question:
* Given a doubly linked list, list nodes also have a child property that can point to
* a separate doubly linked list. These child lists can also have one or more child
* doubly linked lists of their own, and so on.
* Return the list as a single level flattened doubly linked list
* https://leetcode.com/problems/flatten-a-multilevel-doubly-linked-list/
'''
class Node:
def __init__(self, val, prev, next, child):
self.val = val
self.prev = prev
self.next = next
self.child = child
def flatten_list(head: Node) -> Node:
current = head
while current is not None:
if current.child is not None:
# Find the last node of child list
last_child = current.child
while last_child.next is not None:
last_child = last_child.next
# Link last child node to the next node
last_child.next = current.next
if last_child.next is not None:
last_child.next.prev = last_child
# Link child node to the current node
current.next = current.child
current.next.prev = current
current.child = None
current = current.next
return head
# Time complexity: O(N)
# Space complexity: O(1)
| true |
b5b207f42de267c330377ad96d705184ce794acb | ivanamark/bdc | /controlflow/loops/while/pract4.pyw | 493 | 4.4375 | 4 | # Write a while loop that finds the largest square number less than an integerlimit and stores it in a variable nearest_square. A square number is the product of an integer multiplied by itself, for example 36 is a square number because it equals 6*6.
# For example, if limit is 40, your code should set the nearest_square to 36.
limit = 40
nearest=0
# write your while loop here
while nearest**2 < 40:
nearest_square=nearest**2
result=nearest_square
nearest+=1
print(result) | true |
1d8aa0e5c98a26dcfff3d0f4abb2b427ce3b401d | ssavann/Python-Functions | /PrimeNumberChecker.py | 494 | 4.21875 | 4 | """
You need to write a function that checks
whether if the number passed into it is a prime number or not.
"""
def prime_checker(number):
is_prime = True
for nb in range(2, number):
if number % nb == 0:
is_prime = False
if is_prime:
print(f"{number} is a prime number.")
else:
print(f"{number} is Not a prime number")
n = int(input("Check this number: "))
prime_checker(number=n)
"""
Prime numbers: 2 3 5 7 11 13 17 19 23 29
""" | true |
1e1862fda892deba22fc0aa52660b418c5415585 | codertjay/favourtkinter | /tkintergrid.py | 927 | 4.1875 | 4 | #the grid enable us to write a file in row and column not like packing that it just place it on the screen
from tkinter import *
"""
tjay = Tk()
#creating a widget
label1 = Label(tjay,text="hello world")
label2 = Label(tjay,text="hello world")
label3 = Label(tjay,text="hello world")
#shoving it on the scrfeen
label1.grid(row=0,column=0)
label2.grid(row=1,column=1)
label3.grid(row=1,column=5)
tjay.mainloop()
"""
#there is another way you can show it on the ascreen by just making it faster
#you can crfeate a widget and show it on a screen at gthe same time
"""
tja = Tk()
#creating a widget
label1 = Label(tja,text="hello world").label1.grid(row=0,column=0)
label2 = Label(tja,text="hello favour").label2.grid(row=1,column=1)
label3 = Label(tja,text="hello david").label3.grid(row=1,column=5)
#this way i had created the widget and place it on the screen
tja.mainloop()
#but it is not working
""" | true |
0d8791e96486b9d282cf8d7c2f3cd86cfbad9c55 | codertjay/favourtkinter | /tkinter1pack.py | 364 | 4.28125 | 4 | from tkinter import *
tjay = Tk()
#creating a label widget
myLabel1 = Label(tjay,text = "Hello World",fg="red")
myLabel2 = Label(tjay,text = "favour")
myLabel3 = Label(tjay,text = "Thankgod")
#shoving it into the screen
myLabel1.pack()
myLabel2.pack()
myLabel3.pack()
#the loop that create every thing on the screen
tjay.mainloop()
#positioning with tikinter
| true |
a6060824dc7e5b0f6fda58408da6e35b5da9459c | yangzhenxiong/praticepython | /code/ex11.py | 982 | 4.3125 | 4 | #coding=utf-8
'''
Ask the user for a number and determine whether the number is prime or not.
(For those who have forgotten, a prime number is a number that has no divisors.). You can (and should!)
use your answer to Exercise 4 to help you. Take this opportunity to practice using functions, described below.
Discussion
Concepts for this week:
Functions
Reusable functions
Default arguments
'''
def get_number(prompt):
return int(input(prompt))
def is_prime(number):
if number == 1:
prime = False
elif number == 2:
prime = True
else:
prime = True
for check_number in range(2, (number/2)+1):
if number % check_number == 0:
prime=False
break
return prime
def print_prime(number):
prime = is_prime(number)
if prime:
descriptor = " "
else:
descriptor ="not "
print(number," is ", descriptor,"prime.")
print_prime(get_number("Enter a number to check.")) | true |
ee8f0a2e922724451956e287db1402b794c90389 | drouserudd55/lpthw_exercises | /ex6.py | 868 | 4.34375 | 4 | #Declare variable types_of_people
types_of_people = 10
#Format types_of_people into x
x = f"There are {types_of_people} types of people"
#Create variable with the strings binary, and don't
binary = "binary"
do_not = "don't"
#Add above strings into a thrid string
y = f"those who know {binary} and those who {do_not}."
#Print both the strings
print(x)
print(y)
#Print them again
print(f"I said {x}")
print(f"I also said {y}")
#assign hilarious as False
hilarious = False
#assign string into joke evaluation, and prepare it to be formatted
joke_evaluation = "Isn't that joke so funny?! {}"
#print joke_evaluation and format hilarious into it
print(joke_evaluation.format(hilarious))
#assign two stings into two variables
w = "this is the left side of..."
e = "a string with a right side"
#concatinate both variables and print them
print(w + e)
| true |
0896f9e41602aafd179e808836e563affba0141d | wehrwolf217/NIXEducation_TRAINEE-Python.-Level-2 | /task15.py | 1,546 | 4.125 | 4 | #! /usr/bin/env python3
"""Создайте несколько классов: Animal (абстрактный класс), Cat, Dog
Создайте абстрактные методы say, run и jump в классе Animal (abc.abstractmethod)
Реализуйте полиморфизм поведения животных для методов: say, run, jump"""
import abc
from abc import ABC
class Animal(ABC):
"""abstract class"""
def __init__(self):
if type(self) is Animal:
raise Exception('Animal is an abstract class and cannot be instantiated directly')
@abc.abstractmethod
def say(self):
return 'abs method say'
@abc.abstractmethod
def run(self):
return 'abs method run'
@abc.abstractmethod
def jump(self):
return 'abs method jump'
class Cat(Animal):
def __init__(self, name):
super().__init__()
self.name = name
def say(self):
return 'Meow'
def run(self):
return f'Cat {self.name} is running'
def jump(self):
return f'Cat {self.name} is jumping'
class Dog(Animal):
def __init__(self, name):
super().__init__()
self.name = name
def say(self):
return 'Woof!'
def run(self):
return f'Dog {self.name} is running'
def jump(self):
return f'Dog {self.name} is jumping'
# kryakva = Animal()
# print(kryakva.say())
kuzya = Cat('Kuzya')
bobik = Dog('Bobik')
print(kuzya.say())
print(bobik.say())
print(kuzya.run())
print(bobik.jump())
| false |
960a22798b63cd28a7778facf817dc26560b37b2 | believecjt/Student-Management-System | /students.py | 2,353 | 4.125 | 4 | #学生管理系统 -- 添加、删除、查询、修改、退出
import time;
#1、先把整体框架考虑清楚,即搭框架
#1.1 展示选项
def showInfo():
print("-"*30);
print(" 学生管理系统 ");
print("1、添加学生信息");
print("2、删除学生信息");
print("3、查询学生信息");
print("4、修改学生信息");
print("5、列出所有学生信息");
print("6、退出系统");
print("-"*30);
#1.2 提示用户输入选项,并获取用户的输入
#1.3 根据用户输入的选项,执行相应行为
#学生信息的存储方式:字典{姓名:name,年龄:age,学号:id}
#学生列表:列表【{学生1},{学生2},。。。】
students = [];
stuInfo = {};
def addStu(students):#添加学生信息
stuInfo['name'] = input("请输入学生的姓名:");
stuInfo['age'] = input("请输入学生的年龄:");
stuInfo['stuId'] = input("请输入学生的学号:");
students.append(stuInfo);
def delStu(students):#删除学生信息
delNum = int(input("请输入您要删除的学生序号:"));
del students[delNum];
def lookupStu(students):
num = int(input("请输入您要查询的学生序号:"));
print("查询中。。。");
time.sleep(1);
print("姓名:%s"%students[num]['name']);
print("年龄:%s"%students[num]['age']);
print("学号:%s"%students[num]['stuId']);
def editStu(students):
num = int(input("请输入您要修改的学生序号:"));
info = int(input("请选择要修改的信息(1=姓名,2=年龄,3=学号):"));
if(info==1):
students[num]['name'] = input("请输入姓名:");
elif(info==2):
students[num]['age'] = input("请输入年龄:");
elif(info==3):
students[num]['stuId'] = input("请输入学号:");
else:
print("该选项不存在!")
def allStu(students):
print("----学生列表----");
print("序号\t姓名")
for x,s in enumerate(students):
print('%d\t%s'%(x,s['name']));
while(True):
showInfo();
selected = int(input("请选择你要进行的操作(序号):"));
if(selected==1):
addStu(students);
elif(selected==2):
delStu(students);
elif(selected==3):
lookupStu(students);
elif(selected==4):
editStu(students);
elif(selected==5):
allStu(students);
elif(selected==6):
print("已退出系统");
break
else:
print("您输入有误");
break | false |
12b251d42669a66c5a1d8a53b647217fcfedbd84 | helloprasanna/python | /Map Filter Reduce (1).py | 770 | 4.15625 | 4 |
# coding: utf-8
# Demonstrates the Map function
# which applies function to list of values
# In[4]:
import math
def area(n):
return math.pi * (n**2)
radii=[3,4,5,8,10,38]
print(radii)
print(list(map(area,radii)))
# ### Applying Map
# In[5]:
li = [('a',1),('b',2),('c',3)]
conv = lambda data: (data[0],data[1]**2)
print(list(map(conv,li)))
# ### Apply Filter
# Filter the list containing more than average
# In[10]:
import statistics
data = [1,3,4,5,6,7,3,4,6,8,9]
avg = statistics.mean(data)
print(list(filter(lambda x: x>avg,data)))
# ### Filter None
# In[12]:
countries=['hello.py','american','russia','','hell']
print(list(filter(None,countries)))
# ### Apply reduce to data set
# In[ ]:
data = [1,3,4,5,6,7,3,4,6,8,9]
| true |
362b2ac8778211edeae5f2bf7cd2c029d2654d45 | maratumba/erp_blink | /alday mne scripts/input_error_handling.py | 418 | 4.15625 | 4 | # this is a comment
i = input("Enter a number to square: ") # this is another one
while i != "monkey":
try:
i = int(i)
except ValueError:
try:
i = float(i)
except ValueError:
print("Really? can't figure out what a number is?")
i = input("This time enter a NUMBER: ")
continue
print(i*i)
i = input("Enter a number to square: ")
| true |
08b4d1a9cdc993a9f938a0d093421ea57bd5244e | HatsuneMikuV/PythonLearning | /63.py | 853 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""
-------------------------------------------------
File Name: 63
Author : anglemiku
Eamil : anglemiku.v@gmail.com
date: 2020/1/14
-------------------------------------------------
Change Activity: 2020/1/14:
-------------------------------------------------
"""
'''
题目:求100之内的素数。(39.py)
'''
from math import sqrt
def count_prime_number(left, right):
result = []
if left < 2:
left = 2
for number in range(left, right + 1):
k = int(sqrt(number + 1))
leap = 0
for index in range(2, k + 1):
if number % index == 0:
leap = 1
break
if leap == 0:
result.append(number)
return result
if __name__ == '__main__':
print count_prime_number(1, 100)
pass | false |
3d90253ba53d34840f0e35c4926d681c10ed2780 | swetasingh0104/Hacktober2021 | /Languages/Python/powerOfANumber.py | 258 | 4.5 | 4 | # Write a python program to find exponential of a number (power of a number).
base = int(input("Enter an base: "))
exp = int(input("Enter an exponent: "))
power = 1
for i in range(1, exp + 1):
power = power * base
print(f"Power of a number = {power}")
| true |
99c7115fb5f877c79c9d77cc8b703bbdcde63a52 | swetasingh0104/Hacktober2021 | /Languages/Python/fibonacciSearch.py | 955 | 4.25 | 4 | # Write a python program to implement Fibonacci Search
def FibonacciGenerator(n):
if n < 1:
return 0
elif n == 1:
return 1
else:
return FibonacciGenerator(n - 1) + FibonacciGenerator(n - 2)
def fibonacciSearch(list, item):
m = 0
offset = -1
while FibonacciGenerator(m) < len(list):
m = m + 1
while (FibonacciGenerator(m) > 1):
i = min(offset + FibonacciGenerator(m - 2), len(list) - 1)
if (item > list[i]):
m = m - 1
offset = i
elif (item < list[i]):
m = m - 2
else:
return i
if(FibonacciGenerator(m - 1) and list[offset + 1] == item):
return offset + 1
return -1
list = [10, 15, 20, 25, 30, 35, 40, 45, 50]
element = int(input("Enter the element to search: "))
pos = fibonacciSearch(list, element)
if pos != -1:
print(f"Item Found at position {pos}")
else:
print("Item Not Found")
| false |
248f913d68bd9c30b8f8af316fe9474888fbb4f2 | rkkarn32/PythonTest | /myfileReader.py | 333 | 4.375 | 4 | myFile = open('myFile.txt','r+')
print('Your Current file contents:')
for lines in myFile:
print(lines)
inputText = input('what do you want to save ')
myFile.write(inputText);
myFile.close();
print('Things saved: See below for updated contents:')
myFile = open('myFile.txt','r')
for lines in myFile:
print(lines)
myFile.close()
| true |
eb6ee69a5cbf15525c87757fb394248c42a4b40c | sronkowski/quality-code-projects | /Week 1/palindromes.py | 1,527 | 4.34375 | 4 | def reverse(s):
""" (str) -> str
Return s reversed.
>>> reverse('hello')
'olleh'
"""
s_reversed = ''
for ch in s:
s_reversed = ch + s_reversed
return s_reversed
def is_palindrome_v1(s):
""" (str) -> bool
Return True if and only if s is a palindrome.
>>> is_palindrome_v1('noon')
True
>>> is_palindrome_v1('radar')
True
>>> is_palindrome_v1('kayaks')
False
"""
s_reversed = reverse(s)
return s == s_reversed
def is_palindrome_v2(s):
""" (str) -> bool
Return True if and only if s is a palindrome.
>>> is_palindrome_v2('noon')
True
>>> is_palindrome_v2('racecar')
True
>>> is_palindrome_v2('dented')
False
"""
# The number of chars in s.
n = len(s)
# Compare the first half of s to the reverse of the second half.
# Omit the middle character of an odd-length string.
return s[:n // 2] == reverse(s[n - n // 2:])
def is_palindrome_v3(s): """ (str) -> bool
Return True if and only if s is a palindrome.
>>> is_palindrome_v3('noon')
True
>>> is_palindrome_v3('racecar')
True
>>> is_palindrome_v3('dented')
False
"""
# s[i] and s[j] are the next pair of characters to compare.
i = 0
j = len(s) - 1
# The characters in s[:i] have been successfully compared to those in s[j:].
while i < j and s[i] == s[j]:
i = i + 1
j = j - 1
# If we exited because we successfully compared all pairs of characters,
# then j <= i.
return j <= i
| false |
65f6f6d595fb2b33c04bdf325aa3c0451e43d884 | StphnWright/Palindromes-and-Hangman | /problem1_2_3.py | 2,106 | 4.21875 | 4 | """
isPalindrome takes in a positive integer and returns True or False if the
number is a palindrome. puzzle1 computes and prints the three numbers.
make_palindromes returns a list of palindromes, and puzzle2 solves the puzzle.
Puzzle1 Iterations: 979
Puzzle2 Iterations: 87
"""
def isPalindrome(x):
x = str(x)
y = x[::-1]
if y == x:
return True
else:
return False
def puzzle1():
twodigitpal = 0
threedigitpal = 0
fourdigitpal = 0
for x in range(10, 100):
if (isPalindrome(x) == True):
twodigitpal = x
for y in range(100, 1000):
temp = y + twodigitpal
if (isPalindrome(y) == True and temp >= 1000 and isPalindrome(temp) == True):
fourdigitpal = temp
threedigitpal = y
print(twodigitpal, threedigitpal, fourdigitpal, 'puzzle1 iterations', y)
break
if (isPalindrome(y) == True and temp >= 1000 and isPalindrome(temp) == True):
break
def make_palindromes(d):
highest = int(pow(10, d)) + 1
half = int(pow(10, d // 2))
result = []
for i in range(half + 1):
num = str(i)
if num[0] != '0':
if d % 2 == 0:
palin = int(num + num[::-1])
if palin < highest:
if len(str(palin)) == d:
result.append(palin)
else:
for j in range(10):
palin = int(num + str(j) + num[::-1])
if palin < highest:
if len(str(palin)) == d:
result.append(palin)
return result
def puzzle2():
twos = make_palindromes(2)
threes = make_palindromes(3)
for two in twos:
count = 0
for three in threes:
four = two + three
if isPalindrome(four) and four > 1000:
print(two, three, four, 'puzzle2 iterations', count)
count += 1
puzzle1()
puzzle2()
| true |
eda698022656bde1bfbf69ec749002ee3507929f | ChihChaoChang/Leetcode | /009.py | 937 | 4.25 | 4 | '''
Palindrome Number
Determine whether an integer is a palindrome. Do this without extra space.
Could negative integers be palindromes? (ie, -1)
If you are thinking of converting the integer to string, note the restriction of using extra space.
You could also try reversing an integer. However, if you have solved the problem "Reverse Integer",
you know that the reversed integer might overflow. How would you handle such case?
There is a more generic way of solving this problem.
'''
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
div=1
if x <0:
return False
while (x/div) >=10:
div*=10
while x :
left =x/div
right =x%10
if left != right:
return False
x=x%div
x=x/10
div=div/100
return True
| true |
5bbe809f47b07dcafeb0204247f7a3f882db48f2 | RachanaDontula/beginner-learning | /multiThreading.py | 788 | 4.1875 | 4 | """
breaking a big problem into parts,
each part is called thread in programming
Multitasking: at a time multiple applications can be run.
Multitasking can be done using multi threading.
By using threads, multiple functions can be run simultaneously.
"""
from time import sleep
from threading import *
class Hello(Thread):
def run(self):
for i in range(5):
print("hello")
sleep(1) # used for huge code execution will be neat.
class Hi(Thread):
def run(self):
for j in range(5):
print("hi")
sleep(1)
obj1 = Hello()
obj2 = Hi()
obj1.start()
sleep(0.2) # avoid collision
obj2.start()
obj1.join() # join will execute first then print statements.
obj2.join()
print("bye") | true |
c75befa14ecfffe26f51f57fcd5142099a3681bc | DuyTheDao/my-python-journey | /length_characters.py | 373 | 4.125 | 4 | def characters():
while True:
word = input('Enter a word: ')
if len(word) < 5:
print("Your word is less than 5 characters")
elif len(word) > 5:
print("Your word is more than 5 characters")
else:
print("Your word is equal to 5 characters")
if not word:
return word
print (characters())
| true |
5099b1458028d445e7f0faf1171637aa18789262 | Donal-Flanagan/CyberdyneCollective | /tutorials/Intro to Computer Science with python_NUIG/Python Programs/factorial.py | 318 | 4.28125 | 4 | # factorial.py
#
# A program to compute the factorial of a number,
# illustrates the accumulator pattern.
def main():
n = input("Enter a positive integer, please: ")
product = 1
for factor in range(2, n+1):
product = product * factor
print "The factorial of", n, "is", product
main()
| true |
520607c86af96889b49fb1e0c40e1a7919290b63 | Donal-Flanagan/CyberdyneCollective | /tutorials/Intro to Computer Science with python_NUIG/Python Programs/caesar2.py | 574 | 4.375 | 4 | # text2numbers.py
# A program to convert a text message into a sequence of numbers
# according to the underlying ASCII encoding.
def main():
print "This program converts a text message into a sequence"
print "of numbers representing the ASCII encoding of the message."
print
# get the message
message = raw_input("Please enter the message to encode: ")
print
print "These are the ASCII codes:"
# loop over the message a print out the ASCII values.
for c in message:
a=ord(c)
a+5=b
print
print
main()
| true |
9795fc3a5901fdf2f494d811d079f24d09d5727b | Donal-Flanagan/CyberdyneCollective | /tutorials/Intro to Computer Science with python_NUIG/Python Programs/leap.py | 350 | 4.375 | 4 | # leapyear.py
# a program to calculate whether or not a year is a leap year
#
# by Dnal
def leapyear(year):
if year%4 == 0:
if((year%100==0) & (year%400==0)):
print "This is a leap year."
else:
print "This is not a leap year."
else:
print "Thsi is not a leap year."
main()
| false |
49b471af67c760b0e5e26a1d0a72dfbc80f4347c | Donal-Flanagan/CyberdyneCollective | /tutorials/Intro to Computer Science with python_NUIG/Example Programs/fibonacci.py | 384 | 4.25 | 4 | # a program to calculate fibonacci numbers.
def main():
print "this program calculates the n-th number"
print "in the fibonacci sequence 1, 1, 2, 3, 5, 8, ..."
n = input("Enter n: ")
old, new = 0, 1
print old,
for i in range(n):
old, new = new, old + new
print old,
print
print "the n-th Fibonacci number is ", old
main()
| true |
2ac7f6e3a6ec48a2609499d569ebeffa3431c179 | Donal-Flanagan/CyberdyneCollective | /tutorials/Intro to Computer Science with python_NUIG/Python Programs/numbers2text.py | 585 | 4.40625 | 4 | # numbers2text.py
# A program to convert a sequence of ASCII codes into a string of text
import string # the string library
def main():
print "This program converts a sequence of ASCII codes"
print "into the string of text that it represents."
print
# get the encoded message
print "Please enter the ASCII-encoded message:"
code = raw_input()
# loop through the code and build message.
message = ""
for num in string.split(code):
n = eval(num)
message = message + chr(n)
print "The decoded message is:", message
main()
| true |
ef56be48914459f337323131a56592a8e1f9b580 | Donal-Flanagan/CyberdyneCollective | /tutorials/Intro to Computer Science with python_NUIG/Python Programs/maybe.py | 471 | 4.15625 | 4 | # maybe.py
# a program which tells the user if an integer is positive, negative or zero
#
# by Dnal
def main():
print 'This program will tell you if an integer is positive, negative or'
print 'equal to zero.'
x=input('Please input the integer you wish to compute:')
if x==0:
print 'This integer is zero.'
elif x>0:
print 'This integer is positive.'
else:
print 'This integer is negative.'
main()
| true |
52b0e04be2e34aa663295474c3c38386a580ad5f | Castro99/2018-19-PNE-practices | /P0/sumn.py | 304 | 4.25 | 4 | #Exercise make a function n that print the sum of the numbers
number = int(input("Enter number n: "))
def total_sum(n):
total_number = 0
for i in range(n):
total_number = total_number + i + 1
return total_number
print("The sum of the number you introduce is :", total_sum(number)) | true |
d7c918184a32212b9f11c4d52339f846e2e311a1 | ali4413/EART119 | /1_2b_if_else.py | 1,095 | 4.1875 | 4 | #python2.7 -*- coding: utf-8 -*-
"""
- test for variable type and return string
- test sign of number
"""
import numpy as np
def var_type( var):
"""
:param var: some variable of unknown type
:return: type of variable
"""
if isinstance( var, float):
strOut = 'type float'
elif isinstance( var, int):
strOut = 'type float'
elif isinstance( var, np.ndarray):
strOut = 'array of length %i'%( len( var))
elif isinstance( var, list):
strOut = 'list of length %i'%( len( var))
else:
strOut = 'unknown type'
return strOut
print var_type( 3.4)
print var_type( [1,2,3,4,5])
print var_type( np.array([1,2,3,4,5]))
def var_sign( var):
"""
test sign of number
:param var: - some variable with unknow sign
:return:
"""
# in theory you can modify var_type to make sure var is not a list or array
if var > 0:
curr_sign = 'positive'
elif var < 0:
curr_sign = 'negative'
else:
curr_sign = 'var is equal 0'
return curr_sign
print var_sign( -1)
print var_sign( 2) | true |
530fb30fdefe861f085cdd53b9a1dff6a52aca27 | tansyDeveloper04-Arif/learner | /continue.py | 220 | 4.15625 | 4 | numer=0
denom=0
while denom!=-1:
print("Enter a numerator:")
numer=float (raw_input())
print("Enter a denominator:")
denom=float (raw_input())
if denom == 0:
continue
print(numer / denom)
| false |
1fdf47c9326ba34f9f07cb75bab30d7d7d5e8843 | FrankHaymes/intermediatePython | /interPython/Day1/testLiveTemplates.py | 1,617 | 4.6875 | 5 | import math
class Point:
"""
Represents a point in 2-D geometric space
"""
def __init__(self,x=0 , y =0):
"""
Initalizes the position of a new point.
If they are not specified, the points defaults to the origin
:param x: x coordinate
:param y: y coordinate
"""
self.x = x
self.y = y
def reset(self):
"""
Reset the point to the origin in 2D space
:return: Nothing
"""
self.move(0,0)
def move(self,x,y):
"""
Move the point to the new location in 2D space
:param x: x coordinate
:param y: y coordinate
:return:
"""
self.x = x
self.y = y
def calculate_distance(self, other_point):
"""
Calulate the distances from this point to a second point pass as a parameter
This function uses pythagorean Theorem to calculate
the distance between the two points
:param other_point: second point to calculate distance
:return: The distance between two point(float)
"""
return math.sqrt((self.x - other_point.x)**2 + (self.y - other_point.y)**2)
def main():
p1 = Point()
print(p1.x, p1.y)
p2 = Point(5,8)
print(p2.x, p2.y)
p2.reset()
print(p2.x, p2.y)
p2.move(9,10)
print(p2.x,p2.y)
p1 = Point(2,2)
p2 = Point(4,4)
print(p1.calculate_distance(p2))
# test tool (assert)
# program will exit if false
assert(p1.calculate_distance(p2) == p2.calculate_distance(p1))
if __name__ == '__main__':
main()
exit(0) | true |
084bf17d95fbf3728ebe97c66b50c2093f36a963 | bibbycodes/data_structures | /lib/partition_linked_list.py | 1,299 | 4.25 | 4 | # Write code to partition a linked list around a value x such that all nodes less than x come
# before all nodes greater than or equal to x.
# Important! The partition element x can appear anywhere in the right partition.
# It does not need to appeear between the left and right partitions.
# EG input 3 => 5 => 8 => 5 => 10 => 2 => 1 (partition = 5)
# Ou
import sys
import os
sys.path.append(os.path.abspath('../ds/py'))
from ds.linked_list import LinkedList
def partition_linked_list(ll, partition_value):
node = ll.head
right_side = None
previous = None
while node:
if node.value >= partition_value:
deleted_node = remove_node(node, previous, ll)
if right_side:
deleted_node.next_node = right_side
right_side = deleted_node
node = previous
previous = node
node = node.next_node
previous.next_node = right_side
def remove_node(node, previous, ll):
if previous:
previous.next_node = node.next_node
node.next_node = None
return node
else:
head = ll.head
ll.head = ll.head.next_node
previous = ll.head
return head
ll = LinkedList()
for val in [3,5,8,5,10,2,1]:
ll.insert(val)
partition_linked_list(ll, 8)
print(ll) | true |
93c57506fae6364254179e3720871f80002a052a | minghangkai/learningPython | /learn_thread.py | 2,737 | 4.3125 | 4 | import time, threading
# Python的标准库提供了两个模块:_thread和threading,_thread是低级模块,threading是高级模块,
# 对_thread进行了封装。绝大多数情况下,我们只需要使用threading这个高级模块。
#part1
"""
# 新线程执行的代码:
def loop():
print('thread %s is running...' % threading.current_thread().name)
n = 0
while n < 5:
n = n + 1
print('thread %s >>> %s' % (threading.current_thread().name, n))
time.sleep(1)
print('thread %s ended.' % threading.current_thread().name)
print('thread %s is running...' % threading.current_thread().name)
#建立新线程
t = threading.Thread(target=loop, name='LoopThread')
t.start()
t.join()
print('thread %s ended.' % threading.current_thread().name)
"""
#part2:线程共享全局变量而导致出错
"""
balance = 0
def change_it(n):
# 先存后取,结果应该为0:
global balance
balance = balance + n
balance = balance - n
def run_thread(n):
for i in range(100000):
change_it(n)
t1 = threading.Thread(target=run_thread, args=(5,))
t2 = threading.Thread(target=run_thread, args=(8,))
t1.start()
t2.start()
t1.join()
t2.join()
print(balance)
"""
"""
出错原因:函数中每执行一步,每个线程都会产生自己对应的临时变量,这样就会彼此覆盖,如:
初始值 balance = 0
t1: x1 = balance + 5 # x1 = 0 + 5 = 5
t2: x2 = balance + 8 # x2 = 0 + 8 = 8
t2: balance = x2 # balance = 8
t1: balance = x1 # balance = 5
t1: x1 = balance - 5 # x1 = 5 - 5 = 0
t1: balance = x1 # balance = 0
t2: x2 = balance - 8 # x2 = 0 - 8 = -8
t2: balance = x2 # balance = -8
结果 balance = -8
"""
# part3:ThreadLocal——解决了参数在一个线程中各个函数之间互相传递的问题。
# ThreadLocal最常用的地方就是为每个线程绑定一个数据库连接,HTTP请求,用户身份信息等,
# 这样一个线程的所有调用到的处理函数都可以非常方便地访问这些资源。
# 创建全局ThreadLocal对象:可以理解为全局变量local_school是一个dict,
# 不但可以用local_school.student,还可以绑定其他变量,如local_school.teacher等等
local_school = threading.local()
def process_student():
# 获取当前线程关联的student:
std = local_school.student
print('Hello, %s (in %s)' % (std, threading.current_thread().name))
def process_thread(name):
# 绑定ThreadLocal的student:
local_school.student = name
process_student()
t1 = threading.Thread(target= process_thread, args=('Alice',), name='Thread-A')
t2 = threading.Thread(target= process_thread, args=('Bob',), name='Thread-B')
t1.start()
t2.start()
t1.join()
t2.join() | false |
d124ff56af67058df4a3396f2190d8a1c7d5aa14 | Radu1990/Python-Exercises | /think python/src_samples_2/classes_and_objects.py | 585 | 4.375 | 4 | import math
class Point:
"""
Represents a point in 2D space:
"""
def point_creation(pos_x, pos_y):
name_pct = Point()
name_pct.x = pos_x
name_pct.y = pos_y
return name_pct
def print_point(p):
return 'point (%g, %g)' % (p.x, p.y)
def distance_between_two_points(p1, p2):
distance = math.sqrt((p2.x-p1.x)**2 + (p2.y-p1.y)**2)
return distance
p1 = point_creation(pos_x=3, pos_y=4)
p2 = point_creation(pos_x=15, pos_y=80)
print('Distance between %s and %s is %g' % (print_point(p1), print_point(p2), distance_between_two_points(p1, p2)))
| false |
112f15391af2cbe68f913e431ac9f3710c68759f | Radu1990/Python-Exercises | /think python/src_samples_2/rectangles.py | 1,885 | 4.46875 | 4 | import copy
class Point:
"""
Represents a point in 2D space:
attributes: x coordinate, y coordinate
"""
class Rectangle:
"""Represents a rectangle.
attributes: width, height, corner.
"""
# we instantiate an object named box
box = Rectangle()
box.width = 100.0
box.height = 200.0
box.corner = Point()
box.corner.x = 0.0
box.corner.y = 0.0
def find_center(rect):
p = Point()
p.x = rect.corner.x + rect.width/2
p.y = rect.corner.y + rect.height/2
return p
def print_point(p):
return 'point (%g, %g)' % (p.x, p.y)
def grow_rectangle(rect, dwidth, dheight):
rect.width += dwidth
rect.height += dheight
def print_current_size(rect):
return rect.width, rect.height
def move_rectangle(rect, dx, dy):
rect.corner.x += dx
rect.corner.y += dy
def move_rectangle_copy(rect, dx, dy):
"""This function creates a copy of the initial
rectangle and moves it into a new position
"""
new_rect = copy.deepcopy(rect)
new_rect.corner.x += dx
new_rect.corner.y += dy
return new_rect
current_size = (box.width, box.height)
center_rect = find_center(box)
print('Center of rectangle is', print_point(center_rect))
print('Current size', print_current_size(box))
grow_rectangle(box, 50, 200)
print('Current size', print_current_size(box))
print('Current position', print_point(box.corner))
move_rectangle(box, 5, 10)
print('Current position', print_point(box.corner))
#making a new rectangle in a different position than the initial one
box_2 = move_rectangle_copy(box, 100, 200)
print('New rectangle object position', print_point(box_2.corner))
# just checking if the 2 objects are the same (value should be false)
print(box_2 is box)
#print(box_2.corner.z)
print(type(box))
print(type(box_2))
print(type(box.corner))
print('Status instance box_2, rectangle',isinstance(box_2, Rectangle))
| true |
18d3b5071e7714650f64de934deab12498680a76 | Radu1990/Python-Exercises | /think python/src_samples_2/ex_7-2_eval.py | 322 | 4.21875 | 4 | # this program evaluates mathematical expressions
# until the user enters "done"
def eval_loop():
while True:
line = input('Enter input data to be evaluated here: \n>')
if line == 'done':
print('GAME OVER!')
break
result = eval(line)
print(result)
eval_loop()
| true |
8a2130e64defbd332e92b0a93d9f1ca042390e7f | SamuelSimoes31/pythonDrops | /Other types/String-functions.py | 1,380 | 4.3125 | 4 | print(", ".join(["spam", "eggs", "ham"]))
#prints "spam, eggs, ham"
print("|".join(["spam", "eggs", "ham"]))
#prints "spam|eggs|ham"
#=============================================
print("Hello ME".replace("ME", "world"))
#prints "Hello world"
print("Hello MEME ME ME".replace("ME", "world"))
#prints "Hello worldworld world world"
#=============================================
print("This is a sentence.".startswith("This"))
# prints "True"
print("This is a sentence.".endswith("sentence."))
# prints "True"
#=============================================
print("This is a sentence.".upper())
# prints "THIS IS A SENTENCE."
print("AN ALL CAPS SENTENCE".lower())
#prints "an all caps sentence"
#=============================================
print("spam, eggs, ham".split(", "))
#prints "['spam', 'eggs', 'ham']"
#=============================================
sent = "Hello have a nice day"
print(sent)
# Output: Hello have a nice day
sent1 = sent.split(" ")
print(sent1)
#Output: ['Hello', 'have', 'a', 'nice', 'day']
sent1[3] = "super"
sent2 = " ".join(sent1)
print(sent2.upper())
#Output: HELLO HAVE A SUPER DAY
sent3 = sent2.replace("day", "week")
print(sent3.lower())
#Output: hello have a super week
txt=[">","<"]
for i in range(1,10):
str="@"*i
print(str.join(txt))
# >@<
# >@@<
# >@@@<
# >@@@@<
# >@@@@@<
# >@@@@@@<
# >@@@@@@@<
# >@@@@@@@@<
# >@@@@@@@@@< | false |
3b95b38c03545e13db250ac95621e04cfe64d7d9 | AkanchhaChoudhary/Online-Training | /Python for Everybody Specialization-university of Michigan-coursera/1. Programming for everybody/week5/assignment.3.3.py | 697 | 4.65625 | 5 | 3.3 Write a program to prompt the user for a score using raw_input. Print out a letter grade based on the following table:
Score Grade
>= 0.9 A
>= 0.8 B
>= 0.7 C
>= 0.6 D
< 0.6 F
If the user enters a value out of range, print a suitable error message and exit. For the test, enter a score of 0.85.
"""
# output:
#B
try:
s = raw_input("please input your score:")
score = float(s)
if score > 1.0:
print "value out of range"
elif 1.0 >= score>=.9:
print "A"
elif .9 > score>=.8:
print "B"
elif .8 >score>=.7:
print "D"
elif .7 >score>=.6:
print "D"
except:
print "Error , please input is numeric" | true |
3bc0227e6c1b2b6fc385a2053de26558f5f3af81 | AkanchhaChoudhary/Online-Training | /Python for Everybody Specialization-university of Michigan-coursera/3. using python to access webdata/week2/week2 assignment.py | 464 | 4.21875 | 4 | In this assignment you will read through and parse a file with text and numbers.
You will extractall the numbers in the file and compute the sum of the numbers.
'''
import re
fname = raw_input('Enter File name :')
handle = open(fname)
sum=0
count = 0
for line in handle:
f = re.findall('[0-9]+',line)
for num in f:
if num >= [0]:
count = count + 1
sum = sum + int(num)
print 'There are',count,'values with a sum =',sum
| true |
b4a225f2b95494c51db8cbe92c07e9d95f40e00a | diamondstone/project-euler | /python/pe68.py | 2,293 | 4.125 | 4 | import pickle
from math import sqrt,factorial
# Functions for dealing with permutations
def baseftonum(basef): #computes the number with "base" factorial representation basef
num=0
l=len(basef)
for i in range(l): num+=factorial(l-i)*basef[i]
return num
def numtobasef(num,l): # computes the l-"digit" "base" factorial representation of num
# there's probably a real name for this
basef=[0]*l
for i in range(l):
basef[i]=num/factorial(l-i)
num-=basef[i]*factorial(l-i)
return basef
def baseftoperm(basef): # converts a base-factorial representation to the corresponding permutation
basef.append(0)
l=len(basef)
perm=[0]*l
for i in range(l):
while perm[i] in perm[:i]: perm[i] += 1
for j in range(basef[i]):
perm[i]+=1
while perm[i] in perm[:i]: perm[i] += 1
return perm
def permtobasef(perm): # converts a base-factorial representation to the corresponding permutation
l=len(perm)-1
basef=perm[:l]
for i in range(l):
for j in range(basef[i]):
if j in perm[:i]: basef[i] -= 1
return basef
def permtonum(perm): return baseftonum(permtobasef(perm))
def numtoperm(num,l): return baseftoperm(numtobasef(num,l-1))
def nextperm(perm):
l=len(perm)
num=permtonum(perm)+1
if num==factorial(l): return None
return numtoperm(num,l)
def solutionset(i): #takes a permutation of 0...9, maps it to a permutation of 1...10 by changing x to 10-x, and then maps it to the solution set it represents: [[0,9,1],[2,1,3],[4,3,5],[6,5,7],[8,7,9]]
perm=map(lambda x:10-x,numtoperm(i,10))
solution=[perm[0],perm[9],perm[1],perm[2],perm[1],perm[3],perm[4],perm[3],perm[5],perm[6],perm[5],perm[7],perm[8],perm[7],perm[9]]
mini=0
for i in range(3,15,3):
if solution[i]<solution[mini]: mini=i
solution=solution[mini:]+solution[:mini]
solution=int(reduce(lambda x,y:x+y,map(str,solution)))
return solution
candidates=[]
for i in xrange(362880):
perm=numtoperm(i,10)
if sum(perm[1:4])==sum(perm[3:6]) and sum(perm[1:4])==sum(perm[5:8]) and sum(perm[1:4])==sum(perm[7:10]) and sum(perm[2:4])==perm[9]+perm[0]: candidates.append(i)
solutions = map(solutionset,candidates)
solutions.sort()
print solutions
| true |
b774f027949c71d5cc13081c7f77365e07099113 | irvanariyanto/PythonBeginner | /Selection.py | 213 | 4.25 | 4 | num = int(raw_input("Please enter a number: "))
if (num > 0):
print "The number is more then zero"
elif (num < 0):
print "The number is less than zero"
else:
print "The number is zero"
print num
| true |
cfe70e9bdf1f7fcafb33476c64c8440cef7acb0c | borysrohulia/learning | /Python_Basic/week3/classes1.py | 1,059 | 4.25 | 4 | class Human:
pass
class Robot:
"""Данный класс позволяет создавать роботоа"""
print(Robot)
print(dir(Robot))
class Planet:
pass
planet = Planet()
print(planet)
solar_system = []
for i in range(8):
planet = Planet()
solar_system.append(planet)
print(solar_system)
solar_system2 = {}
for i in range(8):
planet = Planet()
solar_system2[planet] = True
print(solar_system2)
class True_Planet:
def __init__(self, name):
self.name = name
def __str__(self):
return self.name
def __repr__(self):
return f"Planet {self.name}"
earth = True_Planet("Earth")
print(earth)
normal_solar_system = []
planet_names = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]
for name in planet_names:
planet = True_Planet(name)
normal_solar_system.append(planet)
print(normal_solar_system)
mars = True_Planet("Mars")
mars.name = "second earth"
print(mars)
# del mars.name - удаляет атрибут класса | false |
8b40bc5357bf1a82e9a55e497392323a30a2c7a4 | lingshanng/my-python-programs | /Practicals DHS/Practical 4/q8_find_uppercase.py | 308 | 4.15625 | 4 | # Finding the number of uppercase letters in a string
def find_num_uppercase(str):
if len(str) == 0:
return 0
elif ord('A') <= ord(str[0]) <= ord('Z'):
return 1 + find_num_uppercase(str[1:])
else:
return 0 + find_num_uppercase(str[1:])
print(find_num_uppercase("Gddd"))
| true |
2f5dfa3a1eb0d27e5ac52ae07adb4fa27f611610 | Wcent/learn-python | /27_coroutine_demo.py | 1,477 | 4.15625 | 4 | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'cent'
'''
a demo about coroutine,
shows how to use yield and send to implement a producer-consumer model.
'''
# 生产者,接受生成器(generator)对象参数
def producer(c):
for i in range(10):
if i == 0:
print('[Producer]->: Get consumer ready!')
# 首先得启动generator,不能send non-None值
result = c.send(None)
else:
print('[Producer]->: producing %s' % i)
# 发送数据到generator,中止当前流程并切换转到generator执行,
# 等generator处理yield返回数据,从send接受后再继续执行
result = c.send(i)
print('[Producer]->: consumer return %s' % result)
print('[Producer]->: End producing!')
# 最后关闭generator
c.close()
# 消费者,定义为yield函数,可以返回generator对象,以支持协程(coroutine)
def consumer():
result = 'Start'
while True:
# 通过yield接受数据,处理,最后再通过yield返回数据
i = yield result
# 接受不到数据,直接返回,注意外层需要捕获generator StopIteration异常
if not i:
return
print('[Consumer]->: consuming %s' % i)
result = 'Done'
# todo some test
if __name__ == '__main__':
# 创建generator对象,通过coroutine实现生产者消费者模式
c = consumer()
producer(c) | false |
b98bb3a9c848ad21901861d4a107c782964ee8bf | Wcent/learn-python | /6_enum_demo.py | 959 | 4.1875 | 4 | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'cent'
'''
a demo about how to use enumeration
'''
from enum import Enum, unique
# define a custom enumeration by inheriting from base class Enum
# the decorator with key word @unique make sure to include no duplication member
# 继承方式定制枚举类型,@unique装饰器保证元素唯一性
@unique
class Week(Enum):
Sunday = 0
Monday = 1
Tuesday = 2
Wednesday = 3
Thursday = 4
Friday = 5
Saturday = 6
# define an enum object directly
# 直接定义枚举类型实例
month = Enum('Month', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec'))
# testing
if __name__ == '__main__':
print(Week.Saturday)
print(month.Jan)
print(month['Mar'])
print(month(12))
for day in Week.__members__.items():
print(day)
for name,member in month.__members__.items():
print(name, '==>', member.value) | true |
121b912707f77f50b115fa64e0f73249bcf8155d | ashokgaire/DSA | /Algorithms/Searching/binary_search.py | 2,111 | 4.125 | 4 | '''
Binary Search: Search a sorted array by repeatedly dividing the search interval in half.
Begin with an interval covering the whole array. If the value of the search key is less than the item in the middle of the interval,
narrow the interval to the lower half. Otherwise narrow it to the upper half.
Repeatedly check until the value is found or the interval is empty
Compare x with the middle element.
If x matches with middle element, we return the mid index.
Else If x is greater than the mid element, then x can only lie in right half subarray after the mid element. So we recur for right half.
Else (x is smaller) recur for the left half.
'''
## Returns index of x in arr if present, else -1
def binarySearch(arr, l, r, x):
# check base case
if r >= l:
mid = l + (r - l) // 2 # divide from half
if arr[mid] == x:
return mid
elif arr[mid] > x:
return binarySearch(arr,l, mid-1,x)
else:
return binarySearch(arr, mid +1 , r ,x)
else:
return -1
# Driver Code
arr = [3, 4, 1,8,10,17,99,76,7,53,35,77]
x = 17
# Function call
result = binarySearch(sorted(arr), 0, len(arr) - 1, x)
if result != -1:
print("Element is present at index % d" % result)
else:
print("Element is not present in array")
# Python3 code to implement iterative Binary
# Search.
# It returns location of x in given array arr
# if present, else returns -1
def binarySearch(arr, l, r, x):
while l <= r:
mid = l + (r - l) // 2;
# Check if x is present at mid
if arr[mid] == x:
return mid
# If x is greater, ignore left half
elif arr[mid] < x:
l = mid + 1
# If x is smaller, ignore right half
else:
r = mid - 1
# If we reach here, then the element
# was not present
return -1
# Driver Code
arr = [2, 3, 4, 10, 40]
x = 10
# Function call
result = binarySearch(arr, 0, len(arr) - 1, x)
if result != -1:
print("Element is present at index % d" % result)
else:
print("Element is not present in array")
| true |
e4f6595cada698ff74208db72cc1fbcd75819610 | jasonwenlee/Automate-the-Boring-Stuff | /Chapter 5 - Dictionaries and Structuring Data/dragonLoot.py | 1,768 | 4.3125 | 4 | # Practical project from Chapter 5, creating an inventory system to show a list of items in the user's possession.
# The code adds dropped items from monster into the user's inventory.
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'ruby', 'ruby', 'ruby', 'diamond', 'fangs']
stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
# Function counts the total amount of items in the user's inventory.
def displayInventory(inventory):
print('Inventory:')
item_total = 0
for k, v in inventory.items():
print(str(v)+ ' ' + k)
item_total = item_total + v
print('Total number of items: ' + str(item_total))
# Function adds drops from enemies into user's inventory.
def addToInventory(inventory, addedItems):
for i in range(len(addedItems)):
if addedItems[i] not in list(inventory.keys()):
inventory.setdefault(addedItems[i], 0)
inventory[addedItems[i]] = inventory[addedItems[i]] + 1
else:
inventory[addedItems[i]] = inventory[addedItems[i]] + 1
return(inventory)
# Shows inventory before dropped items are added into inventory.
print('Inventory BEFORE slaying monster:')
displayInventory(stuff)
print('')
# Calls addToInventory function to add dropped loot into user's inventory.
inv = addToInventory(stuff, dragonLoot)
# Show inventory after items are added.
print('Inventory AFTER slaying monster:')
displayInventory(inv)
# Comment:
# - Added a system that asks for user input to access the inventory. Code shown below.
##while True:
## inventory = (input().lower()).rstrip('?.,!@~#$%^&*()_+{}|:"<>?[]\;/') # Uppercase to lowercase.
## if inventory == 'inventory':
## displayInventory(inv)
## break
## else:
## break
| true |
d6219a0de11768540457944df83ce85d397247b9 | loveniuzi/Python- | /刷题100小组/43画长方形/画长方形.py | 477 | 4.15625 | 4 | ##【问题】打印图形用符号的组合在控制台输出不同大小的矩形图案。
##要求:写一个输出矩形的函数,该函数拥有三个默认参数,矩形的长5、宽5和组成图形的点的符号“*”,
##为函数添加不同的参数,输出三个不同类型的矩形
def draw_rect(symbol = '*', long = 5, width = 5):
for i in range(width):
for j in range(long):
print(symbol, end = "")
print()
draw_rect()
| false |
372ca9fb30286f0a133e17b7fdabdd7fb2de37ff | jhhemal/contactlist | /contactlist.py | 1,797 | 4.28125 | 4 | #!/usr/bin/env python3
#
# contactlist.py - A python program to store your contact data
#
# Author : Jahidul Hasan Hemal
#
# url: https://jhhemal.github.io
#
import json
print("ContactList.py".center(50,'*'))
filename = 'contacts.json'
while True:
print('Enter a name here (blank to quit) :')
uname = input()
if uname == '':
break
try:
with open(filename) as f:
contacts = json.load(f)
except FileNotFoundError:
print("You don't have the file contact.json, Let's create it first.")
print("The file will be creating with the name you have entered.")
print("DO you want to save it? (y/n) : ")
contacts = {}
while True:
dec = input().lower()
if dec == 'y' or dec == 'n':
break
print('You need to enter y or n from keyboard')
if dec == 'y':
print('What is his Full name : ')
f_name = input()
print('What is his mobile number : ')
m_number = input()
contacts[uname] = {'name' : f_name, 'number' : m_number}
with open(filename,'w') as f:
json.dump(contacts, f)
print('Your data has been added.')
else:
break
else:
if uname in contacts:
print("Name ".ljust(14) + ": ".ljust(2) + contacts[uname]['name'])
print("Mobile Number :".ljust(16) + contacts[uname]['number'])
else:
print(f"You don't have information about {uname} ")
print("DO you want to save it? (y/n) : ")
while True:
dec = input().lower()
if dec == 'y' or dec == 'n':
break
print('You need to enter y or n from keyboard')
if dec == 'y':
print('What is his Full name : ')
f_name = input()
print('What is his mobile number : ')
m_number = input()
contacts[uname] = {'name' : f_name, 'number' : m_number}
with open(filename,'w') as f:
json.dump(contacts, f)
print('Your data has been added.')
else:
break
| true |
e914b1e0ec83de5731b4d7ca9d34d39d22c3d1a8 | hguochen/algorithms | /python/data_structures/lists/ll_problems/insertsort.py | 1,724 | 4.5625 | 5 | # Write an insert_sort() function which given a list, rearranges its node so
# they are sorted in increasing order. It should use sorted_insert().
def insert_sort(head):
"""
Given a list, change it to be in sorted order (using sorted_insert()).
"""
# check head is not None
if head is None:
return
# trav the head check that the next node is bigger than prev node and node
# is not None
prev = None
trav = head
while trav is not None:
prev = trav
trav = trav.next
if trav is None:
break
elif prev.data > trav.data:
# when current node is smaller than prev node, remove the node and
# call sorted_insert starting from head of node
node = trav
prev.next = trav.next
node.next = None
sorted_insert(head, node)
return head
def insert_sort2(head):
"""
Start with an empty result list and fill in the result with current nodes
starting at head ref.
"""
if head is None:
return
result = None
trav = head
while trav is not None:
sorted_insert(result, trav)
trav = trav.next
return result
def sorted_insert(head, node):
"""
Given a linked list that is sorted in increasing order, put the node with
data value in its sorted position in the linked list.
"""
if head is None:
head = node
return
prev = None
trav = head
while node.data < trav.data and trav is not None:
prev = trav
trav = trav.next
if prev is None:
node.next = head
head = node
else:
prev.next = node
node.next = trav
return
| true |
8926a9528a9af9be3e390dc5d5bb44bd4413ea75 | hguochen/algorithms | /python/cci/linked_list/2_3_delete_middle_node.py | 1,145 | 4.21875 | 4 | from linked_list import *
# Implement an algorithm to delete a node in the middle of a single linked
# list, given only access to that node.
# Example:
# input the node c from the linked list: a ->b ->c ->d ->e
# result: nothing is returned. but the new lnked list looks like a->b->d->e
def delete_middle_node(ll_obj):
"""
Delete the middle node.
"""
node = generate_mid_pointer(ll_obj)
while node.next.next is not None:
node.data = node.next.data
node = node.next
node.data = node.next.data
node.next = None
return ll_obj
def generate_mid_pointer(ll_obj):
"""
Return a mid pointer to the linked list.
"""
head = ll_obj.get_head()
size = 0
while head is not None:
size += 1
head = head.next
print size
head = ll_obj.get_head()
for i in range(size/2):
head = head.next
return head
if __name__ == "__main__":
test = LinkedList(1)
test.insert(2)
test.insert(3)
test.insert(4)
test.insert(5)
test.insert(6)
test.insert(7)
test.print_list()
print ""
delete_middle_node(test).print_list()
| true |
93b199dea75edc1e8cbfbdfda8e1b3d262f6c3e0 | hguochen/algorithms | /python/leap_year.py | 463 | 4.34375 | 4 | ##################################
### Title: Leap Year ########
### Author: GuoChen Hou ########
##################################
# Calculates if a year is a leap year.
def isLeapYear(year):
if year%400 == 0:
return True
elif year%4 == 0 and year%100 != 0:
return True
else:
return False
year = int(raw_input('Enter a year to test for leap year: '))
if isLeapYear(year):
print "%d is leap year." % year
else:
print "%d is not leap year." % year | false |
54d8b37c5c7baa7cbdefe5c423e866080ec3259d | hguochen/algorithms | /python/oop/roulette/game.py | 1,101 | 4.15625 | 4 | import unittest
class Game(object):
"""
Game manages the sequence of actions that defines the game of Roulette.
This includes notifying the Player to place bets, spinning the Wheel and
resolving the Bet actually present on the Table.
"""
def __init__(self, wheel, table):
"""
This is the Strategy design pattern. Each of these collaborating
objects is a replaceable strategy, and can be changed by the client
that uses this game.
param wheel: the Wheel which produces random events
param table: the Table which holds bets to be resolved.
"""
super(Game, self).__init__()
self.wheel = wheel
self.table = table
def cycle(self, player):
"""
Executes a single cycle play with the given player. It will call
Player.place_bets() method to get bets. It will call the Wheel's
next() method to get the next winning Bin.
"""
pass
class GameTestCase(unittest.TestCase):
def setUp(self):
pass
def test_cycle(self):
pass
| true |
e857436cebd3cc98c23ef0af8be7d70dcd13cc31 | hguochen/algorithms | /python/careercup/data_structures/reverse_cstring.py | 318 | 4.375 | 4 | def reverse_string(a_string):
"""
Takes in a string and return the reverse of the string.
"""
return a_string[::-1]
if __name__ == "__main__":
test_string = "abcd\0"
print test_string
print len(test_string)
print reverse_string(test_string)
print len(reverse_string(test_string))
| true |
e24e6f28e09cd13f9cd43dd75a49cee936ebb548 | hguochen/algorithms | /python/sort/quicksort/quicksort_2.py | 1,295 | 4.25 | 4 | # quicksort
def quicksort(array):
"""
Quicksort selects a pivot element and splits the remaining n-1 items into
two sublists. Left sublist contains all elements appearing before the pivot
and the right sublist contains all elements appear after pivot in sorted
order. Then we merge the left and right sublist by placing pivot element in
between them.
"""
return _quicksort(array, 0, len(array))
def _quicksort(array, low, high):
if low < high:
pivot = partition(array, low, high)
_quicksort(array, low, pivot)
_quicksort(array, pivot+1, high)
return array
def partition(array, low, high):
# set pivot to last element
pivot = high-1
# set ending position where pivot element is in sorted array
first_high = low
# iterate through array until before last element
for i in xrange(low, high):
# if current element less than pivot, swap and increment first_high
# index
if array[i] < array[pivot]:
array[i], array[first_high] = array[first_high], array[i]
first_high += 1
# swap pivot element with first high index element
array[pivot], array[first_high] = array[first_high], array[pivot]
# return the pivot index position
return first_high
| true |
ac2ecd60f951eea5b91f180f662050b14d1d140e | hguochen/algorithms | /python/oop/roulette/outcome.py | 2,376 | 4.25 | 4 | import unittest
class Outcome(object):
"""
Outcome contains a single outcome on which a bet can be placed.
In roulette, each spin of the wheel has a number of outcomes with bets that
will be paid off.
For example, the "1" bin has the following winning Outcomes: "1", "Red",
"Odd", "Low", "Column 1", "Dozen 1-12", "Split 1-2", "Split 1-4",
"Street 1-2-3", "Corner 1-2-4-5", "Five Bet", "Line 1-2-3-4-5-6",
"00-0-1-2-3", "Dozen 1", "Low" and "Column 1". All of these bets will
payoff if the wheel spins a "1".
"""
def __init__(self, name, odds):
super(Outcome, self).__init__()
self.name = name
self.odds = odds
def win_amount(self, amount):
"""
Multiple this Outcome's odd by the given amount. The product is
returned.
param amount: amount being bet.
"""
if not isinstance(amount, int):
return
return self.odds * amount
def __eq__(self, other):
"""
Compare the name attributes of self and other.
param other: another Outcome instance to compare against.
returns: True if this name matches the other name.
"""
if self.name == other.name:
return True
return False
def __ne__(self, other):
"""
Compare the name attributes of self and other.
param other: another Outcome instance to compare against.
returns: True if this name does not match the other name.
"""
if self.name != other.name:
return True
return False
def __str__(self):
"""
Easy to read representation of this Outcome.
returns: String of the form name (odds: 1)
"""
return "%s (%d:1)" % (self.name, self.odds)
class OutcomeTestCase(unittest.TestCase):
"""
Test cases for Outcome class.
"""
def setUp(self):
self.a = Outcome('even', 2)
self.b = Outcome('odd', 2)
self.c = Outcome('even', 2)
def test_two_instances_are_equal(self):
self.assertEqual(self.a == self.c, True)
def test_two_instances_are_not_equal(self):
self.assertEqual(self.a != self.b, True)
def test_corect_win_amount(self):
self.assertEqual(self.a.win_amount(10), 20)
if __name__ == "__main__":
unittest.main()
| true |
8fb9841e054f76ed9269a885a759f0e578bf65b6 | hguochen/algorithms | /python/cci/stack_queues/3_6_sort_stack.py | 1,095 | 4.4375 | 4 | # Write a program to sort a stack in ascending order. You should not make any
# assumptions about how the stack is implemented. The following are the only
# functions that should be used to write this program:
# push | pop | peek | is_empty
# ascending means smallest value at bottom of stack
# considering we use python list as a stack, the operations converted are:
# push: stack.append()
# pop: stack.pop()
# peek: stack[-1]
# is_empty: len(stack) < 1
def sort_stack(stack):
if len(stack) < 1:
return stack
result = []
while len(stack) > 0:
if len(result) < 1:
result.append(stack.pop())
continue
value = stack.pop()
pop_count = 0
while len(result) > 0:
if value < result[-1]:
stack.append(result.pop())
pop_count += 1
else:
break
result.append(value)
for i in range(pop_count):
result.append(stack.pop())
return result
if __name__ == "__main__":
stack = [5, 3, 6, 2, 12, 4]
print sort_stack(stack)
| true |
9b0ec8b0123f758441aa60a40a32b9f3d96346c3 | hguochen/algorithms | /python/last_nth_element.py | 914 | 4.15625 | 4 | ##################################
### Title: Last Nth element ######
### Author: GuoChen Hou ########
##################################
# Implement an algorithm to find the nth to last element of a
# singly linked list.
from ADT.LinkedList import LinkedList
class NthLinkedList(LinkedList):
def nth_to_last(self, position):
if self.size is 0:
return
# get the node position counting from head
node_position = self.size - position - 1 # offset since node starts at 1 instead of 0
trav = self.head
while trav is not None and node_position is not 0:
trav = trav.next
node_position -= 1
return trav.data
if __name__ == "__main__":
test_list = NthLinkedList()
test_list.insert(1)
test_list.insert(2)
test_list.insert(3)
test_list.insert(4)
test_list.print_list()
print test_list.nth_to_last(2)
| true |
009cf3641ac5aa9a0d47073e44dbe310eb1fbc89 | hguochen/algorithms | /python/Matrix.py | 2,891 | 4.1875 | 4 | ##################################
### Title: Matrix ########
### Author: GuoChen Hou ########
##################################
# Given a square matrix, output the final state of the matrix after performing the given operations.
# There are 3 valid operations:
# 1. Rotate r: Rotate the matrix clockwise by r degree (r can be 90, 180, or 270).
# 2. Reflect x: Reflect the matrix across the x-axis.
# 3. Reflect y: Reflect the matrix across the y-axis.
# The first line of the input contains an integer N (1 <= N <= 100). The subsequent N lines contain the
# values of the N x N elements. The following line is an integer K (1 <= K <= 100), where K is the
# number of operations to be performed. The next line is the query with format "Rotate r", (r = {90,
# 180, 270}), "Reflect x" or "Reflect y".
import copy
class Matrix:
"""
Matrix class instantiates a 2-dimensional matrix and performs adjustment operations on the
matrix.
"""
def __init__(self, new_size):
self.size = new_size
self.matrix = [[None for i in range(self.size)] for j in range(self.size)]
def __rotate(self, degree):
"Rotate the matrix by degree"
while degree != 0:
temp = copy.deepcopy(self.matrix)
for row in range(self.size):
for col in range(self.size):
self.matrix[row][col] = temp[self.lastIndex(temp) - col][row]
degree -= 90
return self.matrix
def __reflectX(self):
"Reflect the matrix around x-axis"
temp = copy.deepcopy(self.matrix)
for row in range(self.size):
for col in range(self.size):
self.matrix[row][col] = temp[self.lastIndex(temp) - row][col]
return self.matrix
def __reflectY(self):
"Reflect the matrix around y-axis"
temp = copy.deepcopy(self.matrix)
for row in range(self.size):
for col in range(self.size):
self.matrix[row][col] = temp[row][self.lastIndex(temp)-col]
return self.matrix
def operate(self, operation, pivot):
"Perform operation on the matrix with type specification"
if operation == "rotate":
pivot = int(pivot)
self.__rotate(pivot)
elif operation == "reflect":
if pivot == "x": # reflect ard x-axis
self.__reflectX()
elif pivot == "y": # reflect ard y-axis
self.__reflectY()
return self.matrix
def toString(self):
"Convert the matrix into string"
output = ""
for i in range(self.size):
for j in range(self.size):
if j < 0:
output += " "
output += self.matrix[i][j]
output += " "
output += "\n"
return output
def lastIndex(self, list_2d):
"Returns the last index of a list"
return len(list_2d) - 1
size = int(raw_input())
matrix = Matrix(size)
for index in range(size):
matrix.matrix[index] = raw_input().split(' ')
operations = int(raw_input())
for index in range(operations):
operation, pivot = raw_input().split()
try:
int(pivot)
except ValueError:
pass
matrix.operate(operation, pivot)
print matrix.toString() | true |
0c99d783667a2780acc28990294255f8680eec9b | hguochen/algorithms | /python/estimate_pi.py | 1,551 | 4.28125 | 4 | ##################################
### Title: Estimate pi ########
### Author: GuoChen Hou ########
##################################
# This program estimates the pi value given at least 3 non-negative integers using applications of
# certain theorems in number theory.
# Professor Robert A.J. Matthews of the Applied Mathematics and Computer Science Department at
# the University of Aston in Birmingham, England, has recently described how the positions of
# stars across the night sky may be used to deduce a surprisingly accurate value of p.
# Algorithm:
# 1. Take in a list of integers
# 2. Compute a list of list of integers
# 3. Find the pairs with no common factor other than 1
# 4. Compute value of pi with the equation 6/pow(p,2) = ratio
# 5. Print p
from fractions import gcd
from math import sqrt
def compute_pairs_list(input_list):
"""
Takes in a list of integers and return a paired list of every unique pair of integers
"""
pair = []
pairs_list = []
while input_list:
sub_input_list = input_list[1:]
for index in range(len(sub_input_list)):
pair.append(input_list[0])
pair.append(sub_input_list[index])
pairs_list.append(pair)
pair = []
input_list.pop(0)
return pairs_list
input_list = []
input_list = list(raw_input().split())
for index in range(len(input_list)):
input_list[index] = int(input_list[index])
pairs_list = compute_pairs_list(input_list)
counter = 0
for pair in pairs_list:
if gcd(pair[0], pair[1]) == 1:
counter += 1
ratio = counter / float(len(pairs_list))
p = sqrt(6 / ratio)
print '%.4f' % p | true |
930724408ac5735e5ad1dd9593acaeb700de0745 | hguochen/algorithms | /python/random_questions/sum_to_ten.py | 1,343 | 4.28125 | 4 | # Given an array, write a function to return true if the sum of any two numbers
# in the array is zero.
# O(n^2)
def sum_to_ten(a_list):
"""
Takes in a list of integer arrays and return true if any two numbers sum to
zero. false otherwise.
"""
# check list is not empty
if len(a_list) < 1:
return False
is_sum_zero = False
# initialize a list
data_sets = []
# iterate through the list
for item in a_list:
if -item not in data_sets:
data_sets.append(item)
else:
is_sum_zero = True
return is_sum_zero
# for each item, check if the inverse value is in list
# return true if found, else continue
# return false
# O(n)
def sum_to_ten_v2(a_list):
"""
Takes in a list of integer arrays and return true if any two numbers sum to
zero. false otherwise.
"""
if len(a_list) < 1:
return False
is_sum_zero = False
data_sets = {}
for item in a_list:
if -item not in data_sets.keys():
data_sets[item] = None
else:
is_sum_zero = True
return is_sum_zero
if __name__ == "__main__":
test = [1, 3, 5, 7, -3]
print sum_to_ten(test)
print sum_to_ten_v2(test)
test_2 = [1, 3, 4, 6, -13]
print sum_to_ten(test_2)
print sum_to_ten_v2(test_2)
| true |
92e3952c10cf0be9a9bb93e2bc89f0d26ca16dbe | hguochen/algorithms | /python/fahrenheit_to_celsius.py | 357 | 4.125 | 4 | ##################################
### Title: Fahrenheit to celsius #
### Author: GuoChen Hou ########
##################################
# Converts temperature in Fahrenheit to Celsius
fahrenheit = float(raw_input('Enter temperature in Fahrenheit: '))
celsius = (fahrenheit - 32) / 1.8
print '%.3f fahrenheit equates to %.3f celsius' % (fahrenheit, celsius) | false |
7be36e2101d8de095d1daf12e25dec8552a8ac97 | hguochen/algorithms | /python/random_questions/candles.py | 836 | 4.25 | 4 | ##################################
### Title: Candle Residue ########
### Author: GuoChen Hou ########
##################################
# Alexandra has n candles. He burns them one at a time and carefully collects all unburnt
# residual wax. Out of the residual wax of exactly k (where k > 1) candles, he can roll out
# a new candle.
# Write a program to help Alexandra find out how many candles he can burn in total,
# given two positive integers n and k.
# The output should print the total number of candles he can burn.
# eg. n = 5, k = 3
# Total candles burnt = 7
n,k = raw_input('Enter number of candles and number of residuals to make a new candle: ').split()
n = int(n)
k = int(k)
counter = 0
while n/k != 0:
sets = n / k
counter += k * sets
n = n - (k * sets) + sets
counter += n
print 'Total candles burnt =', counter | true |
18df5b1dac130b6c6edaaf3c6b7c096642619100 | hguochen/algorithms | /python/careercup/data_structures/is_anagram.py | 1,568 | 4.1875 | 4 | ##############################################################################
# Author: GuoChen
# Title: Unique Character search
# Write a method to decide if two strings are anagrams or not.
##############################################################################
# Assumptions and constraints:
# 1. Character can be any ASCII code character.
# 2. Length of string is at most 100 chars.
# 3. Should return True if 2 strings are anagrams, else False
# 4. Spaces does not count
def is_anagram(string_1, string_2):
"""
Takes a strings and test if they are anagrams of each other.
@return: True if they are anagrams, else False.
"""
if len(string_1) is 0 or len(string_2) is 0:
print "One of the string is empty."
return False
# remove whitespaces and spaces in between
string_1 = string_1.strip(" "). replace(" ", "")
string_2 = string_2.strip(" "). replace(" ", "")
charset = {}
print string_1
print string_2
for char in string_1:
if ord(char) in charset:
charset[ord(char)] += 1
else:
charset[ord(char)] = 1
print charset
for char in string_2:
if ord(char) not in charset or charset[ord(char)] is 0:
return False
else:
charset[ord(char)] -= 1
for key, value in charset.items():
if value is not 0:
return False
return True
if __name__ == "__main__":
test_string1 = " a rmy"
test_string2 = "ma ry "
print is_anagram(test_string1, test_string2)
| true |
e6960ce1ad34a9e840daa4994aa273fb4d740501 | hguochen/algorithms | /python/sort/insertion_sort/insertion_sort_5.py | 483 | 4.34375 | 4 | # insertion sort
def insertion_sort(array):
"""
Divid the array in sorted and unsorted sublist. For each item in unsorted
sublist, compare with sorted sublist elements from right to left and swap
if unsorted element is smaller then compare with next sorted element.
"""
for i in xrange(1, len(array)):
j = i
while j > 0 and array[j] < array[j-1]:
array[j], array[j-1] = array[j-1], array[j]
j -= 1
return array
| true |
7cf037a55ad7ddd6a6192e177a463442cce69dd7 | hguochen/algorithms | /python/sort/mergesort/mergesort_6.py | 1,206 | 4.21875 | 4 | # mergesort
def mergesort(array):
"""
Divides the array into 2 almost equal size sublists and recursively sort 2
sublists with mergesort. Then merge both sublists to produce the sorted
result.
"""
# check size of array less than 2
if len(array) <= 1:
return array
# compute mid index and split to left, right sublists
mid = len(array) // 2
# recursively sort both sublists
left = mergesort(array[:mid])
right = mergesort(array[mid:])
# merge both sorted sublists and return result
return merge(left, right)
def merge(left, right):
# init result
result = []
# init left right index
i, j = 0, 0
# while neither sublist is exhausted, repeatedly compare left, right
# elements and put smaller elements in result
while i < len(left) and j < len(right):
if left[i] < right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
# when either list is exhausted, add the other remaining list to result
if left:
result.extend(left[i:])
if right:
result.extend(right[j:])
# return result
return result
| true |
e073fbf3ae4090644966ba206ab5b2dd80f17c98 | hguochen/algorithms | /python/sort/selection_sort/selection_sort_3.py | 722 | 4.21875 | 4 | # selection sort
def selection_sort(array):
"""
Divides the list into 2 parts, sorted and unsorted. Left sublist contains
list of sorted elements, right sublist contains list of unsorted elements.
Find the least element and place it in sorted part of list.
"""
# traverse the array
for i in xrange(len(array)):
# initialize min index
min_index = i
# traverse the unsorted part of list and update min index
for j in xrange(i+1, len(array)):
if array[j] < array[min_index]:
min_index = j
# swap min index value with current value
array[i], array[min_index] = array[min_index], array[i]
# return array
return array
| true |
6f76aadb3f2c3292fc697e8b8eef8bda15340311 | hguochen/algorithms | /python/cci/arrays_strings/1_2_reverse_c_style_string.py | 352 | 4.46875 | 4 | # Write code to reverse a c style string. (C-string means that "abcd" is
# represented as five characters, including the null character.)
def reverse_string(c_string):
if c_string == "":
return None
reverse = c_string[:-1]
return reverse[::-1] + '\0'
if __name__ == "__main__":
test = "abc\0"
print reverse_string(test)
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.