blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
7dadb8ac568f1ee1c0a8912352b74a889859247a | Harrisonkamau/andela_bootcamp | /Day2/classes/polymorphism.py | 1,189 | 4.40625 | 4 | '''This is an examle of polymorphism'''
class SchoolMember:
''' represents a school member '''
def __init__(self, name, age):
self.name = name
self.age = age
print "Initalized school member name: {}".format(self.name)
def tell(self):
''' Tell my details '''
print 'Name: {} Age: {}'.format(self.name, self.age)
class Teacher(SchoolMember):
''' Represents a teacher '''
def __init__(self, name, age, salary):
SchoolMember.__init__(self, name, age)
self.salary = salary
print 'Initialized teacher Name:{}'.format(self.name)
def tell(self):
SchoolMember.tell(self)
print 'Salary {:d}'.format(self.salary)
class Student(SchoolMember):
''' Represents a student '''
def __init__(self, name, age, marks):
SchoolMember.__init__(self, name, age)
self.marks = marks
print 'Initialized student Name: {}'.format(self.name)
def tell(self):
SchoolMember.tell(self)
print 'Marks: {:d}'.format(self.marks)
murungaru = Teacher("Mr. Murungaru", 39, 300000)
print murungaru.tell()
kinuthia = Student("Kinuthia Ndungu", 24, 44000)
print kinuthia.tell()
| false |
22390955223423ae07a8045186d7c01356b76141 | Harrisonkamau/andela_bootcamp | /Day2/exercises.py | 2,638 | 4.3125 | 4 | '''
Define a function called data_type, to take one argument. Compare and return results, based on the argument supplied to the function.
Complete the test to produce the perfect function that accounts for all expectations.
For strings, return its length.
For None return string 'no value'
For booleans return the boolean
For integers return a string showing how it compares to hundred e.g.
For 67 return 'less than 100' for 4034 return 'more than 100' or equal to 100 as the case may be
For lists return the 3rd item, or None if it doesn't exist
'''
# solutions
def data_type(data):
if type(data) == bool:
return data
elif type(data) == int:
if data < 100:
return 'less than 100'
elif data > 100:
return 'more than 100'
elif data == 100:
return 'equal to 100'
elif type(data) == list:
if len(data) >= 3:
return data[2]
else:
return None
elif type(data) == str:
return len(data)
else:
return 'no value'
# declare a student dictionary
student = {
'name': 'Harrison',
'langs': ['Python', 'JavaScript', 'PHP'],
'age': 23
}
'''
Task 1
Create a function add_student that takes a student dictionary as a parameter,
and adds the student in a list of students
'''
# solution
# Declare an empty list
students = []
def add_student(student):
# adds student to the students list
students.append(student)
#
'''
Task 2
Write a function oldest_student that finds the oldest student.
'''
#
def oldest_student(students):
oldest = 0 # This variable assumes the oldest student is 0 years
for student in students:
# if student['age'] > oldest: if the current age is greater than my assumed age, then the oldest age changes
oldest = student['age']
return oldest
# declare any number of dictionaries
student1 = {'name': 'Joy', 'langs': ['Python', 'JavaScript', 'PHP'], 'age': 32}
student2 = {'name': 'Gracie', 'langs': ['Python', 'JavaScript', 'PHP'], 'age': 12}
# adds the declared dictionaries to the students list
add_student(student1)
add_student(student2)
print oldest_student(students)
'''
Task 3
Write a function student_lang that takes in a parameter lang and returns a
list containing names of students who know that language.
'''
def student_lang(lang):
for student in students:
# iterates through the students list
if lang in student['langs']:
# The if statement is iterating through the student's dictionaries to trace the key langs
return student['name']
print student_lang('Python')
| true |
a4e176bad3fd2139fd10079278f500e03c8155e5 | DoubleDPro/practice | /numbers/task_13.py | 500 | 4.15625 | 4 | '''
С клавиатуры вводят число до 5 цифрой.
Вывести в консоль его текстовое представление,
например, ввод - 3, вывод - три.
'''
number = int(input('Введите число\n'))
if number == 1:
print('один')
elif number == 2:
print('Два')
elif number == 3:
print('Три')
elif number == 4:
print('Четыре')
elif number == 5:
print('Пять')
else:
print('Хуета') | false |
fd866513665af61f9a8ae0941015b79755f19998 | leiteg/project-euler | /python/p004.py | 780 | 4.15625 | 4 | #!/usr/bin/env python3
""" Project Euler - Problem 004
A palindromic number reads the same both ways. The largest palindrome made from
the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
"""
def is_palindrome(s):
return s == s[::-1]
def largest_palindrome(digits):
assert digits >= 1
low = 10**(digits - 1)
high = 10**(digits)
largest = 0
for x in reversed(range(low, high)):
for y in reversed(range(low, high)):
s = str(x * y)
if is_palindrome(s) and x * y > largest:
largest = x * y
return largest
def compute_answer():
return largest_palindrome(digits=3)
if __name__ == '__main__':
print(compute_answer())
| true |
1bed69f277174897f350cf2499c79fc3e423ed92 | ihsanbugrabugdayci/2018Hydroinformatics | /src/temperature_converter.py | 279 | 4.3125 | 4 | # ----------------------------------------------
# Convert a temperature in Fahrenheit to Celsius
# ----------------------------------------------
Fahrenheit = 85.2
Celsius = (Fahrenheit - 32) * 5.0 / 9.0
print("Temperature:", Fahrenheit, "Fahrenheit = ", Celsius, " Celsius")
| false |
39bad1332b85982e4c75a586a7bce24a35aea675 | jinurajan/Datastructures | /educative.io/coding_patterns/tree_bfs/vertical_order_traversal.py | 954 | 4.25 | 4 | """
Find the vertical order traversal of a binary tree when the root of the binary tree is given. In other words, return the values of the nodes from top to bottom in each column, column by column from left to right. If there is more than one node in the same column and row, return the values from left to right.
"""
from collections import defaultdict, deque
# Tip: You may use some of the code templates provided
# in the support files
def vertical_order(root):
if not root:
return []
node_list = defaultdict(list)
min_level = 0
max_level = 0
q = [(root, 0)]
while q:
node, level = q.pop(0)
if node:
node_list[level].append(node.data)
min_level = min(min_level, level)
max_level = max(max_level, level)
q.append((node.left, level-1))
q.append((node.right, level+1))
return [node_list[x] for x in range(min_level, max_level+1)]
| true |
e9ae6f65d3667905777ccb21700b37cf25ec27b6 | jinurajan/Datastructures | /crack-the-coding-interview/stacks_and_queues/queue_using_ll.py | 1,408 | 4.15625 | 4 | """
Queue Using LinkedList
"""
class LinkedListNode(object):
def __init__(self, data):
self.data = data
self.next = None
def print_ll(head):
while head is not None:
print head.data,
head = head.next
if head is not None:
print "->",
class Queue(object):
def __init__(self):
self.head = None
self.tail = None
def add(self, data):
if self.head is None:
self.head = LinkedListNode(data)
self.tail = self.head
else:
new_node = LinkedListNode(data)
self.tail.next = new_node
self.tail = new_node
def remove(self):
if self.head is not None:
# not empty queue
val = self.head.data
self.head = self.head.next
return val
else:
raise Exception('Queue is Empty')
def peek(self):
if self.head is not None:
return self.head.data
else:
raise Exception('Queue is Empty')
def isEmpty(self):
return True if self.head is None else False
if __name__ == "__main__":
q = Queue()
q.add(1)
q.add(2)
q.add(3)
q.add(4)
print_ll(q.head)
print "\n"
print q.remove()
print q.peek()
print q.remove()
print q.isEmpty()
print q.remove()
print q.remove()
print q.isEmpty() | true |
b4c1978dceeb02f1e9f67909e5ca91c0b929cef9 | jinurajan/Datastructures | /educative.io/coding_patterns/two_pointers/triplet_sum_to_zero.py | 1,271 | 4.125 | 4 | """
Given an array of unsorted numbers, find all unique triplets in it that add up to zero.
Example 1:
Input: [-3, 0, 1, 2, -1, 1, -2]
Output: [-3, 1, 2], [-2, 0, 2], [-2, 1, 1], [-1, 0, 1]
Explanation: There are four unique triplets whose sum is equal to zero.
Example 2:
Input: [-5, 2, -1, -2, 3]
Output: [[-5, 2, 3], [-2, -1, 3]]
Explanation: There are two unique triplets whose sum is equal to zero.
"""
def search_triplets(arr):
triplets = []
arr.sort()
n = len(arr)
def two_sum(target, left, triplets):
right = len(arr) - 1
while left < right:
curr = arr[left] + arr[right]
if curr == target:
triplets.append([-target, arr[left], arr[right]])
left += 1
right -= 1
while left < right and arr[left] == arr[left - 1]:
left += 1
while right >= 0 and arr[right] == arr[right + 1]:
right -= 1
elif target > curr:
left += 1 # we need a pair with a bigger sum
else:
right -= 1
for i in range(n - 3):
if i > 0 and arr[i] == arr[i - 1]:
continue
two_sum(-arr[i], i + 1, triplets)
return triplets
| true |
a38d20260bb0b046d97b72ced859c74a56938e54 | jinurajan/Datastructures | /educative.io/coding_patterns/inplace_traversal_of_linked_list/swapping_nodes_in_a_linked_list.py | 1,945 | 4.125 | 4 | """
Given the linked list and an integer k return the head of the linked list after swapping the values of the kth node from the beginning and the
kth node from the end of the linked list.
"""
# Template for linked list node class
class LinkedListNode:
# __init__ will be used to make a LinkedListNode type object.
def __init__(self, data, next=None):
self.data = data
self.next = next
# Template for the linked list
class LinkedList:
# __init__ will be used to make a LinkedList type object.
def __init__(self):
self.head = None
# insert_node_at_head method will insert a LinkedListNode at
# head of a linked list.
def insert_node_at_head(self, node):
if self.head:
node.next = self.head
self.head = node
else:
self.head = node
# create_linked_list method will create the linked list using the
# given integer array with the help of InsertAthead method.
def create_linked_list(self, lst):
for x in reversed(lst):
new_node = LinkedListNode(x)
self.insert_node_at_head(new_node)
# __str__(self) method will display the elements of linked list.
def __str__(self):
result = ""
temp = self.head
while temp:
result += str(temp.data)
temp = temp.next
if temp:
result += ", "
result += ""
return result
def swap_nodes(head, k):
# find kth node
slow = head
fast = head
i = 1
while i < k:
fast = fast.next
i += 1
first_kth_node = fast
while fast.next:
prev = slow
slow = slow.next
fast = fast.next
# kth node from other side will be slow
last_kth_node = slow
temp = first_kth_node.data
first_kth_node.data = last_kth_node.data
last_kth_node.data = temp
return head
| true |
22e03ac4fc029539aca43beaf8859fe3c763f620 | jinurajan/Datastructures | /python_programs/regular_expression/begins_ends_vowel.py | 374 | 4.5625 | 5 | import re
def find_all_capital_words_ending_with_vowel(string):
# pattern = "\s?[A-Z]+[A-Za-z0-9_]*[aeiou]{1}\s?|$"
pattern = r"\b[A-Z]+[A-Za-z0-9_]*[aeiou]\b"
result = re.findall(pattern, string)
return result
if __name__ == "__main__":
print "Enter string:"
input_val = raw_input()
print find_all_capital_words_ending_with_vowel(input_val)
| false |
43b1c20fda1a6ca2fad3673a6d313ae264f90fd3 | jinurajan/Datastructures | /LeetCode/facebook/trees_and_graphs/flatten_binary_search_tree_to_linked_list.py | 1,772 | 4.34375 | 4 | """
Flatten Binary Tree to Linked List
Given the root of a binary tree, flatten the tree into a "linked list":
The "linked list" should use the same TreeNode class where the right child pointer points to the next node in the list and the left child pointer is always null.
The "linked list" should be in the same order as a pre-order traversal of the binary tree.
Input: root = [1,2,5,3,4,null,6]
Output: [1,null,2,null,3,null,4,null,5,null,6]
Input: root = []
Output: []
Input: root = [0]
Output: [0]
Constraints:
The number of nodes in the tree is in the range [0, 2000].
-100 <= Node.val <= 100
Follow up: Can you flatten the tree in-place (with O(1) extra space)?
"""
from collections import deque
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def flatten(self, root: TreeNode) -> None:
"""
Do not return anything, modify root in-place instead.
"""
def flatten_tree(node):
if not node or (not node.left and not node.right):
return node
left = flatten_tree(node.left)
right = flatten_tree(node.right)
if left:
left.right = node.right
node.right = node.left
node.left = None
return right if right else left
flatten_tree(root)
def print_l(node):
if not node:
return
print(node.val, end="->")
print_l(node.right)
t = TreeNode(1)
t.left = TreeNode(2)
t.left.left = TreeNode(3)
t.left.right = TreeNode(4)
t.right = TreeNode(5)
t.right.right = TreeNode(6)
import pdb;pdb.set_trace()
Solution().flatten(t)
print_l(t)
| true |
ee2926b518c386d9843227f05ffe5f78c9c69648 | jinurajan/Datastructures | /LeetCode/monthly_challenges/2021/april/7_determine_if_string_halves_are_alike.py | 1,723 | 4.25 | 4 | """
Determine if String Halves Are Alike
You are given a string s of even length. Split this string into two halves of equal lengths, and let a be the first half and b be the second half.
Two strings are alike if they have the same number of vowels ('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'). Notice that s contains uppercase and lowercase letters.
Return true if a and b are alike. Otherwise, return false.
Example 1:
Input: s = "book"
Output: true
Explanation: a = "bo" and b = "ok". a has 1 vowel and b has 1 vowel. Therefore, they are alike.
Example 2:
Input: s = "textbook"
Output: false
Explanation: a = "text" and b = "book". a has 1 vowel whereas b has 2. Therefore, they are not alike.
Notice that the vowel o is counted twice.
Example 3:
Input: s = "MerryChristmas"
Output: false
Example 4:
Input: s = "AbCdEfGh"
Output: true
Constraints:
2 <= s.length <= 1000
s.length is even.
s consists of uppercase and lowercase letters.
"""
class Solution:
def halvesAreAlike(self, s: str) -> bool:
if not s or len(s) == 1:
return False
n = len(s)
v_set = {'a', 'A', 'e', 'E', 'i', 'I', 'o', 'O', 'u', 'U'}
mid = n // 2
count_1 = sum([1 for char in s[:mid] if char in v_set])
count_2 = sum([1 for char in s[mid:] if char in v_set])
return count_1 == count_2
class Solution1:
def halvesAreAlike(self, s: str) -> bool:
def vowel_count(s):
count = 0
for char in s:
if char in set(['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']):
count += 1
return count
n = len(s)
return vowel_count(s[:n // 2]) == vowel_count(s[n // 2:])
| true |
1f70838159840bd5bd89575b64e9fa07d38b7c93 | jinurajan/Datastructures | /LeetCode/easy/longest_palindrome.py | 1,751 | 4.15625 | 4 | """
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example 1:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example 2:
Input: "cbbd"
Output: "bb"
"""
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
if len(s) == 0 or len(s) == 1:
return s
else:
j = 0
start = 0
end = len(s) - 1
while start < end:
if s[start] != s[end]:
end -= 1
if start == end:
start += 1
end = len(s) - 1
else:
if self.longestPalindromeUtil(s, start, end):
return s[start:end + 1]
else:
j += 1
start = j
end = len(s) - 1
return s[0]
def longestPalindromeUtil(self, s, start, end):
if start > end:
return True
if s[start] == s[end]:
return self.longestPalindromeUtil(s, start + 1, end - 1)
else:
return False
if __name__ == "__main__":
# print Solution().longestPalindromeUtil("a", 0, 0)
# print Solution().longestPalindromeUtil("ab", 0, 1)
# print Solution().longestPalindromeUtil("aba", 0, 2)
# print Solution().longestPalindromeUtil("ababa", 0, 4)
print Solution().longestPalindrome("babad")
print Solution().longestPalindrome("babab")
print Solution().longestPalindrome("cbbd")
print Solution().longestPalindrome("ac")
print Solution().longestPalindrome("babadada")
| true |
a09d48ad30becc55bde13b6095195b2d0151cc7a | jinurajan/Datastructures | /educative.io/coding_patterns/sliding_window/maximum_sum_subarray_of_length_k.py | 874 | 4.40625 | 4 | """
Given an array of positive numbers and a positive number ‘k,’ find the maximum sum of any contiguous subarray of size ‘k’.
Example 1:
Input: [2, 1, 5, 1, 3, 2], k=3
Output: 9
Explanation: Subarray with maximum sum is [5, 1, 3].
Example 2:
Input: [2, 3, 4, 1, 5], k=2
Output: 7
Explanation: Subarray with maximum sum is [3, 4].
"""
def max_sub_array_of_size_k(k, arr):
n = len(arr)
left = 0
right = 0
s = 0
max_sum_len = 0
while right < n:
s += arr[right]
if right - left + 1 == k:
max_sum_len = max(max_sum_len, s)
s -= arr[left]
left += 1
right += 1
return max_sum_len
print("Maximum sum of a subarray of size K: " + str(max_sub_array_of_size_k(3, [2, 1, 5, 1, 3, 2])))
print("Maximum sum of a subarray of size K: " + str(max_sub_array_of_size_k(2, [2, 3, 4, 1, 5]))) | true |
f988c27f78cdbc823ddcbfc6a3519f5ff27bb356 | jinurajan/Datastructures | /educative.io/coding_patterns/sliding_window/longest_substring_with_same_letters_after_replacement.py | 1,159 | 4.40625 | 4 | """
Given a string with lowercase letters only, if you are allowed to replace no more than ‘k’ letters with any letter, find the length of the longest substring having the same letters after replacement.
Example 1:
Input: String="aabccbb", k=2
Output: 5
Explanation: Replace the two 'c' with 'b' to have a longest repeating substring "bbbbb".
Example 2:
Input: String="abbcb", k=1
Output: 4
Explanation: Replace the 'c' with 'b' to have a longest repeating substring "bbbb".
Example 3:
Input: String="abccde", k=1
Output: 3
Explanation: Replace the 'b' or 'd' with 'c' to have the longest repeating substring "ccc".
"""
from collections import Counter
def length_of_longest_substring(str, k):
n = len(str)
left = 0
right = 0
max_repeating_count = 0
counter = Counter()
max_len = 0
while right < n:
counter[str[right]] += 1
max_repeating_count = max(max_repeating_count, counter[str[right]])
if right - left + 1 - max_repeating_count > k:
counter[str[left]] -= 1
if counter[str[left]] == 0:
del counter[str[left]]
left += 1
max_len = max(max_len, right-left+1)
right += 1
return max_len
| true |
43812cca0523f846ed580e36b208289facecbffa | jinurajan/Datastructures | /LeetCode/mock_interviews/amazon/shortest_path_with_alternating_colors.py | 2,196 | 4.21875 | 4 |
"""
Shortest Path with Alternating Colors
Consider a directed graph, with nodes labelled 0, 1, ..., n-1. In this graph, each edge is either red or blue, and there could be self-edges or parallel edges.
Each [i, j] in red_edges denotes a red directed edge from node i to node j. Similarly, each [i, j] in blue_edges denotes a blue directed edge from node i to node j.
Return an array answer of length n, where each answer[X] is the length of the shortest path from node 0 to node X such that the edge colors alternate along the path (or -1 if such a path doesn't exist).
Example 1:
Input: n = 3, red_edges = [[0,1],[1,2]], blue_edges = []
Output: [0,1,-1]
Example 2:
Input: n = 3, red_edges = [[0,1]], blue_edges = [[2,1]]
Output: [0,1,-1]
Example 3:
Input: n = 3, red_edges = [[1,0]], blue_edges = [[2,1]]
Output: [0,-1,-1]
Example 4:
Input: n = 3, red_edges = [[0,1]], blue_edges = [[1,2]]
Output: [0,1,2]
Example 5:
Input: n = 3, red_edges = [[0,1],[0,2]], blue_edges = [[1,0]]
Output: [0,1,1]
Constraints:
1 <= n <= 100
red_edges.length <= 400
blue_edges.length <= 400
red_edges[i].length == blue_edges[i].length == 2
0 <= red_edges[i][j], blue_edges[i][j] < n
"""
from typing import List
from collections import defaultdict
inf = float("inf")
class Solution:
def shortestAlternatingPaths(self, n: int, red_edges: List[List[int]], blue_edges: List[List[int]]) -> List[int]:
graph = defaultdict(list)
for u, v in red_edges:
graph[u].append((v, 0))
for u, v in blue_edges:
graph[u].append((v, 1))
dist = [[inf] * 2 for _ in range(n)]
q = [(0, -1)]
k = 0
while q:
new_q = []
for node, color in q:
if dist[node][color] > k:
dist[node][color] = k
for node2, color2 in graph.get(node, []):
if color2 != color:
new_q.append((node2, color2))
q = new_q
k += 1
return [x if x < inf else -1 for x in map(min, dist)]
n = 3
red_edges = [[0,1],[0,2]]
blue_edges = [[1,0]]
print(Solution().shortestAlternatingPaths(n, red_edges, blue_edges))
| true |
713d463e2d3bb90404642bf96f340a3b381766cc | jinurajan/Datastructures | /educative.io/coding_patterns/tree_bfs/right_view_of_a_binary_tree.py | 1,476 | 4.21875 | 4 | """
Right View of a Binary Tree (easy) #
Given a binary tree, return an array containing nodes in its right view. The right view of a binary tree is the set of nodes visible when the tree is seen from the right side.
"""
from __future__ import print_function
from collections import deque
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
def tree_right_view(root):
result = []
if not root:
return result
q = [root]
while q:
l = len(q)
level_nodes = []
for i in range(l):
node = q.pop(0)
level_nodes.append(node)
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
result.append(level_nodes[-1])
return result
def tree_right_view(root):
result = []
if not root:
return result
q = [root]
while q:
l = len(q)
for i in range(l):
node = q.pop(0)
if i == l-1:
result.append(node)
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
result.append(level_nodes[-1])
return result
def main():
root = TreeNode(12)
root.left = TreeNode(7)
root.right = TreeNode(1)
root.left.left = TreeNode(9)
root.right.left = TreeNode(10)
root.right.right = TreeNode(5)
root.left.left.left = TreeNode(3)
result = tree_right_view(root)
print("Tree right view: ")
for node in result:
print(str(node.val) + " ", end='')
main()
| true |
1f21f681b3d5b5f3c0c3e80dd165d3a759687f12 | jinurajan/Datastructures | /LeetCode/facebook_real/is_monotonic.py | 1,399 | 4.1875 | 4 | """
An array is monotonic if it is either monotone increasing or monotone decreasing.
An array A is monotone increasing if for all i <= j, A[i] <= A[j]. An array A is monotone decreasing if for all i <= j, A[i] >= A[j].
Return true if and only if the given array A is monotonic.
Input: [1,2,2,3]
Output: true
Example 2:
Input: [6,5,4,4]
Output: true
Example 3:
Input: [1,3,2]
Output: false
Example 4:
Input: [1,2,4,5]
Output: true
Example 5:
Input: [1,1,1]
Output: true
Note:
1 <= A.length <= 50000
-100000 <= A[i] <= 100000
"""
from typing import List
class Solution:
def isMonotonic(self, A: List[int]) -> bool:
if len(A) == 1:
return True
n = len(A)
decreasing = True
increasing = True
for i in range(n-1):
if A[i] > A[i+1]:
decreasing = False
if A[i] < A[i+1]:
increasing = False
return decreasing or increasing
nums = [2, 2, 2, 1, 4, 5]
print(Solution().isMonotonic(nums))
nums = [1, 2, 2, 3]
print(Solution().isMonotonic(nums))
nums = [9, 7, 5, 3]
print(Solution().isMonotonic(nums))
nums = [1, 6, 5, 4, 8, 3]
print(Solution().isMonotonic(nums))
nums = [2, 2, 2, 2]
print(Solution().isMonotonic(nums))
nums = [2]
print(Solution().isMonotonic(nums))
nums = [1, 2]
print(Solution().isMonotonic(nums))
nums = [9, 6]
print(Solution().isMonotonic(nums))
| true |
c8ca5363da8a6635c17cfea4211c4f2731cdeba4 | jinurajan/Datastructures | /crack-the-coding-interview/linked_lists/partition.py | 2,411 | 4.21875 | 4 | """
Partition: Write code to partition a linked list around a value x, such that
all nodes less than x come before all nodes greater than or equal to x.
If x is contained within the list the values of x only need to be a er the elements less than x (see below). The partition element x can appear anywhere in the "right partition"; it does not need to appear between the left and right partitions.
SOLUTION
EXAMPLE
Input: 3->5->8->5->10->2->1[partition=5] Output: 3->1->2->10->5->5->8
"""
def partition1(node, x):
firsthalf = head
secondhalf = head
while node is not None:
next = node.next
if node.data < x:
node.next = firsthalf
firsthalf = node
else:
secondhalf.next = node
secondhalf = node
node = next
secondhalf.next = None
return firsthalf
def partition2(node, x):
headstart = None
headend = None
tailstart = None
tailend = None
while node is not None:
next = node.next
node.next = None
if node.data < x:
if headstart is None:
headstart = node
headend = headstart
else:
headend.next = node
headend = node
else:
if tailstart is None:
tailstart = node
tailend = tailstart
else:
tailend.next = node
tailend = node
node = next
if headstart is None:
# handle if all values are greater than x
return tailstart
headend.next = tailstart
return headstart
class LinkedList(object):
def __init__(self, data):
self.data = data
self.next = None
def print_ll(head):
while head is not None:
print head.data,
head = head.next
if head is not None:
print "->",
if __name__ == "__main__":
head = LinkedList(3)
head.next = LinkedList(5)
head.next.next = LinkedList(8)
head.next.next.next = LinkedList(5)
head.next.next.next.next = LinkedList(10)
head.next.next.next.next.next = LinkedList(2)
head.next.next.next.next.next.next = LinkedList(1)
print_ll(head)
print "\n"
partitioned_ll = partition2(head, 5)
print_ll(partitioned_ll)
print "\n"
partitioned_ll = partition1(head, 5)
print_ll(partitioned_ll)
| true |
aaf84f544a7d98b664784b69cc6450eeeacfe613 | jinurajan/Datastructures | /LeetCode/hard/minimum_cost_to_merge_stones.py | 2,299 | 4.25 | 4 | """
Minimum Cost to Merge Stones
There are N piles of stones arranged in a row. The i-th pile has stones[i] stones.
A move consists of merging exactly K consecutive piles into one pile, and the cost of this move is equal to the total number of stones in these K piles.
Find the minimum cost to merge all piles of stones into one pile. If it is impossible, return -1.
Example 1:
Input: stones = [3,2,4,1], K = 2
Output: 20
Explanation:
We start with [3, 2, 4, 1].
We merge [3, 2] for a cost of 5, and we are left with [5, 4, 1].
We merge [4, 1] for a cost of 5, and we are left with [5, 5].
We merge [5, 5] for a cost of 10, and we are left with [10].
The total cost was 20, and this is the minimum possible.
Example 2:
Input: stones = [3,2,4,1], K = 3
Output: -1
Explanation: After any merge operation, there are 2 piles left, and we can't merge anymore. So the task is impossible.
Example 3:
Input: stones = [3,5,1,2,6], K = 3
Output: 25
Explanation:
We start with [3, 5, 1, 2, 6].
We merge [5, 1, 2] for a cost of 8, and we are left with [3, 8, 6].
We merge [3, 8, 6] for a cost of 17, and we are left with [17].
The total cost was 25, and this is the minimum possible.
Note:
1 <= stones.length <= 30
2 <= K <= 30
1 <= stones[i] <= 100
"""
class Solution:
def mergeStones(self, stones: List[int], K: int) -> int:
N = len(stones)
dp = [[[10 ** 9] * (K + 1) for i in range(N + 1)] for j in range(N + 1)]
for i in range(N + 1):
dp[i][i][1] = 0 # the initial value
for l in range(2, N + 1): # length of [i,j], range from 2 to N
for i in range(1, N + 2 - l): # i moves forward, but keep j=i+l-1<N+1
j = i + l - 1
summ = sum(stones[i - 1:j]) # the temporary summation of stones[i-1:j], add this value to dp[i][j][k]
for k in range(2, K + 1): # compute k from 2 to K, then fill k=1
temp_res = 10 ** 9
for div in range(i, j):
temp_res = min(temp_res, dp[i][div][1] + dp[div + 1][j][k - 1]) # divide the [i:j] into 2 parts
dp[i][j][k] = temp_res
dp[i][j][1] = summ + dp[i][j][k] # finally compute dp[i][j][1]
return dp[1][-1][1] if dp[1][-1][1] < 10 ** 9 else -1
| true |
71745228c6547faf36f1633990e9d2a63e1b286b | jinurajan/Datastructures | /LeetCode/booking/coloring_a_border.py | 2,072 | 4.15625 | 4 | """
Coloring A Border
You are given an m x n integer matrix grid, and three integers row, col, and color. Each value in the grid represents the color of the grid square at that location.
Two squares are called adjacent if they are next to each other in any of the 4 directions.
Two squares belong to the same connected component if they have the same color and they are adjacent.
The border of a connected component is all the squares in the connected component that are either adjacent to (at least) a square not in the component, or on the boundary of the grid (the first or last row or column).
You should color the border of the connected component that contains the square grid[row][col] with color.
Return the final grid.
"""
from typing import List
class Solution:
def colorBorder(self, grid: List[List[int]], row: int, col: int, color: int) -> List[List[int]]:
rows = len(grid)
cols = len(grid[0])
def cal(i, j, c):
if not (0<=i<rows and 0<=j<cols):
return 1
return grid[i][j] != c and grid[i][j] != -1
def dfs(i, j):
if not (0 <= i < rows and 0 <=j<cols):
return
visited.add((i,j))
c = grid[i][j]
for di, dj in [(-1, 0), (0, -1), (1, 0), (0, 1)]:
new_i = i + di
new_j = j + dj
if 0 <=new_i<rows and 0<=new_j<cols and grid[new_i][new_j] == c and (new_i, new_j) not in visited:
dfs(new_i, new_j)
if cal(i-1, j, c) or cal(i+1, j, c) or cal(i,j+1, c) or cal(i, j-1, c):
grid[i][j] = -1
visited = set()
dfs(row, col)
for i in range(rows):
for j in range(cols):
if grid[i][j] == -1:
grid[i][j] = color
return grid
grid = [[1,1],[1,2]]
row = 0
col = 0
color = 3
print(Solution().colorBorder(grid, row, col, color))
grid = [[1,2,2],[2,3,2]]
row = 0
col = 1
color = 3
print(Solution().colorBorder(grid, row, col, color)) | true |
7d6e25954b639522d420951b2d2f673022eb205b | jinurajan/Datastructures | /educative.io/dynamic_programming/palindromic_subsequence/edit_distance.py | 2,972 | 4.15625 | 4 | """
Given strings s1 and s2, we need to transform s1 into s2 by deleting, inserting, or replacing characters. Write a function to calculate the count of the minimum number of edit operations.
Example 1:
Input: s1 = "bat"
s2 = "but"
Output: 1
Explanation: We just need to replace 'a' with 'u' to transform s1 to s2.
Example 2:
Input: s1 = "abdca"
s2 = "cbda"
Output: 2
Explanation: We can replace first 'a' with 'c' and delete second 'c'.
Example 3:
Input: s1 = "passpot"
s2 = "ppsspqrt"
Output: 3
Explanation: Replace 'a' with 'p', 'o' with 'q', and insert 'r'.
"""
def find_min_operations(s1, s2):
return find_min_operations_recursive(s1, s2, 0, 0)
def find_min_operations_recursive(s1, s2, i1, i2):
n1, n2 = len(s1), len(s2)
if i1 == n1:
return n2-i2
if i2 == n2:
return n1 - i1
if s1[i1] == s2[i2]:
return find_min_operations_recursive(s1, s2, i1+1, i2+1)
c1 = 1 + find_min_operations_recursive(s1, s2, i1, i2+1)
c2 = 1 + find_min_operations_recursive(s1, s2, i1+1, i2)
c3 = 1 + find_min_operations_recursive(s1, s2, i1+1, i2+1)
return min(c1, c2, c3)
def find_min_operations_topdown(s1, s2):
n1, n2 = len(s1), len(s2)
dp = [[-1 for _ in range(n2+1)] for _ in range(n1+1)]
return find_min_operations_recursive_topdown(dp, s1, s2, 0, 0)
def find_min_operations_recursive_topdown(dp, s1, s2, i1, i2):
n1, n2 = len(s1), len(s2)
if i1 == n1:
return n2 - i2
if i2 == n2:
return n1 - i1
if dp[i1][i2] == -1 :
if s1[i1] == s2[i2]:
return find_min_operations_recursive_topdown(dp, s1, s2, i1 + 1, i2 + 1)
c1 = 1 + find_min_operations_recursive_topdown(dp, s1, s2, i1, i2 + 1)
c2 = 1 + find_min_operations_recursive_topdown(dp, s1, s2, i1 + 1, i2)
c3 = 1 + find_min_operations_recursive_topdown(dp, s1, s2, i1 + 1, i2 + 1)
dp[i1][i2] = min(c1, c2, c3)
return dp[i1][i2]
def find_min_operations_bottomup(s1, s2):
n1, n2 = len(s1), len(s2)
dp = [[-1 for _ in range(n2+1)] for _ in range(n1+1)]
for i in range(n1+1):
dp[i][0] = i
for j in range(n2+1):
dp[0][j] = j
for i in range(1, n1+1):
for j in range(1,n2+1):
if s1[i-1] == s2[j-1]:
dp[i][j] = dp[i-1][j-1]
else:
dp[i][j] = 1 + min(
dp[i][j-1],
dp[i-1][j],
dp[i-1][j-1]
)
return dp[n1][n2]
print(find_min_operations("bat", "but"))
print(find_min_operations("abdca", "cbda"))
print(find_min_operations("passpot", "ppsspqrt"))
print(find_min_operations_topdown("bat", "but"))
print(find_min_operations_topdown("abdca", "cbda"))
print(find_min_operations_topdown("passpot", "ppsspqrt"))
print(find_min_operations_bottomup("bat", "but"))
print(find_min_operations_bottomup("abdca", "cbda"))
print(find_min_operations_bottomup("passpot", "ppsspqrt"))
| true |
797cddae0ab1db6315e7544659044b414dfa930c | jinurajan/Datastructures | /LeetCode/bloomberg/most_recently_used_queue.py | 2,587 | 4.125 | 4 | """
Design Most Recently Used Queue
Design a queue-like data structure that moves the most recently used element to the end of the queue.
Implement the MRUQueue class:
MRUQueue(int n) constructs the MRUQueue with n elements: [1,2,3,...,n].
int fetch(int k) moves the kth element (1-indexed) to the end of the queue and returns it.
Input:
["MRUQueue", "fetch", "fetch", "fetch", "fetch"]
[[8], [3], [5], [2], [8]]
Output:
[null, 3, 6, 2, 2]
Explanation:
MRUQueue mRUQueue = new MRUQueue(8); // Initializes the queue to [1,2,3,4,5,6,7,8].
mRUQueue.fetch(3); // Moves the 3rd element (3) to the end of the queue to become [1,2,4,5,6,7,8,3] and returns it.
mRUQueue.fetch(5); // Moves the 5th element (6) to the end of the queue to become [1,2,4,5,7,8,3,6] and returns it.
mRUQueue.fetch(2); // Moves the 2nd element (2) to the end of the queue to become [1,4,5,7,8,3,6,2] and returns it.
mRUQueue.fetch(8); // The 8th element (2) is already at the end of the queue so just return it.
1 <= n <= 2000
1 <= k <= n
At most 2000 calls will be made to fetch.
"""
import math
import bisect
from sortedcontainers import SortedList
class MRUQueue:
def __init__(self, n: int):
self.data = list(range(1, n+1))
def fetch(self, k: int) -> int:
self.data.append(self.data.pop(k-1))
return self.data[-1]
class MRUQueue:
def __init__(self, n: int):
self.data = SortedList((i, i) for i in range(1, n+1))
def fetch(self, k: int) -> int:
_, x = self.data.pop(k-1)
i = self.data[-1][0] + 1 if self.data else 0
self.data.add((i, x))
return x
class MRUQueue:
def __init__(self, n: int):
self.n = n
self.sq_n = int(math.sqrt(n))
self.data = []
self.index = []
for i in range(1, n+1):
sq_i =(i-1) // self.sq_n
if sq_i == len(self.data):
self.data.append([])
self.index.append(i)
self.data[-1].append(i)
def fetch(self, k: int) -> int:
i = bisect.bisect_right(self.index, k) - 1
x = self.data[i].pop(k-self.index[i])
for sq_i in range(i+1, len(self.index)):
self.index[sq_i] -= 1
if len(self.data[-1]) >= self.sq_n:
self.data.append([])
self.index.append(self.n)
self.data[-1].append(x)
if not self.data[i]:
self.data.pop(i)
self.index.pop(i)
return x
# Your MRUQueue object will be instantiated and called as such:
# obj = MRUQueue(n)
# param_1 = obj.fetch(k) | true |
a9766afecd037c6e5b1e5289e0fe59573c49a098 | jinurajan/Datastructures | /LeetCode/medium/maximum_width_of_binary_tree.py | 2,888 | 4.125 | 4 | """
Maximum Width of Binary Tree
Given the root of a binary tree, return the maximum width of the given tree.
The maximum width of a tree is the maximum width among all levels.
The width of one level is defined as the length between the end-nodes (the leftmost and rightmost non-null nodes), where the null nodes between the end-nodes that would be present in a complete binary tree extending down to that level are also counted into the length calculation.
It is guaranteed that the answer will in the range of a 32-bit signed integer.
"""
from typing import Optional
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def widthOfBinaryTree(self, root: Optional[TreeNode]) -> int:
"""
do a bfs and count the width and update. also consider adding null
"""
if not root:
return 0
max_width = 0
q = [(root, 0)]
while q:
l = len(q)
_, level = q[0]
for i in range(l):
node, col_level = q.pop(0)
if node.left:
q.append((node.left, 2*col_level))
if node.right:
q.append((node.right, 2*col_level+1))
max_width = max(max_width, col_level-level+1)
return max_width
class Solution:
def widthOfBinaryTree(self, root: Optional[TreeNode]) -> int:
max_width = 0
first_col_index_map = {}
def dfs(node, depth, col_index):
nonlocal max_width
if not node:
return
if depth not in first_col_index_map:
first_col_index_map[depth] = col_index
max_width = max(max_width, col_index-first_col_index_map[depth]+1)
dfs(node.left, depth+1, 2*col_index)
dfs(node.right, depth+1, 2*col_index+1)
dfs(root, 0, 0)
return max_width
class Solution:
def widthOfBinaryTree(self, root: Optional[TreeNode]) -> int:
"""
do a bfs and count the width and update. also consider adding null
"""
if not root:
return 0
max_width = 0
q = [(root, 0)]
while q:
l = len(q)
_, level = q[0]
first, last = 0, 0
for i in range(l):
node, col_level = q.pop(0)
curr_id = col_level - level
if i == 0:
first = curr_id
if i == l-1:
last = curr_id
if node.left:
q.append((node.left, 2*col_level))
if node.right:
q.append((node.right, 2*col_level+1))
max_width = max(max_width, last-first+1)
return max_width | true |
46cc477c659ffe57cee36ccbc607d2e8258cef8d | jinurajan/Datastructures | /educative.io/coding_patterns/subsets/balanced_parantheses.py | 1,515 | 4.15625 | 4 | """
For a given number ‘N’, write a function to generate all combination of ‘N’ pairs of balanced parentheses.
Example 1:
Input: N=2
Output: (()), ()()
Example 2:
Input: N=3
Output: ((())), (()()), (())(), ()(()), ()()()
"""
def generate_valid_parentheses(num):
result = []
q = [("", 0, 0)]
while q:
s, open_count, close_count = q.pop(0)
if open_count == num and close_count == num:
result.append(s[:])
else:
if open_count < num:
q.append((s + "(", open_count + 1, close_count))
if open_count > close_count:
q.append((s + ")", open_count, close_count + 1))
return result
def generate_valid_parentheses(num):
result = []
parantheses_string = [0 for _ in range(2 * num)]
def dfs(open_count, close_count, index):
if open_count == num and close_count == num:
result.append("".join(parantheses_string))
return
if open_count < num:
parantheses_string[index] = "("
dfs(open_count + 1, close_count, index + 1)
if open_count > close_count:
parantheses_string[index] = ")"
dfs(open_count, close_count + 1, index + 1)
dfs(0, 0, 0)
return result
def main():
print("All combinations of balanced parentheses are: " +
str(generate_valid_parentheses(2)))
print("All combinations of balanced parentheses are: " +
str(generate_valid_parentheses(3)))
main()
| true |
2c2a8b17ba3b3553312db42573d646488cb6f544 | PMinThant/My-Python | /relational database.py | 616 | 4.15625 | 4 | import sqlite3
sql_create_table = """CREATE TABLE IF NOT EXISTS student_name(id INTERGER PRIMARY KEY, name TEXT NOT NULL, phone TEXT);"""
insert_data = """INSERT INTO student_name(name,phone) VALUES(?,?)"""
select_data = """SELECT * FROM student_name"""
con = sqlite3.connect('student.db')
c = con.cursor()
c.exercise(sq1_create_table)
insert = con.cursor()
insert.execute(insert_data,("PhyoeMinThant", "09965152645"))
insert.execute(insert_data,("MinThant", "09794428157"))
select = con.cursor()
all_data = select.execute(select_data)
show = all_data.fetchall()
for x in show:
print(x)
| false |
eb5cc9716b485208cc36121352c0cb4bdf82831a | Oxlotus/PyNumberGuess | /program.py | 1,359 | 4.21875 | 4 | ##
# Author: Alex Metz (alex.tar.gz@gmail.com)
##
# Import Section
from random import *
# Logic Section
def guessing_game(tooLow, tooHigh, guesses):
print("\nGuess a value between {} and {}: ".format(tooLow,tooHigh))
randomNumber = randint(tooLow, tooHigh)
for _ in range(guesses):
guess = int(input("Enter a number: "))
try:
if guess == randomNumber:
print('Your guess is correct! It took you {}/{} ({}%) guess(es) to get {}.'.format((_+1),guesses,"{0:.2f}".format((float(_+1)/int(guesses))*100),randomNumber))
return
elif guess < int(tooLow) or guess > int(tooHigh):
print('Your guess is out of bounds. Try again.')
elif guess < randomNumber:
print('Your guess is too low. Try again.')
elif guess > randomNumber:
print('Your guess is too high. Try again.')
except ValueError:
print("Your guess isn't a number.")
print("\nYou didn't guess correctly within the chosen {} round(s). You lose.".format(guesses,guesses=guesses))
print("Correct number: {}".format(randomNumber))
tooLow = int(input("What minimum value do you want? "))
tooHigh = int(input("What maximum value do you want? "))
guesses = int(input("How many attempts would you like? "))
guessing_game(tooLow, tooHigh, guesses)
| true |
f2702961b1c58b90e3e1f83187c6bbcaf7bc24a5 | LouisJBooth/Python | /Homework Week 4 Assignment 4.py | 2,143 | 4.28125 | 4 | print("Find the roots of quadratic equations!")
while True:
try:
a = float(input("Please enter a nonzero value for the quadratic coefficient (a): "))
if a != 0:
b = float(input("Please enter a value for the linear coefficient (b): "))
c = float(input("Please enter a value for the constant (c): "))
import math
dis = (b**2 - (4*a*c))
print()
if dis < 0:
print("No real roots found.")
elif dis == 0:
x1 = ((-b - (math.sqrt(dis)))/(2*a))
x2 = ((-b + (math.sqrt(dis)))/(2*a))
print("One real root found. The root is: %.2f" %x1)
else:
x1 = ((-b - (math.sqrt(dis)))/(2*a))
x2 = ((-b + (math.sqrt(dis)))/(2*a))
print("Two real roots found. The roots are: {:.2f} & {:.2f}".format(x1, x2))
break
else:
print("Input Error! Value must be a nonzero number.")
except ValueError:
print("Input Error! Values must be numbers.")
print()
print()
print("Calculate the average of seven test scores with letter grade!")
score_list = []
i = 0
while i < 7:
try:
score = float(input("Please enter a test score between 0 and 100: "))
if score >= 0 and score <= 100:
score_list.append(score)
i += 1
else:
print("Input Error! Please enter a nonnegative number between 0 and 100.")
except ValueError:
print("Input Error! Please enter a number between 0 and 100.")
score_list.sort()
score_list = score_list[1:]
avg_score = (sum(score_list) / len(score_list))
print()
print("After dropping the lowest test score:")
if avg_score >= 90:
print("Your average score of %.2f%% is an A." %avg_score)
elif avg_score >= 80:
print("Your average score of %.2f%% is a B." %avg_score)
elif avg_score >= 70:
print("Your average score of %.2f%% is a C." %avg_score)
elif avg_score >= 60:
print("Your average score of %.2f%% is a D." %avg_score)
else:
print("Your average score of %.2f%% is an F." %avg_score)
| true |
ac3b3b909dd824920013f1395b039e36fb25f05c | LouisJBooth/Python | /In Class Week 6-2 (Mortgage functions).py | 1,605 | 4.25 | 4 | def main():
print("Calculate monthly mortgage payment!")
print()
P, r, n, n_yrs, r_annual = getInput()
## calling the mortgage function
monthlyPlay = mnth_pay(P, r, n)
## calling the output function
output_Data(P, r_annual, monthlyPay, n_yrs)
def getInput():
P = float(input("Enter the principal of your mortgage: "))
while not (P > 0):
P = float(input("Enter the principal of your mortgage: "))
r_annual = float(input("Enter the annual interest rate, i.e., 4.25 for 4.25 percent: "))
while not (100 > r_annual > 0):
r_annual = float(input("Enter the annual interest rate, i.e., 4.25 for 4.25 percent: "))
n_yrs = float(input("Enter the duration of your mortgage in years: "))
while not (n_yrs > 0):
n_yrs = float(input("Enter the duration of your mortgage in years: "))
r = (r_annual / 12) / 100
n = (n_yrs * 12)
return P, r, n, n_yrs, r_annual
def mnth_pay(P, r, n):
"""
Input: P, the principal
r, monthly interest rate
n, duration of loan in months
Returns monthly mortgage payment
"""
M = P * ((r * (1 + r)**n) / ((1 + r)**n - 1))
return M
def output_Data(P,r, pay, n):
"""
Input: P, the principal
r, annual interest rate
pay, the monthly payment after calculation
n, duration of loan in years
"""
print()
print("With a principal of ${0:,.2f}; an annual interest rate of {1:g}%;".format(P, r))
print("and a duration of {:g} years: Your monthly payment is about: ${:,.2f}".format(n, pay))
main()
| false |
b046e0b101654000bf690535e8d0cb46068111e8 | tmcw/argonautica | /argonautica-py/argonautica/data.py | 792 | 4.1875 | 4 | class RandomSalt:
"""
``RandomSalt`` is a class representing salt that is updated with random values
before each hash
You can set the ``salt`` property of an instance of ``Argon2`` or ``Hasher`` to an
instance of ``RandomSalt`` in order to ensure that every time you call the ``hash`` method
a new random salt will be created for you and used.
To instantiate a ``RandomSalt`` you must provide it with a length that represents the
length of your desired random salt in bytes.
The default ``salt`` for both the ``Argon2`` class and the ``Hasher`` class is a
``RandomSalt`` with length ``32``.
"""
__slots__ = ['len']
def __init__(self, len: int = 32) -> None:
self.len = len
def __len__(self) -> int:
return self.len
| true |
62ba8fee780ea548271af839a3b3577c3d40b031 | AnthonyB955/PythonSample-Repo | /hungry2.py | 301 | 4.125 | 4 | hungry = input("Are you hungry?")
if hungry == "yes":
print ("Eat Ice Cream")
print ("Eat Pizza")
print ("Eat Burgers")
print ("Eat Fries")
else:
thirsty = input ("Are you thirsty?")
if thirsty == "yes":
print ("drink water")
print ("drink green tea")
| false |
af797a4264661a6cec731038831217d97785ebaf | tburright/C-Programming | /Python/Lab2E.py | 665 | 4.25 | 4 | """
Ghozt
Lab2E
Instructions:
Write a program that takes a string as user input then counts the number of words in that sentence.
Bonus: Add additional functionality, experiment with other string methods.
ex: Output number of characters, number of uppercase letters, etc...
"""
uppers = 0
lowers = 0
my_String = raw_input("Input a string: ")
for i in my_String:
if(i.islower()):
lowers = lowers + 1
elif(i.isupper()):
uppers = uppers + 1
print "\nTotal words: ", len(my_String.split())
print "Total letters: ", len(my_String.replace(" ", ""))
print "Total uppercase: ", uppers
print "Total lowercase: ", lowers | true |
505cac3c34a73f60160cf40f8b8f5753fcd6a399 | surekrishna/PythonBasics | /python3-basics/dictionary.py | 1,407 | 4.34375 | 4 | # Creating a dictionary
person_dictionary = {'name' : 'krish', 'gender' : 'Male', 'city' : 'Bangalore'}
print(person_dictionary)
print(person_dictionary['name'])
alphabets = {1 : 'a', 2 : 'b', 3 : 'c', 4 : 'd', 5 : 'e'}
# accessing with key
print(alphabets.get(1))
#accessing with key if key is not present display None
print(alphabets.get(27, 'None'))
print(alphabets.has_key(1))
print(alphabets.has_key(27))
print('----------------------------------------------------------------')
# Looping over dictionary
for k, v in person_dictionary.items():
print('Key :: %s ' % k)
print('Value :: %s ' % v)
print('=================')
print('----------------------------------------------------------------')
# Adding elements to dictionary
person1_dictionary = {}
person1_dictionary['name'] = 'king'
person1_dictionary['gender'] = 'Male'
person1_dictionary['city'] = 'Heaven'
print(person1_dictionary)
print('----------------------------------------------------------------')
# Combining two dictionaries
person2_dictionary = {'name' : 'queen'}
person22_dictionary = {'gender' : 'Female', 'city' : 'Heaven'}
person2_dictionary.update(person22_dictionary)
print(person2_dictionary)
print('----------------------------------------------------------------')
# Popping key/value pair from dictionary
person2_dictionary.pop('city', None)
print(person2_dictionary.pop('email', None))
print(person2_dictionary) | false |
750195ab68840d92b84cbfc561cb76f46d2da42b | surekrishna/PythonBasics | /python3-basics/for.py | 695 | 4.125 | 4 | # Printing letter by letter in string
for letter in 'krish':
print(letter)
print('-----------------------------------------------')
# Printing fruits array
fruits = ['apple','banana','orange']
for fruit in fruits:
chars = 0
for char in fruit:
chars += 1
print('Name of the Fruit %s and length is %s' % (fruit, chars))
print('-----------------------------------------------')
# Looping both with index and items
for index, fruit in enumerate(fruits):
print('Index %s and item %s ' % (index, fruit))
print('-----------------------------------------------')
#Nested for Loop
for i in range(1,2):
for j in range(1,11):
print('%d x %d = %d' % (i, j, i*j))
| true |
72d3de7dc49d3e36a6a8fe11d973e426397a0f8b | mmassom96/IEEE_Xtreme_5.0 | /problem_A.py | 1,501 | 4.3125 | 4 | import numpy
def pearson (x, y):
if (len(x) != len(y)):
# if the two data sets are not of equal length, then Pearson's Correlation Coefficient
# cannot be calculated so the function will end
print("Error: length of set X is not equal to length of set Y.")
return
setLen = len(x) # assigns the length of x and y to a variable
stdX = numpy.std(x) # calculates the standard deviation of the set X
stdY = numpy.std(y) # calculates the standard deviation of the set Y
avgX = numpy.mean(x) # calculates the mean of the set X
avgY = numpy.mean(y) # calculates the mean of the set X
sum = 0 # sum is a variable used to calculate the numberator of Pearson's Correlation Coefficient
for i in range(setLen):
sum = sum + ((x[i] - avgX) * (y[i] - avgY))
num = sum / setLen # num is the numerator of Pearson's Correlation Coefficient
den = stdX * stdY # den is the denominator of Pearson's Correlation Coefficient
return num / den
# for listX and listY, each value in the array listX makes a pair with the corresponding value
# in the array listY Example: listX[0] and listY[0] make (14, 2)
listX = [14, 16, 27, 42, 39, 50, 83] # listX is the set of X values
listY = [2, 5, 7, 9, 10, 13, 20] # listY is the set of Y values
print(pearson(listX, listY)) # executes the function pearson() using listX and listY and prints the result | true |
cf23428b50be73869028a2f4d89ddd5471222f2e | SaurabhAgarwal1243/Python-Learning | /exponent_function.py | 226 | 4.28125 | 4 | #basic exponent code
print(2**3)
#Exponent using functions
def raise_to_power(base_num, power):
result = 1
for index in range(power):
result = result * base_num
return result
print(raise_to_power(3, 4))
| true |
43c7590adbff028761473bc9264136c049f216e8 | Github-zs/python-study | /learn/04-function/function.py | 1,194 | 4.21875 | 4 | from random import randint
#定义一个求阶乘的函数(用到了递归)
def factorial(num):
"""求阶乘"""
result = 1
for n in range(1, num + 1):
result *= n
return result
#需要时调用函数求出给定参数的阶乘
print(factorial(5))
def roll_dice(n=2):#2为定义函数时的默认值,如果调用时没传参数则用这个默认值
"""摇色子"""
total = 0
for _ in range(n):
total += randint(1, 6)
return total
def add(a=0, b=0, c=0):
"""三个数相加"""
return a + b + c
# 如果没有指定参数那么使用默认值摇两颗色子
print(roll_dice())
# 摇三颗色子
print(roll_dice(3))
print(add())
print(add(1))
print(add(1, 2))
print(add(1, 2, 3))
# 传递参数时可以不按照设定的顺序进行传递,顺序与声明函数时不同时需要指明值赋给哪个参数
print(add(c=50, a=100, b=200))
# 在参数名前面的*表示args是一个可变参数
def add(*args):
total = 0
for val in args:
total += val
return total
# 在调用add函数时可以传入0个或多个参数
print(add())
print(add(1))
print(add(1, 2))
print(add(1, 2, 3))
print(add(1, 3, 5, 7, 9)) | false |
b9fc0738ed0df0366d76ffe67971844f84df7dab | JaswantKanna/Task---2 | /List of positive numbers in the Range.py | 818 | 4.1875 | 4 | # To print all positive numbers in the range
Input :
c = int(input ("Enter number of elements in the list\n "))
list = []
output = []
for p in range (1,c+1) :
element = int(input ("\nEnter the respective number " + str(p) + " of the list :\n"))
list.append(element)
print ("\nList is :\n" ,list)
for x in range (0,c) :
if list [x] >= 0 :
output.append(list [x])
else :
continue
print ("\nPositive numbers in the above List is :\n" ,output)
Output :
Enter number of elements in the list
4
Enter the respective number 1 of the list :
7
Enter the respective number 2 of the list :
6
Enter the respective number 3 of the list :
2
Enter the respective number 4 of the list :
1
List is :
[7, 6, 2, 1]
Positive numbers in the above List is :
[7, 6, 2, 1]
| true |
6efd536d2650f9604ce6ba94e7b2c20931cd310a | ageback/python_work | /string_demo.py | 1,339 | 4.1875 | 4 | # 大小写相关函数
name="ada lovelace"
print('# 大小写相关函数')
print(name.title())
print(name.upper())
print(name.lower())
print("\n")
# 在字符串中使用变量
# f字符串是 python 3.6引入的,3.5或更早版本需要使用format()方法
first_name="ada"
last_name="lovelace"
full_name=f"{first_name} {last_name}"
print('# 在字符串中使用变量')
print(full_name)
print(f"Hello, {full_name.title()}!")
# format
print("{} {}".format(first_name, last_name))
print("\n")
# 制表符和换行符
print('# 制表符和换行符')
print('Languages:\n\tPython\n\tC\n\tJavascript')
# 删除空白
print('# 删除空白')
fav_lang="python "
fav_lang=fav_lang.rstrip()
print(fav_lang)
# 练习 2-3
print('# 练习 2-3')
person_name="Eric"
print(f"Hello {person_name}, would you like to learn some Python today?")
#练习2-5
print('#练习2-5')
print('Albert Einstein once said, "A person who never made a mistake never tried anything new."')
#练习2-6
print('#练习2-6')
famous_person="Albert Einstein"
message=f'{famous_person} once said, "A person who never made a mistake never tried anything new."'
print(message)
#练习2-7
print('#练习2-7')
person_name="\n\t Michael Lu \t\n"
print(person_name)
print(person_name.lstrip())
print(person_name.rstrip())
print(person_name.strip()) | false |
c644cc9fe153cca508b74f01dbe981cbf60ce740 | neok5/python-notes | /05_dicts.py | 2,589 | 4.375 | 4 | my_dict = {"Germany": "Berlin", # declaration and definition; JSON / JS objects
"France": "Paris", "United Kingdom": "London"}
print(my_dict) # access all elements
print(my_dict["France"]) # access one element using it key
print()
print('-----------------------------------------------------------------')
# special way to access a dictionary
# using get(dict_key[, default_value = None])
print(my_dict.get("Germany"))
print(my_dict.get("German"))
print(my_dict.get("German", None))
print(my_dict.get("German", "Incorrect key!"))
print()
print('-----------------------------------------------------------------')
my_dict["Italy"] = "wegrgsds" # add a new element
print(my_dict)
my_dict["Italy"] = "Rome" # edit an existing element
print(my_dict)
del my_dict["United Kingdom"] # remove an element, not return anything
print(my_dict)
country_capital = my_dict.pop('Italy') # remove and return an element
print(f'Italy out! {country_capital}') # return only the value of deleted key
print(my_dict)
print()
mutivalued_type_dict = {"first": 1, 2.5555: "second"}
print(mutivalued_type_dict) # a dict can have several values as key or value
print()
print('-----------------------------------------------------------------')
my_tuple = ["Russia", "China", "Japan"]
reducted_dict = {
my_tuple[0]: "Moscow", my_tuple[1]: "Beijing", my_tuple[2]: "Kyoto"}
print(reducted_dict) # a tuple can be used as collection of keys for a dictionary
print(reducted_dict["Russia"]) # you can also use a tuple to access dict elements
print(reducted_dict[my_tuple[0]])
print()
print('-----------------------------------------------------------------')
dict_with_complex_types = { # a dict can contain lists, tuples or another dicts
23: "Jordan",
"name": "Michael",
"prizes": [1991, 1992, 1993, 1996, 1997, 1998],
"fortune": {
"cash": 50000,
"properties": 2000000
}
}
print("Complete\n", dict_with_complex_types)
print("Prizes\n", dict_with_complex_types["prizes"])
print("Fortune\n", dict_with_complex_types["fortune"])
print()
print('-----------------------------------------------------------------')
print(dict_with_complex_types.keys()) # show dictionary keys
print(dict_with_complex_types.values()) # show dictionary values
print(dict_with_complex_types.items()) # show dictionary entries
print(len(dict_with_complex_types)) # show dictionary size
print()
for key, value in dict_with_complex_types.items():
print(f'{key} -> {value}')
print()
for key in dict_with_complex_types:
print(f'{key} -> {dict_with_complex_types[key]}')
| true |
36aedc9c8a756ef9a5d965c37af3b481bf10346f | niranjan-nagaraju/Development | /python/hackerrank/algorithms/strings/pangrams.py | 1,255 | 4.15625 | 4 | '''
https://www.hackerrank.com/challenges/pangrams
Roy wanted to increase his typing speed for programming contests. So, his friend advised him to type the sentence "The quick brown fox jumps over the lazy dog" repeatedly, because it is a pangram. (Pangrams are sentences constructed by using every letter of the alphabet at least once.)
After typing the sentence several times, Roy became bored with it. So he started to look for other pangrams.
Given a sentence s, tell Roy if it is a pangram or not.
Input Format
Input consists of a string s.
Constraints
Length of can be at most 10**3 and it may contain spaces, lower case and upper case letters. Lower-case and upper-case instances of a letter are considered the same.
Output Format
Output a line containing pangram if s is a pangram, otherwise output not pangram.
Sample Input
Input #1
We promptly judged antique ivory buckles for the next prize
Input #2
We promptly judged antique ivory buckles for the prize
Sample Output
Output #1
pangram
Output #2
not pangram
'''
s = raw_input().strip()
char_counts = [0] *26
for c in s:
if (c.isalpha()):
char_counts[ord(c.lower()) - ord('a')] += 1
for c in char_counts:
if c == 0:
print 'not pangram'
exit(0)
print 'pangram'
| true |
0d5249ca29b9b4b13585d2d3186becf2793295d4 | niranjan-nagaraju/Development | /python/interviewbit/trees/right_view_of_binary_tree/right_view_of_binary_tree.py | 2,912 | 4.1875 | 4 | '''
https://www.interviewbit.com/problems/right-view-of-binary-tree/
Right view of Binary tree
Problem Description
Given a binary tree A of integers. Return an array of integers representing the right view of the Binary tree.
Right view of a Binary Tree: is a set of nodes visible when the tree is visited from Right side.
Problem Constraints
1 <= Number of nodes in binary tree <= 10^5
0 <= node values <= 10^9
Input Format
First and only argument is an pointer to the root of binary tree A.
Output Format
Return an integer array denoting the right view of the binary tree A.
Example Input
Input 1:
1
/ \
2 3
/ \ / \
4 5 6 7
/
8
Input 2:
1
/ \
2 3
\
4
\
5
Example Output
Output 1:
[1, 3, 7, 8]
Output 2:
[1, 3, 4, 5]
'''
'''
Solution Outline:
1. Store `levels_done_so_far`
2. Start a R-L level-order traversal using a queue(node, level).
Upon dequeue,
2.1 print node if level > `levels_done_so_far`
2.2 update levels_done_so_far.
'''
# Definition for a binary tree node
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def right_view_btree(self, root):
if not root:
return []
queue = [(root, 0)]
right_view = []
levels_done = -1
while queue:
node, level = queue.pop(0)
if level > levels_done:
# NOTE: this can be
# levels_done += 1
# but is (somewhat counter-intuitively) slower.
# x = x+1
# LOAD x
# INC
# STOR x
# vs
# x = y
# LOAD y
# STOR x
levels_done = level
right_view.append(node.val)
# Enqueue right and left children of `node`
queue.append( (node.right, level+1) ) if node.right else None
queue.append( (node.left, level+1) ) if node.left else None
return right_view
if __name__ == '__main__':
s = Solution()
'''
1
/ \
2 3
\ /
5 6
'''
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.right = TreeNode(5)
root.right.left = TreeNode(6)
assert s.right_view_btree(root) == [1,3,6]
'''
1
\
2
/
3
'''
root = TreeNode(1)
root.right = TreeNode(2)
root.right.left = TreeNode(3)
assert s.right_view_btree(root) == [1,2,3]
'''
1
/ \
2 3
/ \ / \
4 5 6 7
/
8
'''
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
root.right.left = TreeNode(6)
root.right.right = TreeNode(7)
root.left.left.left = TreeNode(8)
assert s.right_view_btree(root) == [1,3,7,8]
'''
1
/ \
2 3
\
4
\
5
'''
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.right = TreeNode(4)
root.left.right.right = TreeNode(5)
assert s.right_view_btree(root) == [1,3,4,5]
| true |
3d382fa0d67eb20872e29b51cbc8570f86cb5694 | niranjan-nagaraju/Development | /python/interviewbit/two_pointers/merge_two_sorted_lists_ii/merge_two_sorted_lists_ii.py | 1,851 | 4.25 | 4 | '''
https://www.interviewbit.com/problems/merge-two-sorted-lists-ii/
Merge Two Sorted Lists II
Given two sorted integer arrays A and B, merge B into A as one sorted array.
Note: You have to modify the array A to contain the merge of A and B. Do not output anything in your code.
TIP: C users, please malloc the result into a new array and return the result.
If the number of elements initialized in A and B are m and n respectively, the resulting size of array A after your code is executed should be m + n
Example :
Input :
A : [1 5 8]
B : [6 9]
Modified A : [1 5 6 8 9]
'''
'''
Solution Outline:
1. Use the merge algorithm to merge the two arrays into an auxiliary array C
2. Since A needs to contain the merged result, copy C into A
NOTE: Modifying A in-place to insert/place B's elements into A might result in quadratic time-efficiency.
'''
class Solution:
# Merge B into A keeping A sorted
def merge_two_sorted_lists(self, A, B):
def merge(A, B):
C = [0]*(len(A)+len(B))
k = 0
iA = iB = 0
while iA < len(A) and iB < len(B):
if A[iA] <= B[iB]:
C[k] = A[iA]
iA += 1
else:
C[k] = B[iB]
iB += 1
k += 1
# We still might have elements remaining in A
# if there are, all of them are > B
while iA < len(A):
C[k] = A[iA]
iA += 1
k += 1
# We still might have elements remaining in B
# if there are, all of them are > A
while iB < len(B):
C[k] = B[iB]
iB += 1
k += 1
return C
C = merge(A, B)
# Copy C into A until A's current length is filled
# then start appending to the end
for i in xrange(len(A)):
A[i] = C[i]
i += 1
while i < len(C):
A.append(C[i])
i += 1
return A
if __name__ == '__main__':
s = Solution()
A = [1,5,8]
B = [6,9]
s.merge_two_sorted_lists(A, B)
assert A == [1,5,6,8,9]
| true |
689d46bf6b0d5c14e53ef7a7e1bbafdb14de759e | niranjan-nagaraju/Development | /python/hackerrank/algorithms/strings/palindrome_index-1.py | 1,067 | 4.28125 | 4 | '''
https://www.hackerrank.com/challenges/palindrome-index
Given a string, S, of lowercase letters, determine the index of the character whose removal will make S a palindrome. If S is already a palindrome or no such character exists, then print -1. There will always be a valid solution, and any correct answer is acceptable. For example, if S="bcbc", we can either remove 'b' at index 0 or 'c' at index 3.
Output Format
Print an integer denoting the zero-indexed position of the character that makes S not a palindrome; if S is already a palindrome or no such character exists, print -1.
Sample Input
3
aaab
baa
aaa
Sample Output
3
0
-1
'''
def is_palindrome(s, n):
i = 0
j = n-1
while i < j:
if (s[i] != s[j]):
return False
i += 1
j -= 1
return True
# remove 1 char at a time from S and check if its a palindrome
def remove_char_and_test(s, n):
for i in xrange(n):
if is_palindrome(s[:i] + s[i+1:], n-1):
return i
return -1
t = int(raw_input())
for i in xrange(t):
s = raw_input().strip()
print remove_char_and_test(s, len(s))
| true |
f09e80e6e06b77872617093258701a6cf2b96683 | niranjan-nagaraju/Development | /python/interviewbit/backtracking/letter_phone/letter_phone.py | 2,790 | 4.1875 | 4 | '''
https://www.interviewbit.com/problems/letter-phone/
Letter Phone
Given a digit string, return all possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the telephone buttons) is given below.
1 2{abc} 3{def}
4{ghi} 5{jkl} 6{mno}
7{pqrs} 8{tuv} 9{wxyz}
*+ 0_ #
The digit 0 maps to 0 itself.
The digit 1 maps to 1 itself.
Input: Digit string "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
Make sure the returned strings are lexicographically sorted.
'''
'''
Solution Outline:
Let f(c): return all letter combinations for digit c.
Consider a single digit "3"
All possible letters for "3" are ["d", "e", "f"]
=> f("3") = ["d", "e", "f"]
Now if we prepend another digit to "3", say "23"
All letters '2' maps to are {abc}
so all letter combinations for "23" are ["a" + f("3"), "b" + f("3"), "c" + f("3")]
=> f("23") = ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]
If we add another number, say "5", => "523"
f("5") = ["j", "k", "l"]
f("523") = ["j" + f("23"), "k" + f("23"), "l" + f("23")]
= [
"jad", "jae", "jaf", "jbd", "jbe", "jbf", "jcd", "jce", "jcf"]
"kad", "kae", "kaf", "kbd", "kbe", "kbf", "kcd", "kce", "kcf"]
"lad", "lae", "laf", "lbd", "lbe", "lbf", "lcd", "lce", "lcf"]
]
=> f(ni..n1) = foreach (f(ni) + f(ni-1..n1)
'''
class Solution:
def find_letter_combinations(self, digits):
# Helper function to recursively do a DFS of digits at each depth
def find_letter_combinations_r(depth, prefix=''):
if depth == len(digits):
letter_combinations.append(prefix)
return
map(lambda x: find_letter_combinations_r(depth+1, prefix+x), mapping[digits[depth]])
if not digits:
return []
mapping = {
'0': '0',
'1': '1',
'2': 'abc',
'3': 'def',
'4': 'ghi',
'5': 'jkl',
'6': 'mno',
'7': 'pqrs',
'8': 'tuv',
'9': 'wxyz',
}
letter_combinations = []
find_letter_combinations_r(0)
return letter_combinations
if __name__ == '__main__':
s = Solution()
assert s.find_letter_combinations("1") == ['1']
assert s.find_letter_combinations("12") == ['1a', '1b', '1c']
assert s.find_letter_combinations("23") == ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]
assert s.find_letter_combinations("73") == ['pd', 'pe', 'pf', 'qd', 'qe', 'qf', 'rd', 're', 'rf', 'sd', 'se', 'sf']
| true |
2bf4fdf8b5e8367a2e26c0eac218a2baa475a736 | niranjan-nagaraju/Development | /python/interviewbit/trees/populate_next_right_pointers/populate_next_right_pointers.py | 2,879 | 4.3125 | 4 | '''
https://www.interviewbit.com/problems/populate-next-right-pointers-tree/
Populate Next Right Pointers Tree
Given a binary tree
struct TreeLinkNode {
TreeLinkNode *left;
TreeLinkNode *right;
TreeLinkNode *next;
}
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.
Initially, all next pointers are set to NULL.
Note:
You may only use constant extra space.
Example :
Given the following binary tree,
1
/ \
2 3
/ \ / \
4 5 6 7
After calling your function, the tree should look like:
1 -> NULL
/ \
2 -> 3 -> NULL
/ \ / \
4->5->6->7 -> NULL
Note 1: that using recursion has memory overhead and does not qualify for constant space.
Note 2: The tree need not be a perfect binary tree.
'''
'''
Solution Outline:
1. Use two linked-lists(with head and tail references), one for the current level and the other for the next level
2. Use the current level linked list to traverse level-order, while linking the next-level nodes.
At the end of the current level, advance current level to next level, and start over building the next-level links
'''
# Definition for a binary tree node
class TreeLinkNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
self.next = None
def toList(self):
l = []
tmp = self
while tmp:
l.append(tmp.val)
tmp = tmp.next
return l
class LinkedList:
def __init__(self, head=None, tail=None):
self.head = head
self.tail = tail
# Append node to the end of the current linked list
def append(self, node):
if not self.head:
self.head = self.tail = node
return
self.tail.next = node
self.tail = node
# Reset current list to empty list
def reset(self):
self.head = self.tail = None
class Solution:
# @param root, a tree node
# @return nothing
def populate_next_right_pointers(self, root):
if not root:
return
current_level = LinkedList(root, root)
next_level = LinkedList()
tmp = root
while tmp:
next_level.append(tmp.left) if tmp.left else None
next_level.append(tmp.right) if tmp.right else None
tmp = tmp.next
if not tmp:
# Done with current level
# Advance current level to next level
current_level.head = next_level.head
current_level.tail = next_level.tail
next_level.reset()
tmp = current_level.head
if __name__ == '__main__':
s = Solution()
root = TreeLinkNode(1)
root.left = TreeLinkNode(2)
root.right = TreeLinkNode(3)
root.left.left = TreeLinkNode(4)
root.left.right = TreeLinkNode(5)
root.right.left = TreeLinkNode(6)
root.right.right = TreeLinkNode(7)
s.populate_next_right_pointers(root)
assert root.toList() == [1]
assert root.left.toList() == [2,3]
assert root.left.left.toList() == [4,5,6,7]
| true |
7c6d8cf5980fb38e63b440a0fed1581d4532da9b | niranjan-nagaraju/Development | /python/algorithms/math/pascals_triangle/pascals_triangle.py | 521 | 4.15625 | 4 | '''
Print a pascal triangle on length k
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
....
input:
4
Output:
1
1 1
1 2 1
1 3 3 1
'''
def next_row(pascal):
row = []
i = 0
for i in range(len(pascal)-1):
row.append(pascal[i] + pascal[i+1])
return [1] + row + [1]
def print_list(lst):
for x in lst:
print x,
print
# print a pascal's triangle of length 'n' (n rows)
def pascals_triangle(n):
row = [1]
for i in range(n):
print_list(row)
row = next_row(row)
if __name__ == '__main__':
pascals_triangle(5)
| false |
30f4fb7e764dc09302c3dbb51ac2a64374e404db | niranjan-nagaraju/Development | /python/algorithms/sorts/insertion_sort.py | 1,002 | 4.21875 | 4 | '''
Insertion sort:
At any given point, i, all items to the left are sorted.
Insert a[i] in the right place, so now a[0..i] are all sorted.
e.g.
A: 2 4 5, 3 . .
i: 3, A[i] = 3
j = 2, 3 < 5, Copy 5 to A[3], A: 2 4 5 5
j = 1, 3 < 4, Copy 4 to A[2], A: 2 4 4 5
j = 0, 3 < 2? NO, A[1] = 3, A: 2 3 4 5
'''
def insertion_sort(a):
n = len(a)
for i in xrange(1, n):
current = a[i]
j = i - 1
while j >= 0 and current < a[j]:
a[j+1] = a[j]
j -= 1
a[j+1] = current
return a
if __name__ == '__main__':
a = [5,2,6,4,1,3]
assert insertion_sort(a) == a == range(1,7)
assert insertion_sort(range(5, 0, -1)) == range(1, 6)
assert insertion_sort(range(1, 6)) == range(1, 6)
assert (insertion_sort(
[5, 1, 7, 3, 4, 2, 8]) == [1, 2, 3, 4, 5, 7, 8])
assert (insertion_sort(
[11, 9, 7, 5, 3, 2, 1]) == [1, 2, 3, 5, 7, 9, 11])
assert (insertion_sort(
[1, 2, 3, 4, 5, 6, 7]) == [1, 2, 3, 4, 5, 6, 7])
assert (insertion_sort(
[1, 3, 5, 7, 2, 4, 6]) == [1, 2, 3, 4, 5, 6, 7])
| false |
77f613afcb335e9b4e65550d763c19e570b55010 | niranjan-nagaraju/Development | /python/interviewbit/stacks_and_queues/balanced_parantheses/balanced_parantheses.py | 1,543 | 4.40625 | 4 | '''
https://www.interviewbit.com/problems/balanced-parantheses/
Balanced Parantheses!
Problem Description
Given a string A consisting only of '(' and ')'.
You need to find whether parantheses in A is balanced or not ,if it is balanced then return 1 else return 0.
Problem Constraints
1 <= |A| <= 105
Input Format
First argument is an string A.
Output Format
Return 1 if parantheses in string are balanced else return 0.
Example Input
Input 1:
A = "(()())"
Input 2:
A = "(()"
Example Output
Output 1:
1
Output 2:
0
Example Explanation
Explanation 1:
Given string is balanced so we return 1
Explanation 2:
Given string is not balanced so we return 0
'''
'''
Solution Outline:
0. Use a stack
1. For each x in A
1.1 If x is '(' -> push onto the stack
1.2 otherwise, x is ')' -> pop a matching '(' off the stack
If pop() fails due to stack-underflow, => unbalanced; return 0
2. At the end of the pass, if the stack isn't empty => there was a surplus of '('
=> unbalanced, return 0
2.1 If the stack is empty at the end of the pass, parantheses are balanced -> return 1
'''
class Solution:
# @param A : string
# @return an integer
def solve(self, A):
stack = []
for x in A:
try:
if x == '(':
stack.append(x)
else:
stack.pop()
except IndexError:
return 0
if stack:
return 0
return 1
if __name__ == '__main__':
s = Solution()
assert s.solve('(())') == 1
assert s.solve('())') == 0
assert s.solve('(()') == 0
assert s.solve('())(') == 0
assert s.solve('(()())') == 1
| true |
d329bdfc17004b1fdbd632dd94a4cb697ebee8f9 | niranjan-nagaraju/Development | /python/interviewbit/binary_search/matrix_search/matrix_search.py | 2,244 | 4.1875 | 4 | '''
https://www.interviewbit.com/problems/matrix-search/
Matrix Search
Given a matrix of integers A of size N x M and an integer B.
Write an efficient algorithm that searches for integar B in matrix A.
This matrix A has the following properties:
Integers in each row are sorted from left to right.
The first integer of each row is greater than or equal to the last integer of the previous row.
Return 1 if B is present in A, else return 0.
Note: Rows are numbered from top to bottom and columns are numbered from left to right.
Input Format
The first argument given is the integer matrix A.
The second argument given is the integer B.
Output Format
Return 1 if B is present in A, else return 0.
Constraints
1 <= N, M <= 1000
1 <= A[i][j], B <= 10^6
For Example
Input 1:
A =
[ [1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50] ]
B = 3
Output 1:
1
Input 2:
A = [ [5, 17, 100, 111]
[119, 120, 127, 131] ]
B = 3
Output 2:
0
'''
'''
Solution Outline:
1. Regular binary search works by eliminating half the array at each iteration.
2. Start with x == (top-row, right-column), so that all elements to the left are decreasing, all elements below are increasing
Check if x == key, return true
If x < key, skip entire row
if x > key: skip entire column
'''
class Solution:
def matrix_search(self, A, B):
if not A or not A[0]:
return 0
n = len(A)
m = len(A[0])
i, j = 0, m-1
while i<n and j>=0:
x = A[i][j]
if x == B:
return 1
if x < B:
# Entire row 'i' can be skipped
# A[i][j] is the highest in its row, i
i += 1
else:
# x > B => entire column 'j' can be skipped
# A[i][j] is the lowest in its column, j
j -= 1
# Couldn't locate key 'B' in A
return 0
if __name__ == '__main__':
s = Solution()
assert s.matrix_search(B=3, A = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50] ]) == 1
assert s.matrix_search(B=23, A = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50] ]) == 1
assert s.matrix_search(B=21, A = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50] ]) == 0
assert s.matrix_search(B=3, A =[
[5, 17, 100, 111],
[119, 120, 127, 131] ]) == 0
| true |
0efa715dea82df0eb5e8de003f7fb7ab8bb3e919 | 34527/Records | /Revision 3 - code.py | 874 | 4.21875 | 4 | #Euan McElhoney
#27/01/2015
#Records - Revision exercise 3
class payrecord:
def __init__(self):
self.employee_name = None
self.employee_number = None
self.hours_worked = None
self.pay_rate = None
record = payrecord()
record.employee_name = input("Please enter employee's full name: ")
record.employee_number = input("Please enter employee number: ")
record.hours_worked = float(input("Please enter the hours worked: "))
record.pay_rate = float(input("Please enter employee's rate of pay: "))
total_pay = record.hours_worked * record.pay_rate
print("Pay slip ")
print("Name: {0}".format(record.employee_name))
print("Employee Number: {0}".format(record.employee_number))
print("Hours Worked: {0:.2s.f}".format(record.hours_worked,1))
print("Rate of Pay: £{0}".format(record.pay_rate))
print(total_pay)
| true |
91b07e09bceba98bc6dd3864acc57fe2ca879d10 | mm909/CTCI | /python/1.4.py | 677 | 4.3125 | 4 | # Palindrome Permutation: Given a string, write a function to check if it is a permutation of
# a palindrome. A palindrome is a word or phrase that is the same forwards and backwards, A
# permutation is a rearrangement of letters. The palindrome does not need to be limited to just
# dictionary words.
# EXAMPLE
# Input: Tac t Coa
# Output: True (permutations: "taco cat""atc o eta" etc.)
def palCheck(str):
str = str.lower().replace(' ', '')
hash = {}
for char in str:
if char in hash:
hash.pop(char)
else:
hash[char] = 1
return len(hash) == (len(str) & 1 == 1)
print(palCheck('tact coa'))
print(palCheck('10100101'))
| true |
f520afd062a2bb147ccd02f995e912521887e1c5 | karina-15/CS138_Python_Coursework | /hw/hw08/proj2/hw8project2.py | 1,909 | 4.375 | 4 | #! /usr/bin/python
#
# Homework No. 08
# Project No. 02
# File Name: hw8project2.py
# Programmer: Karina Elias
# Date: Oct 20, 2019
#
# Problem Statement: Programming Exercise #14 p.265
# Write a program that converts a color image to grayscale.
# The user supplies the name of a file containing a GIF or
# PPM image, and the program loads the image and displays
# the file. At the click of the mouse, the program converts
# the image to grayscale. The user is then prompted for a
# filename to store the grayscale image in.
#
#
# Overall Plan:
# 1. Print introduction
# 2. Prompt user for image filename
# 3. Display image
# 4. Convert the image to grayscale using p.265 pseudocode
# 5. Display grayscale image
# 6. Prompt user to enter new filename for grayscale image
#
#
# import the necessary python libraries
from graphics import *
def main():
# Print introduction
print("This program will convert a color image to grayscale.\n")
# ---INPUT--- #
imageFileName = input("Enter filename of image: ")
print("Opening image to view...")
img = Image(Point(0, 0), imageFileName)
img = Image(Point(img.getWidth()/2, img.getHeight()/2), imageFileName)
win = GraphWin("Image", img.getWidth(), img.getHeight())
img.draw(win)
# ---PROCESS--- #
print("Click on image to convert to grayscale")
win.getMouse()
for row in range(img.getWidth()):
for column in range(img.getHeight()):
r, g, b = img.getPixel(row, column)
brightness = int(round(0.229 * r + 0.587 * g + 0.114 * b))
img.setPixel(row, column, color_rgb(brightness, brightness, brightness))
win.update()
# ---OUTPUT--- #
saveFileName = input("Enter new filename to save grayscale image as: ")
img.save(saveFileName)
print("Click image window to exit program")
win.getMouse()
win.close()
main()
| true |
fac6d291a290a0340695f2d32f610ae2879b00cc | karina-15/CS138_Python_Coursework | /hw/hw02/proj01/hw2project1.py | 950 | 4.53125 | 5 | #! /usr/bin/python
# Homework No. 02
# Project No. 01
# File Name: hw2project1.py
# Programmer: Karina Elias
# Date: Aug. 31, 2019
#
# Problem Statement: Programming Exercise #1 p.53
# Print an introduction that tells the user what
# the program does. Modify the convert.py program (Section 2.2) to
# print an introduction.
#
# convert.py
# A program to convert Celsius temps to Fahrenheit
# by: Susan Computewell
#
#
# Overall Plan:
# 1. Print statement for introduction describing program
# 2. Copy convert.py
#
#
# import the necessary python libraries
# for this example none are needed
def main():
# Print introduction
print("\nThis program converts the temperature from Celsius\n"
"to Fahrenheit.")
# Program convert.py (Section 2.2 p.30)
celsius = eval(input("What is the Celsius temperature? "))
fahrenheit = 9 / 5 * celsius + 32
print("The temperature is", fahrenheit, "degrees Fahrenheit.")
main()
| true |
cb4e8bd53e77d1fb4602df02b4bb52dc7b664026 | karina-15/CS138_Python_Coursework | /hw/hw12/proj2/hw12project2.py | 2,651 | 4.28125 | 4 | #! /usr/bin/python
#
# Homework No. 12
# Project No. 02
# File Name: hw12project2.py
# Programmer: Karina Elias
# Date: Dec. 12, 2019
#
# Problem Statement: Programming Exercise #3 p.463
# A palindrome is a sentence that contains the same sequence
# of letters reading it either forwards or backwards. A classic
# example is: "Able was I, ere I saw Elba." Write a recursive
# function that detects whether a string is a palindrome.
# The basic idea is to check that the first and last letters
# of the string are the same letter; if they are, then the
# entire string is a palindrome if everything between those
# letters is a palindrome. There a couple of special cases
# to check for. If either the first or last character of
# the string is not a letter, you can check to see if the
# rest of the string is a palindrome with that character
# removed. Also, when you compare letters, make sure that
# you do it in a case-insensitive way.
#
# Use your function in a program that prompts a user for
# a phrase and then tells whether or not it is a palindrome.
# Here's another classic for testing:
# "A man, a plan, a canal, Panama!"
#
#
# Overall Plan:
# 1. Print introduction
# 2. Ask user for input text
# 3. Remove all non-alphabetic characters and make lowercase
# 4. Check if input text is palindrome using recursion
# remove the 1st and last character from string each
# each time it is checked. Base case is when 1 or 0
# characters are left in the string
# 5. Display if user input string is a palindrome or not
#
#
# import the necessary python libraries and classes
# for this program re is used to remove non-alphabetic chars
import re
# ---FUNCTIONS---
def printIntro():
print("\nThis program will check if a string is a palindrome.\n")
# make all lowercase and remove non-alphabetic characters
def cleanString(palindrome):
return re.sub("[^a-zA-Z]+", '', palindrome).lower()
def recursion(cleanString):
# base case
# exit recursion after last 2 char are compared
if len(cleanString) < 2:
return True
# 1st and last char in current string are the same
elif cleanString[0] == cleanString[-1]:
return recursion(cleanString[1:-1])
else:
return False
# ---MAIN---
def main():
printIntro()
# ---INPUT---
text = input("Enter text: ")
# ---OUTPUT---
# checks if user input is a palindrome using recursion
if recursion(cleanString(text)):
print("'{0}' is a palindrome".format(text))
else:
print("'{0}' is not a palindrome".format(text))
if __name__ == '__main__':
main()
| true |
25dd29b2376c4e9a1fcf0dfbe01b48243bb410c9 | karina-15/CS138_Python_Coursework | /hw/hw07/proj3/hw7project3.py | 1,318 | 4.25 | 4 | #! /usr/bin/py
#
# Homework No. 07
# Project No. 03
# File Name: hw7project3.py
# Programmer: Karina Elias
# Date: Oct 06, 2019
#
# Problem Statement: Programming Exercise #6 p.230
# This program will accept a speed limit and a clocked
# speed and will either print a fine for an illegal speed
# or a message indicating the speed was legal.
#
#
# Overall Plan:
# 1. Print introduction
# 2. Prompt user for speed limit and clocked speed
# 3. Calculate fine
# If speed is over limit, fine = $50 + ((speed-limit)*5)
# If speed is over 90mph, fine = fine + $200
# 4. If speed is legal print message
# 5. Display message and fine if applicable
#
#
# import the necessary python libraries
# for this program none are needed
def main():
# Print introduction
print("\nThis program will calculate the fine for a speeding ticket"
"\nor display a message if the speed is legal.\n")
# ---INPUT--- #
limit = eval(input("Enter speed limit: "))
speed = eval(input("Enter clocked speed: "))
print()
# ---PROCESS/OUTPUT--- #
if speed > limit:
print("Speed is illegal.")
fine = (speed - limit) * 5 + 50
if speed > 90:
fine += 200
print("Fine = ${0}".format(fine))
else:
print("Speed is legal.")
main()
| true |
b84b94e8f2b6ab8bb0848f0763ba7e8c2c5dbaf4 | melike-eryilmaz/pythonProgrammingLanguageForBeginners | /loops.py | 296 | 4.15625 | 4 | krediler=["İhtiyaç Kredisi","Maaşını Halkbank İle Alanlara Özel","Emeklilik Kredisi","Araba Kredisi"]
for i in krediler:
print(i)
for i in range(10):
print(i)
for i in range(len(krediler)):
print(krediler[i])
for i in range(3,10):
print(i)
for i in range(0,10,2):
print(i)
| false |
cca5fa5cf0b63dc353a063461f0009d2cbab1aa8 | tjhamad/CheckiO | /Brackets.py | 1,241 | 4.15625 | 4 | '''
Given an expression with numbers, brackets and operators. But in this task only brackets are important. Brackets
can be one of three types -- "{}" "()" "[]". Brackets are determine the scope or restricted some expression.
So each if was opened, then must be closed with the same type. The scopes of brackets must not intersected.
You should to make a decision correct an expression or not. Don't care about operators and operands.
Input: An expression with different of types brackets.
Output: A boolean. Correct an expression or not.
Example:
?
1
2
3
4
5
checkio("((5+3)*2+1)") == True
checkio("{[(3+1)+2]+}") == True
checkio("(3+{1-1)}") == False
checkio("[1+1]+(2*2)-{3/3}") == True
checkio("(({[(((1)-2)+3)-3]/3}-3)") == False
'''
def checkio(data):
brackets = {'}':'{', ')':'(', ']':'['}
stack = []
for c in data:
if c in brackets.values(): stack.append(c)
elif c not in brackets: pass
elif c in brackets and stack and brackets[c] == stack[-1]:
stack.pop()
else: return False
return not stack
print checkio("((5+3)*2+1)")
checkio("{[(3+1)+2]+}")
checkio("(3+{1-1)}")
checkio("[1+1]+(2*2)-{3/3}")
checkio("(({[(((1)-2)+3)-3]/3}-3)") | true |
59cbef897dd089cf5c9eb2e5dbcd9882e26e96c7 | z727354123/pyCharmTest | /2017/11_Nov/08/02-list 遍历操作.py | 772 | 4.21875 | 4 | # 根据 元素遍历
listA = range(1, 11)
listA = listA[::-1]
print(listA) # range(10, 0, -1)
for item in listA:
print(listA.index(item), end='=')
print(item, end=',')
# 0=10,1=9,2=8,3=7,4=6,5=5,6=4,7=3,8=2,9=1,
print()
listA = [1, 2, 1, 3]
for item in listA:
print(listA.index(item), end='=')
print(item, end=',')
# 0=1,1=2,0=1,3=3,
# 故 这样遍历, 获取 index 有缺陷
print()
# 修复
listA = [1, 2, 1, 3]
currentIndex = 0
for item in listA:
print(listA.index(item, currentIndex), end='=')
print(item, end=',')
currentIndex += 1
# 0=1,1=2,2=1,3=3,
print()
# 根据索引 遍历
listA = [1, 2, 1, 3]
for index in range(len(listA)):
item = listA[index]
print(index, end='=')
print(item, end=',')
# 0=1,1=2,2=1,3=3,
| false |
fe6881155a68eb7479e311ad06199b4b9bb2faf8 | VitorArthur/Pratica-Python | /ex033.py | 377 | 4.1875 | 4 | a = int(input('Número 1: '))
b = int(input('Número 2: '))
c = int(input('Número 3: '))
# Analizando o menor
menor = a
if b<a and b<c:
menor = b
if c<a and c<b:
menor = c
print('O menor valor digitado foi {}'.format(menor))
# Analizando o maior
maior = a
if b>a and b>c:
maior = b
if c>a and c>b:
maior = c
print('O maior valor digitado foi {}'.format(maior)) | false |
aecbdfd016735537b97d05e82f3457051b4afda5 | aruarora/DevOps | /PYTHON_FILES/DataTypes.py | 767 | 4.21875 | 4 |
# String's
str1 = "alpha"
str2 = 'beta'
str3 = '''gamma string'''
str4 = """delta string"""
# Numbers
num1 = 123
flt1 = 2.0
# List/ Collection of multi datatype, enclosed in square bracket.
first_list = [str1, "Devops", 47, num1, 1.5]
# Tuple/ Collection of multi datatype, enclosed in round bracket.
my_tuple = (str1, "Devops", 47, num1, 1.5)
# Dictionary/ Elements in the dictionary are always in pairs(Key:Value)
dict_1 = {"Name":"Imran", "Code":47, "Skills": "DevOps"}
print "Value of first_list is: ", first_list
print "Value of my_tuple is: ", my_tuple
print "Value of dict_1 is: ", dict_1
print "Variable type for first_list is: ", type(first_list)
print "Variable type for my_tuple is: ", type(my_tuple)
print "Variable dict_1 is: ", type(dict_1)
| true |
191e907bfb294cf8ee8612feee9fd3779efdf926 | ViartX/PyProject | /lesson5_2.py | 719 | 4.375 | 4 | # 2. Создать текстовый файл (не программно), сохранить в нем несколько строк,
# выполнить подсчет количества строк, количества слов в каждой строке.
# функция принимает строку и возвразает число слов в строке
def get_words_number_in_string(str):
str_list = str.split()
return len(str_list)
f_text = open("lesson5_2.txt", 'r')
str_num = 0
for line in f_text:
str_num += 1
print(f" слов в строке {str_num} : {get_words_number_in_string(line)}")
print(f"строк в файле : {str_num}")
f_text.close() | false |
d6a49fee04cb2218daa051da6f5321a64b427db4 | areshta/python-edu | /006-additional/lab-2/l06.py | 675 | 4.15625 | 4 | # Write a Python program which takes two digits m (row) and n (column) as
# arguments(given from command line) and generates a two dimensional
# array. The element value in the i-th row and j-th column of the array
# should be i*j.
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--m', help='m rows', default = 4)
parser.add_argument('--n', help='n columns', default = 5)
args = parser.parse_args()
def create_matrix (m, n):
return [[i*j for j in range(0,n)] for i in range(0,m)]
m = int(args.m)
n = int(args.n)
matrix = create_matrix(m,n)
for i in range(0, m):
for j in range(0, n):
print(matrix[i][j], end = " ")
print() | true |
84e17f7fa15ac7dfea8bbeaf919e1ed18aa86de7 | areshta/python-edu | /basic-training-examples/flow/for-nested.py | 271 | 4.3125 | 4 | #Python-3 "for/range" example
print("\n*** Multiplication table ***\n")
for i in range(1,11):
print("{:3}!".format(i),end="")
for j in range(1,11):
print("{:4}".format(i*j),end="")
if i==1:
print("\n{:#<44}".format(""),end="")
print("")
| false |
293a2e5feb3349dbfdc5f4e84a6cdfca240eb885 | areshta/python-edu | /006-additional/misc/slice.py | 994 | 4.5625 | 5 | l1 = ['abcd', 786, 2.23, 'john', 70.2]
print("l1:",l1)
print ("l1[0]: ",l1[0]) # Prints first element of the list -> abcd
print ("l1[-1]: ",l1[-1]) # Prints last element of the list -> 70.2
print ("l1[1:3]: ",l1[1:3]) # Prints elements starting from 2nd till 3rd -> [786, 2.23]
print ("l1[2:]: ",l1[2:]) # Prints elements starting from 3rd element -> [2.23, 'john', 70.2]
print ("l1[::-1]: ",l1[::-1]) # Reverses the list
#Example of slice assignment:
l1[0:2] = [1, 2] # Replace some items
print(l1) # Prints [1, 2, 2.23, 'john', 70.2]
l1[0:2] = [] # Remove some items
print(l1) # Prints [2.23, 'john', 70.2]
l1[1:1] = ['insert1', 'insert2'] # Insert some items
print(l1) # Prints [2.23, 'insert1', 'insert2', 'john', 70.2]
l1[:0] = l1 # Insert a copy of itself at the beginning
print(l1) # Prints [2.23, 'insert1', 'insert2', 'john', 70.2, 2.23, 'insert1', 'insert2', 'john', 70.2]
l1[:] = [] # Clear the list
print(l1) # Prints []
l2 = [1,2,3,4,5,6]
print(l2)
print("l2[0:6:1] :", l2[0:6:1]) | true |
a32d46d40c16abb3c3e451e60e20aeb38b8fea85 | areshta/python-edu | /basic-training-examples/str/comments_quates_statements.py | 613 | 4.34375 | 4 | # Python-3 Comment/Quotation/Statements example
str1 = \
"""This is
using several lines
example"""
print(
str1
) # statement can take one line or more
str2 = '\nWe can use "double" quotes inside \'single quotes\'' # \' will ouput as '
str3 = "\nand ' quotes inside other\n" # \n - next line symbol
print( str2 + \
str3) # back slash can contnue statement
print("We can ", end = '')
print("print some words by different prints ", end = '')
print("in the same line")
a = 5; b = a**2; c = b+3; print("Some statements in one line. c = ", c)
print(r"Raw string \n prints 'as is' \n escapes are ignored")
| true |
e8a4165f429040e509efc752d9f7dd9e3b3943fd | H1tman1978/GranthamUniversity | /Python/BMI Calculator/BMI_Calculator.py | 1,461 | 4.34375 | 4 | #!/usr/bin/python
#-*-coding: utf-8 -*-
#This program obtains date on height and weight from the user and then calculates the BMI based on that data.
#Methods
#This method obtains the name of the person from the user.
# NOTE: This method should be run before the getWeight and getHeight methods
def getName():
thisName = str(input('What is the Person\'s name or \'q\' to quit: '))
if thisName == 'q':
print('Goodbye!')
return thisName
def getWeight(): #This method obtains the weight from the user
thisWeight = float(input('What is their weight in pounds: '))
return thisWeight
def getHeight(): #This method obtains the height from the user
thisHeight = float(input("What is the their height in inches: "))
return thisHeight
def calcBMI(weight, height): #This method calculates the BMI
thisBMI = (weight*703)/(height*height)
return thisBMI
def displayBMI(name, weight, height, BMI):
print(name, '\'s BMI Profile:',)
print('------------------')
print('Height: ', height, ' inches')
print('Weight: ', weight, ' pounds')
print('BMI Index: ', format(BMI, '.2f'))
return
#Main Method
userName = str(getName())
while userName != 'q':
userWeight = getWeight()
userHeight = getHeight()
BMI = calcBMI(userWeight, userHeight)
displayBMI(userName, userWeight, userHeight, BMI)
userName = str(getName())
#End of Main Method
| true |
3f850a2c8bb936f8d7165fb63e37f331e8f1e99a | atamayo1/MasterInPython | /05-conditional/index.py | 1,190 | 4.1875 | 4 |
"""
Conditional IF
"""
print("> Condition IF")
# Ejemplo 1
print("########### EJEMPLO 1 ###############")
color = input("Adivina cual es mi color favorito: ")
if color == "rojo":
print("Genial")
print("Adivinaste, mi color es rojo")
else:
print("El color es incorrecto")
# Ejemplo 2
print("############ Ejemplo 2 ##############")
year = int(input("¿En que año estamos?: "))
if year < 2021:
print("El año es anterior al 2021")
else:
print("El año es posterior al 2021")
# Ejemplo 3
print("############ Ejemplo 3 ###############")
day = int(input("Introduce el numero del dia de la semana: "))
if day == 1:
print("Es lunes")
elif day == 2:
print("Es martes")
elif day == 3:
print("Es miercoles")
elif day == 4:
print("Es jueves")
elif day == 5:
print("Es viernes")
else:
print("Es fin de semana")
# Ejemplo 4
print("############### Ejemplo 4 ###############")
edadMinima = 18
edadMaxima = 65
edadOficial = int(input("¿Cual es tu edad?: "))
if edadOficial >= 18 and edadOficial <= 65:
print("Esta en edad para trabajar !!")
else:
print("No esta en edad para trabajar.")
"""
Operadores logicos
and Y
or O
! Negacion
not NO
"""
| false |
c7768faa9fcbf14c32138d2fb93a61ca50f0e807 | crishonsou/modern_python3_bootcamp | /calculadora_de_comparacao_para_propostas_pf_pj.py | 1,302 | 4.125 | 4 | sal_atual = int(input('Digite o salário atual: '))
sal_anual = sal_atual * 13
sal_ir = sal_anual * 0.275
sal_anual_liq = sal_anual - sal_ir
plr = sal_atual * 3
plr_ir = plr * 0.275
plr_anual_liq = plr - plr_ir
plano_saude = 700 * 12
previdencia = (sal_atual * 0.10) * 12
alimentacao = 875 * 12
remuneracao_anual = sal_anual + plr + plano_saude + previdencia + alimentacao
remuneracao_anual_ir = remuneracao_anual * 0.275
remuneracao_anual_liq = remuneracao_anual - remuneracao_anual_ir
remuneracao_mensal_pj = remuneracao_anual_liq / 12
print(f'Salário Anual: R$ {sal_anual:.2f}')
print(f'IR anual: R$ {sal_ir:.2f}')
print(f'Salário Anual Liquido: R$ {sal_anual_liq:.2f}')
print(f'Valor do PLR: R$ {plr:.2f}')
print(f'IR sobre PLR: R$ {plr_ir:.2f}')
print(f'PLR Liquido: R$ {plr_anual_liq:.2f}')
print(f'Plano de Saude Anual: R$ {plano_saude:.2f}')
print(f'Previdência Privada Anual: R$ {previdencia:.2f}')
print(f'Alimentação Anual: R$ {alimentacao:.2f}')
print(f'Remuneracao Anual Total: R$ {remuneracao_anual:.2f}')
print(f'IR sobre RAT Anual Total: R$ {remuneracao_anual_ir:.2f}')
print(f'Remuneracao Anual Total Liquida: R$ {remuneracao_anual_liq:.2f}')
print(f'Remuneracao Mensal PJ: R$ {remuneracao_mensal_pj:.2f}')
| false |
ad276443db242eea05db23e68f878b9d6ee00f58 | iahuang/656-Term-1-Project | /blank_all.py | 2,453 | 4.125 | 4 | """ Reads a CSV file with the data that should be formatted as such:
mode, n, time
mode : what operation is it?
n : number of items in the map on which the operation is performed
time : the average time it takes to perform said operation
example: set, 100, 0.05
"""
from scipy.optimize import curve_fit
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
i = 0
class Functions:
@staticmethod
def constant(x, n):
return x*0 + n
@staticmethod
def linear(x, m, b):
return m*x + b
@staticmethod
def logarithmic(x, a, b):
return a * np.log(x) + b
@staticmethod
def linearithmic(x, a, b, c):
return a * np.log(x) + b * x + c
def plot_csv(path, function, title, graphstep=100):
global i
i+=1
xdata = []
ydata = []
with open(path) as csv:
for line in csv.read().split("\n"):
if line == "":
continue
n, t = line.split(", ")
n = int(n)
t = float(t)*1000 # convert to ms
xdata.append(n)
ydata.append(t)
xdata = np.array(xdata)
ydata = np.array(ydata)
param, v = curve_fit(function, xdata, ydata)
plt.subplot(3,3,i)
plt.plot(xdata, ydata)
lin = np.linspace(min(xdata),max(xdata),graphstep)
plt.xscale("log")
plt.title(title)
p1 = mpatches.Patch(color='C0', label='Benchmark data')
plt.xlabel("n: Number of elements in the map being operated on.")
plt.ylabel("Average time per operation (ms)")
print("RMSE Loss:",np.sqrt(np.mean(np.power(ydata-function(xdata, *param),2))))
plt.figure(figsize=(24,18))
plot_csv("data/linearMapGet.csv", Functions.linear, "Linear map GET O(n)")
plot_csv("data/linearMapAdd.csv", Functions.linear, "Linear map ADD O(n)")
plot_csv("data/linearMapUpdate.csv", Functions.linear, "Linear map UPDATE O(n)")
plot_csv("data/binaryMapGet.csv", Functions.logarithmic, "Binary map GET O(logn)")
plot_csv("data/binaryMapAdd.csv", Functions.linearithmic, "Binary map ADD O(n) [O(n + logn)]")
plot_csv("data/binaryMapUpdate.csv", Functions.logarithmic, "Binary map UPDATE O(logn)")
plot_csv("data/hashMapGet.csv", Functions.linear, "Hash map GET O(n)")
plot_csv("data/hashMapAdd.csv", Functions.linear, "Hash map ADD O(n)")
plot_csv("data/hashMapUpdate.csv", Functions.linear, "Hash map UPDATE O(n)")
plt.savefig('foo.png', bbox_inches='tight')
#plt.show()
| true |
71e66c7b65e41e21ed760f8cc68590fe65c52fc4 | Subikesh/Data-Structures-and-algorithms | /Programs/cyclic_sort.py | 828 | 4.21875 | 4 | # We are given an array containing ‘n’ objects. Each object, when created,
# was assigned a unique number from 1 to ‘n’ based on their creation sequence.
# This means that the object with sequence number ‘3’ was created just before the object with sequence number ‘4’.
# Write a function to sort the objects in-place on their creation sequence number in O(n) and without any extra space.
# For simplicity, let’s assume we are passed an integer array containing only the sequence numbers,
# though each number is actually an object.
# Example 1:
# Input: [3, 1, 5, 4, 2]
# Output: [1, 2, 3, 4, 5]
ar = list(map(int, input().strip().split()))
temp = ar[0]
i = temp-1
while i < len(ar):
if i+1 == ar[i]:
i+=1
continue
i = ar[temp-1]
ar[temp-1] = temp
temp = i
i-=1
print(ar) | true |
3e4856ab0a1e6b78b5cb760fdc609e050d29cb98 | Tapz1/Python-Enigma-Machine | /DriveLoc.py | 683 | 4.375 | 4 | ##########
# Chris Tapia
# CIS 220M
# this program will fetch the drive letter/location of a USB drive
##########
from string import ascii_uppercase
import os
# finds the drive
def DriveLocation():
for USBPATH in ascii_uppercase:
if os.path.exists('%s:\\ProgramFile.txt' % USBPATH):
USBPATH='%s:\\' % USBPATH
print('USB Drive Letter is', USBPATH)
return USBPATH + ""
return ""
drive = DriveLocation()
#while drive == "":
# print('Plug in your USB and hit enter to detect drive letter', end="")
# input()
# drive = DriveLocation()
# this shows that the drive letter can then be used anywhere in a program
#print(drive)
| true |
fb61e55220a811e66828177f428b3c4655e27f1a | Skywalker7/python_work | /looping_dictionaries.py | 2,245 | 4.71875 | 5 | #list & dictionary sample exercise -- looping through dictionaries
favorite_languages = {
"jen": "python",
"sarah": "c",
"edward": "ruby",
"phil": "python",
}
friends = ["phil", "sarah"]
for name in favorite_languages.keys():
print(name.title())
if name in friends:
print("Hi " + name.title() +
", I see your favorite language is " +
favorite_languages[name].title() + "!")
#Glossary 2
#using glossary from 6.2 to create a loop that runs through it
#the words key and value are place holders I can switch for other words
glossary = {
"pep_8": "a python syle guide",
"tuple": "a list in python that contains immutable values; it uses '()' to store its values in.",
"len": "is a function that helps you find the length of an item.",
"range": "is a function that prints a series of numbers up to the number you posted.",
"sort": "is a function that permanently sorts a list into alphabetical order.",
"sorted": "is a function temporarily sorts a list into alphabetical order.",
"python": "is a programming language named for Monty Python.",
"boolean expression": "another name for conditional test",
"boolean value": "is either true or false",
"list": "a collection of items that can be modified",
}
for name, definition in glossary.items():
print(name.title() + " " + definition)
#to print it in alphabetical order I can place my dictionary within sorted() for a temporary alphabetical sorting
for name, definition in sorted(glossary.items()):
print(name.title() + " " + definition)
#Rivers
rivers = {
"Nile": "Egypt.",
"Ganges": "India.",
"Mississippi": "the United States.",
}
for river, country in rivers.items():
print("The" + " " + river + " " + "runs through" + " " + country)
for river in rivers.keys():
print("The river" + " " + river + " " + "runs through its entire country.")
for country in rivers.values():
print(country)
#favorite languages poll
favorite_languages = {
"jen": "python",
"sarah": "c",
"edward": "ruby",
"phil": "python",
}
people_who_need_to_poll = ["richard", "sarah", "jen", "tom"]
for name in favorite_languages.keys():
print(name.title())
if name in people_who_need_to_poll:
print("Hey" + " " + name.title() + " " + "would you please take this poll?")
| true |
4802a3a45a3f9eefc344283d44f07f6d601f46fe | Skywalker7/python_work | /pizza.py | 441 | 4.4375 | 4 | # printing pizza types with for loops
pizzas = ["veggie", "pepperoni", "cheese", "sicilian"]
for pizza in pizzas:
print("I like" + " " + pizza.title() + " " + "pizza.")
print("I really like to eat pizza.")
#totally unreleated topic but still practice with for loops
pets = ["dog", "cat", "parakeet", "rabbit", "fish"]
for pet in pets:
print("A" + " " + pet + " " + "is a great pet.")
print("All of these animals need food and water.")
| true |
347d30434fa7a76aff01043c085b78b1e7047511 | Skywalker7/python_work | /tuple_buffet.py | 436 | 4.40625 | 4 | #tuples cannot be modifed like lists but they can be rewritten
#tuples are good for data that you don't want to change throughout the program
buffets = ("steak", "fish", "chicken", "pork")
for buffet in buffets:
print(buffet)
#tuple' object does not support item assignment so the following code does not work
#buffets[1] = "avocado"
#menu change
buffets = ("veal", "turkey", "fish", "pork")
for buffet in buffets:
print(buffet)
| true |
8f0ed884f3f2d488b7ee0a0d978e3b6970ece0e5 | cameron-teed/ICS3U-2-03-PY | /circumfrence_of_circle.py | 494 | 4.28125 | 4 | #!usr/bin/env python
# Created by: Cameron Teed
# Created On: September 2019
# This program calculates the area and perimeter of a circle with the
# radius of 20mm
import constants
def main():
# this function calculates circumfrence
# input
radius = int(input("enter radius of the circle (mm): "))
# procces
circumfrence = constants.TAU*radius
# output
print("")
print("circumfrence is {}mm^2".format(circumfrence))
if __name__ == "__main__":
main()
| true |
98538775ee5ac3ef9005ba911c362eaac7173c2d | lsDantas/Numerical-Analysis | /interface.py | 1,959 | 4.1875 | 4 | # Text Interface
#
# Description: A simple text interface for using the
# root-finding algorithms.
#
from bisection_method import *
from newton_method import *
from sign import *
from sample_equations import *
# Select algorithm prompt
print("Root-finding algorithms\n\n"
+ "(1) Bisection Method\n"
+ "(2) Newton's Method\n")
method_num = float(input("Select an algorithm: "))
while method_num != 1 and method_num != 2:
method_num = float(input("Unavailable option. Select an algorithm: "))
# Select equation prompt
print("\nAvailable Equations\n\n"
+ "(1) x^5 - 5x + 1\n"
+ "(2) x^2 - 4\n")
eq_num = float(input("Select an equation: "))
while eq_num != 1 and eq_num != 2:
eq_sum = float(input("Unavailable option. Select an equation: "))
# Run methods
if method_num == 1:
# Bisection Method
# Gather parameters
a = float(input("\nInitial left bound: "))
b = float(input("Initial right bound: "))
min_inter = float(input("Minimum interval size (halt criterion): "))
max_iter = float(input("Maximum number of steps: "))
# Run bisection algorithm
if eq_num == 1:
a, b, counter = bisection_method(eq1, a, b, min_inter, max_iter)
else:
a, b, counter = bisection_method(eq2, a, b, min_inter, max_iter)
# Display Results
print("\nInterval: [ {}, {}]".format(a,b))
print("Number of steps required: {}".format(counter))
else:
# Newton's Method
# Gather Parameters
x0 = float(input("Initial guess: "))
precision = float(input("Precision: "))
max_iter = float(input("Maximum number of steps: "))
# Run Newton's algorithm
if eq_num == 1:
x, counter = newton_method(eq1, eq1_d, x0, precision, max_iter)
else:
x, counter = newton_method(eq2, eq2_d, x0, precision, max_iter)
# Display Results
print("\nApproximate root: {}".format(x))
print("Number of steps required: {}".format(counter))
| true |
8d9d4d11e981740a87132ea95b481fcf0e87f347 | hollandaise1/python_exercises | /finger-exercise-2.2.py | 1,352 | 4.5 | 4 |
def main():
largest_odd_number(5.7, 8, 11)
def largest_odd_number(x, y, z):
"""Write a program that examines three variables x, y, z
and prints the largest odd number among them.
If none of them are odd, it should print a message
to that effect. """
odd_number_list = []
try:
if int(x) == x and x % 2 != 0:
odd_number_list.append(x)
else:
if int(y) == y and y % 2 != 0:
odd_number_list.append(y)
else:
if int(z) == z and z % 2 != 0:
odd_number_list.append(z)
print(max(odd_number_list))
except ValueError:
print("No odd integers are found!")
def larger_odd_number(x, y):
"""Write a program that compares the two numbers and prints the larger odd number"""
if x == y:
print("Cannot compare 'cause the two numbers are equal!")
elif x % 2 != 0 and y % 2 != 0:
if x > y:
print("The larger number is: ", x)
else:
print("The larger number is: ", y)
else:
if x % 2 != 0 and y % 2 == 0:
print(x)
elif x % 2 == 0 and y % 2 != 0:
print("The larger number is: ", y)
else:
print("Both numbers are not odd numbers, try another two numbers!")
if __name__ == '__main__':
main()
| true |
6fa11f88a2d8ce0979977df34693dac2ab00d83f | dev7796/MVC_Architecture- | /Core_Python/Python String/Lec 8/FILE BASIC (1).py | 2,427 | 4.21875 | 4 | #file io
#file object = open(file_name,[access_mode])
file = open("1.txt","r")
#access_mode = read,write,append
#Accessing Mode
file = open("1.txt","r+")
"""
r ==> reading only.The file pointer is placed at the beginning of the file.This is the default mode.
r+ ==> both reading and writing.The file pointer placed at the beginning of the file.
rb ==> reading only in binary format.The file pointer is placed at the beginning of the file.(image read)
rb+ ==> both reading and writing in binary format.The file pointer placed at the beginning of the file.
"""
file = open("1.txt","w+")
'''
w ==> writing only.Overwrites the file if the file exists.
If the file does not exist, creates a new file for writing.
w+ ==> both writing and reading.Overwrites the existing file if the file exists.
If the file does not exist, creates a new file for reading and writing.
wb ==> writing only in binary format.Overwrites the file if the fIle exists.
If the file does not exist, creates a new file for writing.
wb+ ==> both writing and reading in binary format.Overwrites the existing file if the file exists.
If the file does not exist, creates a new file for reading and writing.
'''
file = open("1.txt","a+")
'''
a ==> appending. The file pointer is at the end of the file, if the file exists.
If the file does not exist, it creates a new file for writing.
a+ ==> both appending and reading.The file pointer is at the end of the file, if the file exists.
If the file does not exist, it creates a new file for reading and writing.
ab ==> appending in binary format.The file pointer is at the end of the file if the file exists.
If the file does not exist, it creates a new file for writing.
ab+ ==> both appending and reading in binary format.The file pointer is at the end of the file, if the file exists.
If the file does not exist, it creates a new file for reading and writing.
'''
#file object
#read a file
fo = open("foo.txt", "r+")
str = fo.read(10)
position = fo.tell()
#The tell() method tells you the current position(int) within the file
#reposition pointer
fo.seek(0,0)
print ("Read String is : ", str)
fo.close()
#seek(offset,whence)
#offset means character index
#whence means position
#0= begining position
#1= current position
#2= ending position
#write in a file
fo = open("foo.txt", "wb")
fo.write( "Python is a great language.\nYeah its great!!\n");
fo.close()
| true |
4fa230dddbfceb70d71edadb6458cb3d398c2d83 | 109658067/Python3_Codecademy | /10-classes/02-learn-inheritance-and-polymorphism/09-review-concepts.py | 276 | 4.125 | 4 | class SortedList(list):
def __init__(self, values):
self.extend(values)
#for num in values:
# self.append(num)
self.sort()
def append(self, value):
super().append(value)
self.sort()
l1 = SortedList([5,4,3,2,1])
print(l1)
l1.append(-1)
print(l1)
| false |
1a7b0720630370b666badb3bc6ba460788962b33 | ln-xxx/biji | /python 笔记/day09_异常/日常一测.py | 1,458 | 4.5625 | 5 | """
有三种动物animal:狗dog、猫cat、猪pig,
父类:动物、
子类:狗、猫、猪
动物的属性:动物的名字
动物的方法是eat(就是打印自己的名字)
有一个饲养员:饲养员feeder
饲养员的方法:feed_animal(需要饲养的动物)
函数的实现是(其实就是调用动物的eat方法)
创建对象-->调用方法:
饲养员韩哲喂一下猪 写一下执行结果
韩哲喂一下狗 写一下执行结果
韩哲喂一下猫 写一下执行结果
"""
class Animal:
def __init__(self, name):
self.name = name
def eat(self):
print("吃")
class Dog(Animal):
def eat(self):
print("我是狗,我叫%s,我吃骨头,偶尔多管闲事吃个耗子" % self.name)
class Cat(Animal):
def eat(self):
print("我是猫,我叫%s,我爱吃小鱼儿,偶尔跟狗打架抢耗子" % self.name)
class Pig(Animal):
def eat(self):
print("我是猪, 我叫%s,我爱吃西瓜,偶尔在取经的路上看猫狗打架抢耗子" % self.name)
class Feeder:
def __init__(self, name):
self.name = name
def feeder_animal(self, obj): # obj喂养的动物
print(self.name+"喂的:")
obj.eat()
dog = Dog("旺财")
cat = Cat("加菲猫")
pig = Pig("八戒")
f = Feeder("韩哲")
f.feeder_animal(pig) # 我是猪....
f.feeder_animal(dog) # 我是狗....
f.feeder_animal(cat) # 我是猫....
| false |
db65fd8b3967d5f47a65b52ab3beac1eef8d8e4c | ln-xxx/biji | /python 笔记/day09_异常/多态/demo01.py | 589 | 4.28125 | 4 | """
多态: 多种形态
issubclass(参数1, 参数2) 参数1是否是参数2的子类
数值类型: 整数int 浮点数float 复数complex 布尔类型bool True/False
"""
s = "abc"
print(type(s)) # <class 'str'>
print(isinstance(s, str)) # True
class A:
pass
class B(A):
pass
a = A()
print(isinstance(a, A)) # True
b = B() # B类的对象
print(type(b)) # <class '__main__.B'>
print(isinstance(b, B)) # True
print(isinstance(b, A)) # True
# 两个参数必须都是类, 判断参数1类是否是参数2类的子类
print(issubclass(B, A)) # True
| false |
c48dce8706895eb66f0befdf9610084c8b80f281 | ronmoy007/Propedeutico | /Python/clases/1_introduccion/ejemplo_diccionarios.py | 601 | 4.4375 | 4 | ERROR: type should be string, got "\nhttps://docs.python.org/3/tutorial/datastructures.html#dictionaries\n#diccionarios:\nprint('-'*10)\ndic = {'llave1': 1,'llave2':'string1'}\nprint('Diccionario:', dic)\n#podemos acceder a los valores\n#guardados en cada llave como sigue:\nprint('valor guardado en la llave1:', dic['llave1'])\nprint('valor guardado en la llave2:',dic['llave2'])\n\n#imprimimos las llaves\nprint('llaves del diccionario:',dic.keys())\n#imprimimos los valores:\nprint('valores del diccionario:', dic.values())\n#añadimos entradas a un diccionario \n#con:\ndic['llave3'] = -34\nprint('añadiendo pareja llave-valor al diccionario:',dic)\n" | false |
d2378e901ab9183d7203fd4f32bbd93b3de00ad0 | Kenn430/Python-works | /022_factorial_recursion.py | 278 | 4.21875 | 4 | # Get the fatorial of a given number by recursion
def fac(n):
if n == 1:
return 1
else:
return n * fac(n-1)
number = int(input('Please give the number for factorial: '))
result = fac(number)
print("Factorial of %d is %d" % (number, result))
| true |
9a6289f2581e0ce49cd7dbd5b78ae32694e07384 | marcelogarro/challenges | /CodeWars/Python/Terminal Game #2.py | 1,419 | 4.28125 | 4 | """
Create the hero move method
Create a move method for your hero to move through the level.
Adjust the hero's position by changing the position attribute. The level is a grid with the following values.
00 01 02 03 04
10 11 12 13 14
20 21 22 23 24
30 31 32 33 34
40 41 42 43 44
The dir argument will be a string
```
up
down
left
right
```
If the position is not inside the level grid the method should throw an error and not move the hero
"""
class Hero:
def __init__(self):
self.position = '00'
self.downLimit = 4
self.upLimit = 0
self.rightLimit = 4
self.leftLimit = 0
def move(self, dir):
self.position = int(self.position)
firstNumber = self.position / 10
secondNumber = self.position / 10
if dir == 'down' and firstNumber < self.downLimit:
self.position += 10
elif dir == 'up' and firstNumber > self.upLimit:
self.position -= 10
elif dir == 'left' and secondNumber > self.leftLimit:
self.position -= 1
elif dir == 'right' and secondNumber < self.rightLimit:
self.position += 1
else:
self.position = str(self.position)
raise Exception('new position is out of bounds')
if self.position < 10:
self.position = '0{}'.format(str(self.position))
else:
self.position = str(self.position)
| true |
3dcde6bec342e37d99c93f9fb7b27e888cc82466 | marcelogarro/challenges | /CodeWars/Python/The Shell Game.py | 1,244 | 4.53125 | 5 | """
"The Shell Game" involves three shells/cups/etc upturned on a playing surface, with a ball placed underneath one of them. The shells are then rapidly swapped round, and the game involves trying to track the swaps and, once they are complete, identifying the shell containing the ball.
This is usually a con, but you can assume this particular game is fair...
Your task is as follows. Given the shell that the ball starts under, and list of swaps, return the location of the ball at the end. All shells are indexed by the position they are in at the time.
For example, given the starting position 0 and the swap sequence [(0, 1), (1, 2), (1, 0)]:
* The first swap moves the ball from 0 to 1
* The second swap moves the ball from 1 to 2
* The final swap doesn't affect the position of the ball.
So
```
find_the_ball(0, [(0, 1), (2, 1), (0, 1)]) == 2
```
There aren't necessarily only three cups in this game, but there will be at least two. You can assume all swaps are valid, and involve two distinct indices.
"""
def find_the_ball(start, swaps):
""" Where is the ball? """
for swap in swaps:
if swap[0] == start:
start = swap[1]
elif swap[1] == start:
start = swap[0]
return start
| true |
bf7a345452a077177c4c07926af62329018a858b | marcelogarro/challenges | /CodeWars/Python/Write Number in Expanded Form.py | 522 | 4.25 | 4 | """
You will be given a number and you will need to return it as a string in Expanded Form. For example:
```
expanded_form(12) # Should return '10 + 2'
expanded_form(42) # Should return '40 + 2'
expanded_form(70304) # Should return '70000 + 300 + 4'
```
NOTE: All numbers will be whole numbers greater than 0.
"""
def expanded_form(num):
result = []
for index, digit in enumerate(str(num)[::-1]):
if int(digit) != 0:
result.append(digit + ('0' * index))
return ' + '.join(result[::-1])
| true |
21b4b9decc8ac525dd3715f4ca19e236018263aa | y4nj1/Assignment-4-PLD-BSCOE-1-6 | /2-applesandoranges.py | 1,168 | 4.15625 | 4 | # Create a program that will ask how many apples and oranges you want to buy.
# Display the total amount you need to pay if apple price is 20 pesos and orange is 25.
# Display the output in the following format.
# The total amount is ________.
def showPrices():
_PriceA = 20
_PriceO = 25
print(f"The price of an apple is {_PriceA} pesos.")
print(f"The price of an orange is {_PriceO} pesos.")
return _PriceA, _PriceO
def getQuantities():
_AmountA = int(input("How many apples will you buy? "))
_AmountO = int(input("How many oranges will you buy? "))
return _AmountA, _AmountO
def totalPrice(PriceA, PriceO, AmountA, AmountO):
_PriceApple = PriceA * AmountA
_PriceOrange = PriceO * AmountO
_PriceTotal = _PriceApple + _PriceOrange
return _PriceTotal
def display(solve):
print(f"The total amount is {solve} pesos.")
# steps
# 1. show the price of an apple and an orange
PriceA, PriceO = showPrices()
# 2. ask how many apples and oranges will they buy
AmountA, AmountO = getQuantities()
# 3. solve for the total price
solve = totalPrice(PriceA, PriceO, AmountA, AmountO)
# 4. display the total price
display(solve) | true |
2ebee715b0be8d5ae0290d21248924667b977a29 | Radic4l/Python-Training | /data-science-courses/cours/booleens_et_operateurs.py | 563 | 4.1875 | 4 | # == retourne vrai si les variable sont équivalente
print(2 == 2)
# ou faux si elle ne le sont pas
print(2 == 3)
# != retourne vrais si la valeur des variables sont differentes
print(2 != 3)
# ou faut si elle sont equivalente
print(2 != 2)
# > / >= retourne vrais si la premiere variable et plus grande que la deuxieme / plus grande ou egale a la deuxieme variable
print(2>1)
print(2>=2)
# ou faux si inversement
print(2>2)
print(2>=3)
# Idem pour < / <=
# fonctionnent egaleme,nt avec les liste
print(["chien","chat"] == ["chien","chat"])
print(5.0 == 5.0)
| false |
efd8e70728df110723189f07d144badb88245105 | b4158813/my-python-journey | /period1/3/12-4魔法方法__init__讲解.py | 1,080 | 4.15625 | 4 | # -*- coding: utf-8 -*-
#方法名如果是__xxx__()那么就有特殊功能,叫做魔法方法
class Person:
#初始化对象的方法,不是构建对象的方法
def __init__(self):#创建对象后自动执行该方法
self.name="zs"
self.age="18"
print("对象初始化")
def work(self):
pass
p1=Person()#构建对象
print(p1.name)
class Person2():
def __init__(self,name,age,height):#可在后面加形参
self.name=name
self.age=age
self.height=height
def __str__(self):#str方法:打印对象时,自动把对象转换成字符串
return "姓名:%s,年龄:%s,身高:%scm"%(self.name,self.age,self.height)
def introduce(self):
print("姓名:%s,年龄:%s,身高:%s"%(self.name,self.age,self.height))
p2=Person2("zs","18","170")#构建对象
p2.introduce()
print(p2)
'''
对象形成的过程:
创建对象
__new__()构造对象方法,得到一个对象
__init__(self)初始化对象方法
''' | false |
b5a7ceabd5799e0241e131e6a723c0e92a364f75 | b4158813/my-python-journey | /period1/1/4用户交互程序.py | 912 | 4.1875 | 4 | # -*- coding: utf-8 -*-
'''
username = input('username:')
password = input('password:')
print(username,password)
'''
Name = input('Name:')
#raw_input 2.x input 3.x
#input 2.x 没用 多余
Age = int(input('Age:'))#integer
print(type(Age),type(str(Age)))
#所有输入的字符都默认为字符串类型,需要强制转换成整型
Job = input('Job:')
Salary = input('Salary:')
info = '''
-------- info of %s -------
Name:%s
Age:%s
Job:%s
Salary:%s
''' %(Name,Name,Age,Job,Salary)
print(info)
#下面是另一种定义格式
info2 = '''
-------- info of {_Name} -------
Name:{_Name}
Age:{_Age}
Job:{_Job}
Salary:{_Salary}
''' .format(_Name=Name,
_Age=Age,
_Job=Job,
_Salary=Salary)
print(info2)
#下面是另一种方式
info3 = '''
-------- info of {0} -------
Name:{0}
Age:{1}
Job:{2}
Salary:{3}
''' .format(Name,Age,Job,Salary)
print(info3) | false |
23636cc768bcd4ec6525799ff946eaab5534c1ff | RafaelaCamp/Python-Learn | /PythonUSP/Semana2/Exercício1/quadrado.py | 738 | 4.25 | 4 | # Exercício 1 - Perímetro e Área
#Faça um programa em Python que receba (entrada de dados) o valor correspondente ao lado de um quadrado, calcule e imprima (saída de dados) seu perímetro e sua área.
#Observação: a saída deve estar no formato: "perímetro: x - área: y"
#Abaixo um exemplo de como devem ser a entrada e saída de dados do programa:
#Exemplo:
# Entrada de Dados:
# Digite o valor correspondente ao lado de um quadrado: 3
# Saída de Dados:
# perímetro: 12 - área: 9
# Dica: lembre-se que um quadrado tem quatro lados iguais, logo só é necessário pedir o lado uma vez
x = int(input("valor de um lado do quadrado:"))
perimetro = x*4
area = x*x
print("perimetro:", perimetro, "- área:", area) | false |
928daa5ea8ca5d1cc62a65303f5ac4e691173900 | RafaelaCamp/Python-Learn | /PythonUSP/Semana4/Exercício3/Digitos.py | 641 | 4.125 | 4 | # Exercício 3 - Soma dos Dígitos
# Escreva um programa que receba um número inteiro na entrada, calcule e imprima a soma dos dígitos deste número na saída
# Exemplo:
# 1 Digite um número inteiro: 123
# 2 6
#Dica: Para separar os dígitos, lembre-se: o operador "//" faz uma divisão inteira jogando fora o resto, ou seja, aquilo que é menor que o divisor; O operador "%" devolve apenas o resto da divisão inteira jogando fora o resultado, ou seja, tudo que é maior ou igual ao divisor.
x = int(input("Digite um número:"))
soma = 0
while (x != 0):
resto = x % 10
x = (x - resto)//10
soma = soma + resto
print(soma) | false |
d280a4e47925204694f097b52d65f0778aec85dc | ericwu1997/Python | /ModPrime/prime.py | 1,968 | 4.15625 | 4 | """
name : prime.py
author : Eric Wu, A00961904
data : 03/20/2020
"""
def getMod(b,e,m):
"""This function returns the modulus of a given number
Args:
b (int): base of the number
e (int): exponent
m (int): modulus
Returns:
int: modulus result
"""
return (b ** (e)) % m
def isPrime(x):
"""This function check if a number is prime or not
Args:
x (int): number to be checked
Returns:
bool: true if the number is prime, false otherwise
"""
if x > 1:
for i in range(2,x):
# if the number is divisible by smaller number, return False
if (x % i) == 0:
return False;
else:
return True;
def listPrimes(n):
"""This function returns a list of prime number in a given range
Args:
n (int): range of number to check for prime, starting from 1.
Returns:
list of prime number found in range, empty if none
"""
prime_list = []
if(n < 3):
# if n == 2, append 2 to prime list
if (n == 2):
prime_list.append(2)
return prime_list
else :
prime_list.append(2)
# check for prime starting from 3 up to n
for i in range(3, n):
# if a prime is found, append to list
if(isPrime(i)):
prime_list.append(i)
return prime_list;
def gcd(a,b):
"""This function gets the greatest common denominator between two number
Args:
a (int): first number
b (int): second number
Returns:
int: the greatest common denominator
"""
# Get the smaller number between a & b
small = b if a > b else a
# check for gcd from 1 up to the lower number between a & b
for i in range(1, small+1):
if((a % i == 0) and (b % i == 0)):
gcd = i
return gcd;
| true |
907a6cdee07cfa5b9e42aabbd9b5a2663e9362ac | LennyBoyatzis/python-patterns | /patterns/patterns/factory.py | 1,511 | 4.375 | 4 | from abc import abstractmethod, ABC
class Pizza(ABC):
"Simple pizza class"
@abstractmethod
def prepare(self):
pass
@abstractmethod
def bake(self):
pass
@abstractmethod
def cut(self):
pass
@abstractmethod
def box(self):
pass
class CheesePizza(Pizza):
def prepare(self):
print("preparing cheese pizza")
def bake(self):
print("baking cheese pizza")
def cut(self):
print("cutting cheese pizza")
def box(self):
print("boxing cheese pizza")
class GreekPizza(Pizza):
def prepare(self):
print("preparing greek pizza")
def bake(self):
print("baking greek pizza")
def cut(self):
print("cutting greek pizza")
def box(self):
print("boxing greek pizza")
class PizzaFactory:
"Class used to exclusively deal with the object creation process"
def create(self, pizza_type: str) -> Pizza:
if pizza_type == 'Greek':
return GreekPizza()
elif pizza_type == 'Cheese':
return CheesePizza()
else:
print("No matching pizza found..")
class PizzaStore(PizzaFactory):
def __init__(self, factory: PizzaFactory):
self.factory = factory
def order_pizza(self, pizza_type: str):
pizza = self.factory.create(pizza_type)
pizza.prepare()
pizza.bake()
pizza.cut()
pizza.box()
store = PizzaStore(PizzaFactory())
store.order_pizza('Greek')
| true |
8307a7829e56b7af416deafe16eb23ea8b35cccf | 101guptaji/Python-programmes | /hackerRank/Anagram_strings.py | 1,408 | 4.125 | 4 | #Sherlock and Anagrams
'''Two strings are anagrams of each other if the letters of one string can be rearranged to form the other string. Given a string, find the number of pairs of substrings of the string that are anagrams of each other.
For example s = mom, the list of all anagrammatic pairs is [m, m], [mo, om] at positions [[0], [2]], [[0, 1], [1, 2]] respectively.'''
import math
import os
import random
import re
import sys
def subarray(s):
sub=[]
n=len(s)
for i in range(n):
for j in range(i+1,n+1):
sub.append(''.join(sorted(s[i:j])))
return sub
def isAnagram(s1,s2):
charD={}
for i in s1:
charD[i]=charD.get(i,0)+1
for j in s2:
if(j in charD.keys() and charD[j]>0):
charD[j]-=1
else:
return False
#print(charD)
return True
# Complete the sherlockAndAnagrams function below.
def sherlockAndAnagrams(s):
sub=subarray(s)
print(sub)
n=len(sub)
count=0
#print(anagram('abab','abba'))
for i in range(len(sub)):
s1=sub[i]
for j in range(i+1,n):
s2=sub[j]
#print(s1,s2)
if((len(s1)==len(s2)) and (isAnagram(s1,s2)==True)):
count+=1
#print(count)
return count
if __name__ == '__main__':
s = 'abcd' #input()
result = sherlockAndAnagrams(s)
print(str(result) + '\n')
| true |
bc657edad3e807fb48277b1351b9395b86d406fe | vitaliyvoloshyn/Python | /Основы Python/Lesson1/Task3.py | 857 | 4.28125 | 4 | # Реализовать склонение слова «процент» во фразе «N процентов». Вывести эту фразу на экран отдельной строкой для каждого
# из чисел в интервале от 1 до 100:
# 1 процент
# 2 процента
# 3 процента
# 4 процента
# 5 процентов
# 6 процентов
# ...
# 100 процентов
for i in range(1, 101):
if i % 10 == 0 or 5 <= i % 10 <= 9:
print(f'{i} процентов')
elif i % 10 == 1:
if i == 11:
print(f'{i} процентов')
else:
print(f'{i} процент')
elif 2 <= i % 10 <= 4:
if i == 12 or i == 13 or i == 14:
print(f'{i} процентов')
else:
print(f'{i} процента')
| false |
bd57665785ba47c5bddd3f627d71b395c13511d3 | rmainhar/COURSE_NYU-Python | /Assignment#02/Assignment 2.2_Rectangle's area.py | 1,238 | 4.25 | 4 | '''
This is Part 2 of Assignment 2
for Introduction to Computer Programming
by Craig Kapp @ NYU.
'''
'''
This program aims to practice 'if-elif-else' structure
'''
'''
This program prompt user to input dimensions of
two different rectangles. Then, it calculates and compares
the areas
'''
# Prompt the user to enter in dimensions of two different rectangles.
a_length = float(input("Please enter the length of the first rectangle: "))
a_width = float(input("Please enter the width of the first rectangle: "))
b_length = float(input("Please enter the length of the second rectangle: "))
b_width = float(input("Please enter the width of the second rectangle: "))
# Add a blank line
print('')
# Calculate the area of each rectangle.
a_area = a_length*a_width
b_area = b_length*b_width
# Print out the result, determine which is the larger one.
print('The area of first rectangle is: ', a_area)
print('The area of second rectangle is: ', b_area)
# Add a blank line
print('')
# if-elif-else format
if a_area > b_area:
max_area = a_area
print('Rectangle #1 has larger size.')
elif a_area < b_area:
max_area = b_area
print('Rectangle #2 has larger size.')
else:
print('Rectangle #1 and Rectangle #2 are the same size.')
| true |
f62336c6bc4992c990ec76ae0235a6b2afc6673b | simrankaurkhaira1467/Training-with-Acadview | /Assignment3.py | 1,643 | 4.21875 | 4 | #TUPLES
#question 1: Create a tuple with different data types and do the following:
#1. Find the length of tuples.
t= (1,5.6,"hello",True,4)
l=len(t)
print(l)
#2. Print largest and smallest elements of tuple.
tp=(5,6,8,9,4,3,1)
mx=max(tp)
print(mx)
mn=min(tp)
print(mn)
t1=('abcd','xyz','pq')
mx=max(t1)
print(mx)
mn=min(t1)
print(mn)
#3. To find the product of all elements of tuple.
prod=1
for i in tp:
prod *=i
print(prod)
#SETS
#question 2: Create two set using user defined values.
#creating set 1.
x=input("enter values in set:").split()
s1=set()
for i in x:
s1.add(i)
print(s1)
#creating set 2.
y=input("enter values in set:").split()
s2=set()
for i in y:
s2.add(i)
print(s2)
#1. Calculate difference between sets.
print(s1-s2)
print(s2-s1)
#2. Compare two sets.
print(s1==s2)
#3. Print the result of intersection of two sets.
print(s1 & s2)
#DICTIONARY
#question 3:
#1. To create a dictionary to store name and marks of 10 students by user input.
dic={}
for i in range(10):
key=input()
value=int(input())
dic[key]=value
print(dic)
#2. To sort dictionary created in previous question according to marks.
for key,value in sorted(dic.items(), key=lambda x: x[1]):
print("%s : %s" %(key,value))
#3. Count occurences of each letter in word "MISSISSIPPI". Store count of every letter with a letter in a dictionary.
def char_freq(str):
dict ={}
for n in str:
keys=dict.keys()
if n in keys:
dict[n]+=1
else:
dict[n]=1
return dict
print(char_freq('MISSISSIPI')) | true |
27d749dcf873502e0ad53b5d80a22916d34ffd06 | 9juandromero7/taller-4 | /taller 4/punto9.py | 1,008 | 4.15625 | 4 | """
entrada
monto=>int=>mon
salida
monto total a pagar
"""
mon=int(input("ingrese monto: "))
if (mon<=50000)and(mon>=15000):
print("no hay descuento")
elif (mon >= 50000) and (mon <= 100000):
des=(mon*.05)/100
total=(mon-des)
print("el descuento es de: "+str(des))
print("su total a pagar es de: "+str(total))
print("Juan Diego El Crack")
elif(mon >= 100000) and (mon <= 7000000):
des=(mon*.11)/100
total=(mon-des)
print("el descuento es de: "+str(des))
print("su total a pagar es de: "+str(total))
print("Juan Diego El Crack")
elif(mon>=700000) and (mon<=15000000):
des=(mon*.18)/100
total=(mon-des)
print("el descuento es de: "+str(des))
print("su total a pagar es de: "+str(total))
print("Juan Diego El Crack")
elif(mon>=1500000000):
des=(mon*.25)/100
total=(mon-des)
print("el descuento es de: "+str(des))
print("su total a pagar es de: "+str(total))
print("Juan Diego El Crack")
| false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.