blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
eb8ac907b35bacba795aae007f4d3adb03a77e23 | monicajoa/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/4-print_square.py | 703 | 4.5 | 4 | #!/usr/bin/python3
"""
This module hold a function that prints a square with the character #.
"""
def print_square(size):
"""
This function prints square by the size
Paramethers:
size: length of the square
Errors:
TypeError: size must be an integer
ValueError: size must be >= 0
Returns:
Nothing
"""
if type(size) is not int:
raise TypeError("size must be an integer")
if size < 0:
raise ValueError("size must be >= 0")
if (type(size) is float and size < 0):
raise TypeError("size must be an integer")
for x in range(size):
for y in range(size):
print('#', end="")
print()
| true |
63dac65210c83675bf6c7b07e055231e7434a8ec | enkefalos/PythonCourse | /hw1_question3.py | 1,184 | 4.28125 | 4 | def compare_subjects_within_student(subj1_all_students :dict,
subj2_all_students :dict):
"""
Compare the two subjects with their students and print out the "preferred"
subject for each student. Single-subject students shouldn't be printed.
Choice for the data structure of the function's arguments is up to you.
"""
for key, val in subj1_all_students.items():
if key != 'subject' and key in subj2_all_students:
print(key, end = ' ')
if max(val) > max(subj2_all_students[key]):
print(subj1_all_students['subject'])
continue
print(subj2_all_students['subject'])
if __name__ == '__main__':
# Question 3
math_grades = {
'subject': 'Math',
'Zvi': (100, 98),
'Omri': (68, 93),
'Shira': (90, 90),
'Rony': (85, 88) }
history_grades = {
'subject': 'History',
'Zvi': (69, 73),
'Omri': (88, 74),
'Shira': (92, 87),
'Rony': (92, 98) }
print('Preffered subject per student')
compare_subjects_within_student(math_grades, history_grades)
| true |
14f7a544807a575b1ee39c99bfbdad6c7efd90b1 | tyteotin/codewars | /6_kyu/is_triangle_number.py | 1,168 | 4.15625 | 4 | """
Description:
Description:
A triangle number is a number where n objects form an equilateral triangle (it's a bit hard to explain). For example,
6 is a triangle number because you can arrange 6 objects into an equilateral triangle:
1
2 3
4 5 6
8 is not a triangle number because 8 objects do not form an equilateral triangle:
1
2 3
4 5 6
7 8
In other words, the nth triangle number is equal to the sum of the n natural numbers from 1 to n.
Your task:
Check if a given input is a valid triangle number. Return true if it is, false if it is not (note that any non-integers,
including non-number types, are not triangle numbers).
You are encouraged to develop an effective algorithm: test cases include really big numbers.
Assumptions:
You may assume that the given input, if it is a number, is always positive.
Notes:
0 and 1 are triangle numbers.
"""
def is_triangle_number(number):
if(str(number).isdigit() == False):
return False
elif(float(number).is_integer() == False):
return False
else:
if(((8*number+1)**(1.0/2)).is_integer() == True):
return True
else:
return False
| true |
d60efd85d0348706c2262820706a4234a775df1a | Sairahul-19/CSD-Excercise01 | /04_is_rotating_prime.py | 1,148 | 4.28125 | 4 | import unittest
question_04 = """
Rotating primes
Given an integer n, return whether every rotation of n is prime.
Example 1:
Input:
n = 199
Output:
True
Explanation:
199 is prime, 919 is prime, and 991 is prime.
Example 2:
Input:
n = 19
Output:
False
Explanation:
Although 19 is prime, 91 is not.
"""
# Implement the below function and run the program
from itertools import permutations
def is_rotating_prime(num):
l=[]
a=list(permutations(str(num),len(str(num))))
for i in a :
l.append("".join(i))
for k in l:
for j in range(2,int(k)):
if (int(k)%j)==0:
return False
return True
class TestIsRotatingPrime(unittest.TestCase):
def test_1(self):
self.assertEqual(is_rotating_prime(2), True)
def test_2(self):
self.assertEqual(is_rotating_prime(199), True)
def test_3(self):
self.assertEqual(is_rotating_prime(19), False)
def test_4(self):
self.assertEqual(is_rotating_prime(791), False)
def test_5(self):
self.assertEqual(is_rotating_prime(919), True)
if __name__ == '__main__':
unittest.main(verbosity=2)
| true |
dfd38f505944aeb4fee6fa57bda110fa84952084 | ajorve/pdxcodeguild | /json-reader/main.py | 1,131 | 4.5 | 4 | """
Objective
Write a simple program that reads in a file containing some JSON and prints out some of the data.
1. Create a new directory called json-reader
2. In your new directory, create a new file called main.py
The output to the screen when the program is run should be the following:
The Latitude/Longitude of Portland is 45.523452/-122.676207.
'/Users/Anders/Desktop/PDX_Code/practice/json-reader/json_text.txt', {'Portand' : {'Latitude' : '45.523452/-122.676207', 'Longitude' : '-122.676207 '}}
"""
import json
def save(filename, data):
"""
Take a dict as input, serializes it, then the serialized version of the dict saves to the specified filename.
"""
data = input('Enter in the information you would like to write to this file.')
with open(filename, 'w') as file:
serialized = json.dumps(data)
file.write(serialized)
save(filename, data)
def load(filename):
"""
Takes a filename
"""
with open(filename, 'r') as file:
raw_data = file.read()
data = json.loads(raw_data)
return data
load(filename)
| true |
dbfe81b01a012a936086b78b5344682238e88ea5 | ajorve/pdxcodeguild | /puzzles/fizzbuzz.py | 1,145 | 4.375 | 4 | """
Here are the rules for the FizzBuzz problem:
Given the length of the output of numbers from 1 - n:
If a number is divisible by 3, append "Fizz" to a list.
If a number is divisible by 5, append "Buzz" to that same list.
If a number is divisible by both 3 and 5, append "FizzBuzz" to the list.
If a number meets none of theese rules, just append the string of the number.
>>> fizz_buzz(15)
['1', '2', 'Fizz', '4', 'Buzz', 'Fizz', '7', '8', 'Fizz', 'Buzz', 11, 'Fizz', 13, 14, 'FizzBuzz']
REMEMBER: Use Encapsulation! D.R.Y.
>>> joined_buzz(15)
'1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz'
"""
def fizz_buzz(stop_num):
number_list = list()
for each_number in range(1, stop_num + 1):
if each_number % 3 == 0 and each_number % 5 == 0: #if each_number % 15 == 0:
number_list.append("FizzBuzz")
elif each_number % 3 == 0:
number_list.append("Fizz")
elif each_number % 5 == 0:
number_list.append("Buzz")
else:
number_list.append(each_number)
return number_list
def joined_buzz(number):
return " ".join(fizz_buzz(number))
| true |
5733f941bb23cec0470a41d4bb6ab1f78d86bd73 | ajorve/pdxcodeguild | /warm-ups/pop_sim.py | 2,021 | 4.375 | 4 | """
Population Sim
In a small town the population is 1000 at the beginning of a year.
The population regularly increases by 2 percent per year and moreover 50 new inhabitants per year come to live in the town.
How many years does the town need to see its population greater or equal to 1200 inhabitants?
Write a function to determine the the answer given input of the starting population, the number of additional inhabitants coming each year, the anual percent of increase, and the target population.
solve(start_pop, additional, delta, target)
In: solve(1000, 50, 2, 1200)
Out: 3 Years.
"""
def pop_sim(start_pop, growth, births, target):
"""
Write a function to determine the the answer given
input of the starting population,
the number of additional inhabitants coming each year,
the annual percent of increase,
and the target population.
>>> pop_sim(1000, 50, 2, 1200)
It took approximately 3 years to get to 1200 people
:param start_pop: int
:param growth: int
:param births: int
:param target: int
:return: str
"""
population = start_pop
new_inhabs = births
pop_change = growth
target_pop = target
years_past = 0
while population < target_pop:
result = ((population * (pop_change * .01)) + new_inhabs)
population += result
years_past += 1
message = f"It took approximately {years_past} years to get to {target_pop} people"
print(message)
return message
def pop_collection():
print("Welcome to the Global Population Simulator!")
start_pop = int(input("What is the current population?: "))
growth = int(input("What is the average annual growth rate % (use whole number) ?: "))
births = int(input("How many annual births?: "))
target = int(input("What is the desired target population?: "))
data = (start_pop, growth, births, target)
pop_sim(*data)
if __name__ == "__main__":
pop_collection() | true |
8523f0d7a6dd5773e2b947e5302906f1f385187d | kevinwei666/python-projects | /hw1/solution1/Q4.py | 634 | 4.625 | 5 | """
Asks the user to input an integer. The program checks if the user entered an integer,
then checks to see if the integer is within 10 (10 is included) of 100 or 200.
If that is the case, prints ‘Yes’, else prints ‘No’.
Examples:
90 should print 'Yes'
209 should also print 'Yes'
189 should print 'No'
"""
#Get user input
num = input("Enter an integer: ")
try:
num = int(num)
#Checks to see if int is within 10 of 100 or 200
if ((90 <= x <= 110) or (190 <= x <= 210)):
print('Yes')
else:
print('No')
except ValueError as e:
print(num + " is not an integer")
print(e)
| true |
e095d54de54855fbf5c006b6fe47ee93e51fd5ba | DinakarBijili/Data-structures-and-Algorithms | /BINARY TREE/11.Top View of Binary Tree .py | 1,394 | 4.28125 | 4 | """
Top View of Binary Tree
Given below is a binary tree. The task is to print the top view of binary tree. Top view of a binary tree is the set of nodes visible when the tree is viewed from the top. For the given below tree
1
/ \
2 3
/ \ / \
4 5 6 7
Top view will be: 4 2 1 3 7
Note: Return nodes from leftmost node to rightmost node.
Example 1:
Input:
1
/ \
2 3
Output: 2 1 3
Example 2:
Input:
10
/ \
20 30
/ \ / \
40 60 90 100
Output: 40 20 10 30 100
"""
class TreeNode:
def __init__(self,data):
self.data = data
self.left = None
self.right = None
def getData(self):
return self.data
def getLeft(self):
return self.left
def getRight(self):
return self.right
def TopView(Tree):
if not Tree:
return []
if Tree:
TopView(Tree.getLeft())
TopView(Tree.getRight)
print(Tree.data)
if __name__ == "__main__":
"""
1
/ \
2 3
/ \ / \
4 5 6 7
Top view will be: 4 2 1 3 7
"""
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
root.right.left = TreeNode(6)
root.right.right = TreeNode(7)
print("Top View: ")
TopView(root) | true |
7629f38b20e5dd43ceda19cceb9e68a7386adee0 | DinakarBijili/Data-structures-and-Algorithms | /SORTING AND SEARCHING/18.K-th element of two sorted Arrays.py | 1,027 | 4.25 | 4 | """
K-th element of two sorted Arrays
Given two sorted arrays arr1 and arr2 of size M and N respectively and an element K. The task is to find the element that would be at the k’th position of the final sorted array.
Example 1:
Input:
arr1[] = {2, 3, 6, 7, 9}
arr2[] = {1, 4, 8, 10}
k = 5
Output:
6
Explanation:
The final sorted array would be -
1, 2, 3, 4, 6, 7, 8, 9, 10
The 5th element of this array is 6.
Example 2:
Input:
arr1[] = {100, 112, 256, 349, 770}
arr2[] = {72, 86, 113, 119, 265, 445, 892}
k = 7
Output:
256
Explanation:
Final sorted array is - 72, 86, 100, 112,
113, 119, 256, 265, 349, 445, 770, 892
7th element of this array is 256.
"""
def Kth_element_in_two_sortedarr(arr1,arr2,target):
ans =arr1+arr2
ans.sort()
for i, j in enumerate(ans):
if i+1 == target:
return j
return []
if __name__ == "__main__":
arr1 = [100, 112, 256, 349, 770]
arr2 = [72, 86, 113, 119, 265, 445, 892]
target = 7
print(Kth_element_in_two_sortedarr(arr1,arr2,target)) | true |
6d66d78b7774086fa047257b28fd2d3d83c7d7ca | DinakarBijili/Data-structures-and-Algorithms | /ARRAY/10.min_no._of_jumps_to_reach_end_of_arr.py | 1,639 | 4.1875 | 4 | """
Minimum number of jumps
Given an array of integers where each element represents the max number of steps that can be made forward from that element. Find the minimum number of jumps to reach the end of the array (starting from the first element). If an element is 0, then you cannot move through that element.
Example 1:
Input:
N=11
arr=1 3 5 8 9 2 6 7 6 8 9
Output: 3
Explanation:
First jump from 1st element to 2nd
element with value 3. Now, from here
we jump to 5th element with value 9,
and from here we will jump to last.
Example 2:
Input :
N= 6
arr= 1 4 3 2 6 7
Output: 2
Explanation:
First we jump from the 1st to 2nd element
and then jump to the last element.
Your task:
You don't need to read input or print anything. Your task is to complete function minJumps() which takes the array arr and it's size N as input parameters and returns the minimum number of jumps.
Expected Time Complexity: O(N)
Expected Space Complexity: O(1)
"""
def jump(arr):
if len(arr) <= 1 :
return 0
# Return -1 if not possible to jump
if arr[0] <= 0 :
return -1
jump_count = 0
curr_reachable = 0
for index , values in enumerate(arr):
if index > curr_reachable:
curr_reachable = reachable
jump_count += 1
reachable = max(0,index + values)
return jump_count
if __name__ == "__main__":
arr = [1,3, 5, 8, 9, 2, 6, 7, 6, 8, 9 ]
# ndex =[0,1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
result = jump(arr)
print("Max Jumps to reach End in",result,"Steps!") | true |
4bd049da90d733d69710804afaa9b5352667caf3 | DinakarBijili/Data-structures-and-Algorithms | /SORTING AND SEARCHING/7.Majority Element.py | 900 | 4.40625 | 4 | """
Majority Element
Given an array A of N elements. Find the majority element in the array. A majority element in an array A of size N is an element that appears more than N/2 times in the array.
Example 1:
Input:
N = 3
A[] = {1,2,3}
Output:
-1
Explanation:
Since, each element in
{1,2,3} appears only once so there
is no majority element.
Example 2:
Input:A[] = {3,1,3,3,2}
Output: 3
Explanation:
Since, 3 is present more
than N/2 times, so it is
the majority element.
"""
def Majority_elements(arr):
if not arr:
return []
dict = {}
for i in arr:
if i not in dict: #[3:1, 4:1 , 2:1]
dict[i] = 1
else:
dict[i] += 1 #[3:2, 4:5 , 2:2]
if dict[i] > len(arr)//2:
return i
return "No Majority Elements"
if __name__ == "__main__":
arr = [3,1,3,2]
res = (Majority_elements(arr))
print(res)
| true |
a6b70b95e2abd954adf5c0ef7884792630fc1e5e | DinakarBijili/Data-structures-and-Algorithms | /LINKED_LIST/Rotate Doubly linked list by N nodes.py | 2,692 | 4.1875 | 4 | """
Rotate Doubly linked list by N nodes
Given a doubly linked list, rotate the linked list counter-clockwise by N nodes. Here N is a given positive integer and is smaller than the count of nodes in linked list.
N = 2
Rotated List:
Examples:
Input : a b c d e N = 2
Output : c d e a b
Input : a b c d e f g h N = 4
Output : e f g h a b c d
"""
class Node:
def __init__(self,data):
self.data = data
self.next = None
self.prev = None
def set_next(self):
return self.next
def makeList(data):
head = Node(data[0])
for elements in data[1: ]:
ptr = head
while ptr.next:
ptr = ptr.next
ptr.next = Node(elements)
return head
def PrintList(head):
nodes = []
ptr = head
while ptr:
if ptr is head:
nodes.append("[Head %s]"%ptr.data)
elif ptr.next is None:
nodes.append("[Tail %s] ->[None]"%ptr.data)
else:
nodes.append("[%s]"%ptr.data)
ptr = ptr.next
print(" -> ".join(nodes))
class Linked_list:
def __init__(self):
self.head = None
def Rotate_LinkedList_of_N_nodes(head, N = 2):
if N == 0:
return
# list = a <-> b <-> c <-> d <-> e.
curr = head
# current will either point to Nth
# or None after this loop. Current
# will point to node 'b'
count = 1
while count < N and curr != None:
curr = curr.next
count += 1
# If current is None, N is greater
# than or equal to count of nodes
# in linked list. Don't change the
# list in this case
if curr == None:
return
# current points to Nth node. Store
# it in a variable. NthNode points to
# node 'b' in the above example
Nthnode = curr
# current will point to last node
# after this loop current will point
# to node 'e'
while curr.next != None:
curr = curr.next
curr.next = head
# Change prev of Head node to current
# Prev of 'a' is now changed to node 'e'
head.prev = curr
# head is now changed to node 'c'
head = Nthnode.next
# Change prev of New Head node to None
# Because Prev of Head Node in Doubly
# linked list is None
head.prev = None
# change next of Nth node to None
# next of 'b' is now None
Nthnode.next = None
return head
if __name__== "__main__":
obj = Linked_list()
head = makeList(['a','b','c','d','e'])
print("Original Linked List: ")
PrintList(head)
print("\nPairs of Linked List of N=2: ")
PrintList(Rotate_LinkedList_of_N_nodes(head))
| true |
6fc2e1d949f0bfaa8b60947c38faf8e435a41a73 | DinakarBijili/Data-structures-and-Algorithms | /BINARY TREE/1.Level order traversal.py | 1,352 | 4.125 | 4 | """
Level order traversal
Given a binary tree, find its level order traversal.
Level order traversal of a tree is breadth-first traversal for the tree.
Example 1:
Input:
1
/ \
3 2
Output:1 3 2
Example 2:
Input:
10
/ \
20 30
/ \
40 60
Output:10 20 30 40 60 N N
"""
class TreeNone:
def __init__(self, data, left=None, right = None):
self.data = data
self.left = left
self.right = right
def __str__(self):
return str(self.data)
class Soluation:
def Level_order_traversal(self,root):
res = []
if root is None:
return None
queue = []
queue.append(root)
while len(queue)>0:
node = queue.pop(0)
res.append(node.data)
if node.left != None:
queue.append(node.left)
if node.right != None:
queue.append(node.right)
return res
if __name__ == "__main__":
obj = Soluation()
# node = list(map(int, input().split()))
root = TreeNone(10)
root.left = TreeNone(20)
root.right = TreeNone(30)
root.left.left = TreeNone(40)
root.left.right = TreeNone(50)
ans = obj.Level_order_traversal(root)
print(ans) | true |
1c32e5e226de7d4f2d1e3711911554730b406f9a | DinakarBijili/Data-structures-and-Algorithms | /LINKED_LIST/Check if Linked List is Palindrome.py | 2,064 | 4.21875 | 4 | """
Check if Linked List is Palindrome
Given a singly linked list of size N of integers. The task is to check if the given linked list is palindrome or not.
Example 1:
Input:
N = 3
value[] = {1,2,1}
Output: 1
Explanation: The given linked list is
1 2 1 , which is a palindrome and
Hence, the output is 1.
Example 2:
Input:
N = 4
value[] = {1,2,3,4}
Output: 0
Explanation: The given linked list
is 1 2 3 4 , which is not a palindrome
and Hence, the output is 0.
"""
class Node:
def __init__(self, data ):
self.data = data
self.next = None
def makeList(data):
head = Node(data[0])
for elements in data[1:]:
ptr = head
while ptr.next:
ptr = ptr.next
ptr.next = Node(elements)
return head
def PrintList(head):
nodes = []
ptr = head
while ptr:
if ptr is head:
nodes.append("[Head %s]"%ptr.data)
elif ptr is None:
nodes.append("[Tail %s] -> [None]]"%ptr.data)
else:
nodes.append("[%s]"%ptr.data)
ptr = ptr.next
print (" -> ".join(nodes))
class Linked_list:
def __init__(self):
self.head = None
def Check_Palindrome(list):
ptr = list
stack = []
isplaindrome = True
while ptr != None:
stack.append(ptr.data) # Storing Data
ptr = ptr.next # move
while list != None:
i = stack.pop() # pop data from stack and add to i
if list.data == i: #if first and last is equal stack values store in i then stack become empty
isplaindrome = True
else:
isplaindrome = False # else if first and last is not same then the list.data is not equal then stop
break
list = list.next
return isplaindrome
if __name__ == "__main__":
obj = Linked_list()
list = makeList([5, 1, 1 ,5, 4, 3, 2, 3, 3, 3, 3 ,3, 2, 2, 1, 2, 2, 1, 5, 5, 5, 1, 5, 2, 3, 3, 2, 2, 1, 5, 3, 3, 2, 3, 4, 2, 1, 2, 4, 5])
result = Check_Palindrome(list)
print(result)
| true |
dcd5db7c301734d0b7406153043d6e89ece94997 | DinakarBijili/Data-structures-and-Algorithms | /LINKED_LIST/Reverse a Linked List in groups of given size.py | 2,665 | 4.3125 | 4 | """
Reverse a Linked List in groups of given size
Given a linked list of size N. The task is to reverse every k nodes (where k is an input to the function) in the linked list.
Example 1:
Input:
LinkedList: 1->2->2->4->5->6->7->8
K = 4
Output: 4 2 2 1 8 7 6 5
Explanation:
The first 4 elements 1,2,2,4 are reversed first
and then the next 4 elements 5,6,7,8. Hence, the
resultant linked list is 4->2->2->1->8->7->6->5.
Example 2:
Input:
LinkedList: 1->2->3->4->5
K = 3
Output: 3 2 1 5 4
Explanation:
The first 3 elements are 1,2,3 are reversed
first and then elements 4,5 are reversed.Hence,
the resultant linked list is 3->2->1->5->4.
Your Task:
You don't need to read input or print anything. Your task is to complete the function reverse() which should reverse the linked list in group of size k and return the head of the modified linked list.
"""
class Node:
def __init__(self, data):
self.data = data
self.next = None
def makelist(data):
head = Node(data[0])
for elements in data[1:]:
ptr = head
while ptr.next:
ptr = ptr.next
ptr.next = Node(elements)
return head
def printlist(head):
nodes = []
ptr = head
while ptr:
if ptr is head:
nodes.append("[Head: %s]"%ptr.data)
elif ptr.next is None:
nodes.append("[Tail: %s] -> [None]"%ptr.data)
else:
nodes.append("[%s]"%ptr.data)
ptr = ptr.next
print(" -> ".join(nodes))
class Linked_list:
def __init__(self):
self.head = None
def reverse_of_size(self, head, k=4):
new_stack = []
prev = None
current = head
while (current != None):
val = 0
while (current != None and val < k): # if val is < 4
new_stack.append(current.data) # adding to new_stack
current = current.next # current increase to next
val+=1 # val also increase by 1 thround next
# Now pop the elements of stack one by one
while new_stack:
# If final list has not been started yet.
if prev is None:
prev = Node(new_stack.pop())
head = prev
else:
prev.next = Node(new_stack.pop())
prev = prev.next
prev.next = None
return head
if __name__ == "__main__":
obj = Linked_list()
list1 = makelist([1,2,2,4,5,6,7,8])
print("Original Linked_List: ")
printlist(list1)
print("\n Reverse Linked_List of Size K: ")
printlist(obj.reverse_of_size(list1))
| true |
da2f6f83dca1a4776eba5777e39cb41676e29f2a | DinakarBijili/Data-structures-and-Algorithms | /ARRAY/4.Sort_arr-of_0s,1s,and,2s.without_using_any_sortMethod.py | 971 | 4.375 | 4 | # Sort an array of 0s, 1s and 2s
# Given an array of size N containing only 0s, 1s, and 2s; sort the array in ascending order.
# Example 1:
# Input:
# N = 5
# arr[]= {0 2 1 2 0}
# Output:
# 0 0 1 2 2
# Explanation:
# 0s 1s and 2s are segregated
# into ascending order.
# Example 2:
# Input:
# N = 3
# arr[] = {0 1 0}
# Output:
# 0 0 1
# Explanation:
# 0s 1s and 2s are segregated
# into ascending order.
def quick_sort(arr):
if len(arr) <= 1:
return arr
less_than_pivot = []
greater_than_pivot = []
pivot = arr[0] #first index
for value in arr[1:]:
if value <= pivot:
less_than_pivot.append(value)
else:
greater_than_pivot.append(value)
print("%15s %1s %15s"% (less_than_pivot,pivot,greater_than_pivot))
return quick_sort(less_than_pivot)+[pivot]+quick_sort(greater_than_pivot)
if __name__ == "__main__":
arr = [4,6,3,2,9,7,3,5]
print(arr)
result = quick_sort(arr)
print(result)
| true |
11960b0f8caeafeda8c4cffcfa4d90bf087ad4bd | DinakarBijili/Data-structures-and-Algorithms | /BINARY TREE/5.Create a mirror tree from the given binary tree.py | 1,605 | 4.375 | 4 | """
Create a mirror tree from the given binary tree
Given a binary tree, the task is to create a new binary tree which is a mirror image of the given binary tree.
Examples:
Input:
5
/ \
3 6
/ \
2 4
Output:
Inorder of original tree: 2 3 4 5 6
Inorder of mirror tree: 6 5 4 3 2
Mirror tree will be:
5
/ \
6 3
/ \
4 2
Input:
2
/ \
1 8
/ \
12 9
Output:
Inorder of original tree: 12 1 2 8 9
Inorder of mirror tree: 9 8 2 1 12
"""
class TreeNode:
def __init__(self,data):
self.data = data
self.left = None
self.right = None
def getData(self):
return self.data
def getLeft(self):
return self.left
def getRight(self):
return self.right
def inorder(root):
if not root:
return
if root:
inorder(root.getLeft())
print(root.getData(),end=" ")
inorder(root.getRight())
return
def convertToMirror(root):
if not root:
return
if root:
convertToMirror(root.getRight())
print(root.getData(), end=" ")
convertToMirror(root.getLeft())
return
if __name__ == "__main__":
''' Construct the following tree
5
/ \
3 6
/ \
2 4
'''
root = TreeNode(5)
root.left = TreeNode(3)
root.right = TreeNode(6)
root.left.left = TreeNode(2)
root.left.right = TreeNode(4)
print("Inorder Traversal: ")
inorder(root)
print("\nMirror of Inorder Traversal: ")
convertToMirror(root)
| true |
1665a5752794a64a0de7e505e172a814c9b32e8f | andrewsanc/pythonFunctionalProgramming | /exerciseLambda.py | 282 | 4.15625 | 4 | '''
Python Jupyter - Exercise: Lambda expressions.
'''
# Using Lambda, return squared numbers.
#%%
nums = [5,4,3]
print(list(map(lambda num: num**2, nums)))
# List sorting. Sort by the second element.
#%%
a = [(0,2), (4,3), (9,9), (10,-1)]
a.sort(key=lambda x: x[1])
print(a)
#%%
| true |
3a6fa89d2f42f9b264fc509e02c13c8222e8d76c | DandyCV/SoftServeITAcademy | /L07/L07_HW1_3.py | 321 | 4.15625 | 4 | def square(size):
"""Function returns tuple with float {[perimeter], [area], [diagonal]}
Argument - integer/float (side of square)"""
perimeter = 4 * size
area = size ** 2
diagonal = round((2 * area) ** 0.5, 2)
square_tuple = (perimeter, area, diagonal)
return square_tuple
print(square(3))
| true |
97d0ccc3d5c0bd1f9d84c1201695309d49c09fb9 | DandyCV/SoftServeITAcademy | /L07/L07_HW1_1.py | 473 | 4.5 | 4 | def arithmetic(value_1, value_2, operation):
"""Function makes mathematical operations with 2 numbers.
First and second arguments - int/float numbers
Third argument - string operator(+, -, *, /)"""
if operation == "+": return value_1 + value_2
if operation == "-": return value_1 - value_2
if operation == "*": return value_1 * value_2
if operation == "/": return value_1 / value_2
return "Unknown operation"
print(arithmetic(12, 3, "*"))
| true |
b7f773a51b49ad7512c4dee4a860c49d2e600ba7 | ramalho/modernoopy | /examples/tombola/ibingo.py | 814 | 4.34375 | 4 | """
Class ``IBingo`` is an iterable that yields items at random from
a collection of items, like to a bingo cage.
To create an ``IBingo`` instance, provide an iterable with the items::
>>> balls = set(range(3))
>>> cage = IBingo(balls)
The instance is iterable::
>>> results = [item for item in cage]
>>> sorted(results)
[0, 1, 2]
Iterating over an instance does not change the instance. Each iterator
has its own copy of the items. If ``IBingo`` instances were changed on
iteration, the value of this expression would be 0 (zero)::
>>> len([item for item in cage])
3
"""
import bingo
class IBingo(bingo.Bingo):
def __iter__(self):
"""return generator to yield items one by one"""
items = self._items[:]
while items:
yield items.pop()
| true |
53bd12eb151b9514575a8958560352ddb44bd941 | SLongofono/Python-Misc | /python2/properties.py | 1,250 | 4.125 | 4 | """
This demonstrates the use of object properties as a way to give the illusion of private members and
getters/setters per object oriented programming. Variables prefixed by underscore are a signal to other
programmers that they should be changing them directly, but there really isn't any enforcement. There are
still ways around it, but this makes it harder to change members that shouldn't change.
"""
class myThing(object):
def __init__(self, foo=None):
self._foo = foo
# This decorator acts as a getter, accessed with "myFoo.foo"
@property
def foo(self):
return self._foo
# This decorator acts as a setter, but only once
@foo.setter
def foo(self, newFoo):
if self._foo is None:
self._foo = newFoo
else:
raise Exception("Immutable member foo has already been assigned...")
# This decorator protects against inadvertent deletion via "del myFoo.foo"
@foo.deleter
def foo(self):
raise Exception("Cannot remove immutable member foo")
if __name__ == "__main__":
myFoo = myThing()
print(myFoo.foo)
myFoo.foo = "bar"
print(myFoo.foo)
try:
myFoo.foo = "baz"
except Exception as e:
print(e)
print(myFoo.foo)
try:
del myFoo.foo
except Exception as e:
print(e)
| true |
3aa2076bc76d17d5cb2c903e5089f9dc6c913a13 | acemourya/D_S | /C_1/Chatper-01 DataScience Modules-stats-Example/Module-numpy-example.py | 1,100 | 4.15625 | 4 | #numpy: numerical python which provides function to manage multiple dimenssion array
#array : collection of similar type data or values
import numpy as np
#create array from given range
x = np.arange(1,10)
print(x)
y = x*2
print(y)
#show data type
print(type(x))
print(type(y))
#convert list to array
d = [11,22,4,45,3,3,555,44]
n = np.array(d)
print(n)
print(type(n))
print(n*2)
##change data type
n = np.array(d,dtype=float)
print(n)
#show shpae
print(n.shape)
#change demenssion
n = np.array(d).reshape(-1,2) #read from 1st element , 2 two dimenssion
print(n)
d = [11,22,4,45,3,3,555,44,3]
n = np.array(d).reshape(-1,3) #read from 1st element , 3 dimenssion
print(n)
#generate the array of zeors
print(np.zeros(10))
#generate the array of ones
print(np.ones(10))
#matrix or two dimession array and operation
x = [[1,2,3],[5,6,7],[66,77,88]] #list
y = [[11,20,3],[15,26,70],[166,707,88]] #list
#convert to array
x = np.array(x)
y = np.array(y)
print(x)
print(y)
#addition
print(np.add(x,y))
print(np.subtract(x,y))
print(np.divide(x,y))
print(np.multiply(x,y))
| true |
b9b836dffee50eea89374a9978eeb48a86431187 | vladosed/PY_LABS_1 | /3-4/3-4.py | 730 | 4.3125 | 4 | #create random string with lower and upper case and with numbers
str_var = "asdjhJVYGHV42315gvghvHGV214HVhjjJK"
print(str_var)
#find first symbol of string
first_symbol = str_var[0]
print(first_symbol)
#find the last symbol of string
last_symbol = str_var[-1]
print(last_symbol)
#slice first 8 symbols
print(str_var[slice(8)])
#print only symbols with index which divides on 3 without remaining
list_of_str_var = list(str_var.strip(" "))
every_third_elem = list_of_str_var[::3]
list_to_str = ''.join(str(x) for x in every_third_elem)
print(list_to_str)
#print the symbol of the middle of the string text
middle = str_var[int(len(str_var) / 2)] #len(str_var) / 2
print(middle)
#reverse text using slice
print(str_var [::-1]) | true |
b5418dbfb626ef9a83a73a5de00da17e8e3822b5 | Kristjamar/Verklegt-namskei- | /Breki/Add_to_dict.py | 233 | 4.1875 | 4 | x = {}
def add_to_dict(x):
key = input("Key: ")
value = input("Value: ")
if key in x:
print("Error. Key already exists.")
return x
else:
x[key] = value
return x
add_to_dict(x)
print(x) | true |
df86c8f38f511f08aa08938abba0c79875727eb9 | green-fox-academy/hanzs_solo | /Foundation/week_02-week_04/PythonBasicsProject/week_02/expressions_and_control_flow/conditionals/odd_even.py | 234 | 4.46875 | 4 | # Write a program that reads a number from the standard input,
# then prints "Odd" if the number is odd, or "Even" if it is even.
number = int(input("enter an integer: "))
if number % 2 == 0:
print("Even")
else:
print("Odd")
| true |
39147e634f16988b71a0aee7d825d8e93def5359 | green-fox-academy/hanzs_solo | /Foundation/week_02-week_04/PythonBasicsProject/week_02/expressions_and_control_flow/user_input/average_of_input.py | 316 | 4.34375 | 4 | # Write a program that asks for 5 integers in a row,
# then it should print the sum and the average of these numbers like:
#
# Sum: 22, Average: 4.4
sum = 0
number_of_numbers = 5
for x in range(number_of_numbers):
sum += int(input("enter an integer: "))
print("sum:", sum, "average:", sum / number_of_numbers)
| true |
a314a1eef3981612f213986b9d261adaf2ff85ce | green-fox-academy/hanzs_solo | /Foundation/week_02-week_04/PythonBasicsProject/week_02/arrays/reverse_list.py | 327 | 4.46875 | 4 | # - Create a variable named `numbers`
# with the following content: `[3, 4, 5, 6, 7]`
# - Reverse the order of the elements of `numbers`
# - Print the elements of the reversed `numbers`
numbers = [3, 4, 5, 6, 7]
temp = []
for i in range(len(numbers)):
temp.append(numbers[len(numbers)-i-1])
numbers = temp
print(numbers) | true |
31170eab6926b9a475fe8fb1b7258571d762b96e | green-fox-academy/hanzs_solo | /Foundation/week_02-week_04/PythonBasicsProject/week_02/data_structures/list_introduction_1.py | 1,247 | 4.78125 | 5 | # # List introduction 1
#
# We are going to play with lists. Feel free to use the built-in methods where
# possible.
#
# - Create an empty list which will contain names (strings)
# - Print out the number of elements in the list
# - Add William to the list
# - Print out whether the list is empty or not
# - Add John to the list
# - Add Amanda to the list
# - Print out the number of elements in the list
# - Print out the 3rd element
# - Iterate through the list and print out each name
# ```text
# William
# John
# Amanda
# ```
# - Iterate through the list and print
# ```text
# 1. William
# 2. John
# 3. Amanda
# ```
# - Remove the 2nd element
# - Iterate through the list in a reversed order and print out each name
# ```text
# Amanda
# William
# ```
# - Remove all elements
names = []
print(len(names))
print()
names.append("William")
print(len(names))
print()
print(len(names) == 0)
print()
names.append("John")
names.append("Amanda")
print(len(names))
print()
print(names[2])
print()
for name in names:
print(name)
print()
for i in range(len(names)):
print(i + 1, ".", names[i])
print()
names.remove(names[1])
i = len(names) - 1
while i >= 0:
print(names[i])
i -= 1
print()
names[:] = []
| true |
238f272124f13645a7e58e8de1aaee8d9a433967 | green-fox-academy/hanzs_solo | /Foundation/week_02-week_04/PythonBasicsProject/week_02/expressions_and_control_flow/loops/count_from_to.py | 634 | 4.28125 | 4 | # Create a program that asks for two numbers
# If the second number is not bigger than the first one it should print:
# "The second number should be bigger"
#
# If it is bigger it should count from the first number to the second by one
#
# example:
#
# first number: 3, second number: 6, should print:
#
# 3
# 4
# 5
a = -999
b = -1999
while a > b:
if a != -999:
print("\nthe second number should be bigger")
a = int(input("gimme a number to count from: "))
b = int(input("gimme a number to count to: "))
while a < b:
print(a)
a += 1
# for x in range(b):
# if x < a:
# continue
# print(x)
| true |
27a458c5355a32cf2bc9eb53cef586a8120e9e36 | hr4official/python-basic | /td.py | 840 | 4.53125 | 5 | # nested list
#my_list = ["mouse", [8, 4, 6], ['a']]
#print(my_list[1])
# empty list
my_list1 = []
# list of integers
my_list2 = [1, 2, 3]
# list with mixed datatypes
my_list3 = [1, "Hello", 3.4]
#slice lists
my_list = ['p','r','o','g','r','a','m','i','z']
# elements 3rd to 5th
print(my_list[2:5])
# elements beginning to 4th
print(my_list[:-5])
# elements 6th to end
print(my_list[5:])
# elements beginning to end
print(my_list[:])
#We can add one item to a list using append() method or add several items using extend() method.
#Here is an example to make a list with each item being increasing power of 2.
pow2 = [2 ** x for x in range(10)]
# Output: [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]
print(pow2)
#This code is equivalent to
pow2 = []
for x in range(10):
pow2.append(2 ** x) | true |
cff7d4a762f14e761f3c3c46c2e656f74cb19403 | sharikgrg/week3.Python-Theory | /exercises/exercise1.py | 745 | 4.375 | 4 | # Define the following variable
# name, last name, age, eye_colour, hair_colour
# Prompt user for input and reassign these
# Print them back to the user as conversation
# Eg: Hello Jack! Welcome, your age is 26, you eyes are green and your hair_colour are grey
name = input('What is your name?')
last_name = input('What is your surname?')
age = int(input('What is your age?'))
eye_colour = input('What is the colour of your eye?')
hair_colour = input('What is the colour of your hair?')
print('Hello',name.capitalize(), f'{last_name.capitalize()}!', 'Welcome, your age is', f'{age},', 'your eyes are', eye_colour, 'and your hair is', hair_colour)
print(f'Hello {name} {last_name}, Welcome!, your age is')
print('You were born in', 2019 - age) | true |
cda99da103298b6c26c29b9083038a732826be11 | sharikgrg/week3.Python-Theory | /102_data_types.py | 1,736 | 4.5 | 4 | # Numerical Data Types
# - Int, long, float, complex
# These are numerical data types which we can use numerical operators.
# Complex and long we don't use as much
# complex brings an imaginary type of number
# long - are integers of unlimited size
# Floats
# int - stmads for integers
# Whole numbers
my_int = 20
print(my_int)
print(type(my_int))
# Operator - Add, Subtract, multiply and devide
print(4+3)
print(4-3)
print(4/2) # decimals get automatically converted to float
print(4//2) # keeps it as integer/ drops the decimal
print(4*2)
print(3**2) # square
# Modules looks for the number of remainder
# % #
print(10%3) ## --> 3*3 =9, so 1 is the remainder
# Comparison Operators ## --> boolean value
# < / > - Bigger and Smaller than
# <= - Smaller than or equal
# >= Bigger than or equal
# != Not equal
# is and is not
my_variable1 = 10
my_variable2 = 13
# example of using operators
print(my_variable1== my_variable2) # output is false
print(my_variable1 > my_variable2)
print(my_variable1 < my_variable2)
print(my_variable1 >= my_variable2)
print(my_variable1 != my_variable2)
print(my_variable1 is my_variable2)
print(my_variable1 is not my_variable2)
# Boolean Values
# Define by either True or False
print(type(True))
print(type(False))
print (0 == False)
print(1 == True)
## None
print(None)
print(type(None))
print(bool(None))
#Logical And & Or
a = True
b = False
print('Logical and & or -------')
# Using *and* both sides have to be true for it to result in true
print(a and True)
print((1==1) and (True))
print((1==1) and False)
#Use or only one side needs to be true
print('this will print true-----')
print(True or False)
print(True or 1==2)
print('this will print false -----------')
print(False or 1==2) | true |
5cba492f9034b07ca9bc7d266dca716ea684ba3c | sdhanendra/coding_practice | /DataStructures/linkedlist/linkedlist_classtest.py | 1,647 | 4.5 | 4 | # This program is to test the LinkedList class
from DataStructures.linkedlist.linkedlist_class import LinkedList
def main():
ll = LinkedList()
# Insert 10 nodes in linked list
print('linked list with 10 elements')
for i in range(10):
ll.insert_node_at_end(i)
ll.print_list()
# delete three nodes at the end in the linked list
print('\ndelete last three elements')
for i in range(3):
ll.delete_node_at_end()
ll.print_list()
# insert a node at the Head
print('\ninsert a node at head')
ll.insert_node_at_head(10)
ll.print_list()
# delete a node at the Head
print('\ndelete a node from head')
ll.delete_node_at_head()
ll.print_list()
# Insert a node 20 after node 2
print('\ninsert a node after a given node')
ll.insert_node_after_give_node(20, 2)
ll.print_list()
# delete the node 20
print('\ndelete a given node')
ll.delete_given_node(20)
ll.print_list()
# search for node 4 in the linked list
print('\nsearch for a node in linked list')
ll.search_node(4)
# sum all elements of the linked list
print('\nsum all elements of a linked list')
elem_sum = ll.sum_all_elements()
print('Sum of the linked list: {}'.format(elem_sum))
# count the number of nodes in the linked list
print('\ncount the number of elements of a linked list')
num_nodes = ll.count_nodes()
print('Total number of nodes in linked list: {}'.format(num_nodes))
# reverse a linked list
print('\nreverse a linked list')
ll.reverse_list()
ll.print_list()
if __name__ == '__main__':
main()
| true |
f37a3a22ad3f2272e65ba5077308a6bfb5364429 | ItaloPerez2019/UnitTestSample | /mymath.py | 695 | 4.15625 | 4 | # make a list of integer values from 1 to 100.
# create a function to return max value from the list
# create a function that return min value from the list
# create a function that return averaga value from the list.
# create unit test cases to test all the above functions.
# [ dont use python built in min function, write your own
# python script to test the list]
def max_num(a):
myMax = a[0]
for num in a:
if myMax < num:
myMax = num
return myMax
def min_num(a):
myMin = a[0]
for num in a:
if myMin > num:
myMin = num
return myMin
def avg_num(a):
for num in a:
average = sum(a)/len(a)
return average
| true |
f289bd52b2eaf19d4e34ec72b37345af0f747d05 | AErenzo/Python_course_programs | /acronym.py | 640 | 4.21875 | 4 | phrase = input('Please enter a phrase: ')
# strip white spacing from the phrase
phrase = phrase.strip()
# change the phrase to upper case
phrase = phrase.upper()
# create new variable containing the phrase split into seperate items
words = phrase.split()
# create empty list for first letter of each item in words
letters = []
# for loop going through each item in words, extracting the first letter and adding it to letters
for i in words:
letters.append(i[0])
# create new vaiable - joining each item in the letters list using no space. Saved as a new vairbale
avb = ''.join(letters)
print(avb)
| true |
f028bde75c24f7d2eec83ee24a638d0240b5628c | julianalvarezcaro/holbertonschool-higher_level_programming | /0x06-python-classes/6-square.py | 1,780 | 4.40625 | 4 | #!/usr/bin/python3
"""6-square module"""
class Square:
"""Square class"""
def __init__(self, size=0, position=(0, 0)):
"""Class constructor"""
self.size = size
self.position = position
def area(self):
"""Returns the area of the square"""
return self.__size * self.__size
@property
def size(self):
"""Getter for the attribute 'size'"""
return self.__size
@size.setter
def size(self, size):
"""Setter for the attribute 'size'"""
if type(size) is not int:
raise TypeError('size must be an integer')
if size < 0:
raise ValueError('size must be >= 0')
self.__size = size
def my_print(self):
"""Prints a square of __size size with caracter #"""
if self.__size == 0:
print()
return
for y in range(self.__position[1]):
print()
for fil in range(self.__size):
for x in range(self.__position[0]):
print(' ', end='')
for col in range(self.__size):
print("#", end='')
print()
@property
def position(self):
"""Getter for position"""
return self.__position
@position.setter
def position(self, position):
"""Setter for position"""
if type(position) is not tuple or len(position) != 2:
raise TypeError('position must be a tuple of 2 positive integers')
if any(type(val) is not int for val in position):
raise TypeError('position must be a tuple of 2 positive integers')
if any(val < 0 for val in position):
raise TypeError('position must be a tuple of 2 positive integers')
self.__position = position
| true |
d72f79ad097f5eace2fcb22d0471c0d3424290ac | elYaro/Codewars-Katas-Python | /8 kyu/Convert_number_to_reversed_array_of_digits.py | 320 | 4.21875 | 4 | '''
Convert number to reversed array of digits
Given a random number:
C#: long;
C++: unsigned long;
You have to return the digits of this number within an array in reverse order.
Example:
348597 => [7,9,5,8,4,3]
'''
def digitize(n):
nstr = str(n)
l=[int(nstr[i]) for i in range(len(nstr)-1,-1,-1)]
return l | true |
ae32fe698d8afb7b31a70999c9875af162c2dbe6 | elYaro/Codewars-Katas-Python | /8 kyu/Is_it_a_number.py | 582 | 4.28125 | 4 | '''
Given a string s, write a method (function) that will return true if its a valid single integer or floating number or false if its not.
Valid examples, should return true:
isDigit("3")
isDigit(" 3 ")
isDigit("-3.23")
should return false:
isDigit("3-4")
isDigit(" 3 5")
isDigit("3 5")
isDigit("zero")
'''
def isDigit(string):
print(type(string), string)
try:
if abs(float(string)):
return True
else:
if float(string) == 0.0:
return True
else:
return False
except: return False | true |
ba06a43362449d7f90a447537840c42b591b8adf | elYaro/Codewars-Katas-Python | /8 kyu/String_cleaning.py | 955 | 4.125 | 4 | '''
Your boss decided to save money by purchasing some cut-rate optical character recognition software for scanning in the text of old novels to your database.
At first it seems to capture words okay, but you quickly notice that it throws in a lot of numbers at random places in the text. For example:
string_clean('! !') == '! !'
string_clean('123456789') == ''
string_clean('This looks5 grea8t!') == 'This looks great!'
Your harried co-workers are looking to you for a solution to take this garbled text and remove all of the numbers. Your program will take in a string
and clean out all numeric characters, and return a string with spacing and special characters ~#$%^&!@*():;"'.,? all intact.
'''
# 2nd try - after refactor
def string_clean(s):
return "".join(x for x in s if not x.isdigit())
# 1st try
def string_clean(s):
l = list(s)
ll = []
for i in l:
if not i.isdigit():
ll.append(i)
return "".join(ll) | true |
ca9334b0325fdbe0e9d4505dd4ab89649d0628f3 | elYaro/Codewars-Katas-Python | /8 kyu/Find_Multiples_of_a_Number.py | 708 | 4.59375 | 5 | '''
In this simple exercise, you will build a program that takes a value, integer, and returns a list of its multiples up to another value, limit.
If limit is a multiple of integer, it should be included as well. There will only ever be positive integers passed into the function, not consisting of 0.
The limit will always be higher than the base.
For example, if the parameters passed are (2, 6), the function should return [2, 4, 6] as 2, 4, and 6 are the multiples of 2 up to 6.
If you can, try writing it in only one line of code.
'''
def find_multiples(integer, limit):
output = []
i = 1
while integer * i <= limit:
output.append(integer * i)
i = i + 1
return output | true |
79d418430029288067984d7573880866b3e43328 | elYaro/Codewars-Katas-Python | /7 kyu/KISS_Keep_It_Simple_Stupid.py | 1,093 | 4.34375 | 4 | '''
KISS stands for Keep It Simple Stupid. It is a design principle for keeping things simple rather than complex.
You are the boss of Joe.
Joe is submitting words to you to publish to a blog. He likes to complicate things.
Define a function that determines if Joe's work is simple or complex.
Input will be non emtpy strings with no punctuation.
It is simple if: the length of each word does not exceed the amount of words in the string (See example test cases)
Otherwise it is complex.
If complex:
return "Keep It Simple Stupid"
or if it was kept simple:
return "Good work Joe!"
Note: Random test are random and nonsensical. Here is a silly example of a random test:
"jump always mostly is touchy dancing choice is pineapples mostly"
'''
# 2nd try - after refactor
def is_kiss(words):
return "Good work Joe!" if max(len(word) for word in words.split(" ")) <= len(words.split(" ")) else "Keep It Simple Stupid"
# 1st try
def is_kiss(words):
if max(len(word) for word in words.split(" ")) <= len(words.split(" ")): return "Good work Joe!"
else: return "Keep It Simple Stupid" | true |
c35fc57fec26636282eba11ea122628c8a07c0a3 | ericaschwa/code_challenges | /LexmaxReplace.py | 1,192 | 4.34375 | 4 | """
LexmaxReplace
By: Erica Schwartz (ericaschwa)
Solves problem as articulated here:
https://community.topcoder.com/stat?c=problem_statement&pm=14631&rd=16932
Problem Statement:
Alice has a string s of lowercase letters. The string is written on a wall.
Alice also has a set of cards. Each card contains a single letter. Alice can
take any card and glue it on top of one of the letters of s. She may use any
subset of cards in this way, possibly none or all of them. She is not allowed
to glue new letters in front of s or after s, she can only replace the existing
letters.
Alice wants to produce the lexicographically largest possible string.
You are given the String s. You are also given a String t. Each character of t
is a letter written on one of the cards. Compute and return the
lexicographically largest string Alice can produce on the wall while following
the rules described above.
"""
def get(s, t):
"""
Executes the solution to the problem described in the problem statement
"""
x = list(t)
y = list(s)
x.sort()
for i in xrange(len(y)):
if len(x) == 0: break
if y[i] < x[-1]:
y[i] = x.pop()
return "".join(y)
| true |
a10242f6ed3268cad16740d2a072e5851cff7816 | Bhaney44/Intro_to_Python_Problems | /Problem_1_B.py | 1,975 | 4.28125 | 4 | #Part B: Saving, with a raise
#Write a program that asks the user to enter the following variables
#The starting annual salary
#The semi-annual raise
#The portion of the salary to be saved
#The total cost of the dream home
#Return the number of months to pay for the down payment.
starting_annual_salary = int(input('Enter your starting annual salary: '))
portion_saved = float(input('Enter the portion of your salary to save as a decimal: '))
semi_annual_raise = float(input('Enter your semi-annual raise as a decimal: '))
total_cost = int(input('Enter the cost of your dream home: '))
down_payment = total_cost * 0.25
#Initialize variables
months = 0
current_savings = 0
investment_rate = 0.04
annual_salary = starting_annual_salary
def savings_calculator(starting_annual_salary, semi_annual_raise, portion_saved):
#Global variables
global current_savings
global months
global annual_salary
#Exit loop when savings equals or exceeds down_payment
while current_savings < down_payment:
#In Python += adds a value to variable and assigns the result to the that variable
#Monthly_savings
monthly_savings = ((annual_salary/12)*portion_saved)
#Add monthly savings to current savings every month
current_savings += monthly_savings
#Add investment income to current savings every month
current_savings += (current_savings*investment_rate)/12
#Add month
months += 1
#Add semi-annual raise to salary and adjust monthly savings accordingly
#In Python == is a test for equality
#In Python % is a modulus
#Returns the remainder when the first operancd is divided by the second
if (months % 6 == 0):
annual_salary += annual_salary*semi_annual_raise
savings_calculator(starting_annual_salary, semi_annual_raise, portion_saved)
number_of_months = print('Number of months: ', months)
| true |
54d13bef355f59710b0b6f7a314d86a6daf8af68 | TroyJJeffery/troyjjeffery.github.io | /Computer Science/Data Structures/Week 4/CH5_EX3.py | 2,347 | 4.5 | 4 | """
Modify the recursive tree program using one or all of the following ideas:
Modify the thickness of the branches so that as the branchLen gets smaller, the line gets thinner.
Modify the color of the branches so that as the branchLen gets very short it is colored like a leaf.
Modify the angle used in turning the turtle so that at each branch point the angle is selected at random in some range. For example choose the angle between 15 and 45 degrees. Play around to see what looks good.
Modify the branchLen recursively so that instead of always subtracting the same amount you subtract a random amount in some range.
If you implement all of the above ideas you will have a very realistic looking tree.
"""
"""
Modify the recursive tree program using one or all of the following ideas:
Modify the thickness of the branches so that as the branchLen gets smaller, the line gets thinner.
Modify the color of the branches so that as the branchLen gets very short it is colored like a leaf.
Modify the angle used in turning the turtle so that at each branch point the angle is selected at random in some range. For example choose the angle between 15 and 45 degrees. Play around to see what looks good.
Modify the branchLen recursively so that instead of always subtracting the same amount you subtract a random amount in some range.
If you implement all of the above ideas you will have a very realistic looking tree.
"""
"""
I'll come back to this if I have time. I'm tired of dealing with it atm.
"""
import turtle
def tree(branchLen,t):
if branchLen > 5:
drawRect(t,branchLen)
t.right(20)
tree(branchLen-15,t)
t.left(40)
tree(branchLen-15,t)
t.right(20)
t.backward(branchLen)
def drawRect(t, len):
width = ((len // 15)*2)
x, y = t.xcor(), t.ycor()
t.fillcolor("brown")
t.fill(True)
t.left(90)
t.forward(width//2)
for i in range(2):
t.forward(len)
t.left(90)
t.forward(width)
t.left(90)
t.fill(False)
t.setx(x)
t.sety(y+40)
def main():
t = turtle.Turtle()
myWin = turtle.Screen()
t.left(90)
t.up()
t.backward(100)
t.down()
t.color("green")
myWin.exitonclick()
tree(75,t)
main() | true |
1d2f84f2f3a4a22172a30392f5ac8a146555cd0d | lopezjronald/Python-Crash-Course | /part-1-basics/Ch_2/name_cases.py | 1,968 | 4.625 | 5 | """
2-3. Personal Message: Use a variable to represent a person’s name, and print a message to
that person. Your message should be simple, such as, “Hello Eric, would you like to learn some
Python today?”
2-4. Name Cases: Use a variable to represent a person’s name, and then print that person’s
name in lowercase, uppercase, and title case.
2-5. Famous Quote: Find a quote from a famous person you admire. Print the quote and the
name of its author. Your output should look something like the following, including the
quotation marks:
Albert Einstein once said, “A person who never made a mistake
never tried anything new.”
2-6. Famous Quote 2: Repeat Exercise 2-5, but this time, represent the famous person’s name
using a variable called famous_person. Then compose your message and represent it with a
new variable called message. Print your message.
2-7. Stripping Names: Use a variable to represent a person’s name, and include some
whitespace characters at the beginning and end of the name. Make sure you use each character
combination, "\t" and "\n", at least once.
Print the name once, so the whitespace around the name is displayed. Then print the name
using each of the three stripping functions, lstrip(), rstrip(), and strip().
"""
name = "Eric"
print(f"Hello, {name}! Would you like to learn some python today?")
first_name = "jEfF"
last_name = "LoPEz"
print(f"Lowercase: {first_name.lower()} {last_name.lower()}")
print(f"Uppercase: {first_name.upper()} {last_name.upper()}")
print(f"Title: {first_name.title()} {last_name.title()}")
author = "tony robbins"
print(f"Repetition is the mother of skill ~ {author.title()}")
famous_person = "kevin hart"
message = "is one hilarious dude!"
print(f"{famous_person.title()} {message}")
name = "\t\nRonald Lopez\t\t\n"
print(f"Left Strip function: {name.lstrip()}")
print(f"Strip function: {name.strip()}")
print(f"Right Strip function: {name.rstrip()}")
fav_num = 17
print(f'Favorite number is {fav_num}') | true |
26d4c7b0708fab0a34f64a0446a488ca6aafc6b4 | baharaysel/python-study-from-giraffeAcademy | /tryexcept.py | 719 | 4.1875 | 4 |
try:
number = int(input("Enter a number: "))
print(number)
except:
print("Invalid Input")
# trying to catch different type of errors
try:
value = 10 / 0
number = int(input("Enter a number: "))
print(number)
except ZeroDivisionError:
print("Divide by zero")
except ValueError:
print("Invalid Input")
# it didnt work it gives error
# saving Error as variable
try:
answer = 10/0
number = int(input("Enter a number: "))
print(number)
except ZeroDivisionError as err:
print(err)
except ValueError:
print("Invalid Input")
#division by zero
#try:
#except:
# dont leave except empty it is not good practice . We want to know catch the specific type of error.
| true |
fc831d3a4869ab1084622ec1cdee10b43d11203d | Diamoon18/grafika | /burning_flower.py | 1,106 | 4.1875 | 4 | import turtle
from turtle import Turtle, Screen
ANGLE = 2
color = 'blue'
color1 = 'black'
color2 = 'red'
color3 = 'yellow'
def circles(t, size, small):
for i in range(10):
t.circle(size)
size=size-small
def circle_direction(t, size, repeat, small):
for i in range (repeat):
circles(t, size, small)
t.right(360/repeat)
def circle_spiral(turtle, radius, color_name):
for i in range(360 // ANGLE):
turtle.color(color_name)
turtle.circle(radius)
turtle.left(ANGLE)
def main():
screen = Screen()
screen.bgcolor('black')
eye = Turtle(visible=False)
eye.speed('fastest')
spiral(eye, 100, color)
spiral(eye, 50, color2)
spiral(eye, 25, color1)
s = Turtle(visible=False)
s.speed('fastest')
s.color('red')
circle_small(s, 200, 10, 4)
t1 = Turtle(visible=False)
t1.speed('fastest')
t1.color('yellow')
circle_small(t1, 160, 10, 10)
spiral(eye, 10, color3)
screen.exitonclick()
if __name__ == "__main__":
main()
| true |
5d0371c886729ffd8070088321fe21381c2d3487 | xiaowuc2/Code-in-Place-2021-Assignment-Solution | /Assignment-2/4. Random Numbers.py | 864 | 4.59375 | 5 | """
Write a program in the file random_numbers.py that prints 10 random integers (each random integer should have a value between 0 and 100, inclusive).
Your program should use a constant named NUM_RANDOM, which determines the number of random numbers to print (with a value of 10).
It should also use constants named MIN_RANDOM and MAX_RANDOM to determine the minimal and maximal values of the random numbers generated (with respective values 0 and 100).
To generate random numbers, you should use the function random.randint() from Python’s random library.
Here's a sample run of the program:
$ python random_numbers.py
35
10
45
59
45
100
8
31
48
6
"""
import random
NUM_RANDOM=10
MIN_RANDOM=0
MAX_RANDOM=100
def main():
NUM_RANDOM=0
for i in range(10):
print(random.randint(MIN_RANDOM,MAX_RANDOM))
if __name__ == '__main__':
main()
| true |
cf695905d4d217da034247bf4bd9d5b4ab3b0c76 | xiaowuc2/Code-in-Place-2021-Assignment-Solution | /Assignment-3/2. Finding Forest Flames.py | 1,630 | 4.1875 | 4 | """
This program highlights fires in an image by identifying pixels
whose red intensity is more than INTENSITY_THRESHOLD times the
average of the red, green, and blue values at a pixel. Those
"sufficiently red" pixels are then highlighted in the image
and other pixels are turned grey, by setting the pixel red,
green, and blue values to be all the same average value.
"""
from simpleimage import SimpleImage
INTENSITY_THRESHOLD = 1.0
DEFAULT_FILE = 'images/greenland-fire.png'
def find_flames(filename):
"""
This function should highlight the "sufficiently red" pixels
in the image and grayscale all other pixels in the image
in order to highlight areas of wildfires.
"""
image = SimpleImage(filename)
# TODO: your code here
for pixel in image:
average=(pixel.red+pixel.green+pixel.blue)//3
if pixel.red>=average*INTENSITY_THRESHOLD:
pixel.red=255
pixel.green=0
pixel.blue=0
else:
pixel.red=average
pixel.blue=average
pixel.green=average
return image
def main():
# Get file name from user input
filename = get_file()
# Show the original fire
original_fire = SimpleImage(filename)
original_fire.show()
# Show the highlighted fire
highlighted_fire = find_flames(filename)
highlighted_fire.show()
def get_file():
# Read image file path from user, or use the default file
filename = input('Enter image file (or press enter for default): ')
if filename == '':
filename = DEFAULT_FILE
return filename
if __name__ == '__main__':
main()
| true |
13b15323e2cca29ee326a58a7b7a74bf997f3ecd | Graey/pythoncharmers | /Die_Roller.py | 322 | 4.1875 | 4 | #Using Random Number Generator
import random
min_value = 1
max_value = 6
again = True
while again:
print(random.randint(min_value, max_value))
another_roll = input('Want to roll the dice again? ')
if another_roll == 'yes' or another_roll == 'y':
again = True
else:
again = False
| true |
09a05fdb4236cebffaa44ae9b71b734e6b0d82b2 | SMinTexas/multiply_a_list | /mult_list.py | 349 | 4.1875 | 4 | # Given a list of numbers, and a single factor (also a number), create a
# new list consisting of each of the numbers in the first list multiplied by
# the factor. Print this list.
mult_factor = 2
numbers = [2,4,6,8,10]
new_numbers = []
for number in numbers:
product = number * mult_factor
new_numbers.append(product)
print(new_numbers) | true |
8a1bab3272fd58fe4999fe571fa7eb58f1cac9e4 | Souravvk18/Python-Project | /dice_roll.py | 1,204 | 5 | 5 | '''
The Dice Roll Simulation can be done by
choosing a random integer between 1 and 6 for which we can use the random module in the Python programming language.
The smallest value of a dice roll is 1 and the largest is 6, this logic can be used to simulate a dice roll.
This gives us the start and end values to use in our random.randint() function. Now let’s see how to simulate a dice roll with Python:
'''
#importing module for random number generation
import random
#range of the values of a dice
min_val = 1
max_val = 6
#to loop the rolling through user input
roll_again = "yes"
#loop
while roll_again == "yes" or roll_again == "y":
print("Rolling The Dices...")
print("The Values are :")
#generating and printing 1st random integer from 1 to 6
print(random.randint(min_val, max_val))
#generating and printing 2nd random integer from 1 to 6
print(random.randint(min_val, max_val))
#asking user to roll the dice again. Any input other than yes or y will terminate the loop
roll_again = input("Roll the Dices Again?")
'''
Rolling The Dices...
The Values are :
2
3
Roll the Dices Again?yes
Rolling The Dices...
The Values are :
1
5
''' | true |
b836b5f8ee930033348291d83be460e57ef5fd0d | Souravvk18/Python-Project | /text_based.py | 861 | 4.34375 | 4 | '''
you will learn how to create a very basic text-based game with Python.
Here I will show you the basic idea of how you can create this game and then you can modify or
increase the size of this game with more situations and user inputs to suit you.
'''
name = str(input("Enter Your Name: "))
print(f"{name} you are stuck at work")
print(" You are still working and suddenly you you saw a ghost, Now you have two options")
print("1.Run. 2.Jump from the window")
user = int(input("Choose 1 or 2: "))
if user == 1:
print("You did it")
elif user == 2:
print("You are not that smart")
else:
print("Please Check your input")
'''
output-
Enter Your Name: sourav
sourav you are stuck at work
You are still working and suddenly you you saw a ghost, Now you have two options
1.Run. 2.Jump from the window
Choose 1 or 2: 2
You are not that smart
''' | true |
a4626ca589be214fc375c7c0fe005807cf4f9291 | rosekay/data_structures | /lists.py | 1,232 | 4.34375 | 4 | #list methods applied
list_a = [15, 13.56, 200.0, -34,-1]
list_b = ['a', 'b', 'g',"henry", 7]
def list_max_min(price):
#list comprehension
return [num for num in price if num == min(price) or num == max(price)]
def list_reverse(price):
#reverse the list
price.reverse()
return price
def list_count(price, num):
#checks whether an element occurs in a list
return price.count(num)
def list_odd_position(price ):
#returns the elements on odd positions in a list
return [num for num in price if price.index(num) % 2 != 0]
def list_total(price):
#computes the running total of a list
#simple version
# return sum(price)
#for loop
total = 0
for num in price:
total += num
return total
def list_concat(price, new_price):
#concatenates two lists together
if type(new_price) == list:
price.append(new_price)
return price
else:
return "Not a list"
def list_merge_sort(price, new_price):
#merges two sorted lists into a sorted list
price.append(new_price)
return sorted(price)
print list_max_min(list_a)
print list_reverse(list_a)
print list_count(list_a, -34)
print list_odd_position(list_a)
print list_total(list_a )
print list_concat(list_a, list_b)
print list_merge_sort(list_a, list_b)
| true |
6983b9b8ad8737a418c59ed38256630d3ed7b598 | SbSharK/PYTHON | /PYTHON/whileelse.py | 246 | 4.1875 | 4 | num = int(input("Enter a no.: "))
if num<0:
print("Enter a positive number!")
else:
while num>0:
if num==6:
break
print(num)
num-=1
else:
print("Loop is not terminated with break") | true |
0ecddbc90aaf35f0fb28351b096deb152ebd0e44 | tuhiniris/Python-ShortCodes-Applications | /patterns1/hollow inverted right triangle star pattern.py | 374 | 4.1875 | 4 | '''
Pattern
Hollow inverted right triangle star pattern
Enter number of rows: 5
*****
* *
* *
**
*
'''
print('Hollow inverted right triangle star pattern: ')
rows=int(input('Enter number of rows: '))
for i in range(1,rows+1):
for j in range(i,rows+1):
if i==1 or i==j or j==rows:
print('*',end=' ')
else:
print(' ',end=' ')
print('\n',end='') | true |
0215399d8173998139d327bfd73917982e9a4e7a | tuhiniris/Python-ShortCodes-Applications | /array/right rotate an array.py | 797 | 4.3125 | 4 | from array import *
arr=array("i",[])
n=int(input("Enter the length of the array: "))
for i in range(n):
x=int(input(f"Enter the elements into array at position {i}: "))
arr.append(x)
print("Origianl elements of the array: ",end=" ")
for i in range(n):
print(arr[i],end=" ")
print()
#Rotate the given array by n times towards left
t=int(input("Enter the number of times an array should be rotated: "))
for i in range(0,t):
#stores the last element of the array
last = arr[n-1]
for j in range(n-1,-1,-1):
#Shift element of array by one
arr[j]=arr[j-1]
#last element of array will be added to the end
arr[0]=last
print()
#Display resulting array after rotation
print("Array after left rotation: ",end=" ")
for i in range(0,n):
print(arr[i],end=" ")
print()
| true |
6a157dd21d9cdff8fbd373649f1a5dead92151ac | tuhiniris/Python-ShortCodes-Applications | /basic program/print the sum of negative numbers, positive even numbers and positive odd numbers in a given list.py | 779 | 4.125 | 4 | n= int(input("Enter the number of elements to be in the list: "))
even=[]
odd=[]
negative=[]
b=[]
for i in range(0,n):
a=int(input("Enter the element: "))
b.append(a)
print("Element in the list are: {}".format(b))
sum_negative = 0
sum_positive_even = 0
sum_positive_odd = 0
for j in b:
if j > 0:
if j%2 == 0:
even.append(j)
sum_positive_even += j
else:
odd.append(j)
sum_positive_odd += j
else:
negative.append(j)
sum_negative += j
print("Sum of all positive even numbersin the list, i.e {1} are: {0}".format(sum_positive_even,even))
print("Sum of all positive odd numbers in the list, i.e {1} are: {0}".format(sum_positive_odd,odd))
print("Sum of all negative numbers in the list, i.e {1} are: {0}".format(sum_negative,negative)) | true |
987fdb176bd3aba61e03f288233d20db427e47df | tuhiniris/Python-ShortCodes-Applications | /array/print the number of elements of an array.py | 611 | 4.40625 | 4 | """
In this program, we need to count and print the number of elements present in the array.
Some elements present in the array can be found by calculating the length of the array.
"""
from array import *
arr=array("i",[])
n=int(input("Enter the length of the array: "))
for i in range(n):
x=int(input(f"Enter the elements of the array at position {i}: "))
arr.append(x)
print("elements in the array: ",end=" ")
for i in range(n):
print(arr[i],end=" ")
print()
#Number of elements present in the array can be found by using len()
print(f"Number of elements present in given array: {len(arr)}") | true |
7139cde7a49d54db3883ae161d1acecf942489ed | tuhiniris/Python-ShortCodes-Applications | /list/Reversing a List.py | 1,808 | 5.03125 | 5 | print("-------------METHOD 1------------------")
"""
Using the reversed() built-in function.
In this method, we neither reverse a list in-place
(modify the original list), nor we create any copy of the list.
Instead, we get a reverse iterator which we use to cycle through the list.
"""
def reverse(list):
return [ele for ele in reversed(list)]
list=[]
n=int(input("Enter size of the list: "))
for i in range(n):
data=int(input("Enter elements of list: "))
list.append(data)
print(f"elements of the list: {list}")
print(f"Reverse of the list is: {reverse(list)}")
print("-------------METHOD 2--------------------")
"""
Using the reverse() built-in function.
Using the reverse() method we can reverse the contents
of the list object in-place i.e.,
we don’t need to create a new list instead we just copy
the existing elements to the original list in reverse order.
This method directly modifies the original list.
"""
def reverse(list):
list.reverse()
return list
list=[]
n=int(input("Enter size of the list: "))
for i in range(n):
data=int(input("Enter elements of list: "))
list.append(data)
print(f"elements of the list: {list}")
print(f"Reverse of the list is: {reverse(list)}")
print("---------------METHOD 3-------------------")
"""
Using the slicing technique.
In this technique, a copy of the list is made
and the list is not sorted in-place.
Creating a copy requires more space to hold
all of the existing elements.
This exhausts more memory.
"""
def reverse(list):
new_List=list[::-1]
return new_List
list=[]
n=int(input("Enter size of the list: "))
for i in range(n):
data=int(input("Enter elements of list: "))
list.append(data)
print(f"elements of the list: {list}")
print(f"Reverse of the list is: {reverse(list)}")
| true |
584171438444fc7001b68698651b725933f58b26 | tuhiniris/Python-ShortCodes-Applications | /patterns2/program to print 0 or 1 square number pattern.py | 390 | 4.1875 | 4 | '''
Pattern
Square number pattern:
Enter number of rows: 5
Enter number of column: 5
11111
11111
11111
11111
11111
'''
print('Square number pattern: ')
number_rows=int(input('Enter number of rows: '))
number_columns=int(input('Enter number of columns:'))
for row in range(1,number_rows+1):
for column in range(1,number_columns+1):
print('1',end='')
print('\n',end='')
| true |
7166cac047616cf383f96c4584f7cf8a756ede9e | tuhiniris/Python-ShortCodes-Applications | /patterns1/alphabet pattern_29.py | 327 | 4.25 | 4 | """
Example:
Enter number: 5
A B C D E
A B C D
A B C
A B
A
"""
print('Alphabet Pattern: ')
number_rows = int(input("Enter number of rows: "))
for row in range(1,number_rows+1):
print(" "*(row-1),end="")
for column in range(1,number_rows+2-row):
print(chr(64+column),end=" ")
print() | true |
05245453d39856168dbc249ebf5de56d659b338c | tuhiniris/Python-ShortCodes-Applications | /number programs/determine whether a given number is a happy number.py | 1,573 | 4.25 | 4 | """
Happy number:
The happy number can be defined as
a number which will yield 1 when it is replaced by the sum of the square of its digits repeatedly.
If this process results in an endless cycle of numbers containing 4,then the number is called an unhappy number.
For example, 32 is a happy number as the process yields 1 as follows
3**2 + 2**2 = 13
1**2 + 3**2 = 10
1**2 + 0**2 = 1
Some of the other examples of happy numbers are 7, 28, 100, 320 and so on.
The unhappy number will result in a cycle of 4, 16, 37, 58, 89, 145, 42, 20, 4, ....
To find whether a given number is happy or not,
calculate the square of each digit present in number and add it to a variable sum.
If resulting sum is equal to 1 then, given number is a happy number.
If the sum is equal to 4 then, the number is an unhappy number.
Else, replace the number with the sum of the square of digits.
"""
#isHappyNumber() will determine whether a number is happy or not
num=int(input("Enter a number: "))
def isHappyNumber(num):
rem = sum = 0
#Calculates the sum of squares of digits
while(num > 0):
rem = num%10
sum = sum + (rem*rem)
num = num//10
return sum
result = num
while(result != 1 and result != 4):
result = isHappyNumber(result)
#Happy number always ends with 1
if(result == 1):
print(str(num) + " is a happy number")
#Unhappy number ends in a cycle of repeating numbers which contain 4
elif(result == 4):
print(str(num) + " is not a happy number") | true |
091a210b5cc80d42ce28a35b80b7186e808ae101 | tuhiniris/Python-ShortCodes-Applications | /strings/find the frequency of characters.py | 1,095 | 4.3125 | 4 | """
To accomplish this task, we will maintain an array called freq with same size of the length of the string. Freq will be used to maintain the count of each character present in the string. Now, iterate through the string to compare each character with rest of the string. Increment the count of corresponding element in freq. Finally, iterate through freq to display the frequencies of characters."""
string=input('Enter string here: ').lower()
freq = [None] * len(string);
for i in range(0, len(string)):
freq[i] = 1;
for j in range(i+1, len(string)):
if(string[i] == string[j]):
freq[i] = freq[i] + 1;
#Set string[j] to 0 to avoid printing visited character
string = string[ : j] + '0' + string[j+1 : ];
#Displays the each character and their corresponding frequency
print("Characters and their corresponding frequencies");
for i in range(0, len(freq)):
if(string[i] != ' ' and string[i] != '0'):
print(f'frequency of {string[i]} is: {str(freq[i])}') | true |
a92e1513deea941b6d84b8c6bfdac8a5accb8715 | tuhiniris/Python-ShortCodes-Applications | /tuples/Access Tuple Item.py | 367 | 4.21875 | 4 | '''
To access tuple item need to refer it by it's the index number,
inside square brackets:
'''
a=[]
n=int(input('Enter size of tuple: '))
for i in range(n):
data=input('Enter elements of tuple: ')
a.append(data)
tuple_a=tuple(a)
print(f'Tuple elements: {tuple_a}')
for i in range(n):
print(f'\nElements of tuple at position {i+1} is: {tuple_a[i]}') | true |
f3ff7b22352de6864f57eb3c9b52e4643215de8c | tuhiniris/Python-ShortCodes-Applications | /file handling/Read a File and Capitalize the First Letter of Every Word in the File.py | 346 | 4.28125 | 4 | '''
Problem Description:
-------------------
The program reads a file and capitalizes
the first letter of every word in the file.
'''
print(__doc__,end="")
print('-'*25)
fileName=input('Enter file name: ')
print('-'*35)
print(f'Contents of the file are : ')
with open(fileName,'r') as f:
for line in f:
l=line.title()
print(l) | true |
3fc0f4902507d2fab0a8d3b597ab87dd24981a13 | tuhiniris/Python-ShortCodes-Applications | /list/Find the Union of two Lists.py | 1,136 | 4.4375 | 4 | """
Problem Description
The program takes two lists and finds the unions of the two lists.
Problem Solution
1. Define a function which accepts two lists and returns the union of them.
2. Declare two empty lists and initialise to an empty list.
3. Consider a for loop to accept values for two lists.
4. Take the number of elements in the list and store it in a variable.
5. Accept the values into the list using another for loop and insert into the list.
6. Repeat 4 and 5 for the second list also.
7. Find the union of the two lists.
8. Print the union.
9. Exit.
"""
a=[]
n=int(input("Enter the size of first list: "))
for i in range(n):
data=int(input("Enter elements of the list: "))
a.append(data)
print("elements of the first list: ",end=" ")
for i in range(n):
print(a[i],end=" ")
print()
b=[]
n1=int(input("Enter the size of second list: "))
for i in range(n1):
data1=int(input("Enter elements of the list: "))
b.append(data1)
print("elements of the second list: ",end=" ")
for i in range(n1):
print(b[i],end=" ")
print()
union=list(set().union(a,b))
print(f"Union of two lists is: {union}") | true |
5bffa97dee1d35e4f0901c7fa8ca8bb4b7d59d9e | tuhiniris/Python-ShortCodes-Applications | /basic program/test Collatz Conjecture for a Given Number.py | 897 | 4.5625 | 5 | # a Python program to test Collatz conjecture for a given number
"""The Collatz conjecture is a conjecture that a particular sequence always reaches 1.
The sequence is defined as
start with a number n.
The next number in the sequence is n/2 if n is even and 3n + 1 if n is odd.
Problem Solution
1. Create a function collatz that takes an integer n as argument.
2. Create a loop that runs as long as n is greater than 1.
3. In each iteration of the loop, update the value of n.
4. If n is even, set n to n/2 and if n is odd, set it to 3n + 1.
5. Print the value of n in each iteration.
"""
def collatz(n):
while n > 1:
print(n, end=' ')
if (n % 2):
# n is odd
n = 3*n + 1
else:
# n is even
n = n//2
print(1, end='')
n = int(input('Enter n: '))
print('Sequence: ', end='')
collatz(n) | true |
47d85156bab21b683fd7b8314b2e5e5a4a9872cc | tuhiniris/Python-ShortCodes-Applications | /patterns1/alphabet pattern_3.py | 281 | 4.25 | 4 | """
Example:
Enter the number of rows: 5
A A A A A
B B B B
C C C
D D
E
"""
print('Alphabet Pattern: ')
number_rows=int(input('Enter number of rows: '))
for row in range(1,number_rows+1):
for column in range(1,number_rows+2-row):
print(chr(64+row),end=' ')
print() | true |
4961def023e1e2fb805239116cd8785ea4b09b74 | tuhiniris/Python-ShortCodes-Applications | /list/Put Even and Odd elements in a List into Two Different Lists.py | 826 | 4.46875 | 4 | """
Problem Description
The program takes a list and puts the even and odd elements in it into two separate lists.
Problem Solution
1. Take in the number of elements and store it in a variable.
2. Take in the elements of the list one by one.
3. Use a for loop to traverse through the elements of the list and an if statement to
check if the element is even or odd.
4. If the element is even, append it to a separate list and if it is odd,
append it to a different one.
5. Display the elements in both the lists.
6. Exit.
"""
a=[]
n=int(input("Enter number of elements: "))
for i in range(n):
b=int(input("Enter the elements of the array: "))
a.append(b)
even=[]
odd=[]
for j in a:
if j%2 == 0:
even.append(j)
else:
odd.append(j)
print(f"The even list: {even}")
print(f"The odd list: {odd}") | true |
377813d90508ffa5402d90d7a288c078d9fa3786 | tuhiniris/Python-ShortCodes-Applications | /strings/replace the spaces of a string with a specific character.py | 208 | 4.15625 | 4 | string=input('Enter string here: ')
character='_'
#replace space with specific character
string=string.replace(' ',character)
print(f'String after replacing spaces with given character: \" {string} \" ') | true |
454c5b13b7079f428bd1b04b3a243a9c4c05bdcd | tuhiniris/Python-ShortCodes-Applications | /list/Ways to find length of list.py | 1,584 | 4.46875 | 4 | #naive method
print("----------METHOD 1--------------------------")
list=[]
n=int(input("Enter the size of the list: "))
for i in range(n):
data=int(input("Enter elements of the array: "))
list.append(data)
print(f"elements in the list: {list}",end=" ")
# for i in range(n):
# print(list[i],end=" ")
print()
counter=0
for i in list:
counter=counter+1
print(f"Length of list using navie method is: {counter}")
print("---------------------METHOD 2-----------------------")
"""
using len() method
The len() method offers the most used and easy way to find length of any list.
This is the most conventional technique adopted by all the programmers today.
"""
a=[]
a.append("Hello")
a.append("How")
a.append("are")
a.append("you")
a.append("?")
print(f"The length of list {a} is: {len(a)}")
print("------------------METHOD 3------------------------")
"""
Using length_hint()
This technique is lesser known technique of finding list length.
This particular method is defined in operator class and it can also tell
the no. of elements present in the list.
"""
from operator import length_hint
list=[]
n=int(input("Enter the size of the list: "))
for i in range(n):
data=int(input("Enter elements of the list: "))
list.append(data)
print(f"The list is: {list}")
#Finding length of list using len()
list_len=len(list)
#Find length of list using length_hint()
list_len_hint=length_hint(list)
#print length of list
print(f"Length of list using len() is : {list_len}")
print(f"length of list using length_hint() is: {list_len_hint}")
| true |
7c9bef892156d20b357d5855820d8b7e79c316af | tuhiniris/Python-ShortCodes-Applications | /dictionary/Check if a Given Key Exists in a Dictionary or Not.py | 731 | 4.21875 | 4 | '''
Problem Description
The program takes a dictionary and checks if a
given key exists in a dictionary or not.
Problem Solution
1. Declare and initialize a dictionary to have some key-value pairs.
2. Take a key from the user and store it in a variable.
3. Using an if statement and the in operator,
check if the key is present in the dictionary
using the dictionary.keys() method.
4. If it is present, print the value of the key.
5. If it isn’t present, display that the key
isn’t present in the dictionary.
6. Exit.
'''
d={'A' : 1, 'B' : 2, 'C' : 3}
key=input('Enter key to check: ')
if key in d.keys():
print(f'Key is present and value of the key is: {d[key]}')
else:
print('Key is not present.') | true |
293e894a12b3f1064a46443f84cbfe4d0b70db6e | tuhiniris/Python-ShortCodes-Applications | /basic program/count set bits in a number.py | 724 | 4.21875 | 4 | """
The program finds the number of ones in the binary representation of a number.
Problem Solution
1. Create a function count_set_bits that takes a number n as argument.
2. The function works by performing bitwise AND of n with n – 1 and storing the result in n until n becomes 0.
3. Performing bitwise AND with n – 1 has the effect of clearing the rightmost set bit of n.
4. Thus the number of operations required to make n zero is the number of set bits in n.
"""
def count_set_bits(n):
count = 0
while n:
n &= n-1
count += 1
return count
n=int(input("Enter a number: "))
print(f"Number of set bits (number of ones) in number = {n} where binary of the number = {bin(n)} is {count_set_bits(n)}") | true |
6d7a32d214efdcef903bd37f2030ea91df771a05 | tuhiniris/Python-ShortCodes-Applications | /number programs/check if a number is an Armstrong number.py | 414 | 4.375 | 4 | #Python Program to check if a number is an Armstrong number..
n = int(input("Enter the number: "))
a = list(map(int,str(n)))
print(f"the value of a in the program {a}")
b = list(map(lambda x:x**3,a))
print(f"the value of b in the program {b} and sum of elements in b is: {sum(b)}")
if sum(b)==n:
print(f"The number {n} is an armstrong number.")
else:
print(f"The number {n} is not an armstrong number.") | true |
5f4083e687b65899f292802a57f3eb9b1b64ca5a | tuhiniris/Python-ShortCodes-Applications | /basic program/program takes an upper range and lower range and finds those numbers within the range which are divisible by 7 and multiple of 5.py | 295 | 4.125 | 4 | #program takes an upper range and lower range and finds those numbers within the range which are divisible by 7 and multiple of 5
lower = int(input("Enter the lower range: "))
upper = int(input("Enter the upper range: "))
for i in range(lower,upper+1):
if i%7 == 0 and i%5==0:
print(i)
| true |
7599d879058a9fca9866b3f68d93bcf2bda0001c | tuhiniris/Python-ShortCodes-Applications | /number programs/Swapping of two numbers without temperay variable.py | 1,492 | 4.15625 | 4 | ##Problem Description
##The program takes both the values from the user and swaps them
print("-------------------------------Method 1-----------------------")
a=int(input("Enter the First Number: "))
b=int(input("Enter the Second Number: "))
print("Before swapping First Number is {0} and Second Number is {1}" .format(a,b))
a=a+b
b=a-b
a=a-b
print("After swapping First number is {0} and Second Number is {1}".format(a,b))
print("-------------------------------Method 2-----------------------")
a=int(input("Enter the First Number: "))
b=int(input("Enter the Second Number: "))
print("Before swapping First Number is {0} and Second Number is {1}" .format(a,b))
a=a*b
b=a//b
a=a//b
print("After swapping First number is {0} and Second Number is {1}".format(a,b))
print("-------------------------------Method 3-----------------------")
a=int(input("Enter the First Number: "))
b=int(input("Enter the Second Number: "))
print("Before swapping First Number is {0} and Second Number is {1}" .format(a,b))
temp= a
a=b
b=temp
print("After swapping First Number is {0} and Second Number is {1}" .format(a,b))
print("-------------------------------Method 4-----------------------")
a=int(input("Enter the First Number: "))
b=int(input("Enter the Second Number: "))
print("Before swapping First Number is {0} and Second Number is {1}" .format(a,b))
a = a ^ b
b= a ^ b
a = a ^ b
print("After swapping First Number is {0} and Second Number is {1}" .format(a,b))
| true |
ad835b40d50ac5db87b17903ac17f79c3fc820ef | tuhiniris/Python-ShortCodes-Applications | /matrix/find the transpose of a given matrix.py | 1,212 | 4.6875 | 5 | print('''
Note!
Transpose of a matrix can be found by interchanging rows with the column that is,
rows of the original matrix will become columns of the new matrix.
Similarly, columns in the original matrix will become rows in the new matrix.
If the dimension of the original matrix is 2 × 3 then,
the dimensions of the new transposed matrix will be 3 × 2.
''')
matrix=[]
row=int(input('enter size of row of matrix: '))
column=int(input('enter size of column of matrix: '))
for i in range(row):
a=[]
for j in range(column):
j=int(input(f'enter elements of matrix at poistion row({i})column({j}): '))
a.append(j)
print()
matrix.append(a)
print('Elements of matrix: ')
for i in range(row):
for j in range(column):
print(matrix[i][j],end=" ")
print()
#Declare array t with reverse dimensions and is initialized with zeroes.
t = [[0]*row for i in range(column)];
#calcutaes transpose of given matrix
for i in range(column):
for j in range(row):
#converts the row of original matrix into column of transposed matrix
t[i][j]=matrix[j][i]
print('transpose of given matrix: ')
for i in range(column):
for j in range(row):
print(t[i][j],end=" ")
print() | true |
ae96cee9c409b9af3ee4f2cca771093eb5fd32cd | tuhiniris/Python-ShortCodes-Applications | /list/Generate Random Numbers from 1 to 20 and Append Them to the List.py | 564 | 4.53125 | 5 | """
Problem Description
The program takes in the number of elements and generates random numbers from 1 to 20 and appends them to the list.
Problem Solution
1. Import the random module into the program.
2. Take the number of elements from the user.
3. Use a for loop, random.randint() is used to generate random numbers which are them appending to a list.
4. Then print the randomised list.
4. Exit.
"""
import random
a=[]
n=int(input("Enter number of elements: "))
for i in range(n):
a.append(random.randint(1,20))
print(f"randomised list: {a}") | true |
4730566ea55fb752722cfb9257308de6de3ccc9c | tuhiniris/Python-ShortCodes-Applications | /recursion/Find if a Number is Prime or Not Prime Using Recursion.py | 539 | 4.25 | 4 | '''
Problem Description
-------------------
The program takes a number
and finds if the number is
prime or not using recursion.
'''
print(__doc__,end="")
print('-'*25)
def check(n, div = None):
if div is None:
div = n - 1
while div >= 2:
if n % div == 0:
print(f"Number: {n}, is not prime")
return False
else:
return check(n, div-1)
else:
print(f"Number: {n}, is a prime")
return 'True'
n=int(input("Enter number: "))
check(n) | true |
ef045cb0440d1fe1466a7fda39915e68db973872 | mwnickerson/python-crash-course | /chapter_9/cars_vers4.py | 930 | 4.1875 | 4 | # Cars version 4
# Chapter 9
# modifying an attributes vales through a method
class Car:
"""a simple attempt to simulate a car"""
def __init__(self, make, model, year):
"""Initialize attributes to describe a car"""
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
"""return a descriptive name of a car"""
long_name =f"{self.year} {self.make} {self.model}"
return long_name.title()
def read_odometer(self):
"""reads odometer"""
print(f"This car has {self.odometer_reading}")
def update_odometer(self, mileage):
"""
Set the odometer reading to the given value
"""
self.odometer_reading = mileage
my_new_car = Car('audi', 'a4', 2019)
print(my_new_car.get_descriptive_name())
my_new_car.update_odometer(23)
my_new_car.read_odometer() | true |
7e79127380cc86a94a1c4c5e836b8e00158481dc | mwnickerson/python-crash-course | /chapter_7/pizza_toppings.py | 321 | 4.28125 | 4 | # pizza toppings
# chapter 7 exercise 4
# a conditional loop that prompts user to enter toppings
prompt ="\nWhat topping would you like on your pizza?"
message = ""
while message != 'quit':
message = input(prompt)
topping = message
if message != 'quit':
print(f"I will add {topping} to your pizza!") | true |
22bdf928b3a3d79e5dccd1361536f8fb7f0136f1 | mwnickerson/python-crash-course | /chapter_5/voting_vers2.py | 218 | 4.25 | 4 | # if and else statement
age = 17
if age >= 18:
print("You are able to vote!")
print("Have you registered to vote?")
else:
print("Sorry you are too young to vote.")
print("Please register to vote as you turn 18!")
| true |
7393500c1f9e8b7d3e3ceafce7f4e923d9111ae1 | hangnguyen81/HY-data-analysis-with-python | /part02-e13_diamond/diamond.py | 703 | 4.3125 | 4 | #!/usr/bin/env python3
'''
Create a function diamond that returns a two dimensional integer array where the 1s form a diamond shape.
Rest of the numbers are 0. The function should get a parameter that tells the length of a side of the diamond.
Do this using the eye and concatenate functions of NumPy and array slicing.
'''
import numpy as np
from numpy.core.records import array
def diamond(n):
inital_array = np.eye(n, dtype=int)
half_diamond = np.concatenate((inital_array[::-1],inital_array[:,1:]), axis=1)
full_diamond = np.concatenate((half_diamond[:-1],half_diamond[::-1]), axis=0)
return full_diamond
def main():
print(diamond(4))
if __name__ == "__main__":
main()
| true |
14f3fd6898259a53461de709e7dc409a28ba829f | hangnguyen81/HY-data-analysis-with-python | /part01-e07_areas_of_shapes/areas_of_shapes.py | 902 | 4.15625 | 4 | #!/usr/bin/env python3
import math
def main():
while 1:
chosen = input('Choose a shape (triangle, rectangle, circle):')
chosen = chosen.lower()
if chosen == '':
break
elif chosen == 'triangle':
b=int(input('Give base of the triangle:'))
h=int(input('Give height of the triangle:'))
area = (b * h)/2
print(f"The area is {area}")
elif chosen == 'rectangle':
w = int(input('Give width of the rectangle:'))
h = int(input('Give height of the rectangle'))
area = w * h
print(f"The area is {area}")
elif chosen == 'circle':
r = int(input('Give radius of the circle:'))
area = math.pi * r**2
print(f"The area is {area}")
else:
print('Unknown shape!')
if __name__ == "__main__":
main()
| true |
f86510558d0e668d9fc15fd0a3ff277ac93ec656 | keerthisreedeep/LuminarPythonNOV | /Functionsandmodules/function pgm one.py | 1,125 | 4.46875 | 4 | #function
#functions are used to perform a specific task
print() # print msg int the console
input() # to read value through console
int() # type cast to int
# user defined function
# syntax
# def functionname(arg1,arg2,arg3,.................argn):
# function defnition
#---------------------------------------------------------
# function for adding two numbers
def add(n1,n2):
res=n1+n2
print(res)
#calling function by using function name
add(50,60)
#------------------------------------------------------
# function for subtracting two numbers
def sub(n1,n2):
res=n1-n2
print(res)
#calling function by using function name
sub(50,60)
#--------------------------------------------------------
# function for multiply two numbers
def mul(n1,n2):
res=n1*n2
print(product)
#calling function by using function name
product(50,60)
#--------------------------------------------------------
# function for divide two numbers
def div(n1,n2):
res=n1/n2
print(quotioent)
#calling function by using function name
quotient(50,60)
#--------------------------------------------------------- | true |
cb1e9921d2f54d3bc3e3cb8bf67ca3e2af019197 | mgeorgic/Python-Challenge | /PyBank/main.py | 2,471 | 4.25 | 4 | # Import os module to create file paths across operating systems
# Import csv module for reading CSV files
import csv
import os
# Set a path to collect the CSV data from the Resources folder
PyBankcsv = os.path.join('Resources', 'budget_data.csv')
# Open the CSV in reader mode using the path above PyBankiv
with open (PyBankcsv, newline="") as csvfile:
# Specifies delimiter and variable that holds contents
csvreader = csv.reader(csvfile, delimiter=',')
# Create header row first
header = next(csvreader)
monthly_count = []
# Empty lists to store the data
profit = []
profit_change = []
# Read through each row of data after the header
for row in csvreader:
# populate the dates in column "monthly_count"
monthly_count.append(row[0])
# Append the profit information
profit.append(int(row[1]))
#Deleted unneccesary calculations bc I'll do them in print functions
#Calculate the changes in Profit over the entire period
for i in range(len(profit)):
# Calculate the average change in profits.
if i < 85:
profit_change.append(profit[i+1]-profit[i])
#Average of changes in Profit
avg_change = sum(profit_change)/len(profit_change)
# Greatest increase in profit (date and amount)
greatest_increase = max(profit_change)
greatest_index = profit_change.index(greatest_increase)
greatest_date = monthly_count[greatest_index+1]
# Greatest decrease in profit (date and amount)
greatest_decrease = min(profit_change)
lowest_index = profit_change.index(greatest_decrease)
lowest_date = monthly_count[lowest_index+1]
# Print the summary table in display
# Use f-string to accept all data types without conversion
# len counts the total amount of months in column "Monthly_Count"
# sum adds up all the profits in column "Profit"
# Round the average change to two decimals
report = f"""Financial Analysis
-----------------------
Total Months:{len(monthly_count)}
Total: ${sum(profit)}
Average Change: ${str(round(avg_change,2))}
Greatest Increase in Profits: {greatest_date} (${str(greatest_increase)})
Greatest Decrease in Profits: {lowest_date} (${str(greatest_decrease)})"""
print (report)
# Export the file to write
output_path = os.path.join('analysis','Simplified_budget_data.txt')
# Open the file using write mode while holding the contents in the file
with open(output_path, 'w') as txtfile:
# Write in this order
txtfile.write(report)
| true |
672c5c943f6b90605cf98d7ac4672316df20773a | vittal666/Python-Assignments | /Third Assignment/Question-9.py | 399 | 4.28125 | 4 | word = input("Enter a string : ")
lowerCaseCount = 0
upperCaseCount = 0
for char in word:
print(char)
if char.islower() :
lowerCaseCount = lowerCaseCount+1
if char.isupper() :
upperCaseCount = upperCaseCount+1
print("Number of Uppercase characters in the string is :", lowerCaseCount)
print("Number of Lowercase characters in the string is :", upperCaseCount)
| true |
d614fd1df5ad36a1237a29c998e72af51dec2c99 | ahmedbodi/ProgrammingHelp | /minmax.py | 322 | 4.125 | 4 | def minmax(numbers):
lowest = None
highest = None
for number in numbers:
if number < lowest or lowest is None:
lowest = number
if number > highest or highest is None:
highest = number
return lowest, highest
min, max = minmax([1,2,3,4,5,6,7,8,9,10])
print(min, max)
| true |
fa050769df11502c362c3f7000dae14a0373a5c9 | jbenejam7/Ith-order-statistic | /insertionsort.py | 713 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 29 18:02:06 2021
@author: djwre
"""
import random
#Function for InsertionSort
def InsertionSort(A, n):
#traverse through 1 to len(arr)
for i in range(1, n):
key = A[i]
#move elements of arr [0..i-1], that are
#greater than key, to one position ahead
#of the current position
j = i-1
while j >= 0 and key < A[j]:
A[j+1] = A[j]
j -= 1
A[j+1] = key
'''
#driver code to test above
n = 5
A = random.sample(range(1, 99), n)
InsertionSort(A, n)
for i in range(len(A)):
print ("%d" %A[i])
'''
| true |
9a6829d0e2e6cd55e7b969674845a733a14d31d2 | rabi-siddique/LeetCode | /Lists/MergeKSortedLists.py | 1,581 | 4.4375 | 4 | '''
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order.
Merge all the linked-lists into one sorted linked-list and return it.
Example 1:
Input: lists = [[1,4,5],[1,3,4],[2,6]]
Output: [1,1,2,3,4,4,5,6]
Explanation: The linked-lists are:
[
1->4->5,
1->3->4,
2->6
]
merging them into one sorted list:
1->1->2->3->4->4->5->6
Example 2:
Input: lists = []
Output: []
Example 3:
Input: lists = [[]]
Output: []
'''
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
#Created a list to store values for all list elements
arr = []
for l in lists:
while l:
arr.append(l.val)
l = l.next
#Sorting the array containing values from all lists
arr = sorted(arr)
#Creating a dummyNode which will assist in creating a sorted list
dummyNode = ListNode(0)
#head is set to the dummyNode
#this is done to return head.next which
#is the sorted list
head = dummyNode
for value in arr:
dummyNode.next = ListNode(value)
dummyNode = dummyNode.next
return head.next
| true |
55d2c65bb61b82e52e00c2f2f768399f17e78367 | evanmascitti/ecol-597-programming-for-ecologists | /Python/Homework_Day4_Mascitti_problem_2.py | 2,766 | 4.40625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Feb 1 21:16:35 2021
@author: evanm
"""
# assign raw data to variables
observed_group_1_data = [1, 4, 5, 3, 1, 5, 3, 7, 2, 2]
observed_group_2_data = [6, 7, 9, 3, 5, 7, 8, 10, 12]
combined_data = observed_group_1_data + observed_group_2_data
# define a function to compute the difference between the mean of two groups
def mean_diff(group_1, group_2):
group_1_mean = sum(group_1)/len(group_1)
group_2_mean = sum(group_2)/len(group_1)
experiment_diff = abs(group_1_mean - group_2_mean)
return(experiment_diff)
# apply the function to the observed data set
observed_difference = abs(mean_diff(group_1 = observed_group_1_data,
group_2 = observed_group_2_data))
# import the `random` library
import random
# Run the simulations by taking a random sample of half the observations from
# the whole data set. Allow the user to choose the number of simulations.
# Start the iteration number at 1
i = 1
# create an empty list that will be used to store the results of the simulations
x = []
# as user to supply number of simulations
n_simulations = int(input("How many random simulations do you want to run?"))
# Use a while loop to repeat the action as long as the iteration number
# is less than the desired number of simulations. For each iteration, append
# the list to house the mean difference for that simulation
while i <= n_simulations:
group_1 = random.sample(combined_data, len(observed_group_1_data))
group_2 = list(set(combined_data) - set(group_1))
departure = abs(mean_diff(group_1, group_2))
i += 1
x.append(departure)
# create another empty list which will be used to store whether the difference
# in the observed data set was larger than the randomly chosen data set
larger_diff_count = []
# loop over the mean of each simulation and append the list with a logical
# statement about whether it was larger or not.
for i in x:
if i >= 1:
larger_diff_count.append(True)
else:
larger_diff_count.append(False)
# The `larger_diff_count` list now contains the results of whether the observed
# difference was larger or smaller than the randomly generated data. Tally the number
# that exceeded the randomly chosen samples and print the results.
n_random_exceed = n_simulations - sum(larger_diff_count)
print("The difference betwen groups was ", round(observed_difference, 2), ".", sep="")
print("A difference at least this large occurred", n_random_exceed, "times out of", n_simulations, "simulations.")
print("p-value:", round(n_random_exceed / n_simulations, 3))
| true |
373ecc01e393f54d7d67e3fcba648bc9bdae323f | Teresa-Rosemary/Text-Pre-Processing-in-Python | /individual_python_files/word_tokenize.py | 880 | 4.15625 | 4 | # coding: utf-8
import nltk
from nltk import word_tokenize
def word_tokenize(text):
"""
take string input and return list of words.
use nltk.word_tokenize() to split the words.
"""
word_list=[]
for sentences in nltk.sent_tokenize(text):
for words in nltk.word_tokenize(sentences):
word_list.append(words)
return word_list
def main():
text = """Harry Potter is the most miserable, lonely boy you can imagine. He's shunned by his relatives, the Dursley's, that have raised him since he was an infant. He's forced to live in the cupboard under the stairs, forced to wear his cousin Dudley's hand-me-down clothes, and forced to go to his neighbour's house when the rest of the family is doing something fun. Yes, he's just about as miserable as you can get."""
print (word_tokenize(text))
if __name__ == '__main__':
main()
| true |
60154b97d18346acc13abb79f1026e4cf07f80e0 | scott-currie/data_structures_and_algorithms | /data_structures/binary_tree/binary_tree.py | 1,400 | 4.125 | 4 | from queue import Queue
class Node(object):
""""""
def __init__(self, val):
""""""
self.val = val
self.left = None
self.right = None
def __repr__(self):
""""""
return f'<Node object: val={ self.val }>'
def __str__(self):
""""""
return str(self.val)
class BinaryTree(object):
""""""
def __init__(self, it=None):
""""""
self.root = None
if it:
for el in it:
self.insert(el)
def __repr__(self):
""""""
pass
def __str__(self):
""""""
pass
def insert(self, val):
"""Insert a new node with supplied value in the first open position, following
breadth-first traversal order.
"""
new_node = Node(val)
if self.root is None:
self.root = new_node
return
q = Queue()
q.put(self.root)
while q.full():
def breadth_first(self, func=lambda x: print(x)):
if self.root is None:
print('No root.')
return
q = Queue()
q.put(self.root)
while not q.empty():
curr = q.get()
# print(curr)
if curr.left:
q.put(q.left)
if curr.right:
q.put(q.right)
func(curr)
# print(curr.val)
| true |
9964fcd07621271656f2ad95b8befd93f6546a54 | scott-currie/data_structures_and_algorithms | /data_structures/stack/stack.py | 1,756 | 4.15625 | 4 | from .node import Node
class Stack(object):
"""Class to implement stack functionality. It serves as a wrapper for
Node objects and implements push, pop, and peek functionality. It also
overrides __len__ to return a _size attribute that should be
updated by any method that adds or removes nodes from the stack.
"""
def __init__(self, _iterable=None):
"""Initialize a stack.
param: _iterable: Optional list that can be used to seed the stack.
"""
self.top = None
self._size = 0
if not _iterable:
_iterable = []
if type(_iterable) is not list:
raise TypeError('Iterable must be list type.')
for value in _iterable:
self.push(value)
def __len__(self):
"""Override __len__ builtin to return _size. Methods extending the class
that push or pop nodes need to update _size accordingly.
return: _size: an int representing the number of nodes in the stack
"""
return self._size
def push(self, val):
"""Create a new node with data value and push onto stack."""
node = Node(val)
node._next = self.top
self.top = node
self._size += 1
def pop(self):
"""Remove the top node from the stack and return it.
return: Node object that was previously top of the stack
"""
if self.top:
node = self.top
self.top = node._next
self._size -= 1
return node
return None
def peek(self):
"""Return the top node.
return: Node object that is currently top of the stack
"""
if self.top:
return self.top
return None
| true |
134ad277c30c6f24878f0e7d38c238f147196a64 | scott-currie/data_structures_and_algorithms | /challenges/array_binary_search/array_binary_search.py | 788 | 4.3125 | 4 | def binary_search(search_list, search_key):
"""Find the index of a value of a key in a sorted list using
a binary search algorithm. Returns the index of the value if
found. Otherwise, returns -1.
"""
left_idx, right_idx = 0, len(search_list) - 1
# while True:
while left_idx <= right_idx:
mid_idx = (right_idx + left_idx) // 2
# search_key is left of middle value
if search_key < search_list[mid_idx]:
right_idx = mid_idx - 1
# search key is right of middle value
elif search_key > search_list[mid_idx]:
left_idx = mid_idx + 1
else:
return mid_idx
# If we get here, the value was not found.
return -1
if __name__ == '__main__':
binary_search([1, 2, 3], 4) == -1
| true |
16f21ae65b3d5e3aba3f44decb5a1a4c556c95a5 | scott-currie/data_structures_and_algorithms | /challenges/multi-bracket-validation/multi_bracket_validation.py | 900 | 4.25 | 4 | from stack import Stack
def multi_bracket_validation(input_str):
"""Parse a string to determine if the grouping sequences within it are
balanced.
param: input_str (str) string to parse
return: (boolean) True if input_str is balanced, else False
"""
if type(input_str) is not str:
raise TypeError('Input must be of type str')
openers = ('[', '{', '(')
opposites = {']': '[', '}': '{', ')': '('}
stack = Stack()
for c in input_str:
# Push symbol if it's an opener
if c in openers:
stack.push(c)
if c in opposites.keys():
# If it's an opener, but its opposite isn't on the stack, return False
if stack.pop().val != opposites[c]:
return False
# If we get here, and the top is None, all symbols found opposites
if stack.top is None:
return True
return False
| true |
d46fc6f5940512ae2764ba93f4ad59d920ea16c4 | rentheroot/Learning-Pygame | /Following-Car-Game-Tutorial/Adding-Boundries.py | 2,062 | 4.25 | 4 | #learning to use pygame
#following this tutorial: https://pythonprogramming.net/displaying-images-pygame/?completed=/pygame-python-3-part-1-intro/
#imports
import pygame
#start pygame
pygame.init()
#store width and height vars
display_width = 800
display_height = 600
#init display
gameDisplay = pygame.display.set_mode((display_width,display_height))
#name window
pygame.display.set_caption('A bit Racey')
#define rgb colors
black = (0,0,0)
white = (255,255,255)
red = (255,0,0)
#tell program where right side of car is
car_width = 73
#set the game's clock
clock = pygame.time.Clock()
#load the car image
carImg = pygame.image.load('racecar.png')
#function to place car on display
#blit draws car to screen
def car(x,y):
gameDisplay.blit(carImg, (x,y))
#make main game loop
def game_loop():
#define x and y for car
x = (display_width * 0.45)
y = (display_height * 0.8)
#define x_change
x_change = 0
#game not exited
gameExit = False
#run until game exits
while not gameExit:
#log game events
for event in pygame.event.get():
#if user exits window
if event.type == pygame.QUIT:
crashed = True
#print out user actions
print(event)
#move the car
#check for keydown event
if event.type == pygame.KEYDOWN:
#check if left arrow key
if event.key == pygame.K_LEFT:
#change x variable by -5
x_change = -5
#check if right arrow key
elif event.key == pygame.K_RIGHT:
#change x variable by 5
x_change = 5
#check if key is released
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
#make x variable 0
x_change = 0
#move car along x axis
x += x_change
#make everything currently in the game white
gameDisplay.fill(white)
#put car in postition
car(x,y)
#check if car has hit edge of window
if x > display_width - car_width or x <0:
gameExit = True
#update display
pygame.display.update()
#run at 60 fps
clock.tick(60)
#run main game loop
game_loop()
#quit game
pygame.quit()
quit()
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.