blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string | is_english
bool |
|---|---|---|---|---|---|---|---|
2044a3f44b9af55830532e836ddd2505dd5346b3
|
gmastorg/CTI110
|
/M6T2_FeetToInchesConverter_Canjura.py
| 500
| 4.25
| 4
|
#Gabriela Canjura
#CTI110
#10/30/2017
#M6T2: feet to inches converter
def main():
#calls a funtions that converts feet to inches and prints answer
feet = float(0)
inches = float(0)
feet = float(input("Enter a distance in feet: "))
print('\t')
inches = feet_to_inches(feet)
print("That is",inches,"inches.")
def feet_to_inches(feet):
#calculates inches
inches = feet * 12
return inches
main()
| false
|
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
|
8b4fcea87d0a7ac318a2f9c0b0ae019175d7e291
|
juan6630/MTIC-Practice
|
/Python/clase11.py
| 1,273
| 4.15625
| 4
|
def dos_numeros():
num1 = float(input('Ingrese el primer número'))
num2 = float(input('Ingrese el segundo número'))
if num1 == num2:
print(num1 * num2)
elif num1 > num2:
print(num1 - num2)
else:
print(num1 + num2)
def tres_numeros():
num1 = float(input('Ingrese el primer número'))
num2 = float(input('Ingrese el segundo número'))
num3 = float(input('Ingrese el tercer número'))
if num1 > num2 and num1 > num3:
print(num1)
elif num2 > num3:
print(num2)
else:
print(num3)
def utilidad():
antiguedad = float(input('Ingrese su antigüedad en años'))
if antiguedad < 1:
print('Utilidad del 5%')
elif 1 <= antiguedad < 2:
print('Utilidad 7%')
elif 2 <= antiguedad < 5:
print('Utilidad 10%')
elif 5 <= antiguedad < 10:
print('Utilidad 15%')
else:
print('Utilidad 20%')
def horas_extra():
horas = float(input('Ingrese el número de horas trabajadas'))
if horas > 40:
extras = horas - 40
if extras <= 8:
print('Se pagan ' + str(extras * 2) + ' horas extra')
elif extras > 8:
print('Se pagan' + str(8 * 2 + (extras - 8) * 3) + 'horas extra')
horas_extra()
| false
|
24442d594ecf27a0df3058aff922011d6953e8dc
|
YoungWoongJoo/Learning-Python
|
/bool/bool2.py
| 733
| 4.46875
| 4
|
"""
or연산의 결과는 앞의 값이 True이면 앞의 값을, 앞의 값이 False이면 뒤의 값을 따릅니다. 다음 코드를 실행해서 각각 a와 b에 어떤 값이 들어가는지 확인해 보세요.
a = 1 or 10 # 1의 bool 값은 True입니다.
b = 0 or 10 # 0의 bool 값은 False입니다.
print("a:{}, b:{}".format(a, b))
"""
a = 1 or 10 # 1의 bool 값은 True입니다.
b = 0 or 10 # 0의 bool 값은 False입니다.
print("a:{}, b:{}".format(a, b)) #a=1, b=10
#or 앞이 true이면 앞, false이면 뒤
a = 1 or 10 # 1의 bool 값은 True입니다.
b = 0 or 10 # 0의 bool 값은 False입니다.
print("a:{}, b:{}".format(a, b)) #a=1, b=10
#or 앞이 true이면 앞, false이면 뒤
| false
|
f7b72f1287d5a2b3c61390235c41b2fd81681a5b
|
YoungWoongJoo/Learning-Python
|
/function/function2.py
| 705
| 4.3125
| 4
|
"""
함수 add는 매개변수로 a와 b를 받고 있습니다. 코드의 3번째 줄을 수정해서 result에 a와 b를 더한 값을 저장하고 출력되도록 만들어 보세요.
def add(a,b):
#함수 add에서 a와 b를 입력받아서 두 값을 더한 값을 result에 저장하고 출력하도록 만들어 보세요.
result =
print( "{} + {} = {}".format(a,b,result) )#print문은 수정하지 마세요.
add(10,5)
"""
def add(a,b):
#함수 add에서 a와 b를 입력받아서 두 값을 더한 값을 result에 저장하고 출력하도록 만들어 보세요.
result = a+b
print( "{} + {} = {}".format(a,b,result) )#print문은 수정하지 마세요.
add(10,5)
| false
|
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
|
e19fc7953dc495fef5987d49d2a6febb41042ef5
|
igorsobreira/playground
|
/problems/notifications.py
| 1,151
| 4.1875
| 4
|
'''
Eu tenho um objeto da classe A que muda muito de estado e objetos das classes
B e C que devem ser notificados quando o objeto da classe A muda de estado.
Como devo projetar essas classes?
'''
class Publisher(object):
def __init__(self):
self.status = "FOO"
self._subscribers = []
def register(self, subscriber):
if subscriber not in self._subscribers:
self._subscribers.append(subscriber)
def notify_all(self):
for subscriber in self._subscribers:
subscriber.notify(self)
def something_happenned(self):
print ("I'm on Publisher, modifying my state")
self.notify_all()
class Subscriber(object):
def notify(self, publisher):
print ("Hi, I'm {0} being notified".format(str(self)))
class SubscriberB(Subscriber):
def __str__(self):
return "A"
class SubscriberC(object):
def __str__(self):
return "B"
def main():
publisher = Publisher()
publisher.register(SubscriberB())
publisher.register(SubscriberC())
publisher.something_happenned()
if __name__ == '__main__':
main()
| false
|
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
|
bc21452d6fe5e22f5580c172737d2cecea07dee5
|
DimaLevchenko/intro_python
|
/homework_5/task_7.py
| 739
| 4.15625
| 4
|
# Написать функцию `is_date`, принимающую 3 аргумента — день, месяц и год.
# Вернуть `True`, если дата корректная (надо учитывать число месяца. Например 30.02 - дата не корректная,
# так же 31.06 или 32.07 и т.д.), и `False` иначе.
# (можно использовать модуль calendar или datetime)
from datetime import datetime
d = int(input('Enter day: '))
m = int(input('Enter month: '))
y = int(input('Enter year: '))
def is_date(a, b, c):
try:
datetime(day=a, month=b, year=c)
return True
except ValueError:
return False
print(is_date(d, m, y))
| false
|
3d773a08b8a163465cc06cfccb597a47e809a17d
|
vnikhila/PythonClass
|
/listexamples.py
| 1,797
| 4.1875
| 4
|
# --------Basic Addition of two matrices-------
a = [[1,2],[3,4]]
b = [[5,6],[7,8]]
c= [[0,0],[0,0]]
for i in range(len(a)):
for j in range(len(a[0])):
c[i][j] = a[i][j]+b[i][j]
print(c)
# -------Taking values of nested lists from user--------
n = int(input('Enter no of row and column: '))
a = [[0 for i in range(n)] for j in range(n)] #to create a nested list of desired size
b = [[0 for i in range(n)] for j in range(n)]
c = [[0 for i in range(n)] for j in range(n)]
print('Enter the elements: ')
for i in range(n):
for j in range(n):
a[i][j] = int(input('Enter val for list a: '))
b[i][j] = int(input('Enter val for list b: '))
for i in range(n):
for j in range(n):
c[i][j] = a[i][j] + b[i][j]
print('List a: ',a)
print('List b: ',b)
print('a + b:',c)
# -------Values from user method2 (Using While loop)--------
n = int(input('Enter no of rows and col: '))
a,b,rowa,rowb = [],[],[],[]
c = [[0 for i in range(n)] for j in range(n)]
j = 0
print('Enter values for a')
while(j < n):
for i in range(n):
rowa.append(int(input('Enter value for a: ')))
rowb.append(int(input('Enter value for b: ')))
a.append(rowa)
b.append(rowb)
rowa,rowb = [],[]
j += 1
for i in range(n):
for j in range(n):
c[i][j] = a[i][j] + b[i][j]
print('a: ',a)
print('b: ',b)
print('a + b: ',c)
# -------Matrix Multiplication----------
n = int(input('Enter no of rows and col: '))
a,b,rowa,rowb = [],[],[],[]
c = [[0 for i in range(n)] for j in range(n)]
j = 0
print('Enter values for a')
while(j < n):
for i in range(n):
rowa.append(int(input('Enter value for a: ')))
rowb.append(int(input('Enter value for b: ')))
a.append(rowa)
b.append(rowb)
rowa,rowb = [],[]
j += 1
for i in range(n):
for j in range(n):
c[i][j] = a[i][j] * b[j][i]
print('a: ',a)
print('b: ',b)
print('a * b: ',c)
| false
|
9a0ceda7765af0638ec2a3c31f2665b7b7d7075a
|
vnikhila/PythonClass
|
/conditional.py
| 207
| 4.34375
| 4
|
#if else ODD EVEN EXAMPLE
a = int(input('Enter a number\n'))
if a%2==0:
print('Even')
else:
print('Odd')
# if elif else example
if a>0:
print('Positive')
elif a<0:
print('Negative')
else:
print('Zero')
| false
|
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
|
bdc16e91fac7d1045b84f248b0fbb929e44bff0e
|
RoncoGit/Uniquindio
|
/CondicionalesMultiples.py
| 571
| 4.1875
| 4
|
print("===================================")
print("¡¡Convertidor de números a letras!!")
print("===================================")
num = int(input("Cuál es el número que deseas convertit?:"))
if num == 4 :
print("El número es 'Cuatro'")
elif num == 1 :
print("El número es 'Cinco'")
elif num == 2 :
print("El número es 'Cinco'")
elif num == 3 :
print("El número es 'Cinco'")
elif num == 5 :
print("El número es 'Cinco'")
else:
print("Este programa solo puede convertir hasta el número 5")
print("Fin.")
| false
|
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
|
c0355b2269c01bed993270e4472d1771ffab9527
|
sharikgrg/week3.Python-Theory
|
/104_data_type_casting.py
| 316
| 4.25
| 4
|
# casting
# casting is when you change an object data type to a specific data type
#string to integer
my_var = '10'
print(type(my_var))
my_casted_var = int(my_var)
print(type(my_casted_var))
# Integer/Floats to string
my_int_vaar = 14
my_casted_str = str(my_int_vaar)
print('my_casted_str:', type(my_casted_str))
| false
|
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
|
41c20076d3e9ba1433191c4f267605ccb6b351bf
|
zha0/punch_card_daily
|
/第二期-python30天/day2 变量/基础.py
| 554
| 4.15625
| 4
|
#coding: utf-8
#pring
print("hello,world")
print("hello,world","my name is liangcheng")
#len
#输出5
print(len("hello"))
#输出0
a = ""
print(len(a))
#输出3,tuple
b = ("a","b","c")
print(len(b))
# list 输出5
c = [1,2,3,4,5]
print(len(c))
# range 输出9
d = range(1,10)
print(len(d))
# dict 字典 输出1
e = {"name":"liangcheng"}
print(len(e))
# set 输出5
f = {1,2,3,4,"laohu"}
print(len(f))
# str
## 输出<type 'str'>
print(type(str(10)))
# int
## 输出:<type 'int'>
print(type(int('123')))
#float
##
print(type(float(10)))
| false
|
9446b95ea3cb2f71014a9197aa934f03dbb12c5a
|
JiaoPengJob/PythonPro
|
/src/_instance_.py
| 2,780
| 4.15625
| 4
|
#!/usr/bin/python3
# 实例代码
# Hello World 实例
print("Hello World!")
# 数字求和
def _filter_numbers():
str1 = input("输入第一个数字:\n")
str2 = input("输入第二个数字:\n")
try:
num1 = float(str1)
try:
num2 = float(str2)
sum = num1 + num2
print("相加的结果为:%f" % sum)
except ValueError:
print("请输入数字!")
_filter_numbers()
except ValueError:
print("请输入数字!")
_filter_numbers()
# 判断奇偶数
# 0:偶数
# 1:奇数
def _odd_even(num):
if num.isdigit():
if (float(num) % 2) == 0:
return 0
else:
return 1
else:
print("这不是一个数字!")
num = input("奇偶--请输入一个数字:\n")
print(_odd_even(num))
# 判断闰年
# 如果一年是闰年,它要么能被4整除但不能被100整除;要么就能被400整除
# True:是闰年
# False:是平年
def _leap_year(year):
if (year % 4) == 0 and (year % 100) != 0 or (year % 400) == 0:
return True
else:
return False
year = input("闰年--请输入一个年份:\n")
print(_leap_year(int(year)))
# 判断质数
# 一个大于1的自然数,除了1和它本身外,不能被其他自然数(质数)整除(2, 3, 5, 7等),换句话说就是该数除了1和它本身以外不再有其他的因数。
import math
# 0:既不是质数,也不是合数
# 1:是质数
# 2:是合数
def _prime(num):
if num > 1:
square_num = math.floor(num ** 0.5)
for i in range(2, (square_num + 1)):
if (num % i) == 0:
return 2
break
else:
return 1
else:
return 0
num = int(input("质数--输入一个数字:\n"))
print(_prime(num))
# 阶乘
# 整数的阶乘(英语:factorial)是所有小于及等于该数的正整数的积,0的阶乘为1。即:n!=1×2×3×...×n。
def _factorial(num):
if num < 0:
# 负数是没有阶乘的
return num
else:
return math.factorial(num)
num = int(input("阶乘--输入一个数字:\n"))
print(_factorial(num))
# 阿姆斯特朗数
# 如果一个n位正整数等于其各位数字的n次方之和,则称该数为阿姆斯特朗数。
# 当n=3时,又称水仙花数,特指一种三位数,其各个数之立方和等于该数。
def _armstrong(num):
sum = 0
n = len(str(num))
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** n
temp //= 10
if num == sum:
return True
else:
return False
print(_armstrong(int(input("阿姆斯特朗--输入一个数字:\n"))))
| false
|
fd1257e7e33b27e828b1b67d1aac686b4fd1ef9b
|
Coohx/python_work
|
/python_base/python_class/car_old.py
| 2,288
| 4.34375
| 4
|
# -*- coding: utf-8 -*-
# 使用类模拟现实情景
# Car类
class Car():
"""模拟汽车的一个类"""
def __init__(self, test_make, test_model, test_year):
"""初始化汽车属性"""
self.make = test_make
self.model = test_model
self.year = test_year
# 创建属性odometer_reading,并设置初始值为0
# 指定了初始值的属性,不需要为它提供初始值的形参
self.odometer_reading = 0
def get_descriptive(self):
"""返回整洁的描述信息"""
long_name = str(self.year) + ' ' + self.make + ' ' + self.model
return long_name.title()
def read_odometer(self):
"""打印一条指出汽车里程的消息"""
print("This car has " + str(self.odometer_reading) + " miles on it.")
# 用于在内部更新属性值的方法
def update_odometer(self, mileage):
"""
将里程表的读数设置为指定的值
禁止将里程表的读书调小
"""
# 只有新指定的里程数大于当前里程数时,才允许修改这个属性值
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("You can't roll back an odometer!")
# 用于递增属性值的方法
def increment_odometer(self, miles):
"""将里程表读书增加制定的量"""
if miles > 0:
self.odometer_reading += miles
else:
print("You can't roll back an odometer!")
# 创建一个实例
my_new_car = Car('audi', 'A4', 2016)
# 调用类中的方法
print(my_new_car.get_descriptive())
my_new_car.read_odometer()
# 直接修改实例的属性值
my_new_car.odometer_reading = 23
my_new_car.read_odometer()
# 调用类内部编写的方法修改属性值
my_new_car.update_odometer(32)
my_new_car.read_odometer()
# 23小于当前属性值32,禁止修改
my_new_car.update_odometer(23)
# 创建实例——二手车
my_used_car = Car('subaru', 'outback', 2013)
print("\n" + my_used_car.get_descriptive())
# 二手车已经跑的里程数
my_used_car.update_odometer(23500)
my_used_car.read_odometer()
# 我又行驶了100英里
my_used_car.increment_odometer(100)
my_used_car.read_odometer()
| false
|
79bd1b686f72927ad2c94a8c27449e78e4a0fde9
|
Coohx/python_work
|
/python_base/python_class/dog.py
| 2,117
| 4.125
| 4
|
# -*- coding: utf-8 -*-
# Date: 2016-12-16
r"""
python class 面向对象编程
类:模拟现实世界中的事物和情景,定义一大类对象都有的通用行为
对象:基于类创建,自动具备类中的通用行为
实例:根据类创建对象被称为实例化
程序中使用类的实例
"""
# 创建Dog类
# 类名首字母大写
class Dog():
# Python2.7中的类创建:class Dog(object):
"""一次模拟小狗的简单尝试"""
# 创建实例时方法__init__()会自动运行
# self 形参必须位于最前面,创建实例时,自动传入实参self
# 每个与类相关联的方法都会自动传递实参self
def __init__(self, name, age):
"""初始化属性names和age"""
# 两个属性names和age都有前缀self
self.name = name
self.age = age
def sit(self):
"""模拟小狗被命令蹲下"""
print(self.name.title() + " is now sitting.")
def roll_over(self):
"""模拟小狗被命令打滚"""
print(self.name.title() + " rolled over!")
# 创建一条特定小狗的实例
# 调用Dog类中的方法__init__()自动运行,创建一个表示特定小狗的实例
# 使用‘Willie’和6来设置属性name和age
# 方法__init__()自动返回一个实例存储在变量my_dog中,包含类中的所有'行为'
my_dog = Dog('Willie', 6)
# 访问实例的属性——句点表示法
# 但在Dog类内部引用这个属性时,使用self.name
# 实例名.属性名
print("My dog's name is " + my_dog.name.title() + ".")
print("My dog is " + str(my_dog.age) + " years old.")
# 调用方法——创建实例后,使用句点表示法访问Dog类中定义的方法
# 语法: 实例名.方法
# Python在Dog类中查找方法sit()并运行其代码
my_dog.sit()
my_dog.roll_over()
# 创建多个实例
# 每个实例(小狗)都有自己的一组属性(姓名、年龄)
your_dog = Dog('lucy', 7)
print("\nYour dog's name is " + your_dog.name.title() + ".")
print("Your dog is " + str(your_dog.age) + " years old.")
your_dog.sit()
your_dog.roll_over()
| false
|
428b6201575083154aed82d01c1d7e5825d26745
|
Coohx/python_work
|
/python_base/python_if&for&while/do_if.py
| 2,123
| 4.3125
| 4
|
# -*- coding: utf-8 -*-
# if 语句进行条件判断
# Python用冒号(:)组织缩进,后面是一个代码块,一次性执行完
# if/else 简单判断
age = 17
if age >= 18:
print('you are a adult.')
print('Welcome!')
else:
print('You should not stay here, Go home!')
# if/elif/else 多值条件判断
age = 3
if age >= 18:
print('adult!')
elif age > 6:
print('teenager!')
else:
print('kid! Go home!')
# if 从上往下判断,若某个判断是True,就忽略后面的判断。
age = 20
if age >= 6:
print('teenager!')
elif age > 18:
print('adult!')
else:
print('kid! Go home!')
# if 支持简写
tmp = 12
if tmp:
print('The bool is True.')
# input() 返回字符串, if进行数值判断时要转为整数
age = int(input('Please enter your age: '))
if age > 18:
print('Welcome!')
else:
print('Go home!')
# 小明身高1.75,体重80.5kg。请根据BMI公式(体重除以身高的平方)帮小明计算他的BMI指数
# 低于18.5:过轻
# 18.5-25:正常
# 25-28:过重
# 28-32:肥胖
# 高于32:严重肥胖
# 计算小明的BMI指数,用if-elif判断并打印
height = 1.75
weight =80.5
bmi = weight / (height ** 2)
if bmi < 18.5:
status = '过轻'
elif bmi < 25:
status = '正常'
elif bmi < 28:
status = '过重'
elif bmi <= 32:
status = '肥胖'
else:
status = '严重肥胖'
print('Xiao Ming BMI is: %.2f,%s!' % (bmi, status))
# 关键字in
requested_toppings = ['mushroom', 'onions', 'pineapple']
print('mushroom' in requested_toppings)
# if-elif 省略 else代码块
age = 12
price = 0
if age < 4:
price = 0
elif age < 18:
price = 5
elif age < 65:
price = 10
elif age >= 65:
price = 5
print('Your admission cost is $' + str(price) + '.')
# 多个并列的if,检查所有条件
requested_toppings = ['mushrooms', 'extra cheese']
if 'mushrooms' in requested_toppings:
print('Adding mushrooms.')
if 'pepperoni' in requested_toppings:
print('Adding pepperoni.')
if 'extra cheese' in requested_toppings:
print ('Adding extra pepperoni.')
print('\nFinished making your pizza!')
| false
|
eca11f026deccf03ba63fbd946be4219101d4395
|
dashuncel/gb_algorithm
|
/byankina1_7.py
| 1,042
| 4.1875
| 4
|
#7. По длинам трех отрезков, введенных пользователем, определить возможность существования треугольника,
# составленного из этих отрезков. Если такой треугольник существует, то определить, является ли он разносторонним,
# равнобедренным или равносторонним.
len1 = float(input("Длина 1: "))
len2 = float(input("Длина 2: "))
len3 = float(input("Длина 3: "))
if len1 + len2 > len3 and len2 + len3 > len1 and len1 + len3 > len2:
print("Это треугольник")
else:
print("Это не треугольник")
exit(0)
if len1 == len2 == len3:
print("Треугольник равноcторонний")
elif len1 == len2 or len1 == len3 or len2 == len3:
print("Треугольник равнобедренный")
else:
print("Треугольник разносторонний")
| false
|
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
|
dc4b0a658270447c6907b32b892c3965402a1fcb
|
DhavalLalitChheda/class_work
|
/Programs/ConvertCelsiusToFahreneit.py
| 211
| 4.1875
| 4
|
def convertToFahreneit(temp_Celsius):
return temp_Celsius * 9 / 5 + 32
temp_Celsius = float(input("Please enter temp in celsius: "))
print("The temperature in Fahreneit is: ", convertToFahreneit(temp_Celsius))
| false
|
b0bea18fc3d48dd1bda2e83ff52e589c7f54d1bf
|
kshitijgupta/all-code
|
/python/A_Byte_Of_Python/objvar.py
| 1,130
| 4.375
| 4
|
#!/usr/bin/python
#coding=UTF-8
class Person:
'''Represents a person.'''
population = 0
def __init__(self, name):
'''Initializes the person's data.'''
self.name = name
print '(Initializing %s)' % self.name
Person.population += 1
def __del__(self):
'''I am dying'''
print '%s syas bye.' % self.name
Person.population -= 1
if Person.population == 0:
print 'I am the last one.'
else:
print 'There are still %d people left.' % \
Person.population
def sayHi(self):
'''Greeting by the person.
Really, that's all it does'''
print 'Hi, my name is %s.' % self.name
def howMany(self):
'''Prints the current population'''
if Person.population == 1:
print "I am the only person here"
else:
print 'We have %d persons here.' % Person.population
_luolei = Person('luolei')
_luolei.sayHi()
_luolei.howMany()
print 'hi luolei.population', _luolei.population
xiaoming = Person('Xiao Ming')
xiaoming.sayHi()
xiaoming.howMany()
xiaoming.population = 199
print 'hi xiaoming.population', xiaoming.population
print 'hi luolei.population', _luolei.population
_luolei.sayHi()
_luolei.howMany()
| false
|
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
|
483ea8da418c872b647da5d004054f590052f568
|
srohit619/Assignments_LetsUpgrade
|
/Day_2/Assignment_1.py
| 1,667
| 4.53125
| 5
|
# Assignment of Python for LetsUpgrade Python Course
##### Question 1
# Experiment with Five list's Built in Function
students = ["Rohit Shetty","Ram Mishra", "Pari Yadav","Shubam Mishra", "Kanta Bhai", "Urvi Kanade"]
print(students)
students.append("Raakhi Singh") #1 Adds a value to the end of the List
print(students)
students.pop()
students.pop()
students.pop() #2 Removes a value from the last from a list
print(students)
students.remove("Pari Yadav") #3 Removes a specific given value from a list
print(students)
students.sort() #4 Sorts the list in Alphabatic order
print(students)
students.clear() #5 Clears the list items without deleting the List
print(students)
##### Question 2
# Experiment with Five Dictionary's Built in Function
st_aloysius_school = {
"Student_1": "Raju Shashtri",
"Age": 14,
"Std": "7th",
"Result": "Pass",
"Attendance": "91%",
"Loc": "Mumbai"
} # this is a Dict which has a Key value Pair
print(st_aloysius_school)
a = st_aloysius_school.get("Result") #1 To get a specific Value we use get() Function
print(a)
b = st_aloysius_school.keys() #2 key() helps us to get all the keys from a dictionary
print(b)
c = st_aloysius_school.pop("Loc") #3 Like List, Dict also have a pop function but in Dict's Pop we have to give a value to get it removed
print(c)
d = st_aloysius_school.values() #4 values() helps us to get all the Values from a dictionary
print(d)
del st_aloysius_school["Age"] #5 del helps us delete a key:value from a dictionary it can also delete whole dict too
| false
|
97858f535d9217878a0b36a2ad612d443027a750
|
NitinSingh1071/DS
|
/Practical3d.py
| 793
| 4.21875
| 4
|
def factorial(num):
fact = 1
while (num>0):
fact = fact * num
num = num - 1
return fact
def factorial_recursion(num):
if num == 1:
return num
else :
return num*factorial_recursion(num-1)
def factors_num(num):
for i in range(1,num+1):
if (num%i)==0:
print(i, end =" ")
def factors_recursion(num,x):
if x <= num:
if (num % x == 0):
print(x, end =" ")
factors_recursion(num, x + 1)
num = 11
print(f"Factorial of {num} is {factorial(num)}")
print(f"Factorial of {num} using recursion is {factorial_recursion(num)}")
print(f"Factors of {num} : ")
factors_num(num)
print(f"\nFactors of {num} using recursion :")
print(factors_recursion(num,1))
| false
|
ad352e5ef77e961e39356333fc2e6808b27481ad
|
Alegarse/Python-Exercises
|
/Ejercicio4_1.py
| 917
| 4.3125
| 4
|
#! /usr/bin/python3
# Ejercicio 4_1. Pig Latin es un lenguaje creado en el que se toma la primera letra de una palabra
# y se pone al final de la misma y se le agrega también el sonido vocálico “ei”. Por ejemplo, la
# palabra perro sería "erropei". ¿Cuáles pasos debemos seguir?
# Pedir al usuario que ingrese una palabra en español.
# Verificar que el usuario introdujo una palabra válida.
# Convertir la palabra de español a Pig Latin.
# Mostrar el resultado de la traducción.
palabra = input("Introduzca una palabra en español: ")
while (palabra == ""):
print("No has introducido ninguna palabra")
palabra = input("Por favor, introduzca una palabra en español: ")
primeraletra = palabra[0]
longitud = len(palabra)
sinprimera = palabra[1:longitud]
palabra_pig = sinprimera + primeraletra + "ei"
print("La palabra introducida '%s' en idioma pig sería: %s" % (palabra,palabra_pig))
| false
|
8c384ed7883af590b02e00adcec98390d4462458
|
Alegarse/Python-Exercises
|
/Ejercicio7_1.py
| 542
| 4.15625
| 4
|
#! /usr/bin/python3
# Ejercicio 7_1. Escribir un programa que guarde en una variable el diccionario
# {'Euro':'€', 'Dollar':'$', 'Yen':'¥'}, pregunte al usuario por una divisa y
# muestre su símbolo o un mensaje de aviso si la divisa no está en el diccionario.
divisas = {'Euro':'€', 'Dollar':'$', 'Yen':'¥'}
divP = input("Escriba una divisa para saber su símbolo: ")
if (divP in divisas):
print("El símbolo de la divisa %s es: %s" % (divP,divisas[divP]))
else:
print("La divisa %s no existe en el diccionario." % divP)
| false
|
bc60019b0405e20006ce7e73a4e44910818d3bab
|
Alegarse/Python-Exercises
|
/EjemploRecusividad-Factorial.py
| 401
| 4.21875
| 4
|
#! /usr/bin/python3
# Ejercicio Recursividad. Resulver el factorial de un número.
print("Resolucion del factorial de un número.")
print("======================================")
n = int(input("Introduzca el número al que calcular el factorial: "))
resultado = 0
def factN(n):
if (n == 0 or n == 1):
return 1
else:
return n * factN(n - 1)
resultado = factN(n)
print(resultado)
| false
|
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
|
2929641de43ee29ccaa86d1f5864203c6ec8e5c9
|
baharaysel/python-study-from-giraffeAcademy
|
/for_Loops.py
| 693
| 4.1875
| 4
|
for letter in "Giraffe Academy":
print(letter)
friends = ["Figen", "Birgul", "Esra"]
for friend in friends:
print(friend)
# Figen
# Birgul
# Esra
friends = ["Figen", "Birgul", "Esra"]
for index in range(10): # 10 is not included
print(index)
#0
#1
#2
#3
#4
#5
#6
#7
#8
#9
friends = ["Figen", "Birgul", "Esra"]
for index in range(3, 6): # 6 is not included
print(index)
#3
#4
#5
friends = ["Figen", "Birgul", "Esra"]
for index in range(len(friends)):
print(friends[index])
#Figen
#Birgul
#Esra
friends = ["Figen", "Birgul", "Esra"]
for index in range(len(friends)):
if index == 0:
print("first Iteration")
else:
print("Not first")
| false
|
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
|
6fc58e11d2549dc50f66e4b2107424a40071a32e
|
Graey/pythoncharmers
|
/arrayrotation.py
| 532
| 4.125
| 4
|
#Function to left rotate arr[] of size n by d*/
def leftRotate(arr, d, n):
for i in range(d):
leftRotatebyOne(arr, n)
#Function to left Rotate arr[] of size n by 1*/
def leftRotatebyOne(arr, n):
temp = arr[0]
for i in range(n-1):
arr[i] = arr[i+1]
arr[n-1] = temp
# utility function to print an array */
def printArray(arr,size):
for i in range(size):
print ("%d"% arr[i],end=" ")
# Driver program to test above functions */
arr = [1, 2, 3, 4, 5, 6, 7]
leftRotate(arr, 2, 7)
printArray(arr, 7)
| false
|
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
|
8b1370186269880ea804974642cc8f7df23a74e8
|
csrm/python_basics
|
/element_at_last_index.py
| 214
| 4.1875
| 4
|
fruits = ['Apple', 'Banana', 'Orange', 'Sapota']
print(f'Original List: {fruits}')
print(f'Element at index -1: {fruits[-1]}')
print(f'Element at index -2: {fruits[-2]}')
print(f'Element at index -5: {fruits[-5]}')
| false
|
f5ca18d328871f5c41309175725414389239376d
|
csrm/python_basics
|
/copy_list.py
| 664
| 4.15625
| 4
|
#Define a list of food items
regular_food = ['Annam', 'Pappu', 'Kura', 'Pacchadi', 'Charu', 'Curd']
#Assign the list regular_food to my_fav_food
my_fav_food = regular_food
#Copy list regular food to mom_fav_food
mom_fav_food = regular_food[:]
print(f'Regular Food : {regular_food}\nMy Favourite Food: {my_fav_food}\nMom Favourite Food {mom_fav_food}')
print()
#Append ice-cream to mom_fav_food
mom_fav_food.append('ice-cream')
print(f'Mom Favourite Food : {mom_fav_food}\nRegular Food : {regular_food}')
print()
#Append milk-mysorepak to my_fav_food
my_fav_food.append('Milk MysorePak')
print(f'My Favourite Food : {my_fav_food}"\nRegular Food : {regular_food}')
| false
|
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
|
3f868bcc92790acb85e72e8033d29bde05db17a1
|
tuhiniris/Python-ShortCodes-Applications
|
/patterns1/alphabet pattern_12.py
| 302
| 4.15625
| 4
|
'''
Alphabet Pattern:
Enter number of rows: 5
A A A A A
B B B B B
C C C C C
D D D D D
E E E E 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+1):
print(chr(64+row),end=' ')
print()
| false
|
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
|
edf144c53cc3cb95eb5a10cbdb08c8a7fc249868
|
tuhiniris/Python-ShortCodes-Applications
|
/patterns1/mirrored rhombus or parallelogram star.py
| 895
| 4.21875
| 4
|
'''
Pattern 6
Mirrored rhombus star
Enter number of rows: 5
*****
*****
*****
*****
*****
'''
print('Mirrored rhombus star pattern:')
rows=int(input('Enter number of rows: '))
for i in range(1,rows+1):
for j in range(1, i):
print(' ',end=' ')
for j in range(1,rows+1):
print('*',end=' ')
print('\n',end=' ')
print('-------------------------------')
'''
mirrored parallelogram star pattern
Enter number of rows: 5
Enter number of columns: 10
********************
********************
********************
********************
********************
'''
print('Mirrored parallelogram star pattern: ')
rows=int(input('Enter number of rows: '))
columns=int(input('Enter number of columns: '))
for i in range(1,rows+1):
for j in range(1,i):
print(' ',end=' ')
for j in range(1,columns+1):
print('*',end=' ')
print('\n',end=' ')
| false
|
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
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.