blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
af8f6a301de6b7bcf12dce96898944ec99928b6d | vickylee745/Learn-Python-3-the-hard-way | /ex30.py | 925 | 4.46875 | 4 |
people = 30
cars = 40
trucks = 15
if cars > people:
print("We should take the cars.")
elif cars < people:
print("We should not take the cars.")
else:
print("We can't decide.")
if trucks > cars:
print("That's too many trucks.")
elif trucks < cars:
print("Maybe we could take the trucks.")
else:
print("We still can't decide.")
if people > trucks:
print("Alright, let's just take the trucks.")
else:
print("Fine, let's stay home then.")
''' or above decision process can be written:'''
def what_to_take(people, cars, trucks):
if trucks >= people and trucks < cars:
print ("Alright take trucks")
elif trucks < people and cars >= people:
print ("not enough trucks, take cars")
else:
print ("Can't fit everyone")
people = input("number of people: ")
cars = input("number of cars: ")
trucks = input("number of trucks: ")
what_to_take(people, cars, trucks)
| true |
33dffd72dbc71e9bf6d0669e3570557c5102418d | Chyi341152/pyConPaper | /Concurrency/codeSample/Part4_Thread_Synchronuzation_Primitives/sema_signal.py | 1,236 | 4.65625 | 5 | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
# sema_signal.py
#
# An example of using a semaphore for signaling between threads
import threading
import time
done = threading.Semaphore(0) # Resource control.
item = None
def producer():
global item
print("I'm the producer and I produce data.")
print("Producer is going to sleep.")
time.sleep(5)
item = "Hello"
print("Producer is alive. Signaling the consumer.")
done.release() # Increments the count and signals waiting threads
def consumer():
print("I'm a consumer and I want for date.")
print("Consumer is waiting.")
done.acquire() # Waits for the count is 0, otherwise decrements the count and continues
print("Consumer got", item)
t1 = threading.Thread(target=producer)
t2 = threading.Thread(target=consumer)
t1.start()
t2.start()
"""
Semaphore Uses:
1. Resource control
You can limit the number of threads performing certain operations.For example, performing database queries making network connections
2. Signaling
Semaphores can be used to send "signals" between threads. For example, having one thread wake up another thread
"""
| true |
3df062d10ddff464e32ed814ddd2012dc97d326d | DataKind-DUB/PII_Scanner | /namelist.py | 1,231 | 4.25 | 4 | #!/usr/bin/python3 -i
"""This file contain functions to transform a list of names text file to a set
"""
def txt_to_set(filename):
"""(str) -> set()
Convert a text file containing a list of names into a set"""
res = set()
with open(filename,'r') as f:
for line in f:
l = line.strip().split()
for item in l:
try: int(item[0])
except ValueError: res.add(item)
return res
def cleaned_txt_to_set(filename):
"""(str) -> set()
Convert a cleaned text file containing a list of names into a set
a clean text is formatted as a name each line
Same effect as txt_to_set but quicker"""
res = set()
with open(filename,'r') as f:
for line in f:
res.add(line.strip())
return res
def clean_txt(filename):
"""(str) -> None
Rewrite a file with a list of name under the format name, pass line, name"""
tmp = []
with open(filename,'r') as f:
for line in f:
l = line.split()
for item in l:
try: int(item[0])
except ValueError: tmp.append(item)
with open(filename,'w') as f:
for item in tmp: f.write(item+"\n")
if __name__=="__main__":
print(txt_to_set("Irish Name Dict with Number.txt"))
print(cleaned_txt_to_set("Irish Name Dict with Number.txt"))
| true |
9a049b0cd58d5c48f564591f9edb5ff6b19e1ae9 | Ishita46/PRO-C97-NUMBER-GUESSING-GAME | /gg.py | 551 | 4.25 | 4 | import random
print("Number Guessing Game")
Number = random.randint(1,9)
chances = 0
print("Guess a number between 1-9")
while chances < 5:
guess = int(input("Enter your guess"))
if guess == Number:
print("Congratulations you won!")
break
elif guess < Number:
print("You loose, try to choose a higher number.",guess)
else:
print("Your guess was too high, guess a low number than that.",guess)
chances += 1
if not chances < 5:
print("You loose! The actual number is: ",Number) | true |
36a5612ef360eeb868da742bc9f29f535cb3fb84 | saparia-data/data_structure | /geeksforgeeks/maths/2_celcius_to_fahrenheit.py | 852 | 4.5 | 4 | """
Given a temperature in celsius C. You need to convert the given temperature to Fahrenheit.
Input Format:
The first line of input contains T, denoting number of testcases. Each testcase contains single integer C denoting the temperature in celsius.
Output Format:
For each testcase, in a new line, output the temperature in fahrenheit.
Your Task:
This is a function problem. You only need to complete the function CtoF that takes C as parameter and returns temperature in fahrenheit( in double).
The flooring and printing is automatically done by the driver code.
Constraints:
1 <= T <= 100
1 <= C <= 104
Example:
Input:
2
32
50
Output:
89
122
Explanation:
Testcase 1: For 32 degree C, the temperature in Fahrenheit = 89.
def cToF(C):
hints:
1) �F = �C x 9/5 + 32
"""
coding="utf8"
def cToF(C):
return (C * 9/5) + 32
print(cToF(32)) | true |
795bc9954ddcd5e52ad3477bf197c5bedd9a9650 | saparia-data/data_structure | /geeksforgeeks/linked_list/segregate_even_and_odd_nodes_in_linked_list_difficullt.py | 2,808 | 4.15625 | 4 | '''
Given a Linked List of integers, write a function to modify the linked list such that all even numbers appear before all the odd numbers in the modified linked list.
Also, keep the order of even and odd numbers same.
https://www.geeksforgeeks.org/segregate-even-and-odd-elements-in-a-linked-list/
'''
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def push(self, data):
new_node = Node(data)
new_node.next = self.head
self.head = new_node
def printList(self):
temp = self.head
while(temp):
print(temp.data)
temp = temp.next
def segregateEvenOdd(self):
# Starting node of list having
# even values.
evenStart = None
# Ending node of even values list.
evenEnd = None
# Starting node of odd values list.
oddStart = None
# Ending node of odd values list.
oddEnd = None
# Node to traverse the list.
currNode = self.head
while(currNode != None):
val = currNode.data
# If current value is even, add
# it to even values list.
if(val % 2 == 0):
if(evenStart == None):
evenStart = currNode
evenEnd = evenStart
else:
evenEnd.next = currNode
evenEnd = evenEnd.next
# If current value is odd, add
# it to odd values list.
else:
if(oddStart == None):
oddStart = currNode
oddEnd = oddStart
else:
oddEnd.next = currNode
oddEnd = oddEnd.next
# Move head pointer one step in
# forward direction
currNode = currNode.next
# If either odd list or even list is empty,
# no change is required as all elements
# are either even or odd.
if(oddStart == None or evenStart == None):
return
# Add odd list after even list.
evenEnd.next = oddStart
oddEnd.next = None
# Modify head pointer to
# starting of even list.
self.head = evenStart
llist = LinkedList()
llist.push(11)
llist.push(10)
llist.push(9)
llist.push(6)
llist.push(4)
llist.push(1)
llist.push(0)
llist.printList()
llist.segregateEvenOdd()
print("Linked list after re-arranging")
llist.printList() | true |
17d7ca663bf8697b79bd7824a49e561839818cf3 | saparia-data/data_structure | /pepcoding/dynamic_programming/4_climb_stairs_with_minimum_moves.py | 1,375 | 4.15625 | 4 | '''
1. You are given a number n, representing the number of stairs in a staircase.
2. You are on the 0th step and are required to climb to the top.
3. You are given n numbers, where ith element's value represents - till how far from the step you
could jump to in a single move. You can of-course fewer number of steps in the move.
4. You are required to print the number of minimum moves in which you can reach the top of
staircase.
Note -> If there is no path through the staircase print null.
Sample Input:
10
3
3
0
2
1
2
4
2
0
0
Sample Output:
4
https://www.youtube.com/watch?v=d42uDPBOXSw&list=PL-Jc9J83PIiG8fE6rj9F5a6uyQ5WPdqKy&index=4
https://www.youtube.com/watch?v=Zobz9BXpwYE&list=PL-Jc9J83PIiG8fE6rj9F5a6uyQ5WPdqKy&index=5
'''
import sys
def climbStairsWithMinMoves(arr):
dp = [None] * (len(arr) + 1)
dp[n] = 0
for i in range(n-1, -1, -1):
minn = sys.maxsize
j = 1
while(j <= arr[i] and i+j <= len(dp)):
if(dp[i + j] != None):
minn = min(minn, dp[i + j])
j += 1
if(minn != sys.maxsize):
dp[i] = minn + 1
return dp[0]
if __name__ == "__main__":
arr = [3,3,0,2,1,2,4,2,0,0]
n = 10
print(climbStairsWithMinMoves(arr)) | true |
fea46e295115747dfcc38e182eb865603b501e74 | saparia-data/data_structure | /pepcoding/recursion/1_tower_of_hanoi.py | 961 | 4.15625 | 4 | '''
1. There are 3 towers. Tower 1 has n disks, where n is a positive number. Tower 2 and 3 are empty.
2. The disks are increasingly placed in terms of size such that the smallest disk is on top and largest disk is at bottom.
3. You are required to
3.1. Print the instructions to move the disks.
3.2. from tower 1 to tower 2 using tower 3
3.3. following the rules
3.3.1 move 1 disk at a time.
3.3.2 never place a smaller disk under a larger disk.
3.3.3 you can only move a disk at the top.
sample input:
3
10
11
12
sample output:
1[10 -> 11]
2[10 -> 12]
1[11 -> 12]
3[10 -> 11]
1[12 -> 10]
2[12 -> 11]
1[10 -> 11]
https://www.youtube.com/watch?v=QDBrZFROuA0&list=PL-Jc9J83PIiFxaBahjslhBD1LiJAV7nKs&index=12
'''
def toh(n, t1, t2, t3):
if(n == 0):
return
toh(n-1, t1, t3, t2)
print(str(n) + "[" + str(t1) + " -> " + str(t2) + "]")
toh(n-1, t3, t2, t1)
toh(3, 10, 11, 12) | true |
60937f08311c74e6773fa09eaec056097efb9496 | saparia-data/data_structure | /pepcoding/generic_tree/17_is_generic_tree_symmetric.py | 1,776 | 4.1875 | 4 | '''
The function is expected to check if the tree is symmetric, if so return true otherwise return false.
For knowing symmetricity think of face and hand. Face is symmetric while palm is not.
Note: Symmetric trees are mirror image of itself.
Sample Input:
20
10 20 50 -1 60 -1 -1 30 70 -1 80 -1 90 -1 -1 40 100 -1 110 -1 -1 -1
Sample Output:
true
https://www.youtube.com/watch?v=ewEAjK83ZVM&list=PL-Jc9J83PIiEmjuIVDrwR9h5i9TT2CEU_&index=39
https://www.youtube.com/watch?v=gn2ApElF2i0&list=PL-Jc9J83PIiEmjuIVDrwR9h5i9TT2CEU_&index=40
'''
class Node:
def __init__(self):
self.data = None
self.children = []
def create_generic_tree(arr):
root = Node()
st = [] # create empty stack
for i in range(len(arr)):
if(arr[i] == -1):
st.pop()
else:
t = Node()
t.data = arr[i]
if(len(st) > 0):
st[-1].children.append(t)
else:
root = t
st.append(t)
return root
def areMirror(root1, root2):
if(len(root1.children) != len(root2.children)):
return False
for i in range(len(root1.children)):
j = len(root1.children) - 1 - i
c1 = root1.children[i]
c2 = root2.children[j]
if(areMirror(c1, c2) == False):
return False
return True
def isSymmetric(root):
return areMirror(root, root) # symmetric trees are mirror image of itself
if __name__ == "__main__":
arr = [10, 20, 50, -1, 60, -1, -1, 30, 70, -1, 80, -1, 90, -1, -1, 40, 100, -1, 110, -1, -1, -1]
root = create_generic_tree(arr)
print(root.data)
print(isSymmetric(root)) | true |
008b19ff7efc7fc9be540903c086a792aed6c0d2 | saparia-data/data_structure | /geeksforgeeks/maths/7_prime_or_not.py | 1,297 | 4.34375 | 4 | '''
For a given number N check if it is prime or not. A prime number is a number which is only divisible by 1 and itself.
Input:
First line contains an integer, the number of test cases 'T'. T testcases follow. Each test case should contain a positive integer N.
Output:
For each testcase, in a new line, print "Yes" if it is a prime number else print "No".
Your Task:
This is a function problem. You just need to complete the function isPrime that takes N as parameter and returns True if N is prime else returns false.
The printing is done automatically by the driver code.
Constraints:
1 <= T <= 100
1 <= N <= 103
Example:
Input:
2
5
4
Output:
Yes
No
Explanation:
Testcase 1: 5 is the prime number as it is divisible only by 1 and 5.
Hints:
Count the number of factors. If the factors of a number is 1 and itself, then the number is prime.
You can check this optimally by iterating from 2 to sqrt(n) as the factors from 2 to sqrt(n) have multiples from sqrt(n)+1 to n.
So, by iterating till sqrt(n) only, you can check if a number is prime.
def isPrime(N):
'''
import math
def isPrime(N):
if(N == 1):
return True
else:
for i in range(2, int(math.sqrt(N)) + 1):
if (N % i == 0):
return False
return True
print(isPrime(9)) | true |
3fb0fefa594130bd865c342d60d0f7ff34127f7f | saparia-data/data_structure | /geeksforgeeks/linked_list/4_Insert_in_Middle_of_Linked_List.py | 1,343 | 4.15625 | 4 | '''
Given a linked list of size N and a key. The task is to insert the key in the middle of the linked list.
Input:
The first line of input contains the number of test cases T. For each test case,
the first line contains the length of linked list N
and the next line contains N elements to be inserted into the linked list and the last line contains the element to be inserted to the middle.
Output:
For each test case, there will be a single line of output containing the element of the modified linked list.
User Task:
The task is to complete the function insertInMiddle() which takes head reference and element to be inserted as the arguments.
The printing is done automatically by the driver code.
Expected Time Complexity : O(N)
Expected Auxilliary Space : O(1)
Constraints:
1 <= T <= 100
1 <= N <= 104
Example:
Input:
2
3
1 2 4
3
4
10 20 40 50
30
Output:
1 2 3 4
10 20 30 40 50
Explanation:
Testcase 1: The new element is inserted after the current middle element in the linked list.
Testcase 2: The new element is inserted after the current middle element in the linked list and Hence, the output is 10 20 30 40 50.
'''
def insertInMid(head,new_node):
slow = head
fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
new_node.next = slow.next
slow.next = new_node | true |
296acd0cb1655e3fd6d57e80b9bd72529ffb4ecc | saparia-data/data_structure | /geeksforgeeks/matrix/8_Boundary_traversal_matrix.py | 2,384 | 4.34375 | 4 | '''
You are given a matrix A of dimensions n1 x m1.
The task is to perform boundary traversal on the matrix in clockwise manner.
Input:
The first line of input contains T denoting the number of testcases. T testcases follow.
Each testcase two lines of input. The first line contains dimensions of the matrix A, n1 and m1.
The second line contains n1*m1 elements separated by spaces.
Output:
For each testcase, in a new line, print the boundary traversal of the matrix A.
Your Task:
This is a function problem. You only need to complete the function boundaryTraversal()
that takes n1, m1 and matrix as parameters and prints the boundary traversal.
The newline is added automatically by the driver code.
Constraints:
1 <= T <= 100
1 <= n1, m1<= 30
0 <= arri <= 100
Examples:
Input:
4
4 4
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
3 4
12 11 10 9 8 7 6 5 4 3 2 1
1 4
1 2 3 4
4 1
1 2 3 4
Output:
1 2 3 4 8 12 16 15 14 13 9 5
12 11 10 9 5 1 2 3 4 8
1 2 3 4
1 2 3 4
Explanation:
Testcase1: The matrix is:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
The boundary traversal is 1 2 3 4 8 12 16 15 14 13 9 5
Testcase 2: Boundary Traversal will be 12 11 10 9 5 1 2 3 4 8.
Testcase 3: Boundary Traversal will be 1 2 3 4.
Testcase 4: Boundary Traversal will be 1 2 3 4.
hints:
Traverse the top boundary first then the right boundary then the bottom boundary
then the left boundary and print the elements simultaneously.
'''
def BoundaryTraversal(a, n, m):
"""
a: matrix
n: no. of rows
m: no. of columns
"""
if(min(n,m) == 1):
for row in a:
print(*row, end = " ")
return
row_idx, col_idx = 0, 0
#print first row
while(col_idx < m):
print(a[row_idx][col_idx], end = " ")
col_idx += 1
#print last column
col_idx = m - 1
row_idx += 1
while(row_idx < n):
print(a[row_idx][col_idx], end = " ")
row_idx += 1
#print last row
row_idx = n - 1
col_idx -= 1
while(col_idx > -1):
print(a[row_idx][col_idx], end = " ")
col_idx -= 1
#print first column
row_idx -= 1
col_idx = 0
while(row_idx > 0):
print(a[row_idx][col_idx], end = " ")
row_idx -= 1
a = [
[1,2,3],
[4,5,6],
[7,8,9]
]
n, m = 3, 3
BoundaryTraversal(a, n, m) | true |
789288e7c8987df76436b463f7e8fa6f2d9b1a8a | saparia-data/data_structure | /geeksforgeeks/tree/6_height_of_binary_tree.py | 698 | 4.125 | 4 | '''
Hint:
1. If tree is empty then return 0
2. Else
(a) Get the max depth of left subtree recursively i.e.,
call maxDepth( tree->left-subtree)
(a) Get the max depth of right subtree recursively i.e.,
call maxDepth( tree->right-subtree)
(c) Get the max of max depths of left and right
subtrees and add 1 to it for the current node.
max_depth = max(max dept of left subtree,
max depth of right subtree)
+ 1
(d) Return max_depth
'''
def height(root):
if(root is None):
return 0
return (1 + max(height(root.left), height(root.right)))
| true |
770ac8812cac09b77d0990edacc7fed78c612480 | saparia-data/data_structure | /geeksforgeeks/maths/1_absolute_value_solved.py | 1,062 | 4.375 | 4 | '''
You are given an interger I. You need to print the absolute value of the interger I.
Input Format:
The first line of input contains T, denoting number of testcases. Each testcase contains single integer I which may be positive or negative.
Output Format:
For each testcase, in a new line, output the absolute value.
Your Task:
This is function problem. You only need to complete the function absolute that takes integer I as parameter and returns the absolute value of I.
All other things are taken care of by the driver code.
Constraints:
1 <= T <= 100
-106 <= I <= 106
Example:
Input:
2
-32
45
Output:
32
45
Explanation:
Testcase 1: Since -32 is negative, we prints its positive equavalent, i.e., 32
Testcase 1: Since 45 is positive, we prints its value as it is, i.e., 45
Hints:
1. Absolute value of an integer means value >=0. So if a number is negative you can find its absolute value by multiplying it by -1.
For positive numbers no need to multiply as it's already positive.
'''
def printAbs(n):
return abs(n)
print(printAbs(-32)) | true |
35030f181df15a7fb1ad550279aadc98a6baf954 | saparia-data/data_structure | /geeksforgeeks/sorting/11_Counting_Sort.py | 1,265 | 4.25 | 4 | '''
Given a string S consisting of lowercase latin letters, arrange all its letters in lexographical order using Counting Sort.
Input:
The first line of the input contains T denoting number of testcases.Then T test cases follow. Each testcase contains positive integer N denoting the length of string.The last line of input contains the string S.
Output:
For each testcase, in a new line, output the sorted string.
Your Task:
This is a function problem. You only need to complete the function countSort() that takes char array as parameter.
The printing is done by driver code.
Constraints:
1 <= T <= 105
1 <= N <= 105
Example:
Input:
2
5
edsab
13
geeksforgeeks
Output:
abdes
eeeefggkkorss
Explanation:
Testcase 1: In lexicographical order , string will be abdes.
Testcase 2: In lexicographical order , string will be eeeefggkkorss.
hints:
1)
Store the count of elements. And use this count to sort the elements accordingly.
'''
def countingSort(s,n):
freq=[0 for i in range(256)]
print(freq)
for char in s:
freq[ord(char)] += 1
print(freq)
for i in range(256):
for j in range(freq[i]):
print(chr(i),end="")
s = "geeksforgeeks"
n = len(s)
countingSort(s, n) | true |
d476ee8753b489e9a160984ca1a71e49eed86f2d | saparia-data/data_structure | /geeksforgeeks/array/3_majority_in_array_solved.py | 2,439 | 4.40625 | 4 | '''
We hope you are familiar with using counter variables. Counting allows us to find how may times a certain element appears in an array or list.
You are given an array arr[] of size N. You are also given two elements x and y. Now, you need to tell which element (x or y) appears most in the array.
In other words, print the element, x or y, that has highest frequency in the array. If both elements have the same frequency,
then just print the smaller element.
Input Format:
The first line of input contains T denoting the number of testcases. T testcases follow. Each testcase contains 3 lines of input.
The first line contains size of array denoted by n. The second line contains the elements of the array separated by spaces.
The third line contains two integers x and y separated by a space.
Output Format:
For each testcase, in a newline, print the element with highest occurrence in the array. If occurrences are same, then print the smaller element.
Your Task:
Since, this is a function problem. You don't need to take any input, as it is already accomplished by the driver code.
You just need to complete the function majorityWins() that takes array, n, x, y as parameters and return the element with highest
Constraints:
1 <= T <= 100
1 <= n <= 103
0 <= arri , x , y <= 108
Examples:
Input:
2
11
1 1 2 2 3 3 4 4 4 4 5
4 5
8
1 2 3 4 5 6 7 8
1 7
Output:
4
1
Explanation:
Testcase 1: n=11; elements = {1,1,2,2,3,3,4,4,4,4,5}; x=4; y=5
x frequency in arr is = 4 times
y frequency in arr is = 1 times
x has higher frequency, so we print 4.
Testcase 2: n=8; elements = {1,2,3,4,5,6,7,8}; x=1; y=7
x frequency in arr is 1 times
y frequency in arr is 1 times
both have same frequency, so we look for the smaller element.
x=1 is smaller than y=7, so print 1.
'''
def majorityWins(arr, n, x, y):
c_x = 0
c_y = 0
for i in range(n):
if(arr[i] == x):
c_x = c_x + 1
elif(arr[i] == y):
c_y = c_y + 1
else:
continue
#print(c_x)
#print(c_y)
if(c_x > c_y):
return x
elif(c_x < c_y):
return y
elif(c_x == c_y):
return min(x,y)
arr = [854,190,562,906,2,625,678,667,779,755,699,842,970,81,253,155,456,830,575,640,962,44,124,209,841,571,211,213,904,993,130,996,866,938,553,114,3,79,18,823,176,75,740,83,391,223,289,561,927,351,744]
n = len(arr)
x = 10
y = 40
print(majorityWins(arr,n,x,y))
| true |
8f2e60355dfe700cfde7b30b569d431ce959b7e5 | saparia-data/data_structure | /geeksforgeeks/strings/6_check_if_string_is_rotated_by_two_places.py | 1,986 | 4.21875 | 4 | '''
Given two strings a and b. The task is to find if the string 'b' can be obtained by rotating another string 'a' by exactly 2 places.
Input:
The first line of input contains an integer T denoting the number of test cases.
Then T test cases follow. In the next two lines are two string a and b respectively.
Output:
For each test case in a new line print 1 if the string 'a' can be obtained by rotating string 'b' by two places else print 0.
User Task:
The task is to complete the function isRotated() which checks if given strings can be formed by rotations.
The function returns true if string 1 can be obtained by rotating string 2 by two places, else it returns false.
Expected Time Complexity: O(N).
Expected Space Complexity: O(N).
Challenge: Try doing it in O(1) space complexity.
Constraints:
1 <= T <= 50
1 <= length of a, b < 100
Example:
Input:
2
amazon
azonam
geeksforgeeks
geeksgeeksfor
Output:
1
0
Explanation:
Testcase 1: amazon can be rotated anti-clockwise by two places, which will make it as azonam.
Testcase 2: If we rotate geeksforgeeks by two place in any direction , we won't get geeksgeeksfor.
hints:
Step1: There can be only two cases:
a) Clockwise rotated
b) Anti-clockwise rotated
Step 2: If clockwise rotated that means elements are shifted in right. So, check if a substring[2.... len-1] of string2
when concatenated with substring[0,1] of string2 is equal to string1. Then, return true.
Step 3: Else, check if it is rotated anti-clockwise that means elements are shifted to left.
So, check if concatenation of substring[len-2, len-1] with substring[0....len-3] makes it equals to string1. Then return true.
Step 4: Else, return false.
'''
def isRotated(s,p):
n=len(p)
if(n<3):
return p==s
anticlock_str=p[2:]+p[0:2]
clockwise_str=p[-2]+p[-1]+p[:n-2]
if(s==anticlock_str or s==clockwise_str):
return True
return False
s = "amazon"
p = "onamaz"
print(isRotated(s, p)) | true |
b6bf8024d4250adafec321751f4317591391a1c9 | saparia-data/data_structure | /geeksforgeeks/tree/26_Foldable_Binary_Tree.py | 1,007 | 4.4375 | 4 | '''
Given a binary tree, find out if the tree can be folded or not.
-A tree can be folded if left and right subtrees of the tree are structure wise mirror image of each other.
-An empty tree is considered as foldable.
Consider the below tree: It is foldable
10
/ \
7 15
\ /
9 11
'''
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def foldableUtil(root1, root2):
if(root1 is None and root2 is None):
return True
if(root1 is None or root2 is None):
return False
return foldableUtil(root1.left, root2.right) and foldableUtil(root1.right, root2.left)
def foldable(root):
if(root is None):
return True
result = foldableUtil(root.left, root.right)
return result
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.right = Node(5)
root.right.left = Node(4)
print(foldable(root)) | true |
b05134767f55b443af849edfa92df6ae5937491b | saparia-data/data_structure | /geeksforgeeks/matrix/11_Reversing_the _columns_Matrix.py | 1,919 | 4.40625 | 4 | '''
You are given a matrix A of dimensions n1 x m1.
The task is to reverse the columns(first column exchanged with last column and so on).
Input:
The first line of input contains T denoting the number of testcases. T testcases follow.
Each testcase two lines of input. The first line contains dimensions of the matrix A, n1 and m1.
The second line contains n1*m1 elements
separated by spaces.
Output:
For each testcase, in a new line, print the resultant matrix.
Your Task:
This is a function problem. You only need to complete the function reverseCol()
that takes n1, m1, and matrix as parameter and modifies the matrix.
The driver code automatically appends a new line.
Constraints:
1 <= T <= 100
1 <= n1, m1 <= 30
0 <= arri <= 100
Examples:
Input:
2
4 4
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
2 3
4 3 2 1 5 6
Output:
3 2 1 7 6 5 11 10 9 15 14 13
2 3 4 6 5 1
Explanation:
Testcase 1: Original array is as follows:
1 2 3
5 6 7
9 10 11
13 14 15
Array after exchanging columns:
3 2 1
7 6 5
11 10 9
15 14 13
Testcase 2: Original matrix is as follows:
4 3 2
1 5 6
After reversing the column of matrix
2 3 4
6 5 1
hints:
Take two pointers low and high, low at 0 and high at n-1.
Start swapping elements at two pointers and increasing the low and decreasing the high one.
Do the above for all the rows.
Keep in mind, when number of rows is odd, no need to take care of middle column.
'''
#arr1 is matrix
#n1 is rows
#m1 is cols
def reverseCol(n1, m1, arr1):
for i in range(n1):
for j in range(m1//2):
t = arr1[i][j]
arr1[i][j] = arr1[i][m1 - 1 - j]
arr1[i][m1 - 1 - j] = t
for i in range(n1):
for j in range(m1):
print(arr1[i][j], end = " ")
print("\n")
arr1 = [[8, 9, 7, 6],
[4, 7, 6, 5],
[3, 2, 1, 8],
[9, 9, 7, 7]]
n1, m1 = 4, 4
reverseCol(n1, m1, arr1) | true |
e76d09cc97d9d6d8677ae32ba52425ec5fa34a0f | cginiel/si507 | /lecture/week3/2020.01.21.py | 2,638 | 4.46875 | 4 | # # import datetime
# # date_now = datetime.datetime.now()
# # print(date_now.year)
# # print(date_now.month)
# # print(date_now.day)
# # print(type(date_now))
# # class is a type of thing, object is a particular instance of that class!!!!!
# # BEGIN CLASS DEFINITION
# """
# class Dog:
# def __init__(self, nm, br):
# self.name = nm
# self.breed = br
# """
# # END CLASS DEFINITION
# # every time we call "Dog" the program is going to
# # set up the function written above (which is how
# # we "index" or call out the specific names below)
# d1 = Dog('Fido', 'German Shepherd')
# d2 = Dog('Rufus', 'Lhasa Apso')
# print (d1.name, 'is a', d1.breed)
# print (d2.name, 'is a', d2.breed)
# # "self" essentially equals d1 because self corresponds
# # to the object in question
# # in that sense, "self," in the case of d2
# # equals d2
# # "all class methods will have to have self as the first
# # parameter"
# class Dog:
# large_dogs = ['German Shepherd', 'Golden Retriever',
# 'Rottweiler', 'Collie',
# 'Mastiff', 'Great Dane']
# small_dogs = ['Lhasa Apso', 'Yorkshire Terrier',
# 'Beagle', 'Dachshund', 'Shih Tzu']
# def __init__(self, nm, br):
# self.name = nm
# self.breed = br
# def speak(self):
# if self.breed in Dog.large_dogs:
# print('woof')
# elif self.breed in Dog.small_dogs:
# print('yip')
# else:
# print('rrrrr')
# d1 = Dog('Fido', 'German Shepherd')
# d2 = Dog('Rufus', 'Lhasa Apso')
# d3 = Dog('Fred', 'Mutt')
# d1.speak()
# d2.speak()
# d3.speak()
class Dog:
large_dogs = ['German Shepherd', 'Golden Retriever',
'Rottweiler', 'Collie',
'Mastiff', 'Great Dane']
small_dogs = ['Lhasa Apso', 'Yorkshire Terrier',
'Beagle', 'Dachshund', 'Shih Tzu']
def __init__(self, nm, br, a):
self.name = nm
self.breed = br
self.age = a
def speak(self):
if self.breed in Dog.large_dogs:
print('woof')
elif self.breed in Dog.small_dogs:
print('yip')
else:
print('rrrrr')
def print_dog_years(d):
'''prints a dog's name and age in dog years
dog years = actual years * 7
Parameters
----------
dog : Dog
The dog to print
Returns
-------
none
'''
dog_years = d.age * 7
print(f"{d.name} is a {d.breed} who is {dog_years} years old in dog years")
pass #TODO: implement
kennel = [
Dog('Fido', 'German Shepherd', 4),
Dog('Rufus', 'Lhasa Apso', 7),
Dog('Fred', 'Mutt', 11)
]
for dog in kennel:
print_dog_years(dog) | true |
1d07ee37723cc22548908a0a75b02facb6664100 | alexbenko/pythonPractice | /classes/magic.py | 787 | 4.125 | 4 | #how to use built in python methods like print on custom objects
class Car():
speed = 0
def __init__(this,color,make,model):
this.color = color
this.make = make
this.model = model
def __str__(this):
return f'Your {this.make},{this.model} is {this.color} and is currently going {this.speed} mph'
def accelerate(this,toGoTo):
print(f'Accelerating car to {toGoTo},currently going {this.speed} mph...')
while this.speed < toGoTo:
this.speed += 1
print(f'{this.speed} mph...')
print(f'Accelerated to {toGoTo} !')
volt = Car(color='White',make='Chevorlet',model='Volt')
print(volt)
#=>Your Chevorlet,Volt is White and is currently going 0 mph
volt.accelerate(100)
print(volt)
#=>Your Chevorlet,Volt is White and is currently going 100 mph
| true |
b821bd68661a42ae46870bd01178d181656149e6 | xenron/sandbox-github-clone | /qiwsir/algorithm/divide.py | 2,005 | 4.125 | 4 | #! /usr/bin/env python
#coding:utf-8
def divide(numerator, denominator, detect_repetition=True, digit_limit=None):
# 如果是无限小数,必须输入限制的返回小数位数:digit_limit
# digit_limit = 5,表示小数位数5位,注意这里的小数位数是截取,不是四舍五入.
if not detect_repetition and digit_limit == None:
return None
decimal_found = False
v = numerator // denominator
numerator = 10 * (numerator - v * denominator)
answer = str(v)
if numerator == 0:
return answer
answer += '.'
# Maintain a list of all the intermediate numerators
# and the length of the output at the point where that
# numerator was encountered. If you encounter the same
# numerator again, then the decimal repeats itself from
# the last index that numerator was encountered at.
states = {}
while numerator > 0 and (digit_limit == None or digit_limit > 0):
if detect_repetition:
prev_state = states.get(numerator, None)
if prev_state != None:
start_repeat_index = prev_state
non_repeating = answer[:start_repeat_index]
repeating = answer[start_repeat_index:]
return non_repeating + '[' + repeating + ']'
states[numerator] = len(answer)
v = numerator // denominator
answer += str(v)
numerator -= v * denominator
numerator *= 10
if digit_limit != None:
digit_limit -= 1
if numerator > 0:
return answer + '...'
return answer
if __name__=="__main__":
print "5divide2",
print divide(5,2)
print "10divide3",
print divide(10,3)
print divide(10,3,5)
print "15divide7"
print divide(15,7)
print divide(15,7,True,3)
| true |
465074ef23a66b649ac36eb6a259c9ace2732cb3 | YYYYMao/LeetCode | /374. Guess Number Higher or Lower/374.py | 1,424 | 4.15625 | 4 | 374. Guess Number Higher or Lower
We are playing the Guess Game. The game is as follows:
I pick a number from 1 to n. You have to guess which number I picked.
Every time you guess wrong, I ll tell you whether the number is higher or lower.
You call a pre-defined API guess(int num) which returns 3 possible results (-1, 1, or 0):
-1 : My number is lower
1 : My number is higher
0 : Congrats! You got it!
Example:
n = 10, I pick 6.
Return 6.
# The guess API is already defined for you.
# @param num, your guess
# @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
# def guess(num):
#65ms
class Solution(object):
def guessNumber(self, n):
"""
:type n: int
:rtype: int
"""
L , R = 1 , n
M = (L+R)>>1
m = guess(M)
while m != 0 :
# print L , R ,M ,m
if m == -1:
R = M-1
elif m == 1 :
L = M+1
M = (R+L)>>1
m = guess(M)
return M
#46ms
class Solution(object):
def guessNumber(self, n):
"""
:type n: int
:rtype: int
"""
L , R = 1 , n
while 1 :
M = (R+L)>>1
m = guess(M)
if m == -1:
R = M-1
elif m == 1 :
L = M+1
elif m == 0:
return M | true |
b7cfe79cf0003bdb6d174d1471fbb672b0700b7f | codeAligned/interview_challenges | /sort_and_search/binary_search.py | 442 | 4.25 | 4 | def binary_search(iterable, target):
"""Determine if target value is in sorted iterable containing numbers"""
sorted_iterable = sorted(iterable)
low = 0
high = len(sorted_iterable) - 1
while low <= high:
midpoint = (high + low) // 2
if sorted_iterable[midpoint] == target:
return True
elif sorted_iterable[midpoint] > target:
high = midpoint - 1
elif sorted_iterable[midpoint] < target:
low = midpoint + 1
return False
| true |
c92ba78a30f78a134befad3de91f7572a201b1ef | szk0139/python_tutorial_FALL21 | /mysciW4/readdata.py | 1,018 | 4.1875 | 4 |
def read_data(columns, types = {}, filename= "data/wxobs20170821.txt"):
"""
Read data from CU Boulder Weather Stattion data file
Parameters:
colums: A dictonary of column names mapping to column indices
types: A dictonary of column names mapping to the types to which to convert each column of data
filename: A string path pointing to the CU Boulder Wather Station data file
"""
#Initialize my data variable
data = {}
for column in columns:
data[column] = []
with open(filename, "r") as datafile:
# read first three line (header)
for _ in range(3):
#print(_)
datafile.readline()
# Read and parse the rest of the file
for line in datafile:
split_line = line.split()
for column in columns:
i = columns[column]
t = types.get(column, str)
value = t(split_line[i])
data[column].append(value)
return data
| true |
9b34c6cc778d0a45f819a5667308a2e4f5f7f1f8 | Stepancherro/Algorithm | /stack.py | 1,879 | 4.1875 | 4 | # -*- encoding: utf-8 -*-
# Stack() creates a new stack that is empty.
# It needs no parameters and returns an empty stack.
# push(item) adds a new item to the top of the stack.
# It needs the item and returns nothing.
# pop() removes the top item from the stack.
# It needs no parameters and returns the item. The stack is modified.
# peek() returns the top item from the stack but does not remove it.
# It needs no parameters. The stack is not modified.
# isEmpty() tests to see whether the stack is empty.
# It needs no parameters and returns a boolean value.
class Stack():
def __init__(self, size=10):
"""
Initialize python List with size of 10 or user given input.
Python List type is a dynamic array, so we have to restrict its
dynamic nature to make it work like a static array.
"""
self.size = size
self.stack = []
self.top = 0
def push(self, value):
if self.isFull():
raise IndexError("stack is full")
else:
self.stack.append(value)
self.top += 1
def pop(self):
if self.isEmpty():
raise IndexError("stack is empty")
else:
value = self.stack[self.top - 1]
self.top -= 1
self.stack.pop()
return value
def peek(self):
if self.isEmpty():
raise IndexError("stack is empty")
return self.stack[self.top - 1]
def isFull(self):
return self.top == self.size
def isEmpty(self):
return self.top == 0
def showStack(self):
print(self.stack)
if __name__ == '__main__':
stack = Stack(7)
stack.push(15)
stack.push(6)
stack.push(2)
stack.push(9)
stack.showStack()
last_element = stack.pop()
print(last_element)
stack.showStack()
print(stack.peek())
| true |
5b7ad9bbd58b59d7e7319bad5d970b5dbba1a529 | moha0825/Personal-Projects | /Resistance.py | 1,018 | 4.375 | 4 | # This code is designed to have multiple items inputted, such as the length, radius, and
# viscosity, and then while using an equation, returns the resistance.
import math
def poiseuille(length, radius, viscosity):
Resistance = (int(8)*viscosity*length)/(math.pi*radius**(4))
return Resistance
def main():
length = float(input("Please enter the length: "))
radius = float(input("Please enter the radius: "))
viscosity = float(input("Please enter the viscosity: "))
if length <= 0:
print("Failed due to input error. Please make sure your inputs are all positive. Exiting program.")
elif radius <= 0:
print("Failed due to input error. Please make sure your inputs are all positive. Exiting program.")
elif viscosity <= 0:
print("Failed due to input error. Please make sure your inputs are all positive. Exiting program.")
else:
print("The resistance is: ", poiseuille(length, radius, viscosity))
if __name__ == "__main__":
main()
| true |
d0a53a4ca42e65bb86f1e4453bdfe747ea8227ee | AmineNeifer/holbertonschool-interview | /0x19-making_change/0-making_change.py | 578 | 4.25 | 4 | #!/usr/bin/python3
""" Contains makeChange function"""
def makeChange(coins, total):
"""
Returns: fewest number of coins needed to meet total
If total is 0 or less, return 0
If total cannot be met by any number of coins you have, return -1
"""
if not coins or coins is None:
return -1
if total <= 0:
return 0
change = 0
coins = sorted(coins)[::-1]
for coin in coins:
while coin <= total:
total -= coin
change += 1
if (total == 0):
return change
return -1
| true |
3b2c0d8d806dcc4b73a80bf0564a77f77b906b67 | laurenhesterman/novTryPy | /TryPy/trypy.py | 1,832 | 4.5625 | 5 | #STRINGS
# to capitalize each first letter in the word use .capitalize() method, with the string before .capitalize
characters = "rick"
print characters.capitalize()
#returns Rick
#returns a copy of the whole string in uppercase
print characters.upper()
#returns RICK
#.lower() returns a copy of the string converted completely to lowercase
print characters.lower()
#returns rick
#count returns the number of occurances of the substr in original string. Uses (str[start:end]) as paramaters.
#defaults start and end to 0
string ="today is my birthday"
strg= "day"
print string.count("day")
#returns 2
#.find() returns lowest index at which substring is found. (str[start:end]) start and end default to entire string
#-1 on failure
print string.find(strg)
#returns 2, as "day" begins on 2nd index of the string
#.index() is similar to .find(), but returns ValueError when not found
print string.index("day")
#returns 2
""".split() reutrns a list of words of the string. (str[, sep[, maxsplit]]) are parameters. By default
they separate with whitespace, but 'sep' can replace a string as the separateor.
maxsplit defaults to 0, but that number specifies how many splits will occur at most"""
string ="today is my birthday"
print string.split("y")
#.join() concentrates a list or words to string at intervening occurances of sep (default whitespace)
string2 ="today is my birthday"
print string2.join("now")
# returns: ntoday is my birthdayotoday is my birthdayw (wraps each character of "now around" occurances of string2)
#replaces occurances of first argument within string with second argument
print string.replace("day", "month")
#returns tomonth is my birthmonth
#.format() formats string with replacement holders
string3 = "The sum of 1 + 2 = {}"
print string3.format(1+2)
#returns The sum of 1 + 2 = 3
#NUMBERS
| true |
017ccb38921399323ccb3c169a50063b3057a118 | Alex-Reitz/Python_SB | /02_weekday_name/weekday_name.py | 566 | 4.25 | 4 | def weekday_name(day_of_week):
"""Return name of weekday.
>>> weekday_name(1)
'Sunday'
>>> weekday_name(7)
'Saturday'
For days not between 1 and 7, return None
>>> weekday_name(9)
>>> weekday_name(0)
"""
i = 0
weekdays = ["Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday", "Saturday"]
while i < len(weekdays):
if i + 1 == day_of_week:
print(weekdays[i])
i = i + 1
weekday_name(1)
weekday_name(2)
weekday_name(3)
weekday_name(4)
| true |
5c39c42c7787b07e51728b67855c4f58fa98fd0f | leios/OIST.CSC | /hello_world/python/hello_world.py | 788 | 4.15625 | 4 | #-------------hello_world.py---------------------------------------------------#
#
# In most traditional coding courses, they start with a simple program that
# outputs "Hello World!" to the terminal. Luckily, in python... this is pretty
# simple. In fact, it's only one line (the line that follows this long comment).#
# You should be able to type in:
#
# python hello_world.py
#
# and receive the following output in your terminal:
#
# Hello World!
#
# So let's get to it!
#------------------------------------------------------------------------------#
print("Hello World!")
# In python, the "print" command sends whatever is in the parentheses to your
# terminal. That's precisely what we are doing. Sending "Hello World!" to the
# terminal. Let me know if you have any trouble!
| true |
4508866832b2578a43788e47e00c3e9781bb6b44 | cesarmarroquin/blackjack | /blackjack_outline.py | 2,089 | 4.1875 | 4 | """
I need to create a blackjack Game. In blackjack, the player plays against the dealer. A player can win in three
different ways. The three ways are, the player gets 21 on his first two cards, the dealer gets a score higher than 21,
and if the player's score is higher than the dealer without going over 21. The dealer wins if the player goes over 21,
or if the dealer's hand is greater than the player's without going over 21. In the beginning, the player is
dealt two cards. There is also one rule which states that if the dealer's hand is greater than or equal to 17, then he
can not hit anymore. There is a point system that must be followed in the game of blackjack, all cards have a point
value based off the numeric indication on the front. The card's that don't follow this rule are ace's which could be 1
or 11, and face cards which all equal to 10. It is also important to know what a deck of cards has; a deck of cards ha
s 52 cards, 13 unique cards, and 4 suits of those 13 unique cards.
Game(player1, player2=)
The Game
Responsibilities:
* ask players if they want to hit or stand.
*
Collaborators:
* Collected into a Deck.
* Collected into a Hand for each player and a Hand for the dealer.
def play_game
def deal_two_cards_to_player
def switch_players
Player
The player
Responsibilities:
* Has to hit or stand
Collaborators:
* game takes the hit or stand response
def hit
def stand
money
Dealer
The dealer
Responsibilities:
* Has to hit, has to stand at 17 or greater
Collaborators:
* game takes the hit or stand response
def hit
def stand
money
shoe
Hand
cards_in_hand
Card
A playing card.
Responsibilities:
* Has a rank and a suit.
* Has a point value. Aces point values depend on the Hand.
Collaborators:
* Collected into a Deck.
* Collected into a Hand for each player and a Hand for the dealer.
suit
kind
Deck
card_amount
suits
kinds
if __name__ == '__main__':
"""
| true |
3883f41652fa43d96be453f5d5434aead2cf3ead | mohit131/python | /project_euler/14__Longest_Collatz_sequence.py | 1,095 | 4.21875 | 4 | '''The following iterative sequence is defined for the set of positive integers:
n → n/2 (n is even)
n → 3n + 1 (n is odd)
Using the rule above and starting with 13, we generate the following sequence:
13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been
proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.
Which starting number, under one million, produces the longest chain?
NOTE: Once the chain starts the terms are allowed to go above one million.'''
def even(x):
return(x/2)
def odd(x):
return(3*x + 1)
def Collatz(a):
b=[a]
while (a != 1):
if(a%2==0):
b.append(even(a))
a=even(a)
else:
b.append(odd(a))
a=odd(a)
return b
c=[]
lsize=[]
'''
for i in range(1,10000):
c.append((Collatz(i)))
lsize.append((len(c[i-1])))
#lsize.append()
#print(c)
print(max(lsize))
'''
irange=range(1,1000000)
c=list(map(Collatz,irange))
lsize1=list(map(len,c))
print(max(lsize1)) | true |
df01dc415a7750095dcd99b64690469a7c41b983 | Chittadeepan/P342 | /lab5_q2.py | 1,328 | 4.1875 | 4 | #importing everything from math module
from math import *
#importing all functions from library
from library import *
#poly_f(x) function
def poly_f(x,coeff,n):
sum=0
for i in range(1,n+1):
sum=sum+coeff[i-1]*x**(n-i)
return sum
#main program
def main():
#initialising final absolute error(epsilon), initial guess of root(root) and number of terms in polynomial(n)
epsilon=10**(-6)
root=0.9
n=5
#initialising coeff list and appending coeff elements corresponding to their variables with decreasing power
coeff=[1,-3,-7,27,-18]
#solving P(x)=x^4-3x^3-7x^2+27x-18
print('Solving x^(4)-3x^(3)-7x^(2)+27x-18 by Laguerre method and Synthetic Division method:')
#calling Laguerre function and Synthetic Division function and displaying the roots obtained in a loop
for index in range(n,1,-1):
root=Laguerre(root,epsilon,coeff,index,poly_f)
if index>0:
coeff=Synthetic_Division(root,coeff)
print('One of the roots obtained:',round(root,6))
main()
'''
#Output
Solving x^(4)-3x^(3)-7x^(2)+27x-18 by Laguerre method and Synthetic Division method:
One of the roots obtained: 1.0
One of the roots obtained: 2.0
One of the roots obtained: 3.0
One of the roots obtained: -3.0
'''
| true |
e537efac5d4877eb9b8516a4b02cee19f7985323 | PratheekH/Python_sample | /comp.py | 201 | 4.28125 | 4 | name=input("Enter your name ")
size=len(name)
if size<3:
print("Name should be more than 3")
elif size>50:
print("Name should not be more than 50")
else:
print("Name looks fine") | true |
2a8ea1f95001015fba07fc2130024b5c6a8375c7 | aashishah/LocalHackDay-Challenges | /EncryptPassword.py | 702 | 4.28125 | 4 | #Using Vignere Cipher to encrpt password of a user using a key that is private to the user.
def encrypt(password, key):
n = len(password)
#Generate key
if len(key) > n:
key = key[0:n]
else:
key = list(key)
for i in range(n - len(key)):
key.append(key[i % len(key)])
key = "" . join(key)
#Generate encrypted password:
cipher = []
for i in range(n):
letter = (ord(password[i]) + ord(key[i])) % 26
letter += ord('A')
cipher.append(chr(letter))
print("Encrypted password: " + "".join(cipher))
password = input("Enter password: ")
key = input("Enter your private key: ")
encrypt(password, key)
| true |
15c76b453894e5eb09fcaa195a0a8a66351b1048 | Karlo5o/rosalind_problems | /RNA.py | 700 | 4.1875 | 4 | """
An RNA string is a string formed from the alphabet containing 'A', 'C', 'G', and 'U'.
Given a DNA string t corresponding to a coding strand, its transcribed RNA string u is formed by replacing all occurrences of 'T' in t with 'U' in u.
Given: A DNA string t having length at most 1000 nt.
Return: The transcribed RNA string of t.
"""
def dna_transcriber(input_file):
with open('output.txt','w') as output, open(input_file) as input:
dna_string = input.readline()
rna_string = dna_string.replace("T", "U")
#Convert int to string
output.write(rna_string) #Write transcribed string in to file
dna_transcriber('input.txt') #input file name is 'input.txt'
| true |
d516d08d9c1af9bce8e845f69552a45377b6696b | marcusiq/w_python | /greeting.py | 1,570 | 4.4375 | 4 |
"""
Generally. There is no method overloading in python.
Overloading in other languages occurs when two methods have the same name, but different numbers of arguments.
In python, if you give more than one definition using the same name,
the last one entered rules, and any previous definitions are ignored.
"""
# Here an unsuspecting student attempts to overload a method named "greeting" with several definitions.
def greeting():
print "Hi! Are you new here?\n"
# The second takes one argument, and can be used to greet a person whose name you know.
def greeting(name):
print "Yes! It's my first day! My name is %s.\n" % name
# The third takes two arguments, and can be used to name both yourself and the addressee.
def greeting(name1, name2):
print "Nice to meet you %s! My name is %s.\n" % (name1, name2)
# The fourth takes one argument, conceived to be an integer.
def greeting(n):
print "Can I borrow $%d for coffee?\n" % n
# The fifth takes one argument, conceived to be a boolean.
def greeting(b): # A boolean.
if b:
print "Sure! Let's have coffee together.\n"
else:
print "Sorry! I'm flat broke!\n"
# Hmmm, that did not work! There is no overloading in Python!
try:
greeting()
except Exception as e:
print e.message
try:
greeting("Mork")
except Exception as e:
print e.message
try:
greeting("Mork", "Mindy")
except Exception as e:
print e.message
try:
greeting(10)
except Exception as e:
print e.message
try:
greeting(True)
except Exception as e:
print e.message
| true |
0db7eaa487bf54eb30f885b7baf11d93dfd6eabd | adamelliott1982/1359_Python_Benavides | /lab_04/1359-lab_04/drop_grade.py | 1,549 | 4.34375 | 4 | # Program: drop_grade.py
# Programmer: Adam Elliott
# Date: 02/26/2021
# Description: lab 4 - lists and for statements
########################################################
# create list of 5 grades and initialize
grades = [100, 80, 70, 60, 90]
# print report name – DROP LOWEST GRADE PROGRAM
print('DROP LOWEST GRADE PROGRAM:\n')
# show original grades using for in Loop
print('Grades:')
for grade in grades:
print(grade)
# use sum function on grades to calculate the total
total = sum(grades)
# calculate the average by dividing total by len(grades)
average = total/len(grades)
# print number of grades using len function
print(f'Number of grades: {len(grades)}')
# print average formatted to 2 decimal places
print(f'Average: {average:.2f}')
# find the lowest grade using min function and print lowest grade
lowest_grade = min(grades)
print(f'Lowest grade: {lowest_grade}')
#remove lowest grade
grades.remove(lowest_grade)
# print LOWEST GRADE DROPPED
print('\nLOWEST GRADE DROPPED:\n')
# show grades after dropping lowest grade using for in Loop
print('Grades:')
for grade in grades:
print(grade)
# use sum function to calculate the total after dropping lowest grade
total = sum(grades)
# compute new average
average = total/len(grades)
# print new number of grades
print(f'Number of grades: {len(grades)}')
# print new average
print(f'Average: {average:.2f}')
# find new lowest grade and print
lowest_grade = min(grades)
print(f'Lowest grade: {lowest_grade}')
| true |
37ac60fa04dbaed484d77e43317c6069a26ad777 | marc-p-greenfield/tutor_sessions | /payment_system.py | 602 | 4.21875 | 4 | number_of_employees = int(input("How many employees do you want to enter:"))
total_payment = 0
for i in range(number_of_employees):
name = input('Please enter name: ')
hours = float(input('How many hours did you work this week? '))
rate = float(input('What is your hourly rate?'))
payment = 0
overtime = 0
if hours > 40:
overtime = hours - 40
hours = 40
payment = (hours * rate) + (overtime * rate * 1.5)
total_payment += payment
print(name)
print("${:,.2f}".format(payment))
print (total_payment)
print (total_payment/number_of_employees)
| true |
f26e9e6bc1103c6c72fbe0fc72ed2435b62281ad | KishoreMayank/CodingChallenges | /Cracking the Coding Interview/Arrays and Strings/StringRotation.py | 349 | 4.1875 | 4 | '''
String Rotation:
Check if s2 is a rotation of s1 using only one call to isSubstring
'''
def is_substring(string, sub):
return string.find(sub) != -1
def string_rotation(s1, s2):
if len(s1) == len(s2) and len(s1) != 0:
return is_substring(s1 + s1, s2) # adds the two strings together and calls is substring
return False | true |
b5d3beb20cc86479f91f35db74f4f4a87bd54dc4 | KishoreMayank/CodingChallenges | /Interview Cake/Stacks and Queues/MaxStack.py | 821 | 4.3125 | 4 | '''
Max Stack:
Use your Stack class to implement a new class MaxStack with a
method get_max() that returns the largest element in the stack.
'''
class MaxStack(object):
def __init__(self):
self.stack = []
self.max = []
def push(self, item):
"""Add a new item to the top of our stack."""
self.stack.append(item)
if not self.max or item >= self.max[-1]: # add if empty or if greater
self.max.append(item)
def pop(self):
"""Remove and return the top item from our stack."""
item = self.stack.pop()
if item == self.max[-1]: # pop if the same element
self.max.pop()
return item
def get_max(self):
"""The last item in max is the max item in our stack."""
return self.max[-1]
| true |
047638de234a37c895d55b1aa6f571f72d2c9f4c | stellakaniaru/practice_solutions | /learn-python-the-hard-way/ex16.py | 877 | 4.3125 | 4 | '''Reading and writing files'''
from sys import argv
script, filename = argv
print "We're going to erase %r."%filename
print "If you don't want that, hit CTRL-C(^C)."
print "If you don't want that, hit RETURN."
raw_input("?")
print "Opening the file..."
target = open(filename, 'w')
#when you open the file in write mode,you dont need to truncate.
#write erases the contents of the already existing file
print "Truncating the file. Goodbye!"
target.truncate()
print "Now am going to ask you for three lines."
line1 = raw_input("line1: \n")
line2 = raw_input("line2: \n")
line3 = raw_input("line3: \n")
print "I'm going to write these to the file."
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
#alternatively:
#SEE HOW TO WRITE USING ONE COMMAND
print "And finally we close it."
target.close() | true |
b1025eb52f8c374fecd1458fe6e151f38eb8ec1a | stellakaniaru/practice_solutions | /overlapping.py | 500 | 4.1875 | 4 | '''
Define a function that takes in two lists and returns True
if they have one member in common.False if otherwise.
Use two nested for loops.
'''
#function definition
def overlapping(list1, list2):
#loop through items in first list
for i in list1:
#loop through items in second list
for j in list2:
#check if any of the items in list1 are equal to any of the items in list2
if i == j:
return True
#outside loop to ensure its not caught up in any loop conditions
return False
| true |
5b49cf35ea8a0c178691c729f4275a93519be37c | stellakaniaru/practice_solutions | /learn-python-the-hard-way/ex7.py | 849 | 4.40625 | 4 | '''more printing'''
#prints out a statement
print 'Mary had a little lamb.'
#prints out a statement with a string
print 'Its fleece was as white as %s.'%'snow'
#prints out a statement
print 'And everywhere that Mary went.'
print '.' * 10 #prints a line of ten dots to form a break
#assigns variables with a character each
end1 = 'C'
end2 = 'h'
end3 = 'e'
end4 = 'e'
end5 = 's'
end6 = 'e'
end7 = 'B'
end8 = 'u'
end9 = 'r'
end10 = 'g'
end11 = 'e'
end12 = 'r'
#prints out the variables by adding them together to form a name
#experiment with the comma
#when you remove the comma,python inteprates the next command to be executed on the next line.
#the comma tells python that execution of the following line of code should occur on the current line
print end1 + end2 + end3 + end4 + end5 + end6,
print end7 + end8 + end9 + end10 + end11 + end12 | true |
053d3a417ab0f05a201f9999917babd870869561 | stellakaniaru/practice_solutions | /years.py | 664 | 4.25 | 4 | '''
Create a program that asks the user to enter their name and
age. Print out a message addressed to them that tells them
the year they will turn 100 years old.
'''
from datetime import date
#ask for user input on name and age
name = input('Enter your name: ')
age = int(input('Enter your age: '))
num = int(input('Enter a number to show how many times the output should be printed: '))
#generates the current year
years = date.today().year
#generates the year of birth
diff = years - age
#generates the year the individual will turn 100 years
a_100 = diff + 100
#outputs the results
print("%s, you will be a 100yrs in the year %s\n" %(name, a_100) * num) | true |
1f42e53223e2ec4d0ce3f185cf5e4919985e0f0c | stellakaniaru/practice_solutions | /max_three.py | 364 | 4.3125 | 4 | '''
Define a function that takes in three numbers as
arguments and returns the largest of them.
'''
#function definition
def max_of_three(x,y,z):
#check if x if the largest
if x > y and x > z:
return x
#check if y is the largest
elif y > x and y > z:
return y
#if the first two conditions arent met,z becomes the largest by default
else:
return z
| true |
d3b3b842686d62d102ef89dfdffb0fefdc834343 | prabhatpal77/Adv-python-oops | /refvar.py | 475 | 4.1875 | 4 | # Through the reference variable we can put the data into the object, we can get the data from the object
# and we can call the methods on the object.
# We can creste a number of objects for a class. Two different object of a same class or different classes
# does not contain same address.
class Test:
"""sample class to test object"""
def display(self):
print("welcome")
print(Test.__doc__)
t1=Test()
print(t1)
t1.display()
t2=Test()
print(t2)
t2.display()
| true |
69996ed2547992a8a7b8eb86e554740f0ac3647b | IrinaVladimirTkachenko/Python_IdeaProjects_Course_EDU | /Python3/TryExcept/else_finaly.py | 855 | 4.34375 | 4 | # If we have an error - except block fires and else block doesn't fire
# If we haven't an error - else block fires and except block doesn't fire
# Finally block fires anyway
#while True:
# try:
# number = int(input('Enter some number'))
# print(number / 2)
#except:
# print('You have to enter a number!')
#else:
# print('Good job! This is a number!')
# break
#finally:
# print('Finally block')
#print('Code after error handling')
def divide(x, y):
try:
return x / y
except ZeroDivisionError as a:
print('You can\'t divide by zero!')
print(e)
except TypeError as e:
print('x and y must be numbers')
print(e)
else:
print('x has divided by y')
finally:
print('finally block')
print(divide(4, 0))
# print(divide(4, 'w')) | true |
b7c8c1f93678be20578422e02e01adeba36041f9 | Ballan9/CP1404-pracs | /Prac01/asciiTable.py | 420 | 4.25 | 4 | LOWER = 33
UPPER = 127
print("Enter a character:")
character = input()
print("The ASCII code for g is", ord(character))
number = int(input("Enter a number between {} and {}:".format(LOWER,UPPER)))
if number < LOWER or number > UPPER:
print("Invalid number entered")
else:
print("The Character for {} is ".format(number), chr(number))
for i in range (LOWER,UPPER+1):
print("{:<3}, {:>3}".format(i, chr(i)))
| true |
82b1b76a67d899523d77c2ee9d6fdea0812cbd67 | catherinelee274/Girls-Who-Code-2016 | /Python Projects/fahrenheittocelsius.py | 356 | 4.28125 | 4 | degree = input("Convert to Fahrenheit or celsius? For fahrenheit type 'f', for celsius type 'c'")
value = input("Insert temperature value: ")
value =int(value)
if degree == "c":
value = value-32
value = value/1.8
print(value)
elif degree == "f":
value = value*1.8 + 32
print(value)
else:
print("Insert a valid value")
| true |
3775cb6c2e02e1b142b14ef88f2cadd57fd47d3e | blakerbuchanan/algos_and_data_structures | /datastructures/datastructures/queues.py | 697 | 4.1875 | 4 | # Impelement a queue in Python
# Makes use of the list data structure inherent to Python
class Queue:
def __init__(self):
self.Q = []
def remove(self):
try:
self.Q.pop(0)
except:
print("Error: queue is empty.")
def add(self, item):
self.Q.append(item)
def peek(self):
return self.Q[0]
def isEmpty(self):
if len(self.Q) == 0:
return True
else:
return False
if __name__ == '__main__':
queue = Queue()
queue.remove()
print(queue.isEmpty())
queue.add("bird")
queue.add("alligator")
print(queue.Q)
print(queue.peek())
print(queue.isEmpty()) | true |
54785e654145533309b1197a6f17aea09a8d7b28 | go1227/PythonLinkedLists | /DoubleLinkedList.py | 1,655 | 4.1875 | 4 | __author__ = "Gil Ortiz"
__version__ = "1.0"
__date_last_modification__ = "4/7/2019"
__python_version__ = "3"
#Double Linked List
class Node:
def __init__(self, data, prev, next):
self.data = data
self.prev = prev
self.next = next
class DoubleList:
head = None
tail = None
def append(self, data): #append new value to the end of the list + add pointer prev pointing to the node before the last
new_node = Node(data, None, None)
if self.head is None:
self.head = new_node
self.tail = new_node
else:
new_node.prev = self.tail
#new_node.next = None
self.tail.next = new_node
self.tail = new_node
def remove(self, node_value):
this_node = self.head
while this_node is not None:
if this_node.data == node_value:
if this_node.prev is not None:
#re-link pointers to the point we simply "skip" the current node
this_node.prev.next = this_node.next
this_node.next.prev = this_node.prev
else:
self.head = this_node.next
this_node.next.prev = None
this_node = this_node.next
def show(self):
print("FULL Double Linked List:")
this_node = self.head
tmp = ""
while this_node is not None:
tmp = tmp + str(this_node.data) + " -> "
this_node = this_node.next
tmp = tmp + "None"
print(tmp)
d = DoubleList()
d.append(5)
d.append(8)
d.append(50)
d.show()
d.remove(8)
d.show() | true |
56bfaaa56ffb54a986b9d7ea862cb670405b785e | carloslorenzovilla/21NumberGame | /main.py | 2,291 | 4.34375 | 4 | """
Created on Sun Jul 14 10:17:48 2019
@author: Carlos Villa
"""
import numpy as np
# This game is a take on a 21 Card Trick. 21 numbers are randomly placed
# in a 7x3 matrix. The player thinks of a number and enters the column that
# the number is in. This step is repeated three times. Finally, the number
# that the user was thinking of is revealed.
class NumberTrick:
def __init__(self):
pass
@staticmethod
def shuffCards(grid, turn):
# Prompt for player input
if turn == 1:
col = int(input('Pick a number. What column it is in (1, 2, or 3)?: '))
print('\n')
else:
col = int(input('What column is your number in now (1, 2, or 3)?: '))
print('\n')
# Stays in loop until user provides valid entry
while col == 0 or col > 3:
col = int(input('That is not a valid column! Try again genius (1, 2, or 3): '))
print('\n')
# Elements in columns are aranged in reverse, and the selected coulumn
# is aranged between the other two columns. The newly aranged matrix is
# flattened into 1-D array by columns.
if col == 1:
numbers = np.array([grid[::-1,1],grid[::-1,col-1],grid[::-1,2]])
elif col == 2:
numbers = np.array([grid[::-1,0],grid[::-1,col-1],grid[::-1,2]])
else:
numbers = np.array([grid[::-1,0],grid[::-1,col-1],grid[::-1,1]])
numbers = numbers.flatten()
return numbers
def start(self):
#Create array from 1-21, shuffle
numbers = np.arange(1,22)
np.random.shuffle(numbers)
#Round 1
turn = 1
grid_1 = numbers.reshape(7,-1)
print('\n',grid_1)
numbers_1 = self.shuffCards(grid_1, turn)
#Round 2
turn += 1
grid_2 = numbers_1.reshape(7, -1)
print(grid_2)
numbers_2 = self.shuffCards(grid_2, turn)
#Round 3
turn += 1
grid_3 = numbers_2.reshape(7, -1)
print(grid_3)
numbers_3 = self.shuffCards(grid_3, turn)
#Result
print('Your number is {}!'.format(numbers_3[10]))
NumberTrick().start()
| true |
f7e6ef2007bcea37aa7aa2d7ba71a125b0bde471 | yulyzulu/holbertonschool-web_back_end | /0x00-python_variable_annotations/7-to_kv.py | 442 | 4.15625 | 4 | #!/usr/bin/env python3
"""Complex types"""
from typing import Tuple, Union
def to_kv(k: str, v: Union[int, float]) -> Tuple[str, float]:
""" type-annotated function to_kv that takes a string k and an
int OR float v as arguments and returns a tuple. The first element
of the tuple is the string k. The second element is the square of the
int/float v and should be annotated as a float."""
return (k, v ** 2)
| true |
d4d47e92f11fbac4d36867562b0616dd8fad565e | je-castelan/Algorithms_Python | /Python_50_questions/10 LinkedList/merge_sorted_list.py | 1,009 | 4.1875 | 4 | """
Merge two sorted linked lists and return it as a new sorted list.
The new list should be made by splicing together the nodes of the first two lists.
"""
from single_list import Node
def mergeTwoLists(l1, l2):
newList = Node(0,None)
pos = newList
while (l1 and l2):
if l1.value < l2.value:
pos.next = l1
pos = pos.next
l1 = l1.next
else:
pos.next = l2
pos = pos.next
l2 = l2.next
while l1:
pos.next = l1
pos = pos.next
l1 = l1.next
while l2:
pos.next = l2
pos = pos.next
l2 = l2.next
return newList.next #Not neccesary to use first node with "0"
if __name__ == '__main__':
n = Node (7, None)
m = Node (5, n)
c = Node (4, m)
b = Node (3, c)
a = Node (1, b)
f = Node (6, None)
e = Node (4, f)
d = Node (2, e)
newlist = mergeTwoLists(a, d)
x= newlist
while x:
print(x.value)
x = x.next
| true |
42ea8bfbfab0cda471b19eb65d3981a235888341 | je-castelan/Algorithms_Python | /Python_50_questions/19 Tree Graphs/max_path_sum.py | 1,457 | 4.125 | 4 | """
A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once. Note that the path does not need to pass through the root.
The path sum of a path is the sum of the node's values in the path.
Given the root of a binary tree, return the maximum path sum of any path.
"""
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution(object):
def __init__(self):
self.res = -float("inf")
def maxPathSum(self, root):
self._navigate(root)
return self.res
def _navigate(self, root):
if not root:
return 0
# The following recursion check the subpaths on left and right
left = self._navigate(root.left)
right = self._navigate(root.right)
#Maxside check only the node and the max side
maxside = max(root.val, max(left, right) + root.val)
# Then, it will check sumarizing the node and BOTH sides
maxtop = max(maxside, left + right + root.val)
#Having two sides, it check if it is the max path
self.res = max (self.res, maxtop)
# It will return only the max side (not top) in order to check
# upper on the tree
return maxside
| true |
6c8974807d165228b8465c8fbf0f469b7d6ac8c6 | dmoncada/python-playground | /stack.py | 1,359 | 4.1875 | 4 | class Stack:
'''A simple, generic stack data structure.'''
class StackNode:
def __init__(self, item, next_node):
self.item = item
self.next = next_node
class EmptyStackException(Exception):
pass
def __init__(self):
'''Initializes self.'''
self.top = None
self.count = 0
def __len__(self):
'''Returns len(self).'''
return self.count
def push(self, item):
'''push(item) -> None -- Pushes item to the top.'''
t = self.StackNode(item, self.top)
self.top = t
self.count += 1
def pop(self):
'''pop() -> item -- removes and returns the item at the top.
Raises EmptyStackException if the stack is empty.'''
if not self.top:
raise self.EmptyStackException('stack is empty')
item = self.top.item
self.top = self.top.next
self.count -= 1
return item
def peek(self):
'''peek() -> item -- returns (without removing) the item at the top.
Raises EmptyStackException if the stack is empty.'''
if not self.top:
raise self.EmptyStackException('stack is empty')
return self.top.item
def is_empty(self):
'''is_empty() -> boolean -- asserts if the stack is empty.'''
return not self.top
| true |
c122d2a776f88be7797cfbd7768db9be8e54e8a3 | murthyadivi/python-scripts | /Prime number check.py | 864 | 4.1875 | 4 | # returns the number input by user
def input_number(prompt):
return int(input(prompt))
# Checks if the given number is a primer or not
def check_prime(number):
#Default primes
if number == 1:
prime = False
elif number == 2:
prime = True
#Test for all all other numbers
else:
prime = True
for check_number in range(2, (number // 2)+1):
if number % check_number == 0:
prime = False
break
return prime
def display_prime(number):
prime = check_prime(number)
if prime:
check = ""
else:
check = "not "
print("The given number, ", number," is ", check, "prime.", sep = "", end = "\n\n")
while 1 == 1:
display_prime(input_number("Enter a number to check. Ctl-C to exit: "))
| true |
3e8715e64fe0540e8b00d7c28567773c3a8b178c | Krishan00007/Python_practicals | /AI_ML_visulizations/ML_linear_regression.py | 1,873 | 4.15625 | 4 | import warnings
warnings.filterwarnings(action="ignore")
# Practical implementation of Linear Regression
# -----------------------------------------------
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
def get_data(filename):
dataframe = pd.read_csv(filename)
print( dataframe)
x_parameters = []
y_parameters = []
for single_square_feet, single_price in zip(dataframe['square_feet'], dataframe['price'] ):
x_parameters.append( [single_square_feet] )
y_parameters.append( single_price )
# once we got the data, return it to main program
return x_parameters, y_parameters
#sandeepsingla sandeepsingla11:16 AM
def linear_model_main(x_parameters, y_parameters, quest_value):
# create Linear Regression Object
regr = LinearRegression()
regr.fit(x_parameters, y_parameters)
predicted_ans = regr.predict([[quest_value]])
print("Output From Machine = ", predicted_ans)
predictions = {}
print("After Training via Sklearn : Model Parameters")
print("m= ", regr.coef_)
print("c= ", regr.intercept_)
plt.scatter(x_parameters, y_parameters, color="m", s=30, marker="o")
all_predicted_Y=regr.predict( x_parameters)
plt.scatter(x_parameters, all_predicted_Y, color="b", s=30, marker="o")
plt.plot(x_parameters, all_predicted_Y, color="g")
plt.scatter(quest_value, predicted_ans, color="r")
plt.show()
def startAIAlgorithm():
#Collect the training data from external CSV file
x, y = get_data('sample_data/LR_House_price.csv')
print("Formatted Training Data : ")
print("x = ", x)
print("y = ", y)
question_value = 700 #This is the question data
linear_model_main(x, y, question_value)
if __name__ == "__main__":
startAIAlgorithm() | true |
61c414f192b860ad7fd4f392ce611b22d58d0f98 | Krishan00007/Python_practicals | /practical_6(2).py | 2,141 | 4.28125 | 4 | """
Write a GUI-based program that allows the user to convert temperature values between degrees Fahrenheit
and degrees Celsius. The interface should have labeled entry fields for these two values. These components
should be arranged in a grid where the labels occupy the first row and the corresponding fields occupy the
second row. At start-up, the Fahrenheit field should contain 32.0, and the Celsius field should contain
0.0. The third row in the window contains two command buttons, labeled >>>> and <<<. When the user presses
the first button, the program should use the data in the Fahrenheit field to compute the Celsius value,
which should then be output to the Celsius field. The second button should perform the inverse function.
"""
#!/usr/bin/env python3
from tkinter import *
def convert_fahr():
words = fbtext.get()
ftemp = float(words)
celbox.delete(0, END)
celbox.insert(0, '%.2f' % (tocel(ftemp)))
return
def convert_cel():
words = cbtext.get()
ctemp = float(words)
fahrbox.delete(0, END)
fahrbox.insert(0, '%.2f' % (tofahr(ctemp)))
def tocel(fahr):
return (fahr-32) * 5.0 / 9.0
def tofahr(cel):
return cel * 9.0 / 5.0 + 32
Convertor = Tk()
Convertor.title('Temperature converter')
fahrlabel = Label(Convertor, text = 'Fahrenheit')
fahrlabel.grid(row = 0, column = 0, padx = 5, pady = 5, sticky = E)
cellabel = Label(Convertor, text = 'Celsius')
cellabel.grid(row = 1, column = 0, padx = 5, pady = 5, sticky = E)
fbtext = StringVar()
fbtext.set('')
fahrbox = Entry(Convertor, textvariable=fbtext)
fahrbox.grid(row = 0, column = 1, padx = 5, pady = 5)
cbtext = StringVar()
cbtext.set('')
celbox = Entry(Convertor, textvariable=cbtext)
celbox.grid(row = 1, column = 1, padx = 5, pady = 5)
fgobutton = Button(Convertor, text = 'convert_far to cel', command = convert_fahr)
fgobutton.grid(row = 3, column = 0, padx = 5, pady = 5, sticky = N+S+E+W)
cgobutton = Button(Convertor, text = 'convert_cel to far', command = convert_cel)
cgobutton.grid(row = 3, column = 2, padx = 5, pady = 5, sticky = N+S+E+W)
Convertor.mainloop()
| true |
d8c97706c79eaeff2111524b111e3a25753176b7 | Krishan00007/Python_practicals | /AI_ML_visulizations/value_fill.py | 1,035 | 4.34375 | 4 | # Filling a null values using interpolate() method
#using interpolate() functon to fill missing values using Linear method
import pandas as pd
# Creating the dataframe
df = pd.DataFrame(
{ "A": [12, 4, 5, None, 1],
"B": [None, 2, 54, 3, None],
"C": [20, 16, None, 3, 8],
"D": [14, 3, None, None, 6]
}
)
# Print the dataframe
print( df )
#Let’s interpolate the missing values using Linear method.
# Note that Linear method ignore the index and treat the values as equally spaced.
# To interpolate the missing values
#df2 = df.interpolate(method ='linear', limit_direction ='forward')
#print( df2 )
#As we can see the output, values in the first row could not get filled as the direction of filling
# of values is forward and there is no previous value which could have been used in interpolation.
df3 = df.interpolate(method ='linear', limit_direction ='backward')
print( df3 ) | true |
23c50555c6cf85b3157b30c463e390d4b374d50c | Krishan00007/Python_practicals | /practical_3(1).py | 2,229 | 4.78125 | 5 | """
A bit shift is a procedure whereby the bits in a bit string are moved to the left or to the right.
For example, we can shift the bits in the string 1011 two places to the left to produce the string 1110.
Note that the leftmost two bits are wrapped around to the right side of the string in this operation.
Define two scripts, shiftLeft.py and shiftRight.py, that expect a bit string as an input.
The script shiftLeft shifts the bits in its input one place to the left, wrapping the leftmost
bitto the rightmost position. The script shiftRight performs the inverse operation. Each script
prints the resulting string.
"""
val = int(input("Enter 1 for Leftshift , 2 for Rightshift:"))
if(val==1):
num=input("Enter the number you want to left shift: ")
n=input("enter number of digits you want to shift: ")
while True:
if not (num.isnumeric() and n.isnumeric()):
if not num.isnumeric():
num=input("Sorry!! Enter a correct number: ")
else:
n=input("Sorry!! Enter number of digits: ")
else:
num=int(num)
n=int(n)
binary=bin(num)
print("The binary equivalent of the number is: ",binary)
leftShift=num<<n
print("the binary equivalent of the resultant is: ",bin(leftShift))
print("and the dedial equivalent is: ",leftShift)
break
elif(val==2):
num=input("Enter the number you want to right shift: ")
n=input("enter number of digits you want to shift: ")
while True:
if not (num.isnumeric() and n.isnumeric()):
if not num.isnumeric():
num=input("Sorry!! Enter a correct number: ")
else:
n=input("Sorry!! Enter number of digits: ")
else:
num=int(num)
n=int(n)
binary=bin(num)
print("The binary equivalent of the number is: ",binary)
rightShift=num>>n
print("the binary equivalent of the resultant is: ",bin(rightShift))
print("and the dedial equivalent is: ",rightShift)
break
else :
print("Enter a valid value!") | true |
14c47f156cf416431864448d62d3f27918d5226b | PNai07/Python_1st_homework | /02_datatypes.py | 1,888 | 4.5625 | 5 | # Data Types
# Computers are stupid
#They doi not understand context, and we need to be specific with data types.
#Strings
# List of Characters bundled together in a specific order
#Using Index
print('hello')
print(type('hello'))
#Concatenation of Strings - joining of two strings
string_a = 'hello there'
name_person = 'Juan Pier'
print (string_a + ' ' + name_person)
#Useful methods
#Length
print (len(string_a))
print (len(name_person))
#Strip = Removes trailing white spaces
string_num = ' 90323 '
print(type(string_num))
print(string_num)
print(string_num.strip())
#.split - a method for strings
#It splits in a specific location and output a list (data type)
string_text = 'Hello I need to go to the loo'
split_string =string_text.split(' ')
print(split_string)
#Capturing User Input - capture and display user input
#user_input_first_name = input('What is your first name')
#print (user_input_first_name)
# get user input and print first and last name
# 1) get user input/ first name
# save user input to variable
first_name = input ('What is your first name')
# get user last name
# and save it to variable
last_name = input ('what is your last name?')
#user_input_last_name = input('What is your last name')
#print (user_input_last_name)
# join two and
# Let us use concactenation
# Let us use interpolation
# print
full_name = first_name +' ' +last_name
print (full_name)
#Let us use interpolation
welcome_message = f"Hi {full_name} you are very welcome!"
print(welcome_message)
# Count /lower/ upper/ capitalize
text_example = "Here is some text, with lot's of text"
#Count
print(text_example.count('e'))
print(text_example.count('text'))
#lower
print(text_example.lower())
#Upper
print(text_example.upper())
#Capitalize
print(text_example.capitalize())
print('PIZZAHUT'.strip().capitalize())
print('PizzaHut'.capitalize())
print('pizza hut'.capitalize())
| true |
9908be12de460b5cb7a690eae3b9030e8422e8a2 | PNai07/Python_1st_homework | /06_datatypes_booleans.py | 1,426 | 4.5625 | 5 | # Booleans
# Booleans are a data type that is either TRUE or FALSE
var_true = True
var_false = False
#Syntax is capital letter
print(type(var_true))
print(type(var_false))
# When we equate/ evaluate something we get a boolean as a response.
# Logical operator return boolean
# == / ! / <> / >= / <=
weather = 'Rainy'
print(weather =='Sunny')
print (weather== 'Rainy')
#Logical **AND** & ** OR **
# evaluate two sides, BOTH have to be true for it to return True
print ('<Testing logical and: ')
print(weather== 'Rainy') and (weather== 'Sunny')
print(True and False)
#True
print ('<Testing logical and: ')
print(weather== 'Rainy') and (weather== 'Rainy')
print(True and True)
#Logical OR - One of the side
# Some methods or functions can return booleans
potential_number = '10'
print('hey')
print(potential_number.isnumeric())
print(potential_number.isinteger())
print ('location in code!')
print (potential_number.isnumeric())
print ('Location in code 2')
text = 'Hello World'
print(text[0] =='H')
print(text.startswith('h'))
print(text.startswith('H'))
print ('Testing. endswith.(arg)')
print (text[-1]== '!') # Strings are list of characters. -1 represents the last index in said list
print(text.endswith('!'))
print(text.endswith('?'))
#Booleans and Numbere
print("printing bool values of numbers")
print (bool(13))
print (bool(-1))
print (bool(3.14))
print (bool(1+3j))
#Value of None
print (bool(None))
| true |
53e2fc8c6c8ba4b78ad525d40a369a082611cb30 | Parth731/Python-Tutorial | /Quiz/4_Quiz.py | 264 | 4.125 | 4 |
# break and continue satement use in one loop
while (True):
print("Enter Integer number")
num = int(input())
if num < 100:
print("Print try again\n")
continue
else:
print("congrautlation you input is 100\n")
break
| true |
9641bd85b9168ca13ea4e70c287dd703d3f7c19c | Parth731/Python-Tutorial | /Exercise/2_Faulty_Calculator.py | 920 | 4.1875 | 4 | #Exercise 2 - Faulty Calculator
# 45*3 = 555, 56+9 = 77 , 56/6 = 4
# Design a caluclator which will correctly solve all the problems except
# the following ones:
# Your program should take operator and the two numbers as input from the user and then return the result
print("+ Addition")
print("- Subtraction")
print("* Multiplication")
print("/ Division")
op = input("choose the option +, -, *, /")
print("Enter the number 1")
a = int(input())
print("Enter the number 2")
b = int(input())
if op == '+':
if a == 56 and b == 9:
print("77")
else:
print(a+b)
elif op == '-':
if a == 55 and b == 10:
print("60")
else:
print(a - b)
elif op == '*':
if a == 45 and b == 3:
print("555")
else:
print(a * b)
elif op == '/':
if a == 56 and b == 6:
print("4")
else:
print(a / b)
else:
print("Error ! please check your input")
| true |
0a5b0d751a1fcbfa086452b6076527668aa4fcbc | shrobinson/python-problems-and-solutions | /series (2,11).py | 365 | 4.28125 | 4 | #Given two integers A and B. Print all numbers from A to B inclusively, in ascending order, if A < B, or in descending order, if A ≥ B.
#Recommendation. Use for loops.
#For example, on input
#4
#2
#output must be
#4 3 2
A = int(input())
B = int(input())
if A < B:
for i in range(A, B+1):
print(i)
else:
for i in range(A, B-1,-1):
print(i)
print()
| true |
bb4b6083ef0eca3abca1627acfab5a77dd0bc485 | shrobinson/python-problems-and-solutions | /length_of_sequence (2,4).py | 394 | 4.1875 | 4 | #Given a sequence of non-negative integers, where each number is written in a separate line. Determine the length of the sequence, where the sequence ends when the integer is equal to 0. Print the length of the sequence (not counting the integer 0).
#For example, on input
#3
#2
#7
#0
#output should be
#3
n = int(input())
count = 0
while n > 0:
count += 1
n = int(input())
print(count)
| true |
608a587c0123d50950fb43f3321572f01a2450e2 | shrobinson/python-problems-and-solutions | /countries_and_cities (3,18).py | 855 | 4.28125 | 4 | #First line of the input is a number, which indicates how many pairs of words will follow (each pair in a separate line). The pairs are of the form COUNTRY CITY specifying in which country a city is located. The last line is the name of a city. Print the number of cities that are located in the same country as this city.
#Hint. Use dictionaries.
#For example, on input:
#6
#UK London
#US Boston
#UK Manchester
#UK Leeds
#US Dallas
#Russia Moscow
#Manchester
#output must be:
#3
city_dict = {}
dict_count = int(input())
while dict_count > 0:
user_input = input()
value, key = user_input.split(" ")
city_dict[key] = value
dict_count = dict_count - 1
key_input = input()
check_value = city_dict[key_input]
value_count = 0
my_list = list(city_dict.values())
for i in my_list:
if i == check_value:
value_count += 1
print(value_count)
| true |
28150f1848962980561507ee3bf9a41804f3e564 | shrobinson/python-problems-and-solutions | /leap_year (1,13).py | 508 | 4.15625 | 4 | #Given the year number. You need to check if this year is a leap year. If it is, print LEAP, otherwise print COMMON.
#The rules in Gregorian calendar are as follows:
#a year is a leap year if its number is exactly divisible by 4 and is not exactly divisible by 100
#a year is always a leap year if its number is exactly divisible by 400
#For example, on input
#2000
#output must be
#LEAP
year = int(input())
if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
print("LEAP")
else:
print("COMMON")
| true |
a7a8ba21ad69cd68dc8ab7d57faf2cd40681524f | Get2dacode/python_projects | /quickSort.py | 1,180 | 4.15625 | 4 |
def quicksort(arr,left,right):
if left < right:
#splitting our array
partition_pos = partition(arr,left,right)
quicksort(arr,left, partition_pos - 1)
quicksort(arr,partition_pos+1,right)
def partition(arr,left,right):
i = left
j = right -1
pivot = arr[right]
while i < j:
while i < right and arr[i] < pivot:
i += 1
while j > left and arr[j] >= pivot:
j -= 1
if i < j:
arr[i],arr[j] = arr[j],arr[i]
if arr[i] > pivot:
arr[i],arr[right] = arr[right],arr[i]
return i
def display(list):
print('Unsorted:')
print(list)
quicksort(list,0,len(list)-1)
print('sorted')
print(list)
def rando(num):
import random
empty = []
while len(empty) < num:
number_generator = random.randint(0,100)
empty.append(number_generator)
if len(empty) >= num:
print(display(empty))
#test
Knicks_roster = ['RJ Barrett','Alec Burks','Evan Fournier','Taj Gibson','Quentin Grimes','Rokas Jokubaitis','Kevin Knox II','Miles McBride','Nerlens Noel','Immanuel Quickley','Julius Randle','Mitchell Robinson','Derrick Rose','Aamir Simms','Jericho Sims','Obi Toppin','Luca Vildoza','Kemba Walker','MJ Walker']
#display(Knicks_roster)
rando(13)
| true |
7b145f2578ad8e7a8b78b3230f38631bdc1f76c7 | aadilkadiwal/Guess_game | /user_guess.py | 651 | 4.15625 | 4 | # Number guess by User
import random
def user_guess(number):
random_number = random.randint(1, number)
guess = 0
guess_count = 0
while guess != random_number:
guess = int(input(f'Guess the number between 1 and {number}: '))
guess_count += 1
if guess > random_number:
print('Sorry, guess again, Too High')
elif guess < random_number:
print('Sorry, guess again. Too Low')
print(f'Great Job! You guess {random_number} number in {guess_count} guesses. ')
print('Selecting a range of number from 1 to ....')
number = int(input('Enter a last number: '))
user_guess(number) | true |
b4f271e3a902188ce99905547ebcf43d52261f50 | niloy-biswas/OOP-Data-structure-Algorithm | /oop.py | 2,673 | 4.15625 | 4 | class Person:
def __init__(self, name: str, age: int, birth_year: int, gender=None):
self.name = name # Person has a name // has a relation with instance
self.__age = age
self.__birth_year = birth_year # Private variable / Data encapsulation
self.gender = gender
def get_name(self):
return self.name
def set_name(self, new_name):
if self.__has_any_number(new_name):
print("Sorry, Name can't have number")
return
self.name = new_name
def get_birth_year(self):
return self.__birth_year
def __has_any_number(self, string): # private method. It can't be callable by outside of this class
# If anyone directly access the value then we can't check the validity of
# that new data. So that we use method for accessing instance
return "0" in string
def get_summery(self):
return f"Name: {self.name}, Age: {self.__age}, BirthYear: {self.__birth_year}, Gender: {self.gender}"
person1 = Person("Niloy", 22, 1999)
person2 = Person("Akib", 24, 1997)
print(person1.name) # Access directly without function
print(person2.get_name()) # Access with function
person2.set_name("Akib Bin Khodar Khashi") # override the value of name using set
print(person2.get_summery())
person1.name = "Niloy Biswas" # Access variable directly / for stop is use private variable
print(person1.get_name())
person1.set_name("00NIloy")
print(person1.get_name())
person_list = [Person("Mahi", 23, 1998),
Person("Riaz", 23, 1998, "Male"),
Person("Moon", 50, 1970, "Male")]
for person in person_list:
if person.get_birth_year() >= 1990:
print(person.get_summery())
class Student(Person): # Inheritance / Person is the super class
# Student is a Person / is a relation between sub and supper class
def __init__(self, name: str, age: int, birth_year: int, student_id: str):
super().__init__(name, age, birth_year)
self.student_id = student_id
def get_summery(self):
return f"Name: {self.get_name()}, BirthYear: {self.get_birth_year()}, ID: {self.student_id}"
student1 = Student("Tomi", 25, 1995, "171-35-239")
print(student1.get_summery())
student1.set_name("Tanvir")
print(student1.get_summery())
class Teacher(Person): # Teacher is a Person
def __init__(self, name: str, age: int, birth_year: int, dept: str):
super().__init__(name, age, birth_year)
self.department = dept
all_person_list = [
Person("Niloy", 22, 1999),
Student("Taz", 26, 1994, "171-35-241"),
Teacher("BIkash", 30, 1990, "SWE")
]
for p in all_person_list:
print(p.get_summery())
| true |
2c758cd5b6825ae199112690ac55dc7e229f782d | ritopa08/Data-Structure | /array_rev.py | 867 | 4.375 | 4 | '''-----Arrays - DS: An array is a type of data structure that stores elements of the same type in a contiguous block of memory. In an array, , of size , each memory location has some unique index, (where ), that can be referenced as (you may also see it written as ).
Given an array, , of integers, print each element in reverse order as a single line of space-separated integers.------'''
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the reverseArray function below.
def reverseArray(a):
n=len(a)
return a[n::-1]
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
arr_count = int(input())
arr = list(map(int, input().rstrip().split()))
res = reverseArray(arr)
fptr.write(' '.join(map(str, res)))
fptr.write('\n')
fptr.close()
| true |
a87621ac4cb9c506b514ee5c6f69796330c92237 | pratibashan/Day4_Assignments | /factorial.py | 261 | 4.25 | 4 |
#Finding a factorial of a given no.
user_number =int(input("Enter a number to find the factorial value: "))
factorial = 1
for index in range(1,(user_number+1)):
factorial *= index
print (f"The factorial value of a given number is {factorial}") | true |
6671ca404f704cf143d719c60f030eddf9a48b8d | vasudhanapa/Assignment-2 | /assignment 2.py | 750 | 4.40625 | 4 | #!/usr/bin/env python
# coding: utf-8
# 1. Write a program which accepts a sequence of comma-separated numbers from console and generate a list.
# 1. Create the below pattern using nested for loop in Python.
# *
# * *
# * * *
# * * * *
# * * * * *
# * * * *
# * * *
# * *
# *
#
# In[1]:
num1 = 1
num2 = 5
for i in range(0,2*num2):
if i<4:
print(('*'*num1))
num1 = num1 + 1
else:
print(('*'*num1))
num1 = num1 - 1
# 2. Write a Python program to reverse a word after accepting the input from the user. Sample Output:
# Input word: ineuron
# Output: norueni
#
# In[2]:
word = input("enter a word to reverse:")
for i in range(len(word)-1,-1,-1):
print(word[i],end = "")
# In[ ]:
| true |
9709680af1eeef88c1b8472142c5f85b9003114c | AmitAps/advance-python | /generators/generator7.py | 860 | 4.5 | 4 | """
Understanding the Python Yield Statement.
"""
def multi_yield():
yield_str = "This will print the first string"
yield yield_str
yield_str = "This will print the second string"
yield yield_str
multi_obj = iter(multi_yield())
while True:
try:
prt = next(multi_obj)
print(prt)
except StopIteration:
break
# print(next(multi_obj))
#
# print(next(multi_obj))
# print(next(multi_obj))
"""
Take a closer look at that last call to next(). You can see that execution has blown up with a
traceback. This is because generators, like all iterators, can be exhausted. Unless your
generator is infinite, you can iterate through it one time only. Once all values have been
evaluated, iteration will stop and the for loop will exit. If you used next(),
then instead you’ll get an explicit StopIteration exception.
"""
| true |
9f311f33adbc0a2fb31ffc1adb014bb66de0fb2b | AmitAps/advance-python | /oop/class2.py | 337 | 4.15625 | 4 | class Dog:
#class attribute
species = 'Canis familiaris'
def __init__(self, name, age):
self.name = name
self.age = age
"""
Use class attributes to define properties that should have the same value for every class instance. Use instance attributes for properties that vary from one
instance to another.
"""
| true |
42f8e41488f1de16d53ced9f76053374fe5ce4a3 | AmitAps/advance-python | /instance_class_and_static_method/fourth_class.py | 1,073 | 4.15625 | 4 | import math
class Pizza:
def __init__(self, radius, ingredients):
self.radius = radius
self.ingredients = ingredients
def __repr__(self):
return (f'Pizza({self.radius!r}, '
f'{self.ingredients!r})')
def area(self):
return self.circle_area(self.radius)
@staticmethod
def circle_area(r):
return r ** 2 * math.pi
"""
Flagging a method as a static method is not just a hint that a method won’t modify class or instance state — this restriction is also enforced by the Python runtime.
Instance methods need a class instance and can access the instance through self.
Class methods don’t need a class instance. They can’t access the instance (self) but they have access to the class itself via cls.
Static methods don’t have access to cls or self. They work like regular functions but belong to the class’s namespace.
Static and class methods communicate and (to a certain degree) enforce developer intent about class design. This can have maintenance benefits.
"""
| true |
a4a9466ca29261aff4264cd4d2c565df7c19a0fa | AmitAps/advance-python | /dog-park-example.py | 703 | 4.5 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 22 09:25:55 2020
@author: aps
"""
class Dog:
species = "Canis familiaris"
def __init__(self, name, age, breed):
self.name = name
self.age = age
self.breed = breed
# Another instance method
def speak(self, sound):
return f"{self.name} says {sound}"
def __str__(self):
return f"{self.name} is {self.age} years old"
"""
Remember, to create a child class, you create new class with its own name and then put the name of the parent
class in parentheses.
"""
class JackRussellTerrier(Dog):
pass
class Dachshund(Dog):
pass
class Bulldog(Dog):
pass
| true |
c977f10079c4c36333dfc1b33635945b2e469c29 | Ayselin/python | /candy_store.py | 1,014 | 4.125 | 4 | candies = {
'gummy worms': 30,
'gum': 40,
'chocolate bars': 50,
'licorice': 60,
'lollipops': 20,
}
message = input("Enter the number of the option you want to check?: \n1. To check the stock. \n2. How many candies have you sold? \n3. Shipment of new stock.")
if message == '1':
for candy, amount in candies.items():
amount = int(amount)
print(f"{candy}: {amount}")
elif message == '2':
# for candy, amount in candies.items():
items = input("Please enter the product you want to check: ")
sold = input("How many candies have you sold?: ")
sold = int(sold)
candies[items] = candies[items] - sold
print(f"{candies[items]}")
elif message == '3':
# for candy, amount in candies.items():
product = input("Please enter the product you want to check: ")
received = input("How many items were delivered?: ")
received = int(received)
candies[product] = candies[product] + received
print(f"{candies[product]}")
| true |
1788d7fb0349eebc05ab37f91754b18e6ce66b3f | SeshaSusmitha/Data-Structures-and-Algorithms-in-Python | /SelectionSort/selection-sort.py | 423 | 4.3125 | 4 | def insertionSort(array1,length):
for i in range(0, length ):
min_pos = i;
for j in range(i+1, length):
if array1[j] < array1[min_pos]:
min_pos = j;
temp = array1[i];
array1[i] = array1[min_pos];
array1[min_pos] = temp;
array1 = [2, 7, 4, 1, 5, 3];
print "Array before Selection sort"
print(array1);
length = len(array1);
insertionSort(array1, length);
print "Array after Selection sort"
print(array1); | true |
4b414735cbd1563ac59a6598279f7a4863723828 | zaidITpro/PythonPrograms | /inseritonanddeletionlinklist.py | 1,106 | 4.15625 | 4 | class Node:
def __init__(self,data):
self.data=data
self.next=None
class LinkedList:
def __init__(self):
self.head=None
def insert(self,data):
if(self.head==None):
self.head=Node(data)
else:
current=self.head
while(current.next!=None):
current=current.next
current.next=Node(data)
def insert_at_beg(self,data):
newnode=Node(data)
newnode.next=self.head
self.head=newnode
def delete_at_beg(self):
current=self.head
self.head=current.next
del current
def printlist(self):
current=self.head
while(current!=None):
print(current.data)
current=current.next
myLinkList=LinkedList()
myLinkList.insert(25)
myLinkList.insert(45)
myLinkList.insert(78)
print("\n\nCreated Linked List is: \n")
myLinkList.printlist()
print("\n\nEnter the element you want to insert at the beginning: ")
element=int(input())
myLinkList.insert_at_beg(element)
print("\n\nThe updated Linked List after insertion at beginning: \n")
myLinkList.printlist()
print("\n\nThe updated Linked List after deletion at beginning:\n")
myLinkList.delete_at_beg()
myLinkList.printlist() | true |
e2c32f8e48cb84d2c52db49f4559746ac7a56eae | petr-tik/lpthw | /ex30.py | 779 | 4.15625 | 4 | #-*- coding=utf-8 -*-
people = 30
cars = 40
trucks = 15
if cars > people:
print "We should take the cars."
elif cars < people:
print "We should not take the cars."
else:
print "we cannot decide"
if trucks > cars:
print "That's too many trucks"
elif trucks < cars:
print "maybe we could take the trucks"
else:
print "we still cannot decide"
if people > trucks and cars == trucks:
print "people can choose between cars or trucks"
else:
print "there are either more trucks than people or the number of cars doesn't equal the number of trucks"
# if, elif (maybe multiple) and else assess which block of code should be run
# the elif statement with TRUE boolean value executes the block below it
lines = [raw_input("line %d: " % i) for i in range (1,5)]
print lines | true |
92fee0692d9bfd860c4235c13ca639065c0bb7ee | petr-tik/lpthw | /ex4.py | 1,281 | 4.25 | 4 | # assign the variable 'cars' a value of 100
cars = 100
# assign the variable 'space_in_a_car' a floating point value of 4.0
space_in_a_car = 4
# assign the variable 'drivers' a value of 30
drivers = 30
# assign the variable 'passengers' a value of 90
passengers = 90
# assign the variable 'cars_not_driven' a value equaling the difference between the number of cars and drivers
cars_not_driven = cars - drivers
# the variable cars_driven is equal to the number of drivers
cars_driven = drivers
# the variable for carpool capacity is calculated as the product of cars driven and space in a car
carpool_capacity = cars_driven * space_in_a_car
# the variable for average passengers per car is the result of division of the number of passengers by the number of cars driven
average_passengers_per_car = passengers / cars_driven
print "There are", cars, "cars available"
print "There are only", drivers, "drivers available."
print "There will be", cars_not_driven, "empty cars today."
print "We can transport", carpool_capacity, "people today."
print "We have", passengers, "to carpool today."
print "We need to put about", average_passengers_per_car, "in each car."
# = assigns a value to a variable
# == checks if two values/variables are equal
# x = 100 is better than
# x=100
| true |
7e4d07ccaffd2671193f8d011a8c209e15a02552 | plooney81/python-functions | /madlib_function.py | 887 | 4.46875 | 4 | # create a function that accepts two arguments: a name and a subject
# the function should return a string with the name and subject inerpolated in
# the function should have default arguments in case the user has ommitted inputs
# define our function with default arguments of Pete and computer science for name and subject respectively
def madlib(name="Pete", subject="computer science"):
return f'{name}\'s favorite subject is {subject}'
# prompt the user for name and subject
print('\nPlease input your name')
user_name = input('> ')
print('\nPlease input your favorite subject')
user_subject = input('> ')
# call the madlib function with the two user inputs as the parameters, then we save
# the return of that function into a new variable named string output, which we will then print below
string_output = madlib(user_name, user_subject)
print(f'\n\n{string_output}\n\n')
| true |
b41ce62b8a50afdc1fb0fecb58bfe7de4c59d9cd | psukalka/morning_blues | /random_prob/spiral_matrix.py | 2,073 | 4.4375 | 4 | """
Date: 27/06/19
Program to fill (and optionally print) a matrix with numbers from 1 to n^2 in spiral form.
Time taken: 24min
Time complexity: O(n^2)
*) Matrix formed with [[0]*n]*n will result in n copies of same list. Fill matrix elements individually instead.
"""
from utils.matrix import print_matrix
def fill_spiral(n):
'''
There are total four directions. Left to right (LR), Top to Bottom (TB), Right to left (RL) or Bottom to Top (BT).
To fill a spiral matrix, we need to change directions at either boundary of the matrix or if the element is already filled.
:param n: width of the box
'''
direction = "LR"
start_x = 0
start_y = -1
count = 1
matrix = []
for i in range(0, n):
row = []
for j in range(0, n):
row.insert(j, 0)
matrix.insert(i, row)
while count <= n * n:
if direction == "LR":
i = start_x
for j in range(start_y + 1, n):
if matrix[i][j] != 0:
break
matrix[i][j] = count
count += 1
start_y = j
direction = "TB"
if direction == "RL":
i = start_x
for j in range(start_y - 1, -1, -1):
if matrix[i][j] != 0:
break
matrix[i][j] = count
count += 1
start_y = j
direction = "BT"
if direction == "TB":
j = start_y
for i in range(start_x + 1, n):
if matrix[i][j] != 0:
break
matrix[i][j] = count
count += 1
start_x = i
direction = "RL"
if direction == "BT":
j = start_y
for i in range(start_x - 1, -1, -1):
if matrix[i][j] != 0:
break
matrix[i][j] = count
count += 1
start_x = i
direction = "LR"
return matrix
matrix = fill_spiral(4)
print_matrix(matrix)
| true |
26a29fa5956b9ef81041c2d0496c26fd4eb0ad08 | psukalka/morning_blues | /random_prob/matrix_transpose.py | 1,037 | 4.4375 | 4 | """
Given a matrix, rotate it right by 90 degrees in-place (ie with O(1) extra space)
Date: 28/06/19
Time Complexity: O(n^2)
Time taken: 30 min
"""
from utils.matrix import create_seq_matrix, print_matrix
def transpose_matrix(mat):
"""
Rotate a matrix by 90 degrees to right.
Ex:
Original:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Rotated:
13 9 5 1
14 10 6 2
15 11 7 3
16 12 8 4
:param mat: Matrix to be rotated
:return: transpose of matrix
"""
rows = len(mat)
for col in range(0, int(rows / 2)):
for i in range(col, rows - col - 1):
temp = mat[rows - i - 1][col]
mat[rows - i - 1][col] = mat[rows - col - 1][rows - i - 1]
mat[rows - col - 1][rows - i - 1] = mat[i][rows - col - 1]
mat[i][rows - col - 1] = mat[col][i]
mat[col][i] = temp
return mat
matrix = create_seq_matrix(4)
print_matrix(matrix)
matrix = transpose_matrix(matrix)
print_matrix(matrix)
| true |
54053e477ab116aa59c4a4e52bb3744d28fe56b8 | storans/as91896-virtual-pet-ajvl2002 | /exercise_pet.py | 2,167 | 4.25 | 4 | # checks if the number entered is between 1-5 or 1,3 or whatever has been stated
# check int function
def check_int(question, error, low, high):
valid = False
# while loop
while valid == False:
number = input("{}".format(question))
try:
number = int(number)
if low <= number <= high:
return number
else:
print(error)
except ValueError:
print(error)
# puts stars or exclamation points around words if the formatter is used
def formatter(character, output):
print(character * (len(output) + 4))
print("{} {} {}".format(character, output, character))
print(character * (len(output) + 4))
# show items function
def show_items(dictionary_name):
number = 1
for item in dictionary_name:
print("{}. {}".format(number, item.title()))
number += 1
# choose item function
def choose_item(list_name):
choice = check_int("Please choose an option from the following forms of exercise:", "Please choose a number between 1 and 3.", 1, 3)
choice = choice - 1
chosen_item = list_name[choice][1]
return chosen_item
# weight
# calculates the pets weight function
def weight_calc(current_weight, choice, list_name):
total_weight = current_weight - choice
return total_weight
# Main Routine
start_weight = 1.5
EXERCISE_DICTIONARY = {"hop": 0.2, "run": 0.3, "walk": 0.1}
EXERCISE_LIST = [["hop", 0.2], ["run", 0.3], ["walk", 0.1]]
# main_menu
formatter("*", "Virtual pet")
print()
print("Main menu:")
print("1. Check your virtual pet's weight\n"
"2. feed your virtual pet\n"
"3. Exercise your virtual pet\n"
"4. Help\n"
"5. Exit virtual pet\n")
# checks if the number entered is between 1-5
menu_choice = check_int("Please enter the number of the option you wish to do:", "Please choose a number between 1 and 5.", 1, 5)
print()
# if menu choice equals 3 do this...
if menu_choice == 3:
show_items(EXERCISE_DICTIONARY)
exercise = choose_item(EXERCISE_LIST)
weight = weight_calc(start_weight, exercise, EXERCISE_LIST)
print("Your pet weighs {}kgs".format(weight))
| true |
0dba230b503ad68b4fa1c6185a947637633ba7a6 | SimonLundell/Udacity | /Intro to Self-Driving Cars/Bayes rule/numpy_examples.py | 638 | 4.375 | 4 | # but how would you print COLUMN 0? In numpy, this is easy
import numpy as np
np_grid = np.array([
[0, 1, 5],
[1, 2, 6],
[2, 3, 7],
[3, 4, 8]
])
# The ':' usually means "*all values*
print(np_grid[:,0])
# What if you wanted to change the shape of the array?
# For example, we can turn the 2D grid from above into a 1D array
# Here, the -1 means automatically fit all values into this 1D shape
np_1D = np.reshape(np_grid, (1, -1))
print(np_1D)
# We can also create a 2D array of zeros or ones
# which is useful for car world creation and analysis
# Create a 5x4 array
zero_grid = np.zeros((5, 4))
print(zero_grid)
| true |
2c55e90b57860b41171344fcc2d3d1a7e69968b1 | kanuos/solving-https-github.com-ProgrammingHero1-100-plus-python-coding-problems-with-solutions | /NumberRelated/DivisbleBy3And5.py | 522 | 4.3125 | 4 | # Divisible by 3 and 5
# The problem
# For a given number, find all the numbers smaller than the number.
# Numbers should be divisible by 3 and also by 5.
try:
num = int(input("Enter a number : "))
counter = 0
for i in range(num):
if i % 15 == 0:
print(f"{i} is divisible by 3 and 5.")
counter += 1
print(f"There are {counter} numbers between 0 and {num}(not inclusive) "
f"that are divisible by 3 and 5")
except ValueError:
print("Input must be an integer")
| true |
66af1aa9f857197a90b5a52d0d7e83a5a56f1d35 | kanuos/solving-https-github.com-ProgrammingHero1-100-plus-python-coding-problems-with-solutions | /Reverse/ReverseNumber.py | 376 | 4.3125 | 4 | # Reverse a number
# The problem
# Reverse a number.
def reverse_number(num: int) -> int:
reverse_num = 0
while num > 0:
reverse_num = reverse_num * 10 + num % 10
num //= 10
return reverse_num
try:
n = int(input("Enter a number : "))
print(f"Reverse of {n} is {reverse_number(n)}")
except ValueError:
print("Input must be a number")
| true |
4a31afea4a442fef55f57d261d0f93298e056efd | kanuos/solving-https-github.com-ProgrammingHero1-100-plus-python-coding-problems-with-solutions | /PrimeNumber/AllPrimes.py | 530 | 4.1875 | 4 | # All Prime Numbers
# the problem
# Ask the user to enter a number. Then find all the primes up to that number.
try:
n, p = int(input("Enter a number : ")), 2
all_primes = [False, False]
all_primes.extend([True] * (n - 1))
while p ** 2 <= n:
if all_primes[p]:
for i in range(p * 2, n + 1, p):
all_primes[i] = False
p += 1
all_primes = [i for i in range(len(all_primes)) if all_primes[i]]
print(all_primes)
except ValueError:
print("Input must be a number")
| true |
e2f84b0a47c1b9c39d804cd95e53820c1e99c47e | kanuos/solving-https-github.com-ProgrammingHero1-100-plus-python-coding-problems-with-solutions | /EasyOnes/TemporaryVariables.py | 745 | 4.5 | 4 | # Swap two variables
# The problem
# Swap two variables.
#
# To swap two variables: the value of the first variable will become the value of the second variable.
# On the other hand, the value of the second variable will become the value of the first variable.
#
# Hints
# To swap two variables, you can use a temp variable.
var1 = input("Enter variable 1 : ")
var2 = input("Enter variable 2 : ")
# without using temporary variables
print(f"Before swapping : A = {var1}, B = {var2}")
var1, var2 = var2, var1
print(f"After swapping <py way> : A = {var1}, B = {var2}")
var1, var2 = var2, var1
print(f"Before swapping : A = {var1}, B = {var2}")
temp = var1
var1 = var2
var2 = temp
print(f"After swapping <temp variable> : A = {var1}, B = {var2}")
| true |
bc0cdadda198a60507364154b43e3a9088605e08 | kanuos/solving-https-github.com-ProgrammingHero1-100-plus-python-coding-problems-with-solutions | /LoopRelated/SecondSmallest.py | 848 | 4.25 | 4 | # Second smallest element
# The problem
# For a list, find the second smallest element in the list
try:
size = int(input("Enter the size of the array : "))
user_list = []
unique_ordered = []
if size <= 0:
raise ValueError("Size of array must be a non-zero positive integer")
if size > 1:
for _ in range(size):
user_list.append(float(input("Enter the number : ")))
unique_ordered = sorted(list(set(user_list)))
smallest = unique_ordered[0]
second_smallest = unique_ordered[1]
else:
smallest = unique_ordered[0]
second_smallest = unique_ordered[0]
print("User list : ", str(user_list))
print(f"The smallest number : {smallest}")
print(f"The second smallest number : {second_smallest}")
except ValueError:
print("List items must be numbers")
| true |
0bf8f3f1388fc54ef3956e91899841438aca7482 | kanuos/solving-https-github.com-ProgrammingHero1-100-plus-python-coding-problems-with-solutions | /PrimeNumber/SmallestPrimeFactor.py | 770 | 4.1875 | 4 | # Smallest prime factor [premium]
# The problem
# Find the smallest prime factor for the given number.
def is_prime(number):
number = abs(number)
if number == 0 or number == 1:
return False
for i in range(2, number):
if number % i == 0:
return False
return True
def all_factors(number):
number = abs(number)
factors = []
for i in range(1, number + 1):
if number % i == 0:
factors.append(i)
return factors
try:
n = int(input("Enter a number : "))
print(f"The factors of {n} are : {all_factors(n)}")
prime_factors = [x for x in all_factors(n) if is_prime(x)]
print(f"The prime factors of {n} are : {prime_factors}")
except ValueError:
print("Input must be a number")
| true |
7bcb73db98b3c593be479799b1c548e8d83bbfed | ParkerCS/ch18-19-exceptions-and-recursions-elizafischer | /recursion_problem_set.py | 2,681 | 4.125 | 4 | '''
- Personal investment
Create a single recursive function (or more if you wish), which can answer the first three questions below. For each question, make an appropriate call to the function. (5pts each)
'''
#1. You have $10000 on a high interest credit card with an APR of 20.0% (calculated MONTHLY, so MPR is APR/12). Assuming you make no payments for 6 months, what is your new balance? Solve recursively.
money = 10000
apr = 20
monthly_apr = apr/12
#print(monthly_apr)
def one(money, month):
apr = 0.20
monthly_apr = apr / 12
money += money * monthly_apr
if month < 7:
one(money, month + 1)
if month == 6:
money = round(money,2)
print("You have $" + str(money), "after 6 months.")
print("\nProblem #1")
one(money, 1)
print()
#2. You have $5000 on a high interest credit card with an APR of 20.0% (calculated MONTHLY). You make the minimum payment of $100 per month for 36 months. What is your new balance? Solve recursively.
def two(money, month):
monthly_apr = 0.20 / 12
money += money * monthly_apr
money -= 100
#if month < month + 1
if month < 37:
two(money, month +1)
if month == 36:
money = round(money,2)
print("You have $" + str(money), "after 36 months of paying the minimum of $100 a month.")
print("Problem #2")
two(5000, 36)
print()
#3. You have $10000 on a high interest credit card with an APR of 20.0% (calculated MONTHLY). If you make the minimum payment of $100 per month, how many months will it take to pay it off? Solve recursively.
def three(money, month, done):
monthly_apr = 0.20 / 12
money += money * monthly_apr
money -= 100
money = round(money, 2)
print(money)
if month < 100 and not done:
three(money, month +1, False)
if money <= 0:
done = True
print("Your debt was paid off after" , month, "month(s).")
print("Promblem #3 doesn't work because you will never pay off your debt:")
three(10000, 1, False)
print()
#4 Pyramid of Cubes - (10pts) If you stack boxes in a pyramid, the top row would have 1 box, the second row would have two, the third row would have 3 and so on. Make a recursive function which calculates the TOTAL NUMBER OF BOXES for a pyramid of boxes n high. For instance, a pyramid that is 3 high would have a total of 6 boxes. A pyramid 4 high would have 10.
def four(n_height, boxes, index):
boxes += n_height
if n_height != 0:
four(n_height - 1, boxes, index + 1)
elif n_height == 0:
print("There would be", boxes, "boxes for that number of rows")
n_height = int(input("Enter a number of rows (height): "))
four(n_height, 0, 0) | true |
41b46b0cbd0b3b8e5a8be106469a82bcfa096b60 | koakekuna/pyp-w1-gw-language-detector | /language_detector/main.py | 933 | 4.34375 | 4 | # -*- coding: utf-8 -*-
"""This is the entry point of the program."""
from languages import LANGUAGES
def detect_language(text, languages=LANGUAGES):
"""Returns the detected language of given text."""
# create dictionary to store counters of words in a language
# example --> counters = {"spanish": 29, "german": 3, "english": 0}
counters = {}
for language in LANGUAGES:
counters[language["name"]] = 0
# iterate through each word in text,
# compare to common words in each dictionary
# if it matches, then add +1 to the counter for the language
for word in text.split():
for language in LANGUAGES:
name = language['name']
commonwords = language['common_words']
if word in commonwords:
counters[name] += 1
# return the highest value of all keys in the counter dictionary
return max(counters, key=counters.get) | true |
f70add96e7e82cf95f9f6a8df4f00a25b2a8f17d | ankity09/learn | /Python_The_Hard_Way_Codes/ex32.py | 596 | 4.15625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 8 18:40:47 2019
@author: ankityadav
"""
the_count = [1,2,3,4,5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters' ]
for number in the_count:
print("This is count {}".format(number))
for fruit in fruits:
print("A fruit of type: {}".format)
for i in change:
print("I got {}".format(i))
elements = []
for i in range(0, 6):
print("Adding {} to the list.".format(i))
elements.append(i)
for i in elements:
print("Element was: {}".format(i))
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.