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
f377a1f4fcfd4935fde1612668bf91f07987c9e6
katesorotos/module2
/ch11_while_loops/ch11_katesorotos.py
3,691
3.765625
4
# -*- coding: utf-8 -*- """ Created on Tue Dec 18 09:11:36 2018 @author: Kate Sorotos """ """while loops""" ############################################################################################## ### Task 1 - repeated division x = 33 while x >= 1: print(x, ':', end='') #end'' is a parameter that prints a space rather than a new line x = x/2 print(x)#exit the while loop (conditon no longer true) ############################################################################################## ### Task 2 - triangular numbers def triangularNumber(n): number = 0 while n > 0: number = number + n n = n - 1 print(number) return number triangularNumber(3) ############################################################################################## ### Task 2 - factorial numbers def factorialNumber(): n = int(input("Please enter a number: ")) factorial = 1 while n > 0: factorial = factorial * n n = n - 1 print(factorial) return factorial factorialNumber() ############################################################################################## ### Task 3 - studnet's marks def gradingStudentMarks(): mark = 1 while mark > 0: mark = int(input("Please enter your mark: ")) #user input must be inside while loop otherwise condition is forever true if mark >= 70: print("Congratualtions! You got a first class mark.") elif mark >= 40: print("Well done! You passed.") else: print("Fail.") gradingStudentMarks() ############################################################################################## ### Task 3 - student's marks didYouPass = 'yes' while didYouPass == 'yes': mark = int(input("Please enter your mark: ")) if mark >= 90: print("Congratualtions! You got an A*.") elif mark >= 70: print("Well done! You got a A.") elif mark >= 60: print("You got a B.") elif mark >= 50: print("You got a C.") elif mark >= 40: print("You got a D.") else: print("I'm afraid you did not pass.") didYouPass = input("Did you pass? ") ############################################################################################## ###Task 4 - using break in while loops to exit i = 55 while i > 10: print(i) i = i * 0.8 if i == 35.2: break #ends the normal flow of the loop while True: askName = input("Please enter your name: ") if askName == 'done': break print("Hi, " + askName.title()) ############################################################################################### ### Task 5 & 6 - designing a guessing number game program from random import randint def guess(attempts, range): attempt = 0 max_attempts = 3 player_guess = 1 number = randint(1, range) print() print('Welcome to the guessing game! \nYou have ' + str(attempts) + ' attempts to guess a number between 1 and ' + str(range)) print("Can you guess my secret number? ") while attempt < max_attempts: attempt += 1 player_guess = int(input("Make a guess: ")) print("Attempts made: " + str(attempt)) print() print("Result: ") if player_guess < number: print("No - Too low!") elif player_guess > number: print("No - Too high!") else: print("well done! You guessed it!") break guess(3, 10)
c5749efaac303d2f5d56dfdcaeadbb52869208c1
katesorotos/module2
/coding_bat/parrot_trouble.py
419
4.03125
4
# -*- coding: utf-8 -*- """ Created on Thu Dec 13 12:27:13 2018 @author: Kate Sorotos """ We have a loud talking parrot. The "hour" parameter is the current hour time in the range 0..23. We are in trouble if the parrot is talking and the hour is before 7 or after 20. Return True if we are in trouble. def parrot_trouble(talking, hour): if (talking and (hour < 7 or hour > 20)): return True else: return False
8a5e362bb9373ae525010647cad68256dd5b5fa6
katesorotos/module2
/ch13_oop_project/MovingShapes.py
2,681
3.5625
4
# -*- coding: utf-8 -*- """ Created on Mon Dec 17 16:31:34 2018 @author: Kate Sorotos """ from shape import * from pylab import random as r class MovingShape: def __init__(self, frame, shape, diameter): self.shape = shape self.diameter = diameter self.figure = Shape(shape, diameter) self.frame = frame # self.x = 0 # self.y = 0 ### creating random movement in x self.dx = 5 + 10 * r() ### move in positive and negative directions if r() < 0.5: self.dx = 5 + 10 * r() else: self.dx = -5 + -10 * r() ### creating random movement in y self.dy = 5 + 10 * r() ### move in positive and negative directions if r() < 0.5: self.dy = 5 + 10 * r() else: self.dy = -5 + -10 * r() # self.goto(self.x, self.y) ### adding random variation for the start positions self.min_max_start(diameter) ### minimum and maximum start position of x and y def min_max_start(self, diameter): diameter_2 = diameter / 2 self.minx = diameter / 2 self.maxx = self.frame.width - (diameter_2) self.miny = diameter / 2 self.maxy = self.frame.height - (diameter_2) self.x = self.minx + r () * (self.maxx - self.minx) self.y = self.miny + r () * (self.maxy - self.miny) def goto(self, x, y): self.figure.goto(x, y) def moveTick(self): ### hitting the wall if self.x <= self.minx or self.x >= self.maxx: self.dx = (self.dx) * -1 if self.y <= self.miny or self.y >= self.maxy: self.dy =- self.dy self.x += self.dx self.y += self.dy self.figure.goto(self.x, self.y) ### squares vs diamonds vs circles class Square(MovingShape): def __init__(self, frame, diameter): MovingShape.__init__(self, frame, 'square', diameter) class Diamond(MovingShape): def __init__(self, frame, diameter): MovingShape.__init__(self, frame, 'diamond', diameter) def min_max_start(self, diameter): diameter_2 = diameter * 2 self.minx = diameter / 2 self.maxx = frame.width - (diameter_2) self.miny = diameter / 2 self.maxy = frame.height - (diameter_2) min_max_start(self, diameter) class Circle(MovingShape): def __init__(self, frame, diameter): MovingShape.__init__(self, frame, 'circle', diameter)
414745764aaa0191a4fbc6d86171e3ec14660124
simonhej1/So4
/Integral.py
1,694
3.65625
4
import matplotlib.pyplot as plt import numpy as np import sympy as sy import tkinter as tk from tkinter import ttk #a = float(input("hvad er a?:")) #b = float(input("hvad er b?:")) #c = float(input("hvad er c?:")) #x = np.linspace(a, b, 100) #y = np.sin(x) #plt.figure() #plt.plot(x, y) #plt.show() class Application(tk.Frame): def __init__(self, master=None): super().__init__(master) self.pack() self.create_widgets() def create_widgets(self): # create widgets self.Inteknap = tk.Button(text = "Integralregning", command =self.calcInt) self.Difknap = tk.Button(text = "Differentialregning", command =self.calcDif) # place widgets self.Inteknap.pack(side="right") self.Difknap.pack(side="left") def calcDif(self): polynomial = input("To what degree?\n> ") polynomial = int(polynomial) if polynomial == 2: xPower = polynomial xPowerCoefficient = int(input("What is the coefficient of x^n?")) xCoefficient = int(input("What is the coefficient of x?")) newXPower = xPower - 1 newXCoefficient = xCoefficient * xPower newXPower = str(newXPower) newXCoefficient = str(newXCoefficient) equation = newXCoefficient + "x" + newXPower + "+" elif polynomial == 3: pass elif polynomial == 4: pass def calcInt(self): pass #create app root = tk.Tk() root.geometry("225x240") app = Application(master=root) app.master.frame() app.master.title("Dif+Int Regning") #start app app.mainloop()
130f6fcd0668496d386c59b445165adf369c44c0
fsc2016/LeetCode
/code/36_二叉树最小深度.py
2,126
3.671875
4
''' 给定一个二叉树,找出其最小深度。 最小深度是从根节点到最近叶子节点的最短路径上的节点数量。 说明:叶子节点是指没有子节点的节点。 111. 二叉树的最小深度 ''' from collections import deque class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def minDepth(self,root: TreeNode) -> int: ''' dfs :return: ''' def recu(root): if not root: return 0 if not root.left and not root.right: return 1 mindepth=float('inf') if root.left: mindepth = min(mindepth,self.minDepth(root.left)) if root.right: mindepth = min(mindepth, self.minDepth(root.right)) return mindepth+1 return recu(root) def minDepth2(self, root: TreeNode) -> int: ''' bfs ''' if not root: return 0 dq = deque() dq.append([root, 1]) while dq: tmp, depth = dq.popleft() if not tmp.left and not tmp.right: return depth if tmp.left: dq.append([tmp.left, depth + 1]) if tmp.right: dq.append([tmp.right, depth + 1]) return 0 ''' 输入一棵二叉树的根节点,求该树的深度。从根节点到叶节点依次经过的节点(含根、叶节点)形成树的一条路径,最长路径的长度为树的深度。 剑指 Offer 55 - I. 二叉树的深度 ''' def maxDepth2(self, root: TreeNode) -> int: if not root: return 0 dq = deque() dq.append([root,1]) maxdepth = float('-inf') while dq: node,depth =dq.popleft() maxdepth = max(maxdepth,depth) if node.left: dq.append([node.left,depth+1]) if node.right: dq.append([node.right, depth + 1]) return maxdepth
316fbc12929968851b0b6e4f8054e0c0ef182428
fsc2016/LeetCode
/code/3_三数之和.py
1,340
3.59375
4
''' 给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有满足条件且不重复的三元组。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/3sum ''' from typing import * def threeSum(nums: List[int]) -> List[List[int]]: n = len(nums) res = [] if not nums or n<3: return [] # 进行排序 nums.sort() for i in range(n): if nums[i] > 0: return res # 过滤重复元素 # if i > 0 and nums[i] == nums[i-1]: # continue left = i+1 right = n-1 while left < right: if (nums[i] + nums[left] + nums[right]) == 0: res.append((nums[i],nums[left],nums[right])) # 过滤重复元素 # while left < right and nums[left] == nums[left+1]: # left +=1 # while left < right and nums[right] == nums[right-1]: # right-=1 left +=1 right -=1 elif (nums[i] + nums[left] + nums[right])>0: right -=1 else: left+=1 return res if __name__ == '__main__': print(set(threeSum([-1,0,1,2,-1,-4]))) print(threeSum([0,0,0]))
1d8035d57a12007ed578bd052f8b140e1db527c3
fsc2016/LeetCode
/11_bfs_dfs.py
3,087
3.625
4
from collections import deque class Graph: def __init__(self,v): # 图的顶点数 self.num_v = v # 使用邻接表来存储图 self.adj = [[] for _ in range(v)] def add_edge(self,s,t): self.adj[s].append(t) self.adj[t].append(s) def _generate_path(self, s, t, prev): ''' 打印路径 :param s: :param t: :param prev: :return: ''' if prev[t] or s != t: yield from self._generate_path(s, prev[t], prev) yield str(t) def bfs(self,s,t): ''' 广度优先 :param s: 起始节点 :param t: 终止节点 :return: visited 是用来记录已经被访问的顶点,用来避免顶点被重复访问。如果顶点 q 被访问,那相应的 visited[q]会被设置为 true。 queue 是一个队列,用来存储已经被访问、但相连的顶点还没有被访问的顶点 prev 用来记录搜索路径。当我们从顶点 s 开始,广度优先搜索到顶点 t 后,prev 数组中存储的就是搜索的路径 ''' if s == t : return visited = [False] * self.num_v visited[s] = True prev = [None] * self.num_v q = deque() q.append(s) while q : w = q.popleft() # 从邻接表中查询 for neighbour in self.adj[w]: # 没访问过就访问这个节点,并且加入路径 if not visited[neighbour]: prev[neighbour] = w if neighbour == t: print("->".join(self._generate_path(s, t, prev))) return # 当前节点不是,就把节点加入已访问节点列表 visited[neighbour] = True q.append(neighbour) def dfs(self,s,t): ''' 深度优先 采用回溯算法的思想,采用递归来实现 :param s: 起始节点 :param t: 终止节点 :return: ''' found = False visited = [False] * self.num_v prev = [None] * self.num_v def _dfs(from_vertex): nonlocal found if found :return # 当前节点不是终结点,就不停往下一层探寻 visited[from_vertex] = True if from_vertex == t: found = True return for neighbour in self.adj[from_vertex]: if not visited[neighbour]: prev[neighbour] = from_vertex _dfs(neighbour) _dfs(s) print("->".join(self._generate_path(s, t, prev))) if __name__ == "__main__": graph = Graph(8) graph.add_edge(0, 1) graph.add_edge(0, 3) graph.add_edge(1, 2) graph.add_edge(1, 4) graph.add_edge(2, 5) graph.add_edge(3, 4) graph.add_edge(4, 5) graph.add_edge(4, 6) graph.add_edge(5, 7) graph.add_edge(6, 7) graph.bfs(0, 7) graph.dfs(0, 7)
3dd1c0e006ed59e45039c4b49124ec3307aef4f8
fsc2016/LeetCode
/code/22_数据流中第K大元素.py
2,337
4.03125
4
''' 设计一个找到数据流中第K大元素的类(class)。注意是排序后的第K大元素,不是第K个不同的元素。 你的 KthLargest 类需要一个同时接收整数 k 和整数数组nums 的构造器,它包含数据流中的初始元素。每次调用 KthLargest.add,返回当前数据流中第K大的元素。 示例: int k = 3; int[] arr = [4,5,8,2]; KthLargest kthLargest = new KthLargest(3, arr); kthLargest.add(3);   // returns 4 kthLargest.add(5);   // returns 5 kthLargest.add(10);  // returns 5 kthLargest.add(9);   // returns 8 kthLargest.add(4);   // returns 8 链接:https://leetcode-cn.com/problems/kth-largest-element-in-a-stream ''' from typing import * from heapq import * import heapq class KthLargest: ''' 数组法 # ''' # def __init__(self, k: int, nums: List[int]): # self._nums = nums # self._k = k # # def add(self, val: int) -> int: # self._nums.append(val) # self._nums.sort() # return self._nums[-self._k] ''' 堆 ''' def __init__(self, k: int, nums: List[int]): self._nums = nums heapq.heapify(self._nums) self._k = k while len(self._nums) > k: heapq.heappop(self._nums) def add(self, val: int) -> int: heapq.heappush(self._nums,val) if len(self._nums) > self._k: heapq.heappop(self._nums) return self._nums[0] # def __init__(self, k, nums): # """ # :type k: int # :type nums: List[int] # """ # self.k = k # self.nums = nums # heapify(self.nums) # while len(self.nums) > self.k: # cut heap to size:k # heappop(self.nums) # # def add(self, val): # """ # :type val: int # :rtype: int # """ # if len(self.nums) < self.k: # heappush(self.nums, val) # heapify(self.nums) # cation # else: # top = float('-inf') # if len(self.nums) > 0: # top = self.nums[0] # if top < val: # heapreplace(self.nums, val) # return self.nums[0] if __name__ == '__main__': arr=[4,5,8,2] kth = KthLargest(3,arr) print(kth.add(3)) print(kth.add(5)) print(kth.add(10))
7b376a84ba18c6c6da384100816e6c205980f42d
fsc2016/LeetCode
/code/19_最大子序和.py
867
3.78125
4
''' 给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。 示例: 输入: [-2,1,-3,4,-1,2,1,-5,4] 输出: 6 解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。 ''' from typing import * def maxSubArray(nums: List[int]) -> int: ''' 动态规划 :param nums: :return: ''' # n = len(nums) # dp = [float('-inf')] * n # dp[0] = nums[0] # for i in range(1,n): # dp[i] = max(dp[i-1]+nums[i],nums[i]) # return max(dp) # 优化空间复杂度 n = len(nums) pre_num = nums[0] best_num = nums[0] for i in range(1, n): pre_num = max(pre_num + nums[i], nums[i]) best_num = max(best_num,pre_num) return best_num if __name__ == '__main__': l =[-2,1,-3,4,-1,2,1,-5,4] print(maxSubArray(l))
50df31500f9c57e0e829ea163af7987b93992705
fsc2016/LeetCode
/code/24_包含min函数的栈.py
1,935
4.09375
4
''' 定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)。 示例: MinStack minStack = new MinStack(); minStack.push(-2); minStack.push(0); minStack.push(-3); minStack.min(); --> 返回 -3. minStack.pop(); minStack.top(); --> 返回 0. minStack.min(); --> 返回 -2. 链接:https://leetcode-cn.com/problems/bao-han-minhan-shu-de-zhan-lcof ''' class MinStack: ''' 辅助栈是严格有序的 ''' def __init__(self): """ initialize your data structure here. """ self.l = [] self.deque=[] def push(self, x: int) -> None: self.l.append(x) if self.deque: for i in range(len(self.deque)): if self.deque[i] < x: self.deque.insert(i,x) return self.deque.append(x) def pop(self) -> None: popnum=self.l.pop() self.deque.remove(popnum) def top(self) -> int: return self.l[-1] def min(self) -> int: return self.deque[-1] class MinStack1: ''' 非严格有序 ''' def __init__(self): """ initialize your data structure here. """ self.l = [] self.deque=[] def push(self, x: int) -> None: self.l.append(x) if not self.deque or self.deque[-1] > x: self.deque.append(x) def pop(self) -> None: if self.l.pop() == self.deque[-1]: self.deque.pop() def top(self) -> int: return self.l[-1] def min(self) -> int: return self.deque[-1] if __name__ == '__main__': minStack = MinStack1() minStack.push(-2) minStack.push(0) minStack.push(-1) print(minStack.deque) print(minStack.min()) print(minStack.top()) minStack.pop() print(minStack.min())
13ab84b16c74da6f7f93a033dfb9b2f7c89dab6d
darshanrk18/Algorithms
/CountInversions.py
903
3.828125
4
import random def merge(A,B): (C,m,n)=([],len(A),len(B)) (i,j,c)=(0,0,0) while i+j<m+n: if i==m: C.append(B[j]) j+=1 elif j==n: C.append(A[i]) i+=1 elif A[i]<=B[j]: C.append(A[i]) i+=1 else: C.append(B[j]) j+=1 c+=len(A)-i return (C,c) def mergesort(A,left,right): if right-left<=1: return (A[left:right],0) mid=(left+right)//2 (L,ca)=mergesort(A,left,mid) (R,cb)=mergesort(A,mid,right) (res,c)=merge(L,R) c+=ca+cb return (res,c) '''print("Enter the list of elements to be sorted: ",end=' ') A=[int(x) for x in input().split()]''' A=[random.randint(1,50) for x in range(1,10)] print("List:",A) (A,c)=mergesort(A,0,len(A)) print("Sorted list:") for i in A: print(i,end=' ') print("\nNo. of inversions:",c)
d359233240850fbff418284686c8e92a27397b62
darshanrk18/Algorithms
/BucketSort.py
1,779
3.90625
4
import math import string import random DEFAULT_BUCKET_SIZE = 5 def insertionSort(arr): # Traverse through 1 to len(arr) for i in range(1, len(arr)): while i>0 and arr[i]<arr[i-1]: (arr[i-1],arr[i],i)=(arr[i],arr[i-1],i-1) def sort(array, bucketSize=DEFAULT_BUCKET_SIZE): f=0 if type(array)==str: f=1 array=[ord(x) for x in array] if len(array) == 0: return array # Determine minimum and maximum values minValue = array[0] maxValue = array[0] for i in range(1, len(array)): if array[i] < minValue: minValue = array[i] elif array[i] > maxValue: maxValue = array[i] # Initialize buckets bucketCount = math.floor((maxValue - minValue) / bucketSize) + 1 buckets = [] for i in range(0, bucketCount): buckets.append([]) #Distribute input array values into buckets for i in range(0, len(array)): buckets[math.floor((array[i] - minValue) / bucketSize)].append(array[i]) #Sort buckets and place back into input array array = [] for i in range(0, len(buckets)): insertionSort(buckets[i]) for j in range(0, len(buckets[i])): array.append(buckets[i][j]) if f: for i in range(len(array)): print(chr(array[i]),end=' ') else: for i in range(0, len(array)): print(array[i],end=' ') c=int(input("1.Str input\n2.Int input\n3.Float input\nEnter your choice: ")) if c==1: l=[random.choice(string.ascii_uppercase) for x in range(10)] elif c==2: l=[random.randint(1,100) for x in range(10)] else: l=[float('%.2f'%random.uniform(1,3)) for x in range(10)] print("Initial list:",l) print("SORTED LIST".center(51,'*')) sort(l) print()
e8da0a9a73fd0c0e29eb137c4c842bd002068081
techphenom/casino-games
/blackjackTable.py
4,706
3.75
4
from random import shuffle class Card(object): def __init__(self, rank, suit, value, sort): self.rank = rank self.suit = suit self.value = value self.sort = sort def __str__(self): return '{} of {}'.format(self.rank, self.suit) class Deck(object): #A deck made of 52 cards. suits = 'spades diamonds clubs hearts'.split() ranks = [str(num) for num in range(2,11)] + list('JQKA') values = dict(zip(ranks, [x for x in range(2,11)] + [10,10,10,11])) def __init__(self): self.cards = [Card(rank, suit, self.values[rank], self.values[rank]) for rank in self.ranks for suit in self.suits] def __getitem__(self, index): return self.cards[index] def __len__(self): return len(self.cards) def shuffle(self): #Pick up (reset) the cards and reshuffle. self.cards = [Card(rank, suit, self.values[rank], self.values[rank]) for rank in self.ranks for suit in self.suits] shuffle(self.cards) def dealCard(self): return self.cards.pop(0) class Hand(object): def __init__(self): self.contents = [] def __len__(self): return len(self.contents) def __str__(self): return ', '.join([str(x) for x in self.contents]) def hit(self, card): self.contents.append(card) def getHandValue(self): ''' Sums the values of the cards in the hand. Does a check to assign either 11 or 1 to Ace. ''' count = 0 for card in sorted(self.contents, key=lambda card: card.sort): if card.rank == 'A': if count <= 10: card.value = 11 else: card.value = 1 count += card.value return count def checkIfOver(handTotal): return handTotal > 21 def checkIfBlackjack(handTotal): return handTotal == 21 def checkWhoWon(dealer, player): if dealer.getHandValue() > player.getHandValue(): return dealer if dealer.getHandValue() == player.getHandValue(): return None else: return player def main(player): print("\nWelcome to the Blackjack Table, {}.".format(player.getName())) while True: loser = False print("Your bankroll = ${}".format(player.getBankroll())) bet = int(input("Please place a bet: ")) if bet > player.getBankroll(): print("Current bankroll = {}. You don't have enough to cover that bet.".format(player.getBankroll())) continue player.decreaseBankroll(bet) deck = Deck() deck.shuffle() playerHand = Hand() playerHand.hit(deck.dealCard()) playerHand.hit(deck.dealCard()) dealerHand = Hand() dealerHand.hit(deck.dealCard()) print("Dealer's up card - {}".format(dealerHand)) dealerHand.hit(deck.dealCard()) #Check if either Player or Dealer has a Blackjack if checkIfBlackjack(playerHand.getHandValue()) and checkIfBlackjack(dealerHand.getHandValue()): print("Both player and dealer have Blackjack! Tie") continue elif checkIfBlackjack(playerHand.getHandValue()): print("Player has Blackjack! Player wins 3 to 2") player.increaseBankroll(bet*1.5) elif checkIfBlackjack(dealerHand.getHandValue()): print("I'm sorry Dealer has Blackjack. You lose.") continue #Player's turn while True: print("Your cards- {}".format(playerHand)) print("You have {}".format(playerHand.getHandValue())) playOrStay = input("Would you like to hit(h) or stay(s)? ") if playOrStay == 'h': playerHand.hit(deck.dealCard()) if checkIfOver(playerHand.getHandValue()): loser = True break elif playOrStay == 's': break else: print("Not valid input. Type 'h' to hit or 's' to stay.") while dealerHand.getHandValue() < 17: dealerHand.hit(deck.dealCard()) #Determine the winner if loser: print("I'm sorry, you went over.") else: if checkIfOver(dealerHand.getHandValue()): print("Dealer broke. You win") player.increaseBankroll(bet*2) else: winner = checkWhoWon(dealerHand, playerHand) if winner == playerHand: print("Dealer's cards: {}".format(dealerHand)) print("Your total = {}, dealer's total = {}. You win!".format(playerHand.getHandValue(),dealerHand.getHandValue())) player.increaseBankroll(bet*2) elif winner == None: print("Dealer's cards: {}".format(dealerHand)) print("Your total = {}, dealer's total = {}. Tie!".format(playerHand.getHandValue(),dealerHand.getHandValue())) player.increaseBankroll(bet) else: print("Dealer's cards: {}".format(dealerHand)) print("Your total = {}, dealer's total = {}. You lost :(".format(playerHand.getHandValue(),dealerHand.getHandValue())) keepPlaying = input("Would you like to keep playing? (y or n) ") if keepPlaying.lower() == 'n': break print("Thank you for playing. See you again soon!") if __name__ == '__main__': print("Please run the Casino.py file")
291abeb393225f43250c332941419b41c2c6a791
hjpcs/sort_and_search
/algorithm/bubble_sort.py
581
3.796875
4
from algorithm.generate_random_list import generate_random_list import timeit # 冒泡排序 def bubble_sort(l): length = len(l) # 序列长度为length,需要执行length-1轮交换 for x in range(1, length): # 对于每一轮交换,都将序列中的左右元素进行比较 # 每轮交换当中,由于序列最后的元素一定是最大的,因此每轮循环到序列未排序的位置即可 for i in range(0, length-x): if l[i] > l[i + 1]: temp = l[i] l[i] = l[i+1] l[i+1] = temp
c02250cb32fdc76bfc9b156893925fa852cafc8f
Robert66764/Task-Manager
/task_manager.py
5,323
4
4
#Displaying a message and prompting the user for information. print('Welcome to the Task Manager.\n ') usernames = input('Please enter Username: ') passwords = input('Please enter Password: ') #Opening the text file and splitting the username and password. userfile = open ('user.txt', 'r+') uselist = userfile.readlines() usernameList = [us.split(', ')[0] for us in uselist] userpasswordList = [us.strip('\n').split(', ')[1] for us in uselist] #Creating a while loop for the login and password credntials as well as an error message if the username is already in the user.txt file. while 1: if usernames in usernameList: login = False for usnum, usn in enumerate(usernameList): if usn == usernames and userpasswordList[usnum] == passwords: print('You are successfully logged in.') login = True break if login: break else: print('Error: Please try again. ') usernames = input('Please enter Username: ') passwords = input('Please enter Password: ') #Creating a while loop and an if statement to check if the user entered the correct information. while 1: #Displaying the various options to the user. if usernames == 'admin': user_select = input('''Please select one of the following options: r - register user a - add task va - view all tasks vm - view my tasks s - statistics e - exit \n ''') else: user_select = input('''Please select one of the following options: r - register user a - add task va - view all tasks vm - view my tasks e - exit \n ''') #If the user selected 'r' then the following menu will display for further information from the user. if user_select == 's': task_text = open('tasks.txt','r') user_text = open('user.txt','r') num = 0 count = 0 for i in task_text: total_task = 1 print('This is the total number of tasks: ' + str(total_task)) for i in user_text: total_user = 1 print('This is the total number of users: ' + str(total_user)) #If the user selected 'r' then the following menu will display for further information from the user. if user_select == 'r': user_input_username = input('Please enter a username: ') while user_input_username in usernameList: print("user already exist.") user_input_username = input('Please enter a username: ') user_input_password = input('Please enter a password: ') user_input_confirm_password = input('Please confirm password: ') #Writing to the text file if user_input_password == user_input_confirm_password: userfile.write(user_input_username + ", " + user_input_password + "\n") userfile.close() elif user_input_password != user_input_confirm_password: print("Error: Please try again.") #If the user chooses 'a' the following will be executed. if user_select == 'a': task_text = open('tasks.txt','r+') username_input = input('Please enter a username. ') user_task = input('Please enter the title of the task. ') user_description_task = input('Please give a description of the task. ') user_due_date = input('Please provide the due date of the task. ') #Importing a module to give the current date and writing to the text file. from datetime import date user_date = str(date.today()) task_text.write(username_input + ", " + user_task + ", " + user_description_task + ", " + user_due_date + ", " + user_date) task_text.close() #If the user selects va from the menu the following will happen. if user_select == 'va': task_file = open('tasks.txt','r') for i in task_file: i.split(", ") split_i = i.split(", ") print('Task ' + split_i[1]) print('Assigned to: ' + split_i[0]) print('Date assigned: ' + split_i[4]) print('Due date: ' + split_i[3]) print('Task Completed: No') print('Task Description: ' + split_i[2]) #If the user selects vm the following will happen. if user_select == 'vm': task_file = open('tasks.txt','r') for i in task_file: i.split(", ") split_i = i.split(", ") if usernames == split_i[0]: i.split(", ") split_i = i.split(", ") print('Task ' + split_i[1]) print('Assigned to ' + split_i[0]) print('Date assigned: ' + split_i[4]) print('Due date: ' + split_i[3]) print('Task Completed: No') print('Task Description: ' + split_i[2]) #If the user selects e the while loop is discontinued. if user_select == 'e': break break
c6751727d0f6b20e1505c9007f2543a1f3fe108d
JeffCX/LadBoyCoding_leetcode_solution
/DFS/lc_261_graph_valid_tree.py
1,132
3.578125
4
class Solution: def validTree(self, n: int, edges: List[List[int]]) -> bool: # Create Graph graph_dic = {} for start,end in edges: if start not in graph_dic: graph_dic[start] = [end] else: graph_dic[start].append(end) if end not in graph_dic: graph_dic[end] = [start] else: graph_dic[end].append(start) # DFS to detect cycles visited = set() stack = [(0,-1)] while stack: node, parent = stack.pop() visited.add(node) if node in graph_dic: for next_node in graph_dic[node]: if next_node not in visited: stack.append((next_node, node)) else: if next_node != parent: return False # check if we can traverse all node if len(visited) != n: return False return True
98de35a03755ceac1e2917c645df12a5997488cf
JeffCX/LadBoyCoding_leetcode_solution
/BinarySearch/lc_33_search_a_rotatedSorted_array.py
1,143
3.609375
4
class Solution: def search(self, nums: List[int], target: int) -> int: """ O(logn) """ if not nums: return -1 # 1. find where it is rotated, find the smallest element left = 0 right = len(nums) - 1 while left < right: middle = left + (right - left) // 2 if nums[middle] > nums[right]: left = middle + 1 else: right = middle # find which side we need to binary search start = left left = 0 right = len(nums) - 1 if target >= nums[start] and target <= nums[right]: left = start else: right = start # standard binary search while left <= right: middle = left + (right - left) // 2 if nums[middle] == target: return middle elif nums[middle] > target: right = middle - 1 else: left = middle + 1 return -1
418eb29659e375a2c38a3a478791ab71418eec17
Flood-ctrl/mult_table
/mult_table.py
2,485
3.703125
4
#!/usr/bin/env python3 import sys, getopt, random elementes = (2, 3, 4, 5, 6, 7, 8, 9) wrong_answers = 0 re_multiplicable = None re_multiplier = None start_multiplicable = int(0) test_question = int(0) attempts = len(elementes) passed_questions = list() input_attempts = None input_table = None # Validate input arguments try: opts, args = getopt.getopt(sys.argv[1:],"h:a:t:") except getopt.GetoptError: print (f'{sys.argv[0]} -a <attempts> -t <table>') if sys.argv[1] == "-h" or sys.argv[1] == "--help": sys.exit(0) sys.exit(2) for opt, arg in opts: if opt == "-h" or opt == "--help": print (f'{sys.argv[0]} -a <attempts> -t <table>') sys.exit(0) elif opt in ("-a", "--attempts"): try: input_attempts = int(arg) except ValueError: print("Only numbers are allowed") sys.exit(2) elif opt in ("-t", "--table"): try: input_table = int(arg) if not 2 <= input_table <= 9: print("Tables (-t) allowed: [2 3 4 5 6 7 8 9]") sys.exit(2) except ValueError: print("Only numbers are allowed") sys.exit(2) if input_table is not None: start_multiplicable = int(input_table) if input_attempts is not None: attempts = int(input_attempts) while test_question < attempts: if start_multiplicable != 0: multiplicable = start_multiplicable multiplier = random.choice(elementes) else: multiplicable = random.choice(elementes) multiplier = random.choice(elementes) if re_multiplicable is not None: multiplicable = re_multiplicable multiplier = re_multiplier re_multiplier = None re_multiplicable = None else: string_number = str(multiplicable) + str(multiplier) if string_number in passed_questions: #print(f"Duplicate - {string_number}") continue result = multiplicable * multiplier print(f"{multiplicable} x {multiplier} =", end=' ') try: input_result = int(input()) except ValueError: print("Only numbers allowed") re_multiplicable = multiplicable re_multiplier = multiplier continue if input_result != result: print(f"Wrong answer, correct - {multiplicable} x {multiplier} = {result}") wrong_answers += 1 passed_questions.append(string_number) test_question += 1 print(f"Wrong answers - {wrong_answers}")
9cd79796786856ba4c4340a48a69f6110dc14a0c
mzmudziak/Programowanie-wysokiego-poziomu
/zajecia_9/zadanie_2.py
282
3.609375
4
import pdb name = raw_input("Podaj imie: ") surname = raw_input("Podaj nazwisko: ") age = raw_input("Podaj wiek: ") pdb.set_trace() if age > 18: ageMessage = 'PELNOLETNI' else: ageMessage = 'NIEPELNOLETNI' print 'Czesc ' + name + ' ' + surname + ', jestes ' + ageMessage
97a50afd5c942342feb0dbed098807615bf379eb
mzmudziak/Programowanie-wysokiego-poziomu
/zajecia_3/teoria.py
1,171
3.921875
4
# klasy class Klasa: def function(self): print 'metoda' self.variable = 5 print self.variable def function2(self, number): self.function() print number obiekt = Klasa() obiekt.function2(100) class Klasa2: atrr1 = None __attr2 = None def setAttr2(self, zmienna): self.__attr2 = zmienna def setAttr3(self, zmienna): self.attr3 = zmienna def add(self): return self.attr1 + self.__attr2 + self.attr3 obiekt = Klasa2() obiekt.attr1 = 4 obiekt.setAttr2(5) obiekt.setAttr3(10) print obiekt.add() obiekt.__attr2 = 100 # dziedziczenie class Car(object): color = None def setColor(self, color): self.color = color class PersonalCar(Car): brand = 'Mercedes' def setBrandAndColor(self, brand, color): self.brand = brand super(PersonalCar, self).setColor(color) car = PersonalCar() car.setBrandAndColor('Audi', 'niebieski') print car.color + ' ' + car.brand class A: def __init__(self, zmienna): self.zmienna = zmienna def __add__(self, other): return self.zmienna + other.zmienna print A(5) + A(10)
1bfbc576fa5700f11711f258fb1e3f263d487eae
viharika-22/Python-Practice
/Problem-Set-5/13delcons.py
189
3.78125
4
s=list(input()) l=[] for i in range(len(s)): if s[i]=="i" or s[i]=="o" or s[i]=="a" or s[i]=="e" or s[i]=="u": l.append(s[i]) else: continue print("".join(l))
7970d490d049a731b124994c9bec798830fd5732
viharika-22/Python-Practice
/PlacementPractice/12.py
118
3.765625
4
str1="Gecko" str2="Gemma" for i in range(len(str1)): if str1[i]==str2[1]: print(str1.index(str1[i]))
8b822102bc23c07c004987c17718d9ba22347b48
viharika-22/Python-Practice
/Problem-Set-5/new.py
80
3.625
4
s=input() s1="" for i in range(len(s)): s1=s1+s[i]+"-" print(s1)
0019a653229486d697e69a5a40519ccfa6e93503
viharika-22/Python-Practice
/Problem Set-1/prob5.py
153
3.828125
4
n=str(input()) li=[] for i in n: li.append(i) if li[::]==li[::-1]: print("yes it is palindrome ") else: print("it isn't palindrome")
0b0a7902a8f300b3d73f77ae959ec938250e1744
viharika-22/Python-Practice
/Problem-Set-5/5dectobinary.py
82
3.5
4
def db(n): if n>1: db(n//2) print(n%2,end='') db(int(input()))
6782b6a51666db9062c5446b18dd229aa71041b3
viharika-22/Python-Practice
/PlacementPractice/11.py
108
3.953125
4
n=input() if n[::]==n[::-1]: print("it is a palindrome") else: print("it is not a palindrome")
51632d0bba9edb151cff567dc5c7144361a9a97f
viharika-22/Python-Practice
/Patterns/7.py
99
3.625
4
n=1 for i in range(5): for j in range(i): print(n,end='') n+=1 print()
9c5afd492bc5f9a4131d440ce48636ca03fa721c
viharika-22/Python-Practice
/Problem-Set-2/prob1.py
332
4.34375
4
'''1.) Write a Python program to add 'ing' at the end of a given string (length should be at least 3). If the given string already ends with 'ing' then add 'ly' instead. If the string length of the given string is less than 3, leave it unchanged.''' n=input() s=n[len(n)-3:len(n)] if s=='ing': print(n[:len(n)-3]+'ly')
7503e23122425089e90b6d34ee3a2bf7cef0d51a
viharika-22/Python-Practice
/Problem-Set-6/gh10.py
365
3.546875
4
li1=["Arjun", "Sameeth", "Yogesh", "Vikas" , "Rehman","Mohammad", "Naveen", "Samyuktha", "Rahul","Asifa","Apoorva"] li2= ["Subramanian", "Aslam", "Ahmed", "Kapoor", "Venkatesh","Thiruchirapalli", "Khan", "Asifa" ,"Byomkesh", "Hadid"] fname=max(li1,key=len) lname=max(li2,key=len) longname=fname+" "+lname print(longname) ln=longname[::2] for i in ln:
a3f71d9b7b36d057cc1e9aedec93514e7000b682
viharika-22/Python-Practice
/Problem-Set-6/h1.py
203
3.59375
4
n=int(input()) d={} l=[] li=[] for i in range(n): key=input() d[key]=float(input()) for i in d.keys(): l.append([i,d[i]]) for i in range(len(l)): li.append(l[i][1]) print(li)
d31a4b6f5ebbc1c8403d5cd898afb3d0c257b98e
vitorgabrielmoura/Exercises
/Python 3/Curso_em_video/d62.py
361
3.84375
4
raz = int(input('Digite a razão da sua PA')) prim = int(input('Digite o primeiro termo da sua PA')) pa = 0 qnt = 1 recebe = 1 while recebe != 0: total = recebe +10 while qnt != total: pa = (prim)+raz*qnt qnt = qnt + 1 print(pa,end='') print(' > ',end='') recebe = int(input('Quantos valores deseja ver a mais?'))
b61e8d17f1a9efa2909df39f5af3e43ef6314427
vitorgabrielmoura/Exercises
/Python 3/Curso_em_video/d64.py
207
3.96875
4
soma = opcao = 0 while opcao != 999: opcao = int(input('Digite um número ou digite 999 para parar')) if opcao != 999: soma += opcao print(f'A soma de todos os números digitados foi {soma}')
c59e1afb2d8afc09f020531c64fcdd349237aa61
vitorgabrielmoura/Exercises
/Python 3/Jogos/forca.py
3,358
3.5625
4
import time from random import randint import string def linha(): print(f'{"-"*60}') def cabecalho(txt): linha() print(txt.center(60)) linha() def criarLista(txt,list): num = len(txt) pos = 0 while True: list.append("_") pos += 1 if pos == num: break def leiaLetra(txt): while True: a1 = str(input(txt)).strip() if a1 in string.ascii_letters: return a1 else: print('\033[1;31mERRO. Digite uma letra.\033[m') def ArquivoExiste(txt): try: a = open(txt, 'r') a.close() return True except FileNotFoundError: return False def CriarArquivo(txt): a = open(txt, 'wt+') a.close() def lerArquivo(txt): try: a = open(txt, 'r') except: print('Erro ao ler o arquivo') else: print(a.read()) def adicionar(arq, lista): a = open(arq, 'a') for pala in lista: a.write(f'{pala};\n') a.close() listaa = ['banana', 'janela', 'paralelepipedo', 'biblia', 'teclado', 'computador'] listaaa = [] count = 0 cabecalho('JOGO DA FORCA') erro = 0 arquivo = 'palavras.txt' if not ArquivoExiste(arquivo): CriarArquivo(arquivo) a = open(arquivo, 'r') for linha in a: a1 = linha.strip().split(';') listaaa.append(a1) a.close() palavra = listaaa[randint(0,5)] lista = list() criarLista(palavra[0], lista) while True: print('\n\nJogando...') time.sleep(2) a1 = leiaLetra(f'Qual letra você escolhe? Minha palavra contém {len(palavra[0])} letras!').lower() pos = 0 for letra in palavra[0]: pos += 1 if letra == a1: print() print(f'Encontrei a letra {letra} na posição {pos}',end =' ---> ') lista.insert(pos-1, letra) lista.pop(pos) for c in lista: print(c,end='') if a1 not in lista: erro += 1 print(f'Você errou. Restam {len(palavra[0]) - erro} tentativas') if len(palavra[0]) - erro == 0: print(f'\nVocê perdeu o jogo. A palavra era {palavra[0].capitalize()}') print(" _______________ ") print(" / \ ") print(" / \ ") print("// \/\ ") print("\| XXXX XXXX | / ") print(" | XXXX XXXX |/ ") print(" | XXX XXX | ") print(" | | ") print(" \__ XXX __/ ") print(" |\ XXX /| ") print(" | | | | ") print(" | I I I I I I I | ") print(" | I I I I I I | ") print(" \_ _/ ") print(" \_ _/ ") print(" \_______/ ") break if "_" not in lista: print('\n\nVocê ganhou :D') print(" ___________ ") print(" '._==_==_=_.' ") print(" .-\\: /-. ") print(" | (|:. |) | ") print(" '-|:. |-' ") print(" \\::. / ") print(" '::. .' ") print(" ) ( ") print(" _.' '._ ") print(" '-------' ") break
edf3f7438d8bb2fd005c6fec9214dac561de41f5
vitorgabrielmoura/Exercises
/Python 3/Curso_em_video/d88melhorado.py
496
3.5
4
from random import randint from time import sleep print('MEGA SENA') a1 = int(input('\nDigite quantos jogos você quer sortear')) lista = [] dados = [] total = 1 while total <= a1: count = 0 while True: num = randint(1,60) if num not in dados: dados.append(num) count += 1 if count >= 6: break lista.append(dados[:]) dados.clear() total += 1 for c in range(1,a1+1): print(f'Jogo {c}: {lista[c]}') sleep(1)
991c1f76de22d933924b507714b8f2046bf841de
vitorgabrielmoura/Exercises
/Python 3/Curso_em_video/d25.py
112
3.8125
4
a1=input('Digite seu nome completo') a2=a1.upper() print(f"""O seu nome tem Silva? Resposta: {'SILVA' in a2}""")
f675b7ad77db93b4b4ae9219117d16c89eda4392
vitorgabrielmoura/Exercises
/Python 3/Curso_em_video/d89.py
798
3.859375
4
lista = [] temp = [] while True: temp.append(input('Digite o nome do aluno: ').capitalize()) temp.append(float(input('Nota 1: '))) temp.append(float(input('Nota 2: '))) lista.append(temp[:]) temp.clear() resp = ' ' while resp not in 'SN': resp = input('Quer continuar? [S/N]: ').upper() if resp == 'N': break print(f'{"-="*20}') print(f'{"No.":<4}{"Nome":<10}{"Média":>8}\n') for p, v in enumerate(lista): print(f'{p+1:<4}{v[0]:<10}{(v[1]+v[2])/2:>8.1f}') print(f'\n{"-="*20}') while True: resp2 = input('Deseja mostrar as notas de qual aluno?: (Digite "Nenhum" para sair) ').upper() for c in lista: if resp2 == c[0].upper(): print(f'As notas de {c[0]} são: {c[1]} e {c[2]}') if resp2 == 'NENHUM': break
2319918a3682cb32256845bfcbbb09f26107a502
vitorgabrielmoura/Exercises
/Python 3/Curso_em_video/d40.py
423
3.984375
4
print('ESTOU DE RECUPERAÇÃO?') a1=float(input('\nDigite sua primeira nota')) a2=float(input('Digite sua segunda nota')) if (a1+a2)/2 <5: print(f'\033[1;31mVocê está reprovado com nota final {(a1+a2)/2}') elif (a1+a2)/2 >5 and (a1+a2)/2 <=6.9: print(f'\033[7;30mVocê está de recuperação com nota final {(a1+a2)/2}\033[m') else: print(f'\033[1;32mParabéns! Você foi aprovado com nota final {(a1+a2)/2}')
680a11e966b96a1f473247ff88750046a5aac8e1
vitorgabrielmoura/Exercises
/Python 3/Curso_em_video/d82.py
336
3.984375
4
lista = [] while True: lista.append(int(input('Digite um número'))) resp = str(input('Deseja continuar? [S/N]: ')).upper() if resp == 'N': break print(f"""\nA lista completa é {[x for x in lista]}\nA lista de pares é {[x for x in lista if x % 2 == 0]} A lista de ímpares é {[x for x in lista if x % 3 == 0]}""")
6fd6eca9714a2775c68b90acef5e8c2d8fa1bfd6
vitorgabrielmoura/Exercises
/Python 3/Curso_em_video/d09.py
253
3.875
4
p1=float(input('Pick a number')) n1=p1*1 n2=p1*2 n3=p1*3 n4=p1*4 n5=p1*5 n6=p1*6 n7=p1*7 n8=p1*8 n9=p1*9 print('The table of {} is'.format(p1)) print('1:{}\n2: {}\n3: {}\n4: {}\n5: {}\n6: {}\n7: {}\n8: {}\n9: {}\n'.format(n1,n2,n3,n4,n5,n6,n7,n8,n9))
5c55e9878f158a8a283d096347a299c185f66c04
vitorgabrielmoura/Exercises
/Python 3/Curso_em_video/d73.py
1,316
3.921875
4
times = ('Flamengo', 'Santos', 'Palmeiras', 'Grêmio', 'Athletico-PR', 'São Paulo', 'Internacional', 'Corinthians', 'Fortaleza', 'Goiás', 'Bahia', 'Vasco', 'Atlético-MG', 'Fluminense', 'Botafogo', 'Ceará', 'Cruzeiro', 'CSA', 'Chapecoense', 'Avaí') print(f"""\n{'='*30} BRASILEIRÃO 2019 TABELA FINAL {'='*30} """) while True: a1 = int(input("""\nDigite a opção desejada: [1] Ver os 5 primeiros colocados [2] Ver os últimos 4 colocados [3] Times em ordem alfabética [4] Posição de um time em específico [5] Sair do programa Opção: """)) if a1 == 1: print('\nOs 5 primeiros colocados, em ordem, foram:\n') for prim in range (0,len(times[:5])): print(f'{prim+1}. {times[prim]}') elif a1 == 2: print('\nOs últimos 4 colocados, em ordem, foram:\n') for ult in range (16, len(times)): print(f'{ult+1}. {times[ult]}') elif a1 == 3: print('\nOs times em ordem alfabética são:\n') for tim in sorted(times): print(tim) elif a1 == 4: a2 = input('\nDigite o primeiro nome do time que deseja ver a posição: ').lower().capitalize() a3 = times.index(a2) print(f'O {a2} terminou em {a3+1}º lugar') elif a1 == 5: break print('\nObrigado por utilizar a Vitu Enterprises')
7d7273b8632e1f4d7ac7b9d9a94ae1e0f9b52a96
vitorgabrielmoura/Exercises
/Python 3/Curso_em_video/d06.py
154
4.15625
4
n1=float(input('Pick a number')) d=n1*2 t=n1*3 r=n1**(1/2) print('The double of {} is {} and the triple is {} and the square root is {}'.format(n1,d,t,r))
20325275f6f0c1d011dc965f48b9af420ffd2d3f
vitorgabrielmoura/Exercises
/Python 3/Curso_em_video/d30.py
158
3.875
4
print('### LEITOR DE PAR OU IMPAR ###') print('\n') a1=float(input('Digite um número')) a2=a1%2 if a2 == 0: print('É PAR!') else: print('É ÍMPAR')
bd512cbe3014297b8a39ab952c143ec153973495
CarolinaPaulo/CodeWars
/Python/(8 kyu)_Generate_range_of_integers.py
765
4.28125
4
#Collect| #Implement a function named generateRange(min, max, step), which takes three arguments and generates a range of integers from min to max, with the step. The first integer is the minimum value, the second is the maximum of the range and the third is the step. (min < max) #Task #Implement a function named #generateRange(2, 10, 2) // should return iterator of [2,4,6,8,10] #generateRange(1, 10, 3) // should return iterator of [1,4,7,10] #Note #min < max #step > 0 #the range does not HAVE to include max (depending on the step) def generate_range(min, max, step): hey = [] contador = min while contador < max: hey.append(contador) if step > max: break contador = contador + step return hey
80de26c35904fbd989d94270c407c16312aba74e
snehaldalvi/Stock_Prediction
/stock_price_prediction.py
1,163
3.515625
4
#stock-price-prediction# import numpy as np import pandas as pd from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression df = pd.read_csv('infy.csv') print(df.columns.values) df['Open']=df['Open Price'] df['High']=df['High Price'] df['Low']=df['Low Price'] df['Close']=df['Close Price'] print(df) df = df[['Close', 'Open', 'High', 'Low']] print(df) forecast_col = 'Close' forecast_out = 3 df['label'] =df[forecast_col].shift(-forecast_out) print(df) x = np.array(df.drop(['Close','label'],1)) #print(x) x_lately=x[-forecast_out:] print(x_lately) x = x[:-forecast_out] print(x) y = np.array(df['label']) y = y[:-forecast_out] print(y) x_train, x_test, y_train, y_test = train_test_split(x,y, test_size=0.2) print(x_train.shape, x_test.shape, y_train.shape, y_test.shape) clf = LinearRegression() #clf object (part of that class) clf.fit(x_train, y_train) confidence = clf.score(x_test, y_test) #coefficient of determination print('confidence:' , confidence) forecast_set = clf.predict(x_lately) print(clf) #print(df) print(forecast_set)
23071a888fd6d9a059d8f11c3ab040f7bcb4415e
remo-help/Restoring_the_Sister
/concatenate.py
6,217
3.609375
4
# -*- encoding: utf-8 -*- from itertools import chain, zip_longest def read_in(textfilename): #this gives us a master read-in function, this reads in the file file = str(textfilename) + '.txt'# and then splits the file on newline, and then puts that into a list f = open(file, 'r',encoding='utf-8')# the list is returned string = f.read() listvar = [] listvar = string.split("\n") f.close() return listvar ##############reading in the files french_training = read_in('data\\french_training_res') spanish_training = read_in('data\\spanish_training_res') romanian_training = read_in('data\\romanian_training_res') portuguese_training = read_in('data\\portuguese_training_res') italian_training = read_in('data\\italian_training_res') french_val = read_in('data\\french_val_res') spanish_val = read_in('data\\spanish_val_res') romanian_val = read_in('data\\romanian_val_res') portuguese_val = read_in('data\\portuguese_val_res') italian_val = read_in('data\\italian_val_res') french_test = read_in('data\\french_test_res') spanish_test = read_in('data\\spanish_test_res') romanian_test = read_in('data\\romanian_test_res') portuguese_test = read_in('data\\portuguese_test_res') italian_test = read_in('data\\italian_test_res') ##########we need these functions for the complex concatenation v2 def interspace_strings(string1): #function that allows us to interspace the strings return ''.join(chain(*zip_longest(string1, ' ', fillvalue=' '))) def interleave_strings(string1, string2, string3, string4): #ok, so we use itertools chain and zip_longest to interweave, this function allows us to return a string output return ''.join(chain(*zip_longest(string1, string2, string3, string4, fillvalue=''))) def interleave_strings3(string1, string2, string3): #ok, interleave 3 strings return ''.join(chain(*zip_longest(string1, string2, string3, fillvalue=''))) def interleave_strings2(string1, string2): #ok, for two strings return ''.join(chain(*zip_longest(string1, string2, fillvalue=''))) ###########################this is the smart complex concatenation, it interweaves the strings, removes all spaces, and then adds spaces between each character def concatenatecomplexv2(filename, listname1,listname2,listname3,listname4): newlist =[] index = -1 for i in listname1: #first we get every single line index += 1 string2 =listname2[index] string3=listname3[index] string4=listname4[index] newstring=interleave_strings(i, string2, string3, string4) newstring = newstring.replace(" ", "") newstring = interspace_strings(newstring) newlist.append(newstring) #print(newlist) textfilename_complex = 'data\\' + filename + '.txt' # creates the filename of the training file, using the 'name' input in the function textfile_complex = open(textfilename_complex,'w+',encoding='utf-8') c=0 for element in newlist: #iterates over the list of training items c+=1 #creating a counter so we dont have a trailing newline at the end of the file if c==1: #first entry does not get a newline textfile_complex.write(element) else: textfile_complex.write('\n') #newline for all subsequent entries textfile_complex.write(element) #writes in the file textfile_complex.close() #close the file ####################### concatenate with 3 languages def concatenatecomplex_triple(filename, listname1,listname2,listname3): newlist =[] index = -1 for i in listname1: #first we get every single line index += 1 string2 =listname2[index] string3=listname3[index] newstring=interleave_strings3(i, string2, string3) newstring = newstring.replace(" ", "") newstring = interspace_strings(newstring) newlist.append(newstring) #print(newlist) textfilename_complex = 'data\\' + filename + '.txt' # creates the filename of the training file, using the 'name' input in the function textfile_complex = open(textfilename_complex,'w+',encoding='utf-8') c=0 for element in newlist: #iterates over the list of training items c+=1 #creating a counter so we dont have a trailing newline at the end of the file if c==1: #first entry does not get a newline textfile_complex.write(element) else: textfile_complex.write('\n') #newline for all subsequent entries textfile_complex.write(element) #writes in the file textfile_complex.close() #close the file ###########################concatenate 2 languages def concatenatecomplex_duple(filename, listname1,listname2): newlist =[] index = -1 for i in listname1: #first we get every single line index += 1 string2 =listname2[index] newstring=interleave_strings2(i, string2) newstring = newstring.replace(" ", "") newstring = interspace_strings(newstring) newlist.append(newstring) #print(newlist) textfilename_complex = 'data\\' + filename + '.txt' # creates the filename of the training file, using the 'name' input in the function textfile_complex = open(textfilename_complex,'w+',encoding='utf-8') c=0 for element in newlist: #iterates over the list of training items c+=1 #creating a counter so we dont have a trailing newline at the end of the file if c==1: #first entry does not get a newline textfile_complex.write(element) else: textfile_complex.write('\n') #newline for all subsequent entries textfile_complex.write(element) #writes in the file textfile_complex.close() #close the file ####EXECUTE concatenatecomplexv2('concatenate_input_complex',french_training,romanian_training,portuguese_training,spanish_training) concatenatecomplexv2('concatenate_val_complex',french_val,romanian_val,portuguese_val,spanish_val) concatenatecomplexv2('concatenate_test_complex',french_test,romanian_test,portuguese_test,spanish_test) concatenatecomplex_triple('concatenate_fre_po_it_input',french_training,portuguese_training,spanish_training) concatenatecomplex_triple('concatenate_fre_po_it_val',french_val,portuguese_val,spanish_val) concatenatecomplex_triple('concatenate_fre_po_it_test',french_test,portuguese_test,spanish_test) concatenatecomplex_duple('concatenate_fre_it_input',french_training, spanish_training) concatenatecomplex_duple('concatenate_fre_it_val',french_val, spanish_val) concatenatecomplex_duple('concatenate_fre_it_test',french_test, spanish_test)
51626c3279abb8aa5b46e8815976cf73e61f0cba
Wondae-code/coding_test
/backjoon/정렬/quick_sort.py
1,196
3.890625
4
""" 퀵 소트 1. 처음을 피벗으로 설정하고 자신 다음 숫자(왼쪽에서부터) 하나씩 증가하면서 자신보다 높은 숫자를 선택한다. 2. 오른쪽부터 진행하여 피벗보다 작은수를 선택한다. 3. 선택된 두 숫자의 위치를 변환한다. 4. 왼쪽과 오른쪽이 교차 하는 위치에 피벗을 가져다 놓고 왼쪽과 오른쪽을 다시 퀵 소트를 진행한다. """ array = [5,7,9,0,3,1,6,2,4,8] def quick_sort(array, start, end): if start >= end: return pivot = start left = start + 1 right = end # 4. 교차하기 직전까지 반복문 진행 while left <= right: # 피벗보다 큰 데이터를 찾을때 까지 반복 while left <= end and array[left] <= array[pivot]: left+=1 while right > start and array[right] >= array[pivot]: right -=1 if left > right: array[right], array[pivot] = array[pivot], array[right] else: array[left], array[pivot] = array[pivot], array[left] quick_sort(array, start, right-1) quick_sort(array, right+1, end) quick_sort(array, 0, len(array)-1) print(array)
528d2f290048598d640de14ce92a54c47c09817b
Wondae-code/coding_test
/leetcode/listnode.py
1,408
4.0625
4
class ListNode(): def __init__(self, val = None): self.val = val self.next = None class LinkedList(): def __init__(self): self.head = ListNode() def add(self, data): new_node = ListNode(data) cur = self.head while cur.next != None: cur = cur.next cur.next = new_node def length(self): cur = self.head result = 0 while cur.next != None: cur = cur.next result += 1 return result def display(self): elem = [] cur = self.head while cur.next != None: cur = cur.next elem.append(cur.val) print(elem) def erase(self, index): if index >= self.length(): print("error") return cur = self.head cur_index = 0 while True: last_node = cur cur_node = cur.next if cur_index == index: last_node.next = cur_node.next return cur_index+=1 def get(self, index): if index >= self.length(): print("error") return cur = self.head def main(): ll = LinkedList() ll.add(1) ll.display() ll.add(2) ll.display() ll.add(3) ll.display() ll.erase(0) ll.display() if __name__ == "__main__": main()
f4d10ed1bcbaef9319250d295668e3980da4230b
Wondae-code/coding_test
/backjoon/재귀함수/(2)(2447) 별찍기.py
213
3.640625
4
""" 별찍기 -10 https://www.acmicpc.net/problem/2447 ********* """ def print(x): star = "*" non_star = " " test = x/3 if test != 1: x/test x = int(input()) # for i in range(1, x+1):
854f12abc5253e2a06e076cdffb22029208cb285
ontodev/howl
/ontology/template.py
755
3.71875
4
#!/usr/bin/env python3 # Convert a TSV table into a HOWL file # consisting of lines # that append the header to the cell value. import argparse, csv def main(): # Parse arguments parser = argparse.ArgumentParser( description='Convert table to HOWL stanzas') parser.add_argument('table', type=argparse.FileType('r'), help='a TSV file') args = parser.parse_args() rows = csv.reader(args.table, delimiter='\t') headers = next(rows) for row in rows: if len(row) < 1: continue for i in range(0, min(len(headers), len(row))): if headers[i] == 'SUBJECT': print(row[i]) else: print(headers[i] +' '+ row[i]) print() # Run the main() function. if __name__ == "__main__": main()
5a3b4e2ca6d496a53b6b8e55c2f06ac1dbdec3aa
Byung-moon/Daily_CodingChallenge
/0418/bj1236.py
697
3.71875
4
#prob.1236 from https://www.acmicpc.net/problem/1236 N, M = map(int, input().split(" ")) array = [] for x in range(N): array.append(input()) # Row Search NeedRow = len(array) for x in range(len(array)): for y in range(len(array[0])): if array[x][y] == 'X': NeedRow -= 1 break # Column Search NeedColumn = len(array[0]) for x in range(len(array[0])): for y in range(len(array)): if array[y][x] == 'X': NeedColumn -= 1 break # print('NeedRow : %d' %NeedRow) # print('NeedColumn : %d' %NeedColumn) # print answer if (NeedRow >= NeedColumn): print(NeedRow) else: print(NeedColumn)
d9d86188c2f37c16dd1b0a3afdcf03cb5223035c
sakshiguj/list
/list print.py
67
3.59375
4
list=[15,58,20,2,3] i=0 while i<len(list): i=i+1 print(list)
adcad46d8b5e27a20b1660861e8316f9c7044eab
zingpython/Common_Sorting_Algorithms
/selection.py
594
4.125
4
def selectionSort(): for element in range(len(alist)-1): print("element", element) minimum = element print("minimum", minimum) for index in range(element+1,len(alist)): print("index",index) if alist[index] < alist[minimum]: print("alist[index]",alist[index]) print("alist[minimum]",alist[minimum]) minimum = index print("changing minimum", minimum) alist[element], alist[minimum] = alist[minimum], alist[element] print("swap a,b = b,a",alist[element], alist[minimum]) # alist = [54,26,93,17,77,31,44,55,20] alist = [30,20,10] selectionSort() print(alist)
aedf273538698ee9f6c20eb141afe5e3b81f8742
xlr10/pyton
/190729/190729_03.py
1,351
3.984375
4
# class print("class") print() class FourCal: class_num = 1; def __init__(self, first, second): self.first = first self.second = second # def __init__(self, first, second): # self.first = first # self.second = second # def setNum(self, first, second): # self.first = first # self.second = second def add(self): return self.first + self.second def sub(self): return self.first - self.second def mul(self): return self.first * self.second def div(self): return self.first / self.second test = FourCal(1, 4) print(type(test)) # test.setNum(1,2) print(test.add()) print(test.sub()) print(test.mul()) print(test.div()) class FourCal_pow(FourCal): def pow(self): return self.first ** self.second test_inheritance = FourCal_pow(2, 3) print(test_inheritance.add()) print(test_inheritance.sub()) print(test_inheritance.mul()) print(test_inheritance.div()) print(test_inheritance.pow()) class FourCal_safe(FourCal): def div(self): if self.second == 0: print("Can't Divide Zero") return 0 else: return super().div() test_override = FourCal_safe(2, 0) print(test_override.add()) print(test_override.sub()) print(test_override.mul()) print(test_override.div())
0a2c9e6e590cdcb76d761822d6d9fa92afabf659
xlr10/pyton
/190729/example_01.py
1,400
3.90625
4
###################### 01 print() print("example 01") def is_odd(num): if num % 2 == 1: print("%d is Odd" % num) else: print("%d is Even" % num) is_odd(1) is_odd(2) ###################### 02 print() print("example 02") def average_serial(*args): result = 0 for i in args: result += i result /= len(args) return result print(average_serial(1, 2, 3, 4, 5, 6)) ###################### 03 print() print("example 03") # input1 = input("Press 1st Number:") # input2 = input("Press 2nd Number:") #total = int(input1) + int(input2) #print("Sum is %s " % total) ###################### 04 print() print("example 04") print("you" "need" "python") print("you" + "need" + "python") print("you", "need", "python") print("".join(["you", "need", "python"])) ###################### 05 print() print("example 05") f1 = open("test.txt", 'w') f1.write("Life is too short") f1.close() f2 = open("test.txt", 'r') print(f2.read()) f2.close() ###################### 06 print() print("example 06") f1 = open("test2.txt", 'w') #f1.write(input()) f1.close() f2 = open("test2.txt", 'r') print(f2.read()) f2.close() ###################### 07 print() print("example 07") f1 = open("test3.txt", 'r') tmp=f1.read() f1.close() print(tmp) print(tmp.replace('java','python')) f1 = open("test3.txt", 'w') f1.write(tmp.replace('java','python')) f1.close()
1c9b024feb7296496fa5fe37b65844895f6d858e
JiangNanYu639/python-project
/Question 2.py
1,846
4.0625
4
class Time(): def __init__(self, hour, minutes): self.hour = hour self.minutes = minutes @property def hour(self): return self.__hour @hour.setter def hour(self, h): if h >= 0 and h <= 23: self.__hour = h else: raise ValueError('hour must be in 0-23') @property def minutes(self): return self.__minutes @minutes.setter def minutes(self, m): if m >= 0 and m <= 59: self.__minutes = m else: raise ValueError('minutes must be in 0-59') def __str__(self): t = str(self.__hour) + ':' + str(self.__minutes) return t def __lt__(self, other): if self.__hour < other.__hour: return True elif self.__hour == other.__hour: if self.__minutes < other.__minutes: return True else: return False else: return False def __eq__(self, other): if self.__hour == other.__hour and self.__minutes == other.__minutes: return True else: return False def __gt__(self, other): if self.__hour > other.__hour: return True elif self.__hour == other.__hour: if self.__minutes > other.__minutes: return True else: return False else: return False try: t1 = Time(11, 50) t2 = Time(23, 50) print(t1.hour) print(t1.minutes) print(t1) print(t2) if t2 < t1: print('t2 is before t1') elif t2 == t1: print('t2 is the same as t1') else: print('t2 is after t1') except ValueError as ret: print(ret)
5b0719eba5b442343ab31e241083ba6cd54c5b9c
JiangNanYu639/python-project
/HM0226.2.py
439
3.59375
4
# 大乐透游戏,给你的6位数,中奖码是958 (9 5 8可以在6位数中任意位置,都存在) ,如何判断自己中奖? n = input('Pls type your number: ') a = '9' b = '5' c = '8' length = len(n) if n.isdigit() and length == 6: if n.find(a) != -1 and n.find(b) != -1 and n.find(c) != -1: print('You win!') else: print('Sorry.') else: print('Not a valid number.')
4473702e806d184a6189e699bb8fc65352640661
fjnajasm/PLN
/PRACTICA 1/Ejercicio2.py
741
3.796875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Feb 5 19:02:32 2020 @author: fran """ def listas(a, b): lista_final = [] for i in a: if(i not in lista_final) and (i in b): lista_final.append(i) return lista_final def comprueba(a): try: for i in a: int(i) return True except ValueError: return False lista1 = [1,2,3,4, 1,1,1,1,1,1,1,1] lista2 = [1,3,4,5,6] compruebaa = comprueba(lista1) compruebab = comprueba(lista2) res = [] if (compruebaa is True and compruebab is True): res = listas(lista1, lista2) if len(res) == 0: print("Una de las listas no es de enteros completa") else: for i in res: print(i)
614513ba35b93e4c5d2c7a8ee6a22e4ad1f5d424
Neecolaa/tic-tac-toe
/tictactoe.py
4,761
3.65625
4
class gameBoard: def __init__(self, size): self.size = size self.board = [[' '] * size for i in range(size)] self.cellsFilled = 0 def printBoard(self): rows = list(map(lambda r: " "+" | ".join(r), self.board))#generates list of rows with | #^idk if this is the best/cleanest way to do this board = ("\n"+("--- "*self.size)+"\n").join(rows)#adds horizontal lines between rows print(board) return board def printOptions(self): #determine size of cells cellSize = len(str(self.size * self.size)) #create options table options = [[''] * self.size for i in range(self.size)] for i in range(self.size): for j in range(self.size): if self.board[i][j] != ' ': #add symbol to cell options[i][j] = str.center(self.board[i][j],cellSize) else: #add cell number to cell options[i][j] = str.center(str(self.size*i+j+1),cellSize) rows = list(map(lambda r: " "+" | ".join(r), options))#generates list of rows with | #^idk if this is the best/cleanest way to do this pboard = ("\n"+(("-"*(cellSize+2))+" ")*self.size+"\n").join(rows)#adds horizontal lines between rows print(pboard) return cellSize def fillCell(self,cellNum, symbol): #find row and col from cellNum cellNum = int(cellNum) row = (cellNum-1)//self.size col = (cellNum-1)%self.size #make sure cell is in board if row >= self.size or col >= self.size: return False #check if cell is empty if self.board[row][col] == ' ': #if empty add symbol to cell self.board[row][col] = symbol self.cellsFilled += 1 return True else: #else return false w/o adding anything return False def checkForWin(self): if self.cellsFilled < self.size: #no way to win already (technically no win until size*2-1, maybe will change to that) return False for i in range(self.size): #horizontal check row = self.board[i] #vertical check col = [row[i] for row in self.board] if self.checkWinSet(row) == True or self.checkWinSet(col) == True: return True #diagonal check diagL2R = [self.board[i][i] for i in range(self.size)] diagR2L = [self.board[i][self.size-i-1] for i in range(self.size)] if self.checkWinSet(diagL2R) == True or self.checkWinSet(diagR2L) == True: return True else: return False def checkWinSet(self,values): s = set(values) if len(s) == 1 and ' ' not in s: return True else: return False def isFull(self): return (self.cellsFilled == self.size*self.size) class game: def __init__(self): self.playerCount = int(input('Input player count: ')) self.currentPlayerIdx = 0 self.symbols = self.inputSymbols() size = int(input('Input board size: ')) self.board = gameBoard(size) def inputSymbols(self): symbols = [] for i in range(self.playerCount): symbols.append(input("Input Player "+str(i+1)+"'s symbol: ")) return symbols def play(self): gameWon = False while gameWon is False and self.board.isFull() is False: #show current board + available moves self.board.printOptions() #get current player's move moveValid = False while moveValid is False: move = input("Player "+str(self.currentPlayerIdx+1)+"'s move: ") moveValid = self.board.fillCell(move,self.symbols[self.currentPlayerIdx]) if moveValid is False: print('Selected move not valid! Please reselect.') #check for win gameWon = self.board.checkForWin() if gameWon is False: #move on to next player self.currentPlayerIdx = (self.currentPlayerIdx + 1) % self.playerCount #Game is over self.board.printBoard() #Win or tie? if gameWon is True: print('Player '+str(self.currentPlayerIdx+1)+' wins!') elif self.board.isFull() is True: print("It's a tie!") print('GAME OVER') g = game() g.play()
632b8b79e60f6a1ef17c8bc4165fab17b262211c
siddhantpushpraj/Python_Basics-
/reimport.py
4,109
4.1875
4
import re ### ''' if re.search('hi(pe)*','hidedede'): print("match found") else: print("not found") ''' ### ''' pattern='she' string='she sells sea shells on the sea shore' if re.match(pattern,string): print("match found") else: print("not found") ''' ### ''' pattern='sea' string='she sells sea shells on the sea shore' if re.match(pattern,string): print("match found") else: print("not found") ''' ### ''' pattern=r'[a-z A-Z]+ \d+' string='Lx 12013,Xyzabc 2016,i am indian' m=re.findall(pattern,string) for n in m: print(n) ''' ### ''' pattern=r'[a-z A-Z]+ \d+' string='Lx 12013,Xyzabc 2016,i am indian' m=re.finditer(pattern,string) for n in m: print('match at start index',n.start()) print('match at start index', n.end()) print(n.span()) ''' ''' pattern=r'[a-z A-Z]+ \d+' string='Lx 12013' m=re.findall(pattern,string) for n in m: print(n) ''' # Q.A program that uses a regular expression to match string which starts with a # sequence of digit follwed by blank or space, arbitary character. ''' import re a='LXI 2013,XYZ abc 2016,I am an Indian $%5^' pattern='[a-zA-Z]+[!@#$%&()_] +' m=re.findall(pattern,a) for n in m: print(n) ''' # Q.WAP to extract charcter from a string using a regular expression. ''' import re a=input() pattern='[a-zA-Z]+ ' m=re.findall(pattern,a) for i in m: print(i) ''' # Q.A program to print first word of string. ''' import re a=input() pattern='[a-zA-Z]+ ' m=re.findall(pattern,a) for i in m: print(m[0]) break ''' # Q.program to print char in pairs ''' import re a = input() pattern = '[a-zA-Z]+' m = re.findall(pattern, a) x=m.split("2") for i in x: print(i) ''' # Q.print only first two character of every word. ''' import re a=input() pattern='[a-zA-Z]+' m=re.findall(pattern,a) for i in m: print(i[0:2]) ''' ##Q wap to check if string contains only alphabet and digits only ''' a=input() pat='[a-zA-Z]' if re.search(pat,a): if re.search('[0-9]',a): print(a) ''' ##QUE to match if string contains 1 a followed by 0 or more b's ie ab* .a,ab,abbbb... ##QUE text="the qiuck brown fox jumps over the lazy dog".search for the following pattern.pattern fox dog horse. ##(b)to find location of fox in a given text ''' s="the quick brown fox jump over the lazy dog horse" p1='fox' p2='dog' p3='horse' m=re.findall(p1,s) n=re.findall(p2,s) b=re.findall(p3,s) if(m): if(b): if(n): print("VALID : ",s) else: print("INVALID") else: print("INVALID") else: print("INVALID") ''' ''' s="the quick brown fox jump over the lazy dog horse" p1='fox' m=re.search(p1,s) s=m.span() print("index",s)zzzz ''' #Que pularize the word list=[bush,fox,toy,cat] ''' li=['bush','fox','toy','cat','half','knife'] for x in li: if(x[len(x)-1]=='f'): print(x[0:len(x)-1]+'ves') elif (x[len(x) - 2] == 'f'): print(x[0:len(x) - 2] + 'ves') elif (x[len(x) - 1] == 'x' or x[len(x) - 1] == 'h'): print(x+'es') else: print(x + 's') def pluralize(noun): if re.search('[sxz]$', noun): return re.sub('$', 'es', noun) elif re.search('[^aeioudgkprt]h$', noun): return re.sub('$', 'es', noun) elif re.search('[^aeiou]y$', noun): return re.sub('y$', 'ies', noun) else: return noun + 's' list1=['bush','fox','toy','cat','half','knife'] for i in list1: pluralize(i) print(x) ''' ##Que a website req user to input password and user name,write a programm to validate the password. ##at least one letter from a-z,A-z,@#$,length=6-12 ''' value = [] x=input() items=x.split(',') for p in items: if ((len(p)>6 or len(p)<12)): if (re.findall("[a-z]",p)): if (re.findall("[0-9]",p)): if (re.findall("[A-Z]",p)): if (re.findall("[$#@]",p)): value.append(p) print (",".join(value)) '''
1395e5ded5679ceb8a5c607b36a04e647a407147
siddhantpushpraj/Python_Basics-
/class.py
2,929
4.1875
4
''' class xyz: var=10 obj1=xyz() print(obj1.var) ''' ''' class xyz: var=10 def display(self): print("hi") obj1=xyz() print(obj1.var) obj1.display() ''' ##constructor ''' class xyz: var=10 def __init__(self,val): print("hi") self.val=val print(val) print(self.val) obj1=xyz(10) print(obj1.var) ''' ''' class xyz: class_var=0 def __init__(self,val): xyz.class_var+=1 self.val=val print(val) print("class_var+=1",xyz.class_var) obj1=xyz(10) obj1=xyz(20) obj1=xyz("sid") print(obj1.val) ''' ##wap with class employee keeps the track of number of employee in a organisation and also store thier name, desiganation and salary ''' class comp: count=0 def __init__(self,name,desigantion,salary): comp.count+=1 self.name=name self.desigantion=desigantion self.salary=salary print("name ",name,"desigantion ",desigantion,"salary ",salary) obj1=comp("sid","ceo","150000") obj12=comp("rahul","manager1","150000") obj3=comp("danish","manger2","150000") ''' #wap that has a class circle use a class value define the vlaue of the pi use class value and calculate area nad circumferance ''' class circle: pi=3.14 def __init__(self,radius): self.area=self.pi*radius**2 self.circum=self.pi*radius*2 print("circumferance",self.circum) print("area", self.area) radius=int(input()) obj1=circle(radius) ''' #wap that have a class person storing dob of the person .the program subtract the dob from today date to find whether the person is elgoble for vote or vote ''' import datetime class vote: def __intit__(self,name,dob): self.name=name self.dob=dob def agevote(): today=datetime.date.today() print(today) obj1=vote("siddhant",1997) obj.agevote() ''' # ACCESS SPECIFIED IN PYTHON ## 1) .__ (private variable) 2)._ (protected variable) ''' class abc: def __init__(self,var,var1): self.var=var self.__var1=var1 def display(self): print(self.var) print(self.__var1) k=abc(10,20) k.display() print(k.var) # print(k.__var1) #private print(k.__abc__var1) ''' ##wap uses classes to store the name and class of a student ,use a list to store the marks of three student class student: mark=[] def __init__(self,name): self.name=name self.mark=[] def getmarks(self,sub): for i in range(sub): m=int(input()) self.mark.append(m) def display(self): print(self.name," ",self.mark) print("total student") n=int(int(input())) print("total subject") sub=int(input()) s=[] for i in range(n): print("student name") name=input() s=student(name) s.getmarks(sub) s.display()
f0229a16a7d08489515081689675a77e2066e348
siddhantpushpraj/Python_Basics-
/even odd.py
976
4.0625
4
''' #even odd a=int(input("enetr a number")) b=int(input("enetr a number")) if(a%2==0): print("even") for i in range(a,b+1,2): print(i) print("odd") for i in range(a+1,b,2): print(i) for i in range(a,b+1): if(i%2==0): print(i,"even") else: print(i,"odd") # table a=int(input("enter a number")) for i in range(1,11): print(a,"x",i," = ",a*i) #pow a=int(input("enter number")) b=int(input("enter number")) c=pow(a,b) print(c) ''' #fact a=int(input("enter a number")) m=1 for i in range(1,a+1): m=i*m print(m) ''' # sqr sum a=int(input("enter number")) b=int(input("enter number")) c=pow(a,2) d=pow(b,2) e=c+d print(e) #leap year for i in range(1900,2102): if(i%4==0): if(i%100!=0): print(i) #series a=int(input("enter range")) c=1 for i in range(1,a+1): c=(pow(i,i)/i)+c print(c) '''
27bc28f5e960f4fc56360ad19a4f838b06a95813
Andyporras/portafolio1
/cantidadDeNumerosPares.py
1,059
3.90625
4
""" nombre: contadorDepares entrada: num: numero entero positivo salidad: cantidad de numero pares que tiene el numero digita restrinciones: numero entero positivo mayor a cero """ def contadorDepares(num): if(isinstance(num,int) and num>=0): if(num==0): return 0 elif(num%2)==0: return 1+contadorDepares(num//10) else: return contadorDepares(num//10) else: return print("dijite un entero positivo") #--------------------------------------------------------------------------- def cantidadDeNumerosPares(num): if(isinstance(num,int)and num>0): return cantidadDeNumerosPares_aux(num,0) else: return "digite un numero entero positivo" def cantidadDeNumerosPares_aux(numVerified,result): if(numVerified==0): return result elif(numVerified%2==0): return cantidadDeNumerosPares_aux(numVerified//10,result +1) else: return cantidadDeNumerosPares_aux(numVerified//10,result)
f75dbfe00e001bbbebae43f2ed56c4b8d5098028
ferrakkem/Complete_codingbat_problem_Python
/app.py
27,994
4.25
4
''' The parameter weekday is True if it is a weekday, and the parameter vacation is True if we are on vacation. We sleep in if it is not a weekday or we're on vacation. Return True if we sleep in. sleep_in(False, False) → True sleep_in(True, False) → False sleep_in(False, True) → True ''' def sleep_in(weekday, vacation): if(not weekday or vacation): return True else: False #print(sleep_in(False, False)) ''' We have two monkeys, a and b, and the parameters a_smile and b_smile indicate if each is smiling. We are in trouble if they are both smiling or if neither of them is smiling. Return True if we are in trouble. monkey_trouble(True, True) → True monkey_trouble(False, False) → True monkey_trouble(True, False) → False ''' def monkey_trouble(a_smile, b_smile): if a_smile and b_smile: return True elif not a_smile and not b_smile: return True else: return True #print(monkey_trouble(False, True)) ''' Given two int values, return their sum. Unless the two values are the same, then return double their sum. sum_double(1, 2) → 3 sum_double(3, 2) → 5 sum_double(2, 2) → 8 ''' def sum_double(num1, num2): sum = 0 if (num1 == num2): sum = (num1 + num2)*2 return sum else: sum = num1+num2 return sum #print(sum_double(2, 2)) ''' Given an int n, return the absolute difference between n and 21, except return double the absolute difference if n is over 21. diff21(19) → 2 diff21(10) → 11 diff21(21) → 0 ''' def diff21(n): if n <= 21: return 21 - n else: return (n - 21) * 2 #print(diff21(66)) ''' We have a loud talking parrot. The "hour" parameter is the current hour time in the range 0..23. We are in trouble if the parrot is talking and the hour is before 7 or after 20. Return True if we are in trouble. parrot_trouble(True, 6) → True parrot_trouble(True, 7) → False parrot_trouble(False, 6) → False ''' def parrot_trouble(hour, is_talking): if ((is_talking) and (hour<7 or hour>20)): return True else: return False #print(parrot_trouble(True, 7)) ''' Given 2 ints, a and b, return True if one if them is 10 or if their sum is 10. makes10(9, 10) → True makes10(9, 9) → False makes10(1, 9) → True ''' def makes10(a, b): if (a == 10) or (b == 10) or (a+b == 10): return True else: return False #print(makes10(1, 9)) ''' Given an int n, return True if it is within 10 of 100 or 200. Note: abs(num) computes the absolute value of a number. near_hundred(93) → True near_hundred(90) → True near_hundred(89) → False ''' def near_hundred(n): diff1 = abs(100 - n) diff2 = abs(200 - n) if (diff1 <= 10 or diff2 <= 10): return True else: return False #print(near_hundred(90)) ''' Given 2 int values, return True if one is negative and one is positive. Except if the parameter "negative" is True, then return True only if both are negative. pos_neg(1, -1, False) → True pos_neg(-1, 1, False) → True pos_neg(-4, -5, True) → True ''' def pos_neg(a, b, negative): if negative: return (a < 0 and b < 0) else: return ((a < 0 and b > 0) or (a > 0 and b < 0)) #print(pos_neg(-1, -1, True)) ''' Given a string, return a new string where "not " has been added to the front. However, if the string already begins with "not", return the string unchanged. not_string('candy') → 'not candy' not_string('x') → 'not x' not_string('not bad') → 'not bad' ''' def not_string(sting): checking_value = 'Not' if not checking_value.upper() in sting.upper(): return "Not " + sting else: return sting #print(not_string('Not bad')) ''' Given a non-empty string and an int n, return a new string where the char at index n has been removed. The value of n will be a valid index of a char in the original string (i.e. n will be in the range 0..len(str)-1 inclusive). missing_char('kitten', 1) → 'ktten' missing_char('kitten', 0) → 'itten' missing_char('kitten', 4) → 'kittn' ''' def missing_char(string, n): front = string[:n] back = string[n + 1:] return front + back #print(missing_char('kitten', 1)) ''' Given a string, return a new string where the first and last chars have been exchanged. front_back('code') → 'eodc' front_back('a') → 'a' front_back('ab') → 'ba' ''' def front_back(str): if len(str) <= 1: return str front_chrac = str[0] back_chrac = str[-1] rest_chrac = str[1:-1] return back_chrac + rest_chrac + front_chrac #print(front_back('a')) ''' Given a string, we'll say that the front is the first 3 chars of the string. If the string length is less than 3, the front is whatever is there. Return a new string which is 3 copies of the front. front3('Java') → 'JavJavJav' front3('Chocolate') → 'ChoChoCho' front3('abc') → 'abcabcabc ''' def front3(string): get_front_three = string[:3] return get_front_three*3 #print(front3('Chocolate')) ''' Given a string and a non-negative int n, return a larger string that is n copies of the original string. string_times('Hi', 2) → 'HiHi' string_times('Hi', 3) → 'HiHiHi' string_times('Hi', 1) → 'Hi ''' def string_times(string, number): if (number>0): return string*number else: return "You input negative number" #print(string_times('Hi', -3)) ''' Given a string and a non-negative int n, we'll say that the front of the string is the first 3 chars, or whatever is there if the string is less than length 3. Return n copies of the front; front_times('Chocolate', 2) → 'ChoCho' front_times('Chocolate', 3) → 'ChoChoCho' front_times('Abc', 3) → 'AbcAbcAbc' ''' def front_times(string, number): front_slice = string[:3] if (number <= 3): return front_slice*number else: return front_slice*number #print(front_times('abc', 3)) ''' Given a string, return a new string made of every other char starting with the first, so "Hello" yields "Hlo". string_bits('Hello') → 'Hlo' string_bits('Hi') → 'H' string_bits('Heeololeo') → 'Hello' ''' def string_bits(string): result = "" for i in range(len(string)): if i%2 == 0: result = result + string[i] return result #print(string_bits('Heeololeo')) ''' Given a non-empty string like "Code" return a string like "CCoCodCode". string_splosion('Code') → 'CCoCodCode' string_splosion('abc') → 'aababc' string_splosion('ab') → 'aab ''' def string_splosion(str): result = "" for i in range(len(str)): result = result + str[:i+1] return result #print(string_splosion('ab')) ''' Given a string, return the count of the number of times that a substring length 2 appears in the string and also as the last 2 chars of the string, so "hixxxhi" yields 1 (we won't count the end substring). last2('hixxhi') → 1 last2('xaxxaxaxx') → 1 last2('axxxaaxx') → 2 ''' def last2(string): pass ''' Given an array of ints, return the number of 9's in the array. array_count9([1, 2, 9]) → 1 array_count9([1, 9, 9]) → 2 array_count9([1, 9, 9, 3, 9]) → 3 ''' def array_count9(number): count = 0 for i in number: if i == 9: count = count + 1 return count #print(array_count9([1, 9, 9, 3, 9,9])) ''' Given an array of ints, return True if one of the first 4 elements in the array is a 9. The array length may be less than 4. array_front9([1, 2, 9, 3, 4]) → True array_front9([1, 2, 3, 4, 9]) → False array_front9([1, 2, 3, 4, 5]) → False ''' def array_front9(number): count = 0 end = len(number) if end > 4: end = 4 for i in range(end): if number[i] == 9: return True return False #print(array_front9([1, 2, 3, 4, 9])) ''' Given an array of ints, return True if the sequence of numbers 1, 2, 3 appears in the array somewhere. array123([1, 1, 2, 3, 1]) → True array123([1, 1, 2, 4, 1]) → False array123([1, 1, 2, 1, 2, 3]) → True ''' def array123(numbers): for i in range(len(numbers) - 2): if numbers[i] == 1 and numbers[i + 1] == 2 and numbers[i + 2] == 3: return True return False #print(array123([1, 1, 2, 3, 1])) ''' Given two strings, a and b, return the result of putting them together in the order abba, e.g. "Hi" and "Bye" returns "HiByeByeHi". make_abba('Hi', 'Bye') → 'HiByeByeHi' make_abba('Yo', 'Alice') → 'YoAliceAliceYo' make_abba('What', 'Up') → 'WhatUpUpWhat' ''' def make_abba(a, b): return a+b+b+a #print(make_abba('Yo', 'Alice')) ''' The web is built with HTML strings like "<i>Yay</i>" which draws Yay as italic text. In this example, the "i" tag makes <i> and </i> which surround the word "Yay". Given tag and word strings, create the HTML string with tags around the word, e.g. "<i>Yay</i>". make_tags('i', 'Yay') → '<i>Yay</i>' make_tags('i', 'Hello') → '<i>Hello</i>' make_tags('cite', 'Yay') → '<cite>Yay</cite>' ''' def make_tags(tag, string): making_tag = "<{tag}>".format(tag) print(making_tag) #make_tags('i','yay') ''' Given an "out" string length 4, such as "<<>>", and a word, return a new string where the word is in the middle of the out string, e.g. "<<word>>". make_out_word('<<>>', 'Yay') → '<<Yay>>' make_out_word('<<>>', 'WooHoo') → '<<WooHoo>>' make_out_word('[[]]', 'word') → '[[word]] ''' def make_out_word (str1, str2): frist = str1[:2] second = str1[2:] return frist+str2+second #print(make_out_word('[[]]', 'Yay')) ''' Given a string, return a new string made of 3 copies of the last 2 chars of the original string. The string length will be at least 2. extra_end('Hello') → 'lololo' extra_end('ab') → 'ababab' extra_end('Hi') → 'HiHiHi' ''' def extra_end(string): last_two_chars = string[-2:] return last_two_chars*3 #print(extra_end('Hello')) ''' Given a string, return the string made of its first two chars, so the String "Hello" yields "He". If the string is shorter than length 2, return whatever there is, so "X" yields "X", and the empty string "" yields the empty string "". first_two('Hello') → 'He' first_two('abcdefg') → 'ab' first_two('ab') → 'ab' ''' def first_two(string): if len(string)>2: first_two_chars = string[:2] return first_two_chars else: return string #print(first_two('ab')) ''' Given a string of even length, return the first half. So the string "WooHoo" yields "Woo". first_half('WooHoo') → 'Woo' first_half('HelloThere') → 'Hello' first_half('abcdef') → 'abc ''' def first_half(string): get_string_length = int(len(string)/2) return string[:get_string_length] #print(first_half('HelloThere')) ''' Given a string, return a version without the first and last char, so "Hello" yields "ell". The string length will be at least 2. without_end('Hello') → 'ell' without_end('java') → 'av' without_end('coding') → 'odin' ''' def without_end(string): return string[1:len(string)-1] #print(without_end('coding')) ''' Given 2 strings, return their concatenation, except omit the first char of each. The strings will be at least length 1. non_start('Hello', 'There') → 'ellohere' non_start('java', 'code') → 'avaode' non_start('shotl', 'java') → 'hotlava ''' def non_start(str1, str2): return str1[1:]+str2[1:] #print(non_start('Hello', 'There')) ######################################----List_1------############################ ''' Given an array of ints, return True if 6 appears as either the first or last element in the array. The array will be length 1 or more. first_last6([1, 2, 6]) → True first_last6([6, 1, 2, 3]) → True first_last6([13, 6, 1, 2, 3]) → False ''' def first_last6(number): if number[0] == 9 or number[-1] == 6: return True else: return False #print(first_last6([13, 6, 1, 2, 3])) ''' Given an array of ints, return True if the array is length 1 or more, and the first element and the last element are equal. same_first_last([1, 2, 3]) → False same_first_last([1, 2, 3, 1]) → True same_first_last([1, 2, 1]) → True ''' def same_first_last(num): if num[0] == num[-1]: return True else: return False #print(same_first_last([1, 2, 1])) ''' Given 2 arrays of ints, a and b, return True if they have the same first element or they have the same last element. Both arrays will be length 1 or more. common_end([1, 2, 3], [7, 3]) → True common_end([1, 2, 3], [7, 3, 2]) → False common_end([1, 2, 3], [1, 3]) → True ''' def common_end(num1, num2): if (num1[0]== num2[0]) or(num1[-1] == num2[-1]): return True else: return False #print(common_end([1, 2, 3], [1, 3])) ''' Given an array of ints length 3, return a new array with the elements in reverse order, so {1, 2, 3} becomes {3, 2, 1}. reverse3([1, 2, 3]) → [3, 2, 1] reverse3([5, 11, 9]) → [9, 11, 5] reverse3([7, 0, 0]) → [0, 0, 7] ''' def reverse3(number): return number[::-1] #print(reverse3([1, 2, 3])) ####------------------------------------------------logic-1--------------------------------------------------------- ''' When squirrels get together for a party, they like to have cigars. A squirrel party is successful when the number of cigars is between 40 and 60, inclusive. Unless it is the weekend, in which case there is no upper bound on the number of cigars. Return True if the party with the given values is successful, or False otherwise. cigar_party(30, False) → False cigar_party(50, False) → True cigar_party(70, True) → True ''' def cigar_party(cigars,is_weekend): if (cigars >= 40) and (cigars <=60) or(cigars >= 40) and is_weekend: return True else: return False #print(cigar_party(30,False)) ''' You and your date are trying to get a table at a restaurant. The parameter "you" is the stylishness of your clothes, in the range 0..10, and "date" is the stylishness of your date's clothes. The result getting the table is encoded as an int value with 0=no, 1=maybe, 2=yes. If either of you is very stylish, 8 or more, then the result is 2 (yes). With the exception that if either of you has style of 2 or less, then the result is 0 (no). Otherwise the result is 1 (maybe). date_fashion(5, 10) → 2 date_fashion(5, 2) → 0 date_fashion(5, 5) → 1 ''' def date_fashion(you, my_date): if (you >= 8) or my_date >= 8: return '2' elif (you <= 2 or my_date<= 2): return '0' else: return '1' #print(date_fashion(5, 10)) ''' The squirrels in Palo Alto spend most of the day playing. In particular, they play if the temperature is between 60 and 90 (inclusive). Unless it is summer, then the upper limit is 100 instead of 90. Given an int temperature and a boolean is_summer, return True if the squirrels play and False otherwise. squirrel_play(70, False) → True squirrel_play(95, False) → False squirrel_play(95, True) → True ''' def squirrel_play(temperature, is_summer): if (is_summer): if (temperature >= 60) and (temperature <= 100): return True else: if (temperature >= 60) and (temperature <= 90): return True else: return False #print(squirrel_play(95, True)) ''' You are driving a little too fast, and a police officer stops you. Write code to compute the result, encoded as an int value: 0=no ticket, 1=small ticket, 2=big ticket. If speed is 60 or less, the result is 0. If speed is between 61 and 80 inclusive, the result is 1. If speed is 81 or more, the result is 2. Unless it is your birthday -- on that day, your speed can be 5 higher in all cases. caught_speeding(60, False) → 0 caught_speeding(65, False) → 1 caught_speeding(65, True) → 0 ''' def caught_speeding(speed, is_birthday): if(is_birthday): if speed <= 65: return 0 elif (speed >= 65) and (speed <= 85): return 1 else: return 2 else: if speed <= 60: return 0 elif (speed >= 60) and (speed <= 80): return 1 else: return 2 #print(caught_speeding(60, False)) ''' Given 2 ints, a and b, return their sum. However, sums in the range 10..19 inclusive, are forbidden, so in that case just return 20. sorta_sum(3, 4) → 7 sorta_sum(9, 4) → 20 sorta_sum(10, 11) → 21 ''' def sorta_sum(a, b): sum = a+b if sum in range(10, 19): return '20' else: return sum #print(sorta_sum(19, 4)) ''' Given a day of the week encoded as 0=Sun, 1=Mon, 2=Tue, ...6=Sat, and a boolean indicating if we are on vacation, return a string of the form "7:00" indicating when the alarm clock should ring. Weekdays, the alarm should be "7:00" and on the weekend it should be "10:00". Unless we are on vacation -- then on weekdays it should be "10:00" and weekends it should be "off". alarm_clock(1, False) → '7:00' alarm_clock(5, False) → '7:00' alarm_clock(0, False) → '10:00' ''' def alarm_clock(day, is_vacation): if (is_vacation): if (day >= 1) and (day <= 5): return "10.00" else: return 'Off' else: if (day >= 1) and (day <= 5): return "7.00" else: return '10.00' #print(alarm_clock(5, True)) ''' The number 6 is a truly great number. Given two int values, a and b, return True if either one is 6. Or if their sum or difference is 6. Note: the function abs(num) computes the absolute value of a number. love6(6, 4) → True love6(4, 5) → False love6(1, 5) → True ''' def love6(a, b): if (a == 6) or (b == 6): return True elif abs(a+b) == 6: return True elif abs(a-b) == 6: return True else: return False #print(love6(13, 7)) ''' Given a non-negative number "num", return True if num is within 2 of a multiple of 10. Note: (a % b) is the remainder of dividing a by b, so (7 % 5) is 2. near_ten(12) → True near_ten(17) → False near_ten(19) → True ''' def near_ten(num): mod_num = num % 10 if mod_num <= 2: return True else: return False #print(near_ten(17)) ##--------------------------------logic-2-----------------------------------## ''' We want to make a row of bricks that is goal inches long. We have a number of small bricks (1 inch each) and big bricks (5 inches each). Return True if it is possible to make the goal by choosing from the given bricks. This is a little harder than it looks and can be done without any loops. make_bricks(3, 1, 8) → True make_bricks(3, 1, 9) → False make_bricks(3, 2, 10) → True ''' def make_bricks(): pass ''' Given 3 int values, a b c, return their sum. However, if one of the values is the same as another of the values, it does not count towards the sum. lone_sum(1, 2, 3) → 6 lone_sum(3, 2, 3) → 2 lone_sum(3, 3, 3) → 0 ''' def lone_sum(a, b, c): if a == b and b == c: return 0 elif a == b: return c elif a == c: return b elif b == c: return a else: return a+b+c #print(lone_sum(1, 2, 3)) ''' Given 3 int values, a b c, return their sum. However, if one of the values is 13 then it does not count towards the sum and values to its right do not count. So for example, if b is 13, then both b and c do not count. lucky_sum(1, 2, 3) → 6 lucky_sum(1, 2, 13) → 3 lucky_sum(1, 13, 3) → 1 ''' def lucky_sum(a, b, c): if a == 13: return b+c elif b == 13: return a elif c == 13: return a+b else: return a+b+c #print(lucky_sum(1, 13, 3)) ''' Given 3 int values, a b c, return their sum. However, if any of the values is a teen -- in the range 13..19 inclusive -- then that value counts as 0, except 15 and 16 do not count as a teens. Write a separate helper "def fix_teen(n):"that takes in an int value and returns that value fixed for the teen rule. In this way, you avoid repeating the teen code 3 times (i.e. "decomposition"). Define the helper below and at the same indent level as the main no_teen_sum(). no_teen_sum(1, 2, 3) → 6 no_teen_sum(2, 13, 1) → 3 no_teen_sum(2, 1, 14) → 3 ''' def no_teen_sum(a, b, c): return fix_teen(a) + fix_teen(b) +fix_teen(c) def fix_teen(n): #checking in the range 13..19 inclusive then that value counts as 0, except 15 and 16 do not count as a teens if n >=13 and n <= 19 and n !=15 and n!= 16: return 0 return n #print(no_teen_sum(2, 1, 16)) ''' For this problem, we'll round an int value up to the next multiple of 10 if its rightmost digit is 5 or more, so 15 rounds up to 20. Alternately, round down to the previous multiple of 10 if its rightmost digit is less than 5, so 12 rounds down to 10. Given 3 ints, a b c, return the sum of their rounded values. To avoid code repetition, write a separate helper "def round10(num):" and call it 3 times. Write the helper entirely below and at the same indent level as round_sum(). round_sum(16, 17, 18) → 60 round_sum(12, 13, 14) → 30 round_sum(6, 4, 4) → 10 ''' def round_sum(a, b, c): return round10(a)+round10(b)+round10(c) def round10(num): if num%10 <5: return num - (num%10) else: return num + (10 - num%10) #print(round_sum(16, 17, 18)) ''' Given three ints, a b c, return True if one of b or c is "close" (differing from a by at most 1), while the other is "far", differing from both other values by 2 or more. Note: abs(num) computes the absolute value of a number. close_far(1, 2, 10) → True close_far(1, 2, 3) → False close_far(4, 1, 3) → True ''' def close_far(): pass ''' We want make a package of goal kilos of chocolate. We have small bars (1 kilo each) and big bars (5 kilos each). Return the number of small bars to use, assuming we always use big bars before small bars. Return -1 if it can't be done. make_chocolate(4, 1, 9) → 4 make_chocolate(4, 1, 10) → -1 make_chocolate(4, 1, 7) → 2 ''' #--------------------------------string-2----------------------------------------------- ''' Given a string, return a string where for every char in the original, there are two chars. double_char('The') → 'TThhee' double_char('AAbb') → 'AAAAbbbb' double_char('Hi-There') → 'HHii--TThheerree' ''' def double_char(string): new_string = "" for i in string: new_char = i*2 new_string = new_string + new_char return new_string #print(double_char('Hi-There')) ''' Return the number of times that the string "hi" appears anywhere in the given string. count_hi('abc hi ho') → 1 count_hi('ABChi hi') → 2 count_hi('hihi') → 2 ''' def count_hi(string): cout = 0 for i in range(len(string)-1): if string[i] =='h' and string[i+1] == 'i': cout = cout+1 return cout #print(count_hi('hihi')) ''' Return True if the string "cat" and "dog" appear the same number of times in the given string. cat_dog('catdog') → True cat_dog('catcat') → False cat_dog('1cat1cadodog') → True ''' def cat_dog(string): cat_count = 0 dog_count = 0 cat_count = string.count('cat') dog_count = string.count('dog') if cat_count == dog_count: return True else: return False #print(cat_dog('catcat')) ''' Return the number of times that the string "code" appears anywhere in the given string, except we'll accept any letter for the 'd', so "cope" and "cooe" count. count_code('aaacodebbb') → 1 count_code('codexxcode') → 2 count_code('cozexxcope') → 2 ''' def count_code(string): count = 0 for i in range(len(string)-1): if string[i] == 'c' and string[i+1] =='o' and string[i+3] == 'e': count = count+1 return count #print(count_code('cozexxcope')) ''' Given two strings, return True if either of the strings appears at the very end of the other string, ignoring upper/lower case differences (in other words, the computation should not be "case sensitive"). Note: s.lower() returns the lowercase version of a string. end_other('Hiabc', 'abc') → True end_other('AbC', 'HiaBc') → True end_other('abc', 'abXabc') → True ''' def end_other(str1, str2): str1_last_chat = str1[-1] str2_last_chat = str2[-1] #print(str1_last_chat) #print(str2_last_chat) if str1_last_chat.lower() == str2_last_chat.lower(): return True else: return False #print(end_other('Abd', 'HiaBc')) ''' Return True if the given string contains an appearance of "xyz" where the xyz is not directly preceeded by a period (.). So "xxyz" counts but "x.xyz" does not. xyz_there('abcxyz') → True xyz_there('abc.xyz') → False xyz_there('xyz.abc') → True ''' def xyz_there(string): check_xyz = string.count('xyz') dot_count = string.count('.xyz') #print(f'{check_xyz} and {dot_count}') if check_xyz==dot_count: return False else: return True #print(xyz_there('.xyzabc')) #--------------------------list-2--------------------------------------------------------- ''' Return the number of even ints in the given array. Note: the % "mod" operator computes the remainder, e.g. 5 % 2 is 1. count_evens([2, 1, 2, 3, 4]) → 3 count_evens([2, 2, 0]) → 3 count_evens([1, 3, 5]) → 0 ''' def count_evens(numbers): count = 0 for i in numbers: if i%2==0: count = count +1 return count #print(count_evens([1, 3, 5])) ''' Given an array length 1 or more of ints, return the difference between the largest and smallest values in the array. Note: the built-in min(v1, v2) and max(v1, v2) functions return the smaller or larger of two values. big_diff([10, 3, 5, 6]) → 7 big_diff([7, 2, 10, 9]) → 8 big_diff([2, 10, 7, 2]) → 8 ''' def big_diff(numbers): lg_num = max(numbers) sm_num = min(numbers) difference = lg_num - sm_num return difference print(big_diff([7, 2, 10, 9])) ''' Return the "centered" average of an array of ints, which we'll say is the mean average of the values, except ignoring the largest and smallest values in the array. If there are multiple copies of the smallest value, ignore just one copy, and likewise for the largest value. Use int division to produce the final average. You may assume that the array is length 3 or more. centered_average([1, 2, 3, 4, 100]) → 3 centered_average([1, 1, 5, 5, 10, 8, 7]) → 5 centered_average([-10, -4, -2, -4, -2, 0]) → -3 ''' def centered_average(): pass ''' Return the sum of the numbers in the array, returning 0 for an empty array. Except the number 14 is very unlucky, so it does not count and numbers that come immediately after a 14 also do not count. sum14([1, 2, 2, 1]) → 6 sum14([1, 1]) → 2 sum14([1, 2, 2, 1, 14]) → 6 ''' def sum14(numbers): sum = 0 #i = 0 for i in range(len(numbers)-1): if numbers[i] == 14: numbers.pop(i) sum = sum + numbers[i] return sum #print(sum14([1, 2,1,1,2,14,1,1])) ''' Return the sum of the numbers in the array, except ignore sections of numbers starting with a 6 and extending to the next 7 (every 6 will be followed by at least one 7). Return 0 for no numbers. sum67([1, 2, 2]) → 5 sum67([1, 2, 2, 6, 99, 99, 7]) → 5 sum67([1, 1, 6, 7, 2]) → 4 ''' def sum67(numbers): result = 0 flag = True for num in numbers: if num == 6: flag = False if flag: result += num if num == 7: flag = True return result print(sum67([1, 2, 2, 6, 99, 99, 7])) ''' Given an array of ints, return True if the array contains a 2 next to a 2 somewhere. has22([1, 2, 2]) → True has22([1, 2, 1, 2]) → False has22([2, 1, 2]) → False ''' def has22(nums): for i in nums: if nums[i] == 2 and nums[i+1] == 2: return True else: return False #print(has22([1, 2, 1, 2]))
d3b72253c5aad86dcff61d706444521bdf67be76
Anas2-L/Projects
/2ndhighest.py
301
3.875
4
def secondhigh(list1): new_list=set(list1) new_list.remove(max(new_list)) return max(new_list) list1=[] n=int(input("enter list size ")) for i in range(n): x=input("\nenter the element ") list1.append(x) print("original list\n",list1) print(secondhigh(list1))
86b4a2b74893cb40f1e19f469d059be178b838cc
Anas2-L/Projects
/extractdigits.py
176
3.984375
4
num=int(input("Enter a number")) temp=num while (temp>=1): if(temp%10==0): print(0) else: print(int(temp%10)) temp=int(temp/10) print(num)
600ef001b64ebd30b8687ab622b9e7549f714437
MaX-Lo/ProjectEuler
/116_red_green_blue_tiles.py
1,313
3.640625
4
""" idea: """ import copy import time # 122106096, 5453760 def main(): max_row_len = 50 print('row length:', max_row_len) if max_row_len % 2 == 0: start = 2 combinations = 1 else: combinations = 0 start = 1 for gaps in range(start, max_row_len-1, 2): # step 2 because only even num of gaps is possible tmp_combinations = get_gap_combinations(gaps, max_row_len) combinations += tmp_combinations # print('gaps', gaps, 'combs', tmp_combinations) print('all combinations for block len 2:', combinations) def increasing_nums(nums, max_num): max_num += 1 count = {i: 1 for i in range(max_num)} for i in range(1, nums): tmp_count = {} for num in range(max_num): tmp_count[num] = 0 for j in range(num, max_num): tmp_count[num] += count[j] count = copy.deepcopy(tmp_count) res = 0 for num in count: res += count[num] return res def get_gap_combinations(gaps, row_len): if (row_len-gaps) % 2 != 0: print("blocks can't be even") max_jumps = (row_len - gaps) // 2 return increasing_nums(gaps, max_jumps) if __name__ == '__main__': start_time = time.time() main() print("time:", time.time() - start_time)
ff5a073e2083ce23400d787e87907011818b01c6
MaX-Lo/ProjectEuler
/035_circular_primes.py
1,284
3.75
4
""" Task: """ import time import primesieve as primesieve def main(): primes = set(primesieve.primes(1000000)) wanted_nums = set() for prime in primes: str_prime = str(prime) all_rotations_are_prime = True for rotation_num in range(len(str_prime)): str_prime = str_prime[1:] + str_prime[0] if int(str_prime) not in primes or str_prime in wanted_nums: all_rotations_are_prime = False break if all_rotations_are_prime: wanted_nums.add(prime) print(wanted_nums) print("num of these primes:", len(wanted_nums)) def all_primes(limit): # list containing for every number whether it has been marked already numbers = {} for x in range(3, limit, 2): numbers[x] = False primes = [2, 3] p = 3 while p < limit: for i in range(p, limit, p): numbers[i] = True for i in range(p, limit, 2): if not numbers[i]: p = i numbers[i] = True primes.append(i) break else: p += 1 return primes if __name__ == '__main__': start_time = time.time() main() print("time:", time.time() - start_time)
53161d215504eeb7badb8105197bd926091b971b
MaX-Lo/ProjectEuler
/074_digit_factorial_chains.py
696
3.734375
4
""" idea: """ import time import math def main(): t0 = time.time() count = 0 for i in range(1, 1000000): if i % 10000 == 0: print('{}%, {}sec'.format(i / 10000, round(time.time() - t0), 3)) if get_chain_len(i) == 60: count += 1 print('wanted num:', count) def get_chain_len(num): chain = set() element = num while element not in chain: chain.add(element) tmp = 0 for digit in str(element): tmp += math.factorial(int(digit)) element = tmp return len(chain) if __name__ == '__main__': start_time = time.time() main() print("time:", time.time() - start_time)
2e9c25015e590a2139ab7e423d23ab8402a941be
MaX-Lo/ProjectEuler
/helpers_inefficient.py
2,442
3.828125
4
def all_primes(limit): segment_size = 20000000 if limit <= segment_size: return primes_euklid(limit) primes = primes_euklid(segment_size) iteration = 1 while limit > segment_size * iteration: print("progress, at:", segment_size * iteration) start = segment_size*iteration end = segment_size * (iteration + 1) primes = segmented_primes(start, end, primes) iteration += 1 start = segment_size*iteration end = limit if start == end: return primes else: return segmented_primes(start, end, primes) def primes_euklid(limit): # list containing for every number whether it has been marked already numbers = {} for x in range(3, limit, 2): numbers[x] = False primes = [2, 3] p = 3 while p < limit: for i in range(p, limit, p): numbers[i] = True for i in range(p, limit, 2): if not numbers[i]: p = i numbers[i] = True primes.append(i) break else: p += 1 return primes def segmented_primes(n, limit, primes): """ :param n: start value to search for primes :param limit: end value to search for primes :param primes: primes smaller than n :return: """ if n % 2 == 0: n -= 1 # create dict with numbers in that segment numbers = {} for x in range(n, limit, 2): numbers[x] = False # Todo marking takes like forever... # mark all numbers that are multiples of primes in the given list of primes for smaller numbers for num in numbers: for prime in primes: if num % prime == 0: numbers[num] = True if numbers[num]: break # find the first prime in this segment to start with p = -1 for num in numbers: if not numbers[num]: p = num primes.append(p) break if p == -1: print("Error, no prime in segment found...") # sieve primes in the segment while p < limit: for i in range(p, limit, p): numbers[i] = True for i in range(p, limit, 2): if not numbers[i]: p = i numbers[i] = True primes.append(i) break else: p += 2 return primes
72a56a90e4a26e0f1423c95f5d517a07eade3e5d
MaX-Lo/ProjectEuler
/061_cyclical_figurate_numbers.py
3,131
3.640625
4
""" idea: """ import time def main(): # lists containing 4-digit polygonal numbers as strings triangles = generate_figurate_nums(1000, 10000, triangle) squares = generate_figurate_nums(1000, 10000, square) pentagonals = generate_figurate_nums(1000, 10000, pentagonal) hexagonals = generate_figurate_nums(1000, 10000, hexagonal) heptagonals = generate_figurate_nums(1000, 10000, heptagonal) octagonals = generate_figurate_nums(1000, 10000, octagonal) # for every number in squares: # - check in other polygonal lists for numbers beginning with # the last two digits of this square number # - repeat that 5 times # all in all that should be some recursion algorithm lists_to_check_in = [squares, pentagonals, hexagonals, heptagonals, octagonals] for current_num in triangles: first_num = current_num last_two = first_num[-2:] for polygonal_list in lists_to_check_in: for next_num in polygonal_list: first_two = next_num[:2] if first_two == last_two: new_to_check_list = list(lists_to_check_in) new_to_check_list.remove(polygonal_list) ist, elements = is_cyclic(first_num, next_num, new_to_check_list) elements = list(elements) elements.insert(0, first_num) if ist: print(elements) print('sum:', sum([int(ele) for ele in elements])) def is_cyclic(first_num, current_num, lists_to_check_in): # recursion termination condition if len(lists_to_check_in) == 0: last_two = current_num[-2:] first_two = first_num[:2] cyclic = last_two == first_two if cyclic: print('cyclic, start num:', first_num) return True, [current_num] else: return False, [current_num] # recursive check elements in remaining polygonal lists last_two = current_num[-2:] for polygonal_list in lists_to_check_in: for next_num in polygonal_list: first_two = next_num[:2] if first_two == last_two: new_to_check_list = list(lists_to_check_in) new_to_check_list.remove(polygonal_list) ist, elements = is_cyclic(first_num, next_num, new_to_check_list) if ist: elements.insert(0, current_num) return ist, elements return False, [] def triangle(n): return n * (n + 1) / 2 def square(n): return n**2 def pentagonal(n): return n*(3*n-1)/2 def hexagonal(n): return n*(2*n-1) def heptagonal(n): return n*(5*n-3)/2 def octagonal(n): return n*(3*n-2) def generate_figurate_nums(n_min, n_max, func): nums = [] n = 0 i = 1 while func(i) < n_max: n = func(i) if n >= n_min: # Todo n_min: nums.append(str(int(n))) i += 1 return nums if __name__ == '__main__': start_time = time.time() main() print("time:", time.time() - start_time)
6f71761903964bc4431f50a80a58665eb926749b
MaX-Lo/ProjectEuler
/549_divisibility_of_factorials.py
1,718
3.671875
4
""" idea: """ import time import math import primesieve def main(): limit = 10**8 primes = primesieve.primes(limit) primes_s = set(primes) # key: (prime^power), value: s(prime^power) cache = dict() for prime in primes: power = 1 while prime ** power < limit: fac = prime k = prime while fac % prime**power != 0: k += prime fac *= k cache[(prime, power)] = k power += 1 print('finished building cache') # approach with calculating factorization for every single number res = 0 time0 = time.time() for i in range(2, limit+1): if i % 100000 == 0: print('prog', i, round(time.time() - time0, 2), 'sec') if i in primes_s: res += i else: tmp = s(i, primes, cache) res += tmp print('result', res) def s(n, primes, cache): #factors = factorint(n) factors = factorization(n, primes) return max([cache[(factor, factors[factor])] for factor in factors]) def factorization(n, primes): """ :param n: number to factorize :param primes: list with primes :return: dictionary with primes that occur (and count of them) """ factors = {} while n != 1: for prime in primes: if n % prime == 0: #print(n) n //= prime if prime in factors: factors[prime] += 1 else: factors[prime] = 1 break return factors if __name__ == '__main__': start_time = time.time() main() print("time:", time.time() - start_time)
a3bc3257a40b563f88fae09094d1b2de401d4d6f
MaX-Lo/ProjectEuler
/005_evenly_divisible.py
639
3.609375
4
""" 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? """ import time def main(): start = time.time() # n=20 > 26.525495767593384, >232792560 n = 9699690 #2*3*5*7*11*13*17*19 print(n) while not is_devisible(n): n += 9699690 print(time.time()-start) print(n) def is_devisible(n): devisible = True for i in range(11, 20): if n % i != 0: devisible = False return devisible if __name__ == '__main__': main()
b1631d263871aaeaa21ed313eefa8ab8f9c2326a
MaX-Lo/ProjectEuler
/102_triangle_containment.py
1,835
3.6875
4
""" idea: """ import time def main(): data = read_file('102_triangles.txt') count = 0 #print(contains_origin([-340, 495, -153, -910, 835, -947])) for triangle in data: print(contains_origin(triangle)) if contains_origin(triangle): count += 1 print('count:', count) def contains_origin(points): """ idea: check whether one line is above origin and one line is under it if yes the triangle has to contain the origin """ above = False under = False x1, y1, x2, y2, x3, y3 = points t_above, t_under = check_line([x1, y1, x2, y2]) if t_above: above = True if t_under: under = True t_above, t_under = check_line([x1, y1, x3, y3]) if t_above: above = True if t_under: under = True t_above, t_under = check_line([x2, y2, x3, y3]) if t_above: above = True if t_under: under = True return above and under def check_line(points): above = False under = False if points[0] > points[2]: xb, yb = points[0], points[1] xs, ys = points[2], points[3] else: xb, yb = points[2], points[3] xs, ys = points[0], points[1] if xb >= 0 and xs <= 0: m = (yb - ys) / (xb - xs) f0 = ys + m * abs(xs) if f0 > 0: above = True elif f0 < 0: under = True else: above = True under = True return above, under def read_file(filename): data_file = open(filename) data_set = [] for line in data_file.readlines(): values = [int(x) for x in line.strip().split(',')] data_set.append(values) return data_set if __name__ == '__main__': start_time = time.time() main() print("time:", time.time() - start_time)
7abf47c117213f72142f2bb9daeaaffe0cf58de4
MaX-Lo/ProjectEuler
/034_digit_factorials.py
406
3.6875
4
""" Task: """ import time import math def main(): wanted_nums = [] for i in range(3, 1000000): num_sum = 0 for digit in str(i): num_sum += math.factorial(int(digit)) if i == num_sum: wanted_nums.append(i) print(wanted_nums) if __name__ == '__main__': start_time = time.time() main() print("time:", time.time() - start_time)
b17f9bb2ee4cc729989a34c3631f53961fc450f8
MaX-Lo/ProjectEuler
/106_special_subset_sums_meta_testing.py
2,005
3.578125
4
""" idea: """ import copy import time import itertools import math def main(): sets = [ [1], # 1 [1, 2], # 2 [2, 3, 4], # 3 [3, 5, 6, 7], # 4 [6, 9, 11, 12, 13], # 5 [11, 18, 19, 20, 22, 24], # 6 [47, 44, 42, 27, 41, 40, 37], # 7 [81, 88, 75, 42, 87, 84, 86, 65], # 8 [157, 150, 164, 119, 79, 159, 161, 139, 158], # 9 [354, 370, 362, 384, 359, 324, 360, 180, 350, 270], # 10 [673, 465, 569, 603, 629, 592, 584, 300, 601, 599, 600], # 11 [1211, 1212, 1287, 605, 1208, 1189, 1060, 1216, 1243, 1200, 908, 1210] # 12 ] i = 1 for my_set in sets: count = test(my_set) print(i, ' len needs tests:', count) i += 1 def test(nums: list): """ list is sorted ascending""" # check if a subset with more nums than another subset has also a greater sum nums.sort() count = 0 for subset_len in range(2, len(nums)//2 + 1): for subset1 in itertools.combinations(nums, subset_len): remaining = copy.deepcopy(nums) for num in subset1: remaining.remove(num) for subset2 in itertools.combinations(remaining, subset_len): l1 = list(subset1) l1.sort() l2 = list(subset2) l2.sort() l1_ascending = False l1_descending = False for i in range(len(l1)): if l1[i] < l2[i]: if l1_ascending: count += 1 break l1_descending = True elif l1[i] > l2[i]: if l1_descending: count += 1 break l1_ascending = True return count / 2 if __name__ == '__main__': start_time = time.time() main() print("time:", time.time() - start_time)
0fe3da6717019161da1ef5c1d3b1bbb451299b30
MaX-Lo/ProjectEuler
/064_odd_period_square_roots.py
950
3.984375
4
""" idea: """ import time import math def main(): num_with_odd_periods = 0 for i in range(2, 10001): if math.sqrt(i) % 1 == 0: continue count = continued_fraction(i) if count % 2 == 1: num_with_odd_periods += 1 print('rep len for {}: {}'.format(i, count)) print('count of nums with odd periods:', num_with_odd_periods) def continued_fraction(num): """ square root of any natural number that is not a perfect square e.g. 3, 5, 6, 7... but not 4, or 9 """ s = num sqrtS = math.sqrt(num) a0 = math.floor(sqrtS) m = 0 d = 1 a = a0 count = 0 while True: m = d * a - m d = (s - m**2) / d a = math.floor((a0 + m) / d) count += 1 if a == 2*a0: break return count if __name__ == '__main__': start_time = time.time() main() print("time:", time.time() - start_time)
f31fcec47d734feaf6f5d680b6625e88acaa1048
MaX-Lo/ProjectEuler
/039_integer_right_triangles.py
1,453
3.828125
4
""" idea: """ import time import math def main(): p_with_max_solutions = -1 max_solutions = -1 for perimeter in range(1, 1001): print(perimeter) wanted_nums = [] a = 0 b_and_c = perimeter while b_and_c >= a: b_and_c -= 1 a += 1 for i in range(b_and_c): b = i c = b_and_c - i if b >= a or c >= a: continue if is_right_angle_triangle(a, b, c): wanted_nums.append((a, b, c)) num_solutions = len(wanted_nums) / 2 # every triplet if num_solutions > max_solutions: p_with_max_solutions = perimeter max_solutions = num_solutions print("max solutions num:", max_solutions) print("p with max solutions:", p_with_max_solutions) def is_right_angle_triangle(a, b, c): hypothenus = -1 n1 = -1 n2 = -1 if a >= b and a >= c: hypothenus, n1, n2 = a, b, c elif b >= a and b >= c: hypothenus, n1, n2 = b, a, c elif c >= a and c >= b: hypothenus, n1, n2 = c, a, b angle1 = math.degrees(math.asin(n1 / hypothenus)) angle2 = math.degrees(math.asin(n2 / hypothenus)) angle_3 = 180 - angle1 - angle2 return math.fabs(90 - angle_3) < 0.0000001 if __name__ == '__main__': start_time = time.time() main() print("time:", time.time() - start_time)
de55784264f1f52758efe3b09550520df5be25c1
MaX-Lo/ProjectEuler
/119_digit_power_sum.py
711
3.640625
4
""" idea: """ import time import math def main(): upper_limit = 10**13 found_nums = [] for x in range(2, int(math.sqrt(upper_limit))): if x % 100000 == 0: print('prog:', x) p = x while p < upper_limit: p *= x if digit_sum(p) == x: found_nums.append(p) found_nums.sort() print('found {} nums'.format(len(found_nums))) print(found_nums) if len(found_nums) >= 30: print('30th:', found_nums[29]) def digit_sum(n): r = 0 while n: r, n = r + n % 10, n // 10 return r if __name__ == '__main__': start_time = time.time() main() print("time:", time.time() - start_time)
65298718ef4f0c1af6cc574f2d9aba856412af29
itCatface/idea_python
/py_pure/src/catface/introduction/04_functional_programming/3_lambda.py
509
3.90625
4
# -匿名函数 # --ex1 l = [1, 3, 5, 7, 9] r = map(lambda x: x * x, l) print(list(r)) # --ex2 print('匿名函数结果:', list(map((lambda x: x * 2), l))) # --ex3. 可以把匿名函数作为返回值返回 f = lambda x, y: x * y print('使用匿名函数计算:', f(2, 3)) # lambda x: x * x --> def f(x): return x * x # --ex4. 改造以下代码 def is_odd(n): return n % 2 == 1 L = list(filter(is_odd, range(1, 20))) print(L) r = filter(lambda x: x % 2 == 1, range(1, 20)) print(list(r))
67d1cde085301b30592e61152369c2609144305a
itCatface/idea_python
/py_pure/src/catface/introduction/06_oo_junior/2_access_restrict.py
864
3.96875
4
# -访问限制 class Student(object): def __init__(self, name, score): self.__name = name self.__score = score def set_name(self, name): self.__name = name def get_name(self): return self.__name # 检查分数 def set_score(self, score): if 0 <= score <= 100: self.__score = score else: return ValueError('invalid score!') def get_score(self): return self.__score def print(self): print('name: %s, score: %s' % (self.__name, self.__score)) s = Student('kobe', 8) print('s.get_name:', s.get_name()) print('s.get_score:', s.get_score()) s.set_score(24) print('s.get_score:', s.get_score()) print(s.set_score(-1)) # 这里只是给实例s新增了__score变量 s.__score = 99 print('s.get_score:', s.get_score(), ' || s.__score:', s.__score)
b5e51529e0c68b4c5d3879f9c034ce8540fadeab
itCatface/idea_python
/py_pure/src/catface/introduction/07_oo_senior/2_property.py
1,692
3.890625
4
# -@property[既能检查参数,又可以用类似属性这样简单的方式来访问类的变量] # 常规getter&setter class Student(object): def __init__(self): pass def set_score(self, score): if not isinstance(score, int): raise ValueError('score must be an integer') if score < 0 or score > 100: raise ValueError('score must between 0~100') self._score = score def get_score(self): return self._score s1 = Student() # s1.set_score('78') # s1.set_score(789) s1.set_score(78) print("s1's get_score:", s1.get_score()) # 使用@property将方法变成属性调用 class Animal(object): @property def age(self): return self._age @age.setter def age(self, age): if not isinstance(age, int): raise ValueError('age must be an integer') if age < 0: raise ValueError('age must > 0') self._age = age a1 = Animal() # a1.age = '12' # a1.age = -1 a1.age = 1 print("a1's age:", a1.age) # ex1. 利用@property给一个Screen对象加上width和height属性,以及一个只读属性resolution class Screen(object): @property def width(self): return self._width @width.setter def width(self, width): self._width = width @property def height(self): return self._height @height.setter def height(self, height): self._height = height # 只读属性==>只定义getter方法,不定义setter方法 @property def resolution(self): return self._width * self._height s = Screen() s.width = 768 s.height = 1024 print("s's resolution is:", s.resolution)
d2feee5ec35d4bf4575cf61a98bf6d62ef9fb771
itCatface/idea_python
/py_pure/src/catface/introduction/01_base/5_for.py
1,222
3.765625
4
# -循环 def test_for(): # for nums = (1, 2, 3, 4, 5) sum = 0 for x in nums: sum += x print(sum) # 15 for i, v in enumerate(nums): print('第%d个位置的值为%d' % (i, v)) # 第0个位置的值为1\n第1个位置的值为2... # range nums = list(range(10)) # range(x): 生成一个整数序列 | list(range(x)): 通过list()将整数序列转换为list print('range(5):', range(5), 'nums: ', nums) # range(0, 5) nums: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # while sum = 0 num = 100 while num > 0: sum += num num -= 1 print(sum) # 5050 # 练习:循环打印['zhangsan', ...] names = ['zhangsan', 'lisi', 'wanger', 'mazi'] for name in names: print('hi:', name) # break[提前退出循环] & continue[结束本轮循环,直接开始下一轮循环] n = 0 while n < 5: n += 1 if n > 3: # break可退出循环 break print(n) # 1 2 3 n = 0 while n < 6: n += 1 if n % 2 == 0: # continue结束本次循环并开始下一轮循环,通常配合if使用 continue print(n) # 1 3 5 test_for()
262604114db21368103f6c8e670fa17d1b640bed
dante092/Caesar-Cypher
/kassuro.py
5,718
4.3125
4
#!/usr/bin/python3 def encrypt(string, rotate): """ Encrypt given input string with the caeser cypher. args: string (str): string to encrypt. rotate (int): number by whiche the characters are rotated. returns: str: encrypted version of the input string. raises: TypeError: if word is not a string or rotate not an int. ValueError: if word is empty string or rotate is smaller than 1. """ if not isinstance(string, str) or not isinstance(rotate, int): raise TypeError elif not string or rotate < 1: raise ValueError else: encrypted_string = '' for char in string: if not char.isalpha(): encrypted_string += char else: char_code = ord(char) # check if rotated char code is bigger than char code of z if char_code + rotate > 122: # if so, compute left rotations after z and start from a char_code = 96 + (char_code + rotate - 122) # check if rotated char code is bigger than char code of Z but # smaller than char code of a elif char_code + rotate > 90 and char_code + rotate < 97: # if so, compute left rotations after Z and start from A char_code = 64 + (char_code + rotate - 90) else: char_code += rotate encrypted_string += chr(char_code) return encrypted_string def decrypt(string, rotate): """ Decrypt given input string with the caeser cypher. args: string (str): string to decrypt. rotate (int): number by whiche the characters are rotated. returns: str: decrypted version of the input string. raises: TypeError: if word is not a string or rotate not an int. ValueError: if word is empty string or rotate is smaller than 1. """ if not isinstance(string, str) or not isinstance(rotate, int): raise TypeError elif not string or rotate < 1: raise ValueError else: decrypted_string = '' for char in string: if not char.isalpha(): decrypted_string += char else: char_code = ord(char) # check if rotated char code is smaller than char code for a # but char code is bigger than char code for a - 1 if char_code - rotate < 97 and char_code > 96: # if true, than start over from z char_code = 123 - (rotate - (char_code - 97)) # check if rotated char code is smaller than A elif char_code - rotate < 65: # if ture, than start over from Z char_code = 91 - (rotate - (char_code - 65)) else: char_code -= rotate decrypted_string += chr(char_code) return decrypted_string if __name__ == '__main__': zen = "Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those!" zen_encrypt = "Ilhbapmbs pz ilaaly aohu bnsf. Lewspjpa pz ilaaly aohu ptwspjpa. Zptwsl pz ilaaly aohu jvtwsle. Jvtwsle pz ilaaly aohu jvtwspjhalk. Msha pz ilaaly aohu ulzalk. Zwhyzl pz ilaaly aohu kluzl. Ylhkhipspaf jvbuaz. Zwljphs jhzlz hylu'a zwljphs luvbno av iylhr aol ybslz. Hsaovbno wyhjapjhspaf ilhaz wbypaf. Lyyvyz zovbsk ulcly whzz zpsluasf. Buslzz lewspjpasf zpslujlk. Pu aol mhjl vm htipnbpaf, ylmbzl aol altwahapvu av nblzz. Aolyl zovbsk il vul-- huk wylmlyhisf vusf vul --vicpvbz dhf av kv pa. Hsaovbno aoha dhf thf uva il vicpvbz ha mpyza buslzz fvb'yl Kbajo. Uvd pz ilaaly aohu ulcly. Hsaovbno ulcly pz vmalu ilaaly aohu *ypnoa* uvd. Pm aol ptwsltluahapvu pz ohyk av lewshpu, pa'z h ihk pklh. Pm aol ptwsltluahapvu pz lhzf av lewshpu, pa thf il h nvvk pklh. Uhtlzwhjlz hyl vul ovurpun nylha pklh -- sla'z kv tvyl vm aovzl!" print("Starting assert-tests:") print("encrypting tests:") assert encrypt('abcd', 1) == 'bcde' print('Test 01: passed') assert encrypt('xyz', 2) == 'zab' print('Test 02: passed') assert encrypt('ABC', 2) == 'CDE' print('Test 03: passed') assert encrypt('Hallo', 3) == 'Kdoor' print('Test 04: passed') assert encrypt('XYZ', 2) == 'ZAB' print('Test 05: passed') assert encrypt(zen, 7) == zen_encrypt print("Test 06: passed") print("decrypting tests:") assert decrypt('bcde', 1) == 'abcd' print('Test 07: passed') assert decrypt('zab', 2) == 'xyz' print('Test 08: passed') assert decrypt('CDE', 2) == 'ABC' print('Test 09: passed') assert decrypt('Kdoor', 3) == 'Hallo' print('Test 10: passed') assert decrypt('ZAB', 2) == 'XYZ' print('Test 11: passed') assert decrypt(zen_encrypt, 7) == zen print("Test 12: passed")
db18e85eb77c5d672ef397b4f21560e92a7ef5ad
johan-eriksson/advent-of-code-2019
/src/day7.py
5,242
3.5625
4
import itertools import math class Computer(): def __init__(self, phase): self.OPCODES = { 1: self.ADD, 2: self.MUL, 3: self.WRITE, 4: self.READ, 5: self.JNZ, 6: self.JEZ, 7: self.LT, 8: self.EQ, 99: self.EXIT } self.input = [] self.input.append(phase) self.phase = phase self.last_output = None self.input_index = 0 self.PC = 0 self.output_targets = [] self.running = True def read_from_file(self, file, delimiter=','): self.memory = [] with open(file) as f: self.memory.extend([x.strip() for x in f.read().split(',')]) def run(self): while self.running: if self.PC<len(self.memory): if self.PC<len(self.memory): mode = self.memory[self.PC][:-2] op = int(self.memory[self.PC][-2:]) result = self.OPCODES[op](mode) if result == -1: return False else: print("Ran through entire memory") self.running = False return True def add_output_target(self, f): self.output_targets.append(f) def pad_mode(self, mode, goal): while len(mode) < goal: mode = "0" + mode mode = mode[::-1] return mode def get_value(self, mode, value): # mode==1 is immediate mode, mode==0 is position mode if not mode or mode=="0": return self.memory[int(value)] elif mode=="1": return value print("ERROR: Got mode unsupported mode: "+str(mode)) return False def add_input(self, i): self.input.append(i) def send_output(self, out): self.last_output = out for f in self.output_targets: f(out) def ADD(self, mode): mode = self.pad_mode(mode, 3) operand0 = self.get_value(mode[0], self.memory[self.PC+1]) operand1 = self.get_value(mode[1], self.memory[self.PC+2]) operand2 = int(self.memory[self.PC+3]) self.memory[operand2] = str(int(operand0) + int(operand1)) self.PC += 4 def MUL(self, mode): mode = self.pad_mode(mode, 3) operand0 = self.get_value(mode[0], self.memory[self.PC+1]) operand1 = self.get_value(mode[1], self.memory[self.PC+2]) operand2 = int(self.memory[self.PC+3]) self.memory[operand2] = str(int(operand0) * int(operand1)) self.PC += 4 def WRITE(self, mode): if len(self.input) > self.input_index: operand0 = int(self.memory[self.PC+1]) self.memory[operand0] = self.input[self.input_index] self.input_index += 1 self.PC += 2 else: return -1 def READ(self, mode): operand0 = self.get_value(mode, self.memory[self.PC+1]) self.send_output(operand0) self.PC += 2 def JNZ(self, mode): mode = self.pad_mode(mode, 2) operand0 = int(self.get_value(mode[0], self.memory[self.PC+1])) operand1 = int(self.get_value(mode[1], self.memory[self.PC+2])) if operand0 == 0: self.PC += 3 else: self.PC = operand1 def JEZ(self, mode): mode = self.pad_mode(mode, 2) operand0 = int(self.get_value(mode[0], self.memory[self.PC+1])) operand1 = int(self.get_value(mode[1], self.memory[self.PC+2])) if operand0 == 0: self.PC = operand1 else: self.PC += 3 def LT(self, mode): mode = self.pad_mode(mode, 3) operand0 = int(self.get_value(mode[0], self.memory[self.PC+1])) operand1 = int(self.get_value(mode[1], self.memory[self.PC+2])) operand2 = int(self.memory[self.PC+3]) if operand0 < operand1: self.memory[operand2] = 1 else: self.memory[operand2] = 0 self.PC += 4 def EQ(self, mode): mode = self.pad_mode(mode, 3) operand0 = int(self.get_value(mode[0], self.memory[self.PC+1])) operand1 = int(self.get_value(mode[1], self.memory[self.PC+2])) operand2 = int(self.memory[self.PC+3]) if operand0 == operand1: self.memory[operand2] = 1 else: self.memory[operand2] = 0 self.PC += 4 def EXIT(self, mode): self.running = False self.PC += 1 return True def __repr__(self): return "Computer "+str(self.phase) class ResultComparer(): def __init__(self): self.best = 0 def check(self, thrust): thrust = int(thrust) if thrust > self.best: self.best = thrust def get_best(self): return self.best def solvepart1(): rc = ResultComparer() num_computers = 5 for p in itertools.permutations(range(num_computers)): cpus = [] for index, phase in enumerate(p): if index==0: cpu = Computer(str(phase)) cpu.add_input("0") cpus.append(cpu) else: cpus.append(Computer(str(phase))) for i in range(num_computers-1): cpus[i].add_output_target(cpus[i+1].add_input) cpus[num_computers-1].add_output_target(rc.check) for cpu in cpus: cpu.read_from_file('inputs/day7.txt') cpu.run() return rc.get_best() def solvepart2(): rc = ResultComparer() num_computers = 5 for p in itertools.permutations(range(5, 5+num_computers)): cpus = [] for index, phase in enumerate(p): if index==0: cpu = Computer(str(phase)) cpu.add_input("0") cpus.append(cpu) else: cpus.append(Computer(str(phase))) for i in range(num_computers-1): cpus[i].add_output_target(cpus[i+1].add_input) cpus[num_computers-1].add_output_target(cpus[0].add_input) for cpu in cpus: cpu.read_from_file('inputs/day7.txt') while any([cpu.running for cpu in cpus]): for cpu in cpus: cpu.run() rc.check(cpus[num_computers-1].last_output) return rc.get_best() if __name__=='__main__': print(solvepart1()) print(solvepart2())
80643111235604455d6372e409fa248db684da97
s56roy/python_codes
/python_prac/calculator.py
1,136
4.125
4
a = input('Enter the First Number:') b = input('Enter the Second Number:') # The entered value 10 is a string, not a number. To convert this into a number we can use int() or float() functions. sum = float(a)+float(b) print(sum) print('The sum of {0} and {1} is {2}'.format(a, b, sum)) print('This is output to the screen') print ('this is output to the screen') print ('The Sum of a & b is', sum) print('The sum is %.1f' %(float(input('Enter again the first number: '))+float(input('Enter again the second number: ')))) print(1,2,3,4) # Output: 1 2 3 4 print(1,2,3,4,sep='*') # Output: 1*2*3*4 print(1,2,3,4,sep='#',end='&') # Output: 1#2#3#4& print('I love {0} and {1}'.format('bread','butter')) # Output: I love bread and butter print('I love {1} and {0}'.format('bread','butter')) # Output: I love butter and bread print('Hello {name}, {greeting}'.format(greeting = 'Goodmorning', name = 'John')) # Hello John, Goodmorning x = 12.3456789 print('The value of x is %3.2f' %x) # The value of x is 12.35 print('The value of x is %3.4f' %x) # The value of x is 12.3457 import math print(math.pi) from math import pi pi
b55313c576269b2fe93fc708e12bf74966886521
MColosso/Wesleyan.-Machine-Learning-for-Data-Analysis
/Week 4. Running a k-means Cluster Analysis.py
7,015
3.6875
4
# # Created on Mon Jan 18 19:51:29 2016 # # @author: jrose01 # Adapted by: mcolosso # from pandas import Series, DataFrame import pandas as pd import numpy as np import matplotlib.pylab as plt from sklearn.cross_validation import train_test_split from sklearn import preprocessing from sklearn.cluster import KMeans plt.rcParams['figure.figsize'] = (15, 5) # # DATA MANAGEMENT # #Load the dataset loans = pd.read_csv("./LendingClub.csv", low_memory = False) # LendingClub.csv is a dataset taken from The LendingClub (https://www.lendingclub.com/) # which is a peer-to-peer leading company that directly connects borrowers and potential # lenders/investors # # Exploring the target column # # The target column (label column) of the dataset that we are interested in is called # `bad_loans`. In this column 1 means a risky (bad) loan and 0 means a safe loan. # # In order to make this more intuitive, we reassign the target to be: # 1 as a safe loan and 0 as a risky (bad) loan. # # We put this in a new column called `safe_loans`. loans['safe_loans'] = loans['bad_loans'].apply(lambda x : 1 if x == 0 else 0) loans.drop('bad_loans', axis = 1, inplace = True) # Select features to handle # In this oportunity, we are going to ignore 'grade' and 'sub_grade' predictors # assuming those are a way to "clustering" the loans predictors = ['short_emp', # one year or less of employment 'emp_length_num', # number of years of employment 'home_ownership', # home_ownership status: own, mortgage or rent 'dti', # debt to income ratio 'purpose', # the purpose of the loan 'term', # the term of the loan 'last_delinq_none', # has borrower had a delinquincy 'last_major_derog_none', # has borrower had 90 day or worse rating 'revol_util', # percent of available credit being used 'total_rec_late_fee', # total late fees received to day ] target = 'safe_loans' # prediction target (y) (+1 means safe, 0 is risky) ignored = ['grade', # grade of the loan 'sub_grade', # sub-grade of the loan ] # Extract the predictors and target columns loans = loans[predictors + [target]] # Delete rows where any or all of the data are missing loans = loans.dropna() # Convert categorical text variables into numerical ones categorical = ['home_ownership', 'purpose', 'term'] for attr in categorical: attributes_list = list(set(loans[attr])) loans[attr] = [attributes_list.index(idx) for idx in loans[attr] ] print((loans.describe()).T) # # MODELING AND PREDICTION # # Standardize clustering variables to have mean=0 and sd=1 for attr in predictors: loans[attr] = preprocessing.scale(loans[attr].astype('float64')) # Split data into train and test sets clus_train, clus_test = train_test_split(loans[predictors], test_size = .3, random_state = 123) print('clus_train.shape', clus_train.shape) print('clus_test.shape', clus_test.shape ) # K-means cluster analysis for 1-9 clusters from scipy.spatial.distance import cdist clusters = range(1,10) meandist = list() for k in clusters: model = KMeans(n_clusters = k).fit(clus_train) clusassign = model.predict(clus_train) meandist.append(sum(np.min(cdist(clus_train, model.cluster_centers_, 'euclidean'), axis=1)) / clus_train.shape[0]) """ Plot average distance from observations from the cluster centroid to use the Elbow Method to identify number of clusters to choose """ plt.plot(clusters, meandist) plt.xlabel('Number of clusters') plt.ylabel('Average distance') plt.title('Selecting k with the Elbow Method') plt.show() # Interpret 5 cluster solution model = KMeans(n_clusters = 5) model.fit(clus_train) clusassign = model.predict(clus_train) # Plot clusters from sklearn.decomposition import PCA pca_2 = PCA(2) plot_columns = pca_2.fit_transform(clus_train) plt.scatter(x = plot_columns[:, 0], y = plot_columns[:, 1], c = model.labels_, ) plt.xlabel('Canonical variable 1') plt.ylabel('Canonical variable 2') plt.title('Scatterplot of Canonical Variables for 5 Clusters') plt.show() # # BEGIN multiple steps to merge cluster assignment with clustering variables to examine # cluster variable means by cluster # # Create a unique identifier variable from the index for the # cluster training data to merge with the cluster assignment variable clus_train.reset_index(level = 0, inplace = True) # Create a list that has the new index variable cluslist = list(clus_train['index']) # Create a list of cluster assignments labels = list(model.labels_) # Combine index variable list with cluster assignment list into a dictionary newlist = dict(zip(cluslist, labels)) newlist # Convert newlist dictionary to a dataframe newclus = DataFrame.from_dict(newlist, orient = 'index') newclus # Rename the cluster assignment column newclus.columns = ['cluster'] # Now do the same for the cluster assignment variable: # Create a unique identifier variable from the index for the cluster assignment # dataframe to merge with cluster training data newclus.reset_index(level = 0, inplace = True) # Merge the cluster assignment dataframe with the cluster training variable dataframe # by the index variable merged_train = pd.merge(clus_train, newclus, on = 'index') merged_train.head(n = 100) # cluster frequencies merged_train.cluster.value_counts() # # END multiple steps to merge cluster assignment with clustering variables to examine # cluster variable means by cluster # # FINALLY calculate clustering variable means by cluster clustergrp = merged_train.groupby('cluster').mean() print ("Clustering variable means by cluster") print(clustergrp) # Validate clusters in training data by examining cluster differences in SAFE_LOANS using ANOVA # first have to merge SAFE_LOANS with clustering variables and cluster assignment data gpa_data = loans['safe_loans'] # split safe_loans data into train and test sets gpa_train, gpa_test = train_test_split(gpa_data, test_size=.3, random_state=123) gpa_train1 = pd.DataFrame(gpa_train) gpa_train1.reset_index(level = 0, inplace = True) merged_train_all = pd.merge(gpa_train1, merged_train, on = 'index') sub1 = merged_train_all[['safe_loans', 'cluster']].dropna() import statsmodels.formula.api as smf import statsmodels.stats.multicomp as multi gpamod = smf.ols(formula = 'safe_loans ~ C(cluster)', data = sub1).fit() print (gpamod.summary()) print ('Means for SAFE_LOANS by cluster') m1 = sub1.groupby('cluster').mean() print (m1) print ('Standard deviations for SAFE_LOANS by cluster') m2 = sub1.groupby('cluster').std() print (m2) mc1 = multi.MultiComparison(sub1['safe_loans'], sub1['cluster']) res1 = mc1.tukeyhsd() print(res1.summary())
e890b55a98130e34004f3ad15e02b8993aadf55b
eudaimonious/LPTHW
/ex4.py
1,485
4
4
cars = 100 space_in_a_car = 4.0 drivers = 30 passengers = 90 cars_not_driven = cars - drivers cars_driven = drivers carpool_capacity = cars_driven * space_in_a_car average_passengers_per_car = passengers / cars_driven print "There are", cars, "cars available." print "There are only", drivers, "drivers available." print "There will be", cars_not_driven, "empty cars today." print "We can transport", carpool_capacity, "people today." print "We have", passengers, "to carpool today." print "We need to put about", average_passengers_per_car, "in each car." ''' When I wrote this program the first time I had a mistake, and python told me about it like this: Traceback (most recent call last): File "ex4.py", line 8, in <module> average_passengers_per_car = car_pool_capacity / passenger NameError: name 'car_pool_capacity' is not defined Explain this error in your own words. Make sure you use line numbers and explain why. Here's more extra credit: I used 4.0 for space_in_a_car, but is that necessary? What happens if it's just 4? Remember that 4.0 is a "floating point" number. Find out what that means. Write comments above each of the variable assignments. Make sure you know what = is called (equals) and that it's making names for things. Remember _ is an underscore character. Try running python as a calculator like you did before and use variable names to do your calculations. Popular variable names are also i, x, and j. '''
1aaec58e360a3897542886686250694e7971b308
yesiamjulie/pyAlgorithm
/AlgoTest/Passing_bridge.py
617
3.53125
4
def solution(bridge_length, weight, truck_weights): answer =0 waiting = truck_weights length_truck = len(truck_weights) passed = [] passing = [] on_bridge = [] while len(passed) != length_truck: for i in range(len(passing)): passing[i] += - 1 if passing and passing[0] == 0: del passing[0] passed.append(on_bridge.pop(0)) if waiting and weight >= sum(on_bridge) + waiting[0]: on_bridge.append(waiting.pop(0)) passing.append(bridge_length) print(passing) answer += 1 return answer
145a53662de78fc1e68618010034705f73b44d62
yesiamjulie/pyAlgorithm
/AlgoTest/SumOfTwoN.py
518
3.59375
4
""" 서로 다른 자연수들로 이루어진 배열 arr와 숫자 n이 입력으로 주어집니다. 만약 배열 arr에 있는 서로 다른 2개의 자연수를 합하여 숫자 n을 만드는 것이 가능하면 true를, 불가능하면 false를 반환하는 함수를 작성하세요. """ def solution(arr, n): answer = False length = len(arr) for i in range(length - 1): for j in range(i + 1, length): if arr[i] + arr[j] == n: answer = True return answer
d1a4bffe153eaaffde01f1bc0f07bb9fe8646941
gurralaharika21/toy-problems
/LRU-oops/Lru_cache.py
1,290
3.5625
4
import collections # import OrderedDict class LRUCache: # dict = {} def __init__(self,capacity :int): self.capacity = capacity self.cache = collections.OrderedDict() def put(self,key:int,value:int): try: self.cache.pop(key) except KeyError: if len(self.cache) >= self.capacity: self.cache.popitem(last=False) # //first in first out self.cache[key] = value def get(self,key:int): try: value = self.cache.pop(key) self.cache[key] = value val = value # print(value) return value except KeyError: # print(-1) return -1 def get_cache(self): return self.cache # print(self.cache) # if __name__ == "__main__": # dict = LRUCache(4) # dict.put(1,10) # dict.put(2,11) # dict.put(3,12) # dict.put(3,13) # dict.put(4,13) # dict.get_cache() # dict.get(7) # self.key = key # self.value = value # cach = LRUCache(4) # dict.put(1,10) # dict.put(2,3) # # print(dict) # # cach = LRUcache(4) # cache.get(1) # capacity = 10 # put(1,10) # put(2,90) # get(2)
3a0af90aa6b19e7c73245e6724db18fb050aef7d
JinhuaShen/Python-Learning
/CalcCount.py
1,038
3.640625
4
import csv import re import sqlite3 def genInfos(file): csvfile = open(file, 'r') reader = csv.reader(csvfile) seeds = [] for seed in reader: seeds.append(seed) csvfile.close() return seeds def showInfos(infos): result = open("result.txt", 'w') tmplist = [] result.write("total count: " + str(len(infos)) + "\n") #print ("total count: " + str(len(infos))) for seed in infos: if seed in tmplist: continue tmplist.append(seed) result.write("unique count: " + str(len(tmplist)) + "\n") #print ("unique count: " + str(len(tmplist))) for seed2 in tmplist: line = str(seed2) + "\t\t\t\t" + str(infos.count(seed2)) + "\n" result.write(line) #print("%s %d" %(seed2,infos.count(seed2))) result.close(); def init(csv): infos = genInfos(csv) showInfos(infos) def main(): init("seed.csv") if __name__ == '__main__': main()
15b45688390a72bdb74852f76cee51101ef1193e
ykcai/Python_ML
/homework/week11_homework.py
679
3.890625
4
# Machine Learning Class Week 11 Homework # 1. An isogram is a word that has no repeating letters, consecutive or nonconsecutive. Create a function that takes a string and returns either True or False depending on whether or not it's an "isogram". # Examples # is_isogram("Algorism") ➞ True # is_isogram("PasSword") ➞ False # # Not case sensitive. # is_isogram("Consecutive") ➞ False # Notes: Ignore letter case (should not be case sensitive). All test cases contain valid one word strings. def is_isogram(word): pass is_isogram("Algorism") is_isogram("PasSword") is_isogram("Consecutive") # 2. What are the 4 different detection models that we covered in class?
69f49e0d03340dbbe2a4cdf5d489d884d2fe5b53
ykcai/Python_ML
/homework/week8_homework.py
599
3.890625
4
# Machine Learning Class Week 8 Homework import numpy as np # 1. Create an array of 10 zeros # 2. Create an array of 10 ones # 3. Create an array of 10 fives # 4. Create an array of the integers from 10 to 50 # 5. Create an array of all the even integers from 10 to 50 # 6. Create a 3x3 matrix with values ranging from 0 to 8 # 7. Create a 3x3 identity matrix # 8. Use NumPy to generate a random number between 0 and 1 # 9. Use NumPy to generate an array of 25 random numbers sampled from a standard normal distribution # 10. Create an array of 20 linearly spaced points between 0 and 1.
9060d68c59660d4ee334ee824eda15cc49519de9
ykcai/Python_ML
/homework/week5_homework_answers.py
2,683
4.34375
4
# Machine Learning Class Week 5 Homework Answers # 1. def count_primes(num): ''' COUNT PRIMES: Write a function that returns the number of prime numbers that exist up to and including a given number count_primes(100) --> 25 By convention, 0 and 1 are not prime. ''' # Write your code here # --------------------------------Code between the lines!-------------------------------- primes = [2] x = 3 if num < 2: # for the case of num = 0 or 1 return 0 while x <= num: for y in range(3, x, 2): # test all odd factors up to x-1 if x % y == 0: x += 2 break else: primes.append(x) x += 2 print(primes) return len(primes) # --------------------------------------------------------------------------------------- def count_primes2(num): ''' COUNT PRIMES FASTER ''' primes = [2] x = 3 if num < 2: return 0 while x <= num: for y in primes: # use the primes list! if x % y == 0: x += 2 break else: primes.append(x) x += 2 print(primes) return len(primes) # Check print(count_primes(100)) # 2. def palindrome(s): ''' Write a Python function that checks whether a passed in string is palindrome or not. Note: A palindrome is word, phrase, or sequence that reads the same backward as forward, e.g., madam or nurses run. ''' # Write your code here # --------------------------------Code between the lines!-------------------------------- # This replaces all spaces ' ' with no space ''. (Fixes issues with strings that have spaces) s = s.replace(' ', '') return s == s[::-1] # Check through slicing # --------------------------------------------------------------------------------------- print(palindrome('helleh')) print(palindrome('nurses run')) print(palindrome('abcba')) # 3. def ran_check(num, low, high): ''' Write a function that checks whether a number is in a given range (inclusive of high and low) ''' # Write your code here # --------------------------------Code between the lines!-------------------------------- # Check if num is between low and high (including low and high) if num in range(low, high+1): print('{} is in the range between {} and {}'.format(num, low, high)) else: print('The number is outside the range.') # --------------------------------------------------------------------------------------- # Check print(ran_check(5, 2, 7)) # 5 is in the range between 2 and 7 => True
0629cc2ce905a9bcb6d02fdf4114394d8e9ab6dc
Hackman9912/PythonCourse
/Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Medium Stuff/Classes/coinimport.py
599
3.8125
4
# This program imports the ocin module and creates an instance of the Coin Class # needs to be the file name or file path if in a different directory import coin def main(): # create an object from the ocin class # needs the filename.module my_coin = coin.Coin() # Display the side of the coin that is facing up print("This side is up: ", my_coin.get_sideup()) # Toss the coin print(" I am tossing the coin ten times: ") for count in range(10): my_coin.toss() print(count+1, my_coin.get_sideup()) # Call the main function main()
e25a8fc38ef3e98e5dc34aae30fbbea316e709c2
Hackman9912/PythonCourse
/Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Basic Stuff/LoopsPractice/3.py
1,029
4.21875
4
# 3. Budget Analysis # Write a program that asks the user to enter the amount that he or she has budgeted for amonth. # A loop should then prompt the user to enter each of his or her expenses for the month, and keep a running total. # When the loop finishes, the program should display theamount that the user is over or under budget. def main(): budget = float(input("Enter the amount you have budgeted this month: ")) total = 0 cont = "Y" while cont == "Y" or cont == "y": expense = float(input("Enter the expense amount you want tabulated from the budget: ")) cont = str(input("Enter y to continue or any other key to quit: ")) total += expense if total < budget: bottom_line = budget - total print(f"You are {bottom_line:.2f} under budget.") elif total > budget: bottom_line = total - budget print(f"You are {bottom_line:.2f} over budget.") else: print("Your expenses matched your budget.") main()
2b1cf90a6ed89d0f5162114a103397c0f2a211e8
Hackman9912/PythonCourse
/Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Hard Stuff/More advance things/iter.py
612
4.25
4
# Python iterators # mylist = [1, 2, 3, 4] # for item in mylist: # print(item) # def traverse(iterable): # it = iter(iterable) # while True: # try: # item = next(it) # print(item) # except: StopIteration: # break l1 = [1, 2, 3] it = iter(l1) # print next iteration in list # print(it.__next__()) # print(it.__next__()) # print(it.__next__()) # print(it.__next__()) # or you can use this print(next(it)) print(next(it)) print(next(it)) # print(next(it)) # some objects are not itreable and will error iter(100)
b62ba48d92de96b49332b094f8b34a5f5af4a6cb
Hackman9912/PythonCourse
/Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Hard Stuff/More advance things/map.py
607
4.375
4
# The map() function # Takes in at least 2 args. Can apply a function to every item in a list/iterable quickly def square(x): return x*x numbers = [1, 2, 3, 4, 5] squarelist = map(square, numbers) print(next(squarelist)) print(next(squarelist)) print(next(squarelist)) print(next(squarelist)) print(next(squarelist)) sqrlist2 = map(lambda x : x*x, numbers) print(next(sqrlist2)) print(next(sqrlist2)) print(next(sqrlist2)) print(next(sqrlist2)) print(next(sqrlist2)) tens = [10, 20, 30, 40, 50] indx = [1, 2, 3, 4, 5] powers = list(map(pow, tens, indx[:3])) print(powers)
8abfe167d6fa9e524df27f0adce9f777f4e2df58
Hackman9912/PythonCourse
/Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Basic Stuff/LoopsPractice/5.py
1,278
4.5625
5
# 5. Average Rainfall # Write a program that uses nested loops to collect data and calculate the average rainfall over a period of years. # The program should first ask for the number of years. The outer loop will iterate once for each year. # The inner loop will iterate twelve times, once for each month. Each iteration of the inner loop will ask the user for the inches of rainfall for that month. # After all iterations,the program should display the number ofmonths, the total inches of rainfall, and the average rainfall per month for the entire period. monthdict = { 1: "January", 2: "February", 3: "March", 4: "April", 5: "May", 6: "June", 7: "July", 8: "August", 9: "September", 10: "October", 11: "November", 12: "December" } months = 0 years = int(input("Enter a number of years to enter rainfall data for: ")) total_rainfall = 0 for i in range(years): for key in monthdict: rainfall = float(input(f"Enter the rainfall for {monthdict.get(key):}: ")) total_rainfall += rainfall months += 1 average = total_rainfall / months print(f"The total rainfall per for {months:} months is", total_rainfall, "\n" f"The average rainfall a month is {average:}" )
60f890e1dfb13d2bf8071374024ef673509c58b2
Hackman9912/PythonCourse
/Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Medium Stuff/Classes/Inheritance/Practice/Inheritance Exercises - 1.py
1,870
4.59375
5
""" 1. Employee and ProductionWorker Classes Write an Employee class that keeps data attributes for the following pieces of information: • Employee name • Employee number Next, write a class named ProductionWorker that is a subclass of the Employee class. The ProductionWorker class should keep data attributes for the following information: • Shift number (an integer, such as 1, 2, or 3) • Hourly pay rate The workday is divided into two shifts: day and night. The shift attribute will hold an integer value representing the shift that the employee works. The day shift is shift 1 and the night shift is shift 2. Write the appropriate accessor and mutator methods for each class. Once you have written the classes, write a program that creates an object of the ProductionWorker class and prompts the user to enter data for each of the object’s data attributes. Store the data in the object and then use the object’s accessor methods to retrieve it and display it on the screen. """ import worker def main(): shift1 = employees() shift2 = employees() shift3 = employees() displaystuff(shift1) displaystuff(shift2) displaystuff(shift3) def employees(): name = input('Enter the employees name: ') number = int(input('Enter the employee number: ')) shift = int(input('Enter the shift number for the employee, 1 - Days, 2 - Swings, 3 - Mids: ')) pay = float(input('Enter the hourly pay rate of the employee: ')) return worker.ProdWork(name, number, shift, pay) def displaystuff(thingy): print() print('Name: ', thingy.get_name()) print('Employee Number: ', thingy.get_number()) print('Employees Shift: ', thingy.get_shift()) print(f'Employees hourly pay rate ${thingy.get_pay()}') main()