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
2549a209c695242606dcf47315c9ca748236826a
luciangutu/job_test
/sorting.py
1,373
3.703125
4
import random import time def insertion_sort(mylist, ascending=True): tic = time.perf_counter() for i in range(1, len(mylist)): current = mylist[i] while True: ascending_sort = i > 0 and mylist[i - 1] > current and ascending descending_sort = i > 0 and mylist[i - 1] < current and not ascending if not ascending_sort and not descending_sort: break mylist[i] = mylist[i - 1] i = i - 1 mylist[i] = current toc = time.perf_counter() return mylist, f'{toc - tic:0.4f}' def bubble_sort(mylist, ascending=True): tic = time.perf_counter() for i in range(len(mylist) - 1): for j in range(len(mylist) - 1 - i): n = mylist[j] m = mylist[j + 1] if (n > m and ascending) or (n < n and not ascending): mylist[j], mylist[j+1] = mylist[j+1], mylist[j] toc = time.perf_counter() return mylist, f'{toc - tic:0.4f}' def gen_random_list(_n, min_val, max_val): mylist = [] for _ in range(_n): val = random.randint(min_val, max_val) mylist.append(val) return mylist initial_list = gen_random_list(50, 1, 100) print(f'{initial_list=}') print(f'insertion sorted={insertion_sort(initial_list)}') print(f'bubble sorted={bubble_sort(initial_list)}')
75ae9a8e48506a2b649481e2f891ff3ad773887e
MyCatWantsToKillYou/TimusTasks
/Volume 1/src/1020.py
569
3.640625
4
#task 1020 #Difficulty 100 import math def toFixed(numObj, digits=0): return f"{numObj:.{digits}f}" def d(point1, point2): x1 = point1[0] x2 = point2[0] y1 = point1[1] y2 = point2[1] return math.sqrt((x2-x1)**2 + (y2 - y1)**2) sum = 0 pi = math.pi N, R = map(float, input().split()) points = list() for _ in range(int(N)): point = list(map(float, input().split())) points.append(point) for i in range(len(points)-1): sum += d(points[i], points[i+1]) sum += d(points[len(points)-1], points[0]) sum += 2*R*pi print(toFixed(sum, 2))
726ea99dad70b9b1bafe2ca5baa550fcd45bbfbb
MyCatWantsToKillYou/TimusTasks
/Volume 11/src/Grant.py
276
3.90625
4
# task #2056 # Difficulty 58 grades = [] for i in range(int(input())): grades.append(int(input())) if 3 in grades: print('None') elif sum(grades)/len(grades) == 5: print('Named') elif sum(grades)/len(grades) >= 4.5: print('High') else: print('Common')
d015beb141d8010fb06a1b9a4fa9d059794bccfc
MyCatWantsToKillYou/TimusTasks
/Volume 9/src/A380.py
519
3.78125
4
# task 1893 # Difficulty 55 import re string = input() num = re.findall('(\d+)', string) letter = re.findall('[A-Za-z]', string) if int(num[0]) <= 2: if letter[0] in ('A', 'D'): print('window') else: print('aisle') elif int(num[0]) <= 20: if letter[0] in ('A', 'F'): print('window') else: print('aisle') else: if letter[0] in ('A', 'K'): print('window') elif letter[0] in ('C', 'D', 'G', 'H'): print('aisle') else: print('neither')
bde44658da0b62b7cccba0a8719db12e77b810b4
MyCatWantsToKillYou/TimusTasks
/Volume 3/src/1297.py
1,447
3.59375
4
def findPal(string): def findOdd(string): max = 1 for Middle in range(len(string)): leftBorder = Middle - 1 rightBorder = Middle + 1 while (leftBorder >= 0 and rightBorder < len(string) and string[leftBorder] == string[rightBorder]): new_str = string[leftBorder:rightBorder + 1] if len(new_str) > max: max = len(new_str) if len(palindromes[0]) < len(new_str): palindromes[0] = new_str leftBorder -= 1 rightBorder += 1 return max def findEven(string): max = 1 for Middle in range(len(string)): leftBorder = Middle rightBorder = Middle + 1 while (leftBorder >= 0 and rightBorder < len(string) and string[leftBorder] == string[rightBorder]): new_str = string[leftBorder:rightBorder + 1] if len(new_str) > max: max = len(new_str) if len(palindromes[0]) < len(new_str): palindromes[0] = new_str leftBorder -= 1 rightBorder += 1 return max return max([findOdd(string), findEven(string)]) string = input() global palindromes palindromes = list() palindromes.append('') findPal(string) if palindromes[0] != '': print(palindromes[0]) else: print(string[0])
e34e78724225d30e0ebd9d5d1b985df3539abd99
MyCatWantsToKillYou/TimusTasks
/Volume 3/src/1294.py
352
3.59375
4
# task 1294 # Difficulty 310 import math ad, ac, bd, bc = map(int, input().split()) if ad*ac == bd*bc: print('Impossible.') exit(0) t1 = (ad**2+ac**2)*2.0*bd*bc-(bd**2+bc**2)*2.0*ad*ac t2 = 2*bd*bc-2*ad*ac tt = t1*1.0/t2 if tt < 0: print('Impossible.') else: tt = math.sqrt(tt) print("Distance is %(tt).0lf km." % {"tt": tt*1000})
9abf888981e08663ea5c9cc58ae646deb9d469ff
MyCatWantsToKillYou/TimusTasks
/Volume 5/src/OneStepToHappiness.py
693
3.609375
4
# task #1493 # Difficulty 51 strin1 = input() strin = int(strin1) numberleft = strin-1 numerright = strin+1 strleft = str(numberleft) strright = str(numerright) if len(strin1) != len(strleft): strleft = strleft.rjust(6, '0') if len(strin1) != len(strright): strright = strright.rjust(6, '0') left = [] right = [] left1 = [] right1 = [] for i in range(len(strleft)): if i < 3: left.append(strleft[i]) left1.append(strright[i]) else: right.append(strleft[i]) right1.append(strright[i]) if sum(list(map(int, left))) == sum(list(map(int, right))) or sum(list(map(int, left1))) == sum(list(map(int, right1))): print('Yes') else: print('No')
d6863d305c56ff797f017232ab62455525d81de7
juliyat/Python
/Random Programs/sorting.py
142
3.78125
4
s = raw_input("Enter stuff to alphabetically sort") b = "" v = s.split(" ") v.sort() for i in range(0,len(v)): b = b + v[i] + " " print b
31c5722db2896443b0b07f4e368d227bdcf271bb
juliyat/Python
/edabit/uppercaseChar.py
247
3.796875
4
def uppercaseChar(s): splitS = list(s) count = 0 ans = "" for i in splitS: count += 1 if i.isupper() == True: ans = ans + str(count) + "," return ans hmm = raw_input() print uppercaseChar(hmm) q
89746d38cbef6c12695e6d08f6e9e76a04ec1db6
juliyat/Python
/edabit/stringFlips.py
386
3.625
4
a = raw_input() b = raw_input("Enter 'word' or 'sentence'") if b == "word": c = [] d = "" for i in a: c.insert(0, i) for j in c: d = d + j print d elif b == "sentence": c = a.split(" ") d = "" for i in c: d = i + " " + d print d else: print " _ _ " print " | | " print " ______ " print " / \ "
42cd472a11f8d4992387e43608ee3f34580fe360
juliyat/Python
/edabit/medium difficulty problems/Pandigithinghy.py
111
3.578125
4
a = raw_input() for i in range(1,10): if str(i) not in a: print "False" exit() print "True"
5ac73be674ce842043d812be90dd5ea747bee572
juliyat/Python
/edabit/hard/Sieve of Eratosthenes (what!).py
258
3.625
4
def sieve_of_eratosthenes(n): list = [] for i in range(0, n): for j in range(0,i): if i % j == 0: break list.append(i) return list a = int(raw_input("Enter a number | ex: 5")) sieve_of_eratosthenes(a)
9b8119e8e2c54ecd6ca4e11b329316df16232c90
juliyat/Python
/edabit/medium difficulty problems/7boom.py
179
3.625
4
a = raw_input() b = a.split(", ") for i in range(0,len(b)): for j in b[i]: if j == "7": print "Boom!" exit() print "there is no 7 in the list"
d9330880f9ec495ba9526401eba4513b9cec1b8e
juliyat/Python
/edabit/hard/Contact List.py
547
3.9375
4
def contact_list(l, alphabetichoose): ans = "" newlist = [] for i in l: k = i.split(" ") n = k[::-1] " ".join(n) newlist.append(n) if alphabetichoose == "ASC": a = sorted(newlist) else: a = sorted(newlist, reverse=True) for t in a: g = t[::-1] h = " ".join(g) ans = ans + h + ", " return ans v = raw_input("Enter a list of names.") yello = v.split(", ") x = raw_input("Enter 'ASC' or 'DESC'") print contact_list(yello, x)
a7bb5732253560454192f3c695f2fc990f788852
juliyat/Python
/Random Programs/String palindrome check.py
400
3.8125
4
x = raw_input("enter numbers or letters") z = x.count("") - 1 if z % 2 == 0: c = z / 2 b = x[:c] v = b[::-1] if v == x[c:]: print x, "is a palindrome." else: print x, "is NOT a palindrome" else: c = (z - 1) / 2 b = x[:c] v = b[::-1] l = c + 1 if v == x[l:]: print x, "is a palindrome." else: print x, "is NOT a palindrome"
d9a467e2f1187a5a3579c29aa0d7b8e8a542da10
AmeliaMaier/Data_Science_Notes
/data_analytics/statistics/correlation_covariance.py
650
3.984375
4
import numpy as np import pandas as pd ''' the math behind pd.dataframe.cov() and pd.dataframe.corr() ''' def covariance_try(x,y): ''' INPUT: a numpy array or pandas scalar Return: the covariance of the data ''' cov = 0 x_mean = x.mean() y_mean = y.mean() ''' for ind in range(len(x.index)): cov += (x[ind]-x_mean)*(y[ind]-y_mean) ''' cov = ((x-x_mean)*(y-y_mean)).sum() return cov/len(x.index) def correlation_try(x,y): ''' INPUT: a numpy array or pandas scalar Return: the correlation of the data ''' return covariance_try(x,y)/(x.std()*y.std())
3f234ad23d683b8a3ee1846a8312b5a56a46023a
kevinyukaic/Leetcode15---3-Sum
/3Sum.py
2,157
3.71875
4
# Leetcode 15 # 3 Sum # Python 3 # Time Complexity: O(n^2) # # # Set 3 pointers to iterate through the list # # # __p_i____ p_left______________________________________p_right_ # |________|________|___________________________________|________| # # # Check the sum of 3 numbers, # if == 0: append to result # if < 0: move p_left # if > 0: move p_right # # Also, check if the element are the same after shifting the pointer # # class Solution: def threeSum(self, nums: List[int]) -> List[List[int]]: #Sort the input list from small to large nums.sort() result = [] #Case check: List element count smaller than 3 if(len(nums)<3): return result #Case check: List elements are all negative if(nums[-1] < 0): return result #Case check: List elements are all positive if(nums[0] > 0): return result #Initialize pointers for pointer_i in range(len(nums)-2): pointer_left = pointer_i+1 pointer_right = len(nums)-1 if(pointer_i > 0 and nums[pointer_i] == nums[pointer_i-1]): continue #If nums[pointer_i] is positive, then the sum will always be greater than 0 if(nums[pointer_i] > 0): break while pointer_left < pointer_right: _sum = nums[pointer_i] + nums[pointer_left] + nums[pointer_right] if(_sum == 0): result.append([nums[pointer_i], nums[pointer_left], nums[pointer_right]]) pointer_left+=1 pointer_right-=1 #Check same elements while pointer_left < pointer_right and nums[pointer_left] == nums[pointer_left-1]: pointer_left += 1 while pointer_left < pointer_right and nums[pointer_right] == nums[pointer_right+1]: pointer_right-=1 elif(_sum < 0): pointer_left+=1 elif(_sum > 0): pointer_right-=1 return result
331c4aa23955911f7c6967c0d0f3fdcec5065825
eagletusk/LeetCodeProblems
/SortArrayByParity.py
628
3.6875
4
from typing import List class Solution: def sortArrayByParity(self, A: List[int]) -> List[int]: h = 0 end = len(A)-1 temp = 0 j=0 i=0 while i < end: if A[i] %2 != 0: # odd temp = A[i] # shift every thing over j = i+1 while j <=end: A[j-1] = A[j] j+=1 # print(A) A[end] = temp end-=1 i-=1 # print(A) i+=1 return A sol = Solution() print(sol.sortArrayByParity([2,3,4,5,23])) print(sol.sortArrayByParity([3,1,2,4])) # 41245230
bba5d8dcee04707058239fa742cc7c3f13159172
ShreyanshG22/IS-Assignments
/8/ecc.py
3,192
3.671875
4
def modInverse(a, m) : a = a % m; for x in range(1, m) : if ((a * x) % m == 1) : return x return 1 def addition(x1, y1, x2, y2, field): xd = (x2 - x1) xf = modInverse(xd, field) slope = (y2 - y1) * xf slope = slope % field xnew = (slope * slope - x1 - x2) % field ynew = (-y1 + slope * (x1 - xnew)) % field temp = [xnew, ynew] return temp def doubling(x, y, field): s_num = (3 * x * x + 1) s_deno = modInverse(2 * y, field) s = (s_num * s_deno) % field xnew = (s * s - 2 * x) % field ynew = (-y + s *(x - xnew)) % field temp = list() temp.append(xnew) temp.append(ynew) return temp def main(): a = int(raw_input("a = ")) b = int(raw_input("b = ")) if(4*a*a*a + 27*b*b == 0): print("Invalid parameters a & b") return field = int(raw_input("Enter the prime field : ")) i = "y" while(i == "y"): print("Operations:\n0:Generate Keys For Diffie Hellman Key Exchange\n1:Point negation\n2:Point addition\n3:Point doubling\n4:Check whether point lies on curve\n") operation = int(raw_input("Enter the corresponding number: ")) if operation == 0: a = int(raw_input("Enter Private Key for Alice:")) b = int(raw_input("Enter Private Key for Bob:")) print("Enter the generator point:") x = int(raw_input("x coordinate - ")) y = int(raw_input("y coordinate - ")) x1, y1 = doubling(x, y, field) for i in range(a-1): x1, y1 = addition(x1, y1, x, y, field) print("Public Key for Alice: (" + str(x1)+","+str(y1)+")") x2, y2 = doubling(x, y, field) x3, y3 = addition(x1, y1, x, y, field) for i in range(b-1): x2, y2 = addition(x2, y2, x, y, field) x3, y3 = addition(x3, y3, x, y, field) print("Public Key for Bob: (" + str(x2)+","+str(y2)+")") print("Session Key Shared: (" + str(x3)+","+str(y3)+")") elif operation == 1: print("Enter the point:") x = int(raw_input("x coordinate - ")) y = int(raw_input("y coordinate - ")) ynew = (-y) % field print("Negation of point : (" + str(x) + "," + str(ynew) + ")") elif operation == 2: print("First point:") x1 = int(raw_input("x coordinate - ")) y1 = int(raw_input("y coordinate - ")) print("Second point:") x2 = int(raw_input("x coordinate - ")) y2 = int(raw_input("y coordinate - ")) if (x1 == -x2 and y1 == -y2): xnew, ynew = 0, 0 elif (x1 == x2 and y1 == y2): xnew, ynew = doubling(x1, y1, field) else: xnew, ynew = addition(x1, y1, x2, y2, field) print("Addition of points : (" + str(xnew) + "," + str(ynew) + ")") elif operation == 3: print("Enter the point:") x = int(raw_input("x coordinate - ")) y = int(raw_input("y coordinate - ")) xnew, ynew = doubling(x, y, field) print("Doubled point : (" + str(xnew) + "," + str(ynew) + ")") elif operation == 4: print("Enter the point:") x = int(raw_input("x coordinate - ")) y = int(raw_input("y coordinate - ")) lhs = (y * y) % field rhs = (x*x*x + a*x + b) % field if lhs == rhs: print("Point lies on the curve") else: print("Point doesn't lie on the curve") else: print("Invalid Operation Selection!!") continue print("\nDo you want to continue : y/n") i = raw_input().lower() return main()
29a3e2e76ceb77406e347f95a867635aeebd3336
fagan2888/leetcode-6
/solutions/014-longest-common-prefix/longest-common-prefix.py
885
4.03125
4
# -*- coding:utf-8 -*- # Write a function to find the longest common prefix string amongst an array of strings. # # If there is no common prefix, return an empty string "". # # Example 1: # # # Input: ["flower","flow","flight"] # Output: "fl" # # # Example 2: # # # Input: ["dog","racecar","car"] # Output: "" # Explanation: There is no common prefix among the input strings. # # # Note: # # All given inputs are in lowercase letters a-z. # class Solution(object): def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ if strs==[]: return "" res="" min_len=min([len(word) for word in strs]) for i in xrange(min_len): for word in strs: if word[i]!=strs[0][i]: return res res+=strs[0][i] return res
ad6c9704c7f09a5fa1d1faab38eb5d43967026a4
fagan2888/leetcode-6
/solutions/374-guess-number-higher-or-lower/guess-number-higher-or-lower.py
1,199
4.4375
4
# -*- coding:utf-8 -*- # We are playing the Guess Game. The game is as follows: # # I pick a number from 1 to n. You have to guess which number I picked. # # Every time you guess wrong, I'll tell you whether the number is higher or lower. # # You call a pre-defined API guess(int num) which returns 3 possible results (-1, 1, or 0): # # # -1 : My number is lower # 1 : My number is higher # 0 : Congrats! You got it! # # # Example : # # # # Input: n = 10, pick = 6 # Output: 6 # # # # The guess API is already defined for you. # @param num, your guess # @return -1 if my number is lower, 1 if my number is higher, otherwise return 0 # def guess(num): class Solution(object): def guessNumber(self, n): """ :type n: int :rtype: int """ low=1 high=n num=(low+high)/2 while guess(num)!=0: if guess(num)<0: high=num num=(low+high)/2 else: low=num num=(low+high)/2 if guess(num)!=0: if num==low: num=high elif num==high: num=low return num
c6b83878eca998f1213e7fc86f321df4f59803df
fagan2888/leetcode-6
/solutions/919-projection-area-of-3d-shapes/projection-area-of-3d-shapes.py
1,790
4
4
# -*- coding:utf-8 -*- # On a N * N grid, we place some 1 * 1 * 1 cubes that are axis-aligned with the x, y, and z axes. # # Each value v = grid[i][j] represents a tower of v cubes placed on top of grid cell (i, j). # # Now we view the projection of these cubes onto the xy, yz, and zx planes. # # A projection is like a shadow, that maps our 3 dimensional figure to a 2 dimensional plane.  # # Here, we are viewing the "shadow" when looking at the cubes from the top, the front, and the side. # # Return the total area of all three projections. # #   # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # Example 1: # # # Input: [[2]] # Output: 5 # # # # Example 2: # # # Input: [[1,2],[3,4]] # Output: 17 # Explanation: # Here are the three projections ("shadows") of the shape made with each axis-aligned plane. # # # # # Example 3: # # # Input: [[1,0],[0,2]] # Output: 8 # # # # Example 4: # # # Input: [[1,1,1],[1,0,1],[1,1,1]] # Output: 14 # # # # Example 5: # # # Input: [[2,2,2],[2,1,2],[2,2,2]] # Output: 21 # # #   # # # # # Note: # # # 1 <= grid.length = grid[0].length <= 50 # 0 <= grid[i][j] <= 50 # # # # # # # # # # class Solution(object): def projectionArea(self, grid): """ :type grid: List[List[int]] :rtype: int """ top=0 front=0 side=0 tgrid=[] l=len(grid) for i in xrange(l): tgrid.append([]) for gridi in grid: front+=max(gridi) for (j, gridj) in enumerate(gridi): if gridj!=0: top+=1 tgrid[j].append(gridj) for listi in tgrid: side+=max(listi) return top+front+side
1d78c25f53af6e13b92016aa228f7de121273754
fagan2888/leetcode-6
/solutions/670-maximum-swap/maximum-swap.py
1,282
3.890625
4
# -*- coding:utf-8 -*- # # Given a non-negative integer, you could swap two digits at most once to get the maximum valued number. Return the maximum valued number you could get. # # # Example 1: # # Input: 2736 # Output: 7236 # Explanation: Swap the number 2 and the number 7. # # # # Example 2: # # Input: 9973 # Output: 9973 # Explanation: No swap. # # # # # Note: # # The given number is in the range [0, 108] # # class Solution(object): def maxValue(self, strs): strs_len=len(strs) maxv=-1 for i in xrange(strs_len): v=int(strs[i]) if maxv<=v: maxv=v maxi=i return maxv, maxi def maximumSwap(self, num): """ :type num: int :rtype: int """ num_str=str(num) num_list=list(num_str) num_len=len(num_str) for i in xrange(num_len): if i == num_len-1: return num max_i,max_index=Solution.maxValue(self, num_str[i+1:]) max_index=max_index+i+1 if int(num_str[i])>=max_i: continue else: return int(num_str[:i]+num_str[max_index]+num_str[i+1:max_index]+num_str[i]+num_str[max_index+1:]) return num
6a097f9f7027419ba0649e5017bc2e17e7f822d3
fagan2888/leetcode-6
/solutions/557-reverse-words-in-a-string-iii/reverse-words-in-a-string-iii.py
773
4.1875
4
# -*- coding:utf-8 -*- # Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order. # # Example 1: # # Input: "Let's take LeetCode contest" # Output: "s'teL ekat edoCteeL tsetnoc" # # # # Note: # In the string, each word is separated by single space and there will not be any extra space in the string. # class Solution(object): def reverseWords(self, s): """ :type s: str :rtype: str """ sl=[] for word in s.split(' '): wordl=[] for i in xrange(len(word)-1,-1,-1): wordl.append(word[i]) sl.append(''.join(wordl)) rs=' '.join(sl) return rs
fceddd6e088927b0f30aa2234c9f29fcf2d0cebe
lanprijatelj/PyMandel
/pymandel/howto_dialog.py
2,002
3.5625
4
""" How To Dialog Box class for tkinter application. Created on 19 Apr 2020 @author: semuadmin """ from tkinter import Toplevel, Label, Button, LEFT from webbrowser import open_new_tab from .strings import HELPTXT, COPYRIGHTTXT, DLGHOWTO, GITHUBURL class HowtoDialog: """ How To dialog box class """ def __init__(self, app): """ Initialise Toplevel dialog """ self.__app = app # Reference to main application class self.__master = self.__app.get_master() # Reference to root class (Tk) self._dialog = Toplevel() self._dialog.title = DLGHOWTO self._dialog.geometry( "+%d+%d" % (self.__master.winfo_rootx() + 50, self.__master.winfo_rooty() + 50) ) self._dialog.attributes("-topmost", "true") self.body() def body(self): """ Set up widgets """ # Create widgets self.lbl_title = Label(self._dialog, text=DLGHOWTO) self.lbl_title.config(font=("Verdana", 16)) self.lbl_desc = Label(self._dialog, justify=LEFT, text=HELPTXT, wraplength=500) self.lbl_copyright = Label( self._dialog, text=COPYRIGHTTXT, fg="blue", cursor="hand2" ) self.btn_ok = Button(self._dialog, text="OK", width=8, command=self.ok_press) # Arrange widgets self.lbl_title.grid(column=0, row=0, padx=5, pady=5) self.lbl_desc.grid(column=0, row=2, padx=5, pady=5) self.lbl_copyright.grid(column=0, row=3, padx=5, pady=5) self.btn_ok.grid(column=0, row=5, ipadx=3, ipady=3, padx=5, pady=5) # Bind commands and hotkeys self.lbl_copyright.bind("<Button-1>", lambda e: open_new_tab(GITHUBURL)) self.btn_ok.bind("<Return>", self.ok_press) self.btn_ok.focus_set() def ok_press(self, *args, **kwargs): """ Handle OK button press """ self.__master.update_idletasks() self._dialog.destroy()
eae4db58b9bce7eb8b50163e8b1e36d4d624f3f5
atamust123/Backtracking
/assignment4.py
2,691
3.578125
4
import sys def start(maze_input_file, current_health): # if health input is not given make operations according to that maze = [] for i in maze_input_file: maze.append(list(i.split()[0])) # maze sol = [[0 for j in range(len(maze[i]))] for i in range(len(maze))] # output file x, y = 0, 0 for i in maze: if "S" in i: x, y = (maze.index(i), i.index("S")) # start x,y coordinates break sol[x][y] = "S" recursion(maze, sol, x, y, current_health) return def recursion(maze, sol, x, y, current_health): if 0 <= x < len(maze) and 0 <= y < len(maze[x]) and maze[x][y] != "W" and sol[x][y] != 1: if type(current_health) == int: # if health input is given decrease if current_health >= 0: current_health -= 1 else: if sol[x][y] != "S": sol[x][y] = 0 return False if sol[x][y] != "S": sol[x][y] = 1 if maze[x][y] == "H" and current_health != "Without Health": # take health current_health = health if maze[x][y] == "F": # we are out of maze so print sol[x][y] = "F" for i in range(len(sol)): for j in range(len(sol[i]) - 1): output.write(str(sol[i][j]) + ", ") output.write(str(sol[i][-1]) + "\n") return True elif recursion(maze, sol, x, y - 1, current_health): # go left return True elif recursion(maze, sol, x - 1, y, current_health): # go up return True elif recursion(maze, sol, x, y + 1, current_health): # go right return True elif recursion(maze, sol, x + 1, y, current_health): # go go down return True else: if type(current_health) == int: current_health += 1 if sol[x][y] != "S": sol[x][y] = 0 # unsigned coordinates by the rule of backtracking return False else: return False try: maze_input = open(sys.argv[1], "r") # first argument without health maze__health_input = open(sys.argv[2], "r") # second argument with healt health = int(sys.argv[3]) # output = open(sys.argv[4], "w") start(maze_input, "Without Health") # start for maze without health command output.write("\n") start(maze__health_input, health) # start for maze with health output.close() maze__health_input.close() # close files. maze_input.close() except: print("An error occurred") exit(-1)
6f4b3f90db0be1ccc197aacca9b625642c498aee
Raziel10/AlgorithmsAndMore
/Probability/PowerSet.py
267
4.34375
4
#Python program to find powerset from itertools import combinations def print_powerset(string): for i in range(0,len(string)+1): for element in combinations(string,i): print(''.join(element)) string=['a','b','c'] print_powerset(string)
01773bd7107e2ad18ee20cd84cccf4316f2cd2e5
sorachii/2020-advent-of-code
/day3/main.py
656
3.546875
4
def ans1(): count = 0 r = 0 c = 0 while r + 1 < len(G): r += 1 c += 3 if G[r][c % len(G[r])] == "#": count += 1 return count def ans2(): count = 0 slopes = [(1, 1), (3, 1), (5, 1), (7, 1), (1, 2)] ans = 1 for (dc, dr) in slopes: c = 0 r = 0 count = 0 while r < len(G): c += dc r += dr if r < len(G) and G[r][c % len(G[r])] == "#": count += 1 ans *= count return ans G = [] with open("input") as f: for line in f: G.append(list(line.strip())) print(ans1()) print(ans2())
c226e4433d1a38e78d432dbf6af4040eafcb7b47
JadeWibbels/ObjectOrientedDesign
/shapes/display.py
1,133
3.625
4
from init_db import CreateShapesDB import shapes class PrettyPrint(): def __init__(self): #create database self.db = CreateShapesDB() #sort by shapes self.sortedShapes = sorted(self.db.data, key=self.getKey) self.shape_counts = {'circle':0, 'square':0, 'triangle':0} self.shape_objects = [shapes.Circle(), shapes.Square(), shapes.Triangle()] def getKey(self, shape): return shape.name def print_db_info(self): print("Database contains ", len(self.sortedShapes), " shapes.") for element in self.shape_objects: count = sum(p.name == element.name for p in self.sortedShapes) print("There are ",count ,element.name, "objects") self.shape_counts[element.name] = count #display shapes for item in self.shape_objects: item.__repr__(self.shape_counts[item.name]) #try to print out all shapes of a sort on a single line #so maybe like item.__repr__() * sum(p.name == 'circle' for p in self.sortedShapes) or something??? display = PrettyPrint() display.print_db_info()
fc36a90005153632ee6c294835b239c727ac4c63
naman14310/DataStructures_Algorithms
/Dynamic Programming/longest_increasing_subsequence.py
478
3.671875
4
def count(arr,lis): arr1=list() for j in range(1,len(arr)): if arr[j]>arr[0]: arr1.append(lis[j-1]) else: arr1.append(0) return max(arr1) arr = list() n = int(input("how many no. you want to enter : ")) lis = [0]*n print("enter numbers : ") for i in range(n): arr.append(int(input())) for i in range(n-1 , -1 , -1): if(i==n-1): lis[i]=1 else: lis[i]=count(arr[i:],lis[i+1:])+1 print("length of longest increasing subsequence will be :" , max(lis))
1099457b7858d64bebc3e78e1f75657c9d10bccc
786572258/studyRepos
/python/function.py
233
3.53125
4
# -*- coding: UTF-8 -*- var1 = 200 var2 = 400 def printme( str ): "打印传入的字符串到标准显示设备上" var1 = 300 print str print "var1=",var1 var2 = 600 return var1 = 100 printme("哈哈"); print var2
f845db88c8bb6e269928b3c010cec0d7a459b444
BowmanChow/RobotDesign
/ImageRecognition/layers/conv_layer.py
9,553
3.625
4
# -*- encoding: utf-8 -*- import numpy as np import scipy.signal # if you implement ConvLayer by convolve function, you will use the following code. from scipy.signal import fftconvolve as convolve class ConvLayer(): """ 2D convolutional layer. This layer creates a convolution kernel that is convolved with the layer input to produce a tensor of outputs. Arguments: in_channels: Integer, the channels number of input. out_channels: Integer, the number of out_channels in the convolution. kernel_size: Integer, specifying the height and width of the 2D convolution window (height==width in this case). pad: Integer, the size of padding area. trainable: Boolean, whether this layer is trainable. """ def __init__(self, in_channels, out_channels, kernel_size, pad=0, trainable=True): self.in_channels = in_channels self.out_channels = out_channels self.kernel_size = kernel_size self.pad = pad assert pad < kernel_size, "pad should be less than kernel_size" self.trainable = trainable self.XavierInit() self.grad_W = np.zeros_like(self.W) self.grad_b = np.zeros_like(self.b) def XavierInit(self): raw_std = (2 / (self.in_channels + self.out_channels))**0.5 init_std = raw_std * (2**0.5) self.W = np.random.normal( 0, init_std, (self.out_channels, self.in_channels, self.kernel_size, self.kernel_size)) self.b = np.random.normal(0, init_std, (self.out_channels,)) def forward(self, Input): ''' forward method: perform convolution operation on the input. Agrs: Input: A batch of images, shape-(batch_size, channels, height, width) ''' ############################################################################ # TODO: Put your code here # Apply convolution operation to Input, and return results. # Tips: you can use np.pad() to deal with padding. # print("conv layer forward") self.Input = Input # print(f'input shape : {Input.shape}') input_after_pad = np.pad( Input, ((0,), (0,), (self.pad,), (self.pad,)), mode='constant', constant_values=0) input_after_pad_stride = np.lib.stride_tricks.as_strided(input_after_pad, shape=( input_after_pad.shape[0], input_after_pad.shape[1], input_after_pad.shape[2]-self.kernel_size+1, input_after_pad.shape[3]-self.kernel_size+1, self.kernel_size, self.kernel_size), strides=input_after_pad.strides+(input_after_pad.strides[2], input_after_pad.strides[3])) output = np.einsum('bchwij,fcij->bfhw', input_after_pad_stride, self.W) output += np.einsum('bfhw,f->bfhw', np.ones(output.shape), self.b) # print(f'output shape : {output.shape}') return output ############################################################################ def backward(self, delta): ''' backward method: perform back-propagation operation on weights and biases. Args: delta: Local sensitivity, shape-(batch_size, out_channels, output_height, output_width) Return: delta of previous layer ''' ############################################################################ # TODO: Put your code here # Calculate self.self.grad_W, self.grad_b, and return the new delta. # print("conv layer backward") self.grad_W = np.zeros((delta.shape[0],)+self.W.shape) input_after_pad = np.pad( self.Input, ((0,), (0,), (self.pad,), (self.pad,)), mode='constant', constant_values=0) input_after_pad_stride = np.lib.stride_tricks.as_strided(input_after_pad, shape=( input_after_pad.shape[0], input_after_pad.shape[1], input_after_pad.shape[2]-delta.shape[2]+1, input_after_pad.shape[3]-delta.shape[3]+1, delta.shape[2], delta.shape[3]), strides=input_after_pad.strides+(input_after_pad.strides[2], input_after_pad.strides[3])) # for batch in range(self.grad_W.shape[0]): # for filt in range(self.grad_W.shape[1]): # for channel in range(self.grad_W.shape[2]): # self.grad_W[batch, filt, channel] = scipy.signal.correlate2d( # input_after_pad[batch, channel], delta[batch, filt], 'valid') self.grad_W = np.einsum('bchwij,bfij->bfchw', input_after_pad_stride, delta) self.grad_W = np.mean(self.grad_W, axis=0) # self.grad_b = np.zeros((delta.shape[0],)+self.b.shape) # for batch in range(self.grad_W.shape[0]): # for filt in range(self.grad_W.shape[1]): # self.grad_b[batch, filt] = np.sum( # delta[batch, filt, :, :], axis=None) # self.grad_b = np.einsum('bfij->bf', delta) # self.grad_b = np.mean(self.grad_b, axis=0) # # print(self.grad_b.shape) grandient_input_pad = np.zeros([self.Input.shape[0], self.Input.shape[1], self.Input.shape[2] + 2*self.pad, self.Input.shape[3] + 2*self.pad]) for batch in range(grandient_input_pad.shape[0]): for filt in range(self.out_channels): for channel in range(self.in_channels): grandient_input_pad[batch, channel] += scipy.signal.convolve2d( delta[batch, filt], np.rot90(self.W[filt, channel], 0), 'full') # rot = np.rot90(self.W, 2, axes=(2, 3)) # # rot = self.W # delta_pad = np.pad(delta, ((0,), (0,), (self.kernel_size-1,), # (self.kernel_size-1,)), mode='constant', constant_values=0) # delta_pad_stride = np.lib.stride_tricks.as_strided(delta_pad, shape=( # delta_pad.shape[0], delta_pad.shape[1], delta_pad.shape[2]-rot.shape[2]+1, delta_pad.shape[3]-rot.shape[3]+1, rot.shape[2], rot.shape[3]), # strides=delta_pad.strides+(delta_pad.strides[2], delta_pad.strides[3])) # # print(rot) # # print(delta_pad_stride[0]) # grandient_input_pad = np.einsum( # 'bfhwij,fcij->bchw', delta_pad_stride, rot) grandient_input = grandient_input_pad[:, :, self.pad:self.pad + self.Input.shape[2], self.pad:self.pad+self.Input.shape[3]] # print(f"output shape : {grandient_input.shape}") return grandient_input ############################################################################ # layer = ConvLayer(2, 3, 3, 1) # layer.W = np.array([[[[0, 0, 1], # [0, 1, 0], # [0, 0, 1]], # [[1, 1, 0], # [0, 1, 0], # [0, 0, 1]]], # [[[0, 0, 1], # [0, 1, 0], # [1, 1, 0]], # [[1, 0, 0], # [0, 1, 1], # [0, 0, 1]]], # [[[0, 1, 1], # [1, 1, 1], # [0, 0, 1]], # [[1, 1, 1], # [0, 1, 0], # [1, 0, 1]]]] # ) # layer.b = np.array([1, 0, 0]) # # print(layer.W) # # print(layer.b) # Input = np.array([[[[7, 2, 0, 7, 9, 7], # [0, 5, 7, 1, 4, 8], # [7, 2, 3, 7, 5, 3], # [8, 2, 7, 1, 8, 6], # [8, 0, 8, 4, 6, 6]], # [[7, 5, 9, 6, 1, 1], # [9, 9, 8, 6, 6, 7], # [2, 3, 6, 0, 5, 2], # [9, 1, 6, 8, 9, 8], # [5, 6, 5, 8, 3, 6]]], # [[[1, 5, 7, 8, 9, 7], # [2, 1, 6, 2, 1, 0], # [0, 9, 5, 5, 8, 7], # [3, 4, 8, 1, 8, 2], # [4, 2, 8, 6, 6, 2]], # [[6, 9, 0, 6, 2, 6], # [2, 6, 1, 4, 4, 6], # [0, 0, 0, 9, 9, 8], # [1, 1, 2, 6, 9, 1], # [0, 7, 3, 3, 9, 0]]]]) # out = layer.forward(Input) # print(out[0]) # g = layer.backward(out) # print(g[0]) # Input = np.random.randint(0, 64, [3, 4, 8, 8]) # print(Input) # print() # input_after_pad = np.pad( # Input, ((0,), (0,), (2,), (2,)), mode='constant', constant_values=0) # print(input_after_pad) # print() # Input = np.random.randint(0, 10, [3, 5, 6]) # print(Input) # out = np.random.randint(0, 2, [3, 2, 2]) # print(out) # Input = np.lib.stride_tricks.as_strided(Input, shape=( # Input.shape[0], Input.shape[1]-out.shape[1]+1, Input.shape[2]-out.shape[2]+1, out.shape[1], out.shape[2]), strides=Input.strides+(Input.strides[1], Input.strides[2])) # # out = np.zeros((6,) + Input.shape) # # print(Input) # o = np.einsum('klmij,kij->klm', Input, out) # print(o) # input = np.ones([3, 4]) # o = np.random.randint(0, 9, [4]) # print(input) # print(o) # print(np.einsum('ki->k', input))
6c035ce03cfa091d55229b90a8cb0b250201bf8a
zico731/convertisseur-de-chiffre_romain
/nb2romanNumber.py
716
3.53125
4
decimal=[1000,900,500,400,100,90,50,40,10,9,5,4,1] romain=["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"] def conv_romain(chiffre): #assert chiffre >0 and chiffre< 4000, "le nombre saisi doit être compris entre 1 et 3999" chiffre0=chiffre i=0 resultat ="" while chiffre>0: if chiffre>=decimal[i]: resultat+=romain[i] chiffre-=decimal[i] else: i += 1 return chiffre0,resultat nb=1 while nb !=0: nb=int(input("Entrez un nombre (0 = Quitter): ")) if 0 < nb < 4000: print(conv_romain(nb)) elif nb > 0: print ("le nombre saisi doit être compris entre 1 et 3999 !") print("")
da7bd9d5abbdd838c1110515dde30c459ed8390c
Smita1990Jadhav/GitBranchPracticeRepo
/condition&loops/factorial.py
278
4.25
4
num=int(input("Enter Number: ")) factorial=1 if num<1: print("Factorial is not available for negative number:") elif num==0: print("factorial of 1 is zero: ") else: for i in range(1,num+1): factorial=factorial*i print("factorial of",num,"is",factorial)
12c116fea19b6cc1bcfd60a13a59ed187b449011
Setysdv/python-class
/E9.py
2,146
3.859375
4
#EX 045 t = 0 while t <= 50: a= int(input ('add number: ')) t = t + a j= str (t) print ('the total is' + j) else: print('the total is more than the 50') #EX 046 n=0 while n<=5: n=int(input('Enter a number:')) print('The last number you entered was a ' + n) #EX 047 a = int(input('add a number:')) b = int(input('add another number:')) v = a + b c = input('do you want to add another number?') while c == 'yes' or c == 'Yes' or c == 'YES': d = int(input('add another number:')) t = v + d c = input('do you want to add another number?') else: print(t) #EX 048 a = input('enter your guest name:') print(a + ' ' + 'has now been invited') number_g = 1 b = input('do you want to invite sb else?') while b == 'yes' or b == 'Yes' or b == 'YES': c = input('enter your guest name:') number_g = number_g + 1 print(c + 'has now been invited') b = input('do you want to invite sb else?') else: print(number_g) #EX 049 compnum = 50 guess = 0 score = 0 while compnum != guess : guess = int(input('add a number:')) score = score + 1 if guess < compnum : print('too low') elif guess > compnum : print('too high') print('welldone,your score is',score) #EX 050 a = int(input('enter a number between 10 to 20')) while a < 10: print('too low') a = int(input('enter a number between 10 to 20')) while a > 20: print('too high') a = int(input('enter a number between 10 to 20')) else: print('thank you') #EX 051 num = 10 while num > 0: print('there are',num,'green bottles hanging on the wall,if 1 green bottle should accidently fall') a = int(input('how many bottles will be hanging on the wall?')) num -= 1 while num != a: print('no,try again') a = int(input('how many bottles will be hanging on the wall?')) if num == a: print('there will be',num,'bottles hangin on the wall') print('there are no more bottles on the wall')
f500b19e773d6a0e8a5a01955d0fe634bd737391
picnic-yu/study-demo
/python/list.py
784
3.65625
4
nameList = ['小明','terry','angel'] # 1.长度 print(len(nameList))#3 #索引取值 print(nameList[1])#terry # 追加元素到末尾: nameList.append('jerry') print(nameList)#['小明','terry','angel','jerry'] # 把元素插入到指定的位置 nameList.insert(1,'Jack') print(nameList)#['小明','Jack','terry','angel','jerry'] # 删除list末尾的元素 pop nameList.pop() print(nameList)#['小明','Jack','terry','angel'] # 要删除指定位置的元素,用pop(i)方法,其中i是索引位置 nameList.pop(1) print(nameList)#['小明','terry','angel'] # 列表生成器 print([x * x for x in range(1, 11) if x % 2 == 0])#[4, 16, 36, 64, 100] # 2层 print([m + n for m in 'ABC' for n in 'XYZ'])#['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']
75f244a134e091b731a7af76935dcd317b4fb715
davidtc8/Data-Analysis-with-Pandas
/Python_project_code.py
8,956
4.28125
4
""" What this project is about? What I did in the Python project was to analyze 3 franchises from a fictitious company, using pandas dataframes in Python. For this project I used For, While Loops, Function Definition, Main Function, Numpys and Pandas """ import pandas as pd import time import numpy as np #here's the dictionary with the keys (cities) and values(csv's files) CITY_DATA = { 'chicago': 'chicago.csv', 'new york city': 'new_york_city.csv', 'washington': 'washington.csv' } #list of months months = ['all', 'january', 'february', 'march', 'april', 'may', 'june'] #list of days days = ['all','monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'] #dataframe = None df = None start_loc = 0 #defining the function get_filters that will get city, month and day def get_filters(): """ Asks user to specify a city, month, and day to analyze. Returns: (str) city - name of the city to analyze (str) month - name of the month to filter by, or "all" to apply no month filter (str) day - name of the day of week to filter by, or "all" to apply no day filter """ print('Hello! Let\'s explore some US bikeshare data!\n') # get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs while True: city = input("\nWhat city can I get data for you?: ").lower() if city not in CITY_DATA: print('\nYour answer is invalid. Please write Chicago, New Work or Washington') continue else: break # get user input for month (all, january, february, ... , june) while True: month = input ("\nPlease enter a month from Jan-Jun you wish to perform analysis for: ").lower() if month not in months : print ("\nYour answer is invalid. Please write a month from Jan-June") continue else: break # get user input for day of week (all, monday, tuesday, ... sunday) while True: day = input("\nPlease enter the day you wish to perform analysis for: ").lower() if day not in days: print ("\nYour answer is invalid. Please write a day dude, don't make me waste my time") continue else: break return city, month, day def load_data(city, month, day): """ Loads data for the specified city and filters by month and day if applicable. Args: (str) city - name of the city to analyze (str) month - name of the month to filter by, or "all" to apply no month filter (str) day - name of the day of week to filter by, or "all" to apply no day filter Returns: df - Pandas DataFrame containing city data filtered by month and day """ #load the file of the city the user chose city_file = CITY_DATA[city] #Convert the data into pandas and read the csv df = pd.read_csv(city_file) #Start Time to datetime df['Start Time'] = pd.to_datetime(df['Start Time']) #Get the month df['month'] = df['Start Time'].dt.month #get the day df['day_of_week'] = df['Start Time'].dt.day_name() if month != 'all': # use the index of the months list to get the corresponding int month = months.index(month) + 1 # filter by month to create the new dataframe df = df[df['month'] == month] # filter by day of week if applicable if day != 'all': # filter by day of week to create the new dataframe df = df[df['day_of_week'] == day.title()] print('the city you entered is "{}" and the file Im going to read is: {}'.format(city, city_file)) print('\n') print('-'*40) print('\n') return df #this function will tell me which month, day and hour are the most frequent by clients def time_stats(df): """Displays statistics on the most frequent times of travel.""" print('\nCalculating The Most Frequent Times of Travel...\n') start_time = time.time() # TO DO: display the most common month df['Start Time'] = pd.to_datetime(df['Start Time']) # TO DO: display the most common month df['month'] = df['Start Time'].dt.month popular_month = df['month'].mode()[0] print('\nMost Common Month:', popular_month) # TO DO: display the most common day of week df['day_of_week'] = df['Start Time'].dt.day_name() popular_day_of_the_week = df['day_of_week'].mode()[0] print('\nMost Common Day of the Week:', popular_day_of_the_week) # TO DO: display the most common start hour df['hour'] = df['Start Time'].dt.hour popular_hour = df['hour'].mode()[0] print('\nMost Popular Start Hour:', popular_hour) print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) #this function will tell me, which are the most frequent stations def station_stats(df): """Displays statistics on the most popular stations and trip.""" print('\nCalculating The Most Popular Stations and Trip...\n') start_time = time.time() # TO DO: display most commonly used start station most_used_start_station = df['Start Station'].mode()[0] print('\nMost Popular Start Station: ', most_used_start_station) # TO DO: display most commonly used end station most_used_end_station = df['End Station'].mode()[0] print('\nMost Popular End Station: ', most_used_end_station) # TO DO: display most frequent combination of start station and end station trip df['Combined'] = df['Start Station'] + 'to' + ['End Station'] combined_stations = df['Combined'].mode()[0] print('\nMost frequent used station between Start and Eng Stations: ', combined_stations) print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) #this function will let me know, which are the def trip_duration_stats(df): """Displays statistics on the total and average trip duration.""" print('\nCalculating Trip Duration...\n') start_time = time.time() # TO DO: display total travel time total_travel_time = df['Trip Duration'].sum() print('\nthe amount of total travel are {}'.format(total_travel_time)) # TO DO: display mean travel time mean_travel_time = df['Trip Duration'].mean() print('\nThe mean of the travles are: {}'.format(mean_travel_time)) print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) def user_stats(df): """Displays statistics on bikeshare users.""" print('\nCalculating User Stats...\n') start_time = time.time() # TO DO: Display counts of user types user_type_count = df.groupby('User Type')['User Type'].count() print('\nThe total number of users are: {}'.format(user_type_count)) # TO DO: Display counts of gender if 'Gender' in df.columns: gender_count = df.groupby('Gender')['Gender'].count() print('\ntotal travel time: ', gender_count) else: print('\nThere are no columns about gender') # TO DO: Display earliest, most recent, and most common year of birth #earliest year from the database try: earliest_year = df['Birth Year'].min() print('The earliest year from the database {} is {}'.format(city, earliest_date)) except: print('There is no data available for the input you put') #most recent year try: recent_year = df['Birth Year'].max() print('The most recent year from the database {} is {}'.format(city, recent_year)) except: print('There is no data available for the input you put') #most common year try: common_year = df['Birth Year'].mode()[0] print('The earliest year from the database {} is {}'.format(city, common_year)) except: print('There is no data available for the input you put') print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) def raw_data(df): """Ask the user if he wants to display the first five rows of data.""" user_choice = input("\nWould you like to see first 5 rows of raw data; type 'yes' or 'no'?:").lower() if user_choice in ('yes', 'y'): i = 0 while True: print(df.iloc[i:i + 5]) i += 5 next_rows = input('Would you like to see more data? Please enter yes or no: ').lower() if next_rows not in ('yes', 'y'): break #Main fuction to display the inputs and results to end users def main(): while True: city, month, day = get_filters() df = load_data(city, month, day) print(df) time_stats(df) station_stats(df) trip_duration_stats(df) user_stats(df) raw_data(df) restart = input('\nWould you like to restart? Enter yes or no.\n') if restart.lower() != 'yes': break if __name__ == "__main__": main() #changes made for the github project!
bb4062daa13670fae0b8052ae9c78b72471e7675
rofgh/Computational-Linguistics-Class-Programming
/HW6 Files/cky.py
4,760
3.75
4
''' Script cky.py on the command line: python cky.py GRAMMAR_FILE SENTENCE_FILE python cky.py english_cnf.gr sentences.sen python cky.py cky_grammar.gr mary.sen cky.py returns: a .out file named after the sentence file given: this .out file will contain: For sentence in .sen file: "Parsing: sentence" if parse: for parse in parses: "Tree 1 weight: xxx Tree 1 parse in bracketed form:(()(()))()" ''' import sys import math import random from collections import defaultdict from nltk.tree import Tree ''' readGrammarFile(fn) is given: fn: the grammar text file returns: rules: rules[LHS] will produce a list of the RHS, so rules is a dictionary... with lhs nonterminals/preterminals as keys and rhs pre-, non- and terminals as values ''' def readGrammarFile(fn): f = open(fn, "r") rules = defaultdict(lambda:[]) for line in f: line = line.split('#')[0].strip() # strip out comments and whitespace if line == '': continue fields = line.split() weight = str(fields[0]) lhs = fields[1] try: rhs = (fields[2], fields[3]) # a list of RHS symbols except: rhs = (fields[2]) rules[rhs].extend( [lhs] ) # adds a list of the list of RHS symbols for x in rules.items(): print x return rules ''' genNonTerminal(fn) is a recursive (i.e. it calls itself) program that produces our sentences through picking some rhs values for each lhs key until all the symbols being fed into the function are terminals is given: nonterm: something to which the rules are applied (Starts as 'ROOT', and then within this function it is whatever nonterminals are produced in the tree) rules: rules is a dictionary... with lhs nonterminals/preterminals as keys and rhs pre-, non- and terminals as values returns: result: if all symbols are terminal this is the finished sentence, otherwise it is def genNonTerminal(nonterm, rules): # grab a random RHS for this nonterminal from the grammar numrules = len(rules[nonterm]) # randrange will produce from 0-numrules, exclusive. rule = rules[nonterm][ random.randrange(0,numrules) ] result = "" # go through each symbol in the chosen RHS for symbol in rule: if not symbol in rules: # this is a terminal symbol so write it out result += symbol + " " else: # this is a non-terminal symbol so recurse! if T == True: result += "( " + symbol + " " result += genNonTerminal(symbol, rules) if T == True: result += ")" return result T = False # Should trees be drawn? # If insufficient arguments are provided if len(sys.argv) < 2: print "Usage: python randsent.py <grammar-file> [number-of-sentences]" exit(0) ''' def tagTheWord(): exit() def parseTheSentence(line): words = line.split() print line, words, '\n' L = len(words) for x in range(L): for rhs in grammar: for lhs in range(len(grammar[rhs])): for w in grammar[rhs][lhs]: if w == words[x]: print grammar[rhs][lhs] # create a grammar from the grammar file gr = sys.argv[1] grammar = readGrammarFile(gr) # sent = sys.argv[2] sentences = open(sent, "r") print for line in sentences: sentence = parseTheSentence(line) ''' # Main code file = sys.argv[1] if len(sys.argv) >= 3: # produce trees or not? if sys.argv[1] == '-t': # if trees, argument 2 is the grammar file = sys.argv[2] # Trees are a go T =True # Which argument is the number of sentences to produce if len(sys.argv) >= 4: n = int(sys.argv[3]) else: n = 1 else: n = int(sys.argv[2]) # If no # of sentences was provided, just print 1 else: n = 1 # Turns grammar.txt into a dictionary of rules grammar = readGrammarFile(file) #print grammar print # for whatever number of sentences was asked for for i in range(n): # if trees were asked for, use nltk to produce trees, and also print bracketed string sentences if T: bracketed = "( ROOT " + genNonTerminal("ROOT", grammar) + ")" print bracketed t = Tree.fromstring(bracketed) t.draw() # if trees were not asked for, print a generated sentence else: print genNonTerminal("ROOT", grammar) print '''
1669d58901eb94e92f29ed72809e99771834b648
qiqimaochiyu/tutorial-python
/leetcode/leetcode_605.py
361
3.734375
4
class Solution: def canPlaceFlowers(self, flowerbed, n): """ :type flowerbed: List[int] :type n: int :rtype: bool """ f = [0] + flowerbed + [0] for i in range(len(f)-2): if f[i] == 0 and f[i+1] == 0 and f[i+2] == 0: f[i+1] = 1 n -= 1 return n <= 0
90d4b2c42a57a2a2a3cc351e401bf7ed486a59f8
qiqimaochiyu/tutorial-python
/leetcode/leetcode_397.py
450
3.78125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jan 22 18:53:27 2018 @author: macbook """ class Solution: def integerReplacement(self, n): """ :type n: int :rtype: int """ if n == 1: return 0 if n % 2 == 0: return self.integerReplacement(n//2)+1 else: return min(self.integerReplacement(n-1)+1,self.integerReplacement(n+1)+1)
f768a6b842d4669ac02cbc3b5246b519ae3306bb
qiqimaochiyu/tutorial-python
/leetcode/clone_binary_tree.py
623
3.859375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jan 19 14:07:14 2018 @author: macbook """ # Definition of TreeNode: class TreeNode: def __init__(self, val): this.val = val this.left, this.right = None, None class Solution: """ @param: root: The root of binary tree @return: root of new tree """ def cloneTree(self, root): # write your code here if not root: return root s = TreeNode(root) s.val = root.val s.left = self.cloneTree(root.left) s.right = self.cloneTree(root.right) return s
c5372c654dd659195eb5fa5503d1a8fb85247949
qiqimaochiyu/tutorial-python
/leetcode/leetcode_105.py
1,019
3.875
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def buildTree(self, preorder, inorder): """ :type preorder: List[int] :type inorder: List[int] :rtype: TreeNode if not preorder:return None res = TreeNode(preorder[0]) index = inorder.index(preorder[0]) left_in = inorder[:index] right_in = inorder[index+1:] left_pre = preorder[1:len(left_in)+1] right_pre = preorder[len(left_in)+1:] res.left = self.buildTree(left_pre, left_in) res.right = self.buildTree(right_pre, right_in) return res """ if inorder: index = inorder.index(preorder.pop(0)) root = TreeNode(inorder[index]) root.left = self.buildTree(preorder, inorder[:index]) root.right = self.buildTree(preorder, inorder[index+1:]) return root
39dd341cb4473578a314f31b71493557cb36b39c
nchibana/Intro-Python-II
/src/player.py
624
3.703125
4
# Write a class to hold player information, e.g. what room they are in # currently. import textwrap class Player: def __init__(self, name, current_room, items=[]): self.name = name self.current_room = current_room self.items = items def get_name(self): return self.name def get_current_room(self): return self.current_room def __str__(self): output = f"Player's items:" if len(self.items) > 0: for i in self.items: output += f"\n\t{i}" else: output = "You have no items." return output
9f0b7ec7c45ed53ae0c7141eb88d50e04c62a868
silasbispo01/todosOsDias
/Todos os dias/dia41/Exércicio3.py
832
4.1875
4
# Importação do random import random # Criação da lista de sorteios vazia listaSorteio = [] # For para cadastro de 3 pessoas for p in range(3): # Inputs para nome da pessoa e quantia doada. nome = input('Insira seu nome: ') valorDoado = int(input('Insira o valor doado: R$')) # Calculo de quantas vezes a pessoa tem direito a aparecer na lista "quantidade de chances" chances = (int(valorDoado/10)) #For para adicionar pessoa na lista de acordo com as "chances" for x in range(chances): listaSorteio.append(nome) # Método utilizado para embaralhar nomes na lista e print dos nomes embaralhados. random.shuffle(listaSorteio) print(listaSorteio) # Sorteio do ganhador utilizando o método .choice + print do nome da pessoa. print('O ganhador foi {}'.format(random.choice(listaSorteio)))
129152480d417580e47d8bfd42836cb5f3ab465e
CleitonOrtega/Python
/pythonBasico/manipulandoArquivos/primeiraManipulacao.py
437
4.0625
4
#Para incrementar uma nova linha no arquivo use a notação "a" #with open("primeiroManipulado.txt", "a") as arquivo: # arquivo.write("\nAdicionando a segunda linha") #Para ler oque esta no arquivo with open("primeiroManipulado.txt", "r") as arquivo: #Para ler linha a linha do que esta no arquivo for linha in arquivo.readlines(): print(linha) #Para ler todo o arquivo conteudo = arquivo.read() print(conteudo)
817643ffc3a8ee574371e51db8648f62c7d183a0
Davidkintero/Python-Code
/reto1/reto1.py
727
3.515625
4
print('Bienvenido al sistema de ubicación para zonas públicas WIFI') nombre_usuario = 51743 contrasena = 34715 nombre_usuarioinput = int(input('Ingrese el nombre de usuario: ')) if nombre_usuario == nombre_usuarioinput: contrasena_input = int(input('Ingrese la contrasena: ')) if contrasena == contrasena_input: captcha1= 743 captcha2= 5 * 3 - 5 - 6 captchasuma = captcha1 + captcha2 captcha_input = int(input(f'Solucione el siguiente captcha: \n743+4: ')) if captcha_input == captchasuma: print('Inicio de sesion con exito') print('Sesion Iniciada') else: print('Error') else: print('Error') else: print('Error')
d7b13bd96d8b5dab75a3abfcd2c1cf40254a150e
jjspetz/digitalcrafts
/py-exercises3/plot1.py
262
3.984375
4
#!/usr/bin/env python3 import matplotlib.pyplot as pyplot def f(x): return x + 1 def plot(): xs = list(range(-3,3)) ys = [] for x in xs: ys.append(f(x)) pyplot.plot(xs, ys) pyplot.show() if __name__ == "__main__": plot()
a68e1618e1b2887ea208e614a8dabdb6ff67eb30
jjspetz/digitalcrafts
/py-exercises2/stringreverse.py
150
4.03125
4
# reverses a string from argument import sys # get string from argument s = str(sys.argv[1]) # reverses and prints string via slice print(s[::-1])
a3e1eadfdf24f44dc353726180eee97269844c45
jjspetz/digitalcrafts
/py-exercises3/hello2.py
517
4.34375
4
#!/usr/bin/env python3 # This is a simple function that says hello using a command-line argument import argparse # formats the arguments for argparse parser = argparse.ArgumentParser() # requires at least one string as name parser.add_argument('username', metavar='name', type=str, nargs='*', help="Enter a name so the computer can say hello") def hello(name): print("Hello, {}!".format(name)) if __name__ == "__main__": args = parser.parse_args() hello(' '.join(args.username))
c46f2637edea6f94adff6a8e93f78bd858d94fc1
jjspetz/digitalcrafts
/py-exercises2/make-a-box.py
327
4.15625
4
# makes a box of user inputed hieght and width # gets user input height = int(input("Enter a height: ")) width = int(input("Enter a width: ")) # calculate helper variables space = width - 2 for j in range(height): if j == 0 or j == height - 1: print("*" * width) else: print("*" + (" "*space) + "*")
d2b524a1d98d1b97560617705a1a9ac706201f56
jjspetz/digitalcrafts
/py-exercises2/trianglenumbers.py
216
3.75
4
# prints a list of the first 100 'triangle numbers' # https://www.mathsisfun.com/algebra/triangular-numbers.html mylist = [] for n in range(1,101): Tnum = int(n*(n+1)/2) mylist.append(Tnum) print(mylist)
5c9ff36d6710c334e72abc5b9b58abc8a94758bd
jjspetz/digitalcrafts
/dict-exe/error_test.py
343
4.125
4
#!/usr/bin/env python3 def catch_error(): while 1: try: x = int(input("Enter an integer: ")) except ValueError: print("Enter an integer!") except x == 3: raise myError("This is not an integer!") else: x += 13 if __name__ == "__main__": catch_error()
3c4d7d7ec6fb2d48877d8b34dcaac6c86f470bba
jjspetz/digitalcrafts
/py-exercises3/plot-CtoF.py
335
3.84375
4
#!/usr/bin/env python3 import matplotlib.pyplot as pyplot def f(c): return c * 9 / 5 + 32 def plot(): xs = list(range(-10, 40)) ys = [] for x in xs: ys.append(f(x)) pyplot.plot(xs, ys) pyplot.xlabel("Celsius") pyplot.ylabel("Fahrenheit") pyplot.show() if __name__ == "__main__": plot()
6546f5633e42fac8fd9ba89dffde2512fac8543e
jjspetz/digitalcrafts
/dict-exe/wordSummary.py
514
3.921875
4
#!/usr/bin/env python3 ''' Takes a paragraph as an input and returns a dictionary of the word count ''' import sys def histogram(스트링): # create return dictionary and word string histo_dict = {} # split the paragraph into a list of words words = 스트링.lower().split(" ") for word in words: try: histo_dict[word] += 1 except KeyError: histo_dict[word] = 1 return histo_dict if __name__ == "__main__": print(histogram(sys.argv[1]))
c50becc4be52c6d5d090ecf80746c2a20e6bf043
FirstSS-Sub/MirrorGAN_keras
/main.py
255
3.5
4
import train import pretrain_STREAM import sys print("Which do you want to run ?") print("train: 1, pretrain: 2") x = input() if x == "1": train.main() elif x == "2": pretrain_STREAM.main() else: print("Please select 1 or 2") sys.exit()
4bdd9011b451281cdd9b3c8d4c3abbe730f9358f
kusaurabh/CodeSamples
/python_samples/check_duplicates.py
672
4.25
4
#!/usr/bin/python3 import sys def check_duplicates(items): list_items = items[:] list_items.sort() prev_item = None for item in list_items: if prev_item == item: return True else: prev_item = item return False def create_unique_list(items): unique_list = list() for item in items: if item not in unique_list: unique_list.append(item) return unique_list if __name__ == "__main__": items = ["Hello", "rt", "st", "lt", "lt"] result = check_duplicates(items) unqList = create_unique_list(items) print(items) print(result) print(unqList)
9c71cbac4f5a8a29048ac1a22443d4adced9e6b5
kusaurabh/CodeSamples
/python_samples/reducible_words.py
1,457
3.578125
4
#!/usr/bin/python3 import sys from datetime import datetime def check_subwords(word): #Exit condition if len(word) == 1: if word == "a" or word == "i": return True else: return False #Exit if word is already in reducible words list if word in reducible_words: return True status = False sub_words = list() for pos in range(len(word)): sub_word = word[:pos] + word[pos+1:] #Check is any of the sub words is legal word and recurse if sub_word in word_list: check = check_subwords(sub_word) status = status or check return status if __name__ == "__main__": print(datetime.now()) #Read file with words fileHndl = open('words_sample.txt','r') global reducible_words reducible_words = list() global word_list word_list = list() word_list = fileHndl.read().split("\n") print(datetime.now()) for word in word_list: #if word is single char and either i or a add it as reducible if len(word) > 1: #Identify reducible words status = check_subwords(word) if status: reducible_words.append(word) else: if word == "a" or word == "i": reducible_words.append(word) fileHndl.close() print(reducible_words) print(datetime.now())
a5a46c8dbaaf4c4ceee25803e0cca585d74eb883
pseudomuto/sudoku-solver
/Python/model/notifyer.py
1,164
4.125
4
class Notifyer(object): """A simple class for handling event notifications""" def __init__(self): self.listeners = {} def fireEvent(self, eventName, data = None): """Notifies all registered listeners that the specified event has occurred eventName: The name of the event being fired data: An optional parameter to be passed on listeners """ if eventName in self.listeners: for responder in self.listeners[eventName]: responder(data) def addListener(self, eventName, responder): """Registers responder as a listener for the specified event eventName: The name of the event to listen for responder: A callback method that will be notified when the event occurs """ if not eventName in self.listeners: self.listeners[eventName] = [] self.listeners[eventName].append(responder) def removeListener(self, eventName, responder): """Removes the specified listener from the set of observers eventName: The name of the event to stop listening for responder: The callback method to remove """ if eventName in self.listeners: if responder in self.listeners[eventName]: self.listeners[eventName].remove(responder)
cd7c5c9d38eb8ee78dfa53b6ec9292a873005add
Joymine/python_basic
/high_level.py
1,497
4.03125
4
classmate = ["joymine","Tom","Jack","Bill","Yoyo"] print "====================slice BEGIN =============================" print("classmate is : ",classmate) print "classmate[-1] is : ",classmate[-1] # Yoyo print "classmate[:2] is : ",classmate[:2] # ['joymine', 'Tom'] print "classmate[-2:] is : ",classmate[-2:] # ['Bill', 'Yoyo'] #c= classmate[-4:] #print "c :",c #print "c[2] is : ",classmate[2] # print "classmate[:4:2] is : ",classmate[:4:2] # ['joymine', 'Jack'] print "classmate[::2] is : ",classmate[::2] # ['joymine', 'Jack', 'Yoy print "====================Iteration BEGIN =============================" for i, value in enumerate(['A', 'B', 'C']): #enumerate usage print i,value #print "Judge classmate interable : " #isi = isinstance(classmate ,Iterable ) Can not work ,NOK print "====================List Comprehensions BEGIN =============================" print range(1,10) List1 = [] for x in range(1,10): List1.append(x*x) print List1 #above equals as below List1 == List2 List_2 = [x*x for x in range(1,10)] print List_2 #strs = [ m + n for m in [['A','B'],['a','b']] NOK # print strs NOK print "====================List Comprehensions BEGIN =============================" print "Fibonacci calculate :" def febr(x): #L = [] n,a,b = 0,0,1 while n < x: #L.append(b) yield b a,b=b,a+b n = n + 1 print L ooo = febr(int(input('input a umm :'))) ooo.next() #NOK NOT tatally understood
baf31fcf641d7c3ba8b8109d6287ff60a33f0b67
Jolie-Lv/Introduction-to-Graduate-Algorithms
/lesson 4 graphs/BellmanFord_class.py
1,456
3.546875
4
#BellmanFord.py INF = float("Inf") n=7 d= [INF for c in range(n)] c= [0 for c in range(n)] nodes="sabcde" class Graph(): def __init__(self, vertices): self.V = vertices #number of vertices self.graph = [[0 for column in range(vertices)] for row in range(vertices)] def printGraph(self, dist): #print ("Vertex \tDistance") for node in range(self.V): print (nodes[node],"\t",dist[node] ) def BellmanFord(self, src): n=self.V d = [INF] * self.V d[src] = 0 #print(d) for k in range(n-1): for u in range(n-1): for v in range(n): #cost from u to v c[u] = self.graph[u][v] #print ("c=", c) if d[u] + c[u] < d[v]: d[v] = d[u] + c[u] print("at node",u, " dists = ",d) print ("\nSolution\nVertex \tDistance") for node in range(n): print (nodes[node],"\t",d[node] ) g = Graph(6) g.graph =[ #1 2 3 4 5 6 7 #s a b c d e [0, 5,INF,INF,INF,INF], #s [INF, 0, 3,INF,INF,INF], #a [INF,INF, 0, -6, 4,INF], #b [INF, 2,INF, 0,INF, 5], #c [INF,INF,INF,INF, 0,INF], #d [INF,INF,INF,INF,INF, 0], #e ]; print("initial graph") g.printGraph(g.graph) g.BellmanFord(0);
0e02ed4c40c63d63de3b5d6bbb4d0a7309448235
Jolie-Lv/Introduction-to-Graduate-Algorithms
/lesson 2/prob6.1_MCS.py
256
3.546875
4
#6.1 max sum of contiguoius substring a = [5,15,-30,10,-5,40, 10] def findMCS(a): n = len(a) S=[0 for i in range(n)] for j in range(1, n): S[j] = max(0, a[j] + S[j-1]) print ("S = ", S) print("MCS =", max(S)) findMCS(a)
004152902e9f30f88db165dee4e563b602857c20
rspadim/QuantEquityManagement
/python/lib/learning/network_causality/garch/garch.py
3,479
3.859375
4
"""Module implements a Garch(1,1) model""" import numpy as np from scipy.optimize import minimize class Garch: """Class implements Garch(1,1) model Notes: Conditional Maximum Likelihood Estimation is used to estimate the parameters of Garch Model todo - a two point estimation method for medium to large datasets """ def __init__(self, order: tuple = (1, 1), mean: str = 'const'): """Constructor to specify order of Garch and specify mean equation Args: order (tuple, optional): order of Garch Model Defaults to (1, 1) mean (str, optional): the mean equation Defaults to 'const' """ self.mean = mean self.order = order def _loglikelihood(self, vol, a): """Returns the loglikelihood function of Garch(1,1) model Args: vol (np.ndarray): the calculated garch volatility shape = (n_samples,) a (np.ndarray): innovation of returns series shape = (n_samples,) """ return 0.5 * (np.log(vol) + a @ a / vol).sum() def _simulate_vol(self, r: np.ndarray, theta: np.ndarray = None, ) -> np.ndarray: """Simulates the garch(1,1) volatility model Args: r (np.ndarray): Returns vector theta (np.ndarray, optional): estimated weights from fitting. Defaults to None. shape = (3,) Returns: Union[np.ndarray]: predicted volatility """ n = r.shape[0] vol = np.zeros(n) # use sample variance as initial estimate vol[0] = r.var(ddof=1) omega, gamma, beta = theta for idx in range(1, n): vol[idx] = omega + gamma * r[idx-1] + beta * vol[idx-1] return vol def _constraint(self, params): """Specify constraint for variance process Args: params (np.ndarray): parameters of the optimization """ return 1 - (params[1] + params[2]) def _objective_func(self, guess: np.ndarray, r: np.ndarray) -> np.float64: """Objective function to be minimized Args: guess (np.ndarray): initial guess for optimization r (np.ndarray): the returns vector Returns: np.float64: value from loglikelihood function """ # get the garch vol vol = self._simulate_vol(r=r, theta=guess) # estimate the likelihood f = self._loglikelihood(vol, a=r) return f def fit(self, r: np.ndarray) -> 'Garch': """Fits training data via quasi maximum likelihood Args: r (np.ndarray): log returns matrix, shape = (n_samples,) n_samples is number of instances in data Returns: [object]: Garch estimated parameters """ if self.mean: a_t = r - r.mean() else: a_t = r # omega, gamma and beta guess_params = np.array([0.1, 0.2, 0.3]) cons = {'type': 'ineq', 'fun': self._constraint} self.theta = minimize(self._objective_func, guess_params, method='BFGS', options={'disp': True}, args=(a_t), constraints=cons)['x'] return self
3e925a8f0736eec9688f3597502d77f249c05e08
annapaula20/python-practice
/functions_basic2.py
2,510
4.4375
4
# Countdown - Create a function that accepts a number as an input. # Return a new list that counts down by one, from the number (as the 0th element) down to 0 (as the last element). # Example: countdown(5) should return [5,4,3,2,1,0] def countdown(num): nums_list = [] for val in range(num, -1, -1): nums_list.append(val) return nums_list # print(countdown(12)) # print(countdown(5)) # Print and Return - Create a function that will receive a list with two numbers. # Print the first value and return the second. # Example: print_and_return([1,2]) should print 1 and return 2 def print_and_return(nums_list): print(nums_list[0]) return nums_list[1] # print(print_and_return([10,12])) # First Plus Length - Create a function that accepts a list and returns the sum of the first value in the list plus the list's length. # Example: first_plus_length([1,2,3,4,5]) should return 6 (first value: 1 + length: 5) def first_plus_length(nums_list): return nums_list[0] + len(nums_list) # print(first_plus_length([13,2,3,4,5])) # Values Greater than Second - Write a function that accepts a list and # creates a new list containing only the values from the original list that are greater than its 2nd value. # Print how many values this is and then return the new list. # If the list has less than 2 elements, have the function return False # Example: values_greater_than_second([5,2,3,2,1,4]) should print 3 and return [5,3,4] # Example: values_greater_than_second([3]) should return False def values_greater_than_second(orig_list): new_list = [] # get the second value in the original list second_val = orig_list[1] # scan through the original list, find values greater than second value and add them to the new list for idx in range(len(orig_list)): if orig_list[idx] > second_val: new_list.append(orig_list[idx]) print(len(new_list)) return new_list # print(values_greater_than_second([5,2,3,2,1,4])) # This Length, That Value - Write a function that accepts two integers as parameters: size and value. # The function should create and return a list whose length is equal to the given size, and whose values are all the given value. # Example: length_and_value(4,7) should return [7,7,7,7] # Example: length_and_value(6,2) should return [2,2,2,2,2,2] def length_and_value(size, value): new_list = [] for num_times in range(size): new_list.append(value) return new_list # print(length_and_value(4,7))
1df53a2b6673b813cd96186375da9b4cc3fe4132
bitsoftwang/LPC11U_LPC13U_CodeBase
/src/drivers/filters/iir/python/iir_f_response_test.py
1,661
3.515625
4
#------------------------------------------------------------------------------- # Name: iir_f_response_test # # Purpose: Shows the response of an IIR filter over time. Used to determine # how many samples are required to reach n percent of the new # input value. # # Author: K. Townsend (microBuilder.eu) # # Created: 05/05/2013 # Copyright: (c) K. Townsend 2013 # Licence: BSD # # This module requires the following libs # matplotlib - http://matplotlib.org/ # numpy - http://www.numpy.org/ #------------------------------------------------------------------------------- from array import array import matplotlib.pyplot as plt def main(): avg = 0.0 samples = 0 values = [] # Get alpha alpha = float(input("IIR alpha (0..1.0): ")) # Check alpha bounds if (alpha > 1.0): print ('Setting alpha to 1.0') alpha = 1.0 if (alpha < 0): print ('Setting alpha to 0.0') alpha = 0.0 # Run the filter until we arrive at 99.9% of newval values.append(0.0) while avg < 1.0 * 0.999: samples+=1 avg = iirAddValue(avg, alpha, 1.0) # Plot value in percent values.append(avg/0.01); print ("%d: %g" % (samples, avg)) # Display the results plt.title("IIR Response Over Time (Alpha = %g)" % (alpha)) plt.ylim(0, 110) plt.xlabel('Samples') plt.ylabel('IIR Output (%)') plt.plot(values) plt.grid(True) plt.show() pass def iirAddValue(avg, alpha, val): "Adds a new value to the IIR filter" return alpha * val + (1.0 - alpha) * avg if __name__ == '__main__': main()
607e0ba035eaa2dc9216f0884c1562036797ba79
Jagadeesh-Cha/datamining
/comparision.py
487
4.28125
4
# importing the required module import matplotlib.pyplot as plt # x axis values x = [1,2,3,4,5,6,7,8,9,10] # corresponding y axis values y = [35,32,20,14,3,30,6,20,2,30] # plotting the points plt.plot(x, y) # naming the x axis plt.xlabel('busiest places in descending-order') # naming the y axis plt.ylabel('# of important customers') # giving a title to my graph plt.title('important_customers') # function to show the plot plt.show()
b4816526ef6cc323464ac3e9f787a6032e32072f
lilimonroy/CrashCourseOnPython-Loops
/q1LoopFinal.py
507
4.125
4
#Complete the function digits(n) that returns how many digits the number has. For example: 25 has 2 digits and 144 has 3 digits. # Tip: you can figure out the digits of a number by dividing it by 10 once per digit until there are no digits left. def digits(n): count = 0 if n == 0: return 1 while (n > 0): count += 1 n = n // 10 return count print(digits(25)) # Should print 2 print(digits(144)) # Should print 3 print(digits(1000)) # Should print 4 print(digits(0)) # Should print 1
fc551ef5d0524926828fc3d57ac2e995a710e32c
chahatagarwal/log-file-generation
/logstotext.py
1,382
3.78125
4
#write logs into a text file import os from datetime import date import datetime from os import path #function to specify at which duration the log function were asked to write def getDateTimeforFile(): now = datetime.datetime.now() year = str('{:04d}'.format(now.year)) month = str('{:02d}'.format(now.month)) day = str('{:02d}'.format(now.day)) hrs = str('{:02d}'.format(now.hour)) minute = str('{:02d}'.format(now.minute)) sec = str('{:02d}'.format(now.second)) dateTime = year + "_" + month + "_" + day + " " + hrs + " h " + minute + " m " + sec + " s " + " : " return str(dateTime) #Function to create a folder based on current date it had run and also append the logs when the function is called def logfile(text): #To name the folder folder_name = str(date.today()) #to get the current path where the directory is created current_path = str(os.getcwd()) #Checking if the directory is present or not, if not present then create a directory if path.isdir(folder_name): pass else: os.mkdir(folder_name) #name the file text_file = current_path + "/" + folder_name + "/" + folder_name + ".txt" #file operation to append the text received log_file = open(text_file,"a+") log_file.write(getDateTimeforFile() + text + "\n") log_file.close() logfile("This is a Sample Log")
d7bee33069165c6d5277e916ad63bea46d3595cb
vigneshkulo/leetCode
/python3/ConcatenateBinary3.py
678
3.515625
4
class Solution: def concatenatedBinary(self, n: int) -> int: string = "" def toBinary(num): binVal = "" while (num): if (num & 1): binVal += "1" else: binVal += "0" num >>= 1 return binVal binIndex = 0 output = 0 for i in range(n, 0, -1): string = toBinary(i) for i in range(len(string)): if string[i] == '1': output += (2**binIndex) binIndex += 1 output %= ((10 ** 9) + 7) return output
d5576938365b322cccea905c899fe60ecdf420a8
vigneshkulo/leetCode
/python3/FirstAndLastPosition.py
1,275
3.578125
4
class Solution: def searchRange(self, nums: List[int], target: int) -> List[int]: def binarySearch(start, end, isLeft): if (start > end): return -1 mid = (start + end) // 2 if (target == nums[mid]): if isLeft: if (mid > 0) and (nums[mid - 1] < nums[mid]): return mid elif (mid == 0): return mid else: return binarySearch(start, mid - 1, isLeft) else: if (mid < (len(nums)-1)) and (nums[mid + 1] > nums[mid]): return mid elif (mid == (len(nums) - 1)): return mid else: return binarySearch(mid + 1, end, isLeft) if (target < nums[mid]): return binarySearch(start, mid - 1, isLeft) else: return binarySearch(mid + 1, end, isLeft) output = [-1, -1] output[0] = binarySearch(0, len(nums) - 1, True) output[1] = binarySearch(0, len(nums) - 1, False) return output
878f458d6621d4fd5d599d7debfa3bddf8f4c7d3
vigneshkulo/leetCode
/python3/MergeKSortedLists.py
806
3.765625
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def mergeKLists(self, lists: List[ListNode]) -> ListNode: heapList = [] for index, listItem in enumerate(lists): if listItem: heapq.heappush(heapList, (listItem.val, index, listItem)) dummyHead = ListNode() prev = dummyHead while (len(heapList)): item = heapq.heappop(heapList) if item[2].next: heapq.heappush(heapList, (item[2].next.val, item[1], item[2].next)) prev.next = item[2] prev = prev.next prev.next = None return dummyHead.next
ae0078ff02d625446636ede7dbd81af523cc8ce0
vigneshkulo/leetCode
/python3/AddOne.py
1,268
3.640625
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def plusOne(self, head: ListNode) -> ListNode: prevNode = None curNode = head while(curNode.next != None): nextNode = curNode.next curNode.next = prevNode prevNode = curNode curNode = nextNode curNode.next = prevNode newHead = curNode curNode = newHead carry = 1 while (curNode.next != None) and carry: carry = (curNode.val + 1) // 10 curNode.val = (curNode.val + 1) % 10 curNode = curNode.next if carry: carry = (curNode.val + 1) // 10 curNode.val = (curNode.val + 1) % 10 if carry: carryNode = ListNode(1) curNode.next = carryNode prevNode = None curNode = newHead while(curNode.next != None): nextNode = curNode.next curNode.next = prevNode prevNode = curNode curNode = nextNode curNode.next = prevNode return curNode
7a773b0a132eb8a37dc9027b02d0c13e85147831
hugett/pythonstudy
/u11/u11_13.py
535
3.515625
4
from time import clock def timeit(func, *nkwargs, **kwargs): start_time = clock() retval = func(*nkwargs, **kwargs) end_time = clock() return (end_time - start_time, retval) def fact1(N): 'use reduce' return reduce(lambda x, y: x * y, range(1, N + 1)) def fact2(N): 'use iter' ret = 1 for i in xrange(1, N + 1): ret *= i return ret def fact3(N): if N == 1: return 1 return N * fact3(N - 1) print timeit(fact1, 500) print timeit(fact2, 500) print timeit(fact3, 500)
0ca00b26b0774c6e0d1891fca4567889cc657a01
Mmingo28/Week-3
/Python Area and Radius.py
263
4.28125
4
#MontellMingo #1/30/2020 #The program asks if the user can compute the area of an circle and the radius. radius = int(input("what is the radius")) #print("what is the number of the radius"+ ) print("what is the answer") print(3.14*radius*radius)
38a3ed431f0ad709364ca74401261ed844cf6c76
Diegoamx/CS-111-Final-Project
/finalproject.py
9,486
3.9375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Nov 27 14:12:20 2019 @author: diegomurcia """ import math def clean_text(txt): """takes a string of text txt as a parameter and returns a list containing the words in txt after it has been “cleaned”. """ txt = txt.replace('.', '') txt = txt.replace(',', '') txt = txt.replace('!', '') txt = txt.replace('?', '') txt = txt.replace('"', '') txt = txt.replace('$', '') txt = txt.replace(':', '') txt = txt.replace(';', '') txt = txt.replace('-', '') txt = txt.replace('=', '') txt = txt.replace('-', '') txt = txt.replace('/', '') txt = txt.replace('(', '') txt = txt.replace(')', '') txt = txt.lower().split() return txt def sample_file_write(filename): """A function that demonstrates how to write a Python dictionary to an easily-readable file. """ d = {'test': 1, 'foo': 42} # Create a sample dictionary. f = open(filename, 'w') # Open file for writing. f.write(str(d)) # Writes the dictionary to the file. f.close() # Close the file. def sample_file_read(filename): """A function that demonstrates how to read a Python dictionary from a file. """ f = open(filename, 'r') # Open for reading. d_str = f.read() # Read in a string that represents a dict. f.close() d = dict(eval(d_str)) # Convert the string to a dictionary. print("Inside the newly-read dictionary, d, we have:") print(d) def stem(s): """ accepts a string as a parameter and returns the stem of s """ if len(s) >= 5: if s[-3:] == 'ing': if s[-5] != s[-4]: s = s[:-3] else: s = s[:-4] if s[-3:] == 'ies': s = s[:-3] s += 'y' if s[-1:] == 's': s = s[:-1] if s[-2:] == 'er': s = s[:-2] if s[-2:] == 'es': s = s[:-2] if s[-4:] == 'tion': s = s[:-4] if s[-1:] == 'y': s = s[:-1] + 'i' if s[-1:] == 'd': s = s[:-1] if s[-2:] == 'th': s = s[:-2] return s def compare_dictionaries(d1, d2): """ compute and return their log similarity score """ score = 0 total = 0 for key in d1: total += d1[key] for i in d2: if i in d1: score += math.log(d1[i]/total) * d2[i] else: score += math.log(0.5/total) * d2[i] return score class TextModel: def __init__(self, model_name): """constructs a new TextModel object by accepting a string model_name as a parameter and initializing three attributes: 1. name - a string that is a label for this text model 2. words - a dictionary that records the number of times each word appears in the text. 3. word_length - a dictionary that records the number of times each word length appears. """ self.name = model_name self.words = {} self.word_lengths = {} self.stems = {} self.sentence_lengths = {} self.exclamation = {} def __repr__(self): """ returns a string that includes the name of the model as well as the sizes of the dictionaries for each feature of the text. """ s = '' s += 'text model name: ' + self.name + '\n' s += ' number of words: ' + str(len(self.words)) + '\n' s += ' number of word lengths: ' + str(len(self.word_lengths)) + '\n' s += ' number of stems: ' + str(len(self.stems)) + '\n' s += ' number of sentence lengths: ' + str(len(self.sentence_lengths)) + '\n' s += ' number of exclamation marks: ' + str(len(self.exclamtion)) + '\n' return s def add_string(self, s): """Analyzes the string txt and adds its pieces to all of the dictionaries in this text model. """ word_list = clean_text(s) for x in word_list: length = len(x) st = stem(x) if x in self.words: self.words[x] += 1 else: self.words[x] = 1 if length in self.word_lengths: self.word_lengths[length] += 1 else: self.word_lengths[length] = 1 if st in self.stems: self.stems[st] += 1 else: self.stems[st] = 1 if '.' in self.sentence_lengths: self.sentence_lengths[st] += 1 else: self.sentence_lengths[st] = 1 if '!' in self.exclamation: self.exclamation[st] += 1 else: self.exclamation[st] = 1 def add_file(self, filename): """ adds all of the text in the file identified by filename to the model; it should not explicitly return a value """ f = open(filename, 'r', encoding='utf8', errors='ignore') text = f.read() self.add_string(text) def save_model(self): """ saves the TextModel object self by writing its various feature dictionaries to files """ a = open(self.name + '_words.txt', 'w') a.write(str(self.words)) a.close() b = open(self.name + '_word_lengths.txt', 'w') b.write(str(self.word_lengths)) b.close() c = open(self.name + '_stems.txt', 'w') c.write(str(self.stems)) c.close() d = open(self.name + '_sentence_lengths.txt', 'w') d.write(str(self.sentence_lengths)) d.close() e = open(self.name + '_exclamation.txt', 'w') e.write(str(self.exclamation)) e.close() def read_model(self): """ reads the stored dictionaries for the called TextModel object from their files and assigns them to the attributes of the called TextModel """ a = open(self.name + '_words.txt', 'r') self.words = a.read() a.close() self.words = eval(self.words) b = open(self.name + '_word_lengths.txt', 'r') self.word_lengths = b.read() b.close() self.word_lengths = eval(self.word_lengths) c = open(self.name + '_stems.txt', 'r') self.stems = c.read() c.close() self.stems = eval(self.stems) d = open(self.name + '_sentence_lengths.txt', 'r') self.sentence_lengths = d.read() d.close() self.sentence_lengths = eval(self.sentence_lengths) e = open(self.name + '_exclamation.txt', 'r') self.exclamation = e.read() e.close() self.exclamation = eval(self.exclamation) def similarity_scores(self, other): """computes and returns a list of log similarity scores measuring the similarity of self and other – one score for each type of feature """ word_score = compare_dictionaries(other.words, self.words) word_lengths_score = compare_dictionaries(other.word_lengths, self.word_lengths) stems_score = compare_dictionaries(other.stems, self.stems) sentence_lengths_score = compare_dictionaries(other.sentence_lengths, self.sentence_lengths) exclamation_score = compare_dictionaries(other.exclamation, self.exclamation) a = [word_score, word_lengths_score, stems_score, sentence_lengths_score, exclamation_score] return a def classify(self, source1, source2): """ compares the called TextModel object (self) to two other “source” TextModel objects (source1 and source2) and determines which of these other TextModels is the more likely source of the called TextModel """ scores1 = self.similarity_scores(source1) scores2 = self.similarity_scores(source2) print('scores for: ', source1.name, scores1) print('scores for: ', source2.name, scores2) a = 0 b = 0 for i in range(len(scores1)): if scores1[i] > scores2[i]: a += 1 else: b += 1 if a > b: print(self.name, ' is more likely to have come from ', source1.name) else: print(self.name, ' is more likely to have come from ', source2.name) def test(): """ Testing the function""" source1 = TextModel('source1') source1.add_string('It is interesting that she is interested.') source2 = TextModel('source2') source2.add_string('I am very, very excited about this!') mystery = TextModel('mystery') mystery.add_string('Is he interested? No, but I am.') mystery.classify(source1, source2) def run_tests(): """ Tests the Function for Friends versus Fresh Prince of Bel Air """ source1 = TextModel('Friends') source1.add_file('friends_source_text.txt') source2 = TextModel('Fresh Prince of Bel Air') source2.add_file('fresh_prince_source_text.txt') new1 = TextModel('Drake and Josh - Tree Scene') new1.add_file('d&j_tree_source_text.txt') new1.classify(source1, source2)
fa05a6cb6cf5213b5df47aa3ef0eb3d44741c1da
abeljoseph/model_estimation
/sequential_classifier.py
6,437
3.5
4
import random from math import sqrt import numpy as np from statistics import mean, stdev import matplotlib.pyplot as plt import scipy.io classifier_count = 0 class sequential_classifier: def __init__(self, A, B): self.A = A self.B = B global classifier_count classifier_count += 1 self.classifier_num = classifier_count # Adapted from lab 1 @staticmethod def get_euclidean_dist(px1, py1, px0, py0): return sqrt((px0 - px1) ** 2 + (py0 - py1) ** 2) # Adapted from lab 1 @staticmethod def get_med(a, b, prototype_A, prototype_B): dist_a = sequential_classifier.get_euclidean_dist(prototype_A[0], prototype_A[1], a, b) dist_b = sequential_classifier.get_euclidean_dist(prototype_B[0], prototype_B[1], a, b) return 1 if dist_a < dist_b else 2 def perform_classification(self, J=np.inf): j = 1 discriminants = [] true_n_ab = [] true_n_ba = [] A = self.A B = self.B prototype_A = 0 prototype_B = 0 while True: misclassified = True n_ba = 0 # Error count n_ab = 0 while misclassified: mis_A = [] # Misclassified points mis_B = [] n_ab, n_ba = 0, 0 if len(A) > 0: prototype_A = A[random.randint(0, len(A) - 1)] if len(B) > 0: prototype_B = B[random.randint(0, len(B) - 1)] # Classify all points for A for i, pt in enumerate(A): res = self.get_med(pt[0], pt[1], prototype_A, prototype_B) if res == 2: # Misclassified n_ab += 1 mis_A.append(pt) # Classify all points for B for i, pt in enumerate(B): res = self.get_med(pt[0], pt[1], prototype_A, prototype_B) if res == 1: # Misclassified n_ba += 1 mis_B.append(pt) if not n_ab or not n_ba: # No misclassified pts # Remove points from b that were classified as B if not n_ab: B = mis_B if not n_ba: A = mis_A misclassified = False discriminants.extend([[prototype_A, prototype_B]]) true_n_ab.append(n_ab) true_n_ba.append(n_ba) if (j > J) or (not len(A) and not len(B)): break j += 1 return [np.array(discriminants), true_n_ab, true_n_ba] @staticmethod def classify_points(X, Y, discriminants, true_n_ab, true_n_ba): est = 0 for i in range(len(discriminants)): a_mu = discriminants[i][0,:] b_mu = discriminants[i][1,:] est = sequential_classifier.get_med(X, Y, a_mu, b_mu) if not true_n_ba[i] and est == 1: break if not true_n_ab[i] and est == 2: break return est def calculate_error(self, J): K = 20 average_error_rate = [] min_error_rate = [] max_error_rate = [] stdev_error_rate = [] for j in range(1, J+1): error_rate = np.zeros(K) for k in range(K): res = self.perform_classification(j) total_errors = 0 classified = [] # Classify points in class A for i in range(len(self.A)): pt = self.A[i] classified.append(sequential_classifier.classify_points(pt[0], pt[1], *res)) # Add to error rate if class A is misclassified as class B if classified[i] == 2: total_errors += 1 classified = [] # Classify points in class B for i in range(len(self.B)): pt = self.B[i] classified.append(sequential_classifier.classify_points(pt[0], pt[1], *res)) # Add to error rate if class B is misclassified as class A if classified[i] == 1: total_errors += 1 # calcuate error rate error_rate[k] = (total_errors/400) # a) average error rate average_error_rate.append(np.average(error_rate)) # b) minimum error rate min_error_rate.append(np.min(error_rate)) # c) maximum error rate max_error_rate.append(np.max(error_rate)) # d) standard deviation of error rates stdev_error_rate.append(np.std(error_rate)) calculated_error_rates = [average_error_rate, min_error_rate, max_error_rate, stdev_error_rate] # Plot Error Rates J_vals = [1, 2, 3, 4, 5] plt.figure() plt.subplot(2, 1, 1) plt.title("Error Rate of Sequential Classifier as a function of J") plt.errorbar(J_vals, average_error_rate, stdev_error_rate, linestyle='-', marker='D', label='Avg Error Rate') plt.plot(J_vals, min_error_rate, "b.", linestyle='-', label='Min Error Rate') plt.plot(J_vals, max_error_rate, "r.", linestyle='-', label='Max Error Rate') plt.legend(loc='upper left') plt.xlabel('J') plt.ylabel('Error Rate') plt.subplot(2, 1, 2) plt.title("Standard Deviation of Error Rates of Sequential Classifier as a function of J") plt.plot(J_vals, stdev_error_rate, "c.", linestyle='-', label='Stdev Error Rate') plt.xlabel('J') plt.ylabel('Standard Deviation') plt.tight_layout() plt.legend(loc='upper left') plt.show() return calculated_error_rates def plot_sequential(self, x, y, estimation): fig, ax = plt.subplots() ax.plot(self.A[:,0], self.A[:,1], color='b', marker='.', linestyle='', label='Class A') ax.plot(self.B[:,0], self.B[:,1], color='r', marker='.', linestyle='', label='Class B') plt.xlabel('x1') plt.ylabel('x2') plt.title(f'Classifier {self.classifier_num}') ax.contourf(x, y, np.matrix(estimation), colors=['#d6e9ff', '#ffb0b0']) ax.contour(x, y, np.matrix(estimation), colors='purple', linewidths=0.3) ax.legend() plt.show() def perform_estimation(self, J=np.inf): if J < 1: return res = self.perform_classification(J) num_steps = 500 # Create Meshgrid for MED Classification x_grid = np.linspace(min(*self.A[:, 0], *self.B[:, 0]), max(*self.A[:, 0], *self.B[:, 0]), num_steps) y_grid = np.linspace(min(*self.A[:, 1], *self.B[:, 1]), max(*self.A[:, 1], *self.B[:, 1]), num_steps) x, y = np.meshgrid(x_grid, y_grid) estimation = [[0 for _ in range(len(x_grid))] for _ in range(len(y_grid))] for i in range(len(x_grid)): for j in range(len(y_grid)): estimation[i][j] = sequential_classifier.classify_points(x[i][j], y[i][j], *res) self.plot_sequential(x, y, estimation) data_2d = scipy.io.loadmat('data_files/mat/lab2_3.mat') points_a = data_2d['a'].astype(float) points_b = data_2d['b'].astype(float) cl_1, cl_2, cl_3, cl_4 = sequential_classifier(np.array(points_a), np.array(points_b)), \ sequential_classifier(np.array(points_a), np.array(points_b)), \ sequential_classifier(np.array(points_a), np.array(points_b)), \ sequential_classifier(np.array(points_a), np.array(points_b)) cl_1.perform_estimation() cl_2.perform_estimation() cl_3.perform_estimation() cl_4.calculate_error(J=5)
63c37b04bbfbf3c4079e8fb6c4e90c59c685d748
xywgo/Learn
/LearnPython/Chapter 11/test_cities.py
596
3.75
4
# 11-1, 11-2 import unittest from city_function import city_country_name class CityFunctionTest(unittest.TestCase): """Test for city_function.py""" def test_city_function(self): """does 'Santiago, Chile' work?""" formatted = city_country_name('santiago', 'chile') self.assertEqual(formatted, 'Santiago, Chile') def test_city_poulation_functin(self): """does 'Santiago, Chile - populatin 5000000' work?""" formatted = city_country_name('santiago', 'chile', 5000000) self.assertEqual(formatted, 'Santiago, Chile - population 5000000') if __name__ == '__main__': unittest.main()
ff0e184d8a4da4678d8f24ccc9009ac35fdb6f44
xywgo/Learn
/LearnPython/Chapter 6/alien.py
1,589
3.6875
4
#alien_0 = {} # alien_0['color'] = 'green' # alien_0['points'] = 5 # new_points = alien_0['points'] # print(f"You just earned {new_points} points!") # alien_0['x_position'] = 0 # alien_0['y_position'] = 25 # del alien_0['points'] # print(alien_0) # alien_0 = {'color': 'green'} # print(f"The alien is {alien_0['color']}.") # alien_0['color'] = 'yellow' # print(f"The alien is now {alien_0['color']}") # alien_0 = {'x_position': 0, 'y_position': 25, 'speed': 'medium'} # print(f"Original y_position: {alien_0['x_position']}") # # Move the alien to the right. # # Determine how far to move the alien based on its current speed. # if alien_0['speed'] == 'slow': # x_increment = 1 # elif alien_0['speed'] == 'medium': # x_increment = 2 # else: # # This must be a fast alien. # x_increment = 3 # # The new position is the old position plus the incremnet. # alien_0['x_position'] = alien_0['x_position'] + x_increment # print(f"New position: {alien_0['x_position']}") # Make an empty list for storing aliens. aliens = [] # Make 30 green aliens. for alien_number in range(30): new_alein = {'color': 'green', 'points': 5, 'speed': 'slow'} aliens.append(new_alein) for alien in aliens[:3]: if alien['color'] == 'green': alien['color'] = 'yellow' alien['speed'] = 'medium' alien['points'] = 10 elif alien['color'] == 'yellow': alien['color'] = 'red' alien['speed'] = 'fast' alien['points'] = 15 # Show the first 5 aliens. for alien in aliens[:5]: print(alien) print("...") # Show how many aliens have been created. print(f"Total numer of aliens: {len(aliens)}")
8fbfcc3bcd13f2db5c6178cd7ed40f9eade923fc
xywgo/Learn
/LearnPython/Chapter 10/addition.py
372
4.1875
4
while True: try: number1 = input("Please enter a number:(enter 'q' to quit) ") if number1 == 'q': break number1 = int(number1) number2 = input("Please enter another number:(enter 'q' to quit) ") if number2 == 'q': break number2 = int(number2) except ValueError: print("You must enter a number") else: results = number1 + number2 print(results)
48f93c8bcd2d1bf68d0bca0cd00fe33311981f51
xywgo/Learn
/LearnPython/Chapter 10/cats_and_dogs.py
254
3.515625
4
def cats_dogs_names(filename): try: with open(filename) as f: pets_names = f.read() except FileNotFoundError: pass else: print(pets_names) filenames = ['cats.txt', 'pig.txt', 'dogs.txt'] for filename in filenames: cats_dogs_names(filename)
428182311850f8ba88551611162b1a1256d3669b
VojtechBrezina/RTLScript
/utils/tokens.py
1,743
3.71875
4
from typing import * from utils.tokenizing import * TT_all = [] class TokenType: """A class that defines one type of token. A token type has a name for debugging purposes, a regex to perform the check and a clean function called to e.g. remove qotes from a string literal and unwrap the escapes. """ def __init__(self, name: str, regex: str, clean_func: Callable[[str], str]) -> None: TT_all.append(self) self.name = name self.regex = regex self.next_types = [] self.clean_func = clean_func def __str__(self) -> str: return self.name class TokenInstance: """Specifies an instance of a token with the actual contents of a specific token.""" def __init__(self, token_type: TokenType, text: str): self.token_type = token_type self.raw = text self.text = token_type.clean_func(text) def __str__(self) -> str: tmp_text = self.text.replace("\n", "\\n")[::-1] tmp_tt = str(self.token_type).ljust(20) return f"TT_{tmp_tt}{tmp_text}" TT_end = TokenType( "END", r"END", lambda text: "END" ) TT_command = TokenType( "COMMAND", r"[A-Z]+", lambda text: re.sub(r"\s", "", text) ) TT_string_literal = TokenType( "STRING_LITERAL", r"\".*?(?<!\\)\"", lambda text: re.sub(r"\\\"", "\"", text[1:-1]) ) TT_number = TokenType( "NUMBER", r"-?\d+\.?\d*", lambda text: text ) TT_variable_start = TokenType( "VARIABLE_START", r"\](@*|\$)", lambda text: text ) TT_variable_end = TokenType( "VARIABLE_END", r"\[", lambda text: text ) #TT_all = [TT_end, TT_command, TT_string_literal, TT_number, TT_variable_start, TT_variable_end]
02505d17b437df33fb58ae05ae1e9f0323562b0c
learningandgrowing/Data-structures-problems
/queue_using_2_stack.py
929
3.640625
4
class queueusingstack: def __init__(self): self.__s1 = [] self.__s2 = [] self.__count = 0 def enqueue(self, data): self.__s1.append(data) self.__count += 1 def dequeue(self): if self.isEmpty(): return -1 while len(self.__s1) != 1: ele = self.__s1.pop() self.__s2.append(ele) data= self.__s1.pop() while len(self.__s2) != 0: ele = self.__s2.pop() self.__s1.append(ele) self.__count -= 1 return data def front(self): if self.isEmpty(): return -1 return self.__s1[0] def isEmpty(self): return self.getSize() == 0 def getSize(self): return self.__count s = queueusingstack() s.enqueue(12) s.enqueue(13) s.enqueue(14) s.enqueue(15) while s.isEmpty() is False: print(s.front()) s.dequeue()
7a41c18886f35fba368a9493ef5608ce3489e8d3
learningandgrowing/Data-structures-problems
/remove_duplicates.py
346
3.90625
4
def removeduplicates(string): if len(string) == 0 or len(string)==1: return string if string[0] == string[1]: smalleroutput = removeduplicates(string[1:]) return smalleroutput else: smalleroutput = removeduplicates(string[1:]) return string[0] + smalleroutput print(removeduplicates(input()))
ef3de26677f7bf4e2b7c59572c67bf0791f91f06
learningandgrowing/Data-structures-problems
/removex.py
260
3.625
4
def removeX(s, x): if len(s)==0: return s smalllist = s[1:] smalleroutput = removeX(smalllist, x) if s[0]== x: return smalleroutput else: return s[0] + smalleroutput s = "axbxcx" print(removeX(s, "x"))
94193fe4f3490f3f5176efe33e584378b771294a
learningandgrowing/Data-structures-problems
/binarysearch.py
408
3.8125
4
def search_elem(arr,ele) start = 0 end = len(arr)-1 while start <= end: mid = (start+end)//2 if arr[mid] == ele: return mid elif (arr[mid]<ele): start = mid + 1 else: end = mid - 1 return -1 n = int(input()) arr = list(int(i) for i in input().strip().split()) ele = int(input()) print(search_elem(arr,ele))
e72083a05c62e49f74812f2b02ea51399450008a
learningandgrowing/Data-structures-problems
/removeleaf.py
935
3.78125
4
class binarytree: def __init__(self, data): self.data = data self.left = None self.right = None def printdetailtree(root): if root == None: return print(root.data, end = ":") if root.left != None: print(root.left.data, end = ' ') if root.right != None: print(root.right.data) print() printdetailtree(root.left) printdetailtree(root.right) def takeinput(): rootdata = int(input()) if rootdata == -1: return None root = binarytree(rootdata) root.left = takeinput() root.right = takeinput() return root def removeleaf(root): if root == None: return None if root.left == None and root.right == None: return None root.left = removeleaf(root.left) root.right = removeleaf(root.right) return root root = takeinput() printdetailtree(root) root = removeleaf(root) printdetailtree(root)
276f3cea6ade0fbcb1d04af671e52e404714021e
learningandgrowing/Data-structures-problems
/queue_using_array.py
867
3.9375
4
class queue: def __init__(self): self.__data = [] self.__front = 0 self.__count = 0 def enqueue(self,item): self.__data.append(item) self.__count += 1 def dequeue(self): if self.isEmpty(): return ele = self.__data[self.__front] self.__front += 1 self.__count -= 1 return ele def front(self): if self.isEmpty(): return self.__data return self.__data[self.__front] def isEmpty(self): return self.size() == 0 def size(self): return self.__count s = queue() s.enqueue(12) s.enqueue(22) s.enqueue(32) s.enqueue(42) while s.isEmpty() is False: print(s.front()) s.dequeue()
66f132dc87a31899eb6714325049137dd7394f2c
Govindabhakta/tugas-besar-pengkom
/routeFind.py
4,734
3.515625
4
''' DIRECTORY IMPORTS | math 21 DATA | loc 24 | pos 34 | street 49 FUNCTIONS | dist() 61 | Location() 65 | SetMacet() 68 | Jarak() 88 | connectedNodes() 122 | connectedStreets() 135 | connectedCount() 147 | updateDist() 159 | pickNextNode() 175 ''' import math ###DAFTAR NAMA DAN INDEKS TEMPAT loc = [ "Crisbar", "Salman", "Upnormal", "Tubis", "GKUB", "Boromeus" ] ###DAFTAR KOORDINAT LOKASI pos = [ [5, 8], [4, 1], [7, 5], [11, 8], [1, 5], [11, 1] ] ###DAFTAR JALAN ''' street[x][0] = titik awal jalan(indeks loc) street[x][1] = titik akhir jalan(indeks loc) street[x][2] = panjang jalan ''' street = [ [0, 3, 6], [2, 3, 5], [3, 5, 7], [0, 4, 5], [1, 2, 5], [1, 5, 7], [1, 4, 5] ] numOfStreets = 7 def dist(asal, destinasi): dist = math.sqrt((pos[asal][0]-pos[destinasi][0])*(pos[asal][0]-pos[destinasi][0]) + (pos[asal][1]-pos[destinasi][1])*(pos[asal][1]-pos[destinasi][1])) return dist def Location(): return loc def setMacet(timeOfDay): if timeOfDay == "Morning" or "1": street[2][2] *= 2.00 street[0][2] *= 1.25 street[1][2] *= 1.25 elif timeOfDay == "Afternoon" or "2": street[1][2] *= 1.50 street[4][2] *= 2.00 street[2][2] *= 2.00 street[1][2] *= 1.50 street[4][2] *= 2.00 street[2][2] *= 1.25 street[1][2] *= 2.00 elif timeOfDay == "Evening" or "3": street[5][2] *= 0.80 street[0][2] *= 1.50 street[1][2] *= 1.25 def Jarak(asal, destinasi): ''' nodes relisted nodes[x][0] = heuretic distance nodes[x][1] = real distance nodes[x][2] = combined distance ''' nodes = [ [dist(0, destinasi), 0, 9999, 0], [dist(1, destinasi), 0, 9999, 0], [dist(2, destinasi), 0, 9999, 0], [dist(3, destinasi), 0, 9999, 0], [dist(4, destinasi), 0, 9999, 0], [dist(5, destinasi), 0, 9999, 0], ] currentNode = asal while currentNode != destinasi: count = connectedCount(currentNode) connectedNode = connectedNodes(currentNode) connectedStreet = connectedStreets(currentNode) for i in range(count): nodes = updateDist(nodes, int(connectedNode[i]), currentNode, int(connectedStreet[i])) nodes[int(connectedNode[i])][2] = nodes[int(connectedNode[i])][0] + nodes[int(connectedNode[i])][1] nodes[currentNode][3] = 1 currentNode = pickNextNode(nodes, currentNode) distance = nodes[currentNode][1] return distance def connectedNodes(currentNode): nodes = "" for i in range(7): #Mencari jalan yang terhubung dengan A #Menambahkan indeksnya ke routes, dan menambahkan indeks jalan akhirnya ke routesEnd if street[i][0] == currentNode: nodes = nodes + str(street[i][1]) elif street[i][1] == currentNode: nodes = nodes + str(street[i][0]) return nodes def connectedStreets(currentNode): streets = "" for i in range(numOfStreets): #Mencari jalan yang terhubung dengan A #Menambahkan indeksnya ke routes, dan menambahkan indeks jalan akhirnya ke routesEnd if street[i][0] == currentNode: streets = streets + str(i) elif street[i][1] == currentNode: streets = streets + str(i) return streets def connectedCount(currentNode): count = 0 for i in range(7): #Mencari jalan yang terhubung dengan A #Menambahkan indeksnya ke routes, dan menambahkan indeks jalan akhirnya ke routesEnd if street[i][0] == currentNode: count += 1 elif street[i][1] == currentNode: count += 1 return count def updateDist(nodes, nextNode, originNode, path): currentDist = nodes[nextNode][1] newDist = nodes[originNode][1] + street[path][2] newnodes = nodes if currentDist == 0: newnodes[nextNode][1] = newDist else: if currentDist < newDist: newnodes[nextNode][1] = currentDist else: newnodes[nextNode][1] = newDist return newnodes def pickNextNode(nodes, currentNode): if currentNode != 5: iminim = currentNode+1 else: iminim = 4 for i in range(6): if nodes[i][2] <= nodes[iminim][2] and nodes[i][3] == 0 and nodes[iminim][3] == 0: iminim = i return iminim # a = int(input("Origin?")) # b = int(input("Destination?")) # print(Jarak(a, b)) ###COOL COOL COOL COOL COOL COOL COOL COOL COOL
b5152c32e5f3bd47e23d6200db7e57bed3627919
shell909090/utils
/srt.py
714
3.5
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- ''' @date: 2020-12-31 @author: Shell.Xu @copyright: 2020, Shell.Xu <shell909090@gmail.com> @license: BSD-3-clause @comment: translate srt to txt file 将srt文件转换为txt文件,容易阅读。 python3 srt.py [srt file] ''' import sys def read_multi_line(fi): line = fi.readline().strip() while line: yield line line = fi.readline().strip() def main(): with open(sys.argv[1], 'r') as fi: for line in fi: if '-->' not in line: continue ti = line.strip().split('-->')[0].split(',')[0] s = ' '.join(read_multi_line(fi)) print(f'{ti} {s}') if __name__ == '__main__': main()
e15db91dc7f97615e0a6b924a2c50cd8a1b7285c
A-R-M-S-M/dstg
/www/dijkstra.py
4,267
3.65625
4
import sys import cPickle import urllib, json import pprint import time def shortestpath(graph,start,end,visited=[],distances={},predecessors={}): """Find the shortest path between start and end nodes in a graph""" # we've found our end node, now find the path to it, and return if start==end: path=[] while end != None: path.append(end) end=predecessors.get(end,None) return distances[start], path[::-1] # detect if it's the first time through, set current distance to zero if not visited: distances[start]=0 # process neighbors as per algorithm, keep track of predecessors for neighbor in graph[start]: if neighbor not in visited: neighbordist = distances.get(neighbor,sys.maxint) tentativedist = distances[start] + graph[start][neighbor] if tentativedist < neighbordist: distances[neighbor] = tentativedist predecessors[neighbor]=start # neighbors processed, now mark the current node as visited visited.append(start) # finds the closest unvisited node to the start unvisiteds = dict((k, distances.get(k,sys.maxint)) for k in graph if k not in visited) closestnode = min(unvisiteds, key=unvisiteds.get) # now we can take the closest node and recurse, making it current return shortestpath(graph,closestnode,end,visited,distances,predecessors) #main coords = cPickle.load(open('coords.p', 'rb')) adjmat = cPickle.load(open('adjmat.p', 'rb')) distance = cPickle.load(open('distance.p', 'rb')) names = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','R','S','T','U','V','Z','X','Y','W','Q','AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AR','AS','AT','AU','AV','AZ','AX','AY','AW','AQ'] lat = float(sys.argv[1]) lng = float(sys.argv[2]) latLngNum = len(coords) izvan_dosega = 1 coords.append([lat,lng]) dis_temp = [] adj_temp = [] for red in distance: red.append(['a','b']); for red in adjmat: red.append(0); for b in coords: adj_temp.append(0); dis_temp.append(['a','b']); distance.append(dis_temp); adjmat.append(adj_temp); for b in range(0,len(coords)): a = latLngNum error = 0 while error>=0: if(error>0): time.sleep(1.0) if(a==b): distance[a][b] = 0 if(a>b): URL2 = "http://maps.googleapis.com/maps/api/directions/json?origin="+str(coords[a][0])+","+str(coords[a][1])+"&destination="+str(coords[b][0])+","+str(coords[b][1])+"&mode=walking&sensor=false" googleResponse = urllib.urlopen(URL2) jsonResponse = json.loads(googleResponse.read()) try: ij_distance = jsonResponse['routes'][0]['legs'][0]['distance']['value'] except IndexError: ij_distance = '' if(ij_distance!=''): distance[a][b] = ij_distance distance[b][a] = ij_distance error = -1 if( len(jsonResponse['routes'][0]['legs'][0]['steps'])==1 ): adjmat[a][b] = 1 adjmat[b][a] = 1 izvan_dosega = 0 else: error = error + 1 else: error = -1 G = {} for x in range(0,len(coords)): temp = {} for y in range(0,len(coords)): if( int(distance[x][y])==0 or int(adjmat[x][y])!=1): continue temp[names[y]] = int(distance[x][y]) G[names[x]] = temp #print G fullCordsPath = "" if izvan_dosega==1: fullCordsPath = fullCordsPath + str(coords[0][0])+","+str(coords[0][1])+";"+ str(lat)+","+str(lng) else: for index, nood in enumerate(shortestpath(G,"A",names[latLngNum])[1]): poz = 0 for i in range(0,len(names)): if(str(nood)==names[i]): poz = i break if i == 0: fullCordsPath = fullCordsPath + str(coords[poz][0])+","+str(coords[poz][1]) else: fullCordsPath = fullCordsPath+ ";" + str(coords[poz][0])+","+str(coords[poz][1]) print fullCordsPath
bfbd5698c938d0bc546998cc17e50b752983aa40
JazNH/PythonProjects
/RandomNumber.py
212
3.796875
4
# randomly choose a number from 1 to 100 import random def random_number(): num1 = random.randint(1, 100) return(int(num1)) #can change return to print to show the number being returned random_number()
1216c77ab930e34bbcce0df0cfc1ae70f5ce8d36
JazNH/PythonProjects
/PlayingWithList.py
166
4.09375
4
list = [1, 2, 3, 4, 5 ] #list[0] selects first of a list #list[-1] selects last of a list print(list[0], list[-1]) #prints every other of a list print(list[::2])
ca10344f76fddb06f4512038d79e7b0e89fb018b
JazNH/PythonProjects
/RockPaperScissors.py
1,120
4.09375
4
# Rock, Paper, Scissors game import random options = ["rock", "paper", "scissors"] computersChoice = random.choice(options) print("Welcome to Rock, Paper, Scissors") print("What do you choose?") print(" ") print("-----------------------------------") playAgain = input("Ready to play? yes or no?") while playAgain == "yes": myChoice = input("What did you pick? ") if(myChoice == computersChoice): print("Its a tie!") elif(myChoice == "rock" and computersChoice == "scissors"): print("You Won!") elif(myChoice == "paper" and computersChoice == "rock"): print("You Won!") elif (myChoice == "scissors" and computersChoice == "pyaper"): print("You Won!") elif(myChoice == "paper" and computersChoice == "scissors"): print("You Lost") elif(myChoice == "scissors" and computersChoice == "rock"): print("You Lost") elif(myChoice == "rock" and computersChoice == "paper"): print("You Lost") else: print("no one won") print(" ") playAgain = input("Ready to play? yes or no?") if playAgain == "no": break
e37a4a9deede420540b2d8126d1d8902e408c544
davidadamojr/diary_of_programming_puzzles
/arrays_and_strings/knuth_morris_pratt.py
2,579
3.890625
4
""" An implementation of the Knuth-Morris-Pratt (KMP) string matching algorithm The KMP algorithm spends a little time precomputing a table (on the order of the size of W[], O(n)) and then uses the table to do an efficient search of the string in O(k). KMP makes use of previous match information. """ # @param pattern string the pattern to be searched for def build_table(pattern): prefix_table = [0 for character in pattern] current_position = 2 # current position of table we are computing substring_position = 0 # zero-based index in pattern of the next character of the candidate substring prefix_table[0] = -1 prefix_table[1] = 0 while current_position < len(pattern): # first case: next character and previous character of the substring are the same if pattern[current_position - 1] == pattern[substring_position]: substring_position = substring_position + 1 prefix_table[current_position] = substring_position current_position = current_position + 1 # second case: substring does not continue elif substring_position > 0: substring_position = prefix_table[substring_position] # third case: no more candidate substrings else: prefix_table[current_position] = 0 substring_position = substring_position + 1 return prefix_table # @param pattern string the string pattern to be searched for # @param text string the string to be searched def kmp_search(pattern, text): current_match_index = 0 # the beginning of the current match in text current_char_index = 0 # the position of the current character in pattern prefix_table = build_table(pattern) while current_match_index + current_char_index < len(text): if pattern[current_char_index] == text[current_match_index + current_char_index]: if current_char_index == len(pattern) - 1: return current_match_index current_char_index = current_char_index + 1 else: # current character in pattern failed to match corresponding character in text if prefix_table[current_char_index] > -1: current_match_index = current_match_index + current_char_index - prefix_table[current_char_index] current_char_index = prefix_table[current_char_index] else: current_char_index = 0 current_match_index = current_match_index + 1 if __name__ == '__main__': print(kmp_search("aab", "aaaaaaaaaaaaaaaaaaaab"))
d025ef9b5f54fb004dc8ed67b652469566c92754
davidadamojr/diary_of_programming_puzzles
/arrays_and_strings/has_zero_triplets.py
1,089
4.1875
4
""" Given an array of integers that do not contain duplicate values, determine if there exists any triplets that sum up to zero. For example, L = [-3, 2, -5, 8, -9, -2, 0, 1] e = {-3, 2, 1} return true since e exists This solution uses a hash table to cut the time complexity down by n. Time complexity: O(n^2) Space complexity: O(n) Hint: a+b+c = 0 => c = -(a+b) Once we know the first two elements of the triplet, we can compute the third and check its existence in a hash table. """ # @param arr the list of integers to be checked for zero triples # @return true if three elements exist that sum up to zero def has_zero_triplet(arr): if not arr: return False numbers = set([]) for number in arr: numbers.add(number) for i in range(0, len(arr) - 1): for j in range(i, len(arr)): first = arr[i] second = arr[j] third = -first - second if third in numbers: return True return False if __name__ == '__main__': print(has_zero_triplet([-3, 2, -5, 8, -9, -2, 0, 1]))
31966a029427f2de3759a8af889481c05e30339a
davidadamojr/diary_of_programming_puzzles
/arrays_and_strings/three_sum_closest.py
1,284
4.34375
4
""" Given an array "nums" of n integers and an integer "target", find three integers in nums such that the sum is closest to "target". Return the sum of the three integers. You may assume that each input would have exactly one solution. Example: Given array nums = [-1, 2, 1, -4], and target = 1. The sum that is closest to the target is 2. (-1 + 2 + 1 = 2) """ def three_sum_closest(nums, target): if not nums: return 0 nums.sort() difference = float('inf') target_sum = 0 for i in range(0, len(nums)-2): j = i + 1 k = len(nums) - 1 while j < k: first_num = nums[i] second_num = nums[j] third_num = nums[k] element_sum = first_num + second_num + third_num if element_sum < target: j += 1 elif element_sum > target: k -= 1 else: return element_sum current_difference = abs(element_sum - target) if current_difference < difference: difference = current_difference target_sum = element_sum return target_sum assert three_sum_closest([-1, 2, 1, -4], 1) == 2 assert three_sum_closest([], 1) == 0 print("All tests passed successfully.")
a7ad18871194654ee4d1cf04e1264b670df3d204
davidadamojr/diary_of_programming_puzzles
/arrays_and_strings/toeplitz_matrix.py
1,212
4.46875
4
""" A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same element. Now given an MxN matrix, return True if and only if the matrix is Toeplitz. Example 1: Input: matrix = [[1, 2, 3, 4], [5, 1, 2, 3], [9, 5, 1, 2]] Output: True Explanation: 1234 5123 9512 In the above grid, the diagonals are "[9]", "[5, 5]', "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]" Note: 1. matrix will be a 2D array of integers 2. matrix will have a number of rows and columns in range [1, 20] 3. matrix[i][j] will be integers in range [0, 99] https://leetcode.com/problems/toeplitz-matrix/description/ """ def is_toeplitz_matrix(matrix): for row_idx, row in enumerate(matrix): for col_idx, value in enumerate(row): if col_idx == 0 or row_idx == 0: continue if value != matrix[row_idx - 1][col_idx - 1]: return False return True assert is_toeplitz_matrix([[1, 2, 3, 4], [5, 1, 2, 3], [9, 5, 1, 2]]) is True assert is_toeplitz_matrix([[1, 2, 3, 4], [5, 5, 5, 5], [9, 9, 9, 9]]) is False print("All tests passed successfully.")
895e80acf9eed3e1b580a9ac4dec51eb295e7319
davidadamojr/diary_of_programming_puzzles
/sorting_and_searching/find_in_rotated_array.py
1,653
4.21875
4
""" Given a sorted array of n integers that has been rotated an unknown number of times, write code to find an element in the array. You may assume that the array was originally sorted in increasing order. """ def find_in_rotated(key, rotated_lst, start, end): """ fundamentally binary search... Either the left or right half must be normally ordered. Find out which side is normally ordered, and then use the normally ordered half to figure out which side to search to find x. """ if not rotated_lst: return None if end < start: return None middle_idx = (start + end) / 2 middle_elem = rotated_lst[middle_idx] leftmost_elem = rotated_lst[start] rightmost_elem = rotated_lst[end] if middle_elem == key: return middle_idx if leftmost_elem < middle_elem: if leftmost_elem <= key < middle_elem: return find_in_rotated(key, rotated_lst, start, middle_idx - 1) else: return find_in_rotated(key, rotated_lst, middle_idx + 1, end) else: if middle_elem < key <= rightmost_elem: return find_in_rotated(key, rotated_lst, middle_idx + 1, end) else: return find_in_rotated(key, rotated_lst, start, middle_idx - 1) if __name__ == '__main__': assert find_in_rotated(1, [4, 5, 6, 1, 2, 3], 0, 5) == 3 assert find_in_rotated(5, [1, 2, 3, 4, 5, 6], 0, 5) == 4 assert find_in_rotated(5, [6, 6, 6, 6, 6, 6], 0, 5) == None assert find_in_rotated(7, [6, 6, 6, 7, 7, 7, 7], 0, 6) == 3 assert find_in_rotated(6, [6, 6, 6, 6, 6, 6], 0, 5) == 2 print("All test cases passed.")
46a081380aa96ceaf062d72e0101881f8d57a08c
davidadamojr/diary_of_programming_puzzles
/bit_manipulation/hamming_distance.py
1,025
4.3125
4
""" The Hamming distance between two integers is the number of positions at which the corresponding bits are different. Given two integers num1 and num2, calculate the Hamming distance. https://leetcode.com/problems/hamming-distance/ """ # @param num1 integer # @param num2 integer def hamming_distance(num1, num2): distance = 0 while num1 > 0 and num2 > 0: xor = num1 ^ num2 if xor % 2 == 1: distance = distance + 1 num1 = num1 >> 1 num2 = num2 >> 1 while num1 > 0: xor = num1 ^ 0 if xor % 2 == 1: distance = distance + 1 num1 = num1 >> 1 while num2 > 0: xor = num2 ^ 0 if xor % 2 == 1: distance = distance + 1 num2 = num2 >> 1 return distance if __name__ == '__main__': assert hamming_distance(1, 4) == 2 assert hamming_distance(0, 0) == 0 assert hamming_distance(8, 4) == 2 assert hamming_distance(4, 8) == 2 print("All test cases passed successfully.")
1ebdbdafcc3dadabe48676ca0dbda76cdb3181d8
davidadamojr/diary_of_programming_puzzles
/misc/convert_to_hexadecimal.py
1,658
4.75
5
""" Given an integer, write an algorithm to convert it to hexadecimal. For negative integers, two's complement method is used. Note: 1. All letters in hexadecimal (a-f) must be in lowercase. 2. The hexadecimal string must not contain extra leading 0s. If the number is zero, it is represented by a single zero character '0'; otherwise, the first character in the hexadecimal string will not be zero character. 3. The given number is guaranteed to fit within the range of a 32-bit signed integer. 4. You must not use any method provided by the library which converts/formats the number to hex directly. Example 1: Input: 26 Output: "1a" Example 2: Input: -1 Output: "ffffffff" """ # @param num the number to convert to hexadecimal # @return the hexadecimal representation of the number def to_hex(num): if num == 0: return "0" hex_digits = { 10: "a", 11: "b", 12: "c", 13: "d", 14: "e", 15: "f" } hex_num = "" is_negative = False if num < 0: magnitude = abs(num) mask = ((1 << 32) - 1) + (1 << 32) inverted = magnitude ^ mask num = inverted + 1 is_negative = True while num != 0: remainder = num % 16 num = num / 16 if remainder in hex_digits: hex_num = hex_digits[remainder] + hex_num else: hex_num = str(remainder) + hex_num if is_negative: return hex_num[1:] return hex_num if __name__ == '__main__': assert to_hex(0) == "0" assert to_hex(-1) == "ffffffff" assert to_hex(26) == "1a" print("All test cases passed successfully.")
a6673418628269bdac32de4aaa469fc9ea6b8239
davidadamojr/diary_of_programming_puzzles
/arrays_and_strings/integer_to_string.py
952
4.6875
5
""" Write a routine to convert a signed integer into a string. """ def integer_to_string(integer): """ Writes the string backward and reverses it """ if integer < 0: is_negative = True integer = -integer # for negative integers, make them positive else: is_negative = False integer_string = "" while integer != 0: new_digit = integer % 10 # "ord" returns the character code of its argument ascii_code = ord('0') + new_digit # "chr" returns the string representation of its argument integer_string = integer_string + chr(ascii_code) integer = integer / 10 # in python, the easiest way to reverse a string is "string[::-1]"\ integer_string = '-' + integer_string[::-1] if is_negative else integer_string[::-1] return integer_string if __name__ == "__main__": print(integer_to_string(-1234)) print(integer_to_string(54321))