blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
e8ef0c0fab744a9dfe4137167f09b2c15c7815aa
AlanMars/python-game4kids
/games/countNumber.py
737
4.125
4
from os import system from random import randint #this say function is the most important part of kids programming #it uses the built in OSX say command to convert text to speech def say(something): system('say "%s"' % something) welcome_input = "Hi, Baby, Please input a number you would like to count." print(welcome_input) say(welcome_input) Start_Number = 1 Max_Number = eval(input("Your Input? ")) bot_said = "OK. Let me start to count from 1 to %d" % Max_Number say(bot_said) not_solved = True while not_solved: bot_count = "%d" % Start_Number print(bot_count) say(bot_count) if Max_Number > Start_Number: Start_Number +=1 else: not_solved = False say("My Dear, I have done!")
11747cf3f41a1debe2666fc9dcf45749af4b65f5
zanmakes/mooc-progress
/Specializations/Introduction to Python and Java/Introduction to Python Programming/Week 3 and 4/TestCode4/name_slice.py
191
3.859375
4
name = 'Brandon Krakowsky' # get index of single space between first name and last name first_space = name.index(' ') # get substring of name using slice # first_name only print(name[0:first_space])
0711acaa7130a4a2ab6025d3f98cd4619ac29023
jfu-gatech/mbta
/util.py
668
3.78125
4
def breadth_first_search(graph, start, target): # breath first search that outputs the path taken # TODO: expand documentation with parameter details visited = [] queue = [] queue.append([start]) if start == target: return [start] while queue: path = queue.pop(0) last_node = path[-1] if last_node not in visited: visited.append(last_node) for neighbor in graph[last_node]: new_path = path[:] new_path.append(neighbor) queue.append(new_path) if neighbor == target: return new_path return []
57fa954ec9675755975d409af855d8988143f3c2
digipodium/sophomore_python_1230_oct_21
/keep_working.py
332
4.03125
4
# Write your code here :-) question = input('Are you tired? ') if question == 'yes': tired = True else: tired = False q2 = input('Are u sleepy? ') if q2 == 'yes': sleepy = True else: sleepy = False if not tired or not sleepy: print("Keep Working") else: print("Aaj ki din aapki chutti. Jao Ghar ja ke so")
54e6c4af8b3becbd1818c449e433bca26fe25383
carrda/hero-rpg
/hero_rpg.py
1,891
4.0625
4
#!/usr/bin/env python # In this simple RPG game, the hero fights the goblin. He has the options to: # 1. fight goblin # 2. do nothing - in which case the goblin will attack him anyway # 3. flee class Character: def __init__(self, health, power): self.health = health self.power = power self.name = 'Generic' def alive(self): if self.health > 0: return True else: return False def attack(self, enemy): enemy.health -= self.power print("{} does {} damage to the {}.".format(self.name, self.power, enemy.name)) if enemy.health <= 0: print("{} is dead.".format(enemy.name)) if self.health <= 0: print("{} is dead.".format(self.name)) def print_status(self): print("{} has {} health and {} power.".format(self.name, self.health, self.power)) class Hero(Character): def __init__ (self, health, power): super().__init__(health, power) self.name = "Hero" class Goblin(Character): def __init__ (self, health, power): super().__init__(health, power) self.name = "Goblin" def main(): hero1 = Hero(10,5) goblin1 = Goblin(6,2) while goblin1.alive() and hero1.alive(): hero1.print_status() goblin1.print_status() print() print("What do you want to do?") print("1. fight goblin") print("2. do nothing") print("3. flee") print("> ", end=' ') raw_input = input() if raw_input == "1": hero1.attack(goblin1) elif raw_input == "2": pass elif raw_input == "3": print("Goodbye.") break else: print("Invalid input {}".format(raw_input)) if goblin1.health > 0: goblin1.attack(hero1) main()
6377dbb805929edaded2f2c414f4d5e8f354ade0
muthuguna/python
/Sample1.py
3,527
3.9375
4
# Find greatest number of 3 given numbers A = 10 B = 11 C = 12 result = A if A >= B and A >= B: result = A elif B >= A and B >= C: result = B else: result = C print(result) # Fibonacci series count = 15 p1=1 p2=0 if count > 0: for i in range(count): p3=p1+p2 p1=p2 p2=p3 print(p2) #Find highest, lowest and average on series of input number count = 0 while(1): inputNumber = input("Enter number:") if(count == 0): highest = inputNumber lowest = inputNumber average = inputNumber if(inputNumber == 99): print("Exiting...") break if(inputNumber > highest): highest = inputNumber if(inputNumber < lowest): lowest = inputNumber count = count+1 if(count > 1): average = (((average * (count-1))+ inputNumber)/count) print('Highest :',highest) print('Lowest :',lowest) print('Average :',average) # slogan = "\"Strength is life\"\n\t -Swamy Vivekananda" # print(slogan) #Print pyramid string counttryName = "America" for i in range(0, len(counttryName)): print(counttryName[0:(i+1)]) # Find highest, lowest and average for the series of given number count = 0 while(1): inputNumber = input("Enter the number:") if(inputNumber == 99): print("Exiting.....") break else: if(count == 0): highestNum = inputNumber lowestNum = inputNumber average = inputNumber if(inputNumber > highestNum): highestNum = inputNumber if(inputNumber < lowestNum): lowestNum = inputNumber count = count+1 if(count > 1): count average = ((average*(count-1))+inputNumber)/count print(highestNum) print(lowestNum) print(average) #Append user input to the list students = [] while(1): inputStudent = input("Enter the student :") if(inputStudent == "Done"): print("Exiting...") break else: students.append(inputStudent) students.insert(0, "Mr") #print(students.pop()) del students[0:1] students.sort(key=None, reverse=False) for name in students: print(name) maxArraySize = 7 students = [] while(1): addItem = input("Enter item to add :") if(addItem == "Done"): print("Exiting...") break if(len(students) > maxArraySize): print(students) removeItem = input("Enter item to remove from the above list:") students.remove(removeItem) else: students.append(addItem) print(students) # Find series of input number odd or even numList = [1,2,3,4,5,6,7] for x in numList: if(x%2 == 0): print("Even :",x) else: print("Odd :",x) # Find prime number from series of input numbers numList = [1,2,3,4,5,6,7,8,9,10,17,19,34] for x in numList: if x>1: flag = 1 for y in range(2,x): if(x%y == 0): flag = 0 break if(flag == 1): print(x) # Add key value pair to dictionary myDictionary = {"Muthu":["Honda","Toyota"], "Divesh":"Nissan", "Kumar": ["Ford", "Honda"]} for name in myDictionary.keys(): print(name, myDictionary[name]) while(1): addKey = input("Enter key to add :") if(addKey == "Done"): print("Exiting...") break addValue = input("Enter value to add :") myDictionary[addKey]=addValue print(myDictionary)
6b484119535ee7268a87b2855d876cbedb697662
yw-fang/readingnotes
/machine-learning/Matthes-crash-course/chapt09/scripts/user_03.py
1,243
4
4
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'Yue-Wen FANG' __maintainer__ = "Yue-Wen FANG" __email__ = 'fyuewen@gmail.com' __license__ = 'Apache License 2.0' __creation_date__= 'Dec. 28, 2018' """ 9-3. Users: Make a class called User . Create two attributes called first_name and last_name, and then create several other attributes that are typically stored in a user profile . Make a method called describe_user() that prints a summary of the user’s information . Make another method called greet_user() that prints a personalized greeting to the user . Create several instances representing different users, and call both methods for each user .t mv dog.py """ class User: """ a class for User """ def __init__(self, first_name, last_name, gender, age, email='f@cn'): self.name = first_name + last_name self.gender = gender self.age = age self.email = email # if no email is specified, the default will be used def describe_use(self): print('The profile of ' + self.name + ":") print('Gender: ', self.gender) print('Age: ', self.age) print('Email: ', self.email) Tiantian_Li = User('Tiantian', 'Li', 'Male', '20', email='Li@cn') Tiantian_Li.describe_use()
20fe4c6b360c3f782dcbbe31fda1f8f4597fce62
ECE492G9W18/ServoControllerV2
/test_servo_controller.py
377
3.515625
4
import unittest import aiming_controller class TestServoController(unittest.TestCase): ''' for block 3 | 5 | 7 1 | 4 | 9 6 | 2 | 8 it should return (4,8,1,5,2,7,3,9,6) ''' def test_map_numbers(self): a = aiming_controller.AimingController() self.assertEqual(a.map_numbers("357149628"), [4,8,1,5,2,7,3,9,6]) if __name__ == "__main__": unittest.main()
066c4b4b1b48f337665509d93eab5b887718272e
zenubis/LeetCodeAnswers
/04-Daily/20210126/20210126.py
2,725
4.09375
4
# https://leetcode.com/explore/challenge/card/january-leetcoding-challenge-2021/582/week-4-january-22nd-january-28th/3617/ # You are a hiker preparing for an upcoming hike. You are given heights, a 2D array of size rows x columns, # where heights[row][col] represents the height of cell (row, col). You are situated in the top-left cell, (0, 0), # and you hope to travel to the bottom-right cell, (rows-1, columns-1) (i.e., 0-indexed). You can move up, # down, left, or right, and you wish to find a route that requires the minimum effort. # A route's effort is the maximum absolute difference in heights between two consecutive cells of the route. # Return the minimum effort required to travel from the top-left cell to the bottom-right cell. # Example 1: # Input: heights = [[1,2,2],[3,8,2],[5,3,5]] # Output: 2 # Explanation: The route of [1,3,5,3,5] has a maximum absolute difference of 2 in consecutive cells. # This is better than the route of [1,2,2,2,5], where the maximum absolute difference is 3. # Example 2: # Input: heights = [[1,2,3],[3,8,4],[5,3,5]] # Output: 1 # Explanation: The route of [1,2,3,4,5] has a maximum absolute difference of 1 in consecutive cells, which is better than route [1,3,5,3,5]. # Example 3: # Input: heights = [[1,2,1,1,1],[1,2,1,2,1],[1,2,1,2,1],[1,2,1,2,1],[1,1,1,2,1]] # Output: 0 # Explanation: This route does not require any effort. # Constraints: # rows == heights.length # columns == heights[i].length # 1 <= rows, columns <= 100 # 1 <= heights[i][j] <= 106 import heapq class Node: height = 0 x = 0 y = 0 def __init__(self, height, x, y): self.height = height self.x = x self.y = y def __eq__(self, rhs): return self.x == rhs.x and self.y == rhs.y and self.height == rhs.height def __lt__(self, rhs): return self.height < rhs.height class Solution: def minimumEffortPath(self, heights: list[list[int]]) -> int: explored = [] # since we always starts at (0, 0), we can always start the list with (0, 1) and (1, 0) candidates = [Node(heights[0][1], 0, 1), Node(heights[1][0], 1, 0)] heapq.heapify(candidates) lowest = 0 #lowest path def checkAnswer(s:Solution, heights: list[list[int]], ans:int): output = s.minimumEffortPath(heights) if output != ans: print("Wrong answer") print("output:", output) print("answer:", ans) assert(False) if __name__ == "__main__": s = Solution() checkAnswer(s, [[1,2,2],[3,8,2],[5,3,5]], 2) checkAnswer(s, [[1,2,3],[3,8,4],[5,3,5]], 1) checkAnswer(s, [[1,2,1,1,1],[1,2,1,2,1],[1,2,1,2,1],[1,2,1,2,1],[1,1,1,2,1]], 0)
9f12da4ea604994585ece4717b2e406e1c2be2e8
fredtavares2018/ads_ead
/Linguagem - Python/funcoes.py
381
3.578125
4
def precoRoupa(): valor = 3100 if valor <= 1830.29: #comparacao valor -= valor * 0.08 # 1000 - 1000 x 8% = 920 elif valor <= 3050.52: valor -= valor * 0.09 # 2000 - 2000 x 9% = 1820 elif valor <= 6101.06: valor -= valor * 0.11 print(valor) precoRoupa() # valor - desconto = valor com desconto
573db08aa7b049616e2bec4785e8fb1f71d5d357
ttnyoung/fastcampus_python_advanced
/myvenv/Chapter02/03.리스트다루기.py
375
3.71875
4
# 리스트 메서드 # 리스트 데이터 삭제 fruits = ['apple', 'orange', 'mango'] del fruits[1] print(fruits) # 리스트 정렬 numbers = [5, 1, 2, 8, 3] numbers.sort() print(numbers) # enumerate titles = ['출석!!', '출석인증합니다!', '출석이요!!'] for index, title in enumerate(titles, 1): print(f'{index} 번째 글입니다. 제목 : {title}')
a649525110a294882c99fa5366d7e196a880904a
aguscoppe/ejercicios-python
/TP_5_Funciones/TP5_EJ5.py
208
3.8125
4
# EJERCICIO 5 def devolverMaximo(a, b): if a > b: return a else: return b a = int(input("Ingrese un número: ")) b = int(input("Ingrese otro número: ")) print(devolverMaximo(a, b))
aabc7012d401bdd7445cf8c83e1f26e4b0a7c901
mazor/Codelity-Exercises
/mininteger.py
1,893
3.640625
4
""" This is a demo task. Write a function: def solution(A) that, given an array A of N integers, returns the smallest positive integer (greater than 0) that does not occur in A. For example, given A = [1, 3, 6, 4, 1, 2], the function should return 5. Given A = [1, 2, 3], the function should return 4. Given A = [−1, −3], the function should return 1. Write an efficient algorithm for the following assumptions: N is an integer within the range [1..100,000]; each element of array A is an integer within the range [−1,000,000..1,000,000]. """ # you can write to stdout for debugging purposes, e.g. # print("this is a debug message") def solutionTimeconsuming(A): # write your code in Python 3.6 mini = min(A) maxi = max(A) toReturn = 0 if mini >1: return mini-1 else: if mini<0: mini = 1 if maxi<0: return 1 rangi = range(mini,maxi+1) for x in rangi: if x in A: continue else: return x return maxi+1 def solutionAttempt2(A): #77%, some wrong answers # write your code in Python 3.6 maxi = max(A)+1 if maxi<1: return 1 mini = min(A) if mini >1: return mini-1 hasN = [False]*maxi hasN[0]=True for x in A: if x > 0: hasN[x]=True j = 0 # print(hasN) for y in hasN: if y == False: break j+=1 return j def solution(A): #perfect 100% # write your code in Python 3.6 maxi = max(A)+1 if maxi<=1: return 1 mini = min(A) if mini >1: return 1 hasN = [False]*maxi hasN[0]=True for x in A: if x > 0: hasN[x]=True j = 0 for y in hasN: if y == False: break j+=1 return j
3a26b2fbb9dfaffca1cb71e83476a38eba41dcb8
athenian-programming/thread-examples
/src/main/python/leds/non_threaded.py
671
3.5625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import argparse from leds.led import LED def main(): # Setup CLI args parser = argparse.ArgumentParser() parser.add_argument("-p", "--pause", default=0.25, type=float, help="Blink pause (secs) [0.25]") args = vars(parser.parse_args()) # Create LED objects leds = [LED(i) for i in range(8)] # Blink back and forth try: while True: for led in leds: led.blink(args["pause"]) for led in reversed(leds): led.blink(args["pause"]) except KeyboardInterrupt: print("Exiting...") if __name__ == "__main__": main()
b6fb6424e22cd457d26dd29238c8e38c1988a3ef
Capybarralt/PyTask
/leap_year.py
571
3.71875
4
year = int(input()) if (year % 4 != 0) or ((year % 100 == 0) and (year % 400 != 0)): print('no') else: print('yes') """ Попросить пользователя ввести с клавиатуры год. Если год високосный - вывести на экран "yes" Если год не високосный - вывести на экран "no" Год не является високосным в двух случаях: он кратен 100, но при этом не кратен 400 либо он не кратен 4 """
60986c5a717f31814eb3b7c5fa83d1cc98e5236d
niayz10/Web-Programming
/week8/Logic-1/5.py
198
3.734375
4
def sorta_sum(a, b): sum = a + b if sum >= 10 and sum <= 19: print("20") else: print(sum) sorta_sum(3, 4) # → 7 sorta_sum(9, 4) # → 20 sorta_sum(10, 11) # → 21
041e6180cf3452d934b22127992d777f7733947f
daniel-reich/ubiquitous-fiesta
/GWBvmSJdciGAksuwS_19.py
87
3.53125
4
def find_letters(word): lst = [l for l in word if word.count(l) <= 1] return lst
ee7ead67f82a2837ce3ac7041bb3942ba1b36380
Hammad-Ishaque/pydata-practise
/turing/problems.py
2,542
3.515625
4
# Find first duplicate from array # First occurence of any element return this element import sys def first_duplicate(arr): duplicate_map = {} for i, v in enumerate(arr): if v in duplicate_map: return v duplicate_map[v] = 1 return -1 def first_duplicate_without_space(arr): for i in range(0, len(arr)): if arr[abs(arr[i]) - 1] < 0: return abs(arr[i]) else: arr[abs(arr[i]) - 1] = arr[abs(arr[i]) - 1] * -1 def print_triangle(n): for i in range(n): print('*' * (i + 1)) def first_non_repeating_character(word): character_mappper = {} first_index = len(word) for i, v in enumerate(word): if v not in character_mappper: first_index = i character_mappper[v] = 1 else: character_mappper[v] += 1 print(character_mappper) print(first_index) for k, v in character_mappper.items(): if v == 1: return k return '_' def fnr_without_map(word): char_counts = [0 for i in range(26)] for i, v in enumerate(word): char_counts[ord(v) - ord('a')] += 1 for j, v in enumerate(word): if char_counts[ord(v) - ord('a')] == 1: return v return '_' def max_profit(prices): min = sys.maxsize profit = 0 for i, v in enumerate(prices): if v > min: profit = max(profit, v - min) else: min = v return profit def get_product_except_self(arr): product = 1 for i in arr: product *= i print(product) output = [product // i for i in arr] print(output) def get_product_except_self_without_div(arr): product = 1 left_product = [1 for i in range(len(arr))] right_product = [1 for i in range(len(arr))] output = [] for j in range(1, len(arr)): left_product[j] = arr[j-1] * left_product[j-1] for i in range(len(arr)-2, -1, -1): right_product[i] = arr[i+1] * right_product[i+1] for i in range(0, len(arr)): output.append(left_product[i]*right_product[i]) print(output) # arr = [1, 2, 1, 2, 3, 3] # arr = [2, 1, 3, 5, 3, 2] # arr = [1, 2, 3, 4, 5, 6] # print(first_duplicate(arr)) # print(first_duplicate_without_space(arr)) # print_triangle(5) # str = "aaaacccceee" # print(first_non_repeating_character(str)) # print(fnr_without_map(str)) # prices = [1, 2, 3, 4, 5] # print(max_profit(prices)) arr = [1, 2, 3, 4] # get_product_except_self(arr) get_product_except_self_without_div(arr)
4815f53f2e3d2d4fa7d1400e7311115f54260e17
Zylphrex/csc420-project
/geometry/point.py
683
3.8125
4
import math class Point(object): def __init__(self, x, y): self.x = x self.y = y @property def raw(self): return (self.x, self.y) def copy(self): return Point(self.x, self.y) def __mul__(self, n): return Point(self.x * n, self.y * n) def __rmul__(self, n): return self.__mul__(n) def __repr__(self): return '({}, {})'.format(self.x, self.y) def euclidean(point1, point2): dx = point1.x - point2.x dy = point1.y - point2.y return math.sqrt(dx * dx + dy * dy) def manhattan(point1, point2): dx = point1.x - point2.x dy = point1.y - point2.y return abs(dx) + abs(dy)
ba5a62f6f8952adf9d19bf0987f4108faafb8145
Pjamas180/MiscPython
/PA6/vector.py
6,411
4.21875
4
from misc import Failure class Vector(object): """Vector class which creates a vector with a given size or argument list.""" def __init__(self, length): """Constructor for a Vector Object. If the argument is a single int or long, then return a vector with length of argument. if the argument is a sequence, then create a Vector with the same argument list.""" if isinstance(length,(int,long)): # Length is an int or long if length < 0: # return an exception ValueException raise ValueError("Vector length cannot be negative") else: self.length = length self.vector = [0.0 for item in range(length)] elif isinstance(length,(list,str,unicode,tuple,buffer,xrange)): # Length is a sequence self.length = len(length) self.vector = [x for x in length] else: raise TypeError("Vector length is not a valid type: Must be a positive int, long, or sequence") def __repr__(self): """Returns a string representation of the Vector""" vectRep = "" if self.length != 0: if isinstance(self.vector[0],str): vectRep = vectRep + "'" + self.vector[0] + "'" else: vectRep = vectRep + str(self.vector[0]) for x in range(1,len(self.vector)): if isinstance(self.vector[x],str): vectRep = vectRep + ", " + "'" + self.vector[x] + "'" else: vectRep = vectRep + ", " + str(self.vector[x]) return "Vector([" + vectRep + "])" def __len__(self): """Returns the length of the vector""" return self.length def __iter__(self): """Returns an object that can iterate over the elements of Vector.""" curPos = 0 while True: if curPos is self.length: raise StopIteration yield self.vector[curPos] curPos+=1 def __add__(self,b): """Allows for addition of equal length lists or Vectors""" newList = list(b) newVector = self.length for i in range(self.length): newVector = [self.vector[i] + newList[i] for i in range(self.length)] return Vector(newVector) def __radd__(self,b): """Reverse add which is called when the original add cannot compute.""" newList = list(b) newVector = self.length for i in range(self.length): newVector = [self.vector[i] + newList[i] for i in range(self.length)] return Vector(newVector) def dot(self,b): """Computes the dot product of the Vector""" dotProduct = 0 # Checking to see if passed value is a Vector if isinstance(b,Vector): for i in range(len(self.vector)): dotProduct+=self.vector[i]*b.vector[i] elif isinstance(b,list): for i in range(len(self.vector)): dotProduct+=self.vector[i]*b[i] return dotProduct def __getitem__(self,i): """Gets the ith element of a Vector""" # Checking to see if passed in value is a slice if isinstance(i,slice): return Vector([x for x in self.vector[i]]) else: if i <= self.length: if i < 0: return self.vector[self.length + 1] else: return self.vector[i] # Return IndexError raise IndexError("Vector index out of range") def __setitem__(self,i,val): """Sets the ith element of a Vector""" # Checking to see if passed in value is a slice if isinstance(i,slice): if len(val) is len(self.vector[i]): self.vector[i] = val return Vector(self.vector) else: # Raise a ValueError if the length of the slice modifies the length of the Vector raise ValueError("Cannot modify with argument - Vector length will be changed") else: if i <= self.length: if i < 0: self.vector[self.length + 1] = val else: self.vector[i] = val else: raise IndexError("Vector index out of range") def __lt__(a,b): """Operator for <""" return b.__gt__(a) def __le__(a,b): """Operator for <=""" return b.__ge__(a) def __eq__(a,b): """Operator for ==. Vectors are equal if each element in one vector is equal to the respective element in the other Vector.""" if isinstance(b,Vector): for i in range(len(a.vector)): if a.vector[i] != b.vector[i]: return False return True else: return False def __ne__(a,b): """Operator for !=. True when the value is not a Vector.""" if isinstance(b,Vector) is False: return True elif a.__eq__(b) is True: return False else: return True def __ge__(a,b): """Operator for >=. True if every pair of greatest values are equal.""" boolean = False if len(a.vector) is 0 and len(b.vector) is 0: return True else: if len(a.vector) is 0 or len(b.vector) is 0: return False else: if max(a.vector) > max(b.vector): return True elif max(a.vector) == max(b.vector): a.vector.remove(max(a.vector)) b.vector.remove(max(b.vector)) boolean = a.__ge__(b) return boolean def __gt__(a,b): """Operator for >. True if the greatest value of the first Vector is greater than the greatest value of second Vector.""" boolean = False if len(a.vector) > 0: if len(b.vector) is 0: return True elif max(a.vector) > max(b.vector): return True elif max(a.vector) == max(b.vector): # Check for next highest values a.vector.remove(max(a.vector)) b.vector.remove(max(b.vector)) boolean = a.__gt__(b) return boolean pass
15b9d1dbcb315512ae64d8dab6aed4ddde750fe1
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/Shweta/Lesson03/list_lab.py
2,384
4.40625
4
#!/usr/bin/env python3 #Series 1 #Create and do modifications on list #including pop, append, +,insert # print("--------Series 1 started--------") fruit_list=["Apples","Pears","Oranges","Peaches"] print("The fruits mentioned in fruit list are:", fruit_list) new_fruit=input("Name the new fruit want to add in list : ") fruit_list.append(new_fruit.title()) print("The fruits list is: ",fruit_list) print() fruit_num=int(input("Provide the number to see fruit from the list on that number ")) print(fruit_list[fruit_num-1]) print() new_flist=input("Provide new fruit name for beginning of the list using '+' ") new_flist=[new_flist.title()] fruit_list=new_flist+fruit_list print("The new list is : ", fruit_list) print() new_ilist=input("Name the new fruits name to add in beginning using insert ") fruit_list.insert(0,new_ilist.title()) print("The new list is :", fruit_list) print print("Fruits with names starting with P are: ") for item in fruit_list: if item[0]=="P": print(item,end=" ") print() # #Series 2 #Modify first series fruits list # print() print("--------Series 2 started--------") print("The final list from first series is:",fruit_list) print(fruit_list.pop()) print("List after removing last fruit from list:",fruit_list) dfruit=input("Name the fruit want to delete: ") for item in fruit_list: if item == dfruit.title(): fruit_list.remove(item) print("Final list after deleting "+ dfruit.title()+ " is",fruit_list) break else: print(dfruit.title(), "can not be deleted as it's not in list") # # #series 3 #deleting values from using while loop # print() print("--------Series 3 started--------") i=0 f_list=fruit_list[:] length=(len(fruit_list)) while i < length: resp=input("Do you like " + f_list[i].lower()+"?") if resp == "no": fruit_list.remove(f_list[i]) i=i+1 elif resp == "yes": i=i+1 else: print("Please enter yes or no") print(fruit_list) # # #Series 4 #copying and removing the items from list along with reversing the list values # print() print("--------Series 4 started--------") reverse_list=[] for item in fruit_list: reverse_list.append(item[::-1]) print(reverse_list) copy_list=fruit_list print("Fruit removed form list using pop method is:",fruit_list.pop()) print("Original List is:", fruit_list) print("Copied List is :", copy_list)
c7324fa21d37f4a95ce91f3b643d268c0ce9d4d0
ajaysahu3964/pythonasminiprograms
/squareroot.py
159
4.03125
4
def square(num): #num=int(input("enter a number:")) square_root=num**0.5 return"square root of",num,"is",round(square_root) print(square(81))
3a88e5e3c37a9d0728b1627090aabff407409c41
SYN2002/PYTHON-LAB
/d2_Assignment_11_b.py
329
3.625
4
n1=int(input("Enter the lower range(greater than 0): ")) n2=int(input("Enter the upper range: ")) i=n1 if n1>0: print("Perfect numbers are:",end=" ") while i<n2: j,s=1,0 while j<i: if(i%j==0): s=s+j j=j+1 if(s==i): print(i,end=" ") i=i+1
9deca1b67574763d7af287f9975a6a38784714fc
mohira/oop-iroha-python
/class_03.py
857
4.125
4
""" https://qiita.com/nrslib/items/73bf176147192c402049#class 変数で抽象化 """ from typing import List WRITE_TYPE_CONSOLE = "console" WRITE_TYPE_FILE = "file" def write(write_type: str, data: List[str]) -> None: if write_type == WRITE_TYPE_CONSOLE: write_console(data) elif write_type == WRITE_TYPE_FILE: write_file(data) else: raise ValueError(f"write_type: {write_type} is invalid argument.") def write_console(data: List[str]) -> None: print("Data: ") for element in data: print(f"- {element}") def write_file(data: List[str]) -> None: text = ",".join(data) with open("output.txt", "w") as f: print(text, file=f) if __name__ == "__main__": data = ["Bob", "Tom", "Ken"] write("console", data) write("file", data) # write("CONSOLE", data) # ValueError
ac39edb41c9687a46b68fd2d07226fe60a18d298
Messi-ops509/mofan_pytorch
/2.py
754
3.5625
4
# 有关variable # 张量与变量,目前版本一致了, import torch from torch.autograd import Variable #定义一个张量数据, 中括号加中括号,外面还有一个大括号 将张量变为变量形式 requires_grad = True与反向传播有关 tensor = torch.FloatTensor([[1,2],[3,4]]) variable = Variable(tensor,requires_grad = True) print(tensor) print(variable) # v=x*x t_out = torch.mean(tensor*tensor) v_out = torch.mean(variable*variable) print(t_out) print(v_out) #反向传播 X(variable)相当于参数w,然后(grad)求导,求梯度 v_out.backward() print(variable.grad) #打印变量,打印张量,打印numpy数据 print(variable) print(variable.data) print(variable.data.numpy())
f7242d3195488125b68a48c69ef5cb7aad20b1ec
randomman552/Sudoku
/sudoku.py
23,643
3.578125
4
#!/usr/bin/python3.7 import pygame import random import time from tkinter import messagebox as ms_box from tkinter import font as tkFont import tkinter as tk import threading import json import sys import time from solver import Solver import generator from typing import Optional, Tuple, List class DifficultyChooser(object): """ GUI to choose a difficulty. Init parameters: difficulty (str) - The default difficulty to use. Should be "easy", "medium" or "hard". How to use: After instanciating the class, call the .open method to display the interface. It will return the difficutly string. """ def __init__(self, difficulty: str): self.window = tk.Tk() self.window.title("Sudoku") # Attach the exit command to the WM_DELETE_WINDOW event (causes program to close correctly) self.window.protocol("WM_DELETE_WINDOW", self.exit) # Difficulty StringVar to store the result of the radio buttons self.difficulty = tk.StringVar(self.window, difficulty, "difficulty") # Create title label for the menu title_font = tkFont.Font(self.window, ("sans", 20), underline=True) title_font.configure(underline=True) title = tk.Label(self.window, text="Sudoku", font=title_font) title.grid(column=0, row=0, columnspan=2, rowspan=2, padx=5, pady=2) std_font = tkFont.Font(self.window, ("sans", 10)) # Create our option radio buttons options = ["easy", "medium", "hard"] for i in range(len(options)): button = tk.Radiobutton(self.window, text=options[i].capitalize(), value=options[i], variable=self.difficulty, font=std_font ) button.grid(column=0, row=i + 2, columnspan=2, padx=100, pady=2, sticky=tk.W) # Create the exit and start buttons exit_button = tk.Button(self.window, command=self.exit, text="Exit", width=10, font=std_font ) exit_button.grid(column=0, row=5, sticky=tk.E) start_button = tk.Button(self.window, command=self.close, text="Start", width=10, font=std_font ) start_button.grid(column=1, row=5, sticky=tk.W) # Prevent the window from being resized self.window.resizable(False, False) def open(self) -> str: """Open the difficulty menu""" self.window.mainloop() return self.difficulty.get() def close(self) -> str: """ Close the difficulty window. Returns the difficutly string. """ self.window.destroy() self.window.quit() return self.difficulty.get() def exit(self): """Close the program""" sys.exit(0) class Game(object): """ Class to represent the game. Init parameters: difficulty (str) - A string to set the difficutly (must be "easy", "medium", or "hard). tile_sze (int) - The size of each tile. How to use: After initalising, call the .open method to open the game window. """ def __init__(self, difficulty: str, tile_size: Optional[int] = 60): # Pygame setup pygame.init() pygame.font.init() self.difficulty = difficulty # Window setup self.__windowSize = (tile_size * 9, tile_size * 9 + 50) self.__window = pygame.display.set_mode(self.__windowSize) pygame.display.set_caption("Sudoku") self.__font = pygame.font.Font("freesansbold.ttf", tile_size // 2) # Tile setup self.__tile_size = tile_size self.__active_tile = [0, 0] # Threading lock self.__lock = threading.Lock() # Message display attributes self.__display_message = "" self.__message_queue = [] self.__message_duration = 0 # Help function def __display_help(): """Function to display help information on screen.""" self.__display_message = "" self.__message_duration = 0 self.__message_queue = [] self.flash_messages(["Arrow keys, or mouse to change tile", "Press enter to self solve", "Press r to reset the board", "Press a number to fill the current tile"], [4000, 4000, 4000, 4000]) # TODO: Is there a way to improve these key bindings? self.__key_bindings = { pygame.KMOD_LSHIFT: { pygame.K_TAB: lambda: self.__move_active([0, -1]) }, pygame.KMOD_RSHIFT: { pygame.K_TAB: lambda: self.__move_active([0, -1]) }, pygame.KMOD_NUM + pygame.KMOD_LSHIFT: { pygame.K_TAB: lambda: self.__move_active([0, -1]) }, pygame.KMOD_NUM + pygame.KMOD_RSHIFT: { pygame.K_TAB: lambda: self.__move_active([0, -1]) }, pygame.KMOD_NUM: { pygame.K_KP0: lambda: self.__set_active(0), pygame.K_KP1: lambda: self.__set_active(1), pygame.K_KP2: lambda: self.__set_active(2), pygame.K_KP3: lambda: self.__set_active(3), pygame.K_KP4: lambda: self.__set_active(4), pygame.K_KP5: lambda: self.__set_active(5), pygame.K_KP6: lambda: self.__set_active(6), pygame.K_KP7: lambda: self.__set_active(7), pygame.K_KP8: lambda: self.__set_active(8), pygame.K_KP9: lambda: self.__set_active(9) }, pygame.KMOD_NONE: { pygame.K_UP: lambda: self.__move_active([-1, 0]), pygame.K_DOWN: lambda: self.__move_active([1, 0]), pygame.K_LEFT: lambda: self.__move_active([0, -1]), pygame.K_RIGHT: lambda: self.__move_active([0, 1]), pygame.K_w: lambda: self.__move_active([-1, 0]), pygame.K_s: lambda: self.__move_active([1, 0]), pygame.K_a: lambda: self.__move_active([0, -1]), pygame.K_d: lambda: self.__move_active([0, 1]), pygame.K_TAB: lambda: self.__move_active([0, 1]), pygame.K_BACKSPACE: lambda: self.__set_active(0), pygame.K_DELETE: lambda: self.__set_active(0), pygame.K_0: lambda: self.__set_active(0), pygame.K_1: lambda: self.__set_active(1), pygame.K_2: lambda: self.__set_active(2), pygame.K_3: lambda: self.__set_active(3), pygame.K_4: lambda: self.__set_active(4), pygame.K_5: lambda: self.__set_active(5), pygame.K_6: lambda: self.__set_active(6), pygame.K_7: lambda: self.__set_active(7), pygame.K_8: lambda: self.__set_active(8), pygame.K_9: lambda: self.__set_active(9), pygame.K_ESCAPE: lambda: self.close(), pygame.K_r: lambda: self.__reset(), pygame.K_RETURN: lambda: self.solve(), pygame.K_F1: lambda: __display_help(), }, } # Attribute for storing worker thread self.worker_thread = None # Set window color attributes self.__background_color = (128, 128, 128) self.__boundary_color = (0, 0, 0) # Set tile color attributes self.__tile_color = (255, 255, 255) self.__active_color = (255, 0, 0) self.__locked_color = (0, 0, 255) # Load puzzles into memory self.__puzzles = generator.load_boards() # Call reset method self.__reset() # Private methods def __draw(self): """Draw everything on the window.""" # Define draw subfunctions. def draw_boundaries(): """Draw the boundaries between the tileGroups.""" # Draw boundaries along the board for x in range(self.__tile_size * 3, self.__tile_size * 9 - 1, self.__tile_size * 3): pygame.draw.rect(self.__window, self.__boundary_color, (x-2, 0, 4, self.__windowSize[1] - 50)) # Draw boundaries down the board for y in range(self.__tile_size * 3, self.__tile_size * 9 - 1, self.__tile_size * 3): pygame.draw.rect(self.__window, self.__boundary_color, (0, y - 2, self.__windowSize[0], 4)) def draw_tiles(): """Draw the tiles on the screen.""" # For each coordinate on the board for x in range(0, 9): for y in range(0, 9): # Assign varaibles for this tile # X and y are flipped here so that the tiles are drawn correctly. tile_size = self.__tile_size - 2 tile_position = [y * self.__tile_size + 1, x * self.__tile_size + 1] tile_color = self.__tile_color tile_value = self.__board[x][y] # If this tile is active, draw a red boundary around it. if [x, y] == self.__active_tile: if self.__base_board[x][y] == 0: active_tile_color = self.__active_color else: active_tile_color = self.__locked_color pygame.draw.rect(self.__window, active_tile_color, (tile_position[0], tile_position[1], tile_size, tile_size)) pygame.draw.rect(self.__window, tile_color, ( tile_position[0] + 2, tile_position[1] + 2, tile_size - 4, tile_size - 4)) else: pygame.draw.rect( self.__window, tile_color, (tile_position[0], tile_position[1], tile_size, tile_size)) # If the tile value is not 0, draw text on the tile if tile_value != 0: # Generate an inverted color of the text based on the tile color text_color = ( 255 - tile_color[0], 255 - tile_color[1], 255 - tile_color[1]) # Create text object and draw it on the screen text = self.__font.render( str(tile_value), True, text_color, tile_color) text_rect = text.get_rect() text_rect.center = ( tile_position[0] + (tile_size // 2), tile_position[1] + (tile_size // 2)) self.__window.blit(text, text_rect) def draw_message(): """Draw the current display message on the screen.""" # Check whether a new message needs to be displayed if len(self.__message_queue) > 0 and self.__message_duration <= 0: # Remove the message from the queue and add it to active variables message = self.__message_queue.pop(0) self.__message_duration = message[0] self.__display_message = message[1] # Display the message if its duration is greater than 0 if self.__message_duration > 0: self.__message_duration -= 10 text_color = ( 255 - self.__tile_color[0], 255 - self.__tile_color[1], 255 - self.__tile_color[2]) text = self.__font.render( self.__display_message, True, text_color, self.__tile_color) text_rect = text.get_rect() text_rect.center = ( self.__windowSize[0] // 2, self.__windowSize[1] // 2) self.__window.blit(text, text_rect) def draw_time(): text = "Time(s): " if self.end_time: text += f"{round(self.end_time - self.start_time, 2)}" else: text += f"{round(time.time() - self.start_time, 2)}" # Draw a boundary at the end of the board, for the time panel pygame.draw.rect(self.__window, self.__boundary_color, (0, self.__tile_size * 9, self.__windowSize[0], 2)) pygame.draw.rect(self.__window, self.__tile_color, (0, self.__tile_size * 9 + 1, self.__windowSize[0], 50)) text = self.__font.render(text, True, (0, 0, 0)) self.__window.blit(text, (12.5, self.__tile_size * 9 + 12.5)) # Call functions self.__window.fill(self.__background_color) draw_boundaries() draw_tiles() draw_message() draw_time() pygame.display.update() def __mouseHandler(self): """Handle mouse actions.""" mouse_preses = pygame.mouse.get_pressed() pos = pygame.mouse.get_pos() # Positions are reveresed here due to the way the tiles are drawn on screen tile_x = pos[1] // self.__tile_size tile_y = pos[0] // self.__tile_size if mouse_preses[0]: self.__move_active([tile_x, tile_y], absolute=True) def __move_active(self, vector: Tuple[int, int], absolute: Optional[bool] = False): """ Moves the active tile by the given vector when absolute is false.\n Moves the active tile TO the given vector when absolute is true. """ if absolute: self.__active_tile = vector[:] else: new_active = [self.__active_tile[0] + vector[0], self.__active_tile[1] + vector[1]] # If the current active tile is off the left or right of the screen, wrap back to the other side. if new_active[0] == 9: new_active = [0, new_active[1] + 1] elif new_active[0] == -1: new_active = [8, new_active[1] - 1] # If the new_active is within the acceptable bounds, update the current active tile. if new_active[0] < 9 and new_active[1] < 9 and new_active[0] >= 0 and new_active[1] >= 0: self.__active_tile = new_active def __set_active(self, value: int): """Will set the active tile to the passed value, if it passes the __is_valid method.""" if self.__is_valid(self.__active_tile, value): self.__board[self.__active_tile[0]][self.__active_tile[1]] = value def __is_valid(self, pos: Tuple[int, int], value: int): """Validates the current board setup.""" # Check whether the specified tile is writable. if self.__base_board[pos[0]][pos[1]] != 0: return False # Check all tiles in the same group, row, and collumn as the tile in the given position for x in range(9): for y in range(9): if value > 0: # If the tile being checked is in a position where it needs to be checked, and isnt the same as pos if (x // 3 == pos[0] // 3 and y // 3 == pos[1] // 3) or (x == pos[0] or y == pos[1]) and ([x, y] != pos): if self.__board[x][y] == value: return False return True def __keyHandler(self): """Handle key presses.""" key_states = pygame.key.get_pressed() mod_state = pygame.key.get_mods() # Go though the mods in the key_bindings dict. for mod in self.__key_bindings: # Check if a mod is active and process the associated dict (this uses bitwise & operator) # Keybindings that are under KMOD_NONE are always checked, regardless of the mod_state if mod_state == mod or mod == 0: for binds in self.__key_bindings[mod]: execute = True # If the bind in the dict is a tuple (has multiple rules), check all rules in the tuple. if isinstance(binds, tuple): # Check all keys for a bind rule. for bind in binds: if not(key_states[bind]): execute = False break else: if not(key_states[binds]): execute = False # If the key_state for all keys in a bind are true, execute the associated function. if execute: self.__key_bindings[mod][binds]() # Show the users change immedietly. self.__draw() # Wait for 100 ms to prevent registering the same keypress multiple times. pygame.time.delay(100) # Break to prevent different bindings using the same key(s) from triggering. break break def __load_puzzle(self, difficulty: str): """ Loads a random puzzle from the puzzles.json file genereated by the puzzle generator. The puzzle is blended and rotated, so even if the same puzzle is loaded, it should look different. """ # Copy one of the boards from the puzzles dictionary for the required difficulty to_copy = random.choice(list(self.__puzzles.keys())) board = self.__puzzles[to_copy][difficulty] self.__board = [] for row in board: self.__board.append(row.copy()) def blender(): """This mixes the columns and rows randomly in order to make the board look more random.""" def blend_rows(): # Iterate over each band of 3 rows for x in range(0, 9, 3): # Iterate over the 3 rows in the band. for row_num in range(x, x+3): # Select a random row from the band random_row = random.randint(x, x+2) # Switch the specified rows self.__board[row_num], self.__board[random_row] = self.__board[random_row], self.__board[row_num] def blend_columns(): # Iterate over each band of 3 columns for y in range(0, 9, 3): # Iterate over the 3 columns in the band. for column_num in range(y, y+3): # Select a random colu n from the band random_column = random.randint(y, y+2) # Switch the specified columns for row_num in range(0, 9): self.__board[row_num][column_num], self.__board[row_num][random_column] = self.__board[ row_num][random_column], self.__board[row_num][column_num] blend_rows() blend_columns() def rotate(): """Rotate the board a random multiple of 90 degrees.""" for _ in range(random.randint(0, 3)): # Rotate board by 90 degrees self.__board = [*zip(*self.__board[::-1])] # Convert tuples back into lists self.__board = [list(row) for row in self.__board] blender() rotate() self.__base_board = [] for row in self.__board: self.__base_board.append(row[:]) def __reset(self): """Reset the game to its default state.""" if self.worker_thread: self.worker_thread.stop() self.__load_puzzle(self.difficulty) self.worker_thread = None self.complete = False self.start_time = time.time() self.end_time = None def __check_win(self): """Checks whether the sudoku board has been completed.""" if self.complete: return False else: for row in self.__board: for num in row: # If none of the numbers are still 0, then the board has been been completed. if num == 0: return False self.complete = True self.end_time = time.time() return True # Public methods def flash_message(self, message: str, delay: int): """Add message to the message queue.""" message = (delay, message) self.__message_queue.append(message) def flash_messages(self, message_list: List[str], delay_list: List[int]): """Adds passed messages with given delays to the message queue.""" messages = zip(delay_list, message_list) self.__message_queue += messages def solve(self): """Start self-solving the current board""" def update_active(active_pos, board): """This function is used by the solver to update the active tile position, so that it is drawn on screen correctly.""" with self.__lock: self.__move_active(active_pos, True) # Start the solver thread if one is not already running if not self.worker_thread: s = Solver(self.__board, False, update_active) self.worker_thread = s # Reset start time so we are timing the worker thread self.start_time = time.time() self.worker_thread.start() def open(self): """Open game window, call .close method to close the window.""" self.__running = True mouseDown, keyDown = False, False self.flash_message("Press F1 for help.", 4000) while self.__running: # Event loop for event in pygame.event.get(): if event.type == pygame.QUIT: self.close() elif event.type == pygame.MOUSEBUTTONDOWN: mouseDown = True elif event.type == pygame.MOUSEBUTTONUP: mouseDown = False elif event.type == pygame.KEYDOWN: keyDown = True elif event.type == pygame.KEYUP: keyDown = False # If mouseDown or keyDown are true, call their respective functions. if mouseDown: self.__mouseHandler() if keyDown: self.__keyHandler() with self.__lock: self.__draw() if self.__check_win(): # Carry out win action self.flash_message( f"Complete, took {round(time.time() - self.start_time, 2)} seconds", 1000) # print("Time taken: " + str(end - strt)) # Delay of 10 ms to set framerate to 100fps pygame.time.delay(10) pygame.quit() def close(self): """Close the game window""" if self.worker_thread: self.worker_thread.stop() self.__running = False if __name__ == "__main__": difficulty = "easy" while True: difficulty_chooser = DifficultyChooser(difficulty) difficulty = difficulty_chooser.open() game = Game(difficulty) game.open()
dd865aa68e98fcdc3d26330ddf0743bdb5c34899
DmiFomin/HW4
/use_functions.py
1,290
4.15625
4
balance = 0.0 history = [] def incomes(balance_f): add_sum = float(input('Введите сумму для пополнения: ')) return balance_f + add_sum def expenses(balance_f, history_f): price = float(input('Введите сумму покупки: ')) if price > balance_f: print('У вас не хватает средств!') else: product = input('Что вы хотите купить? ') balance_f = balance_f - price history_f.append({'product': product, 'price': price}) return balance_f, history_f def view_history(history_f): print('Ваша история покупок:') for element in history: print(f'Товар: {element["product"]}; цена: {element["price"]}') while True: print('1. пополнение счета') print('2. покупка') print('3. история покупок') print('4. выход') choice = input('Выберите пункт меню: ') if choice == '1': balance = incomes(balance) elif choice == '2': balance, history = expenses(balance, history) elif choice == '3': view_history(history) elif choice == '4': break else: print('Неверный пункт меню')
5b908e3b54f751a8280305ca7b57b12903cf0f5e
Michael-Naguib/ProjectEuler
/16.py
693
4.125
4
''' Author: Michael Sherif Naguib Date: November 7, 2018 @: University of Tulsa Question #16: What is the sum of the digits of the number 2^1000? Example: 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. ''' if __name__=="__main__": #imports import math from functools import reduce #calculate p=1 for i in range(0,1000):#multiply 2 1000 times i.e 2^1000W p = p*2 #get the digits as a string sp = str(p) #iterate over the string converting each number to an integer in a list nums = list(map(lambda x: int(x),sp)) #sum the list sum_str = str(reduce(lambda x,y: x+y, nums)) #print print(sum_str)
9b403296e4dfdff4b6ac48def72e2847cf68adf7
natibaggi/faculdade-python
/Aula 25.09/continue.py
777
4.09375
4
executar = input("Você quer calcular? Sim(S) ou Não(N)"); while executar == "S": num1 = int(input("Digite o 1o número: ")); num2 = int(input("Digite o 2o número: ")); operador = input("Digite o operador: "); if operador == "+": resultado = num1 + num2; elif operador == "-": resultado = num1 - num2; elif operador == "*": resultado = num1 * num2; elif operador == "/": if num2 == 0: print("Divisão por zero!"); executar = input("Você quer calcular? Sim(S) ou Não(N)"); continue else: resultado = num1 / num2; print("%d %c %d = %d\n" % (num1, operador, num2, resultado)); executar = input("Você quer calcular? Sim(S) ou Não(N)");
47f53d1c6552f9f172a994415bb0a348c098f976
JRVSTechnologies/hackerrank_solutions
/easy/challanges/plusMinus.py
647
3.96875
4
#!/bin/python3 import math import os import random import re import sys # Complete the plusMinus function below. def plusMinus(arr): negative = 0 positive = 0 zero = 0 for i in arr: if(i < 0): negative += 1 elif(i > 0): positive += 1 elif(i == 0): zero += 1 print(calculateFraction(arr, positive)) print(calculateFraction(arr, negative)) print(calculateFraction(arr, zero)) def calculateFraction(arr, count): return str.format('{0:.6f}', round(count/len(arr), 6)) if __name__ == '__main__': arr = [1, 2, 3, -1, -2, -3, 0, 0] plusMinus(arr)
f6476beefdb4a0f875b7f3829188bffb5178f2c5
Maerig/advent_of_code_2017
/day19/main.py
1,667
3.5625
4
from utils.vector import Vector def read_input(): return [ line.rstrip() for line in open('input.txt') ] def get_segment(diagram, x, y): try: segment = diagram[y][x] except IndexError: return None if not segment.strip(): # Empty return None return segment def get_neighbours(diagram, x, y): return [ Vector(i, j) for i, j in [ (x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1) ] if get_segment(diagram, i, j) ] def get_next_pos(diagram, current, prev): segment = get_segment(diagram, *current) if segment == '|' or segment == '-': # Continue in the same direction return current + current - prev # Else continue to neighbour which isn't prev for neighbour in get_neighbours(diagram, *current): if neighbour != prev: return neighbour # Nowhere to go return None def navigate(diagram): x = diagram[0].index('|') current = Vector(x, 0) prev = Vector(x, -1) while current: yield current prev, current = current, get_next_pos(diagram, current, prev) def part_1(diagram): letters = [] for position in navigate(diagram): content = get_segment(diagram, *position) if content not in ('|', '-', '+'): letters.append(content) return ''.join(letters) def part_2(diagram): return len(list(navigate(diagram))) if __name__ == '__main__': diagram_input = read_input() print(f"Part 1: {part_1(diagram_input)}") print(f"Part 2: {part_2(diagram_input)}")
976e0820de9c1efb467fac170274544afe7848a8
ahg2656/KICCampus
/pysou/pro1/pack1/test05.py
1,929
3.9375
4
''' tuple : list 와 유사, 읽기 전용(수정 X), list 보다 검색속도가 빠름 ''' # t = 'a', 'b', 'c', 'd' t = ('a', 'b', 'c', 'd') print(t, len(t), t.count('a'), t.index('b')) print() p = (1,2,3) print(p) # p[0] = 10 # err : 'tuple' object does not support item assignment q = list(p) # 형변환 q[0] = 10 p = tuple(q) print(p) print("\n값 교환") t1 = 10, 20 a, b = t1 b, a = a, b t2 = a, b print(t2) print('***' * 10) ''' set : 순서 X, 중복 X ''' a = {1,2,3,1} print(a, ' ' , len(a)) # print(a[0]) # err : 'set' object does not support indexing b = {3, 4} print(a.union(b)) # 합집합 print(a.intersection(b)) # 교집합 print(a - b, a | b, a & b) # 차집합 / 합집합 / 교집합 b.add(5) # 추가 가능 b.update({5,6,7}) # set 추가 b.update([8,9]) # list 추가 b.update((10,11)) # tuple 추가 b.update((12,)) # b.update((12)) # err : tuple 은 요소가 하나일 경우 마지막에 , 추가해야함 print(b) b.discard(7) # 값에 의한 삭제 - 해당 값 없으면 통과 b.remove(8) # 값에 의한 삭제 - 해당 값 없으면 정지 b.discard(7) # b.remove(8) # err print(b) print() li = [1,2,3,1,4] print(li) s = set(li) # 중복제거 li = list(s) print(li) print('***' * 10) ''' dict(key : value) : 순서 X, json 데이터 처리 시 용이 ''' mydic = dict(k1=1, k2='abc', k3=5.6) print(mydic) dic = {'파이썬':'뱀','자바':'커피','스프링':'용수철'} print(dic) print(len(dic)) print(dic['자바']) # key 에 의한 검색 print(dic.get('자바')) # print(dic['커피']) # err : value 에 의한 검색 X # print(dic[0]) # err : 순서가 없기 때문에 dic['오라클'] = '예언자' print(dic) print('오라클' in dic) del dic["오라클"] # 삭제 print(dic) print(dic.keys()) # return : list (중복X) print(dic.values()) # return : list (중복O) dic.clear() # 전부 삭제 print(dic)
0cf3456fa826a3a98fa2434766b960518e61e542
sucpandu/CourseRegistration
/src/src/administratorCourseOp.py
8,327
3.53125
4
import sqlite3 import re import sys conn = sqlite3.connect('OpenOnlineCourse.db') curr = conn.cursor() def create_courses_table(): curr.execute( "CREATE TABLE IF NOT EXISTS courses(c_id INTEGER PRIMARY KEY, c_name TEXT, c_duration INTEGER, c_subject TEXT)") def add_course(): c_id = raw_input("Enter Course ID: ") while len(c_id) < 5 or not re.match('^[0-9]*$', c_id): c_id = raw_input('Please enter valid course ID: ') c_name = raw_input("Enter Course name: ") while not re.match('^[a-zA-Z_ ]*$', c_name) or len(c_name) < 1: c_name = raw_input('Please enter valid course Name: ') c_duration = raw_input("Enter Course duration (in hours): ") while not re.match('^[0-9]*$', c_duration) or len(c_duration) < 1: c_duration = raw_input('Please enter valid course duration in hours: ') c_subject = raw_input("Enter the subject name: ") while not re.match('^[a-zA-Z_ ]*$', c_subject) or len(c_subject) < 1: c_subject = raw_input('Please enter valid course subject: ') try: curr.execute("INSERT INTO courses VALUES(?,?,?,?)", (c_id, c_name, c_duration, c_subject)) conn.commit() print('New course added successfully') list_courses() except sqlite3.IntegrityError: print ('Error while adding course to database. Please make sure you have distinct course IDs. ') return def list_courses(): try: curr.execute("SELECT c_id ,c_name,c_duration, c_subject FROM courses") conn.commit() courses = curr.fetchall() print("\nThe courses available on list are: ") print(" ID - CourseName - CourseDuration (in Hours) - CourseSubject") for course in courses: print(str(course[0]), str(course[1]), str(course[2]), str(course[3])) avlCourseId = [i[0] for i in courses] except sqlite3.IntegrityError as e: print ('Error accessing the database. Cannot complete action. ') return def search_courses(c_search): c_search = raw_input("Enter a search keyword: ") try: curr.execute("CREATE VIRTUAL TABLE searchCourse USING courses(c_id ,c_name,c_duration, c_subject; SELECT * FROM searchCourse WHERE searchCourse MATCH c_search ") conn.commit() searchCourses = curr.fetchall() print (searchCourses) for course in searchCourses: print(str(course[0]), str(course[1]), str(course[2]), str(course[3])) except sqlite3.IntegrityError: print('Cannot find the search string in the database. Cannot complete action. ') return def validate_cid(cid): curr.execute('select c_id from courses where c_id=:c_id' , {"c_id": cid}) data = curr.fetchall() if len(data) == 0: return False return True def del_course(cid): try: if validate_cid: curr.execute("DELETE FROM courses WHERE c_id=:c_id", {"c_id": cid}) conn.commit() print('Course deleted succesfully') list_courses() else: print ('Course ID not valid or not found in the database. ') return except sqlite3.IntegrityError: print('Database error. Cannot complete action. ') return def edit_course(cid): try: curr.execute("SELECT * FROM courses WHERE c_id=:c_id", {"c_id": cid}) conn.commit() courseDetail = curr.fetchone() ocid = courseDetail[0] ocname = courseDetail[1] ocdur = courseDetail[2] ocsub = courseDetail[3] print('Old Course Name: ', ocname) ncname = raw_input('Enter New Course Name: ') if not re.match('^[a-zA-Z_ ]*$', ncname) or len(ncname) < 1: print ("Error! Course name is invalid or empty. Please try again with valid characters.") return print('Old Course duration (in hours): ', ocdur) ncdur = raw_input('Enter New Course duration (in hours): ') if not re.match('^[0-9]*$', ncdur) or len(ncdur) < 1: print ("Error! Course duration is invalid or empty. Please try again with valid integers. ") print('Old Course subject: ', ocsub) nsub = raw_input('Enter New Course subject: ') if not re.match('^[a-zA-Z_ ]*$', nsub) or len(nsub) < 1: print ("Error! Subject name is invalid or empty. Please try again with valid characters.") curr.execute( "UPDATE courses SET c_name = :c_name, c_duration = :c_duration, c_subject = :c_subject WHERE courses.c_id = :c_id", ({"c_name": ncname, "c_duration": ncdur, "c_subject": nsub, "c_id": ocid})) conn.commit() print('Course updated successfully') view_course_detail(ocid) except sqlite3.IntegrityError: print('Database error. Cannot complete action. ') return def view_course_detail(cid): try: curr.execute("SELECT courses.c_id, courses.c_name, courses.c_duration, courses.c_subject from courses where courses.c_id=:c_id", {"c_id": cid}) conn.commit() courseDetail = curr.fetchone() print('Course ID: ', courseDetail[0]) print('Course Name: ', courseDetail[1]) print('Course Duration (in Hours): ', courseDetail[2]) print('Course Subject: ', courseDetail[3]) except sqlite3.IntegrityError: print('Database error. Cannot complete action. ') return def main(): while True: print ("Please select an option: ") print('1: Add course to the super list') print('2: List all the courses') print ('3: Update a course') print ('4: Delete a course') print ('0: Exit') choice = raw_input('Enter: ') if choice == '1': create_courses_table() add_course() cont = raw_input('Would you like to continue? Y/ N') if cont == 'N' or cont == 'n': break elif cont == 'Y' or cont == 'y': continue else: while cont not in ['y', 'Y', 'n', 'N']: cont = raw_input('Please enter a valid choice: Y/ N') elif choice == '2': list_courses() cont = raw_input('Would you like to continue? Y/ N') if cont == 'N' or cont == 'n': break elif cont == 'Y' or cont == 'y': continue else: while cont not in ['y', 'Y', 'n', 'N']: cont = raw_input('Please enter a valid choice: Y/ N') elif choice == '3': cid = raw_input('Please enter the course ID you wish to update: ') if validate_cid(cid): edit_course(cid) cont = raw_input('Would you like to continue? Y/ N') if cont == 'N' or cont == 'n': break elif cont == 'Y' or cont == 'y': continue else: while cont not in ['y', 'Y', 'n', 'N']: cont = raw_input('Please enter a valid choice: Y/ N') else: print ('Not a valid course ID. Please try again.') elif choice == '4': cid = raw_input('Please enter the course ID you wish to delete: ') if validate_cid(cid): del_course(cid) cont = raw_input('Would you like to continue? Y/ N') if cont == 'N' or cont == 'n': break elif cont == 'Y' or cont == 'y': continue else: while cont not in ['y', 'Y', 'n', 'N']: cont = raw_input('Please enter a valid choice: Y/ N') else: print ('Not a valid course ID. Please try again.') elif choice == '0': return else: print('Invalid choice. Please try again. \n')
54066a07f45f51876dc00221eb738b0a469ea63a
prince-prakash/practice_session
/tree.py
276
3.703125
4
hieght = eval(input("Enter the height of tree: ")) row = 0 while row < hieght: count = 0 while count < hieght - row: print(end='') count += 1 count = 0 while count< 2* row + 1: print(end=" ") count += 1 print() row += 1
3c85195049c69a998c673a36bdf33c9392b57d37
imkrislu/Statistical-Machine-Translation
/code/BLEU_score.py
3,786
3.84375
4
import math def BLEU_score(candidate, references, n, brevity=False): """ Calculate the BLEU score given a candidate sentence (string) and a list of reference sentences (list of strings). n specifies the level to calculate. n=1 unigram n=2 bigram ... and so on DO NOT concatenate the measurments. N=2 means only bigram. Do not average/incorporate the uni-gram scores. INPUTS: sentence :(string) Candidate sentence. "SENTSTART i am hungry SENTEND" references:(list) List containing reference sentences. ["SENTSTART je suis faim SENTEND", "SENTSTART nous sommes faime SENTEND"] n :(int) one of 1,2,3. N-Gram level. OUTPUT: bleu_score :(float) The BLEU score """ #TODO: Implement by student. bleu_score = 0 score = 0 sentence = candidate.split() # print(len(sentence[1:1+n]) == n) denom = len(sentence) if not brevity: for i in range(len(sentence)-n+1): phrase = " ".join(sentence[i:i+n]) phrase = " " + phrase + " " # print(phrase) # print(len(phrase)) for sent in references: sent = " " + sent + " " if phrase in sent: score += 1 break # print(score) # print(denom) bleu_score = score/(denom-n+1) return bleu_score else: diff = float('inf') sim = -1 for i in range(len(references)): cur = references[i].split() size = len(cur) # print(size) if abs(size - denom) < diff: diff = abs(size - denom) sim = i # print(sim) # print(diff) brevity = len(references[sim].split())/denom # print("final") # print(len(references[sim])) if brevity < 1: bp = 1 else: bp = math.exp(1-brevity) bleu_score = 1 # print("denom " + str(denom-i+1)) for i in range(1,n+1): score = 0 for j in range(len(sentence)-i+1): phrase = " ".join(sentence[j:j+i]) phrase = " " + phrase + " " for sent in references: sent = " " + sent + " " if phrase in sent: score += 1 break bleu_score = bleu_score * score/(denom-i+1) bleu_score = bleu_score ** (1/n) bleu_score = bp * bleu_score return bleu_score # candidate1 = "It is a guide to action which ensures that the military always obeys the commands of the party" # candidate2 = "It is to insure the troops forever hearing the activity guidebook that party direct" # candidate3 = "I fear David" # # references_list2 = ['I am afraid Dave', 'I am scared Dave', 'I have fear David'] # references_list = ["It is a guide to action that ensures that the military will forever heed Party commands", # "It is the guiding principle which guarantees the military forces always being under command of the Party", # "It is the practical guide for the army always to heed the directions of the party"] # print(BLEU_score(candidate2, references_list, 1, True)) # print(BLEU_score(candidate2, references_list, 2, True)) # print(BLEU_score(candidate2, references_list, 3, True)) # print(BLEU_score(candidate2, references_list, 1)) # print(BLEU_score(candidate2, references_list, 2)) # print(BLEU_score(candidate2, references_list, 3))
271cee7b28ed2cb30b98cd4b505ecd090b3fe15f
anmolrajputriyal/anmol
/assignment2.py
353
3.5625
4
#Q1 print("hello this is my output") #Q2 print("acad"+"view") #Q3 a=2 b=4 c=7 print(a,b,c) #Q4 print('let\'s get started') #Q5 s="acadview" course="python" fees=5000 print("hello welcome to %s your course name is %s and total amount pending rs %d"%(s,course,fees)) #Q6 name="tony" salary=200000 print('%s''%d'%(name,salary))
29560880561a701e2a371d64ce390e88bccabf91
cainingning/leetcode
/tuter_start/116_tree.py
807
3.796875
4
# Definition for a Node. class Node(object): def __init__(self, val, left, right, next): self.val = val self.left = left self.right = right self.next = next class Solution(object): def connect(self, root): """ :type root: Node :rtype: Node """ """这是一个非常完整的二叉树,每层的数目都是2**(n - 1)""" if root is None: return root layer_first = root cur = None while layer_first.left: cur = layer_first while cur: cur.left.next = cur.right if cur.next: cur.right.next = cur.next.left cur = cur.next layer_first = layer_first.left return root
d7751d1873e99be3c5cb074bca409484d968a557
LucasEvo/Estudos-Python
/ex028.py
709
4.15625
4
# Escreva um programa que faça o computador "pensar" em um número inteiro entre 0 e 5 e peça para o usuário tentar # descobrir qual foi o número escolhido pelo computador. # O pragrama deverá escrever na tela se o usuário venceu ou perdeu. import random print('-=' * 30) print('Vou pensar em um número entre 0 e 5. Tente adivinhar...') print('-=' * 30) chute = int(input('Qual número eu pensei? ')) # Palpite do jogador num = random.randint(0, 5) # Sorteio do número if chute == num: print('Eu pensei no número {} e você acertou!'.format(num)) else: print('Eu não pensei nesse número e você errou!') print('-=' * 20) print(' FIM DE JOGO') print('-=' * 20)
2913fb266f37073648601daa06bf0f403f6c60e6
Aasthaengg/IBMdataset
/Python_codes/p02812/s612446736.py
232
3.65625
4
n=int(input()) s=input() l=[] count=0 for i in s: if i=='A': l=['A'] elif i=='B' and l==['A']: l.append('B') elif i=='C' and l==['A','B']: l=[] count+=1 else: l=[] print(count)
9d3339091917164e08df0bbdbaff8eec6945d428
StartAmazing/Python
/venv/Include/book/chapter10/remember_me.py
1,317
3.953125
4
import json # 如果以前存储了用户名,就加载它 # 否则就提示用户输入并存储它 def greet_user(): file_name = 'username.json' try: with open(file_name) as username_obj: username = json.load(username_obj) except FileNotFoundError: username = input("What's your name ? ") with open(file_name, 'w') as username_obj: json.dump(username, username_obj) print("We'll remember you when you come back, {}".format(username)) else: print("welcome back, {}".format(username)) # greet_user() print("-------------------------------") def get_stored_username(): '''如果存储了用户名那么句获取它''' file_name = "username.json" try: with open(file_name) as username_obj: username = json.load(username_obj) except: return None else: return username def greet(): '''问候用户,并指出其名字''' user_name = get_stored_username() if user_name == None: get_new_username() else: print("welcome back! {}".format(user_name)) def get_new_username(): user_name = input("Please input your name: ") file_name = "username.json" with open(file_name, 'w') as file_obj: json.dump(user_name, file_obj) greet()
842c229e431eeaf0b254d2e785e5a5c70ae97d94
willwarreniv/resources
/week3/odd_list_test.py
548
4
4
from odd_list import OddList def test_create(): ol = OddList([1, 3]) def test_append_item(): ol = OddList([]) ol.append(7) def test_append_works(): ol = OddList([1]) ol.append(3) assert 3 in ol def test_insert_item(): ol = OddList([1,5]) ol.insert(3,1) assert list(ol) == [1,3,5] def test_index(): ol = OddList([1,3]) assert ol[0] == 1 def test_add_list(): ol = OddList([1,3]) ol2 = OddList([5,7]) print(ol+ol2) print(OddList([1,3,5,7])) assert ol + ol2 == OddList([1,3,5,7])
e94d3fa4567a072d009caa9dd7560b3e22d6dce8
WaqasAkbarEngr/Python-Tutorials
/Variables.py
1,776
4.46875
4
# variable types are not needed to be declared in python # only value of variable is assigned. # python automatically detects type of entered data # for example numbers = 12345 # CAUTION! variable name is case sensitive # In above statement variable named numbers is declared by giving it numeric value # python will detect its type and automatically assign that type to it i.e. integer python_version = 3.7 # In above statement variable named python_version is declared by giving it numeric value # python will detect its type and automatically assign that type to it i.e. float ################################################################################################ # NOTE: One thing to be noted here is that if numeric value is in decimal form then it will be # # assigned float type and if it is without decimal point the it will be assigned integer type # ################################################################################################ complex = 123j # In above statement variable named complex is declared by giving it numeric value along with character j # python will detect its type and automatically assign that type to it i.e. complex program = 'this is my first program' # In above statement a variable named program is declared by just giving it string value # python will detect its type and automatically assign that type to it i.e. string print (type(numbers)) # This statement outputs the type of variable named numbers print (type(python_version)) # This statement outputs the type of variable named python_version print (type(program)) # This statement outputs the type of variable named program print (type(complex)) # This statement outputs the type of variable named complex
b9161579d77cbc7b7fa4da974faa8e7e4922cdd1
MondayMorningHaskell/Sorting
/src/Quicksort/python/quicksort_inplace.py
1,887
4.34375
4
def swap(arr, i, j): temp = arr[i] arr[i] = arr[j] arr[j] = temp # Partition the array (between indices 'start' and 'end') # Return the final pivot index. All elements to the left # of that index will be smaller than the element there. # All elements to the right will be greater. def partition(arr, start, end): # Read the first element, this will be our "pivot element". pivotElement = arr[start] pivotIndex = start + 1 # Loop through all the elements and swap them into the proper side # of the array. for i in range(start + 1, end): # If the element at 'i' is smaller than the pivot element, # swap it into the smaller/left portion of the array, and # advance the pivot index. if arr[i] <= pivotElement: swap(arr, i, pivotIndex) pivotIndex += 1 # The element at 'finalPivotIndex' will be greater than our pivot element. # (or else it is the end of the array) # So swap our pivot element into the position before it. swap(arr, start, pivotIndex - 1) return pivotIndex - 1 # Main driver of our algorithm. # Sorts a portion of the array, defined by 'start' and 'end'. # Base Case: If start + 1 >= end, we return immediately, # as the current segment is empty. # Note: 'end' refers to the element "one past the end" of our segment. def quicksortHelper(arr, start, end): if start + 1 >= end: return # Partition the array pivotIndex = partition(arr, start, end) # Recursively sort each half. # (The pivot element is already in its correct position) quicksortHelper(arr, start, pivotIndex) quicksortHelper(arr, pivotIndex + 1, end) # Runs the full quicksort. # This is just a wrapper, calling out to the helper function # but using the full bounds of the array. def quicksort(arr): quicksortHelper(arr, 0, len(arr)) my_array = [1, 6, 8, 3, 4, 7, 11, 10, 2, 5, 9] quicksort(my_array) print(my_array)
29415a9120c589cc9219b91223813d4f345135af
vishay28/year-2-project
/plug.py
2,643
3.703125
4
#This program controls the smart plug device #Imports the general file which contains various functions and variables which are used by multiple programs from generalFunctions import * #Importing the GPIO package import RPi.GPIO as GPIO #Setting the server message to blank serverMessage = "" #Creating a function to get the current date and time and formatting it def getTime(): #Converting the current date and time to a string currentTime = str(datetime.datetime.now()) #Selecting only the information that we want to display currentTime = (currentTime[0:19] + ": ") #Returning the current date and time return currentTime #A function to listen for an incomming message from the server def serverListen(): #Defning the global variable for the server message global serverMessage #Creating a main loop to listen for server messages while True: #Listening for a message from the server serverMessage = server.recv(1024) #Decoding the message received by the server serverMessage = serverMessage.decode() #Creating a main method in which to run the program if __name__ == "__main__": #This waiting period has been introduced to ensure the Raspberry PI connects to the wifi before trying to connect to the server time.sleep(10) print(getTime() + "Plug initiated") #Setting up the GPIO pins to be in board mode GPIO.setmode(GPIO.BOARD) #Setting up the set pin GPIO.setup(3, GPIO.OUT) #Setting up the reset pin GPIO.setup(5, GPIO.OUT) #Connecting to the server server = connectToServer() #Defining the client ID clientID = "plug" #Letting the server know that a plug has connected server.send(clientID.encode()) #Creating a thread to listen for messages from the server serverListenThread = Thread(target=serverListen) #Starting the thread serverListenThread.start() #Creating a main loop in which to run the program while True: #Checking what the server message is and responding accordingly if serverMessage == "turnOn": print(getTime() + "Plug turned on") #Pulsing the set pin GPIO.output(3, GPIO.HIGH) time.sleep(1) GPIO.output(3, GPIO.LOW) serverMessage = "" elif serverMessage == "turnOff": print(getTime() + "Plug turned off") #Pulsing the reset pin GPIO.output(5, GPIO.HIGH) time.sleep(1) GPIO.output(5, GPIO.LOW) serverMessage = ""
6dd2125cb8cdf572b9ad1fd535a275f568321b98
nyowusu/ProgramFlow
/set_challenge.py
665
4.46875
4
# Create a program that takes some text and returns a list of all # the characters in the text that are not vowels, # sorted in alphabetical order. # # You can either enter the text from teh keyboard or # initialise a string variable with the string. vowels = frozenset('aeiou') # frozen set is being used because the members mustn't change while True: string_to_check = set(input("Enter a sentence to take out the vowels ")) print("The sentence '{}' without vowels is ".format(string_to_check)) print(sorted(string_to_check.difference(vowels))) repeat = input("Do you want to check another sentence? (y/n) ") if repeat == "n": break
65425b08ac4d72da32509e430d5798ee2556f784
fourthtraining/ep35_c_to_f
/ep35_c_to_f.py
213
3.84375
4
c = input('請輸入攝氏溫度: ') c = float(c) #這一行式型別轉換,把c這個變數轉換成浮點數 --- PS:可以用整數(int)或浮點數(float) f = c * 9 / 5 + 32 print('華式溫度為: ', f)
4cd72861ed536f81e34e6b1044dc598af8047dd4
saulhappy/algoPractice
/python/miscPracticeProblems/Graphs/build_graph_from_edges.py
915
3.828125
4
""" Function that takes edges, and makes a graph """ from collections import defaultdict def build_graph(edges): graph = defaultdict(list) for edge in edges: a, b = edge graph[a].append(b) graph[b].append(a) return graph print(build_graph([ ['w', 'x'], ['x', 'y'], ['z', 'y'], ['z', 'v'], ['w', 'v'] ] )) # => defaultdict(<class 'list'>, {'w': ['x', 'v'], 'x': ['w', 'y'], 'y': ['x', 'z'], 'z': ['y', 'v'], 'v': ['z', 'w']}) # Other, more manual method: def build_graph(edges): graph = {} for edge in edges: a, b = edge if a not in graph: graph[a] = [] if b not in graph: graph[b] = [] graph[a].append(b) graph[b].append(a) return graph print(build_graph([ ['w', 'x'], ['x', 'y'], ['z', 'y'], ['z', 'v'], ['w', 'v'] ] )) # => {'w': ['x', 'v'], 'x': ['w', 'y'], 'y': ['x', 'z'], 'z': ['y', 'v'], 'v': ['z', 'w']}
6eeb86ef6c78405f6a5edc68e748fd825704edd4
27kim/Python_DeepLearning_
/SoftMax_Classification_0.py
1,468
3.515625
4
# tensorflow import import tensorflow as tf import numpy as np xy = np.loadtxt('./data/05train.txt', dtype='float32') print(xy) x_data = xy[:, 0: 3] y_data = xy[:, 3:] print(x_data.shape, y_data.shape) # softmax 는 0으로 넣어도 된다고? W = tf.Variable(tf.zeros([3, 3])) # placeholder 지정 X = tf.placeholder(tf.float32) Y = tf.placeholder(tf.float32) hypothesis = tf.nn.softmax(tf.matmul(X, W)) cost = tf.reduce_mean(-tf.reduce_sum(Y * tf.log(hypothesis), axis=1)) train = tf.train.GradientDescentOptimizer(0.01).minimize(cost) init = tf.global_variables_initializer() with tf.Session() as sess: sess.run(init) sess.run(tf.global_variables_initializer()) for step in range(50001): sess.run(train, feed_dict={X: x_data, Y: y_data}) if step % 2000 == 0: print(step, sess.run(cost, feed_dict={X: x_data, Y: y_data}), sess.run(W)) # 값을 넣어 예측하기. feed_dict 에 값을 넣어서 11시간 공부 7번 수업 a = sess.run(hypothesis, feed_dict={X: [[1, 11, 7]]}) # 예측값 출력 print("예측값") print(a) print(a, sess.run(tf.argmax(a, 1))) c = sess.run(hypothesis, feed_dict={X: [[1, 1, 0]]}) print(c) print(c, sess.run(tf.argmax(c, 1))) correct_prediction = tf.equal(tf.argmax(hypothesis, 1), tf.argmax(Y, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) print(sess.run(accuracy, feed_dict={X: x_data, Y: y_data}))
6be3e42b5a27e49de9e12cd1c03fe37a074d35a9
carolgcastro/Curso_Python
/Mundo 2/ex070.py
706
3.671875
4
total = 0 maior = 0 menor = 0 c = 1 nome_m = '' print('-'*30) print(' LOJA SUPER BARATÃO') print('-'*30) while True: nome = input('Nome do produto: ') preco = float(input('Preço: R$')) if preco > 1000: maior += 1 total += preco #soma preço de todos os produtos if c == 1 or preco < menor: menor = preco nome_m = nome c +=1 op = input('Quer continuar? [S/N] ').upper().strip() if op == 'N': break print('---------- FIM DO PROGRAMA -----------') print(f"""O total da compra foi de R${total:.2f} Temos {maior} produtos custando mais de R$1000.00 O produto mais barato foi {nome_m} que custa R${menor:.2f}""")
1387b979c73755c838b95d101c7b7f85c182dfd7
dima17502/Python-Programes
/information_security/sieve_of_eratosthenes.py
298
3.578125
4
n = int(input()) sieve = [True] * (n + 1) i = 2 count = 0 while i * i <= n: j = i * i if sieve[j]: while j <= n: sieve[j] = False j += i i += 1 for i in range (2, len(sieve)): if sieve[i]: count += 1 #print(i, end=' ') print(count)
37b87e67a533a1693f99c7837d819d5dc2714306
Python-aryan/Hacktoberfest2020
/Python/Rock PaperScissors.py
2,858
4.15625
4
print("Made by Aayushi") win="You Win" loose="The Computer Wins" drew=0 lives=5 score=0 computer_lives=5 while True: rps=input("Rock, Paper, Scissor? ") import random computer=("rock", "paper", "scissor") computer=random.choice(computer) #rock statements if rps=="rock": if computer=="paper": print() print("The computer chose", computer) print(loose) print() lives-=1 if computer=="scissor": print() print("The computer chose", computer) print(win) print() lives+=1 score+=1 computer_lives-=1 if computer=="rock": print() print("The computer chose", computer) print("You Drew") drew+=1 print() if rps=="paper": if computer=="scissor": print() print("The computer chose", computer) print(loose) print() lives-=1 if computer=="rock": print() print("The computer chose", computer) print(win) print() lives+=1 score+=1 computer_lives-=1 if computer=="paper": print() print("The computer chose", computer) print("You Drew") drew+=1 print() if rps=="scissor": if computer=="rock": print() print("The computer chose", computer) print(loose) print() lives-=1 if computer=="paper": print() print("The computer chose", computer) print(win) print() lives+=1 score+=1 computer_lives-=1 if computer=="scissor": print() print("The computer chose", computer) print("You Drew") drew+=1 print() #system if rps=="rules": print("Paper beats Rock") print("Rock beats Scissor") print("Scissor beats Paper") if rps=="lives": print("Your Lives", lives) print("Computer Lives", computer_lives) if rps=="score": print("Score is ",score) #end if lives==0 or rps=="test": print("Thanks for playing") print("You lost. You have ",lives," lives") print("You got ",score," correct") stop=input("Press enter to exit ") import time time.sleep(900) if computer_lives==0: print("Thanks for playing") print("You won. The computer has no lives") print("You got ",score," correct") stop=input("Press enter to exit ") import time time.sleep(100) #exit if rps=="exit": break
5d85b75b28ebbfb6f7fabdc2b37602f48db0e427
kocsisttibor/pallida-exam-basics
/uniquechars/unique_chars_test.py
546
3.703125
4
import unittest from unique_chars import unique_characters class UniqueCharsTestCases(unittest.TestCase): def test_empty_string(self): self.assertEqual(unique_characters(""), []) def test_one_letter_string(self): self.assertEqual(unique_characters("a"), ["a"]) def test_duplicated_letter(self): self.assertEqual(unique_characters("aa"), []) def test_duplicated_letter_and_single_letter(self): self.assertEqual(unique_characters("aab"), ["b"]) if __name__ == '__main__': unittest.main()
6fe7d3fb7f3e3a6aff0af040ac9175503a1a7eb2
T-Nawrocki/Udemy-Python
/Notes06-ProgramFlowControl/05-forloops2.py
505
4.625
5
# lecture 46 # for loops can be used with lists, as lists are another type of sequence for state in ["not pining", "no more", "a stiff", "bereft of life"]: print(f"This parrot is {state}.") # and similarly they work with ranges: for i in range(0, 101, 5): # the third argument is the step value print(i) # embedded for loops iterate over the inner variable first, then the outer one for i in range(1,13): for j in range(1,13): print(f"{i} * {j} = {i * j}") print("==========")
cc9a9d497cd4dc6f9812d2d12632fed3296127c0
maxblood/flask-blog
/test.py
7,607
3.609375
4
from flask import Flask ,render_template,request, session ,redirect # flask is a micro frame work for web development from flask_sqlalchemy import SQLAlchemy #sqlalchemy is used for database from datetime import datetime app = Flask(__name__) app.secret_key = 'hello-world' #this is the syntax for making the flask framework bcoz flask treated as app app.config['SQLALCHEMY_DATABASE_URI'] = "mysql://root:@127.0.0.1/codingthunder" #this is for making the connection with database db = SQLAlchemy(app) #this is for making conection , with database #--------------------------------------------------------------------------------------------------------------------------- class Contacts(db.Model): # this class is used for intreacting with database, sno = db.Column(db.Integer, primary_key=True) # or LHS me vo variable hai jo database m bnae the . name = db.Column(db.String(80), nullable=False) # class name vo ayega jo hmne database bnaya hai, or baki sara syntax hai usme koi change nhi krna . phone_num = db.Column(db.String(15), nullable=False) msg = db.Column(db.String(120), nullable=False) date = db.Column(db.String(12), nullable=False) email = db.Column(db.String(120), nullable=False) class Posts(db.Model): # ye class post k lie bnai hai ,sara same hai database se intract krane k lie sno = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(80), nullable=False) slug = db.Column(db.String(21), nullable=False) content = db.Column(db.String(120), nullable=False) date = db.Column(db.String(12), nullable=False) img_file = db.Column(db.String(25), nullable=False) #----------------------------------------------------------------------------------------------------------------------------- @app.route("/home") # ye important cheex hai , sara syntax hai change bs bracket k bich vala krna hai , or vha jo ayega jisko hmne route krna hai website p. def home(): posts = Posts.query.filter_by().all()[0:6] # home hmara function hai jsik ander m call krwaenge cheeze. return render_template('index.html',posts= posts) # render_template() ek function hai to hmko isko import krwanahota hai fir,hm isme apni html page ka name dete hai. #---------------------------------------------------------------------------------------------------------------------------- @app.route("/about") def about(): return render_template('about.html') #--------------------------------------------------------------------------------------------------------------------------- @app.route("/dashboard", methods= ['GET','POST']) def login(): if ('user' in session and session['user'] == "harsh"): posts = Posts.query.filter_by().all() return render_template('dashboard.html') if request.method == 'POST': username = request.form.get('uname') password = request.form.get('pass') if username == "harsh" and password == "12345678": session['user'] = username return render_template('dashboard.html') return render_template('login.html') #----------------------------------------------------------------------------------------------------------------------------- @app.route("/post/<string:post_slug>", methods = ['GET']) # YE VALA BHI BOHT IMPORTANT HAI(is syntax se hm koi bhi data fetch kra skte hai.) def post_route(post_slug): # jo string upr pass krwai hai vohi niche function m call krwaenge . post = Posts.query.filter_by(slug= post_slug).first() return render_template('post.html', post = post) ''' - post_slug ye hamra banaya hua variable hai.(upr jo first line m likha hai vhoi hamra URL hoga vhi p ye kam krega.) - hmne ek (post) nam ka variable bnaya hai jisme us perticular table ka fetch hoga. - Post.query.filter_by() ye ek method hai jisse hm koi bhi value fetch krwa skte hai. - ab (slug = post_slug) isme jo (slug) hai vo to databse ka hai, or post_slug hmara banaya hua hai. - ab jab hm us URL ko hit krenge tab post_slug k ander post ka name aajaega ,fir vo value database k slug k sath check krenge,ar hmko vo data fetch krk ladega. - first() fuction hm isiliye use krte hai, kuki database m phla post us slug m milega vo fetch ho jaega. ''' #--------------------------------------------------------------------------------------------------------------------------- @app.route("/edit/<string:sno>", methods= ['GET', 'POST']) def edit(sno): if ('user' in session and session['user'] == "harsh"): if request.method == 'POST': box_title= request.form.get('title') box_slug= request.form.get('slug') box_content= request.form.get('content') box_img_file= request.form.get('img_file') if sno =='0': post = Posts(title= box_title, slug= box_slug, content= box_content,img_file=box_img_file, date = datetime.now()) db.session.add(post) db.session.commit() else: post = Posts.query.filter_by(sno=sno).first() post.title = box_title post.slug = box_slug post.content = box_content post.img_file = box_img_file db.session.commit() return redirect('/edit/'+sno) post = Posts.query.filter_by(sno=sno).first() return render_template('edit.html',post=post,sno=sno) #------------------------------------------------------------------------------------------------------------------- @app.route("/logout") def logout(): session.pop('user') return redirect('/dashboard') @app.route("/delete/<string:sno>", methods= ['GET', 'POST']) def delete(sno): if ('user' in session and session['user'] == "harsh"): post= Posts.query.filter_by(sno= sno).first() db.session.delete(post) db.session.commit() return redirect('/dashboard') #----------------------------------------------------------------------------------------- @app.route("/contact", methods= ['GET','POST']) #YE BLOCK HMKO DATABASE M ENTRY KRWANE K KAM ATA HAI def contact(): if (request.method == 'POST'): # ye shuro krne se phle hmko html me sb inputs ko name dene pdenge . # fir name dene k bad same name k variable bnaenge(LHS) m jo hai same. name=request.form.get('name') # request ek module hai jisko hmko import krna pdta hai flask m email=request.form.get('email') # request.form.get() method hai jisse hm value insert krne k lie use krenge. phone=request.form.get('phone') # right side m jo () m hai jo sare name hi hai jo hmne html m die hai. message=request.form.get('message') # jb hm form m value bhrenge tab vo values yha se send hok entry variable m jaengi entry = Contacts(name=name, phone_num=phone, msg= message,date = datetime.now(), email=email) db.session.add(entry) # entry k ander hm apni values database m dalenge db.session.commit() # db.session.add(entry) or db.session.commit() ye dono syntax fixed hai return render_template('contact.html') app.run(debug=True) #-----------------------------------------------------------------------------------------------------------------------------
511ed3b5d5d5ae334a83916a138eaff30785bcae
p1pk4/Tasks-from-YNDX-Practicum
/vetv_task_3_4.py
761
4.03125
4
''' #Функция range(24) перебирает все числа от 0 до 24 и по очереди передаёт их в тело цикла в переменной current_hour («текущее время»). #Научите Анфису желать вам доброго утра, если в переменной current_hour записано значение меньше 12. #Расширьте код из прошлой задачи. Если на часах полдень или больше — пусть Анфиса скажет: 'Добрый день!' ''' for current_hour in range(24): if current_hour < 12: print('Доброе утро!') else: current_hour >= 12 print('Добрый день!')
eeff677f4aaa0e138ca2297914198ac6ab12432d
droudrou/exact_splitting
/shape_split1D.py
18,980
3.6875
4
# coding: utf-8 # In[2]: import numpy as np import matplotlib.pyplot as plt import scipy.integrate as scint import math #get_ipython().magic('matplotlib inline') # In[ ]: # In[3]: def Getx(nx, xmin, xmax): dx = np.abs(xmax - xmin)/float(nx) x = xmin + np.arange(nx+1)*dx return x # In[4]: # reduce is not recognized by python 3.5.2 #def fact(n):return reduce(lambda x,y:x*y,[1]+range(1,n+1)) def fact(n):return math.factorial(n) # In[5]: ''' Calculate binomial coefficient nCk = n! / (k! (n-k)!) ''' def binomial(n, k): if n<0 or k<0 or k>n: binom=0 else: binom = fact(n) // fact(k) // fact(n - k) return binom #Print Pascal's triangle to test binomial() def pascal(m): for x in range(m + 1): print([binomial(x, y) for y in range(x + 1)]) # In[6]: pascal(5) # In[7]: def trinomial(n,k): coef = 0 j_l = np.arange(n+1) #print("j_l",j_l) for j in j_l: val1 = binomial(n, j) val2 = binomial(2*n-2*j, n-k-j) coef = coef + (-1)**j * val1 * val2 #print("n = %d, k = %d, j = %d, coef = %d"%(n, k, j, coef)) #print("binomial(n, j) = %d"%val1) #print("binomial(2*n-2*j, n-k-j) = %d"%val2) return coef #Print Trinomial's triangle to test trinomial() def tri_tri(m): for x in range(m + 1): #print("Row %d"%x) #print(range(-x, x+1)) print([trinomial(x, y) for y in range(-x, x+1)]) # In[8]: tri_tri(10) # In[ ]: # In[ ]: # In[ ]: # In[9]: def GetOrd1(x,x0,dx): xi=(x-x0)/dx izeros = np.argwhere(abs(xi) > 1.) ileft = np.argwhere(xi < 0.) iright = np.argwhere(xi >= 0.) shape = np.zeros(len(x)) for ik in ileft: shape[ik] = xi[ik]+1. for ik in iright: shape[ik] = 1.-xi[ik] for ik in izeros: shape[ik] = 0. return (shape) # In[10]: def GetOrd2(x,x0,dx): xi=(x-x0)/dx iequ1 = np.argwhere( abs(xi) < 0.5 ) iequ2 = np.argwhere( abs(xi) >= 0.5 ) izeros = np.argwhere( abs(xi) > 1.5 ) shape = np.zeros(len(x)) for ik in iequ1: shape[ik] = 0.75 - abs(xi[ik])**2. for ik in iequ2: shape[ik] = 0.5*(1.5 - abs(xi[ik]))**2. for ik in izeros: shape[ik] = 0. return (shape) # In[11]: def Spline2(x,x0,dx): xi=(x-x0)/dx val = 0. if not isinstance(x, float) : print("Cette fonction renvoie un scalaire !") return(val) if abs(xi)<0.5: val = 0.75 - abs(xi)**2. elif abs(xi)>=0.5 and abs(xi)<1.5: val = 0.5*(1.5 - abs(xi))**2. else: val = 0. return (val) # In[12]: x0=3. Spline2(x0+0.5, x0+0., 0.5) # In[13]: def GetOrd3(x,x0,dx): xi=(x-x0)/dx iequ1 = np.argwhere( abs(xi) < 1. ) iequ2 = np.argwhere( abs(xi) >= 1. ) izeros = np.argwhere( abs(xi) > 2. ) shape = np.zeros(len(x)) for ik in iequ1: shape[ik] = 0.5*abs(xi[ik])**3. - xi[ik]**2. + 2./3. for ik in iequ2: shape[ik] = 4./3.*(1. - 0.5*abs(xi[ik]))**3. for ik in izeros: shape[ik] = 0. return (shape) # In[14]: def GetOrd4(x,x0,dx): xi=(x-x0)/dx iequ1 = np.argwhere( abs(xi) < 0.5 ) iequ2 = np.argwhere( abs(xi) >= 0.5 ) iequ3 = np.argwhere( abs(xi) >= 1.5 ) izeros = np.argwhere( abs(xi) > 2.5 ) shape = np.zeros(len(x)) for ik in iequ1: shape[ik] = 1./192.*( 115. - 120.*xi[ik]**2. + 48.*xi[ik]**4. ) for ik in iequ2: shape[ik] = 1./96.*( 55. + 20.*abs(xi[ik]) - 120.*xi[ik]**2. + 80.*abs(xi[ik])**3. - 16.*xi[ik]**4.) for ik in iequ3: shape[ik] = 1./24.*(2.5 - abs(xi[ik]))**4. for ik in izeros: shape[ik] = 0. return (shape) # In[15]: def getShape(order, x, x0, dx_L0): return { 1: GetOrd1(x, x0, dx_L0), 2: GetOrd2(x, x0, dx_L0), 3: GetOrd3(x, x0, dx_L0), 4: GetOrd4(x, x0, dx_L0), }.get(order, GetOrd1(x, x0, dx_L0)) # In[ ]: # In[ ]: # In[ ]: # In[9]: x = Getx(10000,10) shape = GetOrd1(x, 4., 1.) bmin = 2. bmax = 6. plt.plot(x,shape) plt.xlim(bmin, bmax) # In[ ]: # In[10]: x = Getx(10000,10) shape = GetOrd2(x, 4., 1.) bmin = 2. bmax = 6. plt.plot(x,shape) plt.xlim(bmin, bmax) # In[11]: x = Getx(10000,10) shape = GetOrd3(x, 4., 1.) bmin = 2. bmax = 6. plt.plot(x,shape) plt.xlim(bmin, bmax) # In[12]: x = Getx(10000,10) shape = GetOrd4(x, 4., 1.) bmin = 1. bmax = 7. plt.plot(x,shape) plt.xlim(bmin, bmax) # In[ ]: # In[ ]: # In[ ]: # In[13]: NbPoints = 10000 Lmax = 10. dx = Lmax/NbPoints print("dx = %f" %dx) x = Getx(NbPoints,Lmax) x0 = 4. dx_L0 = 1. dx_L1 = dx_L0/2. RF = dx_L0/dx_L1 shape = GetOrd1(x, 4., 1.) w1=0.25 * RF shape_split = w1*GetOrd1(x, x0-dx_L1, dx_L1) + w1*GetOrd1(x, x0+dx_L1, dx_L1) + 2.*w1*GetOrd1(x, x0, dx_L1) # Compute the area using the composite Simpson's rule. area_ref = scint.simps(shape, dx=dx) area_split = scint.simps(shape_split, dx=dx) print("area ref=", area_ref) print("area split=", area_split) bmin = 2. bmax = 6. plt.plot(x,shape) plt.plot(x,shape_split,'red') plt.xlim(bmin, bmax) # In[ ]: # In[17]: NbPoints = 10000 Lmax = 10. dx = Lmax/NbPoints print("dx = %f" %dx) x = Getx(NbPoints,Lmax) x0 = 4. dx_L0 = 1. dx_L1 = dx_L0/2. RF = dx_L0/dx_L1 dta = 1.5*dx_L1 w1 = 0.25 w2 = w1 w3 = 2.*0.5 print("w1 = %.2f, w2 = %.2f, w3 = %.2f"%(w1, w2, w3)) wtot = w1 + w2 + w3 print("wtot = %.2f"%wtot) w1 = w1/wtot * RF w2 = w2/wtot * RF w3 = w3/wtot * RF print("w1 = %.2f, w2 = %.2f, w3 = %.2f"%(w1, w2, w3)) shape = GetOrd2(x, x0, dx_L0) s1 = w1*GetOrd2(x, x0-dta, dx_L1) s2 = w2*GetOrd2(x, x0+dta, dx_L1) s3 = w3*GetOrd2(x, x0, dx_L1) shape_split = s1 +s2 + s3 # Compute the area using the composite Simpson's rule. area_ref = scint.simps(shape, dx=dx) area_split = scint.simps(shape_split, dx=dx) print("area ref=", area_ref) print("area split=", area_split) bmin = 2. bmax = 6. plt.plot(x,shape) plt.plot(x,shape_split,'red') plt.plot(x,s1,'r--') plt.plot(x,s2,'r--') plt.plot(x,s3,'r--') plt.xlim(bmin, bmax) # In[ ]: # In[ ]: # In[35]: # # APPROXIMATE TEST # NbPoints = 10000 xmin = -5. xmax = 5. Lmax = np.abs(xmax - xmin) dx = Lmax/NbPoints print("dx = %f" %dx) x = Getx(NbPoints, xmin, xmax) x0 = 2. dx_L0 = 1. dx_L1 = dx_L0/2. RF = dx_L0/dx_L1 dta = 1.*dx_L1 shape = GetOrd2(x, x0, dx_L0) order = 2 nbpts = (2*int(RF) - 1) + (order-1) # just to have a taste of things coef1 = 1.125 # 0.9 coef2 = 1.125 # 0.9 coef3 = 1. w1 = coef1*Spline2(x0-dta, x0, dx_L0) w2 = coef2*Spline2(x0+dta, x0, dx_L0) w3 = coef3*Spline2(x0, x0, dx_L0) print("w1 = %.2f, w2 = %.2f, w3 = %.2f"%(w1, w2, w3)) wtot = w1 + w2 + w3 print("wtot = %.2f"%wtot) w1 = w1/wtot * RF w2 = w2/wtot * RF w3 = w3/wtot * RF print("w1 = %.2f, w2 = %.2f, w3 = %.2f"%(w1, w2, w3)) s1 = w1*GetOrd2(x, x0-dta, dx_L1) s2 = w2*GetOrd2(x, x0+dta, dx_L1) s3 = w3*GetOrd2(x, x0, dx_L1) shape_split = s1 + s2 + s3 # Compute the area using the composite Simpson's rule. area_ref = scint.simps(shape, dx=dx) As1 = scint.simps(s1, dx=dx) As2 = scint.simps(s2, dx=dx) As3 = scint.simps(s3, dx=dx) print("As1 = %f, As2 = %f, As3 = %f"%(As1, As2, As3)) area_split = As1 + As2 +As3 print("area ref=", area_ref) print("area split=", area_split) #s1 = s1/area_split #s2 = s2/area_split #s3 = s3/area_split #shape_split = shape_split/area_split print("After normalization :") area_split = scint.simps(shape_split, dx=0.001) print("area split=", area_split) bmin = x0 - 0.5*nbpts*dx_L1 - (order+1)*0.5*dx_L1 bmax = x0 + 0.5*nbpts*dx_L1 + (order+1)*0.5*dx_L1 plt.plot(x,shape) plt.plot(x,shape_split,'red') plt.plot(x,s1,'r--') plt.plot(x,s2,'r--') plt.plot(x,s3,'r--') plt.xlim(bmin, bmax) # In[ ]: # # EXACT TEST FOR 1st ORDER # NbPoints = 10000 xmin = -5. xmax = 5. Lmax = np.abs(xmax - xmin) dx = Lmax/NbPoints print("dx = %f" %dx) x = Getx(NbPoints, xmin, xmax) x0 = 2. dx_L0 = 1. dx_L1 = dx_L0/2. RF = dx_L0/dx_L1 shape = GetOrd1(x, x0, dx_L0) order = 2 nbpts = (2*int(RF) - 1) + (order-1) w1 = 1./2. w2 = 1. w3 = 1./2. print("w1 = %.2f"%(w1)) print("w2 = %.2f"%(w2)) print("w3 = %.2f"%(w3)) wtot = w1 + w2 + w3 print("wtot = %.2f"%wtot) print("RF = %.2f"%RF) s1 = w1*GetOrd1(x, x0-dx_L1, dx_L1) s2 = w2*GetOrd1(x, x0 , dx_L1) s3 = w3*GetOrd1(x, x0+dx_L1, dx_L1) shape_split = s1 + s2 + s3 # Compute the area using the composite Simpson's rule. area_ref = scint.simps(shape, dx=dx) As1 = scint.simps(s1, dx=dx) As2 = scint.simps(s2, dx=dx) As3 = scint.simps(s3, dx=dx) print("As1 = %f"%(As1)) print("As2 = %f"%(As2)) print("As3 = %f"%(As3)) area_split = As1 + As2 + As3 print("area ref=", area_ref) print("area split=", area_split) print("After normalization :") area_split = scint.simps(shape_split, dx=0.001) print("area split=", area_split) bmin = x0 - 0.5*nbpts*dx_L1 - (order+1)*0.5*dx_L1 bmax = x0 + 0.5*nbpts*dx_L1 + (order+1)*0.5*dx_L1 plt.plot(x,shape) plt.plot(x,shape_split,'red') plt.plot(x,s1,'r--') plt.plot(x,s2,'r--') plt.plot(x,s3,'r--') plt.xlim(bmin, bmax) # In[83]: # # EXACT TEST FOR 2nd ORDER # NbPoints = 10000 xmin = -5. xmax = 5. Lmax = np.abs(xmax - xmin) dx = Lmax/NbPoints print("dx = %f" %dx) x = Getx(NbPoints, xmin, xmax) x0 = 2. dx_L0 = 1. dx_L1 = dx_L0/2. RF = dx_L0/dx_L1 dta = 0.5 *dx_L1 dta2 = 1.5*dx_L1 shape = GetOrd2(x, x0, dx_L0) order = 2 nbpts = (2*int(RF) - 1) + (order-1) w1 = 3./4. # x0-dta w2 = 3./4. # x0-dta w3 = 1./4. # x0-dta2 w4 = 1./4. # x0-dta2 print("w1 = %.2f, w2 = %.2f"%(w1, w2)) print("w3 = %.2f, w4 = %.2f"%(w3, w4)) wtot = w1 + w2 + w3 + w4 print("wtot = %.2f"%wtot) print("RF = %.2f"%RF) print("w1 = %.2f, w2 = %.2f"%(w1, w2)) print("w3 = %.2f, w4 = %.2f"%(w3, w4)) s1 = w1*GetOrd2(x, x0-dta, dx_L1) s2 = w2*GetOrd2(x, x0+dta, dx_L1) s3 = w3*GetOrd2(x, x0-dta2, dx_L1) s4 = w4*GetOrd2(x, x0+dta2, dx_L1) shape_split = s1 + s2 + s3 + s4 # Compute the area using the composite Simpson's rule. area_ref = scint.simps(shape, dx=dx) As1 = scint.simps(s1, dx=dx) As2 = scint.simps(s2, dx=dx) As3 = scint.simps(s3, dx=dx) As4 = scint.simps(s4, dx=dx) print("As1 = %f, As2 = %f"%(As1, As2)) print("As3 = %f, As4 = %f"%(As3, As4)) area_split = As1 + As2 + As3 + As4 print("area ref=", area_ref) print("area split=", area_split) print("After normalization :") area_split = scint.simps(shape_split, dx=0.001) print("area split=", area_split) bmin = x0 - 0.5*nbpts*dx_L1 - (order+1)*0.5*dx_L1 bmax = x0 + 0.5*nbpts*dx_L1 + (order+1)*0.5*dx_L1 plt.plot(x,shape) plt.plot(x,shape_split,'red') plt.plot(x,s1,'r--') plt.plot(x,s2,'r--') plt.plot(x,s3,'r--') plt.plot(x,s4,'r--') #plt.plot(x,s5,'r--') plt.xlim(bmin, bmax) # In[ ]: # In[ ]: # In[85]: NbPoints = 10000 xmin = -5. xmax = 5. Lmax = np.abs(xmax - xmin) dx = Lmax/NbPoints print("dx = %f" %dx) x = Getx(NbPoints, xmin, xmax) x0 = 2. dx_L0 = 1. dx_L1 = dx_L0/2. RF = dx_L0/dx_L1 shape = GetOrd3(x, x0, dx_L0) order = 2 nbpts = (2*int(RF) - 1) + (order-1) w1 = 1./8. # x0 - 2*dx1 w2 = 4./8. # x0 - dx1 w3 = 6./8. # x0 w4 = 4./8. # x0 + dx1 w5 = 1./8. # x0 + 2*dx1 print("w1 = %.2f, w2 = %.2f"%(w1, w2)) print("w3 = %.2f"%(w3)) print("w4 = %.2f, w5 = %.2f"%(w4, w5)) wtot = w1 + w2 + w3 + w4 + w5 print("wtot = %.2f"%wtot) #w1 = w1/wtot * RF #w2 = w2/wtot * RF #w3 = w3/wtot * RF #w4 = w4/wtot * RF #w5 = w5/wtot * RF print("RF = %.2f"%RF) print("w1 = %.2f, w2 = %.2f"%(w1, w2)) print("w3 = %.2f"%(w3)) print("w4 = %.2f, w5 = %.2f"%(w4, w5)) s1 = w1*GetOrd3(x, x0 - 2.*dx_L1, dx_L1) s2 = w2*GetOrd3(x, x0 - dx_L1, dx_L1) s3 = w3*GetOrd3(x, x0 , dx_L1) s4 = w4*GetOrd3(x, x0 + dx_L1, dx_L1) s5 = w5*GetOrd3(x, x0 + 2.*dx_L1, dx_L1) shape_split = s1 + s2 + s3 + s4 + s5 # Compute the area using the composite Simpson's rule. area_ref = scint.simps(shape, dx=dx) As1 = scint.simps(s1, dx=dx) As2 = scint.simps(s2, dx=dx) As3 = scint.simps(s3, dx=dx) As4 = scint.simps(s4, dx=dx) As5 = scint.simps(s5, dx=dx) print("As1 = %f, As2 = %f"%(As1, As2)) print("As3 = %f"%(As3)) print("As4 = %f, As5 = %f"%(As4, As5)) area_split = As1 + As2 + As3 + As4 + As5 print("area ref=", area_ref) print("area split=", area_split) print("After normalization :") area_split = scint.simps(shape_split, dx=0.001) print("area split=", area_split) bmin = x0 - 0.5*nbpts*dx_L1 - (order+1)*0.5*dx_L1 bmax = x0 + 0.5*nbpts*dx_L1 + (order+1)*0.5*dx_L1 plt.plot(x,shape) plt.plot(x,shape_split,'red') plt.plot(x,s1,'r--') plt.plot(x,s2,'r--') plt.plot(x,s3,'r--') plt.plot(x,s4,'r--') plt.plot(x,s5,'r--') plt.xlim(bmin, bmax) # In[ ]: # GENERAL SCRIPT FOR 1st order # AND ARBITRARY REFINEMENT FACTOR (RF) NbPoints = 10000 xmin = -5. xmax = 5. Lmax = np.abs(xmax - xmin) dx = Lmax/NbPoints print("dx = %f" %dx) x = Getx(NbPoints, xmin, xmax) x0 = 1. RF = 3. dx_L0 = 1. dx_L1 = dx_L0/RF # 1st order order=1 shape = GetOrd1(x, x0, dx_L0) nbpts = (2*int(RF) - 1) + (order-1) print("RF = %.2f"%RF) print("order = %d"%order) print("nbpts = (2*RF - 1) + (order-1)") print("nbr of points = %d"%nbpts) w=np.zeros(nbpts) # Calcul des coefficients ik_l = np.arange(nbpts) for ik in np.nditer(ik_l): print("%d "%ik, end='') print("") inum=1 for ik in ik_l: w[ik] = float(inum)/float(RF) if ik-RF+1 < 0: inum=inum+1 else: inum=inum-1 for wi in np.nditer(w): print("%f "%wi, end='') print("") wtot = np.sum(w) print("wtot = %.2f"%wtot) split_tab = np.zeros((nbpts, len(x))) inum=-(RF-1) for ik in ik_l: split_tab[ik,:] = w[ik]*GetOrd1(x, x0 + float(inum)*dx_L1, dx_L1) print(inum) inum=inum+1 shape_split = split_tab.sum(axis=0) # Compute the area using the composite Simpson's rule. area_ref = scint.simps(shape, dx=dx) Asplit_tab = np.zeros(nbpts) for ik in ik_l: Asplit_tab[ik] = scint.simps(split_tab[ik,:], dx=dx) print("Asplit_tab[%d] = %f"%(ik, Asplit_tab[ik])) print("area ref=", area_ref) area_split = np.sum(Asplit_tab) print("Sum split areas =", area_split) area_split = scint.simps(shape_split, dx=0.001) print("Sum split areas =", area_split) bmin = x0 - 0.5*nbpts*dx_L1 - (order+1)*0.5*dx_L1 bmax = x0 + 0.5*nbpts*dx_L1 + (order+1)*0.5*dx_L1 plt.plot(x,shape) plt.plot(x,shape_split,'red') for ik in ik_l: plt.plot(x,split_tab[ik,:],'r--') plt.xlim(bmin, bmax) plt.ylim(0, 1) plt.xlabel(r"$\xi$",size=20) ; plt.ylabel(r"$S(\xi)$",size=20) # In[ ]: # In[376]: # GENERAL SCRIPT FOR # ARBITRARY ORDER AND RF = 2 NbPoints = 10000 xmin = -5. xmax = 5. Lmax = np.abs(xmax - xmin) dx = Lmax/NbPoints print("dx = %f" %dx) x = Getx(NbPoints, xmin, xmax) # We set the refinement ratio # and the shape function order RF = 2. x0 = 1.5 dx_L0 = 1. dx_L1 = dx_L0/RF # Arbitrary order order = 2 shape = getShape(order, x, x0, dx_L0) print("RF = %.2f"%RF) print("order = %d"%order) nbpts = order+2 print("nbpts = 2*(order+1)+1") print("nbr of points = %d"%nbpts) nt = order+1 # Calcul des coefficients w = np.array([float(binomial(nt, y)) for y in range(0, nt+1)]) w[:] = w[:]/RF**order for wi in np.nditer(w): print("%f "%wi, end='') print("") ik_l = np.arange(nbpts) for ik in np.nditer(ik_l): print("%d "%ik, end='') print("") wtot = np.sum(w) print("wtot = %.2f"%wtot) split_tab = np.zeros((nbpts, len(x))) inum=-(nbpts-1)/2. for ik in ik_l: split_tab[ik,:] = w[ik]*getShape(order, x, x0 + float(inum)*dx_L1, dx_L1) print(inum) inum=inum+1 shape_split = split_tab.sum(axis=0) # Compute the area using the composite Simpson's rule. area_ref = scint.simps(shape, dx=dx) Asplit_tab = np.zeros(nbpts) for ik in ik_l: Asplit_tab[ik] = scint.simps(split_tab[ik,:], dx=dx) print("Asplit_tab[%d] = %f"%(ik, Asplit_tab[ik])) print("area ref=", area_ref) area_split = np.sum(Asplit_tab) print("Sum split areas =", area_split) area_split = scint.simps(shape_split, dx=0.001) print("Sum split areas =", area_split) bmin = x0 - 0.5*nbpts*dx_L1 - (order+1)*0.5*dx_L1 bmax = x0 + 0.5*nbpts*dx_L1 + (order+1)*0.5*dx_L1 plt.plot(x,shape) plt.plot(x,shape_split,'red') for ik in ik_l: plt.plot(x,split_tab[ik,:],'r--') plt.xlim(bmin, bmax) #plt.legend([r"$L_0$, %.2f dx : $\rho$"%delta, r"$L_1$, %.2f dx : $\rho$"%delta]) plt.xlabel(r"$\xi$",size=20) ; plt.ylabel(r"$S(\xi)$",size=20) # In[ ]: # In[ ]: # In[374]: # GENERAL SCRIPT FOR # ARBITRARY ORDER AND RF = 3 NbPoints = 10000 xmin = -5. xmax = 5. Lmax = np.abs(xmax - xmin) dx = Lmax/NbPoints print("dx = %f" %dx) x = Getx(NbPoints, xmin, xmax) # We set RF=3 # Specialized script for RF=3 # and arbitrary order RF = 3. x0 = 2. dx_L0 = 1. dx_L1 = dx_L0/RF # Arbitrary order order=3 shape = getShape(order, x, x0, dx_L0) print("RF = %.2f"%RF) print("order = %d"%order) nbpts = 2*(order+1)+1 print("nbpts = 2*(order+1)+1") print("nbr of points = %d"%nbpts) nt = order+1 # Calcul des coefficients w = np.array([float(trinomial(nt, y)) for y in range(-nt, nt+1)]) print(w) w[:] = w[:]/RF**order print(w) ik_l = np.arange(nbpts) print(ik_l) wtot = np.sum(w) print("wtot = %.2f"%wtot) split_tab = np.zeros((nbpts, len(x))) inum=-(nbpts-1)/2. for ik in ik_l: split_tab[ik,:] = w[ik]*getShape(order, x, x0 + float(inum)*dx_L1, dx_L1) print(inum) inum=inum+1 shape_split = split_tab.sum(axis=0) # Compute the area using the composite Simpson's rule. area_ref = scint.simps(shape, dx=dx) Asplit_tab = np.zeros(nbpts) for ik in ik_l: Asplit_tab[ik] = scint.simps(split_tab[ik,:], dx=dx) print("Asplit_tab[%d] = %f"%(ik, Asplit_tab[ik])) print("area ref=", area_ref) area_split = np.sum(Asplit_tab) print("Sum split areas =", area_split) area_split = scint.simps(shape_split, dx=0.001) print("Sum split areas =", area_split) bmin = x0 - 0.5*nbpts*dx_L1 - (order+1)*0.5*dx_L1 bmax = x0 + 0.5*nbpts*dx_L1 + (order+1)*0.5*dx_L1 plt.plot(x,shape) plt.plot(x,shape_split,'red') for ik in ik_l: plt.plot(x,split_tab[ik,:],'r--') plt.xlim(bmin, bmax) plt.xlabel(r"$\xi$",size=20) ; plt.ylabel(r"$S(\xi)$",size=20) # In[139]: # In[ ]: # In[346]: def f(x): return { 'a': 1, 'b': 2, }.get(x, 9) # In[348]: f('g') # In[349]: # In[ ]: # In[203]: # In[ ]: # In[ ]: # In[229]: ik_l = np.arange(5)+1 print(ik_l) # In[254]: j_l = np.arange(n+1) print(j_l) # In[ ]: # In[ ]: # In[238]: a=range(-3, 3+1) print(a) # In[ ]: # In[204]: n=2 for k in range(2*(n+1)): print( trinomial(n,k) ) # In[ ]: # In[ ]: # In[ ]: # In[ ]: # In[ ]: # In[92]: aa=np.zeros(5) # In[93]: print(aa) # In[98]: np.size(aa) # In[101]: ind=np.arange(5)+1 # In[106]: ind # In[108]: np.sum(ind) # In[ ]: # In[ ]: # In[ ]: # In[ ]:
82b3a028b794949ff9eebb7f840266b4f4263ece
SyntaxStacks/Dev-test-project
/1-finding-the-source/measurements.py
610
3.703125
4
from reading import Reading class Measurements(): def __init__(self): self.measurements = [] def readMeasurementsFile(self, fileName): try: with open(fileName, 'r') as inputFile: for line in inputFile: x, y, distance = line.split() self.addMeasurement(Reading(x, y, distance)) except Exception, e: self.measurements = [] raise Exception("Unable to read measurements from file.") def addMeasurement(self, reading): if reading not in self.measurements: self.measurements.append(reading) def printMeasurements(self): for reading in self.measurements: print(reading)
eb7037eca42d1d6e9ff91231fbbd81d67d781aa7
derekhua/Advent-of-Code
/Day23/Solution.py
3,902
3.734375
4
''' --- Day 23: Opening the Turing Lock --- Little Jane Marie just got her very first computer for Christmas from some unknown benefactor. It comes with instructions and an example program, but the computer itself seems to be malfunctioning. She's curious what the program does, and would like you to help her run it. The manual explains that the computer supports two registers and six instructions (truly, it goes on to remind the reader, a state-of-the-art technology). The registers are named a and b, can hold any non-negative integer, and begin with a value of 0. The instructions are as follows: hlf r sets register r to half its current value, then continues with the next instruction. tpl r sets register r to triple its current value, then continues with the next instruction. inc r increments register r, adding 1 to it, then continues with the next instruction. jmp offset is a jump; it continues with the instruction offset away relative to itself. jie r, offset is like jmp, but only jumps if register r is even ("jump if even"). jio r, offset is like jmp, but only jumps if register r is 1 ("jump if one", not odd). All three jump instructions work with an offset relative to that instruction. The offset is always written with a prefix + or - to indicate the direction of the jump (forward or backward, respectively). For example, jmp +1 would simply continue with the next instruction, while jmp +0 would continuously jump back to itself forever. The program exits when it tries to run an instruction beyond the ones defined. For example, this program sets a to 2, because the jio instruction causes it to skip the tpl instruction: inc a jio a, +2 tpl a inc a What is the value in register b when the program in your puzzle input is finished executing? Your puzzle answer was 307. --- Part Two --- The unknown benefactor is very thankful for releasi-- er, helping little Jane Marie with her computer. Definitely not to distract you, what is the value in register b after the program is finished executing if register a starts as 1 instead? Your puzzle answer was 160. Both parts of this puzzle are complete! They provide two gold stars: ** ''' instructions = [] with open('input.txt', 'r') as f: instructions = f.readlines() f.close() # Registers a = 1 b = 0 i = 0 while i < len(instructions): s = [x.strip() for x in instructions[i].split()] print '[' + str(i) + '] ' + str(s) if 'hlf' == s[0]: if 'a' in s[1]: a /= 2 else: b /= 2 i += 1 elif 'tpl' == s[0]: if 'a' in s[1]: a *= 3 else: b *= 3 i += 1 elif 'inc' == s[0]: if 'a' in s[1]: a += 1 else: b += 1 i += 1 elif 'jmp' == s[0]: if '+' in s[1]: s[1] = s[1].replace('+', '') i += int(s[1]) else: s[1] = s[1].replace('-', '') i -= int(s[1]) elif 'jie' == s[0]: if 'a' in s[1]: if a % 2 == 0: if '+' in s[2]: s[2] = s[2].replace('+', '') i += int(s[2]) else: s[2] = s[2].replace('-', '') i -= int(s[2]) else: i += 1 elif 'b' in s[1]: if b % 2 == 0: if '+' in s[2]: s[2] = s[2].replace('+', '') i += int(s[2]) else: s[2] = s[2].replace('-', '') i -= int(s[2]) else: i += 1 elif 'jio' == s[0]: if 'a' in s[1]: if a == 1: if '+' in s[2]: s[2] = s[2].replace('+', '') i += int(s[2]) else: s[2] = s[2].replace('-', '') i -= int(s[2]) else: i += 1 elif 'b' in s[1]: if b == 1: if '+' in s[2]: s[2] = s[2].replace('+', '') i += int(s[2]) else: s[2] = s[2].replace('-', '') i -= int(s[2]) else: i += 1 print 'a:' + str(a) + ' b:' + str(b) print b
abcb44271f775567bdce6e843debab8828da714d
fulv1o/Python-Basics
/Tipos de Dados/exemplo9.py
300
3.625
4
""" Fúlvio Taroni Monteforte Aluno de engenharia de computação do CEFET-MG. """ """ Exercícios retirados da geek university Leia uma temperatura em graus Celsius e apresente-a convertida em Kelvin. """ c = float(input("Informe a temperatura em graus Celsisu: ")) k = c+273.15 print(f'A temperatura é {k:.2f}K')
3544ebfc62a845356437e2712d8867a3a4983f4a
heathermoses/SI-Sessions
/Week7/kahoot.py
283
3.625
4
""" Questions for Kahoot Quiz Session 7 A """ def foo(start, stop): if start == 0 and stop == 0: print("Invalid start and stop values") if start >= stop: return else: print(start) foo(start + 2, stop) def main(): foo(0, 11) main()
7d45e87a4f29ac2f3cd25a1536cf6c969c5f9cfe
hieugomeister/ASU
/CST100/Chapter_1/Chapter_1/Ch_1_Solutions/Ch_1_Projects/1.1/loops.py
4,453
3.796875
4
""" Author: Hieu Pham ID: 0953-827 Section: 82909 Date: 11/10/2014 Design a function, using 2 loops, to print 10 lines of decimal numbers, from 0 to 9, on each line. Part 1 """ import string #Potential need for string functions import math def printstring(tn,xs): #Printing function """ Use 2 variables to pass into the function for robustness. tn is the triggering number, tn = -1 will print all digits. otherwise, the lines will be whatever tn value is. xs is just 10 for now """ if (tn > -1) and (tn <= 9): for x in range(xs): #Outer loop for line iteration print("\n") #Need this new line to meet the output requirement for y in range(xs): #Inner loop for horizontal printing print(tn,end=' ') #User defined format, which is a #digit followed by a white space elif tn == -1: for x in range(xs): #Outer loop for line iteration print("\n") #Need this new line to meet the output requirement for y in range(xs): #Inner loop for horizontal printing print(y,end=' ') #User defined format, which is a #digit followed by a white space else: print("Must be single digit, please!\n") printstring(-1,10) #call the function, using a digit as an argument. """ Author: Hieu Pham ID: 0953-827 Section: 82909 Date: 11/10/2014 Design a function, using 2 loops, to print 10 lines of decimal numbers, from 0 to 9, on each line. Part 2 """ def printstringtp2(xs): #Printing function """ Use 1 variable to pass into the function for robustness. Print the digits in a right triangle pattern """ for x in range(xs+1): #Outer loop for line iteration print("\n") for y in range(x): print(y,end=' ') printstringtp2(10) #call the function, using a digit as an argument. """ Author: Hieu Pham ID: 0953-827 Section: 82909 Date: 11/10/2014 Design a function, using 2 loops, to concatenate digits and then print out in descending order following an up-side-down isosceles triangle pattern Part 3 """ def printout1(x): #Build a string of digits and spaces y2 = '' #Place holder for summing pattern for y in range(x): #Digits based on given input x y2 = y2 + str(y) + ' ' #summing pattern return y2 #return constructed string to caller xs = 10 #initialize xs to 10 for i in range(10): #loop to add leading spaces to strings yz = printout1(xs) #build the string in reducing order yz = ((' ' * i) + yz) #Add leading white spaces print(yz) #print out to screen print("\n") #Give a new line on screen xs -= 1 #reduce xs to create isosceles triangle effect """ Author: Hieu Pham ID: 0953-827 Section: 82909 Date: 11/11/2014 Design a functions to print out prebuilt array in Floyd indexing pattern. Part 4 """ def floyd(nary,n): #Function to print an array using Floyd's pattern count = 1 #Initialize forward count (Floyd pattern is 1, 2-3, 4-5-6 for i in range(1,n+2): #Outer loop goes from 1 to 10 for j in range(1,i): #Inner loop goes from 1 to i print(nary[count-1],end=' ') #Print out array at index 0 count = count + 1 #Increments count print("\n") #Print it out def trianglenumbers(xs): #Function to construct a triangular number array return [(n*(n+1)//2) for n in range(xs)] def generatenumbers(mn,mx): #Function to add 10 to existing triangular number array return [(n+10) for n in range(mn,(mx),1)] def repacknumbers(numblist,size): #Function to pack array from 10 on nnl = [] #Create a list for n in range(size): #Only use numbers from 10 to 54, inclusive nnl.append(numblist[n]) #Build the new array return nnl #Return it to caller a = trianglenumbers(11) #Create a triangular array of triangular numbers maxnumb = (max(a) - 1) #Get the max number from triangular number array minnumb = min(a) #Get the min number from triangular number array b = generatenumbers(minnumb,maxnumb) #Generate new triangular number from 10 on c = repacknumbers(b,45) #Repack array into a printable one d = len(c) #Obtain the array size floyd(c,9) #Use the Floyd array indexing rule to print.
dffe738b820809fa047f6a8f2f9d50485601798d
chc1129/introducing-python3
/chap04/codeStr.py
3,306
3.71875
4
# 60 sec/min * 60 min/hr * 24 hr/day seconds_per_day = 86400 seconds_per_day = 86400 # 60 sec/min 60 min/hr * 24 hr/day # I can say anything here, even if Python doesn't like it, # because I'm protected by the awesome # octothorpe. print("No comment: quotes make the # harmless.") alphabet = '' print(alphabet) alphabet += 'abcdefg' print(alphabet) alphabet += 'hijklmnop' print(alphabet) alphabet += 'qrstuv' print(alphabet) alphabet += 'wxyz' print(alphabet) alphabet = 'abcdefg' + \ 'hijklmnop' + \ 'qrstuv' + \ 'wxyz' print(alphabet) print(1 + 2 + \ 3) disaster = True if disaster: print("Woe!") else: print("Whee!") furry = True small = True if furry: if small: print("It's a cat.") else: print("It's a bear!.") else: if small: print("It's a skink!") else: print("It's a human. Or a hairless bear.") color = "puce" if color == "red": print("It's a tomato") elif color == "green": print("It's a green pepper") elif color == "bee purple": print("I don't know what it is, but only bees can see it") else: print("I've never heard of the color", color) x = 7 print(x == 5) print(x == 7) print(5 < x) print(x < 10) print(5 < x and x < 10) print((5 < x) and (x < 10)) print(5 < x or x < 10) print(5 < x and x > 10) print(5 < x and not x > 10) print(5 < x < 10) print(5 < x < 10 < 999) some_list = [] if some_list: print("There's something in here") else: print("Hey, it's empty!") count = 1 while count <= 5: print(count) count += 1 numbers = [1, 3, 5] position = 0 while position < len(numbers): number = numbers[position] if number % 2 == 0: print('Found even nmber', number) break position += 1 else: # breakが呼び出されない print('No even number found') rabbits = ['Flopsy', 'Mopsy', 'Cottontail', 'Pater'] current = 0 while current < len(rabbits): print(rabbits[current]) current += 1 print() for rabbit in rabbits: print(rabbit) print() word = 'cat' for letter in word: print(letter) accusation = {'room': 'ballroom', 'weapon': 'lead pipe', 'person': 'Col. Mustard'} for card in accusation: # または for card in accusation.keys(): print(card) for value in accusation.values(): print(value) for item in accusation.items(): print(item) for card, contents in accusation.items(): print('Card', card, 'bas the contents', contents) cheeses = [] for cheese in cheeses: print('This shop has some lovely', cheese) break else: # breakしていないということはチーズがないということ print('This is not much of a cheese shop, is it?') days = ['Monday', 'Tuesday', 'Wednesday'] fruits = ['banana', 'orange', 'peach'] drinks = ['coffee', 'tea', 'beer'] desserts = ['tiramisu', 'ice cream', 'pie', 'puddingi'] for day, fruit, drink, dessert in zip(days, fruits, drinks, desserts): print(day, ": drink", drink, "- eat", fruit, "- enjoy", dessert) english = 'Monday', 'Tuesday', 'Wednesday' french = 'Lundi', 'Mardi', 'Mercredi' print(list( zip(english, french) )) print(dict( zip(english, french) )) for x in range(0, 3): print(x) print(list( range(0, 3) )) for x in range(2, -1, -1): print(x) print(list( range(2, -1, -1) )) print(list( range(0, 11, 2) ))
6b9924405c3393e7d7b4f405651fe5fd4eb6bd03
Kaushal1599/SkitCollege
/Enodes/media/Answer/numberdigit.py
497
3.6875
4
import math n = int(input()) numbers = list(map(int, input().split())) xor = 0 array = [] def printDivisors(n): global array i = 1 while i <= math.sqrt(n): if (n % i == 0): if (n / i == i): array.append(i) else: array.append(i) array.append(n//i) i = i + 1 for i in numbers: printDivisors(i) for i in array: xor = xor ^ i if xor == 0: print("JASBIR") else: print("AMAN")
02bac731615300b70a3c3f68698bddfadd7a3063
callmeislaan/LearnPython
/hello.py
111
3.890625
4
def hello(): name = input("input your name: ") return name name = hello() print("hello " + name + "!")
bfcf74bfa58b26d5f1f7bef719b1e53b5db11797
kenolheiser/try_git
/test_unittest.py
676
3.90625
4
#!/usr/bin/env python ''' Try some unit tests on the sample ''' import unittest from sample_code import is_divisible class TestIsDivisible(unittest.TestCase): def test_divisible_numbers(self): self.assertTrue(is_divisible(10, 2)) self.assertTrue(is_divisible(10, 10)) self.assertTrue(is_divisible(1000, 1)) def test_not_divisble_numbers(self): self.assertFalse(is_divisible(5, 3)) self.assertFalse(is_divisible(5, 6)) self.assertFalse(is_divisible(10, 3)) def test_dividing_by_0(self): with self.assertRaises(ZeroDivisionError): is_divisible(1,0) if __name__ == '__main__': unittest.main()
bf9914816fd8c6e989a785dc7b9e6f0edc45aa86
Aathish04/Old-Python-Game-Projects
/PyRPG/PyRPG.py
1,469
3.59375
4
#Code Setting Up Starts # All Modules are imported import time import random hp=30 count=0 peg="false" #All functions are defined def get_input(prompt, accepted): # This function returns an error message if the input doesnt make sense. while True: value=input(prompt).lower() if value in accepted: return value else: print("This is not a recognised answer. It must be one of", accepted) def handle_room(location): #This function handles where the player will be, the forest, the village, etc. global hp global player global count global speed global peg global inventory # The actual Game Starts Here. if location=="start": time.sleep(1) choice=get_input("Welcome, traveller. Now, what species might you be? \nWe only cater to dwarves,humans or elves. \n >", ["human","elf","dwarf"]) if choice=="human": return "human" if choice=="dwarf": return "dwarf" if choice=="elf": return "elf" if location=="human": print("The human is equipped with a small sheild and sword.") equip=get_input("Be a Human?\n >",["yes","no"]) if equip=='no': return "start" if equip=="yes": player="human" return "Dungeon" #Do not remove, change or in any way edit the code below. location="start" while location != "end": location=handle_room(location)
041a57f8ce0eb5e43f8424bea4d11b8d280043ec
Vipinraj9526/Python
/rect3.py
703
4.03125
4
#create Rectanglr class with atribute lenght and breadth and method to find area and perimeeter. #Compare two Rectangle object by thier area. class Rectangle: def __init__(self,length,breadth): self.length=length self.breadth=breadth def area(self): return (self.length*self.breadth) def perimeter(self): return (2*(self.length+self.breadth)) r1=Rectangle(4,5) r2=Rectangle(9,2) print("Area of 1st Rectangle:",r1.area()) print("Area of 2nd Rectangle:",r2.area()) print("Perimeter of 1st Rectangle:",r1.perimeter()) print("Perimeter of 2nd Rectangle:",r2.perimeter()) if r1.area()>r2.area(): print("first area is grater") else: print("second area is grater")
7bd182a2987bf222028b22135867160e93eb8381
Selidex/holbertonschool-higher_level_programming
/0x10-python-network_0/6-peak.py
526
3.6875
4
#!/usr/bin/python3 """ Test function find_peak """ def find_peak(list_of_integers): """Tests the peak of the list""" loi = list_of_integers if loi is None or len(loi) == 0: return None start = 0 end = len(loi) - 1 while start < end: mid = start + (end - start) // 2 if loi[mid] > loi[mid - 1] and loi[mid] > loi[mid + 1]: return loi[mid] if loi[mid - 1] > loi[mid + 1]: end = mid else: start = mid + 1 return loi[start]
6c29d66c9c24004a538f0f469c03d557c600e89b
shehryarbajwa/Algorithms--Datastructures
/trees/depth_first_search_pre_order.py
5,990
4.15625
4
# There are a total of 10 functions for the Node class that we rely on # 1-Initializing the Node class with value, left, right # 2-Set value of the Node # 3-Get value of the Node # 4-Set the left child of the Node by passing in a node # 5-Set the right child of the Node by passing in a node # 6-Get the left child of the Node - the node object # 7-Get the right child of the Node - the node object # 8-Check if left child exists - return True/False # 9-Check if right child exists - return True/False # For the Tree Class, we need to set up the initial root value # 1-Set up the root value # 2-Get the root value # For the state Class # 1-Node's value # 2-Check if left node is visited # 3-Check if right node is visited # 4-Get True/False if left node is visited # 5-Get True/False if right node is visited # 6-Set the value to True if left node is visited # 7-Set the value to True if right node is visited class Node(object): def __init__(self, value=None): self.value = value self.left = None self.right = None def get_value(self): return self.value def set_value(self, value): self.value = value def set_right_child(self, Node): self.right = Node def set_left_child(self, Node): self.left = Node def get_right_child(self): return self.right def get_left_child(self): return self.left def has_left_child(self): return self.left != None def has_right_child(self): return self.right != None def __repr__(self): return f"Node({self.get_value()})" def __str__(self): return f"Node({self.get_value()})" class Tree(object): def __init__(self, value): self.root = Node(value) def get_root(self): return self.root class State(object): def __init__(self, node): self.node = node self.visited_left = False self.visited_right = False def get_node(self): return self.node def get_visited_left(self): return self.visited_left def get_visited_right(self): return self.visited_right def set_visited_left(self): self.visited_left = True def set_visited_right(self): self.visited_right = True class Stack(): def __init__(self): self.list = list() def push(self,value): self.list.append(value) def pop(self): return self.list.pop() def top(self): if len(self.list) > 0: return self.list[-1] else: return None def is_empty(self): return len(self.list) == 0 def pre_order(tree): visited_list = list() stack = Stack() #We fetch the node value from the root value of the Node node = tree.get_root() visited_list.append(node.get_value()) #We create the state which contains the node and provide it the node state = State(node) #Then on the stack we push the state which is just the node and references to left and right child if they have been visited stack.push(state) count = 0 while(node): print(f""" loop count: {count} current node: {node} stack:{stack} """) count += 1 if node.has_left_child() and not state.get_visited_left(): state.set_visited_left() #Get the next node by getting the root's left child node = node.get_left_child() visited_list.append(node.get_value()) #Next we set the state again with the Node value to be 'B' state = State(node) stack.push(state) elif node.has_right_child() and not state.get_visited_right(): state.set_visited_right() node = node.get_right_child() visited_list.append(node.get_value()) state = State(node) stack.push(state) else: #Pop the value of D stack.pop() if not stack.is_empty(): #State becomes the head value of the stack which now will be 'B' #Thus the node's value also becomes B state = stack.top() node = state.get_node() else: node = None return visited_list ## Using recursion to solve the problem def pre_order_tree(Tree): visit_order = list() root = Tree.get_root() def traverse(node): if node: #Visit the element visit_order.append(node.get_value()) #Traverse left traverse(node.get_left_child()) #Traverse right traverse(node.get_right_child()) traverse(root) return visit_order # In pre_order_tree we start with Apples, left child Banana, left child Dates, and Apple's right child Cherry # The root is apple # We use apple and run the traverse function # In our visit_order list we append Apple # Then we do recursion # We then recurse # At a time we first run the traverse(left_child function) and once it finishes run the traverse(right_child) function # So we provide traverse with the left child which is Banana # It runs the function and appends Banana to the list # It then runs Dates function # Meanwhile when dates finishes, Banana checks for a right child # If it is none the function finishes # All this keeps happening while Apple checks for the right node aswell Node0 = Node("Apple") Node1 = Node('Banana') Node2 = Node('Orange') Node3 = Node('Pomegrenate') Node0.set_left_child(Node1) Node0.set_right_child(Node2) Node1.set_left_child(Node3) print(f""" value: {Node0.value} left: {Node0.left.value} right: {Node0.right.value} """) tree = Tree("apple") tree.get_root().set_left_child(Node("banana")) tree.get_root().set_right_child(Node("cherry")) tree.get_root().get_left_child().set_left_child(Node("dates")) # (pre_order(tree)) print(pre_order_tree(tree))
86995c5a47bcda7d24d9355f16071b0e1951ac44
18101555672/LearnPython
/MOOC_Python/week_01/python_01.py
803
3.984375
4
# 实例1:温度转换 def temperatureChang(value,unit='F'): if unit == 'F': return '{}℃ ==> {:.2f}℉'.format(value,value*9/5+32) elif unit == 'C': return '{}℉ ==> {:.2f}℃'.format(value,5/9*(value-32)) else: return 'The second parameter please enter F or C' print(temperatureChang(18,'F')) print(temperatureChang(84,'C')) print(temperatureChang(55,'A')) TempStr = input('请输入带有符号的温度值:') if TempStr[-1] in ['F','f']: # eval() 去掉参数最外侧引号并执行余下语句 C = (eval(TempStr[0:-1]) - 32) / 1.8 print('转换后的温度是{:.2f}℃'.format(C)) elif TempStr[-1] in ['C','c']: F = 1.8*eval(TempStr[0:-1]) + 32 print('转换后的温度是{:.2f}℉'.format(F)) else: print('输入格式错误')
f23e24e975d33c6f288e3789adfb53130fec1098
nickbuker/python_practice
/src/integer_depth.py
471
4.0625
4
""" The depth of an integer n is defined to be how many multiples of n it is necessary to compute before all 10 digits have appeared at least once in some multiple. https://www.codewars.com/kata/integer-depth/python """ def compute_depth(n): bools = 10 * [False] depth = 1 while True: digits = map(int, list(str(n * depth))) for m in digits: bools[m] = True if all(bools): return depth depth += 1
0d2cef3842d47d3d1169707122f7b8b04998d0f9
sivasai2467/siva-sai-kumar-reddy
/largestnum.py
132
3.71875
4
a=int(raw_input()) b=int(raw_input()) c=int(raw_input()) if (a>b) and (a>c): print a elif (b>c) and (b>a): print b else: print c
6a8f19438029dd5c2c820f6facf2eab62fc21986
payneal/price_picker_TDD
/test_price.py
2,558
3.671875
4
# test cases import unittest from price import Price class Test_Price_Case(unittest.TestCase): def setUp(self): self.price = Price(); def tearDown(self): pass def test_the_the_price_is_rounded_down_two_decimal_points(self): product_a = { "original": 2.91, "minimum": 2.89, "maximum": 2.97} new_product_a = self.price.price_optimisation(product_a, [2, 3, 7]) self.assertEqual( new_product_a["new_price"], 2.92); def test_new_price_inbetween_min_and_max(self): product_a = { "original": 2.91, "minimum": 2.89, "maximum": 2.97} new_product_a = self.price.price_optimisation(product_a, [2, 3, 7]) self.assertGreaterEqual( new_product_a["new_price"], product_a["minimum"]); self.assertLessEqual( new_product_a["new_price"], product_a["maximum"]); def test_new_price_second_decimal_must_be_in_price_points(self): product_a = { "original": 2.91, "minimum": 2.89, "maximum": 2.97} new_product_a = self.price.price_optimisation(product_a, [2, 3, 7]) # get second element in a string new_price = str(new_product_a['new_price']) new_price = int(new_price[-1:]) if new_price in [2, 3, 7]: self.assertEqual(True, True) else: self.assertEqual(False, True) def test_new_price_is_as_close_as_possible_to_original_price(self): product_a = { "original": 2.91, "minimum": 2.89, "maximum": 2.97} new_product_a = self.price.price_optimisation(product_a, [2, 3, 7]) self.assertEqual( new_product_a["new_price"], 2.92); def test_2_the_the_price_is_rounded_down_two_decimal_points(self): product_b = { "original": 3.64, "minimum": 3.69, "maximum": 3.73} new_product_b = self.price.price_optimisation(product_b, [2, 3, 7]) self.assertEqual( new_product_b["new_price"], 3.72); def test_3_the_the_price_is_rounded_down_two_decimal_points(self): product_c = { "original": 3.65, "minimum": 3.65, "maximum": 3.66} new_product_c = self.price.price_optimisation( product_c, [2, 3, 7]) self.assertEqual( new_product_c["new_price"], "No price point withmin / max range"); if __name__ == '__main__': unittest.main()
c1d14128f7e029d3b1a95dd3936908c40a0f763b
justinba1010/Pen-Academy-Python
/CoolStuff/RedBlackTree.py
2,655
3.71875
4
class RedBlackTree: class Node: def __init__(self,data, color = False): self.color = color#True for red, false for black self.data = data self.right = None self.left = None def add(self, data): #Is there a root? if self.root == None: self.root = self.Node(data) return self.__add(self.root, data) def __add(self, currNode, data): #Which way? if(data > currNode.data): #Right if(currNode.right != None): self.__add(currNode.right, data) else: #This is a leaf currNode.right = self.Node(data, True) else: if(data > currNode.data): if(currNode.left != None): self.__add(currNode.left, data) else: currNode.left = self.Node(data, True) def remove(self, data): node = self.__search(self.root, None, data) if(node): child = node[0] parent = node[1] if(child.right != None and child.left != None): pass def str(self): self.__str(self.root) def __str(self, currNode): print(currNode.data) if(currNode.right): __str(self, currNode.right) if(currNode.left): __str(self,currNode.left) def search(self,data): return self.__search(self.root, None, data)[0].data def __search(self, currNode, parent, data): if currNode == None: return None if data == currNode.data: return (currNode, parent) if data > currNode.data: return self.__search(currNode.right, currNode, data) else: return self.__search(currNode.left, currNode, data) def preorder(self): self.__preorder(self.root,0) def postorder(self): self.__preorder(self.root,2) def inorder(self): self.__preorder(self.root,1) def __preorder(self,currNode,x): if(currNode): if x == 0: print(currNode.data) self.__preorder(self,currNode.left) if x == 1: print(currNode.data) self.__preorder(self,currNode.right) if x == 2: print(currNode.data) def __rightChildLeftRotation(self,parent): if(parent == None): return if(parent == self.root): self.__rightChildLeftRotationRoot() return child = parent.right if(child == None): return if(child.right == None): return if(child.right.right == None): return parent.right = child.right child.right = child
78477d2e1f9958a03e9c011146ccd7535afb5954
KaijuVandel/Bioinformatics
/math_functions/variance.py
561
4.28125
4
#!/usr/bin/env python import sys def average(x): tmp=0.0 n=len(x) for number in x: tmp=tmp+float(number) result=tmp/n return result def variance(numbers): '''This function takes in input a list of number and computes the variance''' n=len(numbers) total=0.0 avg=average(numbers) for value in numbers: value=float(value) total=total + (value-avg)**2 total=total/(n-1) return total if __name__=="__main__": series=sys.argv[1].split(',') average(series) final=variance(series) print "The variance is equal to", final
558508d95037a7d732fe31327d33d79f8f8c202a
buptconnor/myleet
/solved/P96_numTrees.py
335
3.609375
4
__author__ = 'Connor' class Solution: # @return an integer def numTrees(self, n): if n == 0 or n == 1: return 1 ans = 0 for i in range(n): ans += self.numTrees(i) * self.numTrees(n-1-i) return ans if __name__ == '__main__': so = Solution() print(so.numTrees(3))
1d2305b0666b9e7a3ecc293ce345c58685f1315f
ahmetoz/algo-assigment
/problem2/inversion.py
1,617
4.3125
4
import random """ Bilmuh 543 => Assigment 3 - Problem 2 ---------------------------------------- The counting inversion algorithm The difference from merge sort algorithm is that we want to do something extra: not only should we produce a single sorted list from A and B, but we should also count the number of "inverted pairs" The SortAndCount algorithm correctly sorts the input list and counts the number of inversions; It runs in O(n log n) time for a list with n elements MergeAndCount algorithm takes O(n) time Ahmet Oz 91140000121 """ def SortAndCount(L): # if list L has one element l = len(L) if l <= 1 or L is None: return 0, L # Divide the list two halves A and B m = l // 2 A = L[:m] B = L[m:] # Find inversions and return sorted list L ra, A = SortAndCount(A) rb, B = SortAndCount(B) r, L = MergeAndCount(A, B) return r, L def MergeAndCount(A, B): count = 0 M = [] # while both list A and B not empty while A and B: if A[0] <= B[0]: M.append(A.pop(0)) else: # if B[0] = current pointer is smaller than A[0] count += len(A) M.append(B.pop(0)) # merged list M M += A + B # return inversion count and merged list return count, M if __name__ == '__main__': n = 10 my_randoms = random.sample(xrange(1, 101), n) print '\nList before: ' print my_randoms inversion_count, sorted_list = SortAndCount(my_randoms) print '\nNumber of inversions: ', inversion_count print '\nSorted List: ' print sorted_list
e0286c528496c096d93bbef9f429edd8a0e04598
sandeepshiven/python-practice
/advance python modules/collection modules/counter.py
1,324
3.875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Aug 24 19:04:08 2019 @author: sandeep """ from collections import Counter # counter with list my_list = [1,1,0,0,0,0,1,5,5,5,3,3,2,-2,2,-3,-3,-3,-2,3,8,9,9,-2,4,1,2,8,8,64,66,1,48,88,888,11,1,1,3,6,6,6,4,4,7] print(Counter(my_list)) # prints the elements as keys and the number of time it repeats as value # counter with strings string = 'asdkfpwrksldnvaghhurtadsfnvaadfjkghiutahsdfkjvnkbvkjsdfhausiuastjkbvkjhdskjahkjvngjfsghughkcvn' print('\n\n',Counter(string)) string1 = 'my name is sandeep shiven my name is sandeep sandeep is is is is my my' print('\n\n',Counter(string1.split())) c = dict(Counter(string1.split())) # creates a counter object print('\n\n',c) #print('\n\n',c.most_common(2),'\n\n') # returns list of the two most common list1 = Counter(my_list) print(sum(list1.values())) # total of all counts print(list(list1)) # list of unique elements print('\n\n',set(list1)) # convert to a set print('\n\n',dict(list1)) # convert to regular dictionary list2 = list1.items() print('\n\n',list1.items()) # convert to a list of (elem,cnt) pairs print('\n\n',Counter(dict(list2))) # coverts from a list of (elem,cnt ) pairs print('\n\n',list1.most_common()[:-3-1:-1]) # n least common elements list1 += Counter() print('\n\n',list1)
a34d4af8152549623f38df6bc63aa246c7740bba
carloshssouza/UniversityStudies
/ProjectsGitHub/Python/Ordering_Methods/InsertionSort.py
338
3.859375
4
def insertionSort(vet): cont = 1 for cont in range(len(vet)): aux = vet[cont] j = cont-1 while j>= 0 and aux < vet[j]: vet[j+1] = vet[j] j -= 1 vet[j+1] = aux n = 5 vet = [] for i in range(n): vet.append(int(input('Type a number: '))) insertionSort(n, vet) print(vet)
3d3ca4bdd5f4452e8f00cf56314f38996ce3edc2
nyucusp/gx5003-fall2013
/kll392/assignment4/problem1.py
3,035
3.578125
4
#Kara Leary #Urban Informatics - Assignment 4 #Problem 1 import MySQLdb import csv db = MySQLdb.connect(host="localhost", user="kll392", passwd="Maywalsh1", db="coursedb") cur = db.cursor() #Create boroughs table: createBoroughs = "create table boroughs (zip int not null, borough varchar(255), primary key(zip))" cur.execute(createBoroughs) #Create zip codes table: createZipCodes = "create table zipcodes (zip int not null, area double, population int, primary key(zip))" cur.execute(createZipCodes) #Create incidents table: createIncidents = "create table incidents (incidentID int not null, address varchar(255), zip int, primary key(incidentID))" cur.execute(createIncidents) #Insert values from boroughs.csv into boroughs table: with open('boroughs.csv') as f: rows = csv.reader(f, delimiter=',') for row in rows: zip = row[0] borough = row[1].lower() #Check for duplicate values of zip codes in table: checkDuplicates = "(SELECT * FROM boroughs WHERE zip =" + zip + ");" if cur.execute(checkDuplicates) != 1: insertCommand = "insert into boroughs values(" + str(zip) + "," + "'" + borough + "');" cur.execute(insertCommand) #Insert values from zipcodes.csv into zipcodes table: with open('zipCodes.csv') as f: rows = csv.reader(f, delimiter=',') rows.next() for row in rows: #Only add value to table if the zip code has a population entry associated with it: if (row[10] != ''): zip = row[0] area = row[7] population = row[10] #Check for duplicate zip codes- if duplicate exists, assume the first one is correct: checkDuplicates = "(SELECT * FROM zipcodes WHERE zip =" + zip + ");" if cur.execute(checkDuplicates) != 1: insertCommand = "insert into zipcodes values(" + str(zip) + "," + str(area) + "," + str(population) + ");" cur.execute(insertCommand) #This function tests for the object type; it will be used to help determine if a zip code value is null in the incident table: tests = [(int, int)] def getType(value): for typ, test in tests: try: test(value) return typ except ValueError: continue return str #Create primary key called "incidentID" incidentID = 0 with open('Incidents_grouped_by_Address_and_Zip.csv') as f: rows = csv.reader(f, delimiter=',') rows.next() for row in rows: incidentID += 1 address = row[0] #Replace any apostrophes in address column so that they do not affect the SQL query: address = address.replace("'", "''") zip = row[1] #If a zip code entry is empty or a string (i.e. N/A), make the entry null in SQL: if getType(zip) != int: zip = 'NULL' insertCommand = "insert into incidents values(" + str(incidentID) + "," + "'" + address + "'" + "," + str(zip) + ");" cur.execute(insertCommand) db.commit() db.close()
00c8035c8e2b386d94f39488f6324e795c34dd7a
matthewharrilal/CS-Questions-GRIND
/Leetcode Problems/majorityElement2.py
1,102
3.6875
4
class Solution(object): def majorityElement(self, nums): """ :type nums: List[int] :rtype: List[int] """ # We have to find the lower bound for how many times an element should appear lower_bound = math.ceil(len(nums) / 3) # Has to be higher than or equal frequency_dict = {} output = [] max_occurence = 1 if len(nums) == 1: return [nums[0]] for num in nums: if num not in frequency_dict: frequency_dict[num] = 1 else: frequency_dict[num] += 1 if frequency_dict[num] > max_occurence: output = [num] # Reset the array with the max element max_occurence = frequency_dict[num] # Updates max_occurence counter elif frequency_dict[num] == max_occurence and frequency_dict[num] > lower_bound: output.append(num) return output
9447848b21396bae8709996a968b7264ef4a2edb
siddhantprateek/Python-in-Practice
/BFS DFS/bfs2.py
4,739
3.875
4
from collections import deque class TreeNode: def __init__(self, val): self.value = val self.left, self.right = None, None class BST(): def __init__(self): self.root = None def insert(self, val): self.root = self.insertHelper(self.root, val) def insertHelper(self, node, value): if node == None: node = TreeNode(value) return node if value < node.value: node.left = self.insertHelper(node.left, value) if value > node.value: node.right = self.insertHelper(node.right, value) return node def isEmpty(self): return self.root == None def populatedWithSorted(self, nums): self.populatedWithSortedHelper(nums, 0, len(nums)) def populatedWithSortedHelper(self, nums, start, end): if start >= end: return mid = (start + end) // 2 self.insert(nums[mid]) self.populatedWithSortedHelper(nums, start, mid) self.populatedWithSortedHelper(nums, mid + 1, end) def bfs(self): if self.isEmpty(): return queue = deque() queue.append(self.root) while queue: # level size ls = len(queue) for _ in range(ls): # we are popping the node not the value popped = queue.popleft() print(popped.value, end = " ") if popped.left: queue.append(popped.left) if popped.right: queue.append(popped.right) print() def zigzag(self): ans = [] if self.isEmpty(): return ans queue = deque() queue.append(self.root) leftToRight = True while queue: # level size ls = len(queue) # queue of that level current = deque() for i in range(ls): popped = queue.popleft() if leftToRight: current.append(popped.value) else: current.appendleft(popped.value) if popped.left: queue.append(popped.left) if popped.right: queue.append(popped.right) ans.append(list(current)) leftToRight = not leftToRight return ans def rightView(self): ans = [] if self.isEmpty(): return ans queue = deque() queue.append(self.root) while queue: # level size: ls = len(queue) for i in range(ls): popped = queue.popleft() # when we are at the end of queue # we will insert it in current if i == ls - 1: ans.append(popped.value) if popped.left: queue.append(popped.left) if popped.right: queue.append(popped.right) return ans # left View # bottom View # top View def nextNodeLevel(self, key): if self.isEmpty(): return None queue = deque() queue.append(self.root) while queue: popped = queue.popleft() if popped.left: queue.append(popped.left) if popped.right: queue.append(popped.right) if popped.value == key: break if queue: return queue[0] return None # DFS def pathSum(self, sum): return self.pathSumHelper(self.root, sum) def pathSumHelper(self, node, sum): if node == None: return False # the node have no child and the node value is equal to the sum if node.value == sum and node.left == None and node.right == None: return True return self.pathSumHelper(node.left, sum - node.value) or self.pathSumHelper(node.right, sum - node.value) def PathSum(self): pass # linked List # make a slow and fast # the get the cycle length # after that keep the fast at distance of cycle length # when slow == fast then at that point the start of the cycle def getCycleStart(): pass if __name__ == '__main__': bst = BST() bst.populatedWithSorted([1,2,3,4,5,6]) bst.bfs() print(bst.zigzag()) print(bst.rightView()) bst.nextNodeLevel(6) print(bst.pathSum(9))
4d2b5c5293ba2202d51053f34e115ee21f2430e5
Joseph-Macalinao/Learn
/exceptions.py
426
4.3125
4
#what to do with code so that a single error won't crash program #try: and except: are what you need to use ''' try: code block here except ErrorType: return/result ''' #example try: age = int(input('Age:')) income = 20000 risk = income / age print(age) except ZeroDivisionError: print('Age must be > 0') except ValueError: #if input type isn't an int, it will do this print('Invalid Value')
8c0c24baecaf3e9ab064e5f46967b2a0e120304d
PdxCodeGuild/20170626-FullStack
/lab04-rock_paper_scissors.py
1,584
4.53125
5
# lab 4: play rock-paper-scissors with the computer # 1) we get the user's choice # 2) we check to make sure that what the user entered was among the valid possibilities # 3) the computer randomly picks rock, paper, or scissors # 4) depending on the choices, the program declares a winner or a tie # below are the various combinations: # rock - rock # rock - scissors # rock - paper # scissors - rock # scissors - scissors # scissors - paper # paper - rock # paper - scissors # paper - paper import random rps = ['rock', 'paper', 'scissors'] user_choice = input('which do you choose: rock, paper, or scissors? ') print('user chooses: '+user_choice) if user_choice in rps: random_index = random.randint(0, 2) #get a random index: 0, 1, or 2 comp_choice = rps[random_index] #get a random choice of 'rock', 'paper' or 'scissors print('computer chooses: '+comp_choice) if user_choice == comp_choice: #we can eliminate 3 possibilities with one if print('tie!') elif user_choice == 'rock' and comp_choice == 'scissors': print('user wins!') elif user_choice == 'rock' and comp_choice == 'paper': print('computer wins!') elif user_choice == 'scissors' and comp_choice == 'rock': print('computer wins!') elif user_choice == 'scissors' and comp_choice == 'paper': print('user wins!') elif user_choice == 'paper' and comp_choice == 'rock': print('user wins!') elif user_choice == 'paper' and comp_choice == 'scissors': print('computer wins!') else: print('you entered an invalid string')
1018964f92bf3c10f53f5dec7c95650ace729567
amritat123/dictionary-questions
/last_value_in_dict.py
154
3.640625
4
import json my_dict={"key1": "value1", "key2": "value2"} j=0 for i in my_dict.keys(): if j==len(my_dict)-1: print(my_dict[i]) j+=1
78de581f46d7517aea1e943ec522564075b9f5a8
LeJeuxStudio/lejeuxstudiodocs
/price_calculator/user_input.py
3,495
3.65625
4
from tkinter import * from tkinter import ttk from calculator import calculate from shipping import SHIPPING_OPT from plan import PLAN_OPT from taxation import IMPORT_TAX from currency import get_currency TITLE = "Selling Price Calculator" def init(): window = Tk() window.title(TITLE) window.geometry('330x360') unit_price = StringVar() unit = StringVar() delivery = StringVar() len = StringVar() width = StringVar() height = StringVar() weight = StringVar() category = StringVar() shipping = StringVar() upc = StringVar() plan = StringVar() commission = StringVar() input_dict = { "unit_price": unit_price, "unit": unit, "delivery": delivery, "len": len, "width": width, "height": height, "weight": weight, "category": category, "shipping": shipping, "upc": upc, "plan": plan, "commission": commission } Label(window, text="Unit Price (CNY)").grid(row=0, column=0) Entry(window, textvariable=unit_price, justify=RIGHT).grid(row=0, column=1) Label(window, text="Units").grid(row=1, column=0) Entry(window, textvariable=unit, justify=RIGHT).grid(row=1, column=1) Label(window, text="Delivery (CNY)").grid(row=2, column=0) Entry(window, textvariable=delivery, justify=RIGHT).grid(row=2, column=1) Label(window, text="Length (CM)").grid(row=3, column=0) Entry(window, textvariable=len, justify=RIGHT).grid(row=3, column=1) Label(window, text="Width (CM)").grid(row=4, column=0) Entry(window, textvariable=width, justify=RIGHT).grid(row=4, column=1) Label(window, text="Height (CM)").grid(row=5, column=0) Entry(window, textvariable=height, justify=RIGHT).grid(row=5, column=1) Label(window, text="Weight (G)").grid(row=6, column=0) Entry(window, textvariable=weight, justify=RIGHT).grid(row=6, column=1) Label(window, text="Category").grid(row=7, column=0) ttk.Combobox(window, width=19, textvariable=category, values= \ list(IMPORT_TAX.keys())).grid(row=7, column=1) Label(window, text="Shipping Method").grid(row=8, column=0) ttk.Combobox(window, width = 19, textvariable = shipping, values=\ list(SHIPPING_OPT.keys())).grid(row=8, column=1) Label(window, text="UPC price (CNY)").grid(row=9, column=0) Entry(window, textvariable=upc, justify=RIGHT).grid(row=9, column=1) Label(window, text="Plan").grid(row=10, column=0) ttk.Combobox(window, width = 19, textvariable = plan, values=\ list(PLAN_OPT.keys())).grid(row=10, column=1) Label(window, text="Commission (%)").grid(row=11, column=0) Entry(window, textvariable=commission, justify=RIGHT).grid(row=11, column=1) Button(window, text="Submit", command=lambda: end(input_dict)).grid(row=12, column=1) window.mainloop() def end(input_dict): window = Tk() window.title(TITLE) window.geometry('350x200') selling_price = calculate(input_dict) sp_cny = round(selling_price / get_currency(), 2) text_1 = "To be profitable" text_2 = "The selling price needs to be higher than {} JPN".format(selling_price) text_3 = "which is {} in RMB".format(sp_cny) Label(window, text=text_1, width=250, anchor='w').grid(row=0, column=0) Label(window, text=text_2, width=250, anchor='w').grid(row=1, column=0) Label(window, text=text_3, width=250, anchor='w').grid(row=2, column=0) window.mainloop()
54ec747106717a3c3c5d4dcec7341bc4afac0e38
antoney1998/Codevita9
/Counting Palindromes/Solution.py
1,891
4.15625
4
from datetime import datetime from datetime import timedelta # code to take input durinng runtime could be added later here n1=1 n2=2 def check_palindrome(string):# returns true if string is palindrome reversed_string = string[::-1] #status=1 if(string==reversed_string): return True else: return False def next_time(prev_time): time_prev = datetime.strptime(prev_time,"%H%M%S")#given string in format hhmmss is converted to time(type) time_new = time_prev + timedelta(0,1)#time is incremented by one second time_new_string=time_new.strftime("%H%M%S")# time is converted to string return (time_new_string)# string is returned def count_palindromes(n1,n2): pal_count=0 #variable to count number of palindrome time_in='235959' # time initilized in format hhmmss .Taking the last second of the day (235959) and addinng one seconnd gives 000000. #thus the while loops checks for palinndroemm from 000000. time_thing=time_in # time is #variables for while loop count=n1 count_till=n2+1#checking the condition of whil emight help you understand why a day greater than n2 is taken #The input n1 and n2 are days.. the while loops until a day greater than n2 is reached while(count<count_till):# we coud also use the condition(a<=b) and increment a below time_thing=next_time(time_thing)#get next second in hhmmss format if(check_palindrome(str(count)+time_thing)==True):#Adds the day counter to the hhmmss and check for palindrome #print(str(count)+time_thing) #commment out the above line to print all the possible palindromes pal_count+=1 if(time_thing=='235959'):#checks if time has looped through every second of the day count+=1 #If the condition evaluates print(pal_count) count_palindromes(n1,n2)
62ed842e6a4f3e7dfd7ab603c719b3702c1b292c
dikoko/practice
/1 Numerics/1-05_total_num.py
1,284
4.03125
4
# 1-05. Total Number of Digits # Given an integer N, count all non-negative integers equal or less than N in which digit 3 is appearing. # e.g. N = 30 -> 4 (3, 13, 23, 30) # a brute-force solution def total_num_digit_bf(N): if N <= 0: return count = 0 for i in range(3, N+1): if '3' in str(i): count += 1 return count # better solution based on the geeksforgeeks def total_num_digit(N): # number of integers with digit 3 of d-length digit def _D(d): if d < 0: return 0 if d == 1: # 0~9 return 1 return 9*_D(d-1) + 10**(d-1) def _totalnum(n): if n < 3: return 0 if n >=3 and n < 10: return 1 # find the length of digits of n d = len(str(n)) # find the MSD (most significant digit) MSD = int(str(n)[0]) if MSD < 3: # 0,1,2 return MSD*_D(d-1) + _totalnum(n % 10**(d-1)) elif MSD == 3: return MSD*_D(d-1) + 1 + (n % 10**(d-1)) else: # MSD > 3 return (MSD-1)*_D(d-1) + 10**(d-1) + _totalnum(n % 10**(d-1)) return _totalnum(N) if __name__ == '__main__': N = 428 print(total_num_digit_bf(N)) print(total_num_digit(N))
3189d993628df0b3992446fe09ddfc1614c700bd
ayushgoel/PythonScripts
/HackerCup2017/ProgressPie/ProgressPie.py
1,579
3.640625
4
#!/usr/bin/env python import math def isOnAxis(x, y): return x == 50 or y == 50 def angleWhenOnAxis(x, y): if x == 50: if y >= 50: return 0 else: return 180 if y == 50: if x >= 50: return 90 else: return 270 def angle(x, y): if isOnAxis(x,y): return angleWhenOnAxis(x, y) if x > 50 and y > 50: q = (1.0 * (x-50)) / (y-50) return math.degrees(math.atan(q)) if x > 50 and y < 50: q = (1.0 * (x-50)) / (50-y) return math.degrees(math.atan(q)) + 90 if x < 50 and y < 50: q = (1.0 * (50-x)) / (50-y) return math.degrees(math.atan(q)) + 180 if x < 50 and y > 50: q = (1.0 * (50-x)) / (y-50) return math.degrees(math.atan(q)) + 270 def outsideCircle(x, y): x1 = x-50 y1 = y-50 if (x1*x1 + y1*y1) > 2500: return True return False with open("in.txt") as f: fo = open("out.txt", "w") f.readline() caseno = 1 for line in f: inp = [int(i) for i in line.split()] p = inp[0] x = inp[1] y = inp[2] ans = "" if outsideCircle(x, y) or p == 0: ans = "Case #{0}: white".format(caseno) else: a = angle(x, y) pa = p * 3.6 ans = "Case #{0}: ".format(caseno) print a, pa if a > pa: ans += "white" else: ans += "black" print ans fo.write(ans+"\n") caseno += 1 fo.close()
c5b6acf4fb3f0d04485b4b2c4db40ba4d610d995
Caleb-Mitchell/code_in_place
/discord_extension/Lecture18/adventure.py
348
3.59375
4
import json ''' Allows the user to navigate around a (text based) world. Data comes from adventure.json ''' START = 'tresidder' def main(): data = json.load(open('adventure.json')) play_game(data) def play_game(data): print('Welcome to the Stanford Adventure Game:\n') # TODO: your code here print(data) if __name__ == '__main__': main()
9ac49d199ec25246a36182cd38446a40ebd47997
Meiselina/Meiselina-
/ex13inputprompt.py
379
3.796875
4
from sys import argv script, first, second, third = argv prompt = '> ' print("The script is called:", script) print("Your first variable is:", first) print("Your second variable is:", second) print("Your third variable is:", third) print("What's your name?") Name = input(prompt) print (""") My english name is Mei My chinese name is Midi Wo de xing Du (""")
20245168da77684b42ece30230ca8f451921cf37
dungpa45/phamanhdung-faudamental-c4e13
/session2/homework/ex4g.py
205
3.859375
4
print("Nhap ma tran n*m voi n cot va m hang") n = int(input("Nhap so cot sao: ")) m = int(input("Nhap so hang sao: ")) for i in range(m): for i in range(1, n+1): print("*", end='') print()
369a3e67e5c9f1754ecfa9882908b1af657e4faa
StefanoBelli/ia1920
/linear_array_queue.py
1,001
3.546875
4
from collections.abc import Collection from ctypes import py_object as PyObject class Queue(Collection): def __init__(self, m): self._array = (PyObject * m)() self._max = m self._write = 0 def enqueue(self, elem): if self._write == self._max: return False self._array[self._write] = elem self._write += 1 return True def dequeue(self): if self._write == 0: return None elem = self._array[0] self._write -= 1 for i in range(self._write): self._array[i] = self._array[i+1] return elem def __len__(self): return self._write def __contains__(self, elem): return elem in self._array def __iter__(self): self._it = 0 return self def __next__(self): if self._it == self._write: raise StopIteration e = self._array[self._it] self._it += 1 return e
0aed344e25fc6d062126af243f698d10d042a4eb
sbordt/markovmixing
/markovmixing/plot_util.py
552
3.890625
4
""" Make good looking plots. """ import numpy def pyplot_bar(y, cmap='Blues'): """ Make a good looking pylot bar plot. Use a colormap to color the bars. y: height of bars cmap: colormap, defaults to 'Blues' """ import matplotlib.pyplot as plt from matplotlib.colors import Normalize from matplotlib.cm import ScalarMappable vmax = numpy.max(y) vmin = (numpy.min(y)*3. - vmax)/2. colormap = ScalarMappable(norm=Normalize(vmin, vmax), cmap='Blues') plt.bar(numpy.arange(len(y)), y, color=colormap.to_rgba(y), align='edge', width=1.0)
304d3b163ee0b52b2388d2c4c0f98594180252f6
danielv7/Algorithms
/DecodeWaysOfAlphabet.py
735
3.84375
4
#This question I first saw on LeetCode. #Given a non-empty string containing only digits, determine the total number of ways to decode it. #'A' -> 1 #'B' -> 2 #... #'Z' -> 26 #Example: Input "226" #Output 3: #Explanation: "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6). #Time: O(n) Space: O(1) def numWaysDecoding(string): if not string or string[0] == '0': return 0 n = len(string) count1 = 1 count2 = 1 for i in range(1, n): if string[i] == '0': if string[i - 1] not in '12': return 0 else: count = count1 else: if 10 <= int(string[i - 1:i + 1]) <= 26: count = count1 + count2 else: count = count2 count1, count2 = count2, count return count2
bdf70280cc4bd78c5b447d450d3186851ec45877
formalabstracts/CNL-CIC
/python-parser/lib.py
1,095
3.703125
4
# from collections.abc import Iterable def iterable(obj): return isinstance(obj, Iterable) def flatten(ls): """flatten a list one level""" return [v for sub in ls for v in sub] #sum([[1,2],[3,4],[5,6]])?? #print(flatten([[1,2],[3,4],[5,6]])) def fflatten(ls): """flatten recursive nested lists""" def rec_f(vs): if not(iterable(vs)): return [vs] return fflatten(vs) return flatten([rec_f(v) for v in ls ]) #print(fflatten([3,4,5])) #print(fflatten([3,[4,5,[6,7]],8,[9,10],(11,(12,13))])) def compress(ls,ind): """create sublist from given indices""" return [ls[i] for i in ind] def swap(f): """reverse the argument order if two arguments""" def g(x,y): return f(y,x) return g def curry(f): """curry a function of two variables""" def Cf(x): def f2(y): return f(x,y) return f2 return Cf def part(ind): return curry(swap(compress)) (ind) def fst(ls): return ls[0] def snd(ls): return ls[1] def prepend(x): return [fst(x)]+snd(x)
37ed3c281e467ed81428034c82977b163aac44d6
ikekou/python-exercise-100-book
/_answer/PythonExercise/p22.py
250
4.03125
4
word1 = input('1つ目の文字列を入力してください > ') word2 = input('2つ目の文字列を入力してください > ') r = '' for ch in word1: if ch in word2 and not ch in r: r += ch print(f'重複する文字列 : {r}')
155ec9353c051440d8c14d390e9dd68beb6d40ac
nsuvorov17/BPS
/HW3/task1.py
1,052
3.84375
4
# Задание 1. Уровень - уверенный хелловордец. # Условие: Аркадий очень любопытный человек. Он загадал два числа A и B (оба строго больше нуля), # Аркадию всегда было интересно, чему равна сумма всех ЦЕЛЫХ чисел, заключенных между A и B, # включая их самих же. # Входные данные : целые числа A,B >0 # Выходные данные: сумма всех целых чисел между A и B. # Пример работы: # Ввод: Вывод: # 1 # 4 10 # 700 # 824 95250 # 999 # 9999 49496499 a=int(input()) b=int(input()) summ = 0 if a > 0 and b > 0: while a != b+1: summ += a a += 1 print(summ) else: print(' ')
8dea81a3a9e60daf80426be15e9814edc666bfc9
EitanVilker/CompLingProject
/transliteration.py
5,973
4.15625
4
# Authors: Eitan Vilker and Kai Frey (eitan.e.vilker.21@dartmouth.edu and kai.m.frey.22@dartmouth.edu) # Usage: Simply run with python transliteration.py and enter Romanized Hebrew words when prompted # Machine-transliterated Hebrew to Hebrew rules, for ease of reference # a -> א # b -> ב # g -> ג # d -> ד # h -> ה # w -> ו # z -> ז # x -> ח # v -> ט # i -> י # k -> כ # k (final) -> ך‎ # l -> ל # m -> מ # m (final) -> ם‎ # n -> נ # n (final) -> ן # s -> ס # y -> ע # p -> פ # p (final) -> ף # c -> צ # c (final) -> ץ # q -> ק # r -> ר # e -> ש # t -> ת # Function that takes as input a word entered by a user and # outputs a word in the transliterated form computers can accept def convertToMachineTransliteration(word): new_word = "" skip = False if_statment_fixer = True for i in range(len(word)): if word[i] == "s": if skip: skip = False elif i < len(word) - 1: if word[i + 1] == "h": new_word += "e" skip = True elif word[i + 1] == "s": new_word += "s" skip = True else: new_word += "s" else: new_word += "s" elif word[i] == "c": if i < len(word) - 1: if word[i + 1] == "h": new_word += "x" skip = True else: new_word += "k" elif word[i] == "k": if i < len(word) - 1: if word[i + 1] == "h": new_word += "x" skip = True else: new_word += "k" else: new_word += "k" elif word[i] == "h": if (skip): skip = False else: new_word += "h" elif word[i] == "b": if skip: skip = False elif i < len(word) - 1: if word[i + 1] == "b": new_word += "b" skip = True else: new_word += "b" else: new_word += "b" elif word[i] == "g": new_word += "g" elif word[i] == "v": new_word += "w" elif word[i] == "z": if skip: skip = False else: new_word += "z" elif word[i] == "t": if skip: skip = False elif i < len(word) - 1: if word[i + 1] == "t": new_word += "t" skip = True elif word[i + 1] == "s" or word[i + 1] == "z": new_word += "c" skip = True else: new_word += "t" else: new_word += "t" elif word[i] == "y": new_word += "i" elif word[i] == "l": if skip: skip = False elif i < len(word) - 1: if word[i + 1] == "l": new_word += "l" skip = True else: new_word += "l" else: new_word += "l" elif word[i] == "m": if skip: skip = False elif i < len(word) - 1: if word[i + 1] == "m": new_word += "m" skip = True else: new_word += "m" else: new_word += "m" elif word[i] == "n": if skip: skip = False elif i < len(word) - 1: if word[i + 1] == "n": new_word += "n" skip = True else: new_word += "n" else: new_word += "n" elif word[i] == "p": new_word += "p" elif word[i] == "f": new_word += "p" elif word[i] == "r": new_word += "r" elif word[i] == "o": if skip: skip = False elif i < len(word) - 1: if word[i + 1] == "o": new_word += "w" skip = True else: new_word += "w" else: new_word += "w" elif word[i] == "u": new_word += "w" elif word[i] == "i": if i == 0: new_word += "y" elif i == len(word) - 1: new_word += "i" elif word[i + 1] == "m": new_word += "im" skip = True elif word[i] == "a": if skip: skip = False elif i == 0: new_word += "a" elif i == len(word) - 1: new_word += "h" elif word[i + 1] == "a": new_word += "y" skip = True elif word[i + 1] == "e": new_word += "a" skip = True elif word[i] == "e": if skip: skip = False elif i == 0: new_word += "a" elif i == len(word) - 1: new_word += "h" elif word[i + 1] == "a": new_word += "a" skip = True elif word[i + 1] == "e": new_word += "i" skip = True else: new_word += word[i] return new_word # while(True): # word = input("Enter your Hebrew word: ") # print("\nYou entered: " + word) # print("This was converted to: " + convertToMachineTransliteration(word))
fa57723f7a7fba71c4038c6d3e9a73d1f5c68f91
jasonlingo/Machine_Learning-Data_to_Models
/Final_Project/program/src/tripDist.py
3,944
3.59375
4
""" Group the trips into three types: short, median, and long trips. For each trip group, plot every trip's starting point with its color determined by the error ratio: 1. blue color: error distance < trip distance * 0.1 2. green color: trip distance * 0.1 <= error distance < trip distance * 0.5 3. red color: trip distance * 0.5 <= error distance where trip distance is the distance between the start and end points of each trip. """ import ast import numpy as np import sys from score import haversine import os import pygmaps import webbrowser def plotErrMap(trips, title, outputFile): SMALL_ERR_COLOR = "#0000FF" # blue MED_ERR_COLOR = "#00FF00" # green LARGE_ERR_COLOR = "#FF0000" # red # set the center of this map center = trips[0][2] mymap = pygmaps.maps(center[1], center[0], 10) # Add every points in framePoint to this map. for dist, errDist, point in trips: if errDist < dist * 0.1: color = SMALL_ERR_COLOR elif errDist < dist * 0.5: color = MED_ERR_COLOR else: color = LARGE_ERR_COLOR mymap.addpoint(point[1], point[0], color) # Create this map. mapFilename = outputFile mymap.draw('./' + mapFilename) # Create the local link to this map file. url = "file://" + os.getcwd() + "/" + mapFilename # Open this map on a browser webbrowser.open_new(url) if __name__=="__main__": # get clusters f = open('../dataset/train/clusters.txt', 'r') clusters = [k.strip("\n").split("|") for k in f.readlines()] f.close() # read training data f = open('../dataset/train/trainData_withLabel.txt', 'r') data = [l for l in f.readlines() if l] rawData = [] err = 0 for d in data: if not d: continue l = d.strip("\n").split("|") rawData.append(l) if len(rawData) % 10000 == 0: print ".", if len(rawData) >= 100000: break f.close() print len(rawData) f = open('../dataset/train/result/dist.txt', 'r') dist = [float(l) for l in f.readlines()] f.close() # divide data into trainData and testData testDataNum = len(rawData) / 10 testData = rawData[len(rawData) - testDataNum:] print len(testData), len(dist) shortTrips = [] # trip dist < 5km medianTrips = [] # 5km <= trip dist < 10km longTrips = [] # 10km <= trip dist # f = open('../dataset/train/result/erro_ratio.txt', 'w') for i in xrange(10000): trip = testData[i] errDist = dist[i] dest = ast.literal_eval(trip[41]) tripDist = haversine(float(trip[22]), float(trip[21]), float(dest[1]), float(dest[0])) # f.write(str(tripDist) + "|" + str(errDist) + "\n") # f.write(str(tripDist) + "\n") data = (tripDist, errDist, (float(trip[21]), float(trip[22]))) if 10 <= tripDist: longTrips.append(data) elif 5 <= tripDist: medianTrips.append(data) else: shortTrips.append(data) # f.close() # calculate average distance error shortErr = sum(map(lambda x: x[1], shortTrips)) / len(shortTrips) medianErr = sum(map(lambda x: x[1], medianTrips)) / len(medianTrips) longErr = sum(map(lambda x: x[1], longTrips)) / len(longTrips) print "avg short err:", shortErr print "avg median err:", medianErr print "avg long err:", longErr outputFile = '../dataset/train/result/small_' + "map.html" title = 'Distance Error of Short Trips' plotErrMap(shortTrips, title, outputFile) outputFile = '../dataset/train/result/med_' + "map.html" title = 'Distance Error of Median Trips' plotErrMap(medianTrips, title, outputFile) outputFile = '../dataset/train/result/large_' + "map.html" title = 'Distance Error of Long Trips' plotErrMap(longTrips, title, outputFile)