blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
af771a30f93a4382dacfb04e423ad01dd96b3160 | zaincbs/PYTECH | /filter_long_words_using_filter.py | 561 | 4.25 | 4 | #!/usr/bin/env python
"""
Using the higher order function filter(), define a function
filter_long_words() that takes a list of words and an
integer n and returns the list of words that are longer
than n.
"""
def filter_long_words(l,n):
return filter(lambda word: len(word) > n, l)
def main():
list_with_len_of_word =filter_long_words(['happy','God','Abdul', 'Samad', 'needs', 'a', 'job'],3)
print list_with_len_of_word
if __name__ == "__main__":
main()
"""
H$ ./filter_long_words_using_filter.py
['happy', 'Abdul', 'Samad', 'needs']
"""
| true |
528bb5e90b48a7b741e96c7df0ffe0905534df39 | zaincbs/PYTECH | /readlines.py | 1,420 | 4.125 | 4 | #!/usr/bin/env python
"""
I am making a function that prints file in reverse order and then reverses
the order of the words
"""
import sys
def readFile(filename):
rorder = ''
opposed = ''
finale= ''
inline = ''
#reading file line by line
#with open(filename) as f:
# lines = f.readlines()
#print lines
f = open(filename,'r')
lines = f.readlines()
print lines
print('')
print ('1')
for i in range(0,1,len(f.readlines())-1):
inline = inline + lines[i]
print inline
print ('')
print ('2')
#printing file in reverse order
for rev in range(len(lines)-1,-1,-1):
rorder = rorder + lines[rev]
print rorder
#print '.'.join(reversed(rorder.split('.')))
print ('3')
#printing words in reverse order
for words_rorder in range(len(rorder)-1,-1,-1):
finale = finale + rorder[words_rorder]
print finale
print ('4')
print('')
print finale.rstrip()
def main():
argList= sys.argv
filename_to_be_read = argList[1]
v = readFile(filename_to_be_read)
# print v
if __name__ == "__main__":
main()
"""
$ cat abc.txt
abc zed
I am funny
stop teasing me, please
Where am I?
Who am I
?
blah blah blah
$ ./readlines.py abc.txt
dez cba
ynnuf ma I
esaelp ,em gnisaet pots
?I ma erehW
I ma ohW
?
halb halb halb
"""
| true |
597368b52b65f2cf0b6a61a78ec076f6ff925432 | AlanFermat/leetcode | /linkedList/707 designList.py | 2,691 | 4.53125 | 5 | """
Design your implementation of the linked list. You can choose to use the singly linked list or the doubly linked list. A node in a singly linked list should have two attributes: val and next. val is the value of the current node, and next is a pointer/reference to the next node. If you want to use the doubly linked list, you will need one more attribute prev to indicate the previous node in the linked list. Assume all nodes in the linked list are 0-indexed.
Implement these functions in your linked list class:
get(index) : Get the value of the index-th node in the linked list. If the index is invalid, return -1.
addAtHead(val) : Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list.
addAtTail(val) : Append a node of value val to the last element of the linked list.
addAtIndex(index, val) : Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted.
deleteAtIndex(index) : Delete the index-th node in the linked list, if the index is valid.
"""
from ListNode import *
class MyLinkedList(object):
"""docstring for myLinkedList"""
def __init__(self):
self.size = 0
self.head = None
def get(self, index):
if index >= self.size:
return -1
temp = self.head
while index:
temp = temp.next
index -= 1
return temp.val
def addAtHead(self, val):
new = ListNode(val)
new.next = self.head
self.head = new
self.size += 1
def addAtTail(self, val):
temp = self.head
while temp.next:
temp = temp.next
temp.next = ListNode(val)
self.size += 1
def addAtIndex(self, index, val):
count = 0
temp = self.head
if self.size >= index:
if index == 0:
self.addAtHead(val)
elif index == self.size:
self.addAtTail(val)
# locate that position
else:
while count < index-1:
temp = temp.next
count += 1
# swap the value
new = ListNode(val)
new.next = temp.next
temp.next = new
self.size += 1
def deleteAtIndex(self, index):
temp = self.head
if index == 0:
self.head = self.head.next
self.size -= 1
else:
if self.size > index:
while index-1:
temp = temp.next
index -= 1
if temp.next:
temp.next = temp.next.next
self.size -= 1
g = MyLinkedList()
g.addAtHead(0)
g.addAtIndex(1,9)
g.addAtIndex(1,5)
g.addAtTail(7)
g.addAtHead(1)
g.addAtIndex(5,8)
show(g.head)
g.addAtIndex(5,2)
g.addAtIndex(3,0)
g.addAtTail(1)
g.addAtTail(0)
show(g.head)
g.deleteAtIndex(6)
show(g.head)
| true |
8f967f1220a5b1dbf211c5360d99c479fb522383 | tskillian/Programming-Challenges | /N-divisible digits.py | 939 | 4.21875 | 4 | #Write a program that takes two integers, N and M,
#and find the largest integer composed of N-digits
#that is evenly divisible by M. N will always be 1
#or greater, with M being 2 or greater. Note that
#some combinations of N and M will not have a solution.
#Example: if you are given an N of 3 and M of 2, the
#largest integer with 3-digits is 999, but the
#largest 3-digit number that is evenly divisible by
#2 is 998, since 998 Modulo 2 is 0. Another example
#is where N is 2 and M is 101. Since the largest
#2-digit integer is 99, and no integers between 1
#and 99 are divisible by 101, there is no solution.
digits_factor = raw_input("Enter digits and factor: ")
[digits, factor] = digits_factor.split()
minimum = 1
while len(str(minimum)) < int(digits):
minimum *= 10
answer = (minimum * 10) - 1
while answer >= minimum:
if answer % int(factor) == 0:
print answer
break
answer -= 1
| true |
ea96f8e8e0c7a7e1bde8a01c47098036d10799f2 | usmanmalik6364/PythonTextAnalysisFundamentals | /ReadWriteTextFiles.py | 1,111 | 4.5 | 4 | # python has a built in function called open which can be used to open files.
myfile = open('test.txt')
content = myfile.read() # this function will read the file.
# resets the cursor back to beginning of text file so we can read it again.
myfile.seek(0)
print(content)
content = myfile.readlines()
myfile.seek(0)
for line in content:
print(line)
myfile.close() # always close the file after you've read.
# w+ is the mode which allows us to read and write.
# w and w+ should be used with caution as it overwrites the underlying file completely.
myfile = open('test.txt', 'w+')
myfile.write("The new Text")
content = myfile.read()
print(content)
myfile.close()
# APPEND TO A FILE
# a+ allows us to append to a file and if file does not exists, a+ will create a new file.
myfile = open('test.txt', 'a+')
myfile.write('MY FIRST LINE IS A+ OPENING')
myfile.close()
myfile = open('test.txt')
content = myfile.read()
print(content)
myfile.close()
# with is a context manager which automatically closes the file for us.
with open('test.txt', 'r') as mynewfile:
myvariable = mynewfile.readlines()
| true |
ce51c27893b378bd6abb314ad4926e17637c6228 | SmischenkoB/campus_2018_python | /Dmytro_Shalimov/1/9.py | 2,110 | 4.3125 | 4 | <<<<<<< HEAD
print("Convert a 24-hour time to a 12-hour time.")
print("Time must be validated.")
user_input = input("Enter time: ")
formatted_time = str()
if len(user_input) != 5:
print("not valid time")
hours = user_input[:2]
minutes = user_input[3:]
if hours.isnumeric() and minutes.isnumeric():
hours_in_int = int(hours)
minutes_in_int = int(minutes)
if (hours_in_int < 0 or hours_in_int > 23) or (minutes_in_int < 0 or minutes_in_int > 59):
print("not valid time")
else:
if hours_in_int > 12:
formatted_time = '{:02d}:{:02d} pm'.format(hours_in_int - 12, minutes_in_int)
elif hours_in_int == 12:
formatted_time = '12:{:02d} pm'.format(minutes_in_int)
elif hours_in_int == 0:
formatted_time = '12:{:02d} am'.format(minutes_in_int)
else:
formatted_time = '{:02d}:{:02d} am'.format(hours_in_int, minutes_in_int)
print(formatted_time)
else:
print("not valid time")
=======
print("Convert a 24-hour time to a 12-hour time.")
print("Time must be validated.")
user_input = input("Enter time: ")
formatted_time = str()
if len(user_input) != 5:
print("not valid time")
hours = user_input[:2]
minutes = user_input[3:]
if hours.isnumeric() and minutes.isnumeric():
hours_in_int = int(hours)
minutes_in_int = int(minutes)
if (hours_in_int < 0 or hours_in_int > 23) or (minutes_in_int < 0 or minutes_in_int > 59):
print("not valid time")
else:
if hours_in_int > 12:
formatted_time = '{:02d}:{:02d} pm'.format(hours_in_int - 12, minutes_in_int)
elif hours_in_int == 12:
formatted_time = '12:{:02d} pm'.format(minutes_in_int)
elif hours_in_int == 0:
formatted_time = '12:{:02d} am'.format(minutes_in_int)
else:
formatted_time = '{:02d}:{:02d} am'.format(hours_in_int, minutes_in_int)
print(formatted_time)
else:
print("not valid time")
>>>>>>> 715fd0763b415a13fb28a483f258a5eadc1ec931
| true |
425c4137611ae13aee9d24a486040bc9e565edd8 | SmischenkoB/campus_2018_python | /Dmytro_Skorobohatskyi/batch_3/verify_brackets.py | 1,004 | 4.3125 | 4 | def verify_brackets(string):
""" Function verify closing of brackets, parentheses, braces.
Args:
string(str): a string containing brackets [], braces {},
parentheses (), or any combination thereof
Returns:
bool: Return True if all brackets are closed, otherwise - False.
"""
opening = ['(', '{', '[']
closing = [')', '}', ']']
corresponding = dict(zip(closing, opening))
is_brackets_closed = True
stack = []
for i, el in enumerate(string):
if el in opening:
stack.append(el)
elif el in closing:
if (len(stack)):
last_element = stack.pop()
if last_element != corresponding[el]:
is_brackets_closed = False
break
else:
is_brackets_closed = False
break
if len(stack):
is_brackets_closed = False
return is_brackets_closed
| true |
92cbac43042872e865e36942ce164e1d5fdb0d40 | SmischenkoB/campus_2018_python | /Kyrylo_Yeremenko/2/task7.py | 2,517 | 4.21875 | 4 | """
This script solves task 2.7 from Coding Campus 2018 Python course
(Run length encoding)
"""
def write_char_to_list(last_character, character_count):
"""
Convenience function to form character and count pairs for RLE encode
:param last_character: Character occurred on previous iteration
:param character_count: Count of mentioned character
:return: List to append to encode return string
"""
return_list = []
if character_count > 1:
return_list += [str(character_count), last_character]
else:
return_list += last_character
return return_list
def rle_encode(string):
"""
Encodes string using Run-Length encoding
:param string: Input raw string
:return: RLE-encoded string
"""
list_string = list(string)
last_character = None
character_count = 0
return_list = []
for index in range(len(list_string)):
character = list_string[index]
if last_character != character:
if last_character is not None:
return_list += write_char_to_list(last_character, character_count)
last_character = character
character_count = 1
else:
character_count += 1
if index == (len(list_string) - 1):
return_list += write_char_to_list(last_character, character_count)
return ''.join(return_list)
def rle_decode(string):
"""
Decodes string using Run-Length encoding
:param string: Input encoded string
:return: Raw decoded string
"""
list_string = list(string)
last_character = None
is_last_character_number = False
character_count = 0
return_list = []
number_buffer = []
for character in list_string:
if not character.isdigit() and is_last_character_number:
count = int(''.join(number_buffer))
return_list += [character for i in range(count)]
number_buffer.clear()
is_last_character_number = False
if character.isdigit():
number_buffer.append(character)
is_last_character_number = True
else:
return_list += character
return ''.join(return_list)
print("WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWB")
print(rle_encode("WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWB"))
print(rle_decode("WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWB"))
| true |
c955386992b1cf118dd6b8c1ffb792c98a12012e | SmischenkoB/campus_2018_python | /Dmytro_Shalimov/1/8.py | 1,062 | 4.125 | 4 | <<<<<<< HEAD
print("Validate a 24 hours time string.")
user_input = input("Enter time: ")
if len(user_input) != 5:
print(False)
hours = user_input[:2]
minutes = user_input[3:]
if hours.isnumeric() and minutes.isnumeric():
hours_in_int = int(hours)
minutes_in_int = int(minutes)
if hours_in_int < 0 or hours_in_int > 23:
print(False)
elif minutes_in_int < 0 or minutes_in_int > 59:
print(False)
else:
print(True)
else:
print(False)
=======
print("Validate a 24 hours time string.")
user_input = input("Enter time: ")
if len(user_input) != 5:
print(False)
hours = user_input[:2]
minutes = user_input[3:]
if hours.isnumeric() and minutes.isnumeric():
hours_in_int = int(hours)
minutes_in_int = int(minutes)
if hours_in_int < 0 or hours_in_int > 23:
print(False)
elif minutes_in_int < 0 or minutes_in_int > 59:
print(False)
else:
print(True)
else:
print(False)
>>>>>>> 715fd0763b415a13fb28a483f258a5eadc1ec931
| true |
92295f2ad2b0ed8ff4d35474780dba9dc88e16e5 | SmischenkoB/campus_2018_python | /Kateryna_Liukina/3/3.5 Verify brackets.py | 766 | 4.25 | 4 | def verify_brackets(string):
"""
Function verify brackets
Args:
string(str): string to verify brackets
Returns:
bool: return true if all brackets are closed and are in right order
"""
brackets_opening = ('(', '[', '{')
brackets_closing = (')', ']', '}')
brackets_dict = dict(zip(brackets_opening, brackets_closing))
bracket_stack = []
for ch in string:
if ch in brackets_opening:
bracket_stack.append(ch)
elif ch in brackets_closing:
if len(bracket_stack) == 0:
return False
if ch == brackets_dict[bracket_stack[-1]]:
bracket_stack.pop(-1)
else:
return False
return(len(bracket_stack) == 0)
| true |
2d9d5ecb3a53c62da62052da5f849c71384a0300 | SmischenkoB/campus_2018_python | /Mykola_Horetskyi/3/Crypto Square.py | 1,074 | 4.125 | 4 | import math
def encode(string):
"""
Encodes string with crypto square method
Args:
string (str) string to be encoded
Returns:
(str) encoded string
"""
encoded_string = "".join([character.lower() for character in string
if character.isalpha()])
length = len(encoded_string)
number_of_columns = math.ceil(math.sqrt(length))
encoded_string = "".join([encoded_string[i::number_of_columns] for i in range(number_of_columns)])
return encoded_string
def decode(string):
"""
Decodes string encoded with crypto square method
Args:
string (str) string to be decoded
Returns:
(str) dencoded string
"""
decoded_string = "".join([character.lower() for character in string
if character.isalpha()])
length = len(decoded_string)
number_of_rows = math.floor(math.sqrt(length))
decoded_string = "".join([decoded_string[i::number_of_rows] for i in range(number_of_rows)])
return decoded_string
| true |
e63105840c53f6e3ea05835cb8a67afe38e741cc | SmischenkoB/campus_2018_python | /Lilia_Panchenko/1/Task7.py | 643 | 4.25 | 4 | import string
input_str = input('Your message: ')
for_question = 'Sure.'
for_yelling = 'Whoa, chill out!'
for_yelling_question = "Calm down, I know what I'm doing!"
for_saying_anything = 'Fine. Be that way!'
whatever = 'Whatever.'
is_question = False
if ('?' in input_str):
is_question = True
is_yelling = True
has_letters = False
is_yelling = input_str.isupper()
has_letters = input_str.islower() or is_yelling
if (not has_letters):
print(for_saying_anything)
elif (is_question):
if (is_yelling):
print(for_yelling_question)
else:
print(for_question)
elif (is_yelling):
print(for_yelling)
else:
print(whatever)
| true |
3f2039d4698f8b153ef13deaee6ec80e266dae3c | SmischenkoB/campus_2018_python | /Yurii_Smazhnyi/2/FindTheOddInt.py | 402 | 4.21875 | 4 | def find_odd_int(sequence):
"""
Finds and returns first number that entries odd count of times
@param sequence: sequnce to search in
@returns: first number that entries odd count of times
"""
for i in sequence:
int_count = sequence.count(i)
if int_count % 2:
return i
test_list = [1, 2, 3, 4, 5, 6, 2, 3, 3, 1]
print(find_odd_int(test_list))
| true |
5fbf80dd6b1bc1268272eb9e79c6c6e792dcc680 | SmischenkoB/campus_2018_python | /Tihran_Katolikian/2/CustomMap.py | 606 | 4.3125 | 4 | def custom_map(func, *iterables):
"""
Invokes func passing as arguments tuples made from *iterables argument.
:param func: a function which expects len(*iterables) number of arguments
:param *iterables: any number of iterables
:return: list filled with results returned by func argument. length of list
will be equal to a length of the shortest iterable argument
:rtype: list
"""
results = [func(*args) for args in zip(*iterables)]
return results
find_sum = lambda x, y: x + y
sum_of_vectors = custom_map(find_sum, [1, 2, 1], [-1, -2, -1])
print(sum_of_vectors)
| true |
03cd271429808ad9cf1ca520f8463a99e91c9321 | SmischenkoB/campus_2018_python | /Tihran_Katolikian/2/FindTheOddInt.py | 1,183 | 4.375 | 4 | def find_odd_in_one_way(list_of_numbers):
"""
Finds an integer that present in the list_of_number odd number of times
This function works as efficient as possible for this task
:param list_of_numbers: a list of integers in which must be at least one integer
which has odd number of copies there
:return: an integer that present in the list_of_number odd number of times
"""
for number in list_of_numbers:
if list_of_numbers.count(number) % 2 == 1:
return number
def find_odd_in_second_way(list_of_numbers):
"""
Finds an integer that present in the list_of_number odd number of times.
This function is likely to work less efficient than find_odd_in_one_way function
:param list_of_numbers: a list of integers in which must be at least one integer
which has odd number of copies there
:return: an integer that present in the list_of_number odd number of times
"""
for i in list_of_numbers:
count = 0
for j in list_of_numbers:
if i == j:
count += 1
if count % 2 == 1:
return i
print(find_odd_in_second_way([1, 2, 3, 1, 3, 2, 1]))
| true |
a19c8d2bf61250e9789f95a202f86dafbe371166 | SmischenkoB/campus_2018_python | /Ruslan_Neshta/3/VerifyBrackets.py | 897 | 4.3125 | 4 | def verify(string):
"""
Verifies brackets, braces and parentheses
:param string: text
:return: is brackets/braces/parentheses matched
:rtype: bool
"""
stack = []
is_valid = True
for ch in string:
if ch == '(' or ch == '[' or ch == '{':
stack.append(ch)
elif ch == ')' or ch == ']' or ch == '}':
if len(stack) == 0:
is_valid = False
break
else:
if ch == ')' and stack[-1] == '(' or ch == ']' and stack[-1] == '[' or ch == '}' and stack[-1] == '{':
stack.pop(-1)
else:
stack.append(ch)
else:
is_valid = len(stack) == 0
return is_valid
if __name__ == "__main__":
line = 'Some string with parentheses( and brackets [])'
is_line_valid = verify(line)
print(is_line_valid)
| true |
6855d88767abbe577f76e8263f5b1ec6aa9a6dee | SmischenkoB/campus_2018_python | /Dmytro_Skorobohatskyi/2/armstrong_numbers.py | 917 | 4.125 | 4 | def amount_digits(number):
""" Function recognize amount of digit in number.
Args:
number(int): specified number
Returns:
int: amount of digits in number
"""
counter = 0
while number != 0:
counter += 1
number //= 10
return counter
def check_if_armstrong_number(number):
""" Function checks if passed number is armstrong.
Args:
number(int): specified number
Returns:
bool: Return True if number is armstrong,
otherwise - return False
"""
sum = 0
number_length = amount_digits(number)
process_number = number
while process_number != 0:
last_digit = process_number % 10
addition = last_digit ** number_length
sum += addition
process_number //= 10
is_armstrong_number = sum == number
return is_armstrong_number
| true |
9879e700bccb8329e9a1b5e5ddca71abfb0aa7ba | SmischenkoB/campus_2018_python | /Dmytro_Shalimov/2/1.py | 1,338 | 4.4375 | 4 | from collections import Counter
print("Given an array, find the int that appears an odd number of times.")
print("There will always be only one integer that appears an odd number of times.")
print("Do it in 3 different ways (create a separate function for each solution).")
def find_odd_number_1(sequence):
"""
Function find int which appears in function odd number of times.
There should be only one int that appears an odd number of times.
Uses method count()
:param list sequence: a list of ints
:return: int which appears odd number of times
:rtype: int
"""
number = 0
for x in sequence:
count = sequence.count(x)
if count % 2 != 0:
number = x
break
return number
def find_odd_number_2(sequence):
"""
Function find int which appears in function odd number of times.
There should be only one int that appears an odd number of times.
Uses Counter class
:param list sequence: a list of ints
:return: int which appears odd number of times
:rtype: int
"""
temp = Counter(sequence)
return list(temp.keys())[0]
user_input = input("Enter sequence using spaces: ")
numbers = list(map(int, user_input.split()))
print(find_odd_number_2(numbers))
| true |
3c2510888352bd0867e04bf557b473af4b4ecfa9 | SmischenkoB/campus_2018_python | /Kyrylo_Yeremenko/3/task5.py | 858 | 4.46875 | 4 | """
This script solves task 3.5 from Coding Campus 2018 Python course
(Verify brackets)
"""
brackets = \
{
'{': '}',
'[': ']',
'(': ')'
}
def verify_brackets(string):
"""
Verify that all brackets in string are paired and matched correctly
:param string: Input string containing brackets
:return: True/False depending on bracket validity
"""
bracket_stack = [character for character in string if character in brackets or character in brackets.values()]
bracket_stack.reverse()
pair_stack = []
while bracket_stack:
next_item = bracket_stack.pop()
if next_item in brackets:
pair_stack.append(brackets[next_item])
elif pair_stack and next_item != pair_stack.pop():
return False
return not pair_stack
| true |
c45867f3199dbb730ae4764ece11d7a4742af826 | walton0193/cti110 | /P3HW2_BasicMath_WaltonKenneth.py | 1,198 | 4.1875 | 4 | #This program is a calculator
#It performs basic math operations
#CTI - 110
#P3HW2 - BasicMath
#Kenneth Walton
#17 March 2020
def add(number1, number2):
return number1 + number2
def subtract(number1, number2):
return number1 - number2
def multiply(number1, number2):
return number1 * number2
print('Menu')
print('1. Add Numbers');
print('2. Multiply Numbers');
print('3. Subtract Numbers');
print('4. Exit')
number1 = int(input('Enter the first number: '))
number2 = int(input('Enter the second number: '))
operation = input(('''Enter the operation you would like to perform:
1 for addition
2 for multiplication
3 for subratction
'''))
if operation == '1':
print('number1 + number2 = ', add(number1, number2))
elif operation == '2':
print('number1 * number2 = ', multiply(number1, number2))
elif operation == '3':
print('number1 - number2 = ', subtract(number1, number2))
print('number1 - number2')
elif operation == '4':
exit('Program will terminate')
else:
print('Error, you have not chosen a valid operation. Please try again')
| true |
b0c99ad473d14d8488a904db839ca328c1cceb1d | Patricia-Henry/tip-calculator-in-python- | /tip_calculator_final.py | 440 | 4.28125 | 4 | print("Welcome to the Tip Calculator")
bill_total = float(input("What was the bill total? $"))
print(bill_total)
tip = int(input("How much of a tip do you wish to leave? 10, 12, 15 \n"))
people_eating = int(input("How many people are splitting the bill?"))
percentage_tip = tip / 100
tip_amount = bill_total * percentage_tip
total_bill = tip_amount + bill_total
amount_to_pay = total_bill / people_eating
print(amount_to_pay) | true |
28fcd79f93af5e8516506dcb1402152ff26b9cfb | samdoty/smor-gas-bord | /morty.py | 995 | 4.28125 | 4 | # If you run this there is a bunch of intro stuff that will print
a = 10
print(a + a)
my_income = 100
tax_rate = 0.1
my_taxes = my_income * tax_rate
print(my_taxes)
print('hello \nworld')
print('hello \tworld')
print(len('hello'))
print(len('I am'))
mystring = "Hello World"
print(mystring[2])
print(mystring[-1])
mystring2 = "abcdefghijk"
print(mystring2[2:])
# stop index below is upto but not including
print(mystring2[:3])
print(mystring2[3:6])
print(mystring2[1:3])
# for what ever reason you can do this to get everything
print(mystring2[::])
# same thing to reverse
print(mystring2[::-1])
# there is this step size thing to jump every character
print(mystring2[::2])
print(mystring2[::3])
# start : stop : step size
# Immutability
name = "Sam"
# name[0] = 'P' doesn't work
last_letters = name[1:]
print(last_letters)
# String Concatenation
print('P' + last_letters)
x = 'Hello '
print(x + 'my name is Sam')
letter = 'z'
print(letter * 10)
print(letter.upper) | true |
d928744c32bde2b1aa046090a2fac343b2faf10d | SallyM/implemented_algorithms | /merge_sort.py | 1,458 | 4.1875 | 4 | def merge_sort(input_list):
# splitting original list in half, then each part in half thru recursion
# until left and right are each one-element lists
if len(input_list) > 1:
# print 'len(input_list)= {}'.format(len(input_list))
split = len(input_list)//2
left = input_list[: split]
right = input_list[split :]
# print 'split list ', left, right
# recursion
merge_sort(left)
merge_sort(right)
i = 0
j = 0
k = 0
# print 'i', i
# print 'j', j
# print 'k', k
while i < len(left) and j < len(right):
# comparing elements at each position of split lists, then merging them into one list
if left[i] < right[j]:
input_list[k] = left[i]
i += 1
# print 'i', i
else:
input_list[k] = right[j]
j += 1
# print 'j', j
k += 1
# print 'k', k
while i < len(left):
input_list[k] = left[i]
i += 1
k += 1
# print 'i', i
# print 'k', k
# print 'merged list', input_list
while j < len(right):
input_list[k] = right[j]
j += 1
k += 1
# print 'j', j
# print 'k', k
# print 'merged list', input_list
return input_list
| true |
6f74a09eb4b76315055d796874feeb993514e8f7 | USFMumaAnalyticsTeam/Kattis | /Autori.py | 590 | 4.1875 | 4 | # This python code is meant to take a single string that is in a
# long naming variation (ex. Apple-Boy-Cat) and change it
# to a short variation (ex. ABC)
import sys
# Receive user input as string
long_var = input()
# Verify user input is no more than 100 characters
if (long_var.count('') > 100):
sys.exit()
# Create an empty list
my_list = []
# Go through each letter in string
# and check if it's uppercase
# If so add to list
for letter in long_var:
if (letter.isupper()) == True:
my_list.append(letter)
# print list
print ("".join(my_list)) | true |
e9c7187e3f56e6bd0dd46ac18c0ff70b879eb0b0 | sahilshah1/algorithm-impls | /course_schedule_ii.py | 2,497 | 4.15625 | 4 | # There are a total of n courses you have to take, labeled from 0 to n - 1.
#
# Some courses may have prerequisites, for example to take course 0 you have
# to first take course 1, which is expressed as a pair: [0,1]
#
# Given the total number of courses and a list of prerequisite pairs,
# return the ordering of courses you should take to finish all courses.
#
# There may be multiple correct orders, you just need to return one of them.
# If it is impossible to finish all courses, return an empty array.
#
# For example:
#
# 2, [[1,0]]
# There are a total of 2 courses to take. To take course 1 you should have finished course 0.
# So the correct course order is [0,1]
#
# 4, [[1,0],[2,0],[3,1],[3,2]]
# There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2.
# Both courses 1 and 2 should be taken after you finished course 0. So one correct course order is [0,1,2,3].
# Another correct ordering is[0,2,1,3].
#
import unittest
class Solution(object):
def findOrder(self, numCourses, prerequisites):
"""
:type numCourses: int
:type prerequisites: List[List[int]]
:rtype: List[int]
"""
graph = {}
for i in xrange(0, numCourses):
graph[i] = {"has_prereqs": set(),
"is_prereq_for": set()}
for prereq in prerequisites:
course = prereq[0]
req = prereq[1]
graph[course]["has_prereqs"].add(req)
graph[req]["is_prereq_for"].add(course)
courses = []
courses_with_no_prereqs = filter(lambda x: not graph[x]["has_prereqs"], graph.keys())
while courses_with_no_prereqs:
courses.append(courses_with_no_prereqs.pop(0))
if len(courses) == numCourses:
return courses
for next_course in graph[courses[-1]]["is_prereq_for"]:
graph[next_course]["has_prereqs"].remove(courses[-1])
if not graph[next_course]["has_prereqs"]:
courses_with_no_prereqs.append(next_course)
return []
class CourseScheduleIITest(unittest.TestCase):
def test_find_order_basic(self):
order = Solution().findOrder(2, [[1,0]])
self.assertEquals(order, [0, 1])
def test_key_error(self):
order = Solution().findOrder(4, [[0, 1], [3, 1], [1, 3], [3, 2]])
self.assertEquals(order, [])
if __name__ == '__main__':
unittest.main() | true |
52d0586ed3cdbe18346e70d45883b74ec929e6c7 | pavankalyannv/Python3-Problems | /HackerRank.py | 1,718 | 4.34375 | 4 | Problme: @HackerRank
==========
Given the names and grades for each student in a Physics class of students, store them in a nested list and print the name(s) of any student(s) having the second lowest grade.
Note: If there are multiple students with the same grade, order their names alphabetically and print each name on a new line.
Input Format
-------------
The first line contains an integer, , the number of students.
The subsequent lines describe each student over lines; the first line contains a student's name, and the second line contains their grade.
Constraints
---------------
There will always be one or more students having the second lowest grade.
Output Format
----------------
Print the name(s) of any student(s) having the second lowest grade in Physics; if there are multiple students, order their names alphabetically and print each one on a new line.
Sample Input 0
---------------
5
Harry
37.21
Berry
37.21
Tina
37.2
Akriti
41
Harsh
39
Sample Output 0
------------------
Berry
Harry
Explanation 0
---------------
There are students in this class whose names and grades are assembled to build the following list:
python students = [['Harry', 37.21], ['Berry', 37.21], ['Tina', 37.2], ['Akriti', 41], ['Harsh', 39]]
The lowest grade of belongs to Tina. The second lowest grade of belongs to both Harry and Berry, so we order their names alphabetically and print each name on a new line.
solution: python3
===========================
marksheet = []
for _ in range(0,int(input())):
marksheet.append([input(), float(input())])
second_highest = sorted(list(set([marks for name, marks in marksheet])))[1]
print('\n'.join([a for a,b in sorted(marksheet) if b == second_highest]))
| true |
944f2a67f38f40370b64c9e97914e355009b9c6b | lixuanhong/LeetCode | /LongestSubstring.py | 979 | 4.15625 | 4 | """
Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb", the answer is "abc", which the length is 3.
Given "bbbbb", the answer is "b", with the length of 1.
Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
"""
#思路:从左往右扫描,当遇到重复字母时,以上一个重复字母的index +1,作为新的搜索起始位置。直到扫描到最后一个字母。
class Solution:
def lengthOfLongestSubstring(self, s):
start = len_max = 0
char_dict = {}
for i in range(len(s)):
if s[i] in char_dict and start <= char_dict[s[i]]:
start = char_dict[s[i]] + 1
else:
len_max = max(len_max, i - start + 1)
char_dict[s[i]] = i
return len_max
obj = Solution()
print(obj.lengthOfLongestSubstring("pwwkew"))
| true |
df7978f0c6a2f0959ecf5ead00a2d05f18325b10 | gauravdhmj/Project | /if programfile.py | 2,761 | 4.1875 | 4 | name = input("please enter your name:")
age = input("How old are you, {0}".format(name))
age = int(input("how old are you, {0}".format(name)))
print(age)
# USE OF IF SYNTAX
if age >= 18:
print("you are old enough to vote")
print("please put an x in the ballot box")
else:
print("please come back after {} years".format(18 - age))
print("Please guess a number between 1 and 10:")
guess = int(input())
# Method 1
if guess < 5:
print("Please guess a higher number")
guess = int(input())
if guess == 5:
print("Well done ,you guessed it correctly")
else:
print("you have not guessed correctly")
elif guess > 5:
print("Please guess a lower number")
guess = int(input())
if guess == 5:
print("Well done ,you guessed it correctly")
else:
print("you have not guessed correctly")
else:
print("You got it right the first time")
# Method 2
if guess != 5:
if guess < 5:
print("Please guess higher")
else:
print("Please guess lower")
guess = int(input())
if guess == 5:
print("Well done ,you guessed it correctly")
else:
print("you have not guessed correctly")
else:
print("You got it right the first time")
# USE OF AND and OR
age = int(input("How old are you?"))
# if (age>=16 and age<=65):
if (16 <= age <= 65):
print("Have a good day at work")
if (age < 16) or (age > 66):
print("Enjoy your meal at work")
else:
print("have a good day at work")
x = "false"
if x:
print("x is true")
print("""False: {0}
None: {1}
0: {2}
0.0: {3}
empty list[]: {4}
empty tuple(): {5}
empty string '': {6}
empty string "": {7}
empty mapping {{}}: {8}
""".format(False,bool(None),bool(0),bool(0.0),bool([]),bool(()),bool(''),bool(""),bool({}) ))
x = input("Please enter some text")
if x:
print('You entered "{}" '.format(x) )
else:
print("you did not enter anything")
# USE OF NOT KEYWORD
print(not True)
print(not False)
# EXAMPLE OF NOT KEYWORD
age = int(input("how old are you,"))
if not(age <= 18):
print("you are old enough to vote")
print("please put an x in the ballot box")
else:
print("please come back after {} years".format(18 - age))
# USE OF IN KEYWORD(DONE IN PREVIOUS VIDEOS)
parrot = "Norwegnian blue"
letter = input("enter any character\n")
if letter in parrot:
print("give me the letter {} lol".format(letter))
else:
print("apne pass rakh ise")
# USE OF NOT IN KEYWORD
parrot = "Norwegnian blue"
letter = input("enter any character\n")
if letter not in parrot:
print("apne pass rakh ise")
else:
print("give me the letter {} lol".format(letter))
| true |
bdf2b0fe68c75b4e9c5fe1c1173ebd19fa8cf5ff | CHS-computer-science-2/python2ChatBot | /chatBot1.py | 808 | 4.40625 | 4 | #This is the starter code for the Chatbot
# <Your Name Here>
#This is a chatbot and this is a comment, not executed by the program
#Extend it to make the computer ask for your favorite movie and respond accordingly!
def main():
print('Hello this is your computer...what is your favorite number?')
#Declaring our first variable below called 'computerfavnumber' and storing the
#value 33
computerfavnumber=25
#We now declare a variable but set the variable to hold whatever the *user*
#inputs into the program
favnumber = input("Number please: ")
print(favnumber + '...is a very nice number indeed. So...what is your name?')
name=input()
print('what a lovely name: ' + name + '...now, I will reveal what my favourite number is:')
print (computerfavnumber)
main()
| true |
a66ee557c0557d6dfe61852771995e3143b74022 | thatdruth/Drew-Lewis-FinalCode | /ExponentFunction.py | 247 | 4.40625 | 4 |
print(3**3) #Easy exponent
def raise_to_power(base_num, pow_num):
result = 1
for index in range(pow_num):
result = result * base_num
return result
print(raise_to_power(4,3)) #A coded loop exponent function
| true |
f97a33df94c0b8bf5424a74bef1d7cc584b7bfb7 | GabrielDaKing/Amateur_ML | /amateur_ml/regression/linear.py | 1,448 | 4.34375 | 4 | class Linear:
"""
A class to handle the basic training and pridiction capability
of a Linear Regression model while storing the slope and intercept.
"""
def __init__(self):
self.slope = 0
self.intercept = 0
def fit(self, x, y):
"""
A function to set the slope and intercept of the line of regression i.e. fit the line to the given data.
Args:
x (list(float)): The independent variable values
y (list(float)): The dependent variable values
"""
self.slope = 0
self.intercept = 0
assert len(x)==len(y)
x_sq = [i**2 for i in x]
xy = [i*j for i,j in zip(x,y)]
sum_x = sum(x)
sum_y = sum(y)
sum_x_sq = sum(x_sq)
sum_xy = sum(xy)
n=len(x)
self.slope = ((n*sum_xy)-(sum_x*sum_y))/((n*sum_x_sq)-sum_x**2)
self.intercept = ((sum_y*sum_x_sq)-(sum_x*sum_xy))/((n*sum_x_sq)-sum_x**2)
def predict(self, x):
"""Predicts the values of the dependent variable based on the independent variable provided
Args:
x (list(float)): The independent variable values
Returns:
list(float): The predicted dependent values
"""
y = [self.slope*i+self.intercept for i in x]
return y
def __repr__(self):
return "Slope: "+str(self.slope)+"\nIntercept: "+str(self.intercept)
| true |
ef7fc6de72d7f28fe6dacb3ad4c2edfcebce3d3d | kiranrraj/100Days_Of_Coding | /Day_59/delete_elemt_linked_list_frnt_back.py | 1,971 | 4.375 | 4 | # Title : Linked list :- delete element at front and back of a list
# Author : Kiran raj R.
# Date : 30:10:2020
class Node:
"""Create a node with value provided, the pointer to next is set to None"""
def __init__(self, value):
self.value = value
self.next = None
class Simply_linked_list:
"""create a empty singly linked list """
def __init__(self):
self.head = None
def printList(self):
linked_list = []
temp = self.head
while(temp):
linked_list.append(temp.value)
temp = temp.next
print(f"The elements are {linked_list}")
def search_list(self, item):
temp = self.head
while temp.next != None:
temp = temp.next
if temp.value == item:
print(f"Found {temp.value}")
break
def delete_fist_elem(self):
if self.head == None:
print("The linked list is empty")
else:
self.head = self.head.next
def delete_elem_end(self):
# print(elem.next, elem.value)
if self.head == None:
print("The linked list is empty")
else:
temp = self.head
while temp != None:
if temp.next.next == None:
temp.next = None
temp = temp.next
sl_list = Simply_linked_list()
sl_list.head = Node(1)
node2 = Node(2)
node3 = Node(3)
node4 = Node(4)
node5 = Node(5)
sl_list.head.next = node2
node2.next = node3
node3.next = node4
node4.next = node5
sl_list.printList()
sl_list.search_list(20)
sl_list.search_list(2)
sl_list.search_list(3)
print("List before deletion at start: ", end="")
sl_list.printList()
sl_list.delete_fist_elem()
print(f"List after deletion at start: ", end="")
sl_list.printList()
print("List before deletion at end: ", end="")
sl_list.printList()
sl_list.delete_elem_end()
print(f"List after deletion at end: ", end="")
sl_list.printList()
| true |
854616d109a06681b8765657cb5ba0e47689484f | kiranrraj/100Days_Of_Coding | /Day_12/dict_into_list.py | 537 | 4.15625 | 4 | # Title : Convert dictionary key and values into a new list
# Author : Kiran raj R.
# Date : 26:10:2020
# method 1 using dict.keys() and dict.values()
main_dict = {'a': 'apple', 'b': 'ball',
'c': 'cat', 'd': 'dog', 'e': 'elephant'}
list_keys = list(main_dict.keys())
list_values = list(main_dict.values())
print(list_keys, list_values)
# method 2 using dict.items()
listkeys = []
listvalues = []
for keys, values in main_dict.items():
listkeys.append(keys)
listvalues.append(values)
print(listkeys, listvalues)
| true |
19ea68c556c52b616ab33e76b24e779a21a8bc08 | kiranrraj/100Days_Of_Coding | /Day_7/count_items_string.py | 998 | 4.1875 | 4 | # Title : Find the number of upper, lower, numbers in a string
# Author : Kiran raj R.
# Date : 21:10:2020
import string
def count_items(words):
word_list = words.split()
upper_count = lower_count = num_count = special_count = 0
length_wo_space = 0
for word in words:
word = word.rstrip()
length_wo_space += len(word)
for index in range(len(word)):
if word[index].isupper():
upper_count += 1
if word[index].islower():
lower_count += 1
if word[index] in string.punctuation:
special_count += 1
if word[index].isnumeric():
num_count += 1
print(f"User entered string is: {words}")
print(f"Total length is {length_wo_space}\nSmall letters in string: {lower_count}\nCapital letters in string: {upper_count}\nSpecial characters in string: {special_count}\nNumbers count in string: {num_count}")
count_items("kiran raj r 12345 ,!# QWERR")
| true |
ec074f7136a4a786840144495d61960430c61c1c | kiranrraj/100Days_Of_Coding | /Day_26/linked_list_insert.py | 1,340 | 4.125 | 4 | # Title : Linked list insert element
# Author : Kiran Raj R.
# Date : 09:11:2020
class Node:
def __init__(self,data):
self.next = None
self.data = data
class LinkedList:
def __init__(self):
self.head = None
def print_list(self):
start = self.head
while start:
print(start.data)
start = start.next
def append_list(self, data):
new_elem = Node(data)
start = self.head
if start is None:
start = new_elem
return
while start.next is None:
start = start.next
start.next = new_elem
def prepand_list(self, data):
new_elem = Node(data)
new_elem.next = self.head
self.head = new_elem
def index_after(self, index, data):
start = self.head
new_elem = Node(data)
if not start:
print("The list is empty")
new_elem.next = index.next
index.next = new_elem
def index_before(self, index, data):
start = self.head
new_elem = Node(data)
if not start:
print("The list is empty")
while start:
if start.next == index:
new_elem.next = start.next
start.next =index
start = start.next
| true |
25ee94661cc1cce075df1356cbd9e9c76c9eb2be | kiranrraj/100Days_Of_Coding | /Day_47/check_tri_angle.py | 402 | 4.21875 | 4 | # Title : Triangle or not
# Author : Kiran Raj R.
# Date : 30/11/2020
angles = []
total = 0
for i in range(3):
val = float(input(f"Enter the angle of side {i}: "))
angles.append(val)
total = sum(angles);
# print(total)
if total == 180 and angles[0] != 0 and angles[1] != 0 and angles[2] != 0:
print("Valid angles for a triangle")
else:
print("Provided angles cannot form a triangle") | true |
13917f87c5fd24ee4f0f90bc0d5152aa2dccce83 | priyankaVi/Python | /challenge 3 #strings.py | 1,983 | 4.4375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
###challenge3 STRINGSabs
# In[ ]:
020
## Ask the user to enter their first name
##and then display the length of their name
# In[2]:
user=input("nter the first name")
len(user)
# In[ ]:
021
#Ask the user to enter their first name
#and then ask them to enter their surname.
#Join them together with a space between and
display the name
#and the length of whole name.
# In[4]:
user=input("enter the first name")
surname=input("enter the surname")
name= user+" "+surname
print("name")
len(name)
length=len(name)
print(length)
# In[ ]:
###Ask the user to enter their first name
and surname in lower case.
Change the case to title case
and join them together.
Display the finished result.
023
# In[7]:
user=input("enter the fiorstname")
surname=input("enter the surname")
surname.lower()
print(loweer)
# In[ ]:
#Ask the user to enter their first name.
#If the length of their first name is under five characters,
#ask them to enter their surname and
join them together (without a space) and
display the name in upper case.
If the length of the first name is five or more characters,
display their first name in lower case.
026
# In[12]:
user=input("enter the firstname")
if len(name)<5:
sur=input("enter the surname")
user=user+sur
else:
print(user.lower())
# In[11]:
user=input("enter the first name")
user=user.upper()
print(user)
# In[ ]:
026
###Pig Latin takes the first consonant of a word,
moves it to the end of the word
and adds on an “ay”.
If a word begins with a vowel you just add “way”
to the end. For example, pig becomes igpay,
banana becomes ananabay, and
aadvark becomes aadvarkway.
Create a program that will ask the
user to enter a word and change it into Pig Latin.
Make sure the new word is displayed in lower case.
# In[ ]:
# In[ ]:
# In[ ]:
# In[ ]:
| true |
dfa353728f27230e57cde4ea7d3ed84d0746527a | ramlaxman/Interview_Practice | /Strings/reverse_string.py | 548 | 4.21875 | 4 | # Reverse a String iteratively and recursively
def reverse_iteratively(string):
new_string = str()
for char in reversed(string):
new_string += char
return new_string
def test_reverse_iteratively():
assert reverse_iteratively('whats up') == 'pu stahw'
def reverse_recursively(string):
print('')
length = len(string)
if length == 1:
return string
return string[length-1] + reverse_recursively(string[:-1])
def test_reverse_recursively():
assert reverse_recursively('whats up') == 'pu stahw'
| true |
d516b1c2b45bf8145759ba5ae676f24c1c7384ce | ahmad-elkhawaldeh/ICS3U-Unit-4-03-python | /loop3.py | 779 | 4.5 | 4 | #!/usr/bin/env python3
# Created by: Ahmad El-khawaldeh
# Created on: Dec 2020
# a program that accepts a positive integer;
# then calculates the square (power of 2) of each integer from 0 to this number
def main():
# input
positive_integer = print(" Enter how many times to repeat ")
positive_string = input("Enter Here plz : ")
# process & output
try:
positive_integer = int(positive_string)
for loop_counter in range(positive_integer + 1):
positive_exponent = loop_counter ** 2
print("{0}² = {1}".format(loop_counter, positive_exponent))
except AssertionError:
print('Given input is not a number.')
except ValueError:
print('Given input is not a number.')
if __name__ == "__main__":
main()
| true |
c0c7507d3d351d1cdd4dff4624acef7f54b4b52f | bikash-das/pythonprograms | /practice/check_list.py | 1,293 | 4.21875 | 4 | def is_part_of_series(lst):
'''
:param: lst - input is the set of integers (list)
:output: returns true if the list is a part of the series defined by the following.
f(0) = 0 f(1) = 1 f(n) = 2*f(n-1) - 2*f(n-2) for all n > 1.
'''
assert(len(lst) > 0)
if(lst[0] != 0):
return False
else:
if(len(lst) == 1):
return True
if(lst[1] != 1):
return False
else:
if(len(lst) == 2):
return True
a = 0 # first initial value is 0
b = 1 # second initial value is 1
i = 2 # loop variable starting at 2, because we already checked for index 0 and 1
lst_length = len(lst)
while(i < lst_length):
c = 2 * (b - a) # f(n) = 2 * (f(n-1) - f(n-2)) = 2 * (b - a)
if(c != lst[i]):
return False
a = b
b = c
i += 1
return True
if __name__ == "__main__":
print("Enter the list of integers seperated by a Space")
lst = [int(x) for x in input().split()]
if(is_part_of_series(lst)):
print("True: {}. List is PART of the Given Series".format(lst))
else:
print("False: {}. List is NOT PART of the Given Series".format(lst)) | true |
3ad3950e0d0b1cef1791b7563714f3ffec93d4ac | bikash-das/pythonprograms | /tkinter/ch-1/clickEvent2.py | 761 | 4.3125 | 4 | import tkinter as tk
from tkinter import ttk
# create an instance of window (tk)
win = tk.Tk() # creates an empty window
# action for button click
def click():
btn.configure(text = "Hello " + name.get()) # get() to retrive the name from the text field
# create a Label
ttk.Label(win, text = "Enter a name: ").grid(column = 0, row = 0)
# add a Text Box Entry widget, StringVar = string variable (telling beforehand)
name = tk.StringVar()
input = ttk.Entry(win, width = 15, textvariable = name) # width is hardcoded, it will not change
input.grid(column = 0, row = 1)
# add a Button
btn = ttk.Button(win, text = "Click", command = click)
btn.grid(column = 1, row = 1)
input.focus() # cursor focused in text box
# start the GUI
win.mainloop()
| true |
5e9c092473f6f2e780979df5f11b74d30db9d346 | bikash-das/pythonprograms | /ds/linkedlist.py | 1,233 | 4.15625 | 4 | class node:
def __init__(self,data):
self.value = data
self.next=None;
class LinkedList:
def __init__(self):
self.start = None;
def insert_last(self,value):
newNode = node(value)
if(self.start == None):
self.start = newNode;
else:
# search last node to insert
temp = self.start
while temp.next != None:
temp = temp.next
temp.next = newNode
def delete_first(self):
if(self.start == None):
print("Linked List Empty")
else:
#temp = self.start
self.start = self.start.next #if no second present than, start will contain None
def display_list(self):
if self.start == None:
print("List empty")
else:
temp=self.start
while(temp != None):
print(temp.value,end=" ")
temp = temp.next
if __name__ == '__main__':
mylist = LinkedList()
mylist.insert_last(10)
mylist.insert_last(20)
mylist.insert_last(30)
mylist.insert_last(40)
mylist.display_list()
print()
mylist.delete_first()
mylist.display_list()
| true |
ff983f0996b4abffdfa420f9449f95aa47097011 | xXPinguLordXx/py4e | /exer11.py | 234 | 4.125 | 4 | def count (word, char):
char_count = 0
for c in word:
if c == char:
char_count += 1
return char_count # occurences
inp_word = input ("Enter word: ")
inp_char = input ("Enter char: ")
print (count)
| true |
2b2260baa8a63839a1d3feeabfc645cf52ef7761 | xXPinguLordXx/py4e | /exer8.py | 768 | 4.28125 | 4 | #declare this shit outside the loop because if you put it inside it will just get looped forever
#declare this outside so that it is accessible by the entire program outside and not just within the loop
sum = 0
count = 0
while True:
number = input ("Enter a number: ")
if number == 'done':
break
try:
number = float(number)
except:
print('Invalid input')
continue
sum += number #this is shorthand for sum = sum + number
count = count + 1 #or you can write count += 1 #write this here so that program tries to do this before moving on to invalidating
## to protect the code from breaking when someone inputs 'done' at the start:
if count == 0:
print(sum,count, None)
else:
print(sum,count,sum/count)
| true |
e3d5c813c35e2ba8683d5404fa936e862a7e35f3 | mileuc/breakout | /paddle.py | 725 | 4.1875 | 4 | # step 2: create paddle class
from turtle import Turtle
class Paddle(Turtle): # paddle class is now effectively the same as a Turtle class
def __init__(self, paddle_position):
super().__init__() # enable Turtle methods to be used in Ball class
self.shape("square")
self.color("white")
self.shapesize(stretch_len=5, stretch_wid=1)
self.penup()
self.goto(paddle_position) # initial position of the paddle center
def move_left(self):
# move paddle left
new_x = self.xcor() - 20
self.goto(x=new_x, y=self.ycor())
def move_right(self):
# move paddle right
new_x = self.xcor() + 20
self.goto(x=new_x, y=self.ycor()) | true |
6ff3d2c4c52c4ed4c0543b81eb97a4e59e6babeb | vishalkmr/Algorithm-And-Data-Structure | /Searching/Binary Search(Ascending Order).py | 1,134 | 4.15625 | 4 | '''
Binary Search on Ascending order Lists
Assume that list is in Ascending order
Note : Binary search is aplicable only when list is sorted
'''
def binary_search(list,item):
'''
funtion for binary search of element in list
synatx: binary_search( list,item)
retrun index of element where the item is found
return -1 when item is not found in list
Time Complexity: O(logn)
'''
beg=0
length=len(list)
end=length-1
while(beg<=end):
mid=(beg+end)//2 #finding middle element index
#if item is mathched with middle element
if(list[mid]==item):
return mid
#if item is less than the middle element than consider only left portion of list
elif(list[mid]>item):
end=mid-1
#if item is greater than the middle element than consider only right portion of list
elif(list[mid]<item):
beg=mid+1
if(beg>end ):
return -1
list=[0,1,2,3,4,5,6,7]
item=6
result=binary_search(list,item)
if result== -1:
print("Not Found !")
else:
print(result) | true |
edd37b42b381dfc85b5f443b79e151f7225b9201 | vishalkmr/Algorithm-And-Data-Structure | /Arrays & Strings/Array Pair Sum.py | 2,761 | 4.40625 | 4 | '''
Given an integer array, output all the unique pairs that sum up to a specific value k.
Example
pair_sum([1,2,3,4,5,6,7],7)
Returns: (3, 4), (2, 5), (1, 6)
'''
#using Sorting
def pair_sum(list,k):
'''
Funtion return all the unique pairs of list elements that sum up to k
Syntax: insert(list,k)
Time Complexity: O(nlogn)
'''
list.sort() #sorting the list
length=len(list)
pairs=[] #for storing the list of pairs that sum up to k
i=0 #pointing to begining of the list (Smallest number in the list)
j=length-1 #pointing to ending of the list (Largest number in the list)
#making iterations until i and j points to the same element
while i<=j:
#if sum of list[i] & list[j] is equal to k that means it is one of the desired pair
if list[i]+list[j]==k:
pairs.append((list[i],list[j]))
i+=1
j-=1
#if these pair sum is less than k
#we know that the list is sorted and hence j is pointing to Largest number in the list
#so it is due to value of number pointed by i that is causes there sum to be lesser than k
#Thus we increment the pointer i so that the sum of values pointed by i and j may gets equal to k
elif list[i]+list[j]<k:
i+=1
#if these pair sum is greater than k
#we know that the list is sorted and hence i is pointing to Smallest number in the list
#so it is due to value of number pointed by j that is causes there sum to be greater than k
#Thus we dicrement the pointer j so that the sum of values pointed by i and j may gets equal to k
else:
j-=1
return pairs
#using Set
def pair_sum(list,k):
'''
Funtion return all the unique pairs of list elements that sum up to k
Syntax: insert(list,k)
Time Complexity: O(n)
'''
pairs=[] #for storing the list of pairs that sums up to k
seen=set() #for storing the elements of the list which are alredy seened
for current in list:
target=k-current #stores the desiered value or target value ( which when added to current element of the list yiedls to the sum k )
#if target value is found in the seen set
#then the sum of target and list current element is equal to k
#Thus we add target & current element touple onto the pairs list
if target in seen:
pairs.append((min(target,current),max(target,current))) #formating the pairs touple so like (min_value_of_pairs,max_value_of_pairs)
#if target value is not found in the seen set
#means the sum of any element of seen set with the current element doesnot yields to k
#Thus we simply add current element of the list to the seen set in a hop that may be this added_current_element_values can be summed up with upcomming element to produce k
else:
seen.add(current)
return pairs
list=[1,2,3,4,5,6,7]
pairs=pair_sum(list,7)
print(pairs)
| true |
aba4633ded621a38d9a0dd4a6373a4b70ee335d9 | vishalkmr/Algorithm-And-Data-Structure | /Linked Lists/Rotate Right.py | 1,755 | 4.40625 | 4 | '''
Rotates the linked-list by k in right side
Example:
link-list : 1,2,3,4,5,6
after 2 rotation to right it becomes 5,6,1,2,3,4
'''
from LinkedList import LinkedList
def rotate_right(linked_list,k):
"""
Rotates the linked-list by k in right side
Syntax: rotate_right(linked_list,k)
Time Complexity: O(n)
"""
#for circular rotation
if k>=len(linked_list):
k=k%len(linked_list)
if len(linked_list)==0 or k==0:
return
count=0
current=linked_list.head
previous=None
#break the linked_list into two portion
while current and count!=(len(linked_list)-k):
previous=current
current=current.next
count=count+1
previous.next=None
#previous represent new likedlist last element
linked_list.tail=previous #update the new linked_list tail
#now list is splited into two portion
#1st contains node form begining of original linked_list to previous node (left list)
#2nd contains from current node to last node (right list)
#for rotation we just have to append 1st linked-list after 2nd linked-list
if count==(len(linked_list)-k):
ptr=current
while ptr.next:
ptr=ptr.next
#ptr points to 2nd linked_list last node
#joining the 1st linked_list at the end of 2nd linked_list
ptr.next=linked_list.head
linked_list.head=current #update the new linked_list head
linked_list=LinkedList()
linked_list.insert_end(1)
linked_list.insert_end(2)
linked_list.insert_end(3)
linked_list.insert_end(4)
linked_list.insert_end(5)
linked_list.insert_end(6)
print(linked_list)
result=rotate_right(linked_list,2)
print(linked_list)
| true |
bac0d9c2b34bf891722e468c11ff0f615faef1fc | vishalkmr/Algorithm-And-Data-Structure | /Arrays & Strings/Missing element.py | 1,576 | 4.28125 | 4 | '''
Consider an array of non-negative integers. A second array is formed by shuffling the elements of the first array
and deleting a random element. Given these two arrays, find which element is missing in the second array.
Example :
The first array is shuffled and the number 5 is removed to construct the second array then
missing_element([1,2,3,4,5,6,7],[3,7,2,1,4,6])
Returns: 5
'''
#using Soting
def missing_element(arr1,arr2):
'''
Funtion return missing element
Syntax: missing_element(arr1,arr2)
Time Complexity: O(nlogn)
'''
# Sort the arrays
arr1.sort()
arr2.sort()
# Compare elements in the sorted arrays
for num1, num2 in zip(arr1,arr2):
if num1!= num2:
return num1
#using Dictionary
def missing_element1(arr1,arr2):
'''
Funtion return missing element
Syntax: missing_element(arr1,arr2)
Time Complexity: O(n)
'''
count={}
#Storing the element count of array2 in Dictionary
for i in arr2:
if i in count:
count[i]+=1
else:
count[i]=1
#Compairing the element count of array1 with Dictionary elements
for i in arr1:
if i not in count:
return i
elif count[i]==0:
return i
else:
count[i]-=1
#using EXOR-Logic
def missing_element(arr1,arr2):
'''
Funtion return missing element
Syntax: missing_element(arr1,arr2)
Time Complexity: O(n)
'''
result=0
# Perform an XOR between the numbers in the concatnated arrays (arr1+arr2)
for num in arr1+arr2:
result^=num
return result
arr1 = [1,2,3,4,5,6,7]
arr2 = [3,7,2,1,4,6]
output=missing_element1(arr1,arr2)
print(output) | true |
23ad168cebd9f937871f8ef52f0822387308dbc5 | vishalkmr/Algorithm-And-Data-Structure | /Trees/Mirror Image.py | 1,639 | 4.34375 | 4 | '''
Find the Mirror Image of a given Binary tree
Exapmle :
1
/ \
2 3
/ \ / \
4 5 6 7
Mirror Image :
1
/ \
3 2
/ \ / \
7 6 5 4
'''
from TreeNode import Node
def mirror_image(root):
"""
Return Mirror Image of the given Tree
Syntax: mirror_image(root)
Time Complexity: O(n)
Recurrence Relation :
Best Case : T(n)=2T(n/2)+C (C represents constant)
Worst Case : T(n)=T(n-1)+C (C represents constant)
"""
# if Tree is empty
if not root:
return root
#if leaf node
if root.left==None and root.right==None:
return root
temp=root.right
root.right=mirror_image(root.left)
root.left=mirror_image(temp)
return root
#to display mirror image
def preorder(root):
"""
Function to find Preorder traversal of the given Tree
Syntax: inorder(root)
Time Complexity: O(n)
Recurrence Relation :
Best Case : T(n)=2T(n/2)+C (C represents constant)
Worst Case : T(n)=T(n-1)+C (C represents constant)
"""
# if Tree is empty
if not root:
return
print(root.data) #root
preorder(root.left) #left
preorder(root.right) #right
a=Node(1)
b=Node(2)
c=Node(3)
d=Node(4)
e=Node(5)
f=Node(6)
g=Node(7)
a.left=b
a.right=c
b.left=d
b.right=e
c.left=f
c.right=g
print('Preorder Traversal Before Mirroring')
preorder(a)
root=mirror_image(a)
print('Preorder Traversal After Mirroring')
preorder(root) | true |
8f8ba9c1a6e13d1527f0c3ac5c2a72dc330a0321 | vishalkmr/Algorithm-And-Data-Structure | /Sorting/Bubble Sort.py | 2,203 | 4.5625 | 5 | '''
SORT the given array using Bubble Sort
Example: Let us take the array of numbers "5 1 4 2 8", and sort the array in ascending order using bubble sort.
First Pass
( 5 1 4 2 8 ) -> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1.
( 1 5 4 2 8 ) -> ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) -> ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) -> ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them.
Second Pass
( 1 4 2 5 8 ) -> ( 1 4 2 5 8 )
( 1 4 2 5 8 ) -> ( 1 2 4 5 8 ), Swap since 4 > 2
( 1 2 4 5 8 ) -> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) -> ( 1 2 4 5 8 )
Now, the array is already sorted, but the algorithm does not know if it is completed. The algorithm needs one whole pass without any swap to know it is sorted.
Third Pass
( 1 2 4 5 8 ) -> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) -> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) -> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) -> ( 1 2 4 5 8 )
Simmilarly other Passes yields same Sorted Array.....
'''
#Conventional Bubble Sort
def bubble_sort(list):
'''
Funtion to sort the list using Bubble Sort
Syntax: bubble_sort(list)
Time Complexity: O(n^2) [Every Case]
'''
for elements in list:
for index in range(len(list)-1):
#check the adjecent elements are in increasing order or not
if list[index]>list[index+1]:
#if not then perform pairwise swaps
list[index],list[index+1]=list[index+1],list[index]
#Efficient Bubble Sort
def bubble_sort(list):
'''
Funtion to sort the list using Bubble Sort
Syntax: bubble_sort(list)
Time Complexity:
Worst Case : O(n^2)
Best Case : O(n)
'''
swapped = True #Flag to monitor that swaping ocuured or not
while swapped:
swapped = False
for index in range(len(list)-1):
#check the adjecent elements are in increasing order or not
if list[index] > list[index+1]:
#if not then perform pairwise swaps
list[index],list[index+1]=list[index+1],list[index]
swapped = True
list=[7, 6, 5, 4, 3, 2, 1]
bubble_sort(list)
print(list) | true |
30a98b2f034a60422a2faafbd044628cd1011e43 | vishalkmr/Algorithm-And-Data-Structure | /Arrays & Strings/Max and Min(Recursion).py | 1,108 | 4.40625 | 4 | '''
Find the maximum and minimum element in the given list using Recursion
Example
max_min([11,-2,3,6,14,8,16,10])
Returns: (-2, 16)
'''
def max_min(list,index,minimum,maximum):
'''
Funtion to return maximum and minimum element in the given list
Syntax: max_min(list,index,minimum,maximum)
Time Complexity: O(n)
Space Complexity: O(n)
Recurence Relation : T(n)=T(n-1)+C (C represents constant)
'''
if index <len(list):
#if current element is lesser than minimum then make the current element as the minimum element
if list[index]<minimum:
minimum=list[index]
#if current element is greater than maximum then make the current element as the maximum element
if list[index]>maximum:
maximum=list[index]
#recursively compute the maximum and minimum element of the remaining list
return max_min(list,index+1,minimum,maximum)
#if all element of list are encountered
#return the current maximum and minimum element
else :
return (minimum ,maximum)
list=[11,-2,3,6,14,8,16,10]
minimum=9999
maximum=-9999
result=max_min(list,0,minimum,maximum)
print(result) | true |
4106cc2dccfacb7322a9e00a440321b30d224e30 | vishalkmr/Algorithm-And-Data-Structure | /Searching/Ternary Search.py | 1,860 | 4.46875 | 4 | '''
Ternary Search on lists
Assume that list is already in Ascending order.
The number of Recursive Calls and Recisrion Stack Depth is lesser for Ternary Search as compared to Binary Search
'''
def ternary_search(list,lower,upper,item):
'''
Funtion for binary search of element in list
Synatx: ternary_search(list,lower,upper,item)
Return index of element where the item is found
Time Complexity: O(logn)
Space Complexity: O(logn)
Recurence Relation : T(n)=T(n/3)+C (C represents constant)
'''
if lower<=upper:
first_middle=lower+((upper-lower)//3) #finding 1st middle element which is at (n/3)rd index of list
second_middle=lower+(((upper-lower)*2)//3) #finding 2nd middle element which is at (2n/3)rd index of list
#if item is mathched with first_middle element then first_middle is the required index
if list[first_middle]==item :
return first_middle
#if item is mathched with second_middle element then second_middle is the required index
elif list[second_middle]==item:
return second_middle
#if item is less than the first_middle element then apply Ternary Search on Left portion of list
elif list[first_middle]>item:
return ternary_search(list,lower,first_middle-1,item)
#if item is between than the first_middle and second_middle then apply Ternary Search on Middle portion of list
elif list[first_middle]<item and item<list[second_middle]:
return ternary_search(list,first_middle+1,second_middle-1,item)
#if item is greater than the second_middle then apply Ternary Search on Right portion of list
elif list[second_middle]<item :
return ternary_search(list,second_middle+1,upper,item)
list=[0,1,2,3,4,5,6,7]
item=5
result=ternary_search(list,0,len(list)-1,item)
if result!=None:
print(result)
else:
print('Not Found !') | true |
29c60efe0b91a9c74c2eebe4d9ce599a8c52ba7f | vishalkmr/Algorithm-And-Data-Structure | /Linked Lists/Cyclic.py | 1,733 | 4.21875 | 4 | '''
Check the given limked-list is cyclic or not
'''
from LinkedList import LinkedList
#using Set
def is_cyclic(linked_list):
"""
Returns True if linked-list is cyclic
Syntax: is_cyclic(linked_list)
Time Complexity: O(n)
"""
# if linked-list is empty
if not linked_list.head or not linked_list.head.next:
return False
visited=set()
current=linked_list.head
while current:
#if the node is already in visited set that mean linked-list is cyclic
if current.data in visited:
return True
#if the node is not visited set that means it appears 1st time so add it on the visited set
else:
visited.add(current.data)
#incement the loop counter
current=current.next
return False
def is_cyclic(linked_list):
"""
Returns True if linked-list is cyclic
Syntax: is_cyclic(linked_list)
Time Complexity: O(n)
"""
# if linked-list is empty
if not linked_list.head or not linked_list.head.next:
return False
slow = fast =linked_list.head
while fast and fast.next:
slow=slow.next #slow takes one step at a time
fast= fast.next.next #fast takes two step at a time
#if slow meets with fast that means linked-list is cyclic
if fast==slow:
return True
return False
linked_list=LinkedList()
linked_list.insert_end(1)
linked_list.insert_end(2)
linked_list.insert_end(3)
linked_list.insert_end(4)
linked_list.insert_end(5)
linked_list.insert_end(6)
#making the linked-list cyclic
linked_list.tail.next=linked_list.head
result=is_cyclic(linked_list)
print(result)
| true |
967ac148b13a59295b9c16523e6e046ffd000950 | PdxCodeGuild/Full-Stack-Day-Class | /practice/solutions/ttt-interface/list_board.py | 1,184 | 4.1875 | 4 | """Module containing a list of lists tic-tac-toe board implementation."""
class ListListTTTBoard:
"""Tic-Tac-Toe board that implements storage as a list
of rows, each with three slots.
The following board results in the following data structure.
X| |
|X|O
| |
[
['X', ' ', ' '],
[' ', 'X', 'O'],
[' ', ' ', ' '],
]
"""
def __init__(self):
"""Initialize an empty board."""
self.rows = [
[' ', ' ', ' '],
[' ', ' ', ' '],
[' ', ' ', ' '],
]
def place_token(self, x, y, player):
"""Place a token on the board at some given coordinates.
x is horizontal position, y is vertical position.
0, 0 is the top-left.
`player` is either 'X' or 'O'
"""
pass
def calc_winner(self):
"""Return which token type won ('X' or 'O') or None if no one
has won yet.
"""
pass
def __str__(self):
"""Return a string representation of the board.
Should be three rows with each cell separated by a '|'.
X| |
|X|O
| |
"""
pass
| true |
dcc6eac9a830867df9b8bf1dbc28c592c4458990 | priyankamadhwal/MCA-101-OOP | /14- bubbleSort.py | 1,139 | 4.28125 | 4 | def swap(lst, lowerIndex=0, pos=0):
'''
OBJECTIVE : To swap the elements of list so that the largest element goes at the lower index.
INPUT :
lst : A list of numbers.
lowerIndex : The lower index upto which swapping is to be performed.
OUTPUT : List, with the correct element at lowerIndex.
'''
#APPROACH : Compare the 2 list elements: If lst[up] is greater than lst[low], then swap them.
length = len(lst)
up=length-1-pos
low=up-1
if low < lowerIndex:
return
if lst[up] > lst[low]:
temp = lst[up]
lst[up] = lst[low]
lst[low] = temp
swap(lst, lowerIndex, pos+1)
def bubbleSort(lst, lowerIndex=0):
'''
OBJECTIVE : To sort the given list using bubble sort.
INPUT :
lst : A list of numbers.
lowerIndex : The lower index from which sorting should begin.
OUTPUT : List, sorted in descending order.
'''
#APPROACH : Make use of the swap() function.
length = len(lst)
if lowerIndex > length-2:
return
swap(lst, lowerIndex)
bubbleSort(lst, lowerIndex+1)
| true |
16bc2814112b7bd4fad04457af0ba79ccf21e68a | soumilk91/Algorithms-in-Python | /Mathematical_algorithms/calculate_fibo_number.py | 1,414 | 4.21875 | 4 | """
@ Author : Soumil Kulkarni
This file contains various methods related to problems on FIBO Series
"""
import sys
# Method to calculate the fibo number recursively
def calculate_fibo_number_recursive(num):
if num < 0:
print "Input incorrect"
elif num == 0 :
return 0
elif num == 1 :
return 1
else :
return (calculate_fibo_number_recursive(num - 1) + calculate_fibo_number_recursive(num -2 ))
# Method to calculate fibo number using a list
def calculate_fibo_number_with_list(num):
num_list =[0,1]
if num < 0:
print "Input incorrect"
elif num == 0:
return 0
elif num == 1:
return 1
else:
n = num - 2
pointer_1 = 0
poniter_2 = 1
for i in range(n):
num_list.append(num_list[pointer_1] + num_list[poniter_2])
pointer_1 += 1
poniter_2 += 1
return (num_list[pointer_1] + num_list[poniter_2])
# Method to reduce the space complexity in the previous soultion.
# Hint : All you need is the last 2 digits, so just store the last 2 digits and neglect the others. Space complexity will be reduced from O(N) to O(1)
def calulate_fibo_number_with_list_improved(num):
num_list = [0,1]
if num < 0:
print "Input incorrect"
elif num == 0:
return 0
elif num == 1:
return 1
else:
n = num - 2
pointer_1 = 0
poniter_2 = 1
for i in range (n):
temp = num_list[0] + num_list[1]
num_list[0] = num_list[1]
num_list[1] = temp
return (num_list[0] + num_list[1])
| true |
8358b7abc87c5062eeb4b676eb1091b5d6d897ba | abhijit-nimbalkar/Python-Assignment-2 | /ftoc.py | 530 | 4.125 | 4 | #Author-Abhijit Nimbalkar & Sriman Kolachalam
import Functions #importing Functions.py file having multiple functions
temp_in_F=Functions.check_temp_input_for_F("Enter the Temperature in Fahrenheit: ") #Calling function check_temp_input_for_F() for accepting the valid input from User
temp_in_C=Functions.FtoC(temp_in_F) #Calling function to convert temperature from Fahrenheit to Celsius
print("{0}{1:0.2f}".format("Temperature in Celsius is: ", temp_in_C)) #printing the output in right format
| true |
685d18829d1197fa5471cfed83446b14af65789e | hsuvas/FDP_py_assignments | /Day2/Q6_FibonacciRecursion.py | 263 | 4.25 | 4 | #6. fibonacci series till the Nth term by using a recursive function.
def fibo(n):
if n<=1:
return n
else:
return (fibo(n-1)+fibo(n-2))
n=int(input("How many numbers: "))
print("Fibonacci series: ")
for i in range(n):
print(fibo(i))
| true |
99bb6059454cf462afbe9bfc528b8ea6d9d84ecb | hsuvas/FDP_py_assignments | /Day2/Q3_areaCircumference.py | 279 | 4.5 | 4 | #3.compute and return the area and circumference of a circle.
def area(r):
area=3.14*r*r
return area
def circumference(r):
c=2*3.14*r
return c
r=float(input("enter the radius"))
a=area(r)
print("area is: ",a)
cf=circumference(r)
print("Circumference is: ",cf)
| true |
edb63793a549bf6bf0e4de33f86a7cefb1718b57 | onionmccabbage/python_april2021 | /using_logic.py | 355 | 4.28125 | 4 | # determine if a number is larger or smaller than another number
a = int(float(input('first number? ')))
b = int(float(input('secomd number? ')))
# using 'if' logic
if a<b: # the colon begins a code block
print('first is less than second')
elif a>b:
print('second is less than first')
else:
print('probably the same number')
| true |
ee715cb90cf4724f65c0f8d256be926b66dc1ddb | onionmccabbage/python_april2021 | /fifo.py | 1,739 | 4.1875 | 4 | # reading adnd writing files file-input-file-output
# a simple idea is to direct printout to a file
# fout is a common name for file output object
# 'w' will (over)write the file 'a' will append to the file. 't' is for text (the default)
fout = open('log.txt', 'at')
print('warning - lots of interesting loggy stuff', file=fout)
fout.close() # clean up when done
# we can write to a file a bit at a time
long_str = '''we can use a while loop to automatically close any open file access objects
This saves us doing it explicitly'''
try:
fout = open('other.txt', 'xt') # 'a' to append, 'x' for exclusive access
size = len(long_str)
offset = 0
chunk = 24
while True:
if offset > size:
fout.write('\n') # we need to put our own new line at the end of the file (if needed)
break
else:
fout.write(long_str[offset:offset+chunk])
offset+=chunk
except FileExistsError as err:
print('the file already exists', err.errno)
except Exception as err:
print(err)
finally:
print('all done')
# next we read content in from text files via a file access object
fin = open('other.txt', 'r') # 'r' for read ('t' is the default)
# received = fin.read() # reads the entire file
received = fin.readline()+'---'+fin.readline() # reads TWO lines!
fin.close() # tidy up
print(received)
# writing and reading byte files
# we need some bytes
b = bytes( range(0, 256) )
print(b)
fout = open('bfile', 'wb') # 'wb' to (over)write bytes
fout.write(b)
fout.close()
# now read them back in
fin = open('bfile', 'rb') # 'rb' to read bytes
retrieved_b = fin.read() # read the whole file
fin.close()
print(retrieved_b) | true |
4417ee4d4251854d55dd22522dfef83a0f55d396 | VadymGor/michael_dawson | /chapter04/hero's_inventory.py | 592 | 4.40625 | 4 | # Hero's Inventory
# Demonstrates tuple creation
# create an empty tuple
inventory = ()
# treat the tuple as a condition
if not inventory:
print("You are empty-handed.")
input("\nPress the enter key to continue.")
# create a tuple with some items
inventory = ("sword",
"armor",
"shield",
"healing potion")
# print the tuple
print("\nThe tuple inventory is:")
print(inventory)
# print each element in the tuple
print("\nYour items:")
for item in inventory:
print(item)
input("\n\nPress the enter key to exit.")
| true |
6d19be295873c9c65fcbb19b9adbca57d700cb64 | vedk21/data_structure_playground | /Arrays/Rearrangement/Pattern/alternate_positive_negative_numbers_solution.py | 1,882 | 4.125 | 4 | # Rearrange array such that positive and negative elements are alternate to each other,
# if positive or negative numbers are more then arrange them all at end
# Time Complexity: O(n)
# Auxiliary Space Complexity: O(1)
# helper functions
def swap(arr, a, b):
arr[a], arr[b] = arr[b], arr[a]
return arr
def rightRotate(arr, size, startIndex, endIndex):
temp = arr[endIndex]
for i in range(endIndex, startIndex, -1):
arr[i] = arr[i - 1]
arr[startIndex] = temp
return arr
def arrange(arr, size):
# divide array into positive and negative parts
i = 0
for j in range(size):
if arr[j] < 0:
arr = swap(arr, j, i)
i += 1
# get index for positive and negative elements
positive = i
negative = 0
# increase negative index by 2 and positive index by 1 and swap elements
while(positive < size and negative < positive and arr[negative] < 0):
arr = swap(arr, positive, negative)
negative += 2
positive += 1
return arr
# Rearrange array such that positive and negative elements are alternate to each other,
# if positive or negative numbers are more then arrange them all at end
# here we maintain the initial sequence
def arrangeInSeq(arr, size):
outOfPlaceIndex = -1
for i in range(size):
if outOfPlaceIndex >= 0:
if (arr[i] < 0 and arr[outOfPlaceIndex] >= 0) or (arr[i] >= 0 and arr[outOfPlaceIndex] < 0):
arr = rightRotate(arr, size, outOfPlaceIndex, i)
# rearrange outOfPlaceIndex
if i - outOfPlaceIndex >= 2:
outOfPlaceIndex += 2
else:
outOfPlaceIndex = -1
if outOfPlaceIndex == -1:
if (arr[i] < 0 and i % 2 == 0) or (arr[i] >= 0 and i % 2 != 0):
outOfPlaceIndex = i
return arr
| true |
e149ad4cc8b69c2addbcc4c5070c00885d26726d | KyrillMetalnikov/HelloWorld | /Temperature.py | 329 | 4.21875 | 4 | celsius = 10
fahrenheit = celsius * 9/5 + 32
print("{} degrees celsius is equal to {} degrees fahrenheit!".format(celsius, fahrenheit))
print("Roses are red")
print("Violets are blue")
print("Sugar is sweet")
print("But I have commitment issues")
print("So I'd rather just be friends")
print("At this point in our relationship")
| true |
c018cea22879247b24084c56731289a2a0f789f5 | abhay-jindal/Coding-Problems | /Minimum Path Sum in Matrix.py | 1,409 | 4.25 | 4 | """
MINIMUM PATH SUM IN MATRIX
https://leetcode.com/problems/minimum-path-sum/
https://www.geeksforgeeks.org/min-cost-path-dp-6/
Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right,
which minimizes the sum of all numbers along its path.
Note: You can only move either down or right at any point in time.
"""
def minPathSum(grid, row=0, column=0):
row = len(grid)
column = len(grid[0])
matrix = [[0 for _ in range(column)] for _ in range(row)]
matrix[0][0] = grid[0][0]
for i in range(1, row):
matrix[i][0] = matrix[i-1][0] + grid[i][0]
for i in range(1, column):
matrix[0][i] = matrix[0][i-1] + grid[0][i]
# For rest of the 2d matrix
for i in range(1, row):
for j in range(1, column):
matrix[i][j] = grid[i][j] + min(matrix[i - 1][j], matrix[i][j - 1])
# In case we can move diagonally as well, consider the previous diagonal element
# matrix[i][j] = grid[i][j] + min(matrix[i - 1][j], matrix[i][j - 1], min[i-1][j-1])
return matrix[row-1][column-1]
rows = int(input("Number of rows: "))
columns = int(input("Number of columns: "))
grid = []
for _ in range(rows):
grid.append(list(map(int,input("\nEnter the elements: ").strip().split()))[:columns])
print(f"Minimum path sum in given matrix: {}")
| true |
a711681f3168d9f733694126d0487f60f39cdf56 | abhay-jindal/Coding-Problems | /Linked List Merge Sort.py | 1,275 | 4.21875 | 4 | """
LINKEDLIST MERGE SORT
"""
# Class to create an Linked list with an Null head pointer
class LinkedList:
def __init__(self):
self.head = None
# sorting of linked list using merge sort in O(nlogn) time complexity
def mergeSort(self, head):
if head is None or head.next is None:
return head
middle = self.getMiddleNode(head)
nextToMiddle = middle.next
middle.next = None
left = self.mergeSort(head)
right = self.mergeSort(nextToMiddle)
sortedList = self.sortedMerge(left, right)
return sortedList
# helper function for merge sort to compare two elements of partitioned linkedlist.
def sortedMerge(self, left, right):
sortedList = None
if left == None:
return right
if right == None:
return left
if left.data <= right.data:
sortedList = left
sortedList.next = self.sortedMerge(left.next, right)
else:
sortedList = right
sortedList.next = self.sortedMerge(left, right.next)
return sortedList
# class to create a new node of an linkedlist
class Node:
def __init__(self,data):
self.data = data
self.next = None
| true |
c2c19d072b086c899b227646826b7ef168e24a78 | abhay-jindal/Coding-Problems | /Array/Zeroes to Left & Right.py | 1,239 | 4.125 | 4 | """
MOVE ZEROES TO LEFT AND RIGHT IN ARRAY
https://leetcode.com/problems/move-zeroes/
Given an integer array nums, move all 0's to the end of it while maintaining the relative order
of the non-zero elements. Note that you must do this in-place without making a copy of the array.
Time complexity: O(n)
"""
def zerosToRight(nums, n):
start = -1
for i in range(n):
if nums[i] == 0:
if start < 0:
start = i
else:
continue
elif start >= 0:
nums[start] = nums[i]
nums[i] = 0
start += 1
return nums
def zerosToLeft(nums, n):
last = -1
for i in range(n-1, -1, -1):
if nums[i] == 0:
if last < 0:
last = i
else:
continue
elif last >= 0:
nums[last] = nums[i]
nums[i] = 0
last -= 1
return nums
if __name__ == "__main__":
n = int(input('Number of elements: '))
array = list(map(int,input("\nEnter the elements: ").strip().split()))[:n]
print(f"Array after moving all zeroes to left: {zerosToLeft(array, n)}")
print(f"Array after moving all zeroes to right: {zerosToRight(array, n)}") | true |
952943db49fe23060e99c65a295d35c1aff7c7d5 | abhay-jindal/Coding-Problems | /LinkedList/check_palindrome.py | 2,523 | 4.21875 | 4 | """
Palindrome Linked List
https://leetcode.com/problems/palindrome-linked-list/
https://www.geeksforgeeks.org/function-to-check-if-a-singly-linked-list-is-palindrome/
Given a singly linked list of characters, write a function that returns true if the given list is a palindrome, else false.
"""
from main import LinkedList
from get_middle_node import get_middle_node
from reverse_linked_list import reverse_list
def is_palindrome(head):
if head is None or head.next is None:
return True
before_mid = head
mid_node = get_middle_node(head) # get middle node of linkedlist from where the next half will be reversed for comparison.
next_to_mid = mid_node.next # store next to mid in temp variable
# make first half of list independent of second half, both lists will be treated as separate lists.
mid_node.next = None
after_mid = reverse_list(next_to_mid) # reverse second half list and store the list in variable
# here the main comparison happens, as soon as we find unequal data, we return False.
while after_mid is not None:
if after_mid.data != before_mid.data:
return False
after_mid = after_mid.next
before_mid = before_mid.next
# if list is odd, then one node will be left after above comparisons, and we simply return True
if before_mid.next is None:
return True
# if list is even, two nodes will be left to compare, compare before_mid and its next and return accordingly.
elif before_mid.data == before_mid.next.data:
return True
return False
# A simple solution is to use a stack of list nodes.
def is_palindrome_using_stack(head):
if head is None or head.next is None:
return True
stack, curr = [], head
while curr is not None:
stack.append(curr.data)
curr = curr.next
curr = head
nodes_to_check = len(stack)//2 # to check first half stack elements with first half of linkedlist
while nodes_to_check != 0 and stack and curr is not None:
temp = stack.pop()
if curr.data != temp:
return False
curr = curr.next
nodes_to_check -= 1
return True
if __name__ == "__main__":
n = int(input('Number of nodes to be inserted: '))
vals = list(map(int,input("\nEnter the node values in space separated manner: ").strip().split()))[:n]
list = LinkedList()
list.insert_nodes(vals)
print(f"Is list a Palindrome: {is_palindrome_using_stack(list.head)}")
| true |
9be41506dd4300748e2b37c19e73cd4e62d107f7 | abhay-jindal/Coding-Problems | /LinkedList/last_nth_node.py | 1,537 | 4.28125 | 4 | """
Clockwise rotation of Linked List
https://leetcode.com/problems/rotate-list/
https://www.geeksforgeeks.org/clockwise-rotation-of-linked-list/
Given a singly linked list and an integer K, the task is to rotate the linked list clockwise to the right by K places.
"""
from main import LinkedList
# function to return nth node from end of the list
def get_nth_from_last(head, n):
# corner cases
if head is None or head.next is None:
return head
# get to the nth node of list from head.
start = head
temp = None
for _ in range(n-1):
start = start.next
# if n is out of range then start will be None, therefore return
if start is None:
return "Nth index out of range!"
# initialize second pointer to again start from head while start pointer which is at nth index reaches the end
# of list.
second_start = head
while start.next is not None:
temp = second_start
start = start.next
second_start = second_start.next
return second_start
if __name__ == "__main__":
n = int(input('Number of nodes to be inserted: '))
vals = list(map(int,input("\nEnter the node values in space separated manner: ").strip().split()))[:n]
k = int(input('Nth node position from end: '))
list = LinkedList()
list.insert_nodes(vals)
print(list) # to print linkedlist representation in 1 -> 2 -> 3 -> None
nth_node = get_nth_from_last(list.head, k)
print(f"Node from end of linked list: {nth_node}")
| true |
45eb0065c98e74c6502b973fc234b6a19ffed92a | bakossandor/DataStructures | /Stacks and Queues/single_array_to_implement_3_stacks.py | 910 | 4.28125 | 4 | # describe how would you implement 3 stack in a single array
# I would divide the array into 3 spaces and use pointer to mark the end of each stack
# [stack1, stack1, stack2, stack2, stack3, stack3]
# [None, None, "1", None, "one", "two"]
class threeStack:
def __init__(self):
self.one = 0
self.two = 0
self.three = 0
self.arr = []
def add(self, data, where):
if where == 1:
self.arr.insert(self.one, data)
self.one += 1
elif where == 2:
self.arr.insert(self.one + self.two, data)
self.two += 1
elif where == 3:
self.arr.insert(self.one + self.two + self.three, data)
self.three += 1
def printArr(self):
print(self.arr)
stack = threeStack()
stack.add("whatup", 3)
stack.add("wher is this", 1)
stack.add("twotwo", 2)
stack.add("one one", 1)
stack.printArr() | true |
b86d42a1ed8bd87ddae179fda23d234096459e0c | bakossandor/DataStructures | /LinkedLists/linked_list.py | 2,278 | 4.28125 | 4 | # Implementing a Linked List data structure
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def add(self, val):
new_node = Node(val)
if self.head is not None:
new_node.next = self.head
self.head = new_node
else:
self.head = new_node
def remove(self, val):
# removing item 2
# [1 -> 2 -> 3]
# [1 -> 3]
if self.head is None:
return False
current_node = self.head
previous_node = None
removed = False
while current_node is not None and removed is False:
if current_node.data is val:
if previous_node is None:
# it means we are at the first iteration
# and just need to change the head pointer
self.head = current_node.next
else:
# if the element is in the middle of the list
# change the next pointer of the previous node
previous_node.next = current_node.next
removed = True
previous_node = current_node
current_node = current_node.next
return removed
def search(self, val):
current_node = self.head
found = False
while current_node is not None and not found:
if current_node.data is val:
found = True
else:
current_node = current_node.next
return found
def print_values(self):
current_node = self.head
while current_node is not None:
print(current_node.data)
current_node = current_node.next
new_list = LinkedList()
for test_val in range(5):
new_list.add(test_val)
# new_list.print_values()
# print(new_list.search(2))
# print(new_list.search("string"))
value_to_add_and_remove = "this is the value"
new_list.add(value_to_add_and_remove)
new_list.print_values()
new_list.search(value_to_add_and_remove)
print(new_list.remove(value_to_add_and_remove))
print(new_list.search(value_to_add_and_remove))
new_list.remove(2)
print("remove 2")
new_list.print_values() | true |
97d430a520e681cd8a0db52c1610436583bf9889 | raj-rox/Coding-Challenges | /hurdle.py | 946 | 4.125 | 4 | #1st attempt. DONE. bakwaas
#https://www.hackerrank.com/challenges/the-hurdle-race/problem
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'hurdleRace' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
# 1. INTEGER k
# 2. INTEGER_ARRAY height
#
def hurdleRace(k, height):
# Write your code here
max=height[0]
for i in height:
if max<i:
max=i
if max<=k:
return 0
else:
return (max-k)
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
first_multiple_input = input().rstrip().split()
n = int(first_multiple_input[0])
k = int(first_multiple_input[1])
height = list(map(int, input().rstrip().split()))
result = hurdleRace(k, height)
fptr.write(str(result) + '\n')
fptr.close()
| true |
6f134495fa15c220c501a82206a33839d0083079 | tanbir6666/test-01 | /starting codes/python after 1 hour.py | 808 | 4.21875 | 4 | newString="hello Tanbir";
print(type(newString));
newstring_value= newString[5:]
print(newstring_value);
print(newstring_value.upper());
print(newstring_value.lower());
print(newstring_value.replace("Tanbir", "Taohid"))
print(newstring_value);
#replace string
whatTosay=newString.replace("hello","how are you");
print(whatTosay)
# loop for array or list
def loop(listItem):
print("Primary stage :",listItem)
print("loop through every pice :")
itemNumnber=0;
for items in listItem:
itemNumnber+=1
print(itemNumnber," : ",items);
#splits
splitSay=whatTosay.split(" ")
print(splitSay);
loop(splitSay);
splitSentence="hi whats up ! how you are doing ? I am coming Buddy. Are you ready ?";
splitWord2 = splitSentence.split("?")
print(splitWord2[1])
loop(splitWord2)
| true |
9c6627692d958ddf64b87aaa495ce7e315dc8e8f | simon-fj-russell/ds_python | /linear_regression.py | 2,509 | 4.1875 | 4 | # Linear Regression model using stats models
# First import the modules
import pandas as pd
import statsmodels.api as sm
import seaborn as sns
import matplotlib.pyplot as plt
sns.set()
# User made functions
# Use Stats models to train a linear model
# Using OLS -> ordinary least squares
def train_lr_model(x, y):
# X is the feature column(s) of the dataframe (can be in the format df['Column Title'])
# y is the target column of the dataframe (can be in the format df['Column Title'])
x = sm.add_constant(x) #We add the intercept term
model = sm.OLS(y, x).fit()
# print out the summary of the model
print(model.summary())
return model
# Plot observed and predicted values with respect to feature 'x' in log scale.
# THERE CAN ONLY BE ONE FEATURE COLUMN (at the moment)
def plot_observed_vs_predicted(x, y, pred):
# X is the feature column(s) of the dataframe (can be in the format df['Column Title'])
# y is the target column of the dataframe (can be in the format df['Column Title'])
fig, ax = plt.subplots()
plt.plot(x, y, label='Target Column') # Change label to your target column.
plt.plot(x, pred, label='Regression')
ax.set(xlabel='X Axis', ylabel='Y Axis')
ax.set_xscale('log') # If you need to log one of the axis
plt.title("Sample Plot") # Title of the graph
plt.show()
# Read as ether csv or from clipboard
data = pd.read_csv('data.csv')
data = pd.read_clipboard()
# Check out the header to make sure everything is there.
print(data.columns.values)
# work out the correlation between the feature columns and the target column
correlation = data.corr().loc[['Feature Column 1','Feature Column 2','Feature Column 3',...],['Target Column']]
print(correlation)
# Select the feature with the highest correlation and train the model on it.
lr1 = train_lr_model(data['Feature Column 1'],data['Target Column'])
# There can be more then one feature column, input x in the format data[['Feature Column 1','Feature Column 2','Feature Column 3',...]]
lr2 = train_lr_model(data[['Feature Column 1','Feature Column 2','Feature Column 3',...]],data['Target Column'])
# Now you have the model as lr1, use it to predict the Target Column based on a Feature Column
pred = lr1.predict(sm.add_constant(data['Feature Column']))
print(pred.head(10))
# Once you have the predicted values you can feed them into the plot function to view the results vs actual data
plot_observed_vs_predicted(data['Feature Column'], data['Target Column'], pred)
| true |
2e8a17d29fd352af98d0cc4b2b53d9d543601f6a | trenton1199/Python-mon-K | /Reminder.py | 2,157 | 4.34375 | 4 | from datetime import date
import os
def pdf():
pdf = input(f"would you like to turn {file_name} into a pdf file? [y/n] ").lower()
if pdf == 'y':
pdf_name = input("what would you like the pdf file to be named ") + ".pdf"
font_size = int(input("what would you like your font size to be?"))
# Python program to convert
# text file to pdf file
from fpdf import FPDF
# save FPDF() class into
# a variable pdf
pdf = FPDF()
# Add a page
pdf.add_page()
# set style and size of font
# that you want in the pdf
pdf.set_font("Arial", size=font_size)
# open the text file in read mode
f = open(file_name, "r")
# insert the texts in pdf
for x in f:
pdf.cell(200, 10, txt=x, ln=1, align='C')
# save the pdf with name .pdf
pdf.output(pdf_name)
question = input("Option A: create a new file or option B: continue with another file [a/b]").lower()
if question == 'a':
date = str(date.today())
file_name = input("what would you like the file name of this Reminder to be:") + ".txt"
body = input("write your reminder here:")
with open(file_name, 'w') as f:
f.write(f"date: ")
f.write(date)
f.write(os.linesep)
f.write(body)
f.write(os.linesep)
f.write(
'----------------------------------------------------------------------------------------------------------------------------')
f.write(os.linesep)
pdf()
elif question == 'b':
file_name = input("what is the previous file name for the To do list? (please do not provide file type):") + ".txt"
date = str(date.today())
body = input("write your reminder here:")
with open(file_name, 'a') as f:
f.write(f"date: ")
f.write(date)
f.write(os.linesep)
f.write("To do:")
f.write(body)
f.write(os.linesep)
f.write(
'----------------------------------------------------------------------------------------------------------------------------')
f.write(os.linesep)
pdf()
| true |
2dfad5d7fcf6789c93002064f621691677899758 | kraftpunk97-zz/Fundamentals-ML-Algos | /k_means.py | 2,338 | 4.1875 | 4 | #! /usr/local/bin/python3
'''Implementing the k-Means Clustering Algorithm from scratch'''
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
def kmeans(dataset, num_clusters=3, max_iter=10):
'''
The k-means implemention
'''
m, n = dataset.shape
cluster_arr = np.zeros(dtype=int, shape=(m,))
# Initialize clusters
cluster_centroids = np.array(dataset[np.random.randint(low=0,
high=m,
size=num_clusters
)])
for i in range(max_iter):
# To find which cluster a point belongs to, just find the cluster centroid
# closest to that point.
for i in range(m):
cluster_arr[i] = np.argmin(np.linalg.norm(cluster_centroids - dataset[i], axis=1))
# This is where we update the cluster centroids to the mean position of
# the datapoints in that cluster
for i in range(num_clusters):
cluster_family = dataset[np.where(cluster_arr == i)]
cluster_centroids[i] = np.mean(cluster_family, axis=0)
return cluster_centroids, cluster_arr
def nice_plot(dataset, num_clusters, cluster_arr, cluster_centroids):
'''A utility function that shows the distribution of data points and the cluster they belong to.'''
color_list = ('red', 'blue', 'green', 'black', 'brown', 'turquoise')
plt.figure()
for i in range(num_clusters):
idx = np.where(cluster_arr == i)
plt.scatter(dataset[idx, 0], dataset[idx, 1], c=color_list[i], alpha=0.4)
plt.scatter(cluster_centroids[:, 0], cluster_centroids[:, 1], c='white')
plt.show()
data = pd.read_csv('speeding_data.csv', header=0, delimiter='\t')
data = data.drop('Driver_ID', axis=1)
dataset = np.array(data)
print("First, let's see how the points are distributed...")
data.plot(x='Distance_Feature', y='Speeding_Feature', kind='scatter', alpha=0.4,
c='black')
plt.show()
print('Running the kmeans algorithm...')
num_clusters = 4
num_iterations = 8
cluster_centroids, cluster_arr = kmeans(dataset, num_clusters, num_iterations)
print('Alogrithm ran successfully. Plotting results')
nice_plot(dataset, num_clusters, cluster_arr, cluster_centroids)
| true |
ab87e9277d7605bb7353c381f192949b40abcc49 | rprustagi/EL-Programming-with-Python | /MT-Python-Programming/MT-Programs/hanoi.py | 2,368 | 4.5 | 4 | #!/usr/bin/env python3
""" turtle-example-suite:
tdemo_minimal_hanoi.py
A minimal 'Towers of Hanoi' animation:
A tower of N discs is transferred from the
left to the right peg.
The value of N is specified by command line argument
An imho quite elegant and concise
implementation using a tower class, which
is derived from the built-in type list.
Discs are turtles with shape "square", but
stretched to rectangles by shapesize()
---------------------------------------
To exit press STOP button
---------------------------------------
"""
from turtle import *
import sys
class Disc(Turtle):
def __init__(self, n):
Turtle.__init__(self, shape="square", visible=False)
self.pu()
self.shapesize(1.5, n*1.5, 2) # square-->rectangle
self.fillcolor(n/(num_of_disks * 1.0), 1.0, 1-n/(num_of_disks * 1.0))
self.st()
class Tower(list):
"Hanoi tower, a subclass of built-in type list"
def __init__(self, x):
"create an empty tower. x is x-position of peg"
self.x = x
def push(self, d):
d.setx(self.x)
d.sety(-150+34*len(self))
self.append(d)
def pop(self):
d = list.pop(self)
d.sety(150)
return d
def hanoi(n, from_, with_, to_):
if n > 0:
hanoi(n-1, from_, to_, with_)
to_.push(from_.pop())
#textinput("Hanoi Tower", "Press any key to continue")
hanoi(n-1, with_, from_, to_)
def play():
onkey(None,"s")
clear()
try:
hanoi(num_of_disks, t1, t2, t3)
write("press q to exit",
align="center", font=("Courier", 16, "bold"))
except Terminator:
pass # turtledemo user pressed STOP
def main():
global t1, t2, t3
ht(); penup(); goto(0, -225) # writer turtle
t1 = Tower(-250)
t2 = Tower(0)
t3 = Tower(250)
# make tower of num_of_disks discs
for i in range(num_of_disks,0,-1):
t1.push(Disc(i))
# prepare spartanic user interface ;-)
write("press s to start game, q to quit",
align="center", font=("Courier", 16, "bold"))
onkey(play, "s")
onkey(bye,"q")
listen()
return "EVENTLOOP"
if __name__=="__main__":
global num_of_disks
num_of_disks = 5
if (len(sys.argv) > 1):
num_of_disks = int(sys.argv[1])
msg = main()
print(msg)
mainloop()
| true |
94fd0458b2282379e6e720d07581fd15467d0581 | Anirban2404/HackerRank_Stat | /CLT.py | 2,013 | 4.125 | 4 | #!/bin/python
import sys
'''
A large elevator can transport a maximum of 9800 pounds. Suppose a load of cargo containing 49 boxes
must be transported via the elevator. The box weight of this type of cargo follows a distribution
with a mean of 205 pounds and a standard deviation of 15 pounds. Based on this information,
what is the probability that 49 all boxes can be safely loaded into the freight elevator and transported?
'''
'''
The number of tickets purchased by each student for the University X vs. University Y football game follows
a distribution that has a mean of 2.4 and a standard deviation of 2.0.
A few hours before the game starts, 100 eager students line up to purchase last-minute tickets. If there are
only 250 tickets left, what is the probability that all 100 students will be able to purchase tickets?
'''
'''
You have a sample of 100 values from a population with mean 500 and with standard deviation 80.
Compute the interval that covers the middle 95% of the distribution of the sample mean;
in other words, compute A and B such that P(A < X < B ) = 0.95. Use the value of z = 1.96.
Note that z is the z-score.
'''
# MAIN #
if __name__ == "__main__":
#max = int(raw_input().strip())
num_of_elements = int(raw_input().strip())
#mean = int(raw_input().strip())
#std_dev = int(raw_input().strip())
mean = float(raw_input().strip())
std_dev = float(raw_input().strip())
prob = float(raw_input().strip())
Z_score = float(raw_input().strip())
# P ( Xk << 98800 ) = P ( X - n * mean / n^.5 * std_dev)
# z_score = (max - num_of_elements * mean) / ((num_of_elements ** 0.5) * std_dev)
# print z_score
# z_05 = 0.6915
#z_233 = 0.0099
#print z_233
# print z_05
# Z_score = (A - mean) / (std_dev/ (num_of_elements ** 0.5))
A = - Z_score * (std_dev / (num_of_elements ** 0.5)) + mean
print A
B = Z_score * (std_dev/ (num_of_elements ** 0.5)) + mean
print B | true |
4aa692633576198ea6580dfd97e2b068d5dbe920 | AbhijeetDixit/MyAdventuresWithPython | /OOPython/ClassesExample2.py | 1,927 | 4.34375 | 4 | ''' This example shows the use of multiple classes in a single program'''
class City:
def __init__(self, name):
self.name = name
self.instituteCount = 0
self.instituteList = []
pass
def addInstitute(self, instObj):
self.instituteList.append(instObj)
self.instituteCount += 1
def displayInstitute(self):
print 'instituteCount %d'%self.instituteCount
for inst in self.instituteList:
inst.displayInfo()
pass
def displayCity(self):
print '________________ City ________________'
print 'CityName : %s'%self.name
print 'City Institutes'
self.displayInstitute()
class institute:
def __init__(self, name):
self.name = name
self.numDepts = 0
self.depts = []
def addDepts(self, deptname):
self.depts.append(deptname)
self.numDepts += 1
def displayInfo(self):
print 'name : %s'%self.name
print 'dept Count : %d'%self.numDepts
i = 0
for dept in self.depts:
print '%d. %s'%(i+1, dept)
def main():
print 'Creating a new City'
cName = raw_input('Enter City Name : ')
city1 = City(cName)
print 'Displaying new City Information'
city1.displayCity()
print 'Creating a new institute'
iName = raw_input('Enter the name of institute : ')
institute1 = institute(iName)
print 'Displaying newly created institute'
institute1.displayInfo()
response = raw_input('Should we add institute to the created city? (y/n) : ')
if response == "y" or response == "Y":
city1.addInstitute(institute1)
print 'The created city now becomes'
city1.displayCity()
pass
print 'We need to add atleast 2 depts in the institute'
dept1 = raw_input('Add first dept name : ')
institute1.addDepts(dept1)
dept2 = raw_input('Add second dept name : ')
institute1.addDepts(dept2)
if response == "y" or response == "Y":
print 'The city now becomes : '
city1.displayCity()
else:
print 'The new department becomes : '
institute1.displayInfo()
if __name__ == '__main__':
main() | true |
8720d528fb634c4a61eeb5b33a3405ee87883ada | Siddhant-Sr/Turtle_race | /main.py | 1,006 | 4.21875 | 4 | from turtle import Turtle, Screen
import random
race = False
screen = Screen()
screen.setup(width= 500, height= 400)
color = ["red", "yellow", "purple", "pink", "brown", "blue"]
y = [-70, -40, -10, 20, 50, 80]
bet = screen.textinput(title="make your bet", prompt="Which turtle will win the race? Enter a color")
all_turtle = []
for turtle_index in range(0, 6):
new_turtle = Turtle(shape="turtle")
new_turtle.color(color[turtle_index])
new_turtle.penup()
new_turtle.goto(x=-230, y=y[turtle_index])
all_turtle.append(new_turtle)
if bet:
race = True
while race:
for turtles in all_turtle:
if turtles.xcor()>230:
race =False
winning_color = turtles.pencolor()
if winning_color == bet:
print(f"You've won! The {winning_color} turtle is the winner ")
else:
print(f"You've lost! The {winning_color} turtle is the winner ")
turtles.forward(random.randint(0,10))
screen.exitonclick()
| true |
3c7665bbadb5ae2903b9b5edfda93d3a78ada475 | dgupta3102/python_L1 | /PythonL1_Q6.py | 916 | 4.25 | 4 | # Write a program to read string and print each character separately.
# a) Slice the string using slice operator [:] slice the portion the strings to create a sub strings.
# b) Repeat the string 100 times using repeat operator *
# c) Read string 2 and concatenate with other string using + operator.
Word = input("Please Enter the String : ")
sent = Word
for i in range(len(Word)):
print("The Character at %d Index Position = %c" % (i, Word[i]))
# Slice operation --- starts from 2nd index till n-1 index
print("Slicing-->",sent[2:5])
# b) Repeat the string 100 times using repeat operator *
print("Repeat string 100 times ..",(sent[0:5]*100))
# c) Read string 2 and concatenate with other string using + operator.
str1 = input("Enter String 1 ")
str2 = input("Enter String 2 ")
# concatenation of 2 strings using + operator
str3 = str1+" "+str2
print(str3)
| true |
347ac39407381d1d852124102d38e8e9f746277f | dgupta3102/python_L1 | /PythonL1_Q19.py | 969 | 4.21875 | 4 | # Using loop structures print even numbers between 1 to 100.
# a) By using For loop, use continue/ break/ pass statement to skip odd numbers.
# i) Break the loop if the value is 50
print("part 1a --------------")
for j in range(1, 101):
if j % 2 != 0: # checks the number is Odd and Pass
pass
else:
print(j) # prints the number
if j == 50: # checks if the number is 50
break # it will break the loop and come out
# ii) Use continue for the values 10,20,30,40,50
print("Part 2")
for i in range(1, 101):
# print(i)
if i % 2 == 0: # checks the number is even
print(i) # prints the number
if i == 10:
continue
elif i == 20:
continue
elif i == 30:
continue
elif i == 40:
continue
elif i == 50: # checks if the number is 50
break # it will break the loop and come out
| true |
ec2ae4d1db1811fcca703d6a35ddf1732e481e2a | riteshrai11786/python-learning | /InsertionSort.py | 1,600 | 4.40625 | 4 | # My python practice programs
# function for sorting the list of integers
def insertion_sort(L):
# Loop over the list and sort it through insertion algo
for index in range(1, len(L)):
# define key, which is the current element we are using for sorting
key = L[index]
# Move elements of arr[0..i-1], that are
# greater than key, to one position ahead
# of their current position
pivot_idx = index - 1
# Loop over the list and compare
while pivot_idx >= 0 and key < L[pivot_idx]:
L[pivot_idx + 1] = L[pivot_idx]
pivot_idx -= 1
# assign the key to next index
L[pivot_idx + 1] = key
# Insertion sort with recursion
def recursive_insertion_sort(L, n):
# Base case
if n <= 1:
return
# Sort n-1 elements
recursive_insertion_sort(L, n - 1)
'''Insert last element at its correct position
in sorted array.'''
last = L[n - 1]
j = n - 2
# loop over the array and sort
while j >= 0 and last < L[j]:
L[j + 1] = L[j]
j -= 1
# assign the last element to original position
L[j + 1] = last
# Driver code to test above
arr = [12, 11, 13, 5, 6]
print(arr)
insertion_sort(arr)
print("Sorted array:");
for i in range(len(arr)):
print(arr[i], end=' ')
print()
# A utility function to print an array of size n
def printArray(arr, n):
for i in range(n):
print(arr[i], end=' ')
# Driver program to test insertion sort
arr = [12, 11, 13, 5, 6]
n = len(arr)
recursive_insertion_sort(arr, n)
printArray(arr, n)
| true |
93481419afcb5937eca359b323e038e7e29c6ad9 | rzfeeser/20200831python | /monty_python3.py | 1,075 | 4.125 | 4 | #!/usr/bin/python3
round = 0
answer = " "
while round < 3:
round += 1 # increase the round counter by 1
answer = input('Finish the movie title, "Monty Python\'s The Life of ______": ')
# transform answer into something "common" to test
answer = answer.lower()
# Correct Answer
if answer == "brian":
print("Correct!")
break # you gave an answer... escape the while loop!
# Easter Egg
elif answer == "shrubbery":
print("We are no longer the knights who say Ni! We are now the knights\
who say ekki-ekki-ekki-pitang-zoom-boing!")
break # you gave an answer... escape the while loop!
# Easter Egg 2
elif answer == "tim":
print("Oh great wizard! What do they call you?\nWizard: Some call me... Tim...")
break
# if counter reaches 3
elif round == 3: # logic to ensure round has not yet reached 3
print("Sorry, the answer was Brian.")
else: # if answer was wrong
print("Sorry. Try again!")
# say goodbye!
print("Thanks for playing!")
| true |
4c5a2f9b26e6d4fa7c3250b3043d1df5865b76c8 | g-boy-repo/shoppinglist | /shopping_list_2.py | 2,162 | 4.5 | 4 | # Have a HELP command
# Have a SHOW command
# clean code up in general
#make a list to hold onto our items
shopping_list = []
def show_help():
#print out instructions on how to use the app
print("What should we pick up at the store?")
print("""
Enter 'DONE' to stop addig items.
Enter 'HELP' for this help.
Enter 'SHOW' to see your current list.
""") #We used miltiline comments here
#This part will show the list we have already listed
def show_list():
#print out the list.
print("Here's your list:")
for item in shopping_list:
print(item)
#This function will take new lists.
def add_to_list(new_item):
#add new items to our list
shopping_list.append(new_item)
print("Added {}. List now has {} items.".format(new_item, len(shopping_list))) # first {} contains somthing and second {} contains some number. len stands for length of the shopping_list. So len is a function that tells us how many things are in a list or an iterable.
#Let's just show the help right here right above the while true. So that way the hlp gets shown before the while loop starts running.
show_help()
while True:
#ask for new items
new_item = input("> ")
#be able to quit the app
if new_item == 'DONE': #What this does is when you type in DONE the program quit using the break keyword.
break
elif new_item == 'HELP': #Here we need to check to see if they put in help
show_help() #Calling out function named show_help()
continue # Since we don't want to add help into our list, and we don't wanna break, we don't wanna end the loop. We actually just wanna go to the next step of the loop. We wanna run the loop again so we say continue.
elif new_item == 'SHOW': #Here by typing SHOW this show up our list that we have listed down.
show_list() #Calling out our show_list function to display the list.
continue #And again you wanna go on to the next step of the loop so we say continue again.
add_to_list(new_item) #We could do an else here but we dont have to. We called funcion add_to_list(new_item) with its parameter named new_item.
show_list() #Calling function named show_list
| true |
3edf29f645ecb4af1167359eab4c910d47c40805 | sankar-vs/Python-and-MySQL | /Data Structures/Basic Program/41_Convert_to_binary.py | 519 | 4.3125 | 4 | '''
@Author: Sankar
@Date: 2021-04-08 15:20:25
@Last Modified by: Sankar
@Last Modified time: 2021-04-08 15:27:09
@Title : Basic_Python-41
'''
'''
Write a Python program to convert an integer to binary keep leading zeros.
Sample data : 50
Expected output : 00001100, 0000001100
'''
decimal = 50
print("Convertion to binary from {} is: {:08b}".format(decimal, decimal))
print("Convertion to binary from {} is: {:010b}".format(decimal, decimal))
print("Convertion to binary from {} is: {:012b}".format(decimal, decimal)) | true |
67bdb85c94a8874623c89d0ac74a9b1464e5c391 | sankar-vs/Python-and-MySQL | /Data Structures/List/8_Find_list_of_words.py | 739 | 4.5 | 4 | '''
@Author: Sankar
@Date: 2021-04-09 12:36:25
@Last Modified by: Sankar
@Last Modified time: 2021-04-09 12:42:09
@Title : List_Python-8
'''
'''
Write a Python program to find the list of words that are longer than n from a
given list of words.
'''
n = 3
list = ['Hi','Sankar','How','are','you',"brotha"]
def countWord(n, list):
'''
Description:
To find the list of words that are longer than n from a
given list of words.
Parameter:
n (int)
list (list)
Return
count (int)
'''
count = 0
for i in list:
if (len(i)>n):
count += 1
return count
print("From list {} the words that are greater than {} is: {}".format(list, n, countWord(n, list))) | true |
1e16341185e46f060a7a50393d5ec47275f6b009 | sankar-vs/Python-and-MySQL | /Data Structures/List/3_Smallest_number.py | 440 | 4.15625 | 4 | '''
@Author: Sankar
@Date: 2021-04-09 12:07:25
@Last Modified by: Sankar
@Last Modified time: 2021-04-09 12:13:09
@Title : List_Python-3
'''
'''
Write a Python program to get the smallest number from a list.
'''
list = [1,2,3,4,6,10,0]
minimum = list[0]
for i in list:
if (minimum>i):
minimum = i
print("Minimum of list {} is: {}".format(list, minimum))
print("Minimum of list using function {} is: {}".format(list, min(list))) | true |
08a53c3d25d935e95443f1dfa3d2cefdd10237fb | sankar-vs/Python-and-MySQL | /Data Structures/Array/4_Remove_first_element.py | 482 | 4.1875 | 4 | '''
@Author: Sankar
@Date: 2021-04-09 07:46:25
@Last Modified by: Sankar
@Last Modified time: 2021-04-09 07:51:09
@Title : Array_Python-4
'''
'''
Write a Python program to remove the first occurrence of a specified element from an
array.
'''
array = []
for i in range(5):
element = int(input("Enter Element {} in array: ".format(i)))
array.append(element)
arrayResult = array
print("Remove first occurance of {} in array {} is: {}".format(3, array, arrayResult.remove(3))) | true |
2b3f22bb3fcad13848f40e0c938c603acb2f3959 | sankar-vs/Python-and-MySQL | /Functional Programs/Distance.py | 1,357 | 4.28125 | 4 | '''
@Author: Sankar
@Date: 2021-04-01 09:06:25
@Last Modified by: Sankar
@Last Modified time: 2021-04-02 12:25:37
@Title : Euclidean Distance
'''
import re
def num_regex_int(x):
'''
Description:
Get input from user, check whether the input is matching with the pattern
expression, if True then return
Parameter:
x (str) : Statement to be printed to take the the inputs from user
Return:
num (int): input from user
'''
while True:
try:
num = input(x)
pattern = "^([+-]?[0-9]{,8})$"
result = re.match(pattern, num)
if (result):
return int(num)
except:
pass
print("Only numeric integer")
def calculateEuclideanDistance():
'''
Description:
Getting the x and y co-ordinates from the user and
Calculate the Euclidean Distance by the given formula x**x+y**y
and print the distance
Parameter:
None
Return:
None
'''
try:
x = num_regex_int("Enter x co-ordinate: ")
y = num_regex_int("Enter y co-ordinate: ")
distance = pow(abs(x),abs(x))+pow(abs(y),abs(y))
print("Euclidean distance from the point ({}, {}) to the origin (0, 0) is: {}".format(x, y, distance))
except:
pass
calculateEuclideanDistance() | true |
55f9b7cd0aa5a2b10cd819e5e3e6020728e2c670 | Dilshodbek23/Python-lessons | /38_4.py | 366 | 4.4375 | 4 | # Python Standard Libraries
# The user was asked to enter a phone number. The entered value was checked against the template.
import re
regex = "^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$"
phone = input("Please enter phone number: ")
if re.match(regex, phone):
print(f"phone: {phone}")
else:
print(f"phone number is incorrecr")
| true |
38c79868e60d20c9a6d5e384b406c3656f565ffb | Haldgerd/Simple_coffee_machine_project | /main.py | 2,305 | 4.5 | 4 | """
An attempt to simulate a simple coffee machine and it's functionality. This version is used as in depth exercise, before
writing same program using OOP later within the programming course.
The main requirements where:
1. Output a report on resources.
2. Receive user input, referring to type of coffee they want.
3. Check for sufficient resources.
4. Process coin payment. Check if transaction is successful. (refund if payment is not sufficient. )
5. Return amount of change if needed.
"""
from functions_module import clear, output_ascii_title, money_function, resource_output_formatter, \
resource_checker_function, resource_modifier_function
# MAIN PROGRAM
off = False
print(output_ascii_title())
while not off:
order = input("\nWhat would you like? (espresso/latte/cappuccino): ").lower()
if order not in ["latte", "espresso", "cappuccino"]:
if order == "off":
break
elif order == "report":
resource_output_formatter()
continue
else:
print("Unknown coffee request.")
continue
if resource_checker_function(order):
print("Please insert coins.")
euro_coins = int(input("How many euros: "))
cent_50 = int(input("How many 50 cents: "))
cent_20 = int(input("How many 20 cents: "))
cent_10 = int(input("How many 10 cents: "))
is_enough_money = money_function(order, euro_coins, cent_50, cent_20, cent_10)
if not is_enough_money:
clear()
continue
resource_modifier_function(order)
print(f"Here is your {order}. Enjoy!")
clear()
else:
continue
"""
PSEUDO CODE:
if off: DONE!!
maintenance, break from loop, exit coffee machine.
elif report:
show report on resources
else:
1.check resource quantity (if sufficient or not) when user asks for drink. If there's not enough let user know.
2. if resources are OK., ask for coins -PAYMENT.
3. check if money given is sufficient in amount. ADD profit to machine registry if so, else let user know they
didn't give enough money.
4. if all ok, give drink. (behind scenes: take away resources, add money)
"""
print("\nMaintenance time! Turning off.")
| true |
2370915fa2514143fc56ea1e055b70805d22d170 | samaracanjura/Coding-Portfolio | /Python/Shapes.py | 996 | 4.375 | 4 | #Samara Canjura
#shapes.py
#Finding the area and perimeter of a square, and finding the circumference and area of a circle.
import math # Python Library needed for access to math.pi and math.pow
def main():
inNum = getInput("Input some number: ")
while inNum != 0: #Loop ends when zero input
if inNum > 0:
calculate_square(inNum)
else:
calculate_circle(inNum)
inNum = getInput("Input next number: ")
print("End of Program")
def calculate_square(side):
perimeter = side * 4
print("Square with side", side, "has a perimeter", perimeter)
print("Square with side", side, "has a area", perimeter)
def calculate_circle(radius):
radius = math.fabs(radius)
pi = math.pi
r = radius
c = 2*pi*r
a = pi*r*r
print("Circle w/ radius", radius, "has a circumference", c)
print("Circle w/ radius", radius, "has a area", c)
def getInput(prompt):
number = float(input(prompt))
return number
main()
| true |
74c00f287ec85a3a8ac0b3b9fd8f3d0bd6babe70 | psmzakaria/Practical-1-2 | /Practical2Q1.py | 478 | 4.125 | 4 | # Question 1
# Write codes for the incomplete program below so that it sums up all the digits in the integer variable num (9+3+2) and displays the output as a sum.
num = int(input("Enter your Number Here"))
print(num)
# Getting the first digit number
digit1 = int(num/100)
print(digit1)
# Getting the second digit number
digit2 = (int(num/10) % 10)
print(digit2)
# Getting the third digit number
digit3 = (num % 10)
print(digit3)
sum = digit1 + digit2 + digit3
print(sum) | true |
5de721579c27704e39cf12b1183a1eebea4d22d4 | lion137/Python-Algorithms | /shuffling.py | 441 | 4.1875 | 4 | # algorithm for shuffling given subscriptable data structure (Knuth)
import random
def swap(alist, i, j):
"""swaps input lists i, j elements"""
alist[i], alist[j] = alist[j], alist[i]
def shuffle(data):
"""randomly shuffles element in the input data"""
n = len(data)
for token in range(n - 1):
swap(data, token, random.randrange(token, n))
alist1 = [1, 3, 5, 6]
print(alist1)
shuffle(alist1)
print(alist1)
| true |
f882f9dcf344950cc893bf1e2fb49ffb103d168e | chenjyr/AlgorithmProblems | /HackerRank/Search/FindTheMedian.py | 1,652 | 4.3125 | 4 | """
In the Quicksort challenges, you sorted an entire array.
Sometimes, you just need specific information about a list of numbers,
and doing a full sort would be unnecessary.
Can you figure out a way to use your partition code to find the median in an array?
Challenge
Given a list of numbers, can you find the median?
Input Format
There will be two lines of input:
n - the size of the array
ar - n numbers that makes up the array
Output Format
Output one integer, the median.
Constraints
1<= n <= 1000001
-10000 <= x <= 10000 , x ∈ ar
There will be an odd number of elements.
Sample Input
7
0 1 2 4 6 5 3
Sample Output
3
"""
from random import randint
def swap(nums, i, j):
nums[i], nums[j] = nums[j], nums[i]
def partition(nums, index):
swap(nums, 0, index)
pivot = nums[0]
lesser_list = [x for x in nums[1:] if x <= pivot]
greater_list = [x for x in nums[1:] if x > pivot]
pivot_index = len(lesser_list)
return pivot_index, lesser_list + [pivot] + greater_list
def median(nums):
def helper(nums, index):
median_num = -1
rand_index, nums = partition(nums, randint(0, len(nums) - 1))
result = nums[index]
if rand_index < index: result = helper(nums[rand_index+1:], index - rand_index - 1)
elif rand_index > index: result = helper(nums[:rand_index], index)
return result
return helper(nums, len(nums) / 2)
if __name__ == "__main__":
_ = raw_input()
nums = map(int, raw_input().split())
if nums and len(nums) > 0:
print median(nums)
| true |
0adf7ed3f2301c043ef269a366a90c3970673b1f | chenjyr/AlgorithmProblems | /HackerRank/Sorting/Quicksort1.py | 2,143 | 4.21875 | 4 | """
The previous challenges covered Insertion Sort, which is a simple and intuitive sorting algorithm.
Insertion Sort has a running time of O(N2) which isn’t fast enough for most purposes.
Instead, sorting in the real-world is done with faster algorithms like Quicksort,
which will be covered in these challenges.
The first step of Quicksort is to partition an array into two parts.
Challenge
Given an array ar and a number p, can you partition the array,
so that all elements greater than p are to the right of it
and all the numbers smaller than p are to its left?
Besides for necessary partitioning, the numbers should otherwise remain in the same order.
This means if n1 was before n2 in the original array,
it must remain before it in the partitioned array, unless n1 > p > n2.
Guideline - In this challenge, you do not need to move around the numbers ‘in-place’.
This means you can create 2 lists and combine them at the end.
Input Format
You will be given an array of integers. The number p is the first element in ar.
There are 2 lines of input:
n - the number of elements in the array ar
the n numbers of ar (including p at the beginning)
Output Format
Print out the numbers of the partitioned array on one line.
Constraints
1<=n<=1000
-1000<=x<= 1000 , x ∈ ar
All elements will be distinct
Sample Input
5
4 5 3 7 2
Sample Output
3 2 4 5 7
Explanation
p = 4.
The 5 was moved to the right of the 4, 2 was moved to the left of 4
and the 3 is also moved to the left of 4.
The numbers otherwise remained in the same order.
Task
Complete the method partition which takes in one parameter -
an array ar to be partitioned,
where the first element in it is the number p.
"""
def partition(nums):
pivot = nums[0]
return [x for x in nums[1:] if x <= pivot] + [pivot] + [x for x in nums[1:] if x > pivot]
if __name__ == "__main__":
_ = raw_input()
nums = map(int, raw_input().split())
print " ".join(map(str, partition(nums)))
| true |
248f5308062ddc2b896413a99dc9d5c3f3c29ac6 | chenjyr/AlgorithmProblems | /HackerRank/Sorting/InsertionSort2.py | 1,852 | 4.625 | 5 | """
In Insertion Sort Part 1, you sorted one element into an array.
Using the same approach repeatedly, can you sort an entire unsorted array?
Guideline: You already can place an element into a sorted array.
How can you use that code to build up a sorted array, one element at a time?
Note that in the first step, when you consider an element with just the first element -
that is already “sorted” since there’s nothing to its left that is smaller than it.
In this challenge, don’t print every time you move an element.
Instead, print the array every time an element is “inserted” into the array
in (what is currently) its correct place.
Since the array composed of just the first element is already “sorted”,
begin printing from the second element and on.
Input Format
There will be two lines of input:
s - the size of the array
ar - the list of numbers that makes up the array
Output Format
On each line, output the entire array at every iteration
Constraints
1<=s<=1000
-10000<=x<= 10000 , x ∈ ar
Sample Input
6
1 4 3 5 6 2
Sample Output
1 4 3 5 6 2
1 3 4 5 6 2
1 3 4 5 6 2
1 3 4 5 6 2
1 2 3 4 5 6
Explanation
Insertion Sort checks the ‘4’ first and doesn’t need to move it, so it just prints out the array.
Next, the 3 is inserted next to the 4 and the array is printed out.
This continues one element at a time until the entire array is sorted.
"""
def insertion_sort(nums):
for i in xrange(1, len(nums)):
this_num = nums[i]
j = i - 1
while j >= 0 and nums[j] > this_num:
nums[j+1] = nums[j]
j-= 1
nums[j+1] = this_num
print_nums(nums)
def print_nums(nums):
print " ".join(map(str, nums))
if __name__ == "__main__":
_ = raw_input()
nums = [int(i) for i in raw_input().strip().split()]
insertion_sort(nums)
| true |
c2098e9dd0710577a8bcac533b34b3bbee7b3a19 | NishuOberoi1996/IF_ELSE | /num_alph_chatr.py | 206 | 4.15625 | 4 | num=input("enter anything:-")
if num>="a" and num<="z" or num>="A" and num<="Z":
print("it is a alphabet")
elif num>="0" and num<="9":
print("it is number")
else:
print("Special Character") | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.