blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
dcd5df108f3668bfb8e8c2228d1cc86350703500 | KurinchiMalar/DataStructures | /LinkedLists/DoublyLinkedListInsert.py | 1,889 | 4.03125 | 4 | class Node(object):
def __init__(self, data=None, next_node=None, prev_node=None):
self.data = data
self.next = next_node
self.prev = prev_node
def SortedInsert(head, data):
if head == None:
head = Node(data)
return head
p = head
newNode = Node(data)
if p.data > data: # insert in beginning
newNode.next = p
p.prev = newNode
head = newNode
return head
while p.next != None:
if p.data > data: # insert in middle
p.prev.next = newNode
newNode.prev = p.prev
newNode.next = p
p.prev = newNode
return head
p = p.next
if p.data < data:
p.next = newNode # insert at last
newNode.prev = p
return head
p.prev.next = newNode
newNode.prev = p.prev
newNode.next = p
p.prev = newNode
return head
def print_dlist(head):
current = head
while current != None:
print current.data,
current = current.next
print
def swap(current):
temp = current.next
current.next = current.prev
current.prev = temp
def Reverse(head):
if head == None:
return head
current = head
while current != None:
swap(current)
#current.next,current.prev = swap(current.next,current.prev)
#current.next,current.prev = current.prev,current.next
if current.prev == None:
head = current
return current
current = current.prev
return head
one = Node(1)
head = one
two = Node(2)
three = Node(3)
four = Node(4)
six = Node(6)
one.next = two
two.prev = one
three.prev = two
two.next = three
four.prev = three
three.next = four
six.prev = four
four.next = six
print_dlist(head)
# head = SortedInsert(head,5)
# print_dlist(head)
head = Reverse(head)
print_dlist(head)
|
f0a64396e3cd7998f6c982d1b059344d2adfb94d | KurinchiMalar/DataStructures | /Medians/MajorityElement_Copy.py | 4,505 | 3.875 | 4 |
# Sorting Solution
# Time Complexity : O(nlogn) + O(n)
from Sorting.MergeSort import mergesort
from Sorting.Median import getMedian_LinearTime
def find_majorityelem_bruteforce(Ar):
Ar = mergesort(Ar)
print Ar
max_elem = -1
max_count = 0
for i in range(0,len(Ar)):
count = 1
for j in range(i+1,len(Ar)):
if Ar[i] != Ar[j]:
break
count = count + 1
if count > max_count:
max_elem = Ar[i]
max_count = count
count = 0
print "max elem is :"+ str(max_elem) +"occured :"+str(max_count)+"times."
if max_count > len(Ar)/2:
return max_elem
return -1
# Median Logic
# Time Complexity : O(n) + O(n) ---> worst case LinearSelection - O(n*n)
'''
1) Use Linear Selection to find median of Ar
2) Do one more pass to count number of occurences of median. Return true if it is more than n/2
'''
def find_majority_median_logic(Ar):
median = getMedian_LinearTime(Ar)
print "median is "+str(median)
count = 0
for i in range(0,len(Ar)):
if Ar[i] == median:
count = count + 1
if count > len(Ar)/2:
return median
return -1
# BST logic
#Time Complexity - O(n) + O(logn) --> n (creation) + logn for insertion
#Space Complexity - O(2n) = O(n) since every node in BST needs two extra pointers.
class BstNode:
def __init__(self,key):
self.key = key
self.left = None
self.right = None
self.count = 1
def insert_bst(root,node):
if root is None:
root = node
return root
max_elem = None
max_count = 0
while root != None:
if root.key == node.key:
root.count = root.count+1
if max_count < root.count:
max_count = root.count
max_elem = root
break
elif node.key < root.key:
if root.left is None:
root.left = node
else:
root = root.left
else:
if root.right is None:
root.right = node
else:
root = root.right
return root
def create_bst(Ar):
root = BstNode(Ar[0])
for i in range(1,len(Ar)):
max_node = insert_bst(root,BstNode(Ar[i]))
return max_node
def find_majority_bst_logic(Ar):
r = create_bst(A)
print "result"+str(r.key)
if r.count > len(Ar) // 2:
return r.key
else:
return -1
'''
This is a two step process.
1. Get an element occurring most of the time in the array. This phase will make sure that if there is a majority element then it will return that only.
2. Check if the element obtained from above step is majority element.
1. Finding a Candidate:
The algorithm for first phase that works in O(n) is known as Moore’s Voting Algorithm.
Basic idea of the algorithm
If we cancel out each occurrence of an element e with all the other elements that are different from e
then e will exist till end if it is a majority element.
The algorithm loops through each element and maintains a count of a[maj_index],
If next element is same then increments the count,
if next element is not same then decrements the count,
and if the count reaches 0 then changes the maj_index to the current element and sets count to 1.
First Phase algorithm gives us a candidate element.
2. In second phase we need to check if the candidate is really a majority element.
Second phase is simple and can be easily done in O(n).
We just need to check if count of the candidate element is greater than n/2.
'''
# Time Complexity : O(n)
# Space Complexity : O(1)
def find_majority_MooresVotingAlgorithm(Ar):
# Find candidate
element = 0
count = 0
for i in range(0,len(Ar)):
if count == 0:
element = Ar[i]
count = 1
elif element == Ar[i]:
count = count + 1
else:
count = count -1
print "majority_candidate:"+str(element)
count_in_ar = 0
for i in range(0,len(Ar)):
if Ar[i] == element:
count_in_ar = count_in_ar + 1
if count_in_ar > len(Ar) // 2:
return element
return -1
A = [3,3,4,2,4,4,2,4,4]
A = [7,3,2,3,3,6,9]
#print ""+str(find_majorityelem_bruteforce(A))
#print ""+str(find_majority_median_logic(A))
#print ""+str(find_majority_bst_logic(A))
print ""+str(find_majority_MooresVotingAlgorithm(A))
|
f2640a1412c6ee3414bf47175439aba242d5c81f | KurinchiMalar/DataStructures | /LinkedLists/SqrtNthNode.py | 1,645 | 4.1875 | 4 | '''
Given a singly linked list, write a function to find the sqrt(n) th element, where n is the number of elements in the list.
Assume the value of n is not known in advance.
'''
# Time Complexity : O(n)
# Space Complexity : O(1)
import ListNode
def sqrtNthNode(node):
if node == None:
return None
current = node
count = 1
sqrt_index = 1
crossedthrough = []
result = None
while current != None:
if count == sqrt_index * sqrt_index:
crossedthrough.append(current.get_data())
result = current.get_data()
print "Checking if current count = sq( "+str(sqrt_index)+" )"
sqrt_index = sqrt_index + 1
count = count + 1
current = current.get_next()
print "We have crossed through: (sqrt(n))== 0 for :"+str(crossedthrough)
return result
head = ListNode.ListNode(1)
#print ListNode.ListNode.__str__(head)
n1 = ListNode.ListNode(2)
n2 = ListNode.ListNode(3)
n3 = ListNode.ListNode(4)
n4 = ListNode.ListNode(5)
n5 = ListNode.ListNode(6)
n6 = ListNode.ListNode(7)
n7 = ListNode.ListNode(8)
n8 = ListNode.ListNode(9)
n9 = ListNode.ListNode(10)
n10 = ListNode.ListNode(11)
n11 = ListNode.ListNode(12)
n12 = ListNode.ListNode(13)
n13 = ListNode.ListNode(14)
n14 = ListNode.ListNode(15)
#orig_head = ListNode.ListNode(1)
#orig_head.set_next(n1)
head.set_next(n1)
n1.set_next(n2)
n2.set_next(n3)
n3.set_next(n4)
n4.set_next(n5)
n5.set_next(n6)
n6.set_next(n7)
n7.set_next(n8)
n9.set_next(n10)
n10.set_next(n11)
n11.set_next(n12)
n12.set_next(n13)
n13.set_next(n14)
print "Sqrt node (last from beginning): "+str(sqrtNthNode(head))
|
1133d5be23312ce519c55837cea5880fd729c3f6 | KurinchiMalar/DataStructures | /Medians/PairComparisonMinMax.py | 991 | 4.09375 | 4 |
# Time Complexity : O(n)
# Space Complexity : O(1)
'''
Number of Comparisons:
n is even : (3n/2) - 2
n is odd : (3n/2) - 3/2
'''
def get_MinMax_using_paircomparison(Ar):
start = -1
if len(Ar)% 2 == 0 : # even
min_elem = Ar[0]
max_elem = Ar[1]
start = 2
else: # odd
min_elem = max_elem = Ar[0]
start = 1
for i in range(start,len(Ar),2):
#print ""+str(i)
first = Ar[i]
second = Ar[i+1]
if first < second:
if first < min_elem:
min_elem = first
if second > max_elem:
max_elem = second
else:
if second < min_elem:
min_elem = second
if first > max_elem:
max_elem = first
return min_elem,max_elem
Ar = [2,67,1,5,3,7,8,234,55,72,9]
Ar = [2,3,1,5,6,7]
min_elem , max_elem = get_MinMax_using_paircomparison(Ar)
print "min: "+str(min_elem)+"max: "+str(max_elem) |
ec4a2fc2faea5acfea8a352c16b768c79e679104 | KurinchiMalar/DataStructures | /Hashing/RemoveGivenCharacters.py | 507 | 4.28125 | 4 | '''
Give an algorithm to remove the specified characters from a given string
'''
def remove_chars(inputstring,charstoremove):
hash_table = {}
result = []
for char in charstoremove:
hash_table[char] = 1
#print hash_table
for char in inputstring:
if char not in hash_table:
result.append(char)
else:
if hash_table[char] != 1:
result.append(char)
result = ''.join(result)
print result
remove_chars("hello","he")
|
82ecc3e32e7940422238046cd7aa788979c51f9c | KurinchiMalar/DataStructures | /Stacks/Stack.py | 1,115 | 4.125 | 4 |
from LinkedLists.ListNode import ListNode
class Stack:
def __init__(self,head=None):
self.head = head
self.size = 0
def push(self,data):
newnode = ListNode(data)
newnode.set_next(self.head)
self.head = newnode
self.size = self.size + 1
def pop(self):
if self.head is None:
print "Nothing to pop. Stack is empty!"
return -1
toremove = self.head
self.head = self.head.get_next()
self.size = self.size - 1
return toremove
def peek(self):
if self.head is None:
print "Nothing to peek!. Stack is empty!"
return -1
return self.head.get_data()
def print_stack(self):
current = self.head
while current != None:
print current.get_data(),
current = current.get_next()
print
'''
stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3)
stack.push(4)
stack.push(5)
stack.push(6)
stack.print_stack()
stack.pop()
stack.print_stack()
print stack.size
print "top: "+str(stack.peek())
print stack.size
''' |
0bd2a4006643ef1a0955fa89137bc9dc280efecc | KurinchiMalar/DataStructures | /DynamicProgramming/CountOccurenceOfStringInAnotherString.py | 1,821 | 3.90625 | 4 | '''
Given two strings S and T, give an algorithm to find the number of times S appears in T. It's not compulsory that all the
characters of S should appear contiguous to T.
eg) S = ab and T = abadcb ---> ab is occuring 2 times in abadcb.
'''
'''
Algorithm:
if dest[i-1] == source[j-1]:
T[i][j] = T[i][j-1] + T[i-1][j]
else:
T[i][j] = T[i][j-1]
If same --> a b a
a
b x y
x indicates how many times ab occurs in ab substring of aba.
y indicates how many times ab occurs in aba
Logic --> if equal --> left + top ( how many times a has occured till now(top) + how many times ab has appeared (left) )
if not equal --> copy the left alone.
'''
# Time Complexity : O(n1 * n2)
# Space Complexity : O(n1 * n2)
def count_number_of_times_dest_in_source(source,dest):
n1 = len(source)
n2 = len(dest)
T= [[0]*(n1+1) for x in range(n2+1)]
#T[0][0] = 1 # since searching \0 in \0 is 1
i = 1 # starting from 1 for the above reason
j = 0
#print T
while i <= n2: # dest
T[i][0] = 0 # if source string is empty, then nothing to check.
i = i + 1
while j <= n1: # source
T[0][j] = 1 # /0 in dest , will be available in non empty source.
j = j + 1
#print T
for i in range(1,n2+1):
for j in range(1,n1+1):
if dest[i-1] == source[j-1]:
T[i][j] = T[i][j-1] + T[i-1][j]
else:
T[i][j] = T[i][j-1]
print T
return T[n2][n1]
#source = "geeksforgeeks"
#dest = "geek"
source = "abadcb"
dest = "ab"
source = "ababab"
dest ="ab"
#print source.count(dest)
print "Number of times : "+str(dest)+" appears in : "+str(source)+" is :"+str(count_number_of_times_dest_in_source(list(source),list(dest))) |
ace208de8edd92accd7286e73e99b99c89c1eadc | KurinchiMalar/DataStructures | /DynamicProgramming/LongestIncreasingSubsequence.py | 2,826 | 3.90625 | 4 | '''
Given an array find longest increasing subsequence in this array.
https://www.youtube.com/watch?v=CE2b_-XfVDk
'''
# Time Complexity : O(n*n)
# Space Complexity : O(n)
def get_length_of_longest_increasing_subsequence(Ar):
n = len(Ar)
T = [1]*(n)
#print T
for i in range(1,n):
for j in range(0,i):
if Ar[j] < Ar[i]:
T[i] = max(T[i],T[j]+1) # i contributes to 1 and till now how many increasing in T[j] ==> 1+T[j]
# if T[i] has a bigger number, occurence of -1 should not be reducing it, so see a max...
#print T
max_subseq_len = T[0]
for i in range(1,n):
if T[i] > max_subseq_len:
max_subseq_len = T[i]
return max_subseq_len
def do_binary_search(Ar,T,end,elem):
start = 0
while start <= end:
if start == end:
return start+1
middle = (start+end)//2
if middle < end and Ar[T[middle]] <= elem and elem <= Ar[T[middle+1]]:
return middle + 1 # we are returning the ceil...
elif Ar[T[middle]] < elem:
start = middle+1
else:
end = middle -1
return -1
# https://www.youtube.com/watch?v=S9oUiVYEq7E
# Time Complexity : O(nlogn)
# Space Complexity : O(n)
def longest_increasing_subsequence_nlogn(Ar):
n = len(Ar)
T = [0] * (n)
R = [-1] * (n)
res_length = 0
# if greater append
# if less replace
for i in range(1,len(Ar)):
if Ar[i] > Ar[T[res_length]]: # append
R[i] = T[res_length]
res_length = res_length + 1
T[res_length] = i
else: # replace
if Ar[i] <= Ar[T[0]]:
T[0] = i
else: # should be between 0 and res_len
ceil_index = do_binary_search(Ar,T,res_length,Ar[i])
#print "ceil for : "+str(Ar[i])+" is :"+str(ceil_index)
T[ceil_index] = i # found the place to put i
R[i] = T[ceil_index-1] # put the mapping for i in result.
#print R
#print T
#print res_length # holds the end index of T list. Hence the actual length will be res_length + 1
# to print the sequence..
index = T[res_length]
result = []
result.insert(0,Ar[index])
while index >= 0:
if R[index] == -1:
break
else:
result.insert(0,Ar[R[index]])
index = R[index]
return res_length+1,result
Ar = [3,4,-1,0,6,2,3]
Ar = [3,4,-1,5,8,2,3,12,7,9,10]
print "length of longest incr subseq O(n*n): "+str(get_length_of_longest_increasing_subsequence(Ar))
print
length,result = longest_increasing_subsequence_nlogn(Ar)
print "length of longest increasing subseq O(nlogn) :"+str(length)
print "longest increasing subseq O(nlogn) :"+str(result) |
bd92e67855f505019f17694631ca04db74aa3fc4 | KurinchiMalar/DataStructures | /lcaBT.py | 1,309 | 3.71875 | 4 | # Time Complexity : O(n)
class BTNode:
def __init__(self,data):
self.data = data
self.left = None
self.right = None
def isNodePresentBT(root, node):
if node == None:
return True
if root == None:
return False
if root == node:
return True
return isNodePresentBT(root.left, node) or isNodePresentBT(root.right, node)
def lca_bt(root, a, b):
if root == None:
return None
if root == a or root == b:
return root
isAOnLeft = isNodePresentBT(root.left, a)
isBOnLeft = isNodePresentBT(root.left, b)
if isAOnLeft != isBOnLeft:
return root
if isAOnLeft == True and isBOnLeft == True:
return lca_bt(root.left, a, b)
return lca_bt(root.right, a, b)
def util(root, a, b):
if (not isNodePresentBT(root, a)) or (not isNodePresentBT(root, b)):
return None
if a.data < b.data:
return lca_bt(root, a, b)
return lca_bt(root, b, a)
root = BTNode(1)
two = BTNode(2)
three = BTNode(2)
four = BTNode(4)
five = BTNode(5)
six = BTNode(6)
seven = BTNode(7)
eight = BTNode(8)
root.left = two
root.right = three
two.left = four
two.right = five
three.left = six
three.right = seven
seven.right = eight
lca = util(root,four,five)
print(str(lca.data))
|
61aca3793e81011ff08632c1b110e7fe4a7b7e7d | KurinchiMalar/DataStructures | /LinkedLists/Stack.py | 1,133 | 4.0625 | 4 |
import ListNode
class Stack:
def __init__(self,head=None):
self.head = None
self.size = 0
def print_stack(self):
current = self.head
while current != None:
print current.get_data(),
current = current.get_next()
print
#return self.size
def push(self,data):
newnode = ListNode.ListNode(data)
newnode.set_next(self.head)
self.head = newnode
self.size = self.size + 1
def pop(self):
if self.head is None:
print "Nothing to pop. Stack is empty!"
return -1
toremove = self.head
self.head = self.head.get_next()
self.size = self.size - 1
return toremove
def peek(self):
if self.head is None:
print "Nothing to peek!. Stack is empty!"
return -1
return self.head.get_data()
'''stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3)
stack.push(4)
stack.push(5)
print "Printing: "+str(stack.print_stack())
stack.pop()
print "Printing: "+str(stack.print_stack())
print "Peek: "+str(stack.peek())'''
|
98783f5bfd44ae9259f05242baaac5ff796008e5 | KurinchiMalar/DataStructures | /Searching/SeparateOddAndEven.py | 799 | 4.25 | 4 | '''
Given an array A[], write a function that segregates even and odd numbers.
The functions should put all even numbers first and then odd numbers.
'''
# Time Complexity : O(n)
def separate_even_odd(Ar):
even_ptr = 0
odd_ptr = len(Ar)-1
while even_ptr < odd_ptr:
while even_ptr < odd_ptr and Ar[even_ptr] % 2 == 0:
even_ptr = even_ptr + 1
while even_ptr < odd_ptr and Ar[odd_ptr] % 2 == 1:
odd_ptr = odd_ptr -1
# now odd and even are positioned appropriately.
#if Ar[odd_ptr] % 2 == 0 and Ar[even_ptr] % 2 == 1:
Ar[odd_ptr],Ar[even_ptr] = Ar[even_ptr],Ar[odd_ptr]
odd_ptr = odd_ptr-1
even_ptr = even_ptr+1
return Ar
Ar = [12,34,45,9,8,90,3]
#Ar = [1,2]
print ""+str(separate_even_odd(Ar)) |
c407defd7ab9eef69e27f3ca7134e49d068962b0 | KurinchiMalar/DataStructures | /LinkedLists/PalindromeOrNot.py | 3,930 | 4.1875 | 4 | '''
Give a function to check if linked list is palindrome or not.
'''
import ListNode
import Stack
def reverse_recursive(node):
if node == None:
return
if node.get_next() == None:
head = node
return node
head = reverse_recursive(node.get_next())
node.get_next().set_next(node)
node.set_next(None)
return head
def get_middle_node(node):
prev_tort = node
tort = node
hare = node
while hare != None and hare.get_next() != None:
prev_tort = tort
tort = tort.get_next()
hare = hare.get_next().get_next()
# Let's return middle node, start of next list
# for odd list tort will be the middle node.
if hare != None: # odd list.
return tort,tort.get_next()
else: # for even list prev_tort will be the middle node.
return prev_tort,tort
def compare_lists(list1,list2):
temp1 = list1
temp2 = list2
while temp1 != None and temp2 != None:
if temp1.get_data() != temp2.get_data():
return 0
temp1 = temp1.get_next()
temp2 = temp2.get_next()
if temp1 == None and temp2 == None:
return 1
return 0
# Time Complexity : O(n)
# Space Complexity : O(1)
def chec_pali(node):
if node == None:
return 1
if node.get_next() == None:
return 1
prev_tort = node
tort = node
hare = node
while hare != None and hare.get_next() != None:
prev_tort = tort
tort = tort.get_next()
hare = hare.get_next().get_next()
if hare != None: # for odd list tort will be the middle node. so secondhalf starting will be tort.get_next()
middle_node = tort
tort = tort.get_next()
else: # for even list prev_tort will be the middle node. so secondhalf starting will be tort.
middle_node = None
prev_tort.set_next(None) # breaking firsthalf
tort = reverse_recursive(tort) # reversing second half
print "Comparing .... "
traverse_list(node)
traverse_list(tort)
result = compare_lists(node,tort) # comparing
if middle_node != None: # resetting odd list.
prev_tort.set_next(middle_node)
middle_node.set_next(reverse_recursive(tort))
else:
prev_tort.set_next(reverse_recursive(tort))
#traverse_list(node)
return result
def traverse_list(node):
current = node
count = 0
while current != None:
print current.get_data(),
count = count + 1
current = current.get_next()
print
# Time Complexity : O(n)
# Space Complexity : O(n)
def chec_pali_stackmethod(node):
if node == None:
return 1
if node.get_next() == None:
return 1
stack = Stack.Stack()
prev_tort = node
tort = node
hare = node
while hare != None and hare.get_next() != None:
prev_tort = tort
tort = tort.get_next()
hare = hare.get_next().get_next()
if hare != None: # odd list
topush = tort.get_next()
else:
topush = tort
while topush != None:
stack.push(topush.get_data())
topush = topush.get_next()
print "stack"
stack.print_stack()
print stack.size
current = node
while stack.size > 0:
if current.get_data() != stack.peek():
return -1
current = current.get_next()
stack.pop()
return 1
head = ListNode.ListNode(1)
#print ListNode.ListNode.__str__(head)
n1 = ListNode.ListNode(2)
n2 = ListNode.ListNode(3)
n3 = ListNode.ListNode(4)
n4 = ListNode.ListNode(3)
n5 = ListNode.ListNode(2)
n6 = ListNode.ListNode(1)
#orig_head = ListNode.ListNode(1)
#orig_head.set_next(n1)
head.set_next(n1)
n1.set_next(n2)
n2.set_next(n3)
n3.set_next(n4)
n4.set_next(n5)
n5.set_next(n6)
traverse_list(head)
#head1 = reverse_recursive(head)
#print "isPalindrome: "+str(chec_pali(head))
print "isPalindrome stackmethod: "+str(chec_pali_stackmethod(head))
|
c0a0d05abe2be7af0b67b81d46002b4b8cdcbd40 | KurinchiMalar/DataStructures | /LinkedLists/OddFirstThenEven.py | 2,091 | 4.03125 | 4 | __author__ = 'kurnagar'
import ListNode
'''
Segregate a link list to put odd nodes in the beginning and even behind
'''
# Time Complexity : O(n)
# Space Complexity : O(1)
def swap_values_nodes(node1,node2):
temp = node1.get_data()
node1.set_data(node2.get_data())
node2.set_data(temp)
def segregate_odd_and_even(node):
if node == None:
return node
if node.get_next() == None:
return node
oddptr = node
evenptr = oddptr.get_next()
while oddptr != None and evenptr != None:
while oddptr != None and oddptr.get_data() % 2 != 0:
if oddptr.get_data() % 2 == 0: # found even location.
#oddptr = current
break
oddptr = oddptr.get_next()
if oddptr == None:
return node
evenptr = oddptr.get_next()
while evenptr != None and evenptr.get_data() % 2 == 0:
if evenptr.get_data() % 2 != 0: # found odd location
#evenptr = current
break
evenptr = evenptr.get_next()
if evenptr == None:
return node
print "oddptr: "+str(ListNode.ListNode.__str__(oddptr))
print "evenptr: "+str(ListNode.ListNode.__str__(evenptr))
swap_values_nodes(oddptr,evenptr)
oddptr = oddptr.get_next()
evenptr = evenptr.get_next()
return node
def traverse_list(node):
current = node
count = 0
while current != None:
print current.get_data(),
count = count + 1
current = current.get_next()
print
head = ListNode.ListNode(12)
#print ListNode.ListNode.__str__(head)
n1 = ListNode.ListNode(92)
n2 = ListNode.ListNode(32)
n3 = ListNode.ListNode(12)
n4 = ListNode.ListNode(19)
n5 = ListNode.ListNode(8)
n6 = ListNode.ListNode(7)
#orig_head = ListNode.ListNode(1)
#orig_head.set_next(n1)
head.set_next(n1)
n1.set_next(n2)
n2.set_next(n3)
n3.set_next(n4)
n4.set_next(n5)
n5.set_next(n6)
traverse_list(head)
#swap_values_nodes(n5,n6)
#traverse_list(head)
head1 = segregate_odd_and_even(head)
traverse_list(head1)
|
2661ddc368e29f81cb002a4a5c413580f227d284 | KurinchiMalar/DataStructures | /Searching/CountOccurence.py | 1,957 | 3.953125 | 4 | '''
Given a sorted array of n elements, possibly with duplicates. Find the number of occurrences of a number.
'''
# BruteForce
# Time Complexity - O(n)
from FirstAndLastOccurence import find_first_occurence,find_last_occurence
def count_occurence_bruteforce(Ar,k):
count = 0
for i in range(0,len(Ar)):
if Ar[i] == k:
count = count + 1
return count
def do_binary_search(Ar,low,high,elem):
if low == high:
if Ar[low] == elem:
return low
if low+1 == high:
if Ar[low] == elem:
return low
if Ar[high] == elem:
return high
while low < high:
middle = (low+high) // 2
if Ar[middle] == elem:
return middle
if Ar[middle] > elem:
return do_binary_search(Ar,low,middle,elem)
else:
return do_binary_search(Ar,middle+1,high,elem)
# BinarySearch + Scan
# Time Complexity : O(log n) + S ...where S is the number of occurences of the data.
def count_occurence_binarysearch(Ar,k):
searched_index = do_binary_search(Ar,0,len(Ar)-1,k)
count = 1
for i in range(searched_index-1,-1,-1):
if Ar[i] != k:
break
count = count + 1
for j in range(searched_index+1,len(Ar)):
if Ar[j] != k:
break
count = count + 1
print "The number "+str(k)+"occured:"+str(count)+"times..."
return count
# With First and Last Occurence
# Time Complexity = O(log n) + O(log n) = O(log n)
def count_occurence_withfirstandlast(Ar,k):
first_occur = find_first_occurence(Ar,0,len(Ar)-1,k)
last_occur = find_last_occurence(Ar,0,len(Ar)-1,k)
return (last_occur-first_occur)+1
Ar = [1,3,3,3,6,6,7]
#Ar = [1,2,3,4,5,6,7]
#print ""+str(do_binary_search(Ar,0,len(Ar)-1,7))
#print ""+str(count_occurence_bruteforce(Ar,6))
#print ""+str(count_occurence_binarysearch(Ar,6))
print ""+str(count_occurence_withfirstandlast(Ar,1)) |
30a81157968dcd8771db16cf6ac48e9cd235d713 | KurinchiMalar/DataStructures | /Stacks/InfixToPostfix.py | 2,664 | 4.28125 | 4 | '''
Consider an infix expression : A * B - (C + D) + E
and convert to postfix
the postfix expression : AB * CD + - E +
Algorithm:
1) if operand
just add to result
2) if (
push to stack
3) if )
till a ( is encountered, pop from stack and append to result.
4) if operator
if top of stack has higher precedence
pop from stack and append to result
push the current operator to stack
else
push the current operator to stack
'''
# Time Complexity : O(n)
# Space Complexity : O(n)
import Stack
def get_precedence_map():
prec_map = {}
prec_map["*"] = 3
prec_map["/"] = 3
prec_map["+"] = 2
prec_map["-"] = 2
prec_map["("] = 1
return prec_map
def convert_infix_to_postfix(infix):
if infix is None:
return None
prec_map = get_precedence_map()
#print prec_map
opstack = Stack.Stack()
result_postfix = []
for item in infix:
print "--------------------------item: "+str(item)
# if operand just add it to result
if item in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or item in "0123456789":
print "appending: "+str(item)
result_postfix.append(item)
opstack.print_stack()
# if "(" just push it to stack
elif item == "(":
opstack.push(item)
opstack.print_stack()
# add to result upto open brace
elif item == ")":
top_elem = opstack.pop()
while top_elem.get_data() != "(" and opstack.size > 0:
print "appending: "+str(top_elem.get_data())
result_postfix.append(top_elem.get_data())
top_elem = opstack.pop()
opstack.print_stack()
#result_postfix.append(top_elem) # no need to append paranthesis in result.
else:
# should be an operator
while opstack.size > 0 and prec_map[opstack.peek()] >= prec_map[item]:
temp = opstack.pop()
print "appending: "+str(temp.get_data())
result_postfix.append(temp.get_data())
opstack.push(item) # after popping existing operator , push the current one. (or) without popping just push. based on the precedence check.
opstack.print_stack()
#print result_postfix
while opstack.size != 0:
result_postfix.append(opstack.pop().get_data())
return result_postfix
infixstring = "A*B-(C+D)+E"
infix = list(infixstring)
postfix = convert_infix_to_postfix(infix)
postfix = "".join(postfix)
print "Postfix for :"+str(infixstring)+" is : "+str(postfix)
|
982e3cb81b9a194b629434923943f919b3e36ab8 | KurinchiMalar/DataStructures | /LinkedLists/floyd_LoopLinkList.py | 3,145 | 4.125 | 4 | __author__ = 'kurnagar'
import ListNode
# Time Complexity : O(n)
# Space Complexity : O(n) for hashtable
def check_if_loop_exits_hashtable_method(node):
if node == None:
return -1
hash_table = {}
current = node
while current not in hash_table:
hash_table[current] = current.get_data()
current = current.get_next()
#print hash_table
if current in hash_table:
print "Loop at: "+ListNode.ListNode.__str__(current)
return 1
'''
Floyd's Cycle Finding Algorithm
'''
# Time Complexity : O(n)
# Space Complexity : O(1)
def check_if_loop_exits_and_return_loopnode_and_lengthofloop(node):
if node == None:
return -1,None,-1
tort = node
hare = node
while tort and hare and hare.get_next():
tort = tort.get_next()
hare = hare.get_next().get_next()
if tort == hare:
print "tort and hare met at: "+str(ListNode.ListNode.__str__(tort))
#return 1
break
if tort != hare:
return -1,None # noloop
meeting_point = tort # will be useed for length of loop and remove loop
# To find the loop node
# Bring tort to beginning
tort = node
print "tort:"+str(tort.get_data())
print "hare:"+str(hare.get_data())
while tort != hare:
tort = tort.get_next()
hare = hare.get_next()
loopnode = tort
# To find length of loop
length_of_the_loop = 1 # current meeting point is 1.
tort = meeting_point
hare = tort.get_next()
while tort != hare:
length_of_the_loop = length_of_the_loop + 1
hare = hare.get_next()
return 1,loopnode,length_of_the_loop,meeting_point
def traverse_list(node):
current = node
count = 0
while current != None:
print current.get_data(),
count = count + 1
current = current.get_next()
print
return count
# Time Complexity : O(n)
# Space Complexity : O(1)
def remove_loop(node,loopnode,meeting_point):
current = meeting_point
while current.get_next() != loopnode:
current = current.get_next()
if current.get_next() == loopnode:
current.set_next(None)
return node
head = ListNode.ListNode(1)
#print ListNode.ListNode.__str__(head)
n1 = ListNode.ListNode(2)
n2 = ListNode.ListNode(3)
n3 = ListNode.ListNode(4)
n4 = ListNode.ListNode(5)
n5 = ListNode.ListNode(6)
n6 = ListNode.ListNode(7)
#orig_head = ListNode.ListNode(1)
#orig_head.set_next(n1)
head.set_next(n1)
n1.set_next(n2)
n2.set_next(n3)
n3.set_next(n4)
n4.set_next(n5)
n5.set_next(n6)
n6.set_next(n2) # loop set here
print "HashTable method : is loop exists: "+str(check_if_loop_exits_hashtable_method(head))
isloop_exists,loopnode,length_of_loop,meeting_point = check_if_loop_exits_and_return_loopnode_and_lengthofloop(head)
print "Check if loop exists: "+str(isloop_exists)
print "Meeting point: "+str(meeting_point)
print "Loop node :"+str(ListNode.ListNode.__str__(loopnode))
print "Length of loop: "+str(length_of_loop)
head = remove_loop(head,loopnode,meeting_point)
print "Removed loop:"+str(traverse_list(head))
|
22f1d817b2d292a4b3fae09a77e3013b9d45bd31 | KurinchiMalar/DataStructures | /Sorting/NearlySorted_MergeSort.py | 1,528 | 4.125 | 4 | #Complexity O(n/k * klogk) = O(nlogk)
# merging k elements using mergesort = klogk
# every n/k elem group is given to mergesort
# Hence totally O(nlogk)
'''
k = 3
4 5 9 | 7 8 3 | 1 2 6
1st merge sort all blocks
4 5 9 | 3 8 9 | 1 2 6
Time Complexity = O(n * (n/k) log k)
i.e to sort k numbers is k * log k
to sort n/k such blocks = (n/k) * k log k = n log k
2nd start merging two blocks at a time
i.e
to merge k + k elements 2k log k
to merge 2k + k elements 3k log k
similarly it has to proceed until qk + k = n, so it becomes n log k
where q = (n/k) - 1
'''
from MergeSort import mergesort
def split_into_groups_of_size_k(Ar,k):
r = []
for j in range(0,(len(Ar)/k)+1):
start = k * j
end = start + k
if start >= len(Ar):
break
if end >=len(Ar) and start < len(Ar):
r.append(Ar[start:end])
break
#print "start,end = "+str(start)+","+str(end)
r.append( Ar[start:end])
#print r[j]
return r
def merge_two_lists(list1,list2):
list1.extend(list2)
return list1
Ar = [6,9,10,1,2,3,5]
Ar = [8,9,10,1,2,3,6,7]
Ar = [8,9,10,1,2,3]
print Ar
split_blocks = split_into_groups_of_size_k(Ar,3)
print str(split_blocks)
for i in range(0,len(split_blocks)):
mergesort(split_blocks[i])
print "Sorted blocks:" +str(split_blocks)
while len(split_blocks) > 1 :
split_blocks[1] = merge_two_lists(split_blocks[0],split_blocks[1])
split_blocks.pop(0)
mergesort(split_blocks[0])
print str(split_blocks)
|
6d878bd6ab1e0dbecb0c2a5a2803ee41359b51b8 | KurinchiMalar/DataStructures | /LinkedLists/MergeZigZagTwoLists.py | 2,040 | 4.15625 | 4 | '''
Given two lists
list1 = [A1,A2,.....,An]
list2 = [B1,B2,....,Bn]
merge these two into a third list
result = [A1 B1 A2 B2 A3 ....]
'''
# Time Complexity : O(n)
# Space Complexity : O(1)
import ListNode
import copy
def merge_zigzag(node1,node2,m,n):
if node1 == None or node2 == None:
return node1 or node2
p = node1
q = p.get_next()
r = node2
s = r.get_next()
while q != None and s != None:
p.set_next(r)
r.set_next(q)
p = q
if q != None:
q = q.get_next()
r = s
if s != None:
s = s.get_next()
if q == None:
p.set_next(r)
if s == None:
p.set_next(r)
r.set_next(q)
return node1
def get_len_of_list(node):
current = node
count = 0
while current != None:
#print current.get_data(),
count = count + 1
current = current.get_next()
#print
return count
def traverse_list(node):
current = node
count = 0
while current != None:
print current.get_data(),
count = count + 1
current = current.get_next()
print
head1 = ListNode.ListNode(1)
#print ListNode.ListNode.__str__(head)
n1 = ListNode.ListNode(3)
n2 = ListNode.ListNode(5)
n3 = ListNode.ListNode(7)
n4 = ListNode.ListNode(9)
n5 = ListNode.ListNode(10)
n6 = ListNode.ListNode(12)
head2 = ListNode.ListNode(2)
m1 = ListNode.ListNode(4)
m2 = ListNode.ListNode(6)
m3 = ListNode.ListNode(8)
m4 = ListNode.ListNode(11)
m5 = ListNode.ListNode(14)
m6 = ListNode.ListNode(19)
head1.set_next(n1)
n1.set_next(n2)
n2.set_next(n3)
n3.set_next(n4)
n4.set_next(n5)
n5.set_next(n6)
head2.set_next(m1)
m1.set_next(m2)
m2.set_next(m3)
m3.set_next(m4)
m4.set_next(m5)
m5.set_next(m6)
orig_head1 = copy.deepcopy(head1)
orig_head2 = copy.deepcopy(head2)
traverse_list(head1)
traverse_list(head2)
m = get_len_of_list(head1)
n = get_len_of_list(head2)
result = merge_zigzag(head1,head2,m,n)
print "RESULT:"
traverse_list(result)
|
d1c079ea514b668ac8e2ca32afbaa2aa171754d0 | kwichmann/euler | /pe012.py | 437 | 3.6875 | 4 | def factor_count(n):
count = 0
for i in range(1, n + 1):
if n % i == 0:
count += 1
return count
def triangle(n):
return int(n * (n + 1) / 2)
num = 1
while True:
if num % 2 == 0:
fac = factor_count(int(num / 2)) * factor_count(num + 1)
else:
fac = factor_count(int((num + 1)/ 2)) * factor_count(num)
if fac > 500:
print(triangle(num))
quit()
num += 1
|
f4726dd533c9efdff032b1e5d3b8589b7469d56f | kwichmann/euler | /pe003.py | 505 | 3.53125 | 4 | num = 600851475143
def divides(n, p):
return n % p == 0
def divides_list(n, l):
for p in l:
if divides(n, p):
return True
return False
def next_prime(l):
counter = max(l) + 1
while divides_list(counter, l):
counter += 1
return counter
cur_prime = 2
prime_list = [2]
while num != 1:
while divides(num, cur_prime):
print(cur_prime)
num /= cur_prime
cur_prime = next_prime(prime_list)
prime_list.append(cur_prime)
|
3304d188c15ebea8b0f4f7d4846e90c1dbd9420c | cdpn/htb-challenges | /misc/eternal-loop/unzip-loop.py | 811 | 3.71875 | 4 | #!/usr/bin/env python3
import zipfile
zip_file = "Eternal_Loop.zip"
password = "hackthebox"
# Take care of the first zip file since password won't be the filename inside
with zipfile.ZipFile(zip_file) as zr:
zr.extractall(pwd = bytes(password, 'utf-8'))
# namelist() returns an array, so take the first index to get the filename
zip_file = zr.namelist()[0]
# print(zip_file)
while True:
with zipfile.ZipFile(zip_file) as zr:
# gets a list of all the files within the zip archive
for files in zr.namelist():
password = files.split(".")[0]
print(f"Now extracting {zip_file} with the password of: {password}")
# unzip p/w protected zip with filename of zip inside
zr.extractall(pwd = bytes(password, 'utf-8'))
zip_file = files
|
c1bb89404de014f6a188d04c61ba6bc32f68a4f4 | slw2/library-python | /Books.py | 1,710 | 3.734375 | 4 | from Book import Book
import random
class Books:
database = ""
def __init__(self, database):
self.database = database
def books(self):
self.database.cursor.execute('''SELECT title, author, code FROM books''')
allrows = self.database.cursor.fetchall()
list_of_books = []
for row in allrows:
newBook = Book()
newBook.init(row[0], row[1], row[2])
list_of_books.append(newBook)
return list_of_books
def booksearch_by_title(self, title):
bookList = self.books()
books_with_title = []
for book in bookList:
if book.title == title:
books_with_title.append(book)
return books_with_title
def booksearch_by_author(self, author):
bookList = self.books()
books_by_author = []
for book in bookList:
if book.author == author:
books_by_author.append(book)
return books_by_author
def booksearch_by_code(self, code):
bookList = self.books()
for book in bookList:
if book.code == code:
return book
return False
def add_book(self, title, author):
code = random.randint(1, 1000)
while self.booksearch_by_code(code) != False:
code = random.randint(1, 1000)
self.database.cursor.execute('''INSERT INTO books(title, author, code)
VALUES(?,?,?)''', (title, author, code))
self.database.db.commit()
def remove_book(self, book):
self.database.cursor.execute('''DELETE FROM books WHERE code = ? ''', (book.code,))
self.database.db.commit() |
36e1619c70ac8f322aaa1ac085dc3c9c3e61f099 | slw2/library-python | /LoanController.py | 2,356 | 3.921875 | 4 | class LoanController:
books = ""
users = ""
loans = ""
def __init__(self, books, users, loans):
self.books = books
self.users = users
self.loans = loans
def borrow(self, book_code, user_code):
book = self.books.booksearch_by_code(book_code)
user = self.users.usersearch_by_code(user_code)
if not book:
print("The book code does not match any books")
elif not user:
print("The user code does not match any users")
elif book in self.loans.loans(user):
print("You have already taken this book out")
elif not self.loans.borrow(book, user):
print("This book is already on loan")
else:
self.loans.borrow(book, user)
print("You have successfully borrowed a book!")
def return_book(self, book_code):
book = self.books.booksearch_by_code(book_code)
if not book:
print("The book code does not match any books")
else:
self.loans.return_book(book)
print("You have successfully returned the book!")
def user_loans(self, user_code):
user = self.users.usersearch_by_code(user_code)
if not user:
print("The user code does not match any users")
on_loan = self.loans.loans(user)
if on_loan == []:
print("You have no books on loan")
else:
print("These are your loans: ")
for book in on_loan:
book.print()
def print_books_loaned(self):
books_loaned = self.loans.books_loaned()
if books_loaned == []:
print("There are currently no books on loan")
else:
for book in books_loaned:
book.print()
def print_books_not_loaned(self):
books_not_loaned = self.loans.books_not_loaned()
if books_not_loaned == []:
print("There are no books currently available in the library")
else:
for book in books_not_loaned:
book.print()
def print_users_with_loans(self):
users_with_loans = self.loans.users_with_loans()
if users_with_loans == []:
print("There are currently no users with loans")
else:
for user in users_with_loans:
user.print() |
228ee138bdc254c9cb229ae19fb4432dadb2e43c | yeyifu/python | /other/set.py | 621 | 4.03125 | 4 | #集合的创建:1.初始化{1,2,3},2.set()函数声明
#特点:无序,无下标,去重
# set = {10, 20, 30, 40, 50, 10}
# print(set)
#增加
# set1 = {10,20}
# set1.add(30) #增加单一数据
# print(set1)
#
# set1.update([5,6,9,5]) #追加数据序列
# print(set1)
#删除
# set2 = {10,20,30,40,50}
# set2.remove(10) #删除不存在的值则报错
# print(set2)
# set2.discard(20)
# print(set2)
#
# set2.pop() #随机删除,返回删除值
# print(set2)
#查找,判断是否在集合里
# set4 = {10,20,30,40,50}
# print(10 in set4)
# if 80 in set4:
# print('yes')
# else:
# print('no')
|
b61a043aedd39dc9120e0b4066327d0095979556 | yeyifu/python | /other/function.py | 602 | 3.90625 | 4 | # 定义函数说明文档
def info_print():
"""函数说明文档"""
print(1+2)
info_print()
# 查看函数文档
help(info_print)
# 一个函数返回多个值
def return_num():
# return 1, 3 #返回的是元组(默认)
# return(10,20) #返回的是元组
# return[10,20] #返回的是列表
return {'name':'python','age':'30'} #返回的是字典
print(return_num())
#函数的参数
# 1.位置参数:传递和定义参数的顺序及个数必须一致
def user_info(name,age,add):
print(f'我叫{name},今年{age}岁,来自{add}')
user_info('yyf',20,'china') |
2a5e1828f8e2bc9f46274bd166d3f566f0225d22 | yeyifu/python | /other/test.py | 1,561 | 3.75 | 4 | # import sys
# print(sys.argv)
# num1 = 1
# num2 = 1.1
# print(type(num2))
# name = 'tom'
# age = 18
# weight = 55.5
# stu_id = 2
# print('我叫%s,学号是%.10d,今年%d岁,体重%.2f' % (name, stu_id, age, weight))
# print(f'我叫{name},学号是{stu_id}')
# print('hello\nworld')
# print('hello\tworld')
# print('hello', end='\t')
# print('world')
#输入
# str = input('请输入字符:')
# print(str)
#数据转换
# str = input(f'请输入:')
# print(type(str))
# num = int(str)
# print(type(num))
# print(float(str, 2))
#eval()
# str1 = '4'
# print(type(eval(str1)))
# str = input('请输入年龄:')
# if int(str) < 18:
# print('童工')
# elif 18 <= int(str) <= 60:
# print('合法')
# else:
# print('年龄过大')
# import random
# print(random.randint(1,3))
# i=1
# while i<10:
# print(i)
# i = i+1
# str = '01234545678'
# print(str[1:8:2])
# print(str[-1:1:-1])
# print(str.find('34'))
# print(str.count('45',4,10))
# print(str.find('45'))
# print(str.count('45'))
str = ' hello World and itcast and itheima and pythoN'
str3 = 'df34d6f'
num='123456'
# print(str.replace('and','he'))
# print(str.split('and',3))
str1 = ['hello world ', ' itcast ', ' itheima ', ' python']
str2 = ''.join(str1)
# print(str2)
# print(''.join(str1).replace(' ',''))
# print(str.capitalize())
# print(str.title())
# print(str.lower())
# print(str.strip())
# # str.ljust()
# # str.rjust()
# # str.center()
#
# print(str.startswith(''))
# print(str.endswith('n'))
# print(str.isalpha())
# print(num.isdigit())
print(str3.isalnum())
|
10b994ebf775a1ad965e7522fae132d5bdc1e1ee | colorfulComeMonochrome/data_analysis | /matplotlib/fish.py | 555 | 3.546875 | 4 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
imdata = plt.imread('fish.png')
# 数据变换
# mydata = np.random.rand(100*100*3).reshape(100,100,3)
# mydata = np.ones(100*100*3).reshape(100,100,3)
mydata = np.zeros(100*100*3).reshape(100,100,3)
# mydata = mydata + np.array([1, 0, 0])
mydata = mydata + np.array([0.5, 0.3, 0.7])
# print(imdata)
# print(imdata.shape)
# plt.imshow(imdata[:, :, ::-1])
# plt.imshow(imdata[::50, ::50, ::])
plt.imshow(mydata)
plt.show()
|
c10b5596458ddc22d97f6dd93968adf9e7766833 | HyunAm0225/Python_Algorithm | /study/programmers/kakao_dart_game.py | 1,163 | 3.625 | 4 | from collections import deque
dartResult = input()
dartque = deque(dartResult)
point = []
def check_dart_point(dartque,point):
index = -1
while dartque:
data = dartque.popleft()
if data.isnumeric():
if data =="0" and index== -1:
point.append(int(data))
index +=1
elif data == "0":
if point[index] == 1:
point[index] = 10
else:
point.append(int(data))
index +=1
else:
point.append(int(data))
index +=1
else:
if data == "S":
point[index] **=1
elif data == "D":
point[index] **=2
elif data == "T":
point[index] **=3
elif data == "#":
point[index] *=(-1)
else:
if index == 0:
point[index] *=2
else:
point[index-1] *=2
point[index] *=2
print(point)
return point
print(sum(check_dart_point(dartque,point)))
|
ad9b99eef4faff4186c37a26516e4dc085ae9060 | HyunAm0225/Python_Algorithm | /코딩테스트책/7-5.py | 687 | 3.71875 | 4 | # 이진 탐색 실전 문제
# 부품찾기
import sys
input = sys.stdin.readline
def search_binary(array,start,end,target):
while start <= end:
mid = (start + end)//2
if array[mid] == target:
return mid
elif array[mid] > target:
end = mid -1
else:
start = mid + 1
return None
n = int(input())
store = list(map(int,input().split()))
store.sort()
m = int(input())
host = list(map(int,input().split()))
for product in host:
# 해당 부품이 있는지 확인하기
result = search_binary(store,0,n-1,product)
if result != None:
print('yes', end=' ')
else:
print('no', end=' ') |
16e12fbf8289dfb9d62274ccae8196bb06849314 | HyunAm0225/Python_Algorithm | /study/9012.py | 875 | 3.65625 | 4 | # 9012
# 괄호
# 스택문제
# 테스트 케이스의 숫자를 입력받음
t = int(input())
ans = []
data = []
def check_vps(stack_list):
# pop 한 괄호를 담을 list
temp_list = []
temp_list.append(stack_list.pop())
for i in range(len(stack_list)):
# temp_list 비어있을 경우 append
if not temp_list:
temp_list.append(stack_list.pop())
# temp에는 ), stackList 는 (
elif (temp_list[-1] == ')' and stack_list[-1] =='('):
temp_list.pop()
stack_list.pop()
else:
temp_list.append(stack_list.pop())
if not temp_list:
print(temp_list)
return "YES"
else:
print(temp_list)
return "NO"
for _ in range(t):
data = list(input())
ans.append(check_vps(data))
# 결과값 출력
for i in ans:
print(i)
|
ca0de2eabb70373eccdefd891484900c21fef0fb | HyunAm0225/Python_Algorithm | /study/1181.py | 203 | 3.5625 | 4 | n = int(input())
data = []
ans = []
for _ in range(n):
data.append(input())
data.sort(key = lambda x:(len(x),x))
for x in data:
if x not in ans:
ans.append(x)
for i in ans:
print(i)
|
65f583ecf0cd952237b9dcd7130cc71a7a519177 | HyunAm0225/Python_Algorithm | /코딩테스트책/10-7.py | 889 | 3.796875 | 4 | # 팀결성 문제
# 서로소 집합 자료구조를 이용하여 구한다
def find_parent(parent,x):
if parent[x] !=x:
return find_parent(parent,parent[x])
return parent[x]
def union_parent(parent,a,b):
a = find_parent(parent,a)
b = find_parent(parent,b)
if a<b:
parent[b] = a
else:
parent[a] = b
n,m = map(int,input().split())
parent = [0] * (n+1) # 부모 테이블 초기화
# 부모 테이블 상에서, 부모를 자기 자신으로 초기화
for i in range(0,n+1):
parent[i] = i
# 각 연산을 하나씩 확인
for i in range(m):
oper,a,b = map(int,input().split())
# 합집합 (union)
if oper ==0:
union_parent(parent,a,b)
# 찾기(find) 연산 일 경우
elif oper == 1:
if find_parent(parent,a) == find_parent(parent,b):
print("YES")
else:
print("NO") |
194086367cacb0dffa9a8e996b35edfe94887754 | HyunAm0225/Python_Algorithm | /hello_coding/chap04/quick_sum.py | 180 | 3.78125 | 4 | def sum(lst):
if lst == []:
return 0
else:
print(f"sum({lst[:]}) = {lst[0]} + sum({lst[1:]})")
return lst[0] + sum(lst[1:])
print(sum([1,2,3,4,5])) |
1b1a4d3bd63310edc10c7e0add62526b041591bb | HyunAm0225/Python_Algorithm | /study/programmers/ternary.py | 443 | 3.9375 | 4 | # 3진법으로 만드는 코드
def ternary(n):
tern_list = []
ans = ''
while n > 0:
# print(f"현재 n값 : {n}")
tern_list.append(n%3)
n //=3
tern_list.reverse()
return tern_list
def solution(n):
tern_list = ternary(n)
ans = 0
for i,num in enumerate(tern_list):
num = num * (3**i)
ans += num
return ans
n = int(input())
print(ternary(n))
print(solution(n)) |
83115abfeb4394433aafa7fd291614a826743049 | HyunAm0225/Python_Algorithm | /2292.py | 265 | 3.625 | 4 | # 백준
# 백준 수학 문제
def room_count(number):
six_num = 1
count = 1
while number > six_num and number >1:
six_num+=(6*count)
count +=1
# print(f"six_num : {six_num}")
return count
n = int(input())
print(room_count(n)) |
0e08b45d1f4917cd9d4854344441c635283d683c | hucatherine7/cs362-hw4 | /test_question1.py | 451 | 3.734375 | 4 | #Unit testing question 1
import unittest
import question1
class Question1(unittest.TestCase):
def test_calcVolume(self):
#Normal test case
self.assertEqual(question1.calcVolume(4), 64)
#Negative number test case
self.assertEqual(question1.calcVolume(-1), -1)
#Wrong input type
self.assertEqual(question1.calcVolume("bad input"), -1)
if __name__ == '__main__':
unittest.main(verbosity=2)
|
40ef7592544d316ec0fe22e2d0a08e6f95e5611d | lavakin/bioinformatics_tools | /bioinf/distance.py | 1,094 | 3.875 | 4 | #!/usr/bin/env python3
from Bio import pairwise2
def editing_distance(seq1:str, seq2:str):
"""
:param seq1: sequence one
:param seq2: sequence two
:return: editing distance of two sequences along with all alignments with the maximum score
"""
align = list(pairwise2.align.globalms(seq1, seq2, 0, -1, -1, -1))
align = [list(a)[:3] for a in align]
for a in align:
a[2] = str((-1)*int(a[2]))
return align
class SequencesNotTheSameLength(Exception):
def __init__(self, message="Sequences does not have the same length"):
"""
:param message: error message
"""
self.message = message
super().__init__(self.message)
def __str__(self):
return f'{self.message}'
def hamming_distance(seq1, seq2):
"""
:param seq1: sequence one
:param seq2: sequence two
:return: hamming distance of the two sequences, if they are the same length
"""
if len(seq1) == len(seq2):
return sum(c1 != c2 for c1, c2 in zip(seq1, seq2))
else:
raise SequencesNotTheSameLength()
|
77990bea69aff99c9201bc80da4e4ede8e2e7f93 | WYHNUS/old-xirvana | /assets/Practice/practice02/skeleton/mile_to_km.py | 317 | 4.0625 | 4 | # mile_to_km.py
# Converts distance in miles to kilometers.
import sys
# main function
def main():
KMS_PER_MILE = 1.609
miles = float(raw_input("Enter distance in miles: "))
kms = KMS_PER_MILE * miles
print "That equals %9.2f km." % kms
# Runs the main method
if __name__ == "__main__":
main()
sys.exit(0)
|
f07201523a286803dafc06c5a4305451f9ea9fd9 | ibbles/HousyBuying | /Stepper.py | 6,811 | 3.859375 | 4 | from datetime import timedelta
import datetime
import calendar
class FastDateNumberList(object):
"""
This may be a bit unnecessary. It is a fixed sized, pre-allocated
DateNumberList used when running the stepper. The purpose is to avoid
reallocations inside the innermost loop, where hundreds of thousands of
appends are performed distributed over a handful of lists.
"""
endIndex = 0
"""
The index one-past the end of the populated part of the list. I.e., the
index where the next append should write.
"""
dates = None
numbers = None
def __init__(self, numItems):
self.dates = [datetime.date(1,1,1)] * numItems
self.numbers = [0.0] * numItems
def append(self, date, number):
self.dates[self.endIndex] = date
self.numbers[self.endIndex] = number
self.endIndex += 1
def appendAccumulated(self, date, number):
"""At least one call to append must have been made before calling appendAccumulated."""
self.dates[self.endIndex] = date
self.numbers[self.endIndex] = self.numbers[self.endIndex-1] + number
self.endIndex += 1
def done(self):
del self.dates[self.endIndex:]
del self.numbers[self.endIndex:]
class StepResult(object):
"""
Data container class holding the results of the stepper calculations for one
account. Contains a number of FastDateNumberLists, one for each data item
that is calculated. Some lists hold one element per day, and some one
element per month.
"""
def __init__(self, startDate, years, months, days):
self.balances = FastDateNumberList(days)
self.addedInterests = FastDateNumberList(days)
self.accumulatedIterests = FastDateNumberList(days+1)
self.accumulatedIterests.append(startDate, 0.0)
self.collectedInterests = FastDateNumberList(months)
self.accumulatedCollectedInterests = FastDateNumberList(months+1)
self.accumulatedCollectedInterests.append(startDate, 0.0)
self.savings = FastDateNumberList(months)
self.accumulatedSavings = FastDateNumberList(months+1)
self.accumulatedSavings.append(startDate, 0.0)
def addBalance(self, date, balance):
self.balances.append(date, balance)
def addInterest(self, date, interest):
self.addedInterests.append(date, interest)
self.accumulatedIterests.appendAccumulated(date, interest)
def addCollectedInterest(self, date, collectedInterest):
self.collectedInterests.append(date, collectedInterest)
self.accumulatedCollectedInterests.appendAccumulated(date, collectedInterest)
def addSaving(self, date, saving):
self.savings.append(date, saving)
self.accumulatedSavings.appendAccumulated(date, saving)
def done(self):
self.balances.done()
self.addedInterests.done()
self.accumulatedIterests.done()
self.collectedInterests.done()
self.accumulatedCollectedInterests.done()
self.savings.done()
self.accumulatedSavings.done()
class Stepper(object):
"""
Main stepper algorithm. Moves a date forward day by day and updates a number
of given accounts for each day, calculating savings and interests and such
whenever appropriate. Can send progress information to a progress listener.
"""
def __init__(self):
pass
def stepAccounts(self, accounts, startDate, endDate, progressListener):
# Worst case estimate of the number of years, months, and days that will
# be recorded. USed to preallocate result lists.
numYears = endDate.year - startDate.year + 1
numMonths = numYears * 12
numDays = numYears * 366
# Create a result object for each account.
results = []
for account in accounts:
results.append(StepResult(startDate, numYears, numMonths, numDays))
# Setup a progress bar for "long" calculations. Not sure how to determine
# that a calculation is long in the best way.
if progressListener != None:
if numYears > 10:
progressListener.progressStarted(numYears)
else:
progressListener = None
# Iterate through the dates.
date = startDate
aborted = False # The progress listener can abort the calculation. The results so far will be returned.
while date < endDate and not aborted:
# Record current balance and interests for the current day.
self.recordCurrentBalance(date, accounts, results)
self.recordInterest(date, accounts, results)
# Move to the next day.
date += timedelta(days=1)
# Special handling for every new month.
if date.day == 1:
self.recordSavings(date, accounts, results)
self.collectInterestsForLoans(date, accounts, results)
# Special handling for every new year.
if date.month == 1 and date.day == 1:
self.collectInterestsForSavingAccounts(date, accounts, results)
# Progress bar is updated on a per-year basis.
if progressListener != None:
currentYear = date.year - startDate.year
aborted = progressListener.progressUpdate(currentYear)
# Iteration is done, record final balance and truncate result lists.
self.recordCurrentBalance(date, accounts, results)
self.markAsDone(results)
# Remove progress bar.
if progressListener != None:
progressListener.progressDone()
return results
def recordCurrentBalance(self, date, accounts, results):
for index in range(0, len(accounts)):
account = accounts[index]
result = results[index]
result.addBalance(date, account.getBalance())
def recordInterest(self, date, accounts, results):
if calendar.isleap(date.year):
timeFraction = 1.0/366.0
else:
timeFraction = 1.0/365.0
for index in range(0, len(accounts)):
account = accounts[index]
result = results[index]
addedInterest = account.applyInterest(date, timeFraction)
result.addInterest(date, addedInterest)
def recordSavings(self, date, accounts, results):
for index in range(0, len(accounts)):
account = accounts[index]
result = results[index]
saving = account.addSaving(date)
result.addSaving(date, saving)
def collectInterestsForSavingAccounts(self, date, accounts, results):
for index in range(0, len(accounts)):
account = accounts[index]
result = results[index]
if not account.isLoan():
collectedInterest = account.collectInterest()
result.addCollectedInterest(date, collectedInterest)
def collectInterestsForLoans(self, date, accounts, results):
for index in range(0, len(accounts)):
account = accounts[index]
result = results[index]
if account.isLoan():
collectedInterest = account.collectInterest()
result.addCollectedInterest(date, collectedInterest)
def markAsDone(self, results):
for result in results:
result.done()
|
276faf09e77e69979004b00a910df2d0ce4c7923 | sumanthreddy07/GOST_Algorithm | /src/main.py | 2,163 | 3.65625 | 4 | #import section
import os
import argparse
from encryption import encrypt,encrypt_cbc
from decryption import decrypt,decrypt_cbc
#locate function returns the path for the txt files in the data folder
def locate(filename):
__location__ = os.path.dirname(os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__))))
return os.path.join(__location__,'data',filename)
def main(args):
print("would you like to encrypt or decrypt?")
opt = int(input("1.Encrypt 2.Decrypt: 3:EncryptCBC 4:DecryptCBC: "))
if opt==1:
encrypt( locate(args.main_file),locate(args.key_file),locate(args.encrypted_file),locate(args.decrypted_file))
elif opt==2:
decrypt( locate(args.encrypted_file),locate(args.key_file),locate(args.decrypted_file))
elif opt==3:
encrypt_cbc(locate(args.vector_file), locate(args.main_file),locate(args.key_file),locate(args.encrypted_file),locate(args.decrypted_file))
else:
decrypt_cbc(locate(args.vector_file), locate(args.encrypted_file),locate(args.key_file),locate(args.decrypted_file))
if __name__ == "__main__":
#parser arguments
parser = argparse.ArgumentParser(description='Main Script to run the code')
parser.add_argument('--main_file', type=str, default='original.txt',
help='The name of the file to be encrypted. This file must be placed in the data folder.')
parser.add_argument('--key_file', type=str, default='key.txt',
help='The key for encryption, with size = 32 Characters. This file must be placed in the data folder.')
parser.add_argument('--encrypted_file', type=str, default='encrypted.txt',
help='The name of the file to be decrypted. This file must be placed in the data folder.')
parser.add_argument('--decrypted_file', type=str, default='decrypted.txt',
help='The name of the file in which decrypted data is written. This file must be placed in the data folder.')
parser.add_argument('--vector_file', type=str, default='vector.txt',
help='The initialization vector in string format .')
args = parser.parse_args()
main(args) |
3b91de50d77f86a93f67b9da205573ca8231b874 | Shuguberu/Hello-World | /猜整数.py | 383 | 3.84375 | 4 | import random
secret=random.randint(1,10)
print("=======This is Shuguberu=======")
temp=input("输入数字")
guess=int(temp)
while guess!=secret:
temp=input("wrong,once again:")
guess=int(temp)
if guess==secret:
print("right")
else:
if guess>secret:
print("大了")
else:
print("小了")
print("over")
|
f3ab92ce7e915013dc8d62cb87d0dbbc05a16275 | mangrisano/ProjectEuler | /euler17.py | 1,646 | 4.03125 | 4 | # If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19
# letters used in total.
#
# If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used?
#
# Result: 21124
def problem():
result = 0
all_numbers = list()
one_digit_numbers = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]
two_digits_numbers = ["ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen",
"eighteen", "nineteen", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty",
"ninety"]
three_digits_numbers = ["hundred"]
for number in one_digit_numbers:
all_numbers.append(number)
for number in two_digits_numbers:
all_numbers.append(number)
if number.endswith("ty"):
for digit in one_digit_numbers:
all_numbers.append(number + digit)
for digit in one_digit_numbers:
for number in three_digits_numbers:
all_numbers.append(digit + number)
for n in one_digit_numbers:
all_numbers.append(digit + number + 'and' + n)
for n in two_digits_numbers:
all_numbers.append(digit + number + 'and' + n)
if n.endswith("ty"):
for y in one_digit_numbers:
all_numbers.append(digit + number + 'and' + n + y)
all_numbers.append("onethousand")
for number in all_numbers:
result += len(number)
return result
print problem()
|
21a192f8d31f93d63fa60d4b2b19f7e6821a171d | mangrisano/ProjectEuler | /euler6.py | 650 | 3.5625 | 4 | # The sum of the squares of the first ten natural numbers is,
#
# 12 + 22 + ... + 102 = 385
# The square of the sum of the first ten natural numbers is,
#
# (1 + 2 + ... + 10)2 = 552 = 3025
# Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum
# is 3025 - 385 = 2640.
#
# Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
#
# Answer: 25164150
def problem(n):
sum_squares = sum([i**2 for i in range(1, n + 1)])
squares_of_sum = ((n * (n + 1)) / 2)**2
return squares_of_sum - sum_squares
print(problem(100))
|
3fd420c5f119f608dda0a1bb30f6014a76a6f82a | mangrisano/ProjectEuler | /euler38.py | 1,318 | 4.03125 | 4 | # Take the number 192 and multiply it by each of 1, 2, and 3:
#
# 192 x 1 = 192
# 192 x 2 = 384
# 192 x 3 = 576
# By concatenating each product we get the 1 to 9 pandigital, 192384576.
# We will call 192384576 the concatenated product of 192 and (1,2,3)
#
# The same can be achieved by starting with 9 and multiplying by 1, 2, 3, 4, and 5, giving
# the pandigital, 918273645, which is the concatenated product of 9 and (1,2,3,4,5).
#
# What is the largest 1 to 9 pandigital 9-digit number that can be formed as the concatenated
# product of an integer with (1,2, … , n) where n > 1?
#
# Answer: 932718654
def problem(limit=10000, range_numbers=9):
max_number = 0
pandigital = 0
for number in list(range(1, limit+1)):
ispandigital, pandigital = is_pandigital(number, range_numbers)
if ispandigital:
if pandigital > max_number:
max_number = pandigital
return max_number
def is_pandigital(number, limit):
st_pandigit = ''
pandigital = '123456789'
for i in list(range(1, limit+1)):
st_pandigit += str(number * i)
if len(st_pandigit) >= 9:
break
if ''.join(sorted(st_pandigit)) == pandigital:
return True, int(st_pandigit)
return False, int(st_pandigit)
if __name__ == '__main__':
print(problem())
|
0ec6ab37481600c42bb40b7d7560afd1cfa06e67 | SubrataSarkar32/college3rdsem3035 | /class12pythoncbse-master/Chapter 6&7/studentrecord.py | 2,470 | 3.90625 | 4 | class Student:
def __init__(self,name,classs,section,rollno):
self.name=name
self.classs=classs
self.section=section
self.rollno=rollno
def __str__(self):
string='Student Name:'+str(self.name)+'\nStudent Class:'+\
str(self.classs)+'\nStudent Section:'+str(self.section)+\
'\nStudent Roll No.:'+str(self.rollno)
return string
class stack:
'''Implementing stack with list'''
from copy import deepcopy
def __init__(self,limit,L=[],pos=-1):
self.L=L
if len(self.L)==0:
for i in range(limit):
self.L+=[None]
self.pos=pos
self.limit=limit
else:
self.limit=limit
self.pos=pos
def add(self,element):
if self.pos<self.limit-1:
self.pos+=1
self.L[self.pos]=element
else:
print 'OVERFLOW!!'
def remove(self):
if self.pos!=-1:
print 'Element removed is ',self.L[self.pos]
self.pos-=1
else:
print 'UNDERFLOW!!'
def display(self):
if self.pos==self.limit-1:
print 'Stack is empty'
for i in range(self.pos,-1,-1):
print self.L[i],
print
print '#'*30
def __len__(self):
return len(self.L)
def __str__(self):
print self.L
print self.pos,self.limit
return str(self.L)
#--------------------------main----------------------------------
while True:
g=[]
print 'Creating new stack'
limit=input('Enter number of students you want to store:')
st1=stack(limit)
print 'Stack created'
print '1.PUSH element'
print '2.POP element'
print '3.Display element'
print '5.Display list'
print '4.Quit'
while True:
res=raw_input('Enter your choice: ')
if res=='1':
rollno=input("Enter roll no: ")
name=raw_input("Enter name: ")
classs=raw_input("Enter class: ")
section=raw_input("Enter section: ")
stu=Student(name,classs,section,rollno)
from copy import deepcopy
st1.add(deepcopy(stu))
elif res=='2':
st1.remove()
elif res=='3':
st1.display()
elif res=='4':
import sys
sys.exit()
elif res=='5':
print st1
else:
print 'Invalid command'
|
e818073196e6fabaf47145fab615f345237bf7e3 | SubrataSarkar32/college3rdsem3035 | /class12pythoncbse-master/Practical3/binsearch.py | 924 | 4.03125 | 4 | class binsearch:
def __init__(self):
self.n=input('Enter number of elements: ')
self.L=[]
for i in range (self.n):
self.L.append(input('Enter element: '))
itemi=input('Enter element to be searched for : ')
self.L.sort(reverse=True)
self.index=self.binsearchdec(itemi)
if self.index:
print 'Element found at index:',self.index,'position:',self.index+1
else:
print 'The element could not be found'
def binsearchdec(self,item):
array=self.L
beg=0
last=len(array)-1
while(beg<=last):
mid=(beg+last)/2
if item==array[mid]:
return mid
elif array[mid]<item:
last=mid-1
else:
beg=mid+1
else:
return False
#--------------------------main--------------------
fiop=binsearch()
|
3f1f068d1d557358a42db8bbb9534e5236e2f0f9 | SubrataSarkar32/college3rdsem3035 | /class12pythoncbse-master/Chapter 4/Question5.py | 1,123 | 3.65625 | 4 | class Bowler:
def __init__(self):
self.fname=''
self.lname=''
self.oversbowled=0
self.noofmaidenovers=0
self.runsgiven=0
self.wicketstaken=0
def inputup(self):
self.fname=raw_input("Player's first name: ")
self.lname=raw_input("Player's last name: ")
self.oversbowled=input('Number of over bowled: ')
self.noofmaidenovers=input('Number of maiden over bowled: ')
self.runsgiven=input('Runs given: ')
self.wicketstaken=input('Wickets taken: ')
def infup(self):
self.oversbowled=input('Number of over bowled: ')
self.noofmaidenovers=input('Number of maiden over bowled: ')
self.runsgiven=input('Runs given: ')
self.wicketstaken=input('Wickets taken: ')
def display(self):
print "Player's first name ",self.fname
print "Player's last name ",self.lname
print 'Number of over bowled ',self.oversbowled
print 'Number of maiden over bowled ',self.noofmaidenovers
print 'Runs given ',self.runsgiven
print 'Wickets taken ',self.wicketstaken
|
4ad77d79088f85449035804824a12f6beb2e1e7a | SubrataSarkar32/college3rdsem3035 | /class12pythoncbse-master/Chapter 5/int.py | 503 | 3.515625 | 4 | def compare(listsuper,listsub):
stat=None
for element in listsuper:
if listsuper.count(element)==listsub.count(element):
pass
else:
stat=False
if stat==None:
for element in listsub:
if element in listsub and element in listsuper:
pass
else:
stat=False
if stat==None:
stat=True
return stat
print compare([2,3,3],[2, 2])
|
8147118c98c5d7bf084f405607d3b15c22ea1d3f | SubrataSarkar32/college3rdsem3035 | /class12pythoncbse-master/Chapter 4/Question10.py | 1,464 | 3.625 | 4 | class HOUSING:
def __init__(self):
self.__REG_NO=0
self.__NAME=''
self.__TYPE=''
self.__COST=0.0
def Read_Data(self):
while not(self.__REG_NO>=10 and self.__REG_No<=1000):
self.__REG_NO=input('Enter registraton number betwee 10-1000: ')
self.__NAME=raw_input('Enter name: ')
self.__TYPE=raw_input('Enter house type: ')
self.__COST=float(input('Enter cost: '))
def Display(self):
print 'Registration number ',self.__REG_NO
print 'Name: ',self.__NAME
print 'House type: ',self.__TYPE
print 'Cost: ',self.__COST
def Draw_Nos(self,list1):
if len(list1)==10:
c=0
for i in range(10):
if self.__name__=='HOUSING':
c+=1
if c==10:
import random
c1=2
while c1!=2:
print 'raw No.',i
print '-----------'
draw=random.randint(10,1000)
if draw==self.__REG_NO:
self.Display()
c1+=1
else:
for i in range(10):
x=list1[i]
if draw==x._HOUSING__REG_NO:
x.Display()
c1+=1
break
|
e8cee8af302c88e5e20ff072a466e28c2aa808ae | SubrataSarkar32/college3rdsem3035 | /class12pythoncbse-master/Chapter 6&7/queue.py | 1,875 | 3.96875 | 4 | class queue:
'''This normal queue'''
def __init__(self,limit):
self.L=[]
self.limit=limit
self.insertstat=True
def insertr(self,element):
if self.insertstat==True:
if len(self.L)==0:
self.L.append(element)
elif len(self.L)<self.limit:
L1=[element]
L1=self.L+L1
from copy import deepcopy
self.L=deepcopy(L1)
if len(self.L)==self.limit:
self.insertstat=False
else:
print 'OVERFLOW!!'
else:
print 'OVERFLOW!!'
def deletel(self):
if len(self.L)==0:
print 'UNDERFLOW!!'
else:
k=self.L.pop(0)
print 'Element removed ',k
def display(self):
for i in self.L:
print i,
if len(self.L)==0:
for j in range(len(self.L)-1,self.limit):
print '_',
print
print '#'*30
def __str__(self):
return str(self.L)
#--------------------------main----------------------------------
while True:
g=[]
print 'Creating new queue'
limit=input('Enter number of blocks you want in queue:')
st1=deque(limit)
print 'queue created'
print '1.Enqueue element'
print '2.Dequeue element'
print '3.Display queue'
print '4.Display list'
print '5.Quit'
while True:
res=raw_input('Enter your choice: ')
if res=='1':
element=input('Enter element: ')
st1.insertr(element)
elif res=='2':
st1.deletel()
elif res=='3':
st1.display()
elif res=='5':
import sys
sys.exit()
elif res=='4':
print st1
else:
print 'Invalid command'
|
4ff55a48679abadf58c65cd9e92f86231c089424 | SubrataSarkar32/college3rdsem3035 | /class12pythoncbse-master/Chapter 4/Question8.py | 539 | 3.65625 | 4 | class ticbooth:
price=2.50
people=0
totmoney=0.0
def __init__(self):
self.totmoney=float(input('Enter the amount if paid else 0:'))
ticbooth.people+=1
if self.totmoney==2.50:
ticbooth.totmoney+=2.50
@staticmethod
def reset():
ticbooth.people=0
ticbooth.totmoney=0.0
def dis(self):
print 'Number of people ',ticbooth.people,'amount paid ',ticbooth.totmoney
def distics(self):
print 'Number of people who paid money',ticbooth.totmoney/2.50
|
6ad09ceb2ab4a05697fb9673000154dcae6d3e0a | SubrataSarkar32/college3rdsem3035 | /class12pythoncbse-master/Chapter 4/Question11.py | 876 | 3.796875 | 4 | class DATE:
monda=[[1,31],[2,28],[3,31],[4,30],[5,31],[6,30],[7,31],[8,31],[9,30],[10,31],[11,30],[12,31]]
def __init__(self,month,day):
a=len(DATE.monda)
self.month=month
self.day=day
while self.month<1 or self.month>12:
self.month=input('Enter month (1 to 12):')
while self.day<1 or self.day>DATE.monda[self.month-1][1]:
self.day=input('Enter day within limit of respective month: ')
def days_in_month(self):
return DATE.monda[self.month-1][1]
def next_day(self):
if self.day+1<=DATE.monda[self.month-1][1]:
self.day+=1
else:
if self.month<12:
self.month+=1
self.day=1
else:
self.month=1
self.day=1
def __str__(self):
print str(self.month),'/',str(self.day)
|
b31f09ab94e4cbddb88f5180b3d2951c55d4b868 | Kmr-Chetan/python_practice | /Palindrome.py | 907 | 4 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head= None
def isPalindromeUtil(self, string):
return (string == string[:: -1])
def isPalindrome(self):
node = self.head
temp = []
while(node is not None):
temp.append(node.data)
node = node.next
string = "".join(temp)
return self.isPalindromeUtil(string)
def printList(self):
temp =self.head
while(temp):
print(temp.data),
temp = temp.next
llist = LinkedList()
llist.head = Node('a')
llist.head.next =Node('b')
llist.head.next.next =Node('c')
llist.head.next.next.next =Node('b')
llist.head.next.next.next.next =Node('a')
llist.head.next.next.next.next.next =Node('c')
print("true" if llist.isPalindrome() else "false")
|
4277a08cf47b4f91712841ef2e3757a49090650f | IStealYourSkill/python | /les3/3_3.py | 579 | 4.28125 | 4 | '''3. Проверить, что хотя бы одно из чисел a или b оканчивается на 0.'''
a = int(input('Введите число A: '))
b = int(input('Введите число B: '))
if ((a >= 10) or (b >= 10)) and (a % 10 == 0 or b % 10 == 0):
print("Одно из чисел оканчивается на 0")
else:
print("Числа {}, {} без нулей".format(a, b))
'''
if (10 <= a <= -10) and (a % 10 == 0):
print("ноль, естЬ! {}".format(a))
else:
print("Без нулей {}".format(a))
''' |
36c1f3a4606a1e9cc61a363387495cb2f8fdb31d | charlottekosche/compciv-2018-ckosche | /week-05/ezsequences/ezlist.py | 2,581 | 3.546875 | 4 | #################################
# ezsequences/ezlist.py
#
# This skeleton script contains a series of functions that
# return
ez_list = [0, 1, 2, 3, 4, ['a', 'b', 'c'], 5, ['apples', 'oranges'], 42]
def foo_hello():
"""
This function should simply return the `type`
of the `ez_list` object.
This guarantees that you'll past at least one of
the tests/assertions in test_ezlist.py
"""
return type(ez_list)
##################
# Exercises foo_a through foo_e cover basic list access
##################
def foo_a():
"""
Return the very first member of `ez_list`
"""
return ez_list [0]
def foo_b():
"""
Return the sum of the 2nd and 4th members of
`ezlist`
"""
sum_second_and_forth = ez_list [1] + ez_list [3]
return sum_second_and_forth
def foo_c():
"""
Return the very last member of `ez_list`.
Use a negative index to specify this member
"""
return ez_list [-1]
def foo_cx():
"""
Return the type of the object that is the
second-to-last member of `ez_list`
"""
return type(ez_list [-2])
def foo_d():
"""
Return the very last member of the sequence that itself
is the second-to-last member of `ez_list`
"""
second_to_last_member_of_ez_list = ez_list [-2]
last_member_of_sequence = second_to_last_member_of_ez_list [-1]
return last_member_of_sequence
def foo_e():
"""
Calculate and return the length of `ez_list`, i.e., the
number of members it contains.
"""
return len(ez_list)
def foo_f():
"""
Return the 6th member of `ez_list` as a single,
semi-colon delimited string
i.e. the separate values are joined with the
semi-colon character
"""
whole_string = ""
sixth_member = ez_list [5]
for i in sixth_member:
single_string = str(i)
if i == sixth_member [0]:
whole_string = single_string
else:
whole_string = whole_string + ";" + single_string
return whole_string
"""
Alternatively, I could have used the join function:
return ';'.join(ez_list[5])
"""
def foo_g():
"""
Return a list that contains the 2nd through 5th
elements of `ez_list`
(it should have 4 members total)
"""
new_list = ez_list [1:5]
return new_list
def foo_h():
"""
Return a list that consists of the last
3 members of `ez_list` in *reverse* order
"""
new_list = ez_list [-3::]
reverse_list = list(reversed(new_list))
return reverse_list |
cfdeb5d426d745a6986a5da2c172d9ff4293ab35 | storm2513/Task-manager | /task-manager/library/tmlib/models/notification.py | 755 | 3.640625 | 4 | import enum
class Status(enum.Enum):
"""
Enum that stores values of notification's statuses
CREATED - Notification was created
PENDING - Notification should be shown
SHOWN - Notification was shown
"""
CREATED = 0
PENDING = 1
SHOWN = 2
class Notification:
"""Notification class that is used remind user about task"""
def __init__(
self,
task_id,
title,
relative_start_time,
status=Status.CREATED.value,
id=None,
user_id=None,):
self.id = id
self.user_id = user_id
self.task_id = task_id
self.title = title
self.relative_start_time = relative_start_time
self.status = status
|
ec5f0599d0af4f726978ea37e17c66b4e67da986 | sweetkristas/mercy | /utils/citygen.py | 4,065 | 3.5625 | 4 | from random import randint, random
import noise
# variables: block_vertical block_horizontal road_vertical road_horizontal
# start: block_vertical
# rules: (block_vertical -> block_horizontal road_vertical block_horizontal)
# (block_horizontal -> block_vertical road_horizontal block_vertical)
block_vertical = 1
block_horizontal = 2
road_vertical = 10
road_horizontal = 11
road_width = 2
min_width = road_width + 4
min_height = road_width + 4
def as_string(data):
if data == block_vertical:
return "block_vertical"
elif data == block_horizontal:
return "block_horizontal"
elif data == road_vertical:
return "road_vertical"
return "road_horizontal"
class Tree(object):
def __init__(self):
self.left = None
self.right = None
self.data = None
def recurse_tree(root, num_iterations, x, y, width, height):
if num_iterations == 0 or (width <= min_width and height <= min_height): return
if root.data[0] == block_vertical and width > min_width:
w = int(width * random())/2
if w < min_width: w = min_width
root.data = (road_vertical, x+w, y, road_width, height)
root.left = Tree()
root.left.data = (block_horizontal, x, y, w-road_width, height)
root.right = Tree()
root.right.data = (block_horizontal, x+w+road_width, y, width - w - road_width, height)
recurse_tree(root.left, num_iterations-1, x, y, w, height)
recurse_tree(root.right, num_iterations-1, x+w+road_width, y, width - w - road_width, height)
elif root.data[0] == block_horizontal and height > min_height:
h = int(height * random())/2
if h < min_height: h = min_height
root.data = (road_horizontal, x, y+h, width, road_width)
root.left = Tree()
root.left.data = (block_vertical, x, y, width, h-road_width)
root.right = Tree()
root.right.data = (block_vertical, x, y+h+road_width, width, height - h - road_width)
recurse_tree(root.left, num_iterations-1, x, y, width, h)
recurse_tree(root.right, num_iterations-1, x, y+h+road_width, width, height - h - road_width)
def print_tree(root):
if root == None: return
print_tree(root.left)
print "%s" % as_string(root.data)
print_tree(root.right)
def create_grid(root, output):
if root == None: return output
create_grid(root.left, output)
x = root.data[1]
y = root.data[2]
w = root.data[3]
h = root.data[4]
#print "%d, %d, %d, %d %s" % (x, y, w, h, as_string(root.data[0]))
for m in range(y, y+h):
for n in range(x, x+w):
if root.data[0] == block_vertical:
output[m][n] = '+'
elif root.data[0] == block_horizontal:
output[m][n] = '+'
elif root.data[0] == road_vertical:
output[m][n] = ' '
elif root.data[0] == road_horizontal:
output[m][n] = ' '
create_grid(root.right, output)
return output
def main(width, height, num_iterations=10):
root = Tree()
root.data = (block_vertical, width)
recurse_tree(root, num_iterations, 0, 0, width, height)
output = []
for i in range(0, height):
output.append([])
for j in range(0, width):
output[-1].append(' ')
output = create_grid(root, output)
#print_tree(root)
return output
ascii_noise_map = [(0.0,'~'), (0.1,'-'), (0.25,'.'), (0.6,'+'), (1.0,'^')]
def noise_map(width, height):
ascii_noise_map.reverse()
output = []
for i in range(0, height):
output.append([])
for j in range(0, width):
nv = noise.snoise2(float(j) / width, float(i) / height)
outc = ' '
for np in ascii_noise_map:
if nv < np[0]: outc = np[1]
output[-1].append(outc)
return output
if __name__ == '__main__':
#res = main(120, 50, 1000)
#for row in res:
# print ''.join(row)
res2 = noise_map(150, 1000)
for row in res2:
print ''.join(row)
|
31d6a644a8962ddabee4d3d9140d47b131880667 | ivanifp/tresEnRaya | /main.py | 641 | 3.625 | 4 | from utils import numJugadores,getFicha,colocaFicha,imprimirTablero,tableroLibre,victoria
#me creo mi tablero con nueve posiciones
tablero = [' ']*9
numJu = numJugadores()
fichaj1,fichaj2 = getFicha()
while tableroLibre(tablero) or victoria(tablero,fichaj1)== False or victoria(tablero,fichaj2)== False:
imprimirTablero(tablero)
pos = int(input("Diga movimiento jugador Uno"+fichaj1))
colocaFicha(tablero,pos,fichaj1)
imprimirTablero(tablero)
pos2 = int(input("Diga movimiento jugador Dos"+fichaj2))
colocaFicha(tablero,pos2,fichaj2)
imprimirTablero(tablero)
#fin tableroLibre
|
264b622be15b275164a1259f3906c9d69fe00819 | stteem/Python | /MyPython/SearchExercise.py | 689 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 20 13:29:27 2017
@author: Uwemuke
"""
print("Please think of a number between 0 and 100!")
high = 100
low = 0
guess = (high - low)//2.0
while guess**2 < high:
print('Is your secret number' + str(guess) + '?')
(input("Enter 'h' to indicate the guess is too high. \
Enter 'l' to indicate the guess is too low.\
Enter 'c' to indicate I guessed correctly.\
:" ))
if ans == 'h':
high = guess
elif ans == 'l':
low = guess
elif ans == 'c':
print('Game over. Your secret number was: ' + str(guess))
else:
print('Sorry, i did not understandd your input.') |
fb43e3221791f1b84663b42bb5d3b7e2917270a5 | stteem/Python | /MyPython/Finding biggest value of a key.py | 471 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jun 26 12:04:30 2017
@author: Uwemuke
"""
def biggest(aDict):
'''
aDict: A dictionary, where all the values are lists.
returns: The key with the largest number of values associated with it
'''
result = None
biggestValue = 0
for key in aDict.keys():
if len(aDict[key]) >= biggestValue:
result = key
biggestValue = len(aDict[key])
return result |
25dcce43a2306b81de2040ec215ae16dd77a2136 | stteem/Python | /MyPython/midterm1 unfinished.py | 569 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Jul 1 23:48:44 2017
@author: Uwemuke
"""
def largest_odd_times(L):
L1 = {}
for i in L:
if i in L1:
L1[i] += 1
else:
L1[i] = 1
return L1
def even(k):
k = max(freq)
for i in range(0, k, 2):
return i
def odd_times(p):
best = max(L1.values())
bestkey = max(L1.keys())
if bestkey not in even:
return
freq = largest_odd_times([3,9,5,3,5,3]) |
a63221aca27c99efdc063aa6a716b4fa4f6670c0 | stteem/Python | /Pset4/Pset402.py | 797 | 3.96875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jul 10 00:19:54 2017
@author: Uwemuke
"""
def updateHand(hand, word):
"""
Assumes that 'hand' has all the letters in word.
In other words, this assumes that however many times
a letter appears in 'word', 'hand' has at least as
many of that letter in it.
Updates the hand: uses up the letters in the given word
and returns the new hand, without those letters in it.
Has no side effects: does not modify hand.
word: string
hand: dictionary (string -> int)
returns: dictionary (string -> int)
"""
update_hand = hand.copy()
for i in word:
update_hand[i] -= 1
return update_hand
updateHand({'u': 1, 'a': 1, 'i': 1, 'l': 2, 'q': 1, 'm': 1}, 'quail') |
861508bd3e5b4eeeeb8fcfe56fff987e723f4176 | stteem/Python | /MyPython/multiplication_iterative_solution.py | 225 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jun 21 12:58:11 2017
@author: Uwemuke
"""
def multi_iter(a, b):
result = 0
while b > 0:
result += a
b -= 1
return result
multi_iter(4, 8) |
0f9bc0663d9c38f5e3be9a5051cf0e960736d148 | unbecomingpig/scotchbutter | /scotchbutter/util/database.py | 4,711 | 3.515625 | 4 | """Contains functions to help facilitate reading/writing from a database.
NOTE: Currently only supporting sqlite databases
"""
import logging
import sqlite3
import time
from scotchbutter.util import environment, tables
DB_FILENAME = 'tvshows.sqlite'
logger = logging.getLogger(__name__)
class DBInterface():
"""Provides a contraced API to query the DataBase.
Providing a contracted API allows for an transparent backend
changes. # TODO: Add DB connections beyond sqlite.
"""
library_name = 'library'
def __init__(self, db_file: str = DB_FILENAME):
"""Create an interface to query the DataBase."""
self._settings_path = environment.get_settings_path()
self._db_file = self._settings_path.joinpath(db_file)
logger.info('Using database located at %s', self._db_file)
self._conn = None
self._cursor = None
self.close()
@property
def conn(self):
"""Create a DB connection if it doesn't already exist."""
if self._conn is None:
self.connect()
return self._conn
@property
def cursor(self):
"""Create a cursor to interact with the database."""
if self._cursor is None:
self.connect()
return self._cursor
@property
def existing_tables(self):
"""List tables currently in the database."""
query = "SELECT name FROM sqlite_master WHERE type='table'"
results = self.cursor.execute(query)
table_names = sorted([name for result in results for name in result])
return table_names
def connect(self):
"""Create a new connection to DB."""
# If the database file doesn't exist, this will create it.
self._conn = sqlite3.connect(self._db_file)
self._cursor = self.conn.cursor()
def close(self, commit: bool = True):
"""Close the DB connections."""
if self._conn is not None:
if commit is True:
self.conn.commit()
self.conn.close()
self._conn = None
self._cursor = None
def __enter__(self):
"""Context management protocol."""
self.connect()
return self
def __exit__(self, exc_type, exc_value, traceback):
"""Closes any existing DB connection."""
self.close()
def create_table(self, name, columns):
"""Create a table in the database."""
table = tables.Table(name)
for column in columns:
table.add_column(column)
if name not in self.existing_tables:
self.cursor.execute(table.create_table_string)
logger.info('Created table %s', name)
return table
def add_series(self, series):
"""Add a series to the database."""
table = self.create_table(self.library_name, tables.LIBRARY_COLUMNS)
values = [series[column.name] for column in table.columns]
self.cursor.execute(table.insert_string, values)
logger.info('Added seriesId %s to %s', series.series_id, self.library_name)
show_table = self.create_table(series.series_id, tables.SHOW_COLUMNS)
episodes = []
for episode in series.episodes:
values = [episode[column.name] for column in show_table.columns]
episodes.append(values)
logger.info('Added %s episodes to table %s', len(series.episodes), series.series_id)
self.cursor.executemany(show_table.insert_string, episodes)
def remove_series(self, series_id):
"""Remove a series from the database."""
drop_string = f"DROP TABLE IF EXISTS '{series_id}'"
delete_string = f"DELETE FROM '{self.library_name}' WHERE seriesId = {series_id}"
self.cursor.execute(delete_string)
logger.info('Removed %s from table %s', series_id, self.library_name)
self.cursor.execute(drop_string)
logger.info('Removed table %s', series_id)
def _select_from_table(self, table_name: str):
"""Select all entries from a table."""
# TODO: expand this to accept where statements
results = self.cursor.execute(f'SELECT * from {table_name}')
column_names = [x[0] for x in results.description]
rows_values = [dict(zip(column_names, row)) for row in results]
logger.debug('Selected %s rows from table %s', len(rows_values), table_name)
return rows_values
def get_library(self):
"""return a list of series dicts for shows in the library."""
return self._select_from_table(self.library_name)
def get_episodes(self, series_id):
"""Return a list of episode dicts for the requested series."""
return self._select_from_table(series_id)
|
08ef8703147476759e224e66efdc7b5de5addf6e | chaoma1988/Coursera_Python_Program_Essentials | /days_between.py | 1,076 | 4.65625 | 5 | '''
Problem 3: Computing the number of days between two dates
Now that we have a way to check if a given date is valid,
you will write a function called days_between that takes six integers (year1, month1, day1, year2, month2, day2)
and returns the number of days from an earlier date (year1-month1-day1) to a later date (year2-month2-day2).
If either date is invalid, the function should return 0. Notice that you already wrote a
function to determine if a date is valid or not! If the second date is earlier than the first date,
the function should also return 0.
'''
import datetime
from is_valid_date import is_valid_date
def days_between(year1,month1,day1,year2,month2,day2):
if is_valid_date(year1,month1,day1):
date1 = datetime.date(year1,month1,day1)
else:
return 0
if is_valid_date(year2,month2,day2):
date2 = datetime.date(year2,month2,day2)
else:
return 0
delta = date2 - date1
if delta.days <= 0:
return 0
else:
return delta.days
# Testing
#print(days_between(1988,7,19,2018,7,3))
|
d53544648c25cc8d0562cc4cd92ce70341e8d353 | lch172061365/Computational-Physics | /Project3/3e(for jupiter of original mass).py | 3,370 | 3.640625 | 4 | import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
import math
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.image as img
G = 6.67*10**(-11)
m1 = 6*10**24 #earth
m2 = 2*10**30 #sun
m3 = 1.9*10**27 #jupiter
#m1
x10 = -149597870000
y10 = 0
z10 = 0
p10 = 0
q10 = 29783
r10 = 0
#m2
x20 = 0
y20 = 0
z20 = 0
p20 = 0
q20 = 0
r20 = 0
#m3
x30 = 778547200000
y30 = 0
z30 = 0
p30 = 0
q30 = -13070
r30 = 0
dt = 2000
n = 1000000
#initialize the position
x1 = [0]
y1 = [0]
z1 = [0]
x2 = [0]
y2 = [0]
z2 = [0]
x3 = [0]
y3 = [0]
z3 = [0]
x1[0] = x10 #set up initial position
y1[0] = y10
z1[0] = z10
x2[0] = x20
y2[0] = y20
z2[0] = z20
x3[0] = x30
y3[0] = y30
z3[0] = z30
#initialzie the speed, create a list
p1 = [0]
q1 = [0]
r1 = [0]
p2 = [0]
q2 = [0]
r2 = [0]
p3 = [0]
q3 = [0]
r3 = [0]
p1[0] = p10 #set up initial speed
q1[0] = q10
r1[0] = r10
p2[0] = p20
q2[0] = q20
r2[0] = r20
p3[0] = p30
q3[0] = q30
r3[0] = r30
#loop
i = 0
while i < n-1:
#three distances
S12 = math.sqrt((x2[i]-x1[i])**2+(y2[i]-y1[i])**2+(z2[i]-z1[i])**2)
S13 = math.sqrt((x3[i]-x1[i])**2+(y3[i]-y1[i])**2+(z3[i]-z1[i])**2)
S23 = math.sqrt((x2[i]-x3[i])**2+(y2[i]-y3[i])**2+(z2[i]-z3[i])**2)
x1.append(x1[i]+p1[i]*dt)
y1.append(y1[i]+q1[i]*dt)
z1.append(z1[i]+r1[i]*dt)
x2.append(x2[i]+p2[i]*dt)
y2.append(y2[i]+q2[i]*dt)
z2.append(z2[i]+r2[i]*dt)
x3.append(x3[i]+p3[i]*dt)
y3.append(y3[i]+q3[i]*dt)
z3.append(z3[i]+r3[i]*dt)
p1.append(dt*(G*m3*(x3[i+1]-x1[i+1])/((S13)**3)+G*m2*(x2[i+1]-x1[i+1])/((S12)**3))+p1[i])
q1.append(dt*(G*m3*(y3[i+1]-y1[i+1])/((S13)**3)+G*m2*(y2[i+1]-y1[i+1])/((S12)**3))+q1[i])
r1.append(dt*(G*m3*(z3[i+1]-z1[i+1])/((S13)**3)+G*m2*(z2[i+1]-z1[i+1])/((S12)**3))+r1[i])
p2.append(dt*(G*m1*(x1[i+1]-x2[i+1])/((S12)**3)+G*m3*(x3[i+1]-x2[i+1])/((S23)**3))+p2[i])
q2.append(dt*(G*m1*(y1[i+1]-y2[i+1])/((S12)**3)+G*m3*(y3[i+1]-y2[i+1])/((S23)**3))+q2[i])
r2.append(dt*(G*m1*(z1[i+1]-z2[i+1])/((S12)**3)+G*m3*(z3[i+1]-z2[i+1])/((S23)**3))+r2[i])
p3.append(dt*(G*m1*(x1[i+1]-x3[i+1])/((S13)**3)+G*m2*(x2[i+1]-x3[i+1])/((S23)**3))+p3[i])
q3.append(dt*(G*m1*(y1[i+1]-y3[i+1])/((S13)**3)+G*m2*(y2[i+1]-y3[i+1])/((S23)**3))+q3[i])
r3.append(dt*(G*m1*(z1[i+1]-z3[i+1])/((S13)**3)+G*m2*(z2[i+1]-z3[i+1])/((S23)**3))+r3[i])
#next loop
i += 1
import mpl_toolkits.mplot3d.axes3d as p3
#make plot
def update_lines(num,datalines,lines):
for line,data in zip(lines,datalines):
line.set_data(data[0:2, :num])
line.set_3d_properties(data[2, :num])
return lines
fig = plt.figure()
ax = p3.Axes3D(fig)
#data turple
data=[np.array([x1,y1,z1])[:,0:1000000:100],
np.array([x2,y2,z2])[:,0:1000000:100],
np.array([x3,y3,z3])[:,0:1000000:100]]
lines =[ax.plot(dat[0, 0:1], dat[1, 0:1], dat[2, 0:1])[0] for dat in data]
#make plot
ax.set_xlim3d([-10**12,10**12])
ax.set_xlabel('X')
ax.set_ylim3d([-10**12,10**12])
ax.set_ylabel('Y')
ax.set_zlim3d([-10**12,10**12])
ax.set_zlabel('Z')
ax.set_title('Simulation on three-body')
#figure show
line_ani = animation.FuncAnimation(fig, update_lines,fargs = (data,lines),interval =1,blit = False)
plt.show()
|
95357539ad5ea90938cb13440a9e419206ba42f3 | moisindustries/Leetcode-practice | /238-product-of-array-except-self.py | 855 | 3.546875 | 4 | """
Problem Link: https://leetcode.com/problems/product-of-array-except-self/description/
Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements
of nums except nums[i].
Example:
Input: [1,2,3,4]
Output: [24,12,8,6]
Note: Please solve it without division and in O(n).
Follow up:
Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity
analysis.)
"""
class Solution(object):
def productExceptSelf(self, nums):
p = 1
n = len(nums)
result = []
for i in range(0,n):
result.append(p)
p = p * nums[i]
p = 1
for i in range(n-1,-1,-1):
result[i] = result[i] * p
p = p * nums[i]
return result |
b2ead9da892231c4d5e5c610d88797290a1cda29 | ken4815/CP3-Pakkapong-Thonchaisuratkrul | /Lexture 46.py | 87 | 3.546875 | 4 | n = int(input("N:"))
for x in range(24):
x = x+1
print(n ,"*",x,"=",n * (x)) |
562ac5cebcf516d7e40724d3594186209d79c2f4 | Vyara/First-Python-Programs | /quadratic.py | 695 | 4.3125 | 4 | # File: quadratic.py
# A program that uses the quadratic formula to find real roots of a quadratic equation.
def main():
print "This program finds real roots of a quadratic equation ax^2+bx+c=0."
a = input("Type in a value for 'a' and press Enter: ")
b = input("Type in a value for 'b' and press Enter: ")
c = input("Type in a value for 'c' and press Enter: ")
d = (b**2.0 - (4.0 * a * c))
if d < 0:
print "No real roots"
else:
root_1 = (-b + d**0.5) / (2.0 * a)
root_2 = (-b - d**0.5) / (2.0 * a)
print "The answers are:", root_1, "and", root_2
raw_input("Press Enter to exit.")
main()
|
301a8410b1a192e4c0c40b404e0bdaca03005de6 | chilu49/python | /deck-blackjack.py | 321 | 3.6875 | 4 | #from random import shuffle
#ranks = range(2,11) + ['JACK', 'QUEEN', 'KING', 'ACE']
#print ranks
#suits = ['S', 'H', 'D', 'C']
#print suits
#def get_deck():
# """Return new deck of cards"""
# return [[rank,suit] for rank in ranks for suit in suits]
#deck = get_deck()
#shuffle(deck)
#print deck
#print len(deck)
|
2981b59c33aec6471398075ff81f7757888d68e5 | hurenkam/AoC | /2022/Day02/part2.py | 538 | 3.765625 | 4 | #!/bin/env python
with open('input.txt','r') as file:
lines = [line.strip() for line in file]
lookup = {
"A X": "A C",
"A Y": "A A",
"A Z": "A B",
"B X": "B A",
"B Y": "B B",
"B Z": "B C",
"C X": "C B",
"C Y": "C C",
"C Z": "C A"
}
scores = {
"A A": 4,
"A B": 8,
"A C": 3,
"B A": 1,
"B B": 5,
"B C": 9,
"C A": 7,
"C B": 2,
"C C": 6
}
total = 0
while (len(lines)):
line = lines.pop(0)
score = scores[lookup[line]]
total += score
print(total)
|
f8ce648c17349a1b550f4e22d6146a9bffe2509f | hurenkam/AoC | /2022/Day11/part2.py | 2,832 | 3.625 | 4 | #!/bin/env python
with open('input.txt','r') as file:
lines = [line.strip() for line in file]
def parseInput(lines):
while len(lines):
while not lines[0].startswith("Monkey"):
lines.pop(0)
parseMonkey(lines)
monkeys={}
def parseMonkey(lines):
global monkeys
index = parseIndex(lines.pop(0))
items = parseStartItems(lines.pop(0))
operation = parseOperation(lines.pop(0))
divider = parseDivider(lines.pop(0))
monkeytrue = parseTargetIndex(lines.pop(0))
monkeyfalse = parseTargetIndex(lines.pop(0))
monkeys[index] = { "index": index, "items": items, "operation": operation, "divider": divider, "targets": [monkeytrue,monkeyfalse], "inspections":0 }
def parseIndex(line):
p1 = line.split(':')
p2 = p1[0].split(' ')
return int(p2[1])
def parseStartItems(line):
p1 = line.split(':')
p2 = p1[1].split(',')
items = []
for item in p2:
items.append(int(item))
return items
def parseOperation(line):
p1 = line.split(':')
p2 = p1[1].split('=')
p3 = p2[1].strip().split(' ')
operator = p3[1].strip()
if operator == '+':
return (add,int(p3[2]))
if operator == '*':
if p3[2] == 'old':
return (power,None)
return (multiply,int(p3[2]))
raise Exception("unsupported operation")
def power(old,arg):
return old * old
def add(old,arg):
return old + arg
def multiply(old,arg):
return old * arg
def parseDivider(line):
p1 = line.split(':')
p2 = p1[1].split(' ')
divider = int(p2.pop())
return divider
def parseTargetIndex(line):
p1 = line.split(':')
p2 = p1[1].split(' ')
index = int(p2.pop())
return index
def doRound():
monkeysToVisit = sorted(monkeys)
for index in sorted(monkeys):
doRoundForMonkey(index)
#printMonkeys()
def doRoundForMonkey(index):
items = monkeys[index]["items"]
monkeys[index]["items"] = []
for item in items:
doItemForMonkey(item,index)
def doItemForMonkey(item,index):
monkeys[index]["inspections"] += 1
op = monkeys[index]["operation"][0]
arg = monkeys[index]["operation"][1]
item = op(item,arg) % moduloFactor
test = (item % monkeys[index]["divider"] == 0)
if (test):
target = monkeys[index]["targets"][0]
else:
target = monkeys[index]["targets"][1]
monkeys[target]["items"].append(item)
moduloFactor = 1
def calculateModuloFactor():
global moduloFactor
for key in sorted(monkeys):
moduloFactor *= monkeys[key]["divider"]
parseInput(lines)
calculateModuloFactor()
for i in range(0,10000):
doRound()
inspections = []
for key in sorted(monkeys):
inspections.append(monkeys[key]["inspections"])
inspections.sort()
l = len(inspections)
print(inspections[l-1]*inspections[l-2])
|
4dcb005342c13a213a78196aab6a4739aa80776a | hurenkam/AoC | /2022/Day08/part2.py | 1,310 | 3.578125 | 4 | #!/bin/env python
with open('input.txt','r') as file:
lines = [line.strip() for line in file]
def buildMatrix():
forrest = []
for line in lines:
treeline = []
for tree in line:
height = int(tree)
treeline.append(height)
forrest.append(treeline)
return forrest
def calculateScenicScore(forrest,x,y):
current = forrest[y][x]
left = countVisibleTrees(forrest,current,x,y,-1,0)
right = countVisibleTrees(forrest,current,x,y,1,0)
top = countVisibleTrees(forrest,current,x,y,0,-1)
bottom = countVisibleTrees(forrest,current,x,y,0,1)
result = left*right*top*bottom
return left * right * top * bottom
def countVisibleTrees(forrest,current,x,y,dx,dy):
height = len(forrest)
width = len(forrest[0])
count = 0
x += dx
y += dy
if (x>=0) and (x<width) and (y>=0) and (y<height):
if (forrest[y][x] < current):
return 1 + countVisibleTrees(forrest,current,x,y,dx,dy)
else:
return 1
return 0
forrest = buildMatrix()
height = len(forrest)
width = len(forrest[0])
score = 0
for y in range(0,height):
for x in range(0,width):
result = calculateScenicScore(forrest,x,y)
if (result > score):
score = result
print(score)
|
23aeb35a5d118fe8e57e355514ff5bb71652b62b | hurenkam/AoC | /2020/Day13/solve.py | 1,214 | 3.703125 | 4 | #!/usr/bin/env python3
#===================================================================================
def Part1():
departures={}
tmp = [int(bus) for bus in busses if bus !='x']
for bus in tmp:
departs = (int(arrival / bus) +1) * bus
waittime = departs - arrival
departures[waittime] = bus
best = min(departures.keys())
return departures[best] * best
def FindEarliestDepartureTime(desired,bus):
return (int(desired / bus) +1) * bus
#===================================================================================
def Part2():
mods = {bus: -i % bus for i, bus in enumerate(busses) if bus != "x"}
sortedbusses = list(reversed(sorted(mods)))
t = mods[sortedbusses[0]]
r = sortedbusses[0]
for bus in sortedbusses[1:]:
while t % bus != mods[bus]:
t += r
r *= bus
return t
#===================================================================================
print("Day 13")
with open('input','r') as file:
lines = [line.strip() for line in file]
arrival = int(lines[0])
busses = ["x" if x == "x" else int(x) for x in lines[1].split(",")]
print("Part1: ",Part1())
print("Part2: ",Part2())
|
852cba828e67b97d2ddd91322a827bfdc3c6a849 | ridhamaditi/tops | /Assignments/Module(1)-function&method/b1.py | 287 | 4.3125 | 4 | #Write a Python function to calculate the factorial of a number (a non-negative integer)
def fac(n):
fact=1
for i in range(1,n+1):
fact *= i
print("Fact: ",fact)
try:
n=int(input("Enter non-negative number: "))
if n<0 :
print("Error")
else:
fac(n)
except:
print("Error")
|
287f5f10e5cc7c1e40e545d958c54c8d01586bfb | ridhamaditi/tops | /Assignments/Module(1)-Exception Handling/a2.py | 252 | 4.15625 | 4 | #write program that will ask the user to enter a number until they guess a stored number correctly
a=10
try:
n=int(input("Enter number: "))
while a!=n :
print("Enter again")
n=int(input("Enter number: "))
print("Yay")
except:
print("Error")
|
4337d05a72684cdfc0bdef255ccfcce72d5f6432 | ridhamaditi/tops | /Assignments/Module(1)-modules/I2.py | 188 | 4.375 | 4 | # Aim: Write a Python program to convert degree to radian.
pi=22/7
try:
degree = float(input("Input degrees: "))
radian = degree*(pi/180)
print(radian)
except:
print("Invalid input.") |
e3eca8bce227d8d6c6b4526189945c2cd79e0c41 | ridhamaditi/tops | /functions/prime.py | 234 | 4.1875 | 4 | def isprime(n,i=2):
if n <= 2:
return True
elif n % i == 0:
return False
elif i*i > n:
return True
else:
return isprime(n,i+1)
n=int(input("Enter No: "))
j=isprime(n)
if j==True:
print("Prime")
else:
print("Not prime") |
bcc1edf1be77b38dff101b8221497dc5baa3f2ec | ridhamaditi/tops | /modules/math_sphere.py | 237 | 4.15625 | 4 | import math
print("Enter radius: ")
try:
r = float(input())
area = math.pi * math.pow(r, 2)
volume = math.pi * (4.0/3.0) * math.pow(r, 3)
print("\nArea:", area)
print("\nVolume:", volume)
except ValueError:
print("Invalid Input.") |
1d2389112a628dbf8891f85d6606ec44543fc81d | ridhamaditi/tops | /Assignments/Module(1)-Exception Handling/a4.py | 791 | 4.21875 | 4 | #Write program that except Clause with No Exceptions
class Error(Exception):
"""Base class for other exceptions"""
pass
class ValueTooSmallError(Error):
"""Raised when the input value is too small"""
pass
class ValueTooLargeError(Error):
"""Raised when the input value is too large"""
pass
# user guesses a number until he/she gets it right
number = 10
while True:
try:
inum = int(input("Enter a number: "))
if inum < number:
raise ValueTooSmallError
elif inum > number:
raise ValueTooLargeError
break
except ValueTooSmallError:
print("This value is too small, try again!")
except ValueTooLargeError:
print("This value is too large, try again!")
print("Congratulations! You guessed it correctly.") |
ad9be274f3f72de34d1adafccb473bbcb637556b | ridhamaditi/tops | /basics/factorial.py | 149 | 4.15625 | 4 | n= int(input("Enter: "))
fact = 1
# while n > 1:
# fact = fact * n
# n -= 1
for i in range(1, n+1):
fact = fact * i
print("Factorial: ", fact) |
609812d3b68a77f35eb116682df3f844ab3a44c9 | ridhamaditi/tops | /Assignments/Module(1)-Exception Handling/a3.py | 216 | 4.15625 | 4 | #Write function that converts a temperature from degrees Kelvin to degrees Fahrenheit
try:
k=int(input("Enter temp in Kelvin: "))
f=(k - 273.15) * 9/5 + 32
print("Temp in Fahrenheit: ",f)
except:
print("Error")
|
5f9d82659fbfcaac9008b379d82726bcc28b1e96 | pdevezeaud/Python | /range.py | 256 | 3.984375 | 4 | tableau = list(range(10))
print (tableau)
start = 0
stop = 20
x = range(start,stop)
print(x)
print(list(x))
#on peut définir un pas dans la liste
x = range(start,stop,2)
print(list(x))
#on peut boucler sur un range
for num in range(10):
print (num) |
7b8e48108d95aa59aa9cd5af63b5672ee99aa0d1 | pdevezeaud/Python | /tuple.py | 553 | 3.9375 | 4 | t=(4,1,5,2,3,9,7,2,8)
print(t)
print(t[2:3])
t +=(10,) #concenation
print(t)
print(len(t))
ch ='trou du cul'
st = tuple(ch)
print(st)
print("*******************************************")
'''
(!) Tuple : conteneur imuable (dont on ne peut modifier les valeurs)
création de tupe : mon_tuple = () #vide
mon_tuple = 17 #avec une valeurs
mon_tuple = (4,17) #plusieurs valeurs
raisons d'utiliser les tuples : affectation multiple de variable
retour multiple de fonction
'''
|
e5779f5e61468032d5f28b432938c279e9c3af3b | pdevezeaud/Python | /liste_en_comprehension.py | 415 | 3.9375 | 4 |
liste = [x for x in 'exemple']
print (liste)
liste2 = [x**2 for x in range(0,11)]
print(liste2)
# possibilite de mettre des conditions dans la liste
liste2 = [x**2 for x in range(0,11) if x%2 == 0]
print(liste2)
celsius = [0,10,20.1,34.5]
farenheit = [((9/5)*temp + 32) for temp in celsius ]
print(farenheit)
#imbriqué une liste de compréhension
lst = [x**2 for x in [x**2 for x in range(11)]]
print (lst)
|
6940e23dfdfc93a23dab888ead9fe54b8b7baefe | pdevezeaud/Python | /fonction_detaillee.py | 970 | 3.90625 | 4 |
def est_premier (num):
'''
Fonction simple pour determiner si un nombre est premier
parametre : num, le nombre à tester
on par de 2 jusqu'au numero entré (num). Utilisation du range dans ce cas.
'''
for n in range(2,num):
if num % n == 0:
print("Il n'est pas premier")
'''
on sort du test car n'est plus divisible
'''
break
else:
print("est premier")
pass
est_premier(16)
import math
def est_premier_elabo (nume):
'''
Fonction plus elaborée pour determiner si un nombre est premier
param : num le nombre à tester
utilisation de la bibliotheque Math
renvoi un boleen
false n'est pas premier
true le nombre est premier
'''
if nume % 2 == 0 and nume > 2:
return False
for n in range(3, int(math.sqrt(nume))+1, 2):
if nume % n == 0:
return print(False)
return print(True)
est_premier_elabo(16)
|
3ec7e25277951842988d506ed16428575601e0a2 | pdevezeaud/Python | /graven_developpement/boucle_while.py | 88 | 3.640625 | 4 | a = "q"
b = 0
while b = "q":
a = a+1
print ("Vous êtes le client n° 1")
|
144177f8c8d260cbac5c161036564151afe30d1c | pdevezeaud/Python | /gestion_erreur.py | 1,113 | 3.875 | 4 |
# iNSTRUCTION POUR GERER LES EXCEPTIONS (BASE)
'''
Gérer les exceptions : try /except (+ else, finally)
type d'exception : ValueError
NameError
TypeError
ZeroDivisioçnError
OSError
AssertionError
exemple
try:
age = input("quel age as tu ?")
age = int(age)
asset age > 25 # Je veux que age soit plus grand que 25
except AssertionError:
print("J'ai attrapé l'exception")
'''
# ageUtilisateur = input("Quel âge as tu ?")
# try:
# ageUtilisateur = int(ageUtilisateur)
# except:
# print("L'âge indiqué est incorrect !")
# else:
# print("Tu as", ageUtilisateur, "ans")
# finally:
# print("FIN DU PROGRAMME")
#autre Exemple
nombre1 = 150
nombre2 = input("Choisir nombre pour diviser : ")
try:
nombre2= int(nombre2)
print("Résultat = {}".format(nombre1/nombre2))
except ZeroDivisionError:
print("Vous ne pouvez diviser par 0.")
except ValueError:
print("Vous devez entrer un nombre.")
except:
print("Valeur incorrect.")
finally:
print("FIN DU PROGRAMME") |
4d6c8205dee0f10c9ceb4f3e647f5599679e02c1 | MrLanka/algorithm008-class02 | /Week_01/d12_559_N-maxDepth.py | 506 | 3.515625 | 4 | #还是递归,O(N)和O(logN)
#define N-Tree Node
class Node:
def __init__(self,val=None,children=None):
self.val=val
self.childeren=children
class Solution(object):
def maxDepth(self, root):
"""
:type root: Node
:rtype: int
"""
if root is None:
return 0
elif root.children == []:
return 1
else:
height = [self.maxDepth(c) for c in root.children]
return max(height) + 1
|
f56fc3015bdf8de048436f333b1109886768a67a | MrLanka/algorithm008-class02 | /Week_01/homework2_189_rotate.py | 742 | 3.96875 | 4 | #使用三次旋转数组
class Solution:
def rotate(self, nums: List[int], k: int)->None:
"""
Do not return anything, modify nums in-place instead.
"""
n=len(nums)
k=k%n #k对n取余,确定最终旋转的长度
def reverse_nums(list,start,end): #定义一个反转数组的函数
while start<end:
list[start],list[end]=list[end],list[start]
start += 1
end -=1
reverse_nums(nums,0,n-1) #整个数组旋转一次
reverse_nums(nums,0,k-1) #前k个旋转一次
reverse_nums(nums,k,n-1) #后n-k个再旋转一次
#时间复杂度O(n) 空间复杂度O(1) |
4c69d23e20efafc0e6fa5ac96bd51e5c43fecb2d | annamiklewska/GA | /generate_points.py | 3,852 | 3.609375 | 4 | import numpy as np
import random
import matplotlib.pyplot as plt
import numpy.polynomial.polynomial as p
class Points:
#domain = np.linspace(0, 10, 200) # 100 evenly distributed points in range 0-10
domain = [random.random()*10 for _ in range(100)]
def __init__(self, M):
'''
:param M: degree of the polynomial separating points
'''
self.M = M
self.w = Points.generate_parameters(self.M)
self.y_above, self.y_below = Points.generate_points(self.w)
def get_y_above(self):
return self.y_above
def get_y_below(self):
return self.y_below
def get_values(self):
return self.y_above, self.y_below
@staticmethod
def polynomial(x, w): # it was replaced by polyval
'''
:param x: vector of arguments (starting with x^0); Nx1
:param w: vector of parameters; (M-1)x1
:return: vector of polynomial values for points x; Nx1
w[0]x[M-1] + w[1]x[M-1] + ... + w[N]x[0]
w[0]x^M + w[1]x^M-1 + ... + w[N]x^0
'''
dm = [w[i] * x ** i for i in range(len(w))] # np.shape(w)[0] = no. of rows
return np.sum(dm, axis=0)
def draw(self):
domain = Points.domain
plt.scatter(domain, self.y_below, c='g')
plt.scatter(domain, self.y_above, c='r')
plt.plot(domain, p.polyval(domain, self.w))
plt.axes([-10, -10, 10, 10])
plt.show()
@staticmethod
def generate_points(w):
'''
:param w: vector of parameters
:return: y values of points above and below a polynomial line
'''
domain = Points.domain
mx = abs(max(p.polyval(domain, w)))
y_above = [p.polyval(domain, w)[i] + (abs(random.gauss(10, 50)) * mx) + 5 for i in range(len(domain))]
y_below = [p.polyval(domain, w)[i] - (abs(random.gauss(10, 50)) * mx) for i in range(len(domain))]
return y_above, y_below
@staticmethod
def generate_parameters(N):
'''
:param N: no of parameters (equal to degree of polynomial)
:return: vector of parameters (starting with x^0); Nx1
'''
# w = np.zeros(N)
# for i in range(N):
# w[i] = random.random() * 10 * random.choice((-1, 1))
# OR
# w = [random.random() * 10 * random.choice((-1, 1))
return np.random.randint(-4, 4, N)
'''
def polynomial(x, w):
dm = [w[i] * x**i for i in range(len(w))] # np.shape(w)[0] = no. of rows
return np.sum(dm, axis=0)
'''
'''
def solution02 ():
def y(x, m, b):
return m * x + b
m = random.random()*10*random.choice((-1, 1))
b = random.random()*10
w = np.array([b, m])
domain = np.linspace(0, 10, 100) # 100 evenly distributed points in range 0-10
#y_above = [y(x, m, b) + (abs(random.gauss(10, 50))+5) for x in domain]
#y_below = [y(x, m, b) - (abs(random.gauss(10, 50))+5) for x in domain]
y_above = [polynomial(domain, w)[i] + (abs(random.gauss(10, 50))) + 5 for i in range(len(domain))]
y_below = [polynomial(domain, w)[i] - (abs(random.gauss(10, 50))) + 5 for i in range(len(domain))]
plt.scatter(domain, y_below, c='g')
plt.scatter(domain, y_above, c='r')
#plt.plot(X, y(X, m, b))
plt.plot(domain, polynomial(domain, w))
plt.show()
'''
'''
def solution00():
m, b = 1, 0
lower, upper = -25, 25
num_points = 10
x1 = [random.randrange(start=1, stop=9) for i in range(num_points)]
x2 = [random.randrange(start=1, stop=9) for j in range(num_points)]
y1 = [random.randrange(start=lower, stop=m * x + b) for x in x1]
y2 = [random.randrange(start=m * x + b, stop=upper) for x in x2]
plt.plot(np.arange(10), m * np.arange(10) + b)
plt.scatter(x1, y1, c='blue')
plt.scatter(x2, y2, c='red')
'''
|
d6f2e7a6ea51d7a7c9d7841349264e77e5b70832 | StechAnurag/python_basics | /33_docstrings.py | 317 | 3.5625 | 4 | # DOCSTRINGS - are used to document the action within a function
def test(a):
'''
Info: this function tests and prints param a
'''
print(a)
# to read documenation there are 3 ways
# 1 - our text editor helps with it
# 2 - help function
# 3 - .__doc__ dundar method
print(help(test))
print(test.__doc__) |
f33e25913c4ad29958ec26a9742055d9a80c5803 | StechAnurag/python_basics | /16_list_patterns.py | 474 | 3.921875 | 4 | # Common List Patterns
basket = ['Apple', 'Guava', 'Banana', 'Lichi']
#1) length
print(len(basket))
#2) sorting
basket.sort()
print(basket)
#3) Reversing
basket.reverse()
print(basket)
#4) copying a list / portion of a list
print(basket[:])
#5) Joining list items
new_sentence = ' '.join(basket)
print(new_sentence)
#6) creating a list quickly with range(start, stop)
numbers = list(range(1, 100))
print(numbers)
whole_numbers = list(range(100))
print(whole_numbers) |
927346c7283cb20b708aa151b94679eebb28a330 | StechAnurag/python_basics | /27_is_vs_==.py | 328 | 3.96875 | 4 | # is VS ==
# Implicit type conversion takes place wherever possible
print(True == 1)
print('' == 1)
print(10 == 10.0)
print([] == [])
print('1' == 1)
print([] == 1)
# == checks if the two values are equal
# is - checks the exact reference of the values in memory
print(True is True)
print('1' is 1)
print([1,2,3] is [1,2,3]) |
44952b8458de5ee13c724e4bd172e400c4caa165 | StechAnurag/python_basics | /09_string_immutability.py | 529 | 4.03125 | 4 | # CONCEPT: STRINGS ARE IMMUTABLE in pyhton
fruit = 'Apple'
print(fruit)
# we can reassign a whpole new value to fruit
fruit = 'Orange'
print(fruit)
# but we can't replace any character of the string
# strings are immutable
#fruit[0] = 'U' # ERROR
# print(fruit)
quote = 'To be or Not to be'
# we're just overriding the value of quote in memory
print(quote.replace('be', 'me'));
# but we can save it in other variable
quote2 = quote.replace('be', 'me')
# but the quote remains original, immutable
print(quote)
print(quote2)
|
5426ce922c71f599e2336eea57b9ad0a08458e03 | StechAnurag/python_basics | /03_numbers.py | 405 | 3.71875 | 4 |
print(2+4)
print(type(6))
print(9*9)
print(type(4/2))
print(type(10.56))
# implict type conversion
print(type(20 + 1.1)) #float
# exponentail operator
print(2 ** 3) #equals 8
# divide and round operator
print(2 // 3) #equals 0
print(5 // 4) #equals 1
# modular division
print(5 % 4) #equals 1
#Math Functions
print(round(10.45))
print(abs(-90))
# google --> python maths functions for more |
bf498bfa0db5373377e0403bbee3bedc259bd9a1 | rahimnathwani/combogrid | /combogrid/plot.py | 2,463 | 3.75 | 4 | import pandas as pd
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
import datetime
def plot(
df,
x,
y_line,
y_bar,
facet_dimension,
ncols=2,
percent_cols=[],
style="fivethirtyeight",
):
"""Plots a grid of combo charts from a pandas dataframe.
Parameters
----------
df : pandas.core.frame.DataFrame
The data you want to plot
x : str
The name of the column to plot on the horizontal axis
y_line : str
The name of the column to plot as a line
y_bar : str
The name of the column to plot as bars
facet_dimension : str
The name of the column to split the data into multiple charts
ncols : int, optional
The number of columns in the grid (default is 2)
percent_cols : list of str, optional
The name(s) of the column(s) whose scale should be X% not 0.X (default is [])
style : str, optional
The matplotlib style (theme) to use (default is "fivethirtyeight")
Example
------
plt = combogrid.plot(df, "date", "volume", "price", "color")
plt.show()
"""
y1, y2 = y_line, y_bar
plt.style.use(style)
@matplotlib.ticker.FuncFormatter
def decimal_to_percentage(x, pos):
return "{0:.0%}".format(x)
facets = set(df[facet_dimension])
nrows = int(np.ceil(len(facets) / ncols))
indices = [(row, col) for row in range(nrows) for col in range(ncols)]
mapping = {facet: indices.pop() for facet in facets}
plt.rcParams.update({"figure.autolayout": True})
fig, ax = plt.subplots(nrows, ncols, figsize=(6 * ncols, 5 * nrows))
for facet in facets:
row, col = mapping[facet]
dff = df[df[facet_dimension] == facet]
ax1 = ax[row][col]
ax1.plot(dff[x], dff[y1], color="red")
if y1 in percent_cols:
ax1.yaxis.set_major_formatter(mtick.PercentFormatter)
ax1.set(
xlim=(df[x].min(), df[x].max()),
ylim=(df[y1].min(), df[y1].max()),
title=facet,
)
labels = ax1.get_xticklabels()
plt.setp(labels, rotation=45, horizontalalignment="right")
ax2 = ax1.twinx()
ax2.bar(dff[x], dff[y2], alpha=0.4)
if y2 in percent_cols:
ax2.yaxis.set_major_formatter(mtick.PercentFormatter())
ax2.set(xlim=(df[x].min(), df[x].max()), ylim=(df[y2].min(), df[y2].max()))
return plt
|
6419a504a30690b864264b1e013cd4eb7a4f4a9e | mpcalzada/data-science-path | /3-PROGRAMACION-ORIENTADA-OBJETOS/algoritmos_ordenamiento/ordenamiento_burbuja.py | 590 | 3.59375 | 4 | import random
def ordenamiento_burbuja(lista):
n = len(lista)
for i in range(n):
for j in range(0, n - i - 1):
if lista[j] > lista[j + 1]: # O(n) * O(n - i -1) = O(n) * O(n) = O(n ** 2)
lista[j], lista[j + 1] = lista[j + 1], lista[j]
return lista
if __name__ == '__main__':
tamano_lista = int(input('Tamaño de la lista: '))
lista = [random.randint(0, 100) for i in range(tamano_lista)]
print(f'La lista desordenada es: {lista}')
ordenada = ordenamiento_burbuja(lista)
print(f'La lista ordenada es: {ordenada}')
|
a9e6082aca888bbdbfe81e75e533b49f92ef397e | mpcalzada/data-science-path | /1-CURSO-BASICO-PYTHON/prueba-primalidad.py | 310 | 3.78125 | 4 | def es_primo(numero):
if numero < 2:
return False
for i in range(1, numero):
if (numero % 2) == 0:
return False
return True
if __name__ == '__main__':
n = int(input('Ingrese un numero: '))
print(f'El numero {n} {"es primo" if es_primo(n) else "no es primo"}')
|
ffe4d01767371c73cc5b1e7ab0bb5b30e0046def | drishtim17/supervisedML | /sML_example.py | 386 | 3.515625 | 4 | #!/usr/bin/python3
import sklearn
from sklearn import tree
#features about apple and orange
data=[[100,0],[130,0],[135,1],[150,1]]
output=["apple","apple","orange","orange"]
#decision tree algorithm call
algo=tree.DecisionTreeClassifier()
#train data
trained_algo=algo.fit(data,output)
#now testing phase
predict=trained_algo.predict([[136,0]])
#printing output
print(predict)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.