blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
38e90a995c9a50cba7aac0df8362af1aac9e8809
stephens-dev/afs-210
/week2/linked.py
921
3.640625
4
class Node: def __init__(self, data=None): self.data = data self.next = None class singlyLinkedList: def __init__(self): self.head = None self.tail = None self.count = 0 def iterateItem(self): currentItem = self.head while currentItem: val = currentItem.data currentItem = currentItem.next yield val def appendItem(self, data): node = Node(data) if self.tail: self.tail.next = node self.tail = node else: self.head = node self.tail = node self.count += 1 items = singlyLinkedList() items.appendItem('PHP') items.appendItem('Python') items.appendItem('C#') items.appendItem('C++') items.appendItem('Java') for val in items.iterateItem(): print(val) print("\nhead.data: ",items.head.data) print("tail.data: ",items.tail.data)
50bd2294b7a6c8c9363cf27c7bd7d88992bc9b37
RomyNRug/pythonProject2
/Week 3/MathWeek3part2.py
1,691
4
4
#8 def triangle_numbers(n): for i in range(1, n + 1): print("n = {0}, triangle = {1}".format(i, (i ** 2 + i)//2)) triangle_numbers(5) #9 Write a program which prints True when n is a prime number and False otherwise # Program to check if a number is prime or not num = 407 # To take input from the user num = int(input("Enter a number: ")) if num > 1: for i in range(2, num): if (num % i) == 0: print(num, "false") break else: print(num, "True") #10 Revisit the drunk pirate problem. This time, the drunk pirate makes a turn, and then takes some steps forward, and repeats this. Our social science student now records pairs of data: the angle of each turn, and the number of steps taken after the turn. Her experimental data is [(160, 20), (-43, 10), (270, 8), (-43, 12)]. Use a turtle todraw the path taken by our drunk friend. #import turtle #paper=turtle.Screen() #zubi= turtle.Turtle #path = [160, -43, 270,-43] #angle=[20,10,8,12] #def draw_path(zubi,path,angle): # for i in path,angle: # zubi.left(angle) # zubi.forward(path) #11 #import turtle #tori = turtle.Turtle #paper = turtle.Screen() #tori.left(100) #12?????? #13 def num_digits(n): i=0 count = 0 while i < n: i+=1 if n%2==0: count += 1 return count #14 Write a program that computes the sum of the squares of the numbers in the list numbers. For example a call with, numbers = [2, 3, 4] should print 4+9+16 which is 29. list = [0,1,2,3,4,5,6] for i in list: sqr= (i**2) print("the number is {0} and the square is {1}".format(i,sqr))
540d8b98398b360d505f3a1d3963772ad33d338e
AleksMaykov/GB
/lesson1_all.py
6,232
4.0625
4
# Задача-1: поработайте с переменными, создайте несколько, # выведите на экран, запросите от пользователя и сохраните в переменную, выведите на экран a = 5 b = 7 c = 9 print(a,b,c) z = input('Введите любое число:') print('Вы ввели число: ' + z) # Задача-2: Запросите от пользователя число, сохраните в переменную, # прибавьте к числу 2 и выведите результат на экран. # Если возникла ошибка, прочитайте ее, вспомните урок и постарайтесь устранить ошибку. num = int(input('Введите любое число:')) num +=2 print('Вы ввели число: ' + str(num)) # Задача-3: Запросите у пользователя его возраст. # Если ему есть 18 лет, выведите: "Доступ разрешен", # иначе "Извините, пользование данным ресурсом только с 18 лет" age = int (input('Сколько Вам лет?: ')) if age < 18: print("Извините, пользование данным ресурсом только с 18 лет") exit() else: print("Доступ разрешен") ################################################################################### import time # Задача: используя цикл запрашивайте у пользователя число пока оно не станет больше 0, но меньше 10. # После того, как пользователь введет корректное число, возведите его в степерь 2 и выведите на экран. # Например, пользователь вводит число 123, вы сообщаете ему, что число не верное, # и сообщаете об диапазоне допустимых. И просите ввести заного. # Допустим пользователь ввел 2, оно подходит, возводим в степерь 2, и выводим 4 num = 0 while num < 1 or num >10: num = int (input('Введите любое число:')) if num < 0: print('ведите число заново и побольше!') elif num >10: print('Введите число заново и поменьше!') num **=2 print(num) # Задача-2: Исходные значения двух переменных запросить у пользователя. # Поменять значения переменных местами. Вывести новые значения на экран. # Решите задачу, используя только две переменные. # Подсказки: # * постарайтесь сделать решение через действия над числами; a = input('Введите значение числа А:') b = input('Введите значение числа B:') print('Вы ввели 2 числа: А = ' + a + ' и B = ' + b ) time.sleep(3) a,b = b,a print('Или такие 2 числа: А = ' + a + ' и B = ' + b ) ########################################################################### import time # Создайте программу медицинская анкета, где вы запросите у пользователя такие данные, как имя, фамилию, возраст, и вес. # И выведите результат согласно которому пациент в хорошем состоянии, если ему до 30 лет и вес от 50 и до 120 кг, # Пациенту требуется начать вести правильный образ жизни, если ему более 30 и вес меньше 50 или больше 120 кг # Пациенту требуется врачебный осмотр, если ему более 40 и вес менее 50 или больше 120 кг. print('Добро пожаловать в наш медицинский центр "Центр всягой фигни Алана Харпера"!') time.sleep(2) ask = input('Вы у нас в первый раз? y/n: ') if ask == 'y': print('Заечательно! Для начала давайте заведем Вам новую карточку.') name = input('Ваше имя?: ') sname= input('Ваша Фамилия?: ') age = int (input('Ваш возраст?: ')) weight = int (input('Ваш вес (и пожалуйства честно)?: ')) if age < 30 and (weight < 120 or weight > 50): print('УАУ! ' + name + '. Да вы такой бодричек! Поздравляем!') elif (age > 30 and age <40) and (weight < 50 or weight > 120): print('Хм... Уважаемый ' + sname + ' ' + name + '. Вам пора начать вести более здоровый образ жизни.') elif age > 40 and (weight < 50 or weight > 120): print('ОЙЙЙ! ' + name + '. Вам СРОЧНО требуется осмотр!') else: print('что то не так') elif ask == 'n': print('Дада... припоминаю, Вам же сказали "Пейте валерьянку и мажте зеленкой". Всего доброго.') else: print('Вам бы к окулисту сходить.') #Формула не отражает реальной действительности и здесь используется только ради примера. # Пример: Вася Пупкин, 31 год, вес 90 - хорошее состояние # Пример: Вася Пупкин, 31 год, вес 121 - следует заняться собой # Пример: Вася Пупкин, 31 год, вес 49 - следует заняться собой # Пример: Вася Пупкин, 41 год, вес 121 - следует обратится к врачу! # Пример: Вася Пупкин, 41 год, вес 49 - следует обратится к врачу!
b81da31ae5874696e23d4edd231797d78d776e7f
carlan/dailyprogrammer
/easy/3/python/app.py
1,778
3.96875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """app.py: challenge #3""" __author__ = "Carlan Calazans" __copyright__ = "Copyright 2016, Carlan Calazans" __credits__ = ["Carlan Calazans"] __license__ = "MIT" __version__ = "1.0.0" __maintainer__ = "Carlan Calazans" __email__ = "carlancalazans at gmail dot com" __status__ = "Development" class CaesarCipher(object): def encrypt(self, key, text): result = '' for symbol in text: if symbol.isalpha(): symbol_number = ord(symbol) if symbol.islower(): shifted = (symbol_number - 97 + key) % 26 + 97 result += chr(shifted) if symbol.isupper(): shifted = (symbol_number - 65 + key) % 26 + 65 result += chr(shifted) else: result += symbol return result def decrypt(self, key, text): result = '' for symbol in text: if symbol.isalpha(): symbol_number = ord(symbol) if symbol.islower(): shifted = (symbol_number - 97 - key) % 26 + 97 result += chr(shifted) if symbol.isupper(): shifted = (symbol_number - 65 - key) % 26 + 65 result += chr(shifted) else: result += symbol return result caesar = CaesarCipher() quote_lowercase = 'The first step is you have to say that you can.' quote_uppercase = quote_lowercase.upper() enc_lowercase = caesar.encrypt(1, quote_lowercase) enc_uppercase = caesar.encrypt(1, quote_uppercase) dec_lowercase = caesar.decrypt(1, enc_lowercase) dec_uppercase = caesar.decrypt(1, enc_uppercase) print( "Quote (lowercase): {}".format(quote_lowercase) ) print( "Quote (uppercase): {}".format(quote_uppercase) ) print( "Encrypted (lowercase): {}".format(enc_lowercase) ) print( "Encrypted (uppercase): {}".format(enc_uppercase) ) print( "Decrypted (lowercase): {}".format(dec_lowercase) ) print( "Decrypted (uppercase): {}".format(dec_uppercase) )
4136d9bae1896bdfdf3febcf4da3abf2bcdb83a9
Jason101616/LeetCode_Solution
/Hash Table/249. Group Shifted Strings.py
1,190
4
4
# Given a string, we can "shift" each of its letter to its successive letter, for example: "abc" -> "bcd". We can keep "shifting" which forms the sequence: # # "abc" -> "bcd" -> ... -> "xyz" # Given a list of strings which contains only lowercase alphabets, group all strings that belong to the same shifting sequence. # # Example: # # Input: ["abc", "bcd", "acef", "xyz", "az", "ba", "a", "z"], # Output: # [ # ["abc","bcd","xyz"], # ["az","ba"], # ["acef"], # ["a","z"] # ] from collections import defaultdict class Solution(object): def groupStrings(self, strings): """ :type strings: List[str] :rtype: List[List[str]] """ mapping = defaultdict(lambda: []) for string in strings: mapping[self.helper(string)].append(string) return list(mapping.values()) def helper(self, string): if len(string) == 1: return () minus = ord(string[0]) - ord('a') res = [] for char in string: tmp = ord(char) - minus if tmp < ord('a'): res.append(tmp + 26) else: res.append(tmp) return tuple(res)
507379e3d533e5d779859d5fb9bc93efae39384f
oliverhuangchao/python_study
/data_structure/worker_arrange.py
276
3.90625
4
x = {"a":["p1","p2","p3"],"b":["p2","p4"],"c":["p1","p3"]} print x y = dict() for i in x: for j in x[i]: #print j if j in y: y[j].append(i) else: y[j] = list() y[j].append(i) for i in y: print i + str(y[i])
ef0e43f1f337b4c2b8732cf18fcd9a0561f70c0f
RossMedvid/Pythone_core_tasks
/Classwork200919.py
8,086
4.46875
4
# 1. Написати функцію, яка знаходить середнє арифметичне значення довільної кількості чисел. # def arifmetic_mean(*args): # """This function calculate arifmetic mean of a non-empty arbitrary numbers""" # return(sum(args))/len(args) # print(arifmetic_mean(1,3,6)) # 2. Написати функцію, яка повертає абсолютне значення числа # def return_absolute_number(a): # """This function returns absolute mean of numbers""" # if a>0: # print(a) # else: # return (a*-1) # print(return_absolute_number(-54)) # 3.3. Написати функцію, яка знаходить максимальне число з двох чисел, а також в функції використати рядки документації DocStrings. # def max_numbers(a,b): # """This function returns maximum in output between two numbers""" # if a>b: # print(a) # if a==b: # print("The values ​​are equal") # else: # return b # print(max_numbers(5,9)) #44. Написати програму, яка обчислює площу прямокутника, трикутника та кола (написати три функції для обчислення площі, і викликати їх в головній програмі в залежності від вибору користувача) # def rectangel(a,b): # """This function calculate area of rectangel""" # s_rectangel=a*b # return s_rectangel # def triangle(a,b,c): # """This function calculate area of triangle""" # p=(a+b+c)/2 # return ((p*(p-a)*(p-b)*(p-c))** 0.5) # def circle(r): # """This function calculate area of circle""" # return(3.14*(r**2)) # area=input("Please enter what area of figure you want to count:") # if area=="rectangel" or area=="triangle" or area=="circle": # while True: # if area=="rectangel": # a=int(input("Enter the lenght of the first side:")) # b=int(input("Enter the lenght of another side:")) # print(rectangel(a,b)) # break # elif area=="triangle": # a=int(input("Enter the lenght of the side a:")) # b=int(input("Enter the lenght of the side b:")) # c=int(input('Enter the lenght of the side c:')) # print(triangle(a,b,c)) # break # elif area=="circle": # r=int(input("Please enter the radius of circle:")) # print(circle(r)) # break # else: # print("EROR: You are entering inncorect value, please try again") # 55. Написати функцію, яка обчислює суму цифр введеного числа. # def list_of_numbers(*kwargs): # """This function calculates the sum of entered numbers""" # a=0 # for i in kwargs: # a=i+a # return a # print(list_of_numbers(431,5213,2321)) # 6. Написати програму калькулятор, яка складається з наступних функцій: # головної, яка пропонує вибрати дію та додаткових, які реалізовують вибрані дії, калькулятор працює доти, поки ми не виберемо дію вийти з калькулятора, # після виходу, користувач отримує повідомлення з подякою за вибір нашого програмного продукту!!! # def sum_of_numbers(a,b): # """This function calculates sum of entered numbers""" # a=a+b # return a # def multiplication_(a,b): # """This function calculates multiplication of entered numbers""" # a=a*b # return a # def subtraction_(a,b): # """This function calculates subtraction between two values""" # a=a-b # return a # def division_(a,b): # """This function calculates division between two values""" # a=a/b # return a # # Calculator # h=input("Hello, please type start for the next step, or exit for the end:") # if h=="start": # a=int(input("Please choose your first number:")) # s=input("Please choose the operation between +, *, -, / :") # b=int(input("Please choose your second number:")) # while True: # if s=="+" or s=="*" or s=="-"or s=="/": # while True: # if s=="+": # print(sum_of_numbers(a,b)) # s=input("If you want exit out of this program tape EXIT or choose another operation:") # if s=="exit": # break # if s=="+" or s=="*" or s=="-" or s=="/": # a=int(input("Please choose your first number:")) # b=int(input("Please choose your second number:")) # continue # else: # break # if s=="*": # print(multiplication_(a,b)) # s=input("If you want exit out of this program tape EXIT or choose another operation:") # if s=="exit": # break # if s=="+" or s=="*" or s=="-" or s=="/": # a=int(input("Please choose your first number:")) # b=int(input("Please choose your second number:")) # continue # else: # break # if s=="-": # print(subtraction_(a,b)) # s=input("If you want exit out of this program tape EXIT or choose another operation:") # if s=="exit": # break # if s=="+" or s=="*" or s=="-" or s=="/": # a=int(input("Please choose your first number:")) # b=int(input("Please choose your second number:")) # continue # else: # break # if s=="/": # while True: # if a>0 and b>0: # print(division_(a,b)) # s=input("If you want exit out of this program tape EXIT or choose another operation:") # if s=="/": # a=int(input("Please choose your first number:")) # b=int(input("Please choose your second number:")) # continue # if s=="exit": # break # if s=="+" or s=="*" or s=="-": # a=int(input("Please choose your first number:")) # b=int(input("Please choose your second number:")) # break # else: # break # if a==0 or b==0: # print("EROR:Please type your values without 0 if you want do divison operation:") # a=int(input("Please choose your first number:")) # b=int(input("Please choose your second number:")) # continue # else: # break # else: # break # if s=="exit": # print("Thank you that you choose our software. Have a nice day.") # break # else: # print("Something gone wrong please try again.") # break # else: # print("Thank you that you choose our software. Have a nice day.")
45a1b6f720d081594dfab848585a33ef8ed85ee3
Ramsum123/Python
/baby_name.py
1,957
3.796875
4
from numpy import * import numpy as np import random2 from array import * import os ## to run the loop class Daughter(object): def take_input(self): h = input('What is your name?') g = int(input('Enter the number of character you want to be in your baby name.')) f = input("Enter your spouse name.") #print("Among one thousand names, Possible baby names are") first_let = h[0] let_anywhere = f[0] #print(h,g) # Characters to generate the random word rest_char = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] i = 0 while i < 10001: i = i + 1 #List to carry the character my_char = [] my_char_len = len(my_char) # List to carry the word after joining them word = [] while my_char_len < g: my_char_len = my_char_len + 1 pull = random2.choice(rest_char) my_char.append(pull) #print(my_char) # use of join built-in function to join the character in the my_char list and make a single word name = ("".join(my_char)) word.append(name) #print('No name with letter',first_let) # print(word) # To create the file if not created and to apend the data in the file f1 = open("names.txt",'a+') if name[0] == first_let: f1.write("\n"+name) f1.close() else: pass # to read the data from the file f2 = open("names.txt",'r') content = f2.read() print(len(content)) #return content print('These are the possible baby names.',content.upper()) os.remove("names.txt") x = Daughter() x.take_input()
48dd3c57674205655db8eb66d1db9d25b8764e90
Daiyunfeng/crawler
/thread.py
424
3.53125
4
import threading import time def target(n): n = int(n) num = [0 for x in range(0, n)] for i in range(2,n): if(num[i]==0): print(i,end=" ") for j in range(2,int(n/i)): num[i*j]=1 print() count = 100 while(count!=0): # n = input("n:") count-=1 n=10000 t = threading.Thread(target=target,args=(n,)) t.setDaemon(True) t.start() #t.join()
3bb6b0a50bd328a2bc37903ba7fb5096c944bb0e
Shevah92/100doors
/doors.py
223
3.578125
4
#!/usr/bin/env python # mathematical solution: we figured a doors will be open if # the number of the divisors for that are odd. that's only true for square numbers for i in range(1,11): square= i*i print(square)
7f05345f9896511c51cdef6dccc5f1eee5606483
wxmsummer/algorithm
/leetcode/array/3_removeDuplicates.py
455
3.65625
4
class Solution: def removeDuplicates(self, nums:list) -> int: i, j = 0, 0 while j < len(nums): print('j:', j) if j+1 < len(nums) and nums[j+1] == nums[j]: j += 1 else: nums[i] = nums[j] i += 1 j += 1 print('nums:', nums) return i if __name__ == '__main__': obj = Solution() print(obj.removeDuplicates([0]))
1aa2380a01be4e7b08fabb3318a17d0c0c1daff2
mikewarren02/PythonReview
/calculator.py
506
4.15625
4
def calculator(): first_no = float(input("First number: ")) operation = input("Operation: ") second_no = float(input("Second number: ")) if operation == "+": total = first_no + second_no print(total) elif operation == "-": total = first_no - second_no print(total) elif operation == "/": total = first_no / second_no print(total) elif operation == "*": total = first_no * second_no print(total) calculator()
3f519292eb2b7cfcda7e9bc86b35b80e6b693b44
YadunathK/plab
/hw 18-22/rect_lessthan.py
638
3.96875
4
class rectangle(): def __init__(self,l,w): self.__length=l self.__width=w self.ar=self.__length*self.__width def __lt__(self,a2): if self.ar<a2.ar: print(self.ar,'is least area than',a2.ar) else: print(a2.ar ,'is the least area than',self.ar) l1=int(input("enter the length of the first rectangle=")) w1=int(input("enetr the width of the first rectangle=")) r1=rectangle(l1,w1) l2=int(input("enter the length of the second rectangle=")) w2=int(input("enetr the width of the second rectangle=")) r2=rectangle(l2,w2) r1<r2
2792c80d790b766791224c50fcb896422b4e0a7a
bnitin92/coding_practice
/Graphs/Graph_BFS.py
580
4.125
4
# Traversing the graph using Breadth first search (BFS) visited = set() def bfs(visited, graph, node): queue = [] queue.append(node) while queue: element = queue.pop(0) if element not in visited: print(element) visited.add(element) for neighbour in graph[element]: queue.append(neighbour) # Using a Python dictionary to act as an adjacency list graph = { 'A' : ['B','C'], 'B' : ['D', 'E'], 'C' : ['F'], 'D' : [], 'E' : ['F'], 'F' : [] } print(bfs(visited, graph, 'A'))
44900a7540e41ea51de7f5c1950709effdc29962
prasen7/python-examples
/student.py
1,399
4.34375
4
# program to evaluate students average score: # an example to show how tuples and dictionaries can work together. # create an empty dictionary for the input data; the student's name is used as a key, # while all the associated scores are stored in a tuple. school_class = {} while True: name = input("Enter the student's name (or type exit to stop): ") if name == 'exit': break score = int(input("Enter the student's score (0-10): ")) # if the student's name is already in the dictionary, # lengthen the associated tuple with the new score if name in school_class: school_class[name] += (score,) else: # if this is a new student (unknown to the dictionary), create a new entry - # its value is a one-element tuple containing the entered score; school_class[name] = (score,) for name in sorted(school_class.keys()): # iterate through the sorted students' names; adding = 0 # sum of scores of all subjects of a student counter = 0 # no of subjects for each student for score in school_class[name]: adding += score counter += 1 # iterate through the tuple, taking all the subsequent scores # and updating the sum, together with the counter # print the student's name and average score print(name, ":", adding / counter)
a3e545142aace399fcb025769414793c0d0e9212
kchen36/fantastic-computing-machine
/db_builder.py
801
3.546875
4
import sqlite3 #enable control of an sqlite database import csv #facilitates CSV I/O f="discobandit.db" db = sqlite3.connect(f) #open if f exists, otherwise create c = db.cursor() #facilitate db ops c.execute("CREATE TABLE courses(code TEXT, mark INTEGER, id INTEGER)" ) c.execute("CREATE TABLE peeps(name TEXT, age INTEGER, id INTEGER)" ) sfile = csv.DictReader(open("peeps.csv")) cfile = csv.DictReader(open("courses.csv")) for row in cfile: code = row['code'] mark = row['mark'] ids = row['id'] c.execute('INSERT INTO courses VALUES (?,?,?)', (code,mark,ids) ) for row in sfile: name = row['name'] age = row['age'] ids = row['id'] c.execute('INSERT INTO peeps VALUES (?,?,?)', (name,age,ids) ) db.commit() #save changes db.close() #close database
a4568ed78d9d88df89f2fd9e9354ab25738ec567
sharonLuo/LeetCode_py
/two-sum-iii-data-structure-design.py
1,823
4
4
""" Design and implement a TwoSum class. It should support the following operations: add and find. add - Add the number to an internal data structure. find - Find if there exists any pair of numbers which sum is equal to the value. For example, add(1); add(3); add(5); find(4) -> true find(7) -> false """ ### 580 ms class TwoSum: def __init__(self): self.ctr = {} def add(self, number): if number in self.ctr: self.ctr[number] += 1 else: self.ctr[number] = 1 def find(self, value): ctr = self.ctr for num in ctr: if value - num in ctr and (value - num != num or ctr[num] > 1): return True return False ##### 870 ms class TwoSum(object): def __init__(self): """ initialize your data structure here """ self.nums = {} self.sum = set() def add(self, number): """ Add the number to an internal data structure. :rtype: nothing """ self.nums[number] = self.nums.get(number, 0) + 1 def find(self, value): """ Find if there exists any pair of numbers which sum is equal to the value. :type value: int :rtype: bool """ if value in self.sum: return True for num in self.nums: if value-num==num: if self.nums[num]>1: self.sum.add(value) return True else: if value-num in self.nums: self.sum.add(value) return True return False # Your TwoSum object will be instantiated and called as such: # twoSum = TwoSum() # twoSum.add(number) # twoSum.find(value)
77f713c82dade421ce0aae5c11c7c9331dd41aa5
huangxueqin/algorithm_exercise
/leetcode/python/reverseLinkedList.py
564
4.125
4
#!/usr/bin/env python3 #definition of single linked list class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: # @param {ListNode} head # @return {ListNode} def reverseList(self, head): if head == None: return head currNode = head nextNode = currNode.next head.next = None while nextNode != None: t = nextNode.next nextNode.next = currNode currNode = nextNode nextNode = t return currNode
0975a3090017efdc6e236bcbb45fe692fcba9490
linda-oranya/pypi_calculator
/src/calculator.py
2,698
4.5
4
from typing import Union class Calculator: """ This class performs basic calculator functions such as: - Addition / Subtraction - Multiplication / Division - Take (n) root of number - Reset memory """ def __init__(self, start:int = 0)-> None: """ Initializes memory to 0 """ self.__index = start @property def memory_val(self): """ access the memory which is always set to 0 """ return self.__index @staticmethod def __input_validation(number: Union[int, float]): """ Validates input """ if not isinstance (number, (int, float)): raise TypeError("only numerical inputs allowed (float or integer)") def reset(self): """ Resets memory to 0 """ self.__index = 0 def add(self, num: Union[int, float]): """ Add num to value in the memory """ self.__input_validation(num) self.__index += num return self.__index def subtract(self, num: Union[int, float]): """ Subtracts num from value in memory """ self.__input_validation(num) self.__index -= num return self.__index def multiply(self, num: Union[int, float]): """ Multiply number by value in memory """ self.__input_validation(num) self.__index *= num return self.__index def divide(self, num: Union[int, float]): """ Divide number by value in memory """ self.__input_validation(num) try: self.__index /= num return self.__index except ZeroDivisionError as err: print(f"number cannot be zero => {err}") def modulus(self, num: Union[int, float]): """ Divide number by value in memory and return the reminder """ self.__input_validation(num) try: self.__index %= num return self.__index except ZeroDivisionError as err: print(f"number cannot be zero => {err}") def square_root(self, num: Union[int, float]): """ Find the squreroot of number given that value is > 0 """ self.__input_validation(num) if self.__index <= 0: raise ValueError(f"The calculator does not have the capacity to compute negative roots") if num <= 0: raise ValueError("The calculator does not have the capacity to compute negative roots") self.__index = self.__index**(1./num) return self.__index
4c4d341bfba2697aadb87389aa64844112650da3
naeimnb/pythonexersices
/old/test3.py
711
3.9375
4
def standardName (name): alphabet='abcdefghijklmnopqrstuvwxyz' name=name.lower() for alpha in alphabet: startw=name.startswith(alpha) if startw==True: name = name[1:] name= alpha.upper()+name return name name1= input('') name2= input('') name3= input('') name4= input('') name5= input('') name6= input('') name7= input('') name8= input('') name9= input('') name10= input('') print(standardName(name1)) print(standardName(name2)) print(standardName(name3)) print(standardName(name4)) print(standardName(name5)) print(standardName(name6)) print(standardName(name7)) print(standardName(name8)) print(standardName(name9)) print(standardName(name10))
975ec3a6f286288b9e838daf5d60afc2ac0f0bd8
allyssnerd/Python-520
/aula_2/exercicio_5.py
1,201
3.65625
4
# Criar uma classe Usuario que tenha # os atributos nome, idade, email # e os metodos : # - maior de idade # - funcionario da 4linux # - tem moto class Usuario: def __init__(self, nome, email, idade): self.nome = nome self.email = email self.idade = idade def maior_de_idade(self): if self.idade > 21: return True return False def funcionario_da_4linux(self): if '@4linux' in self.email: return True return False def tem_moto(self): if self.nome == 'Lucas Ricciardi de Salles': return True return False nome = input('Digite seu nome: ') email = input('Digite seu email: ') idade = int(input('Digite sua idade: ')) usuario = Usuario(nome, email, idade) print('Olá {}'.format(usuario.nome)) if usuario.maior_de_idade(): print('Maior de idade') if usuario.tem_moto(): print('Tem moto') exit() class Lampada: acesa = False def pressionar_interruptor(self): self.acesa = not self.acesa lampada1 = Lampada() lampada2 = Lampada() lampada1.pressionar_interruptor() print('Lampada 1: ' + str(lampada1.acesa)) print('Lampada 2: ' + str(lampada2.acesa))
4c769ca550d072e29a3eb1a87218c09127ed687c
Stella2019/study
/刷题/86.分隔链表.py
2,978
3.5625
4
# # @lc app=leetcode.cn id=86 lang=python3 # # [86] 分隔链表 # # https://leetcode-cn.com/problems/partition-list/description/ # # algorithms # Medium (60.23%) # Likes: 282 # Dislikes: 0 # Total Accepted: 60.8K # Total Submissions: 100.9K # Testcase Example: '[1,4,3,2,5,2]\n3' # # 给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。 # # 你应当保留两个分区中每个节点的初始相对位置。 # # # # 示例: # # 输入: head = 1->4->3->2->5->2, x = 3 # 输出: 1->2->2->4->3->5 # # # 思路 设定两个虚拟节点,dummyHead1 用来保存小于该值的链表,dummyHead2 来保存大于等于该值的链表 遍历整个原始链表,将小于该值的放于 dummyHead1 中,其余的放置在 dummyHead2 中 遍历结束后,将 dummyHead2 插入到 dummyHead1 后面 关键点解析 链表的基本操作(遍历) 虚拟节点 dummy 简化操作 遍历完成之后记得currentL1.next = null;否则会内存溢出 如果单纯的遍历是不需要上面操作的,但是我们的遍历会导致 currentL1.next 和 currentL2.next 中有且仅有一个不是 null, 如果不这么操作的话会导致两个链表成环,造成溢出。 class Solution: def partition(self, head: ListNode, x: int) -> ListNode: """在原链表操作,思路基本一致,只是通过指针进行区分而已""" # 在链表最前面设定一个初始node作为锚点,方便返回最后的结果 first_node = ListNode(0) first_node.next = head # 设计三个指针,一个指向小于x的最后一个节点,即前后分离点 # 一个指向当前遍历节点的前一个节点 # 一个指向当前遍历的节点 sep_node = first_node pre_node = first_node current_node = head while current_node is not None: if current_node.val < x: # 注意有可能出现前一个节点就是分离节点的情况 if pre_node is sep_node: pre_node = current_node sep_node = current_node current_node = current_node.next else: # 这段次序比较烧脑 pre_node.next = current_node.next current_node.next = sep_node.next sep_node.next = current_node sep_node = current_node current_node = pre_node.next else: pre_node = current_node current_node = pre_node.next return first_node.next 时间复杂度:O(N)O(N)​ 空间复杂度:O(1)O(1) # @lc code=start # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def partition(self, head: ListNode, x: int) -> ListNode: # @lc code=end
c24e3b74dcdef56986cdcbb4fe0bf085cddef022
jaberg/nengo
/examples/squaring.py
1,317
3.8125
4
from .. import nengo as nengo ## This example demonstrates computing a nonlinear function (squaring) in neurons. ## ## Network diagram: ## ## [Input] ---> (A) ---> (B) ## ## ## Network behaviour: ## A = Input ## B = A * A ## # Create the nengo model model = nengo.Model('Squaring') # Create the model inputs model.make_node('Input', [0]) # Create a controllable input function # with a starting value of 0 # Create the neuronal ensembles model.make_ensemble('A', 100, 1) # Make 2 populations each with model.make_ensemble('B', 100, 1) # 100 neurons and 1 dimension # Create the connections within the model model.connect('Input', 'A') # Connect the input to A def square(x): # Define the squaring function return x[0] * x[0] model.connect('A', 'B', func = square) # Connect A to B with the # squaring function approximated # in that connection # Build the model model.build() # Run the model model.run(1) # Run the model for 1 second
8a274b169fef7b256062342ae10c0f4944d47ab8
Abdilaziz/Collections-And-Algorithms-Notes
/Example Problems/Project Euler Problems/17. Number letter counts/problem.py
1,147
3.734375
4
# coding=utf-8 # If the numbers 1 to 5 are written out in words: # one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total. # If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, # how many letters would be used? # NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) # contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. # The use of "and" when writing out numbers is in compliance with British usage. # one = 3, two = 3, three = 5, four = 4, five = 4, six = 3, seven = 5, eight = 5, nine = 4 # 1-9 = 36 letters # ten = 3, eleven = 6, twelve = 6, thirteen = 8, fourteen = 8, fifteen = 7, sixteen = 7, seventeen = 9, eighteen = 8, nineteen = 8, # 10-19 = 70 letters # 20 - 99 # each prefix 10 times (6 + 6 + 5 + 5 + 5 + 7 + 6 + 6) + 8*36 = 748 # 1-99 = 36+70+748= 854 # 100-999 # prepend by number 1-9, then 'hundred and' (10 letters) # then last is number 1-99 # special case is number 1-9 followed by 'hundred' (7 letters) # 1-99 occurs 9 times: 9*854 = 7686 # 'hundred' occurs 9 times = 7*9 = 63 # etc
6d282abae3986fb0f697448372d87af7293e49e7
avida/sandbox
/python/else.py
347
3.875
4
#!/usr/bin/env python3 import random print("hi") for i in range(3): if i is random.randint(0,3): print("Found random number") break else: print("Random number not found") try: a = list(range(3)) b = a[3] except: print("except block") else: print("except else block") finally: print("finally block")
35c4dc56cc84d34e2a34babb5c4014d73fc8a099
banchee/pirobot
/TankController/tank.py
1,768
3.8125
4
import motor class tank(object): def __init__(self): self.left_motor = motor.motor(7,11) self.right_motor = motor.motor(12,13) self.actions = {'forward':False, 'reverse':False, 'left':False, 'right':False, 'stop':False} def forward(self): if not self.actions['forward']: print 'Forward' self.left_motor.positive() self.right_motor.positive() for key, value in self.actions.items(): if key == 'forward': self.actions[key] = True else: self.actions[key] = False def reverse(self): if not self.actions['reverse']: print 'Reverse' self.left_motor.negative() self.right_motor.negative() for key, value in self.actions.items(): if key == 'reverse': self.actions[key] = True else: self.actions[key] = False def left(self): if not self.actions['left']: print 'Left' self.left_motor.positive() self.right_motor.negative() for key, value in self.actions.items(): if key == 'left': self.actions[key] = True else: self.actions[key] = False def right(self): if not self.actions['right']: print 'Right' self.left_motor.negative() self.right_motor.positive() for key, value in self.actions.items(): if key == 'right': self.actions[key] = True else: self.actions[key] = False def stop(self): if not self.actions['stop']: print 'Idle' self.left_motor.stop() self.right_motor.stop() for key, value in self.actions.items(): if key == 'stop': self.actions[key] = True else: self.actions[key] = False
12c84a54561d8c8d22ec6751d3f2258651c76b9b
mauriziokovacic/ACME
/ACME/math/barrier_function.py
627
3.671875
4
import torch from .constant import * def barrier_function(x, t): """ Returns the barrier function for a given value x and a threshold t Parameters ---------- x : Tensor the input value t : scalar the threshold value from which the barrier starts Returns ------- Tensor the barrier value """ def g(y): return (y**3)/(t**3) - 3*(y**2)/(t**2) + 3*y/t out = torch.zeros_like(x, dtype=torch.float, device=x.device) i = (x > 0) and (x < t) out[i] = torch.reciprocal(g(x[i])) - 1 out[x <= 0] = Inf return out
e906bde00c901f2672d27fc92dafe5929ea387f2
zeel1234/mypython
/ma007/Practical 9/class_static.py
628
3.671875
4
class Person: count = 0 avg_age = 70 def __init__(self,name): print("Constructor called !") self.name = name Person.count = Person.count + 1 def show(self): print("Name of person : ",self.name) @staticmethod def showCount(): print("Total count : ",Person.count) @classmethod def set_avg_age(cls,ag): cls.avg_age = ag @classmethod def get_avg_age(cls): return(cls.avg_age) # p1 = Person("person 1") p1.show() p1.showCount() Person.set_avg_age(60) print("New average age is : ",Person.get_avg_age())
81e34cd52e52cff387834da836fdd529529f9015
AbandonBlue/Coding-Every-Day
/Data_Structure/RandomizedSet.py
2,047
3.875
4
import random # Version 1 class RandomizedSet: def __init__(self): """ Initialize your data structure here. """ self.data = {} # use dict(hash table concept) to implement def insert(self, val: int) -> bool: """ Inserts a value to the set. Returns true if the set did not already contain the specified element. time: O(1) """ if val not in self.data: self.data[val] = 1 return True else: return False def remove(self, val: int) -> bool: """ Removes a value from the set. Returns true if the set contained the specified element. time: O(1) """ if val not in self.data: return False else: del self.data[val] return True def getRandom(self) -> int: """ Get a random element from the set. time: O(1) """ return random.choice(list(self.data.keys())) # without list will fail # Verson 2 class RandomizedSet2: def __init__(self): """ Initialize your data structure here. """ self.data = {} self.rdata = [] def insert(self, val: int) -> bool: """ Inserts a value to the set. Returns true if the set did not already contain the specified element. """ if val not in self.data: self.data[val] = 1 self.rdata.append(val) return True else: return False def remove(self, val: int) -> bool: """ Removes a value from the set. Returns true if the set contained the specified element. """ if val not in self.data: return False else: del self.data[val] self.rdata.remove(val) return True def getRandom(self) -> int: """ Get a random element from the set. """ return random.choice(self.rdata)
fa9c41ec83a61ec8e6762633b60b172e6d5d8b06
pavanrao/bitesofpy
/pybites_bite132/vowels.py
536
4.03125
4
import re from collections import Counter # VOWELS = list('aeiou') VOWELS = 'aeiou' def get_word_max_vowels(text): """Get the case insensitive word in text that has most vowels. Return a tuple of the matching word and the vowel count, e.g. ('object-oriented', 6)""" vowel_count = {} for word in text.lower().split(' '): # re.subn returns the count of overlapping replacements vowel_count[word] = re.subn(f'[{VOWELS}]', '', word)[1] return Counter(vowel_count).most_common()[0]
080f63cb2c383acc73ebdb557adc3dbfb8b2d000
AKondro/ITSE-1329-Python
/Chatbot Project/python3 chatbot-phase3-amykondro.py
1,262
4.28125
4
#chatbot-phase3-amykondro.py def greeter(first_name, last_name, time_of_day) : """Returns a sentence containing first name, last name and the meal depending on the time of day""" last_initial = last_name[0:1] if time_of_day == 'Morning': result = 'Have a good breakfast, '+' '+ first_name +' '+ last_initial elif time_of_day == 'Afternoon': result = 'Have a good lunch, '+' '+ first_name +' '+ last_initial elif time_of_day == 'Evening': result = 'Have a good dinner, '+' '+ first_name +' '+ last_initial return(result) count = 0 a_greeting = 'yes' #run the following loop until user doesn't want another greeting while a_greeting == 'yes': #inputs for first name, last name and time of day first_name = input('What is your first name? ') last_name = input('What is your last name? ') time_of_day = input('What time of day is it (Morining, Afternoon, Evening)? ') #calls the greeter function to get the result back sentence = greeter(first_name, last_name, time_of_day) #prints the results from the greeter function print(sentence) count=count+1 a_greeting = input('Would you like another greeting? ') print('You received' ,count, 'greetings')
e8f0572dc3d8bb7cbad002babd6b0a6a5f47e78c
tusharongit/Python
/pytraining/modules/sanitize.py
426
3.5625
4
# to ensure every data member is a capitalized string def makeCaps (var): return var.title() def cleanup (data): if type(data) != str: data = str(data) return makeCaps(data) if __name__ == "__main__": # print(makeCaps("a")) # print(makeCaps("abcd")) # x = "a" # x = "abcd efgh" x = 23 # x = False print(x,type(x)) x = cleanup(x) print(x,type(x))
8df0ed2b0e792d9c8809d9b757db0404ad97640b
masnursalim/belajar-python
/08_strings/01_strings/cek_string.py
241
4.09375
4
txt = "Belajar Python sangat menyenangkan" print("string : "+txt) print() print("Python" in txt) kata = "PHP" if kata not in txt: print(kata + " tidak ditemukan dalam string") else: print(kata + " tidak ditemukan dalam string")
47677782faa9ca5bd5f4cf711c0ea1c66b9b2c18
Fortune-Adekogbe/python_algorithms
/graph.py
4,201
4.125
4
class Vertex: """A vertex that maintains a dict of (vertex -> weight) key-value pairs of neighbors to which it is connected. This avoids needing an extra data type, EDGE, to represent connections between vertices.""" def __init__(self, node): self.node = node self.adjacent = {} def __repr__(self): """Override this to print a string representation of this object.""" return str(self.node) def print(self): print(self.node, "->", self.adjacent) def get_node(self): return self.node def add_neighbor(self, neighbor, weight=0): self.adjacent[neighbor] = weight def get_neighbors(self): return self.adjacent.keys() def get_weight(self, neighbor): return self.adjacent[neighbor] class UnweightedVertex(Vertex): """A vertex that maintains a list of vertices to which it is connected, instead of a dict with vertices and their corresponding weights. The implementation can also use a set of vertices instead of a list, which removes the ability to have parallel edges, but which speeds up queries for whether vertex_a is a neighbor of vertex_b.""" def __init__(self, node): self.node = node self.adjacent = [] def add_neighbor(self, neighbor): self.adjacent.append(neighbor) def get_neighbors(self): return self.adjacent class Graph: """A collection of vertices connected by edges to their neighbors. The vertices are maintained in a dict of (node -> vertex) key-value pairs.""" def __init__(self, vertices=None): self.vertices = {} if vertices is None else vertices def __iter__(self): """Returns all vertex instances in vertices dict.""" return iter(self.vertices.values()) def add_vertex(self, node): new_vertex = Vertex(node) self.vertices[node] = new_vertex return new_vertex # returns keys instead of values def get_nodes(self): return self.vertices.keys() def get_vertex(self, node): try: return self.vertices[node] except: return None def size(self): return len(self.vertices) def has_vertex(self, node): return node in self.vertices def add_edge(self, frm, to, cost=0, both=False): if frm not in self.vertices: self.add_vertex(frm) if to not in self.vertices: self.add_vertex(to) self.vertices[frm].add_neighbor(self.vertices[to], cost) if both: self.vertices[to].add_neighbor(self.vertices[frm], cost) class UnweightedGraph(Graph): """UnweightedVertex instances are stored instead of Vertex instances.""" def add_vertex(self, node): new_vertex = UnweightedVertex(node) self.vertices[node] = new_vertex return new_vertex def add_edge(self, frm, to, both=False): if frm not in self.vertices: self.add_vertex(frm) if to not in self.vertices: self.add_vertex(to) self.vertices[frm].add_neighbor(self.vertices[to]) if both: self.vertices[to].add_neighbor(self.vertices[frm]) def reverse(self): """Reverse (frm -> to) for neighbors of each vertex in graph.""" reversed_vertices = {} for node, vertex in self.vertices.items(): reversed_vertices[node] = UnweightedVertex(node) for v in self.vertices.values(): for u in v.get_neighbors(): reversed_vertices[u.get_node()].add_neighbor( reversed_vertices[v.get_node()] ) return UnweightedGraph(reversed_vertices) if __name__ == "__main__": g = UnweightedGraph() g.add_vertex(1) g.add_vertex(2) g.add_vertex(3) g.add_vertex(4) g.add_vertex(5) g.add_edge(1, 2) g.add_edge(1, 3) g.add_edge(2, 3) g.add_edge(3, 5) g.add_edge(3, 4) g.add_edge(5, 2) g.add_edge(5, 1) g.add_edge(1, 5) print("graph") for v in g: v.print() print("\nreverse of graph") rg = g.reverse() for v in rg: v.print()
d96ff8ffec7734d68ece2812afe0c1fe6fa219f4
aduispace/EE232E_Graphs-and-Network-Flows
/Project2_Code-and-Report/Prob1-3_generate_graph.py
3,574
3.75
4
# In this script, we will generate three dicts: # (1) id_name->{id:name} (finally abandon this thought, R cannot support this method to read graph)(2) id_movie->{id:movie1,2,3...} (3)movie_id->{movie:id1,id2,id3} edgefile = open("/Users/lindu/Desktop/Spring 2017 Classes/EE232E Graphs Mining/Project2/project_2_data/edge_weight.txt", "w") # part one: construct three dicts # id_name = dict() id_movie = dict() movie_id = dict() # print("start processing id_name dict") # with open('/Users/lindu/Desktop/Spring 2017 Classes/EE232E Graphs Mining/Project2/project_2_data/id_actors.txt') as idactors: # for line in idactors.readlines(): # word = line.split("\t\t") # # don't need to check duplicate items # id_name[word[0]] = word[1] # print("id_name dict done!") with open('/Users/lindu/Desktop/Spring 2017 Classes/EE232E Graphs Mining/Project2/project_2_data/merge_movies.txt') as idmovie: print("start processing id_movie dict") for line in idmovie.readlines(): word = line.split("\t\t") for movie in word[1:]: # word[0] is id, note in id_movie, movie is value if word[0] not in id_movie: id_movie[word[0]] = list() id_movie[word[0]].append(movie) else: id_movie[word[0]].append(movie) print("id_movie dict done!") with open('/Users/lindu/Desktop/Spring 2017 Classes/EE232E Graphs Mining/Project2/project_2_data/merge_movies.txt') as movieid: print("start processing movie_id dict") for line in movieid.readlines(): word = line.split("\t\t") for movie in word[1:]: # word[0] is id, note in movie_id, id is value if movie not in movie_id: movie_id[movie] = list() movie_id[movie].append(word[0]) else: movie_id[movie].append(word[0]) print("movie_id dict done!") # for i in movie_id: # if len(movie_id[i]) == 0: # print(i) # exit() print("start processing edge_weight") # part two: construct edge_weight file edge_number = 0 # i is the actor, j is i's movies, k is other actors in j # project2 spec not excluded self pointing for i in id_movie: i_weight = dict() # i_weight: {k: [temp, i_k_weight]} iweight = len(id_movie[i]) for j in id_movie[i]: for k in movie_id[j]: if k not in i_weight: edge_number += 1 i_weight[k] = list() i_weight[k].append(1) weight = float(1)/int(iweight) i_weight[k].append(weight) else: i_weight[k][0] += 1 weight = float(i_weight[k][1])/int(iweight) i_weight[k][1] = weight for item in i_weight: weight = str(i_weight[item][1]) weight = weight.strip() if str(i) and str(item) and weight: edgefile.write(str(i)+"\t\t"+str(item)+"\t\t"+weight+"\n")# jump to another line else: continue # edgefile.write("\n") edgefile.close() print("edge_weight dict done!" + "Producing %d weighted edges" % (edge_number)) print("all done!") ### log: # start processing id_movie dict # id_movie dict done! # start processing movie_id dict # movie_id dict done! # start processing edge_weight # edge_weight dict done!Producing 34267114 weighted edges # all done! ### data format: # {id1}\t\t{id2}\t\t{weight}
9d7975aa713d588285f37cab7c035f037274c11b
2003sl500/functions_basic_2
/countdown.py
132
3.6875
4
def countdown(num): numList = [] for x in range(num,-1,-1): numList.append(x) return numList print(countdown(5))
cf082f1c4010eb2d5557a7cedf2a6ada200d3391
chunjiw/leetcode
/L525_findMaxLength.py
1,447
3.84375
4
# 525. Contiguous Array # DescriptionHintsSubmissionsDiscussSolution # Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1. # Example 1: # Input: [0,1] # Output: 2 # Explanation: [0, 1] is the longest contiguous subarray with equal number of 0 and 1. # Example 2: # Input: [0,1,0] # Output: 2 # Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1. # Note: The length of the given binary array will not exceed 50,000. from collections import defaultdict class Solution(object): def findMaxLength(self, nums): """ :type nums: List[int] :rtype: int """ # DP: first, dp1 and dp0 represents how many 1s and 0s before index i # then ddp = dp1 - dp0 # when there are same values, that means dp1[j] - dp1[i] = dp0[j] - dp0[i], such that # there are same number of 1s and 0s between j and i. # Or, simply construct ddp: ddp[i] is the difference between number of 1s and 0s before index i dp = [0 for _ in range(len(nums) + 1)] index = defaultdict(int) for i, num in enumerate(nums): dp[i + 1] = dp[i] + num*2 - 1 index[dp[i + 1]] = max(index[dp[i + 1]], i + 1) result = 0 for i, cnt in enumerate(dp): result = max(result, index[cnt] - i) return result
e7dc80e234dbaab98a3b3f4853cf5ede556ea43d
TomiSar/ProgrammingMOOC2020
/osa03-13c_osajonon_haku/src/osajonojen_haku.py
145
3.84375
4
sana = input("Sana: ") merkki = input("Merkki: ") kohta = sana.find(merkki) if kohta + 3 <= len(sana): print(sana[kohta:kohta + 3])
79aad048361d0147b727eeb5fb30007d778fad3f
dlefcoe/daily-questions
/directed_list_edge.py
374
3.78125
4
import pandas as pd # read the data df = pd.read_csv('test_csv.csv') # build the new column df['filter']='-' for index, row in df.iterrows(): if row['from'] + '-' + row['to'] not in df['filter'].values: if row['to'] + '-' + row['from'] not in df['filter'].values: df.loc[index,'filter']= row['from'] + '-' + row['to'] print(df)
75e7152f1c7e558273ffceca43d810237371e63a
deepakrajvenkat/dhilip
/sumofnnumber.py
180
3.890625
4
n=input() if n.isdigit(): n=int(n) if n < 0: print ("enter the postive integer") else: sum=0 while(n > 0): sum+= n n-= 1 print (sum) else: print("invalid input")
f8114ec28447eee38a12cf5ac1de1c2782d617a8
strint/pybind11_examples
/08_cpp-overload-eigen/test.py
210
3.703125
4
import numpy as np import example A = np.array([[1,2,1], [2,1,0], [-1,1,2]]) B = 10 print(example.mul(A.astype(np.int ),int (B))) print(example.mul(A.astype(np.float),float(B)))
51a0c330f6d3d882daeb158e4f28b838368517b1
amuchand47/Python
/tuple.py
306
3.890625
4
''' MD Chand Alam Aligarh Muslim University ''' import sys ''' # Tuple y = [1, 2, 3] x = () x = tuple(y) print(x) z = (1, 2, 3) s = 4, 5, 6 print(z) print(s) # Immutable l = (1, 2, 3) #del(l[3]) # Error a = ([1, 3], 2, 4) del(a[0][1]) # But Inside tuple ,list can be deleted print(a) '''
eda095a560aebf7b960be86f0fae2ac304f3f6a5
layaxx/project_euler
/034_digit-factorials.py
528
3.8125
4
""" 145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145. Find the sum of all numbers which are equal to the sum of the factorial of their digits. Note: as 1! = 1 and 2! = 2 are not sums they are not included. """ # max 7 digits import math def solve(): result = 0 for i in range(10, 1000000): if isCurious(i): result += i print(result) def isCurious(input): sum = 0 for digit in str(input): sum += math.factorial(int(digit)) return sum == input solve()
bebb94edd53e0cbc01bb822c94c092d8f0eb256a
jtlai0921/XB1817-
/XB1817《資料結構 使用Python》範例程式檔案/課後習題/Ex_02_6.py
157
3.75
4
#第二章,習題6 total = 1 number = int(input('輸入一個整數,計算階乘和->')) for item in range(1, number+1): total *= item print(total)
615105c7c76c12432b37c4ff596bf6df94c770ad
shafaypro/AndreBourque
/assignment1/example.py
713
4.25
4
''' name = input("Enter any name here") # takes input of the name if name == "Shafay": print("Shafay") # this is optimal code or optimized code elif name == "Andre": # elif --> else if --> elif condition: print("Andre") elif name == "Bob": print("Bob") else: # final Option print("This is not Bob nor Andre nor Shafy") ''' # ---- if --------# number = 2 if number == 2: print("it is 2") if number % 2 == 0: print("It is even ") # -- nested if #####(if with in an if) name = "Shafay" mood = "happy" age = 20 if name == "Shafay": if mood == "happy": if age == 20: print("Shafay is Happy and is 20 years old") # Do you want Cheese and Cake ? # Yes or No --> and , or , not --> Boolean Expressions !!
05105a31d54dfef7a1a4ecaae3fe586f1aab526e
samantabueno/python
/GCD_geeksforgeeks.py
379
3.828125
4
# Greatest Common Divisor with n numbers # GCD of more than two (or array) numbers # This function implements the Euclidian # algorithm to find H.C.F. of two number def find_gcd(x, y): while (y): x, y = y, x % y return x l = [30, 35, 20, 5] num1 = l[0] num2 = l[1] gcd = find_gcd(num1, num2) for i in range(2, len(l)): gcd = find_gcd(gcd, l[i]) print(gcd)
6488b215997f68f766985eea50fdf717ab51e8a7
Rakios/Alfa
/Proyectos_Python/norepetir.py
648
3.984375
4
# -*- coding: utf-8 -*- def revisar(palabra,letra): cont = 0 for letra2 in palabra: if letra == letra2: cont += 1 if cont == 1: return letra else: return '_' def main(palabra): for letra in palabra: resultado = revisar(palabra,letra) if resultado != '_': return resultado return resultado if __name__ == '__main__': palabra = str(input('Introdusca una palabra: ')) result = main(palabra) if result == '_': print('Todas las letras se repiten') else: print('La primera letra que solo aparece una vez es {}' .format(result))
73df4ae97f94396f9dedda971555fcf89ccd6c38
gunjan-madan/Python-Solution
/Module7/3.2.py
3,887
4.34375
4
# A set is a collection which is unordered and unindexed. # Sets are written with curly brackets. ''' Task 1: Unique or Not ''' print("***** Task 1: *****") print() # In Python, you can use data structures called sets to perform operations like # - Combining items # - Finding common items # - Identifying unique items # Uncomment the statements and click Run #containerA = {"circle", "heart", "rectangle","cloud","star","bolt","moon","triangle","smiley"} #print("Container A contains:\n",containerA ) print("***** Task 1: *****") print() # Create a similar set for containerB containerB = {"circle","arrow","cloud","triangle","plus","flag"} print(containerB) ''' Task 2: Vowel Count ''' print("***** Task 2: *****") print() # Write a program to count number of vowels using sets in a given string # The key steps to follow are: # - Create a set of vowels # - Initialize a count variable to 0. # - Using a for loop, check if the letter in the string is present in the set "vowel". # - If it is present, the count variable is incremented. def vowel_count(str): # Initializing count variable to 0 count = 0 # Creating a set of vowels #vowel = set("aeiouAEIOU") vowel = ("a","e","i","o","u") # Loop to traverse the alphabet # in the given string for i in str: # Check if the alphabet is a vowel if i in vowel: count = count + 1 print("No. of vowels :", count) # Get the word from the user str = input("Enter a word: ") # Function Call vowel_count(str.lower()) ''' Task 3: Languages Galore ''' print("***** Task 3: *****") print() # Uncomment the statements below and click Run #lang={"Java","Python","C++","C#"} ## Add SQL to the set #lang.add("SQL") ## Add HTML and Perl to the set #lang.update(["HTML","Perl"]) ##Number of items in the set #print("The total number of items :",len(lang)) #print(lang) ##Remove C# #lang.remove("C#") # Here is the description to the methods used in the statements # add() - Adds an item to a set # update() - Adds multiple items to a set # len() - Determines how many items a set has # remove() - Removes an item from the set # Uncomment the statements below and click Run #lang1={"Java","Python","C++","C#","CSS"} #lang2={"HTML","Perl","CSS"} #print("Union: ",lang1 | lang2) #print("Common: ",lang1 & lang2) #print("Difference: ",lang1 - lang2) # Here is the description of the operations used in the statements # | means Union. It displays all items from both sets. # & means Intersection. It displays items common to both sets # - means Difference. The difference of the set lang1 from set lang2(lang1 - lang2) is a set of elements that are only in lang1 but not in lang2 ''' Task 4: Dat(a)nalyst or Scientist ''' print("***** Task 5: *****") print() # Write a program detailing the skill set for a data scientist and data analyst. # Create a set each for: # - Data scientist - Python, R, SQL, Scala, Java, Hive # - Data analyst - Python, SQL, BI, Excel, Tableau, R # Display the common skills between the two roles # Display the skills unique to each role # Add the following skills to each of the set: # - Data scientist - Machine Learning, Hadoop # - Data analyst - Statistics, NoSQL Create the sets datascientist = {"Python", "R", "SQL", "Scala", "Java", "Hive"} datanalyst = {"Python", "SQL", "BI", "Excel", "Tableau", "R"} print() # Skill Set print("Data Scientist Skills: ",datascientist) print("Data Analyst Skills: ",datanalyst) print() # Common Skills print("Common skills: ",datascientist & datanalyst) print() #Unique Skills print() print("Unique Data Scientist Skills: ",datascientist-datanalyst) print("Unique Data Analyst Skills: ",datanalyst-datascientist) # Add skills datascientist.update(["Machine Learning", "Hadoop"]) datanalyst.update(["Statistics", "NoSQL"]) #Updated Skill Set print() print("Updated Data Scientist Skills: ",datascientist) print("Updated Data Analyst Skills: ",datanalyst)
d96a17a49dea2e80bb62dd8f86c0e25bdd58edbc
loganetherton/quiz_exercise
/classes/School.py
1,032
3.875
4
from random import randrange class School(object): def __init__(self): """ The shool class will handle the entirety of the interactions between the students and teachers, as well as determining the schoool year, assigning quizzes, grading quizzes, assigning final grades, and printing the results of each students' performance """ self._school_year_length = None self.time_per_subject = None @property def school_year_length(self): """ The number of days in the school year """ return self._school_year_length @school_year_length.setter def school_year_length(self, value): self._school_year_length = value def determine_school_year_length(self): """ Determine the number of days in a school year """ self._school_year_length = randrange(50, 200) def assign_students_to_classes(self): """ Randomly assign students to each class """ pass
cabc5411cdcf554d8f505e098e27a0c82aed00aa
larisamara/uri-programming-computers
/ur-desvio-de-fluxo/Elf-Time.py
184
3.96875
4
n = input() a, b = input().split() result = 0 if(int(a) + int(b) <= int(n)): result = ("Farei hoje!") if(int(a) + int(b) > int(n) ): result = ("Deixa para amanha!") print(result)
dc957ddf7bd1aaf6a83563c950dbe7078e89c1db
AnonimousX1/coursepython
/Semana3/Calculo de Bhaskara.py
578
4.09375
4
print ("Extração de Raizes") a= float(input("Qual o valor do quoficiente a?: ")) b= float(input("Qual o valor de quoficiente b?: ")) c= float(input("Qual o valor de quoficiente c?: ")) delta = b**2-4*a*c if delta > 0: x = (-b+(delta**0.5))/(2*a) x2= (-b-(delta**0.5))/(2*a) if x2<x: print("as raízes da equação são", x2, "e", x) elif x>x2: print("as raízes da equação são", x, "e", x2) elif delta == 0: x = (-b+(delta**0.5))/(2*a) print("a raiz desta equação é",x) else: print("esta equação não possui raízes reais")
4c0ed8f8a30e3801a82a3740545775a7087a3d26
bitterengsci/algorithm
/九章算法/基础班LintCode/2.39.Recover Rotated Sorted Array.py
533
4.0625
4
#-*-coding:utf-8-*- ''' Description Given a rotated sorted array, recover it to sorted array in-place. For example, the orginal array is [1,2,3,4], The rotated array of it can be [1,2,3,4], [2,3,4,1], [3,4,1,2], [4,1,2,3] Example1: [4, 5, 1, 2, 3] -> [1, 2, 3, 4, 5] Example2: [6,8,9,1,2] -> [1,2,6,8,9] Challenge In-place, O(1) extra space and O(n) time. ''' class Solution: """ @param nums: An integer array @return: nothing """ def recoverRotatedSortedArray(self, nums): nums.sort()
6e85d72d245d8124cfd44b6af71cf30b5fe0230e
MarshalLeeeeee/myLeetCodes
/132-palindromePartition2.py
1,165
3.703125
4
''' 132. Palindrome Partitioning II Given a string s, partition s such that every substring of the partition is a palindrome. Return the minimum cuts needed for a palindrome partitioning of s. Example: Input: "aab" Output: 1 Explanation: The palindrome partitioning ["aa","b"] could be produced using 1 cut. ''' class Solution: def minCut(self, s): """ :type s: str :rtype: int """ if not s: return 0 else: tailPalin, cut = [0], [-1] for i,x in enumerate(s): newTailPalin = [] cut.append(cut[-1]+1) for head in tailPalin: if head and x == s[head-1]: newTailPalin.append(head-1) cut[-1] = min(cut[-1],cut[head-1]+1) elif not head: if i: cut[-1] = min(cut[-1],1) else: cut[-1] = 0 newTailPalin.append(i) # new character itself is a palindrome newTailPalin.append(i+1) # the empty string is a palindrome tailPalin = newTailPalin return cut[-1]
399ea2fc3b1efe616bc22da1227fc42e1ece7d91
YHLin19980714/week2
/lesson_0205_list.py
931
4.40625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Sep 6 11:56:50 2021 @author: fennieliang """ #list [item1, item2,...] a=['apple','melon','orange','pine apple'] a.append('tomato')# append single item #print (a) a.insert(3,'tomato')# insert into a certain position #print (a) a.remove('apple')# indicate the item to be remove #print (a) a.pop(1)#pop out a certain position print (a) a1=['fish','pork'] #a.append(a1)# append a list print(a) a.extend(a1) print(a) print (a.index('fish')) #find the index print (a.count('tomato')) #count quantity a.reverse()# do the action before printing print (a) a.sort()# in the alphabetic order print (a) a2=a.copy() #equals to a2=a print (a2) a1=['fish','pork'] a.extend(a1) print (a) a.extend('tomato') print (a) for fruit in a: print(fruit) a.clear() print (f"final list:{a}") ''' practice 0205 print the list a using range '''
6d2750ca3776983cc81021089df4dc1c5ec627d9
AbdelrahmanAhmed98/user-name-age
/Untitled9.py
188
4.15625
4
#!/usr/bin/env python # coding: utf-8 # In[2]: name = input('Enter your name: ') name age = int( input('Enter your age:')) age print('Hello', name+',','\nyour age is',age,'years old')
7f3fba9c5a8e76715c02927bbe10faf165053666
lisamarieharrison/Py-machine-learning
/week_1_gradient_descent.py
1,528
3.5
4
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D data = np.genfromtxt('C:/Users/Lisa/Documents/code/machine learning/ex1/ex1data1.txt', delimiter=',') x = data[:,0] y = data[:,1] m = x.size #Figure 1: Scatter plot of training data plt.plot(x, y, 'o') plt.xlabel('Population of City in 10,000s') plt.ylabel('Profit in $10,000s') #plt.show() X = np.column_stack((np.ones(m), x)) # add column of 1s for the intercept theta = np.zeros(2) iterations = 1500 alpha = 0.01 #gradient descent J = 10000 dJ = 10000 while abs(dJ) > 10e-10: h = theta[0] + theta[1]*x theta[0] -= alpha*(1/float(m))*sum(h-y) theta[1] -= alpha*(1/float(m))*sum((h-y)*x) dJ = J - sum(theta) J = sum(theta) line_best_fit = theta[0] + theta[1]*x plt.plot(x, line_best_fit) #plt.show() #plot cost function size = 50 theta_0 = np.repeat(np.linspace(-10, 10, size), size) theta_1 = np.tile(np.linspace(-1, 4, size), size) J = [0]*theta_0.size for l in range(0, len(theta_0)): J[l] = 1/(2*float(m))*sum((theta_0[l] + theta_1[l]*x - y)**2) ''' fig = plt.figure() ax = fig.gca(projection='3d') X = np.linspace(-10, 10, size) Y = np.linspace(-1, 4, size) X, Y = np.meshgrid(Y, X) Z = np.array(J).reshape(X.shape) surf = ax.plot_surface(Y, X, Z, rstride=1, cstride=1, cmap=plt.cm.jet, linewidth=0, antialiased=False) ax.set_zlim(0, 800) plt.show() ''' #normal equation for comparison print np.dot(np.linalg.inv(np.dot(X.T, X)), np.dot(X.T, y)) print theta
e4a5254b47d04eed47099bb1279ce8b3909263ec
santiago-quinga/Proyectos_Python
/Python Funtion #1.py
881
3.828125
4
# -*- coding: utf-8 -*- """ Created on Thu Jul 2 13:36:15 2020 @author: Santiago Quinga """ def isYearLeap(year): # # Un año es bisiesto si cumple lo siguiente: # es divisible por 4 y no lo es por 100 ó si es divisible por 400. if (year % 4 == 0) and (year % 100 != 0) or (year % 400 == 0): return True else: return False # En year podemos ingresar cualquier año # para poder realizar la prueba. year=2020 # Ingrese un año que quiera. print("¿El año %a es bisiesto?: %s" % (year, isYearLeap(year))) print("\n"*0) # # Este es el codigo para verificar si el codigo funciona correctamente. testData = [1900, 2000, 2016, 1987] testResults = [False, True, True, False] for i in range(len(testData)): yr = testData[i] print(yr,"->",end="") result = isYearLeap(yr) if result == testResults[i]: print("OK") else: print("Failed")
b00aae32ea1609546e35f30c85156e3761459c4b
usc-isi-i2/etk
/etk/crf_tokenizer.py
16,897
3.75
4
import string import sys class CrfTokenizer: """The tokenization rules take into account embedded HTML tags and entities. HTML tags begin with "<" and end with ">". The contents of a tag are treated as a single token, although internal spaces, tabs, and newlines are stripped out so as not to confuse CRF++. HTML entities begin with "&" and end with ";", with certain characters allowed inbetween. They are treated as single tokens. HTML tags and HTML entities optionally can be skipped (omitted form the output array of tokens) after recognition. There are risks to the HTML processing rules when the text being tokenized is not proper HTML. Left angle brackets can cause the following text to become a single token. Ampersands can merge into the following textual word. A possible solution to the bare ampersand problem is to recognize only the defined set of HTML entities. It is harder to think of a solution to the bare left angle bracket problem; perhaps check if they are followed by the beginning of a valid HTML tag name? There is also special provision to group contiguous punctuation characters. The way to use this tokenizer is to create an instance of it, set any processing flags you need, then call the tokenize(value) function, which will return the tokens in an array. To tokenize, breaking on punctuation without recognizing HTML tags and entities, try: t = CrfTokenizer() tokens = t.tokenize(value) To tokenize, breaking on punctuation and recognizing both HTML tags and entites as special tokens, try: t = CrfTokenizer() t.setRecognizeHtmlEntities(True) t.setRecognizeHtmlTags(True) tokens = t.tokenize(value) To tokenize, breaking on punctuation, recognizing and HTML tags and entities, and skipping the tags, try: t = CrfTokenizer() t.setRecognizeHtmlEntities(True) t.setRecognizeHtmlTags(True) t.setSkipHtmlTags(True) tokens = t.tokenize(value) The following sequence will tokenize, strip HTML tags, then join the tokens into a string. The final result will be the input string with HTML entities treated as single tokens, HTML tags stripped out, punctuation separated from adjacent words, and excess white space removed. t = CrfTokenizer() t.setRecognizeHtmlEntities(True) t.setRecognizeHtmlTags(True) t.setSkipHtmlTags(True) result = t.tokenize(value).join(" ") The same as above, but with punctuation remaining glued to adjacent words: t = CrfTokenizer() t.setRecognizePunctuation(False) t.setRecognizeHtmlTags(True) t.setSkipHtmlTags(True) result = t.tokenize(value).join(" ") """ whitespaceSet = set(string.whitespace) # whitespaceSet.add('\xc2\xa0') whitespaceSet.add(u"\u00A0") punctuationSet = set(string.punctuation) htmlEntityNameCharacterSet = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '#'} linebreaking_start_character_set = {'\n', '\r'} linebreaking_character_set = {'\n', '\r', '\t'} START_HTML_TAG_CHAR = "<" END_HTML_TAG_CHAR = ">" START_HTML_ENTITY_CHAR = "&" END_HTML_ENTITY_CHAR = ";" def __init__(self, recognize_linebreaks=False, skipHtmlTags=False, skipHtmlEntities=False, recognizePunctuation=True, recognizeHtmlTags=False, recognizeHtmlEntities=False, groupPunctuation=False, create_structured_tokens=False): self.groupPunctuation = groupPunctuation self.recognizeHtmlEntities = recognizeHtmlEntities self.recognizeHtmlTags = recognizeHtmlTags self.recognizePunctuation = recognizePunctuation # Notice self.skipHtmlEntities = skipHtmlEntities self.skipHtmlTags = skipHtmlTags self.tokenPrefix = None self.recognize_linebreaks = recognize_linebreaks self.create_structured_tokens = create_structured_tokens def setGroupPunctuation(self, groupPunctuation): """When True and self.recognizePunctuation is True, group adjacent punctuation characters into a token. """ self.groupPunctuation = groupPunctuation def setRecognizeHtmlEntities(self, recognizeHtmlEntities): """When True, assume that the text being parsed is HTML. Recognize HTML entities, such as "&gt;", and parse them into single tokens (e.g., "&gt;" instead of ["&", "gt", ";"]). """ self.recognizeHtmlEntities = recognizeHtmlEntities def setRecognizeHtmlTags(self, recognizeHtmlTags): """When True, assume that the text being parsed is HTML. Recognize HTML tags, such as "<bold>", and parse them into single tokens (e.g., "<bold>" instead of ["<", "bold", ">"]). """ self.recognizeHtmlTags = recognizeHtmlTags def setRecognizePunctuation(self, recognizePunctuation): """When True, treat punctuation characters as separate tokens. """ self.recognizePunctuation = recognizePunctuation def setSkipHtmlEntities(self, skipHtmlEntities): """When True and when self.recognizeHtmlEntities is True, skip HTML entities instead of storing them as tokens. """ self.skipHtmlEntities = skipHtmlEntities def setSkipHtmlTags(self, skipHtmlTags): """When True and when self.recognizeHtmlTags is True, skip HTML tags instead of storing them as tokens. """ self.skipHtmlTags = skipHtmlTags def setTokenPrefix(self, tokenPrefix): """When non None, a string that should be prepended to each token. This may be useful when tokens are being generated from different sources, and it is desired to be able to distinguish the source of a token. """ self.tokenPrefix = tokenPrefix def setRecognizeLinebreaks(self, recognize_linebreaks): """When True line breaks \n and \r will be recognized as tokens and all line breaking characters will be grouped into a single token. """ self.recognize_linebreaks = recognize_linebreaks def tokenize(self, value, disable=None): """Take a string and break it into tokens. Return the tokens as a list of strings. """ # This code uses a state machine: class STATE: NORMAL = 0 GROUP_PUNCTUATION = 1 PROCESS_HTML_TAG = 2 PROCESS_HTML_ENTITY = 3 GROUP_LINEBREAKS = 4 state_names = { STATE.NORMAL: "normal", STATE.GROUP_PUNCTUATION: "punctuation", STATE.PROCESS_HTML_TAG: "html", STATE.PROCESS_HTML_ENTITY: "html_entity", STATE.GROUP_LINEBREAKS: "break" } # "state" and "token" have array values to allow their # contents to be modified within finishToken(). state = [STATE.NORMAL] token = [""] # The current token being assembled. tokens = [] # The tokens extracted from the input. index = -1 def clearToken(): """Clear the current token and return to normal state.""" token[0] = "" state[0] = STATE.NORMAL def emitToken(): """Emit the current token, if any, and return to normal state.""" if len(token[0]) > 0: # add character end and start char_start, char_end = index, index + len(token[0]) if self.create_structured_tokens: new_token = {'value': token[0], 'type': state_names[state[0]], 'char_start': char_start, 'char_end': char_end} tokens.append(new_token) else: tokens.append(token[0]) clearToken() def fixBrokenHtmlEntity(): # This is not a valid HTML entity. # TODO: embedded "#" characters should be treated better # here. if not self.recognizePunctuation: # If we aren't treating punctuation specially, then just treat # the broken HTML entity as an ordinary token. # # TODO: This is not quite correct. "x& " should # be treated as a single token, althouth "s & " # should result in two tokens. state[0] = STATE.NORMAL return if self.groupPunctuation: # If all the saved tokens are punctuation characters, then # enter STATE.GROUP_PUNCTUATION insted of STATE.NORMAL. sawOnlyPunctuation = True for c in token[0]: if c not in CrfTokenizer.punctuationSet: sawOnlyPunctuation = False break if sawOnlyPunctuation: state[0] = STATE.GROUP_PUNCTUATION return # Emit the ampersand that began the prospective entity and use the # rest as a new current token. saveToken = token[0] token[0] = saveToken[0:1] emitToken() if len(saveToken) > 1: token[0] = saveToken[1:] # The caller should continue processing with the current # character. # Process each character in the input string: for c in value: index += 1 if state[0] == STATE.PROCESS_HTML_TAG: if c in CrfTokenizer.whitespaceSet: continue # Suppress for safety. CRF++ doesn't like spaces in tokens, for example. token[0] += c if c == CrfTokenizer.END_HTML_TAG_CHAR: if self.skipHtmlTags: clearToken() else: emitToken() continue if state[0] == STATE.PROCESS_HTML_ENTITY: # Parse an HTML entity name. TODO: embedded "#" # characters imply more extensive parsing rules should # be performed here. if c == CrfTokenizer.END_HTML_ENTITY_CHAR: if len(token[0]) == 1: # This is the special case of "&;", which is not a # valid HTML entity. If self.groupPunctuation is # True, return to normal parsing state in case more # punctuation follows. Otherwise, emit "&" and ";" as # separate tokens. if not self.recognizePunctuation: # TODO: This is not quite correct. "x&;" should # be treated as a single token, althouth "s &;" # should result in two tokens. token[0] = token[0] + c state[0] = STATE.NORMAL elif self.groupPunctuation: token[0] = token[0] + c state[0] = STATE.GROUP_PUNCTUATION else: emitToken() # Emit the "&" as a seperate token. token[0] = token[0] + c emitToken() # Emit the ";' as a seperate token. continue token[0] = token[0] + c if self.skipHtmlEntities: clearToken() else: emitToken() continue elif c in CrfTokenizer.htmlEntityNameCharacterSet: token[0] = token[0] + c continue else: # This is not a valid HTML entity. fixBrokenHtmlEntity() # intentional fall-through if state[0] == STATE.GROUP_LINEBREAKS: # we will look for \n\r and ignore spaces if c in CrfTokenizer.linebreaking_character_set: token[0] += c continue elif c in CrfTokenizer.whitespaceSet: continue else: emitToken() state[0] = STATE.NORMAL if c in CrfTokenizer.whitespaceSet: # White space terminates the current token, then is dropped. emitToken() # Check to see whether we should look for line breaks if c in CrfTokenizer.linebreaking_start_character_set and self.recognize_linebreaks: state[0] = STATE.GROUP_LINEBREAKS token[0] = c elif c == CrfTokenizer.START_HTML_TAG_CHAR and self.recognizeHtmlTags: emitToken() state[0] = STATE.PROCESS_HTML_TAG token[0] = c elif c == CrfTokenizer.START_HTML_ENTITY_CHAR and self.recognizeHtmlEntities: emitToken() state[0] = STATE.PROCESS_HTML_ENTITY token[0] = c elif c in CrfTokenizer.punctuationSet and self.recognizePunctuation: if self.groupPunctuation: # Finish any current token. Concatenate # contiguous punctuation into a single token: if state[0] != STATE.GROUP_PUNCTUATION: emitToken() state[0] = STATE.GROUP_PUNCTUATION token[0] = token[0] + c else: # Finish any current token and form a token from # the punctuation character: emitToken() token[0] = c emitToken() else: # Everything else goes here. Presumably, that includes # Unicode characters that aren't ASCII # strings. Further work is needed. if state[0] != STATE.NORMAL: emitToken() token[0] = token[0] + c # Finish any final token and return the array of tokens: if state[0] == STATE.PROCESS_HTML_ENTITY: fixBrokenHtmlEntity() emitToken() # Was a token prefix requested? If so, we'll apply it now. If the # normal case is not to apply a token prefix, this might be a little # more efficient than applying the prefix in emitToken(). if self.tokenPrefix is not None and len(self.tokenPrefix) > 0: tokens = map(lambda x: self.tokenPrefix + x, tokens) return tokens def main(argv=None): '''this is called if run from command line''' t = CrfTokenizer() print(t.tokenize("This is a sentence.")) print(t.tokenize("Buy???This...Now!!!")) print(t.tokenize("The <bold>only</bold> source.")) print(t.tokenize("The<bold>only</bold>source.")) print(t.tokenize("Big&gt;little.")) print(t.tokenize("Big & little.")) print(t.tokenize("blond&curly.")) print(t.tokenize("&brokenHtml")) t.setGroupPunctuation(True) t.setRecognizeHtmlTags(True) t.setRecognizeHtmlEntities(True) print(t.tokenize("Buy???This...Now!!!")) print(t.tokenize("The <bold>only</bold> source.")) print(t.tokenize("The<bold>only</bold>source.")) print(t.tokenize("Big&gt;little.")) print(t.tokenize("Big & little.")) print(t.tokenize("blond&curly.")) print(t.tokenize("&brokenHtml")) t.setSkipHtmlTags(True) t.setSkipHtmlEntities(True) print(t.tokenize("Buy???This...Now!!!")) print(t.tokenize("The <bold>only</bold> source.")) print(t.tokenize("The<bold>only</bold>source.")) print(t.tokenize("Big&gt;little.")) print(t.tokenize("Big & little.")) print(t.tokenize("blond&curly.")) print(t.tokenize("&fbrokenHtml")) t.setTokenPrefix("X:") print(t.tokenize("Tokenize with prefixes.")) t.setTokenPrefix(None) print(t.tokenize("No more prefixes.")) t.setRecognizePunctuation(False) print(t.tokenize("This is a sentence.")) print(t.tokenize("Buy???This...Now!!!")) print(t.tokenize("The <bold>only</bold> source.")) print(t.tokenize("The<bold>only</bold>source.")) print(t.tokenize("Big&gt;little.")) print(t.tokenize("Big & little.")) print(t.tokenize("blond&curly.")) print(t.tokenize("&brokenHtml")) print(t.tokenize("A line break goes here\n\t \rand a new line starts")) t.setRecognizeLinebreaks(True) print(t.tokenize("A line break goes here\n\r \rand a new line starts")) print('---\n\n') if __name__ == "__main__": sys.exit(main())
6a7bef04babf764c2accaaaa0ca10b40aa502582
ycwang522/simpleEditor
/dict.py
629
3.734375
4
# coding: cp936 ''' Created on 20161025 @author: iPC ''' print '-------------dict----------' items={('Ruby','56'),('python','89')} ite = dict(items) print ite print ite['Ruby'] d = dict(Ruby='56',python='89') print d print d['Ruby'] d.clear() print d print '-------------ֵ䷽----------' x={'username':'admin','machines':['foo','bar','baz']} y=x.copy() y['username']='wyc' y['machines'].remove('foo') print y print {}.fromkeys(['name','age']) names=['anne','jane','geogre','damon'] ages=[12,34,32,102] print zip(names,ages) for name,age in zip(names,ages): print name,'is',age,'years old!'
4116a9dab8d3501204cfd87afa23d07dc990b44c
phipps980316/TCP-simulator
/14729831_server.py
20,738
3.625
4
from socket import socket # import for the TCP Socket object from json import dumps, loads # import for turning the packet object into a json string from random import randint # import to generate random number encrypting a packet from sys import getsizeof # import to get the size of a packet object in bytes key = "IHDoqs7oZoyUVY1g8ivXtfCBYW8QKBgTy46okSL38RYSBIalXnW4AMtfBaoEJODscINVf4wZfInPWCpsBnF0lkz4q4UhiN98aEYw6V347Fv3fh034HUa6VxLcemO8VmjiY6yJjtspdGUaV7EvkG32J9F25G9Kns0ph5kHlFSJgtC3SevdOVwAUKwYMK1DJ2o" # key used for encryption end_key_position = len(key) - 1 # variable to hold the position of the last position of the encryption key class Packet: # class to represent a TCP packet def __init__(self): # class constructor to set up the object to its default values self.message = "" # variable to hold a message string self.syn_flag = 0 # variable to hold the syn flag, set to 0 for unset and 1 for set self.ack_flag = 0 # variable to hold the ack flag, set to 0 for unset and 1 for set self.fin_flag = 0 # variable to hold the fin flag, set to 0 for unset and 1 for set self.rst_flag = 0 # variable to hold the rst flag, set to 0 for unset and 1 for set self.ack_number = 0 # variable to hold the ack number self.seq_number = 0 # variable to hold the seq number def to_json(self): # function to convert a packet into a json string and then encrypt the string # the packet object gets converted into a dictionary first with keys set to represent the variables of the class packet = {"message": self.message, "syn_flag": self.syn_flag, "ack_flag": self.ack_flag, "fin_flag": self.fin_flag, "rst_flag": self.rst_flag, "ack_number": self.ack_number, "seq_number": self.seq_number } json_string = dumps(packet) # the pack is converted into a unencrypted json string current_key_position = 0 # variable to keep track of which position in the key the stream cipher is currently on encrypted_json_string = "" # variable to record the encrypted json string as it is produced random_number = randint(1, 10000) # random number is generated message_length = len(json_string) # the length of the json string is recorded random_char = chr(((random_number*message_length) % 255)) # both the length of the json string and the random number are used to generate a random character that will give the cipher text a bit of randomness especially if the same messsage is sent repeatedly encrypted_json_string += random_char # the random character is the first character of the cipher text however both this character and the key would be needed to decipher the message for byte_to_encrypt in json_string: # loop through the characters in the json string and encrypt each of them if current_key_position > end_key_position: # if the current key position is going to go past the end position of the key, reset the position to 0 as this will stop the program trying to access non existing characters current_key_position = 0 output_byte = ord(byte_to_encrypt) ^ (ord(random_char) ^ ord(key[current_key_position])) # use XOR to encrypt each letter with the random character and the key encrypted_json_string += chr(output_byte) # add the result of the XOR operation to the output string current_key_position += 1 # increment the position in the key by 1 return encrypted_json_string # return the encrypted json string def to_object(self, json_string): # function to turn a incoming encrypted json string into a packet object current_key_position = 0 # variable to keep track of which position in the key the stream cipher is currently on decrypted_json_string = "" # variable to record the encrypted json string as it is produced random_char = json_string[0:1] # splice the first character off of the incoming string encrypted_json_string = json_string[1:] # store the remaining characters as a string for byte_to_decrypt in encrypted_json_string: # loop through the characters in the json string and decrypt each of them if current_key_position > end_key_position: # if the current key position is going to go past the end position of the key, reset the position to 0 as this will stop the program trying to access non existing characters current_key_position = 0 output_byte = ord(byte_to_decrypt) ^ (ord(random_char) ^ ord(key[current_key_position])) # use XOR to decrypt each letter with the random character and the key decrypted_json_string += chr(output_byte) # add the result of the XOR operation to the output string current_key_position += 1 # increment the position in the key by 1 # change the decrypted json string into a packet object incoming_packet = loads(decrypted_json_string) self.message = incoming_packet["message"] self.syn_flag = incoming_packet["syn_flag"] self.ack_flag = incoming_packet["ack_flag"] self.fin_flag = incoming_packet["fin_flag"] self.rst_flag = incoming_packet["rst_flag"] self.ack_number = incoming_packet["ack_number"] self.seq_number = incoming_packet["seq_number"] class State: # class to represent the states in the state diagram currentContext = None # variable to hold the current context def __init__(self, context): # constructor for state that will set the current context to the value passed in as a parameter self.currentContext = context def trigger(self): # default trigger for all states that is overridden in each state class return True class StateContext: state = None # variable to hold the dictionary key of the current state currentState = None # variable to hold the current state availableStates = {} # a dictionary of available states def setState(self, newState): # function to change the state of the state machine to the given state name in the parameter try: self.currentState = self.availableStates[newState] # fetch the object of the desired state from the available state dictionary self.state = newState # record the key used to fetch the desired state self.currentState.trigger() # call the trigger function of the new state return True except KeyError: # catch if the desired state name does not exist in the dictionary return False def getStateIndex(self): # function to return the state variable of this class return self.state class Transition: # a class to hold all of the default transitions for the state machine so that if a transition is unavailable in a given state, an error message will be displayed def passive_open(self): print "Error! Passive Open Transition Not Available!" return False def syn(self): print "Error! Syn Transition Not Available!" return False def ack(self): print "Error! Ack Transition Not Available!" return False def rst(self): print "Error! Rst Transition Not Available!" return False def syn_ack(self): print "Error! Syn Ack Transition Not Available!" return False def close(self): print "Error! Close Transition Not Available!" return False def fin(self): print "Error! Fin Transition Not Available!" return False def timeout(self): print "Error! Timeout Transition Not Available!" return False def active_open(self): print "Error! Active Open Transition Not Available!" return False class ClosedState(State, Transition): # class to represent the closed state of the state machine def __init__(self, context): # constructor to call the superclasses constructor State.__init__(self, context) def passive_open(self): # function to open the server side of the TCP connection and shift to the listen state self.currentContext.socket = socket() # create a new socket object within the current context try: print "Opening Connection" self.currentContext.socket.bind((self.currentContext.host, self.currentContext.port)) # set the address and port number for the connection, here it will be the loopback address self.currentContext.socket.listen(1) # listen for a total of 1 connection at any given time self.currentContext.connection, self.currentContext.connection_address = self.currentContext.socket.accept() # accept the first available incoming connection except: self.currentContext.setState("CLOSED") # transition back to the closed state if an error occurs self.currentContext.setState("LISTEN") # transition to the listen state return True def trigger(self): # states's trigger function to run as soon as the state is changed print "Entering Closed State" if self.currentContext.end: # if the end boolean is set to true, return true which will end the demo return True if self.currentContext.connection_address is not 0: # if the connection address is not 0, indicating an existing connection, reset the TCP connection self.currentContext.socket.close() self.currentContext.connection_address = 0 self.currentContext.socket = None self.currentContext.connection = None self.currentContext.seq_number = 0 self.currentContext.ack_number = 0 self.currentContext.passive_open() # call to the passive open transition return True class ListenState(State, Transition): # class to represent the listen state of the state machine def __init__(self, context): # constructor to call the superclasses constructor State.__init__(self, context) def syn(self): # function to send a synack packet and transition to the syn received state print "Received SYN Command, Sending SYNACK Command" packet = Packet() # create a new packet packet.syn_flag = 1 # set the syn flag packet.ack_flag = 1 # set the ack flag packet.seq_number = self.currentContext.seq_number # set the seq number packet.ack_number = self.currentContext.ack_number # set the ack number self.currentContext.connection.send(packet.to_json()) # convert the packet to an encrypted json string and send it along the socket self.currentContext.seq_number += 1 # increase the seq number by 1 becuase of the sent syn self.currentContext.setState("SYNRECEIVED") # change to the syn received state return True def trigger(self): # states's trigger function to run as soon as the state is changed print "Entering Listen State" while True: raw_data = self.currentContext.connection.recv(1024) # receive the next json string packet = Packet() # create a new packet try: packet.to_object(raw_data) # convert the json string into a packet object except: pass if packet.seq_number == self.currentContext.ack_number: # accept the packet if the seq number is as expected if packet.syn_flag is 1: # if the syn flag is set, and no timeout is to occur, update the ack number and call the syn transition go_to_timeout = raw_input("Go To Timeout (y/n) :") if go_to_timeout == "n": self.currentContext.ack_number = packet.seq_number + 1 self.currentContext.syn() return True if packet.rst_flag is 1: # if the rst flag is set, maintain the connection after the server has reset print "Client Timed Out And Reset" self.currentContext.socket.listen(1) self.currentContext.connection, self.currentContext.connection_address = self.currentContext.socket.accept() class SynReceivedState(State, Transition): # class to represent the syn received state of the state machine def __init__(self, context): # constructor to call the superclasses constructor State.__init__(self, context) def ack(self): # function to change to the established state when an ack has been received print "Received ACK Command" self.currentContext.setState("ESTABLISHED") return True def trigger(self): # states's trigger function to run as soon as the state is changed print "Entering Syn Received State" while True: raw_data = self.currentContext.connection.recv(1024) # receive the next json string packet = Packet() # create a new packet packet.to_object(raw_data) # convert the json string into a packet object if packet.seq_number == self.currentContext.ack_number: # accept the packet if the seq number is as expected if packet.ack_flag is 1: # if the ack flag is set, call the ack transition self.currentContext.ack() return True class EstablishedState(State, Transition): # class to represent the established state of the state machine def __init__(self, context): # constructor to call the superclasses constructor State.__init__(self, context) def fin(self): # function to send an ack packet in response to a fin packet and transition to the close wait state print "Received FIN Command, Sending ACK Command" packet = Packet() # create a new packet packet.ack_flag = 1 # set the ack flag packet.seq_number = self.currentContext.seq_number # set the seq number packet.ack_number = self.currentContext.ack_number # set the ack number self.currentContext.connection.send(packet.to_json()) # convert the packet to an encrypted json string and send it along the socket self.currentContext.setState("CLOSEWAIT") # transition to close wait state return True def trigger(self): # states's trigger function to run as soon as the state is changed print "Entering Established State" while True: raw_data = self.currentContext.connection.recv(1024) # receive the next json string packet = Packet() # create a new packet packet.to_object(raw_data) # change the json string to a packet object if packet.seq_number == self.currentContext.ack_number: # accept the packet if the seq number is as expected if packet.fin_flag is 1: # if the fin flag is set, update the ack number and call the fin transition self.currentContext.ack_number = packet.seq_number + 1 self.currentContext.fin() return True else: # otherwise if the packet wasnt dropped, send an ack in response drop_packet = raw_input("Drop Packet (y/n) :") if drop_packet == "n": self.currentContext.ack_number = (packet.seq_number + getsizeof(packet)) # update the ack number print "Received Message:", packet.message.rstrip() print "Sending ACK Command To Confirm Message Was Received" packet = Packet() # create a new packet packet.ack_flag = 1 # set the ack flag packet.seq_number = self.currentContext.seq_number # set the seq number packet.ack_number = self.currentContext.ack_number # set the ack number self.currentContext.connection.send(packet.to_json()) # send the packet as a json string along the socket class CloseWaitState(State, Transition): # class to represent the close wait state of the state machine def __init__(self, context): # constructor to call the superclasses constructor State.__init__(self, context) def close(self): # function to send a fin packet and transition to the last ack state print "Closing Connection, Sending FIN Command" packet = Packet() # create a new packet packet.fin_flag = 1 # set the fin flag packet.seq_number = self.currentContext.seq_number # set the seq number packet.ack_number = self.currentContext.ack_number # set the ack number self.currentContext.connection.send(packet.to_json()) # send the packet as a json string self.currentContext.seq_number += 1 # update the seq number self.currentContext.setState("LASTACK") # transition to the last ack state return True def trigger(self): # states's trigger function to run as soon as the state is changed print "Entering Close Wait State" self.currentContext.close() # call the close transition return True class LastAckState(State, Transition): # class to represent the close wait state of the state machine def __init__(self, context): # constructor to call the superclasses constructor State.__init__(self, context) def ack(self): # function to transition to the closed state when an ack has been received print "Received ACK Command" self.currentContext.end = True # sets the end bool to true to end the demo self.currentContext.setState("CLOSED") # trnasitions to the closed state return True def trigger(self): # states's trigger function to run as soon as the state is changed print "Entering Lack Ack State" while True: raw_data = self.currentContext.connection.recv(1024) # receive the next json string packet = Packet() # create a new packet packet.to_object(raw_data) # change the json string to a packet object if packet.seq_number == self.currentContext.ack_number: # if the seq number matches the expected ack number if packet.ack_flag is 1: # if the ack flag is set, call if the ack transition self.currentContext.ack() return True class TCPServer(StateContext, Transition): # class to represent the context for the state machine def __init__(self): # constructor to set all of the variables to default values and start the server by transitioning to the closed state self.host = "127.0.0.1" # variable to hold the desired address to bind to the socket self.port = 5000 # variable to hold the desired port number to bind to the socket self.connection_address = 0 # variable to hold the address of the connected client self.socket = None # variable to hold the socket object self.connection = None # variable to hold the connection object self.seq_number = 0 # variable to hold the seq number self.ack_number = 0 # variable to hold the ack number self.end = False # variable to hold the end bool # add instances of each state to the available state dictionary self.availableStates["CLOSED"] = ClosedState(self) self.availableStates["LISTEN"] = ListenState(self) self.availableStates["SYNRECEIVED"] = SynReceivedState(self) self.availableStates["ESTABLISHED"] = EstablishedState(self) self.availableStates["CLOSEWAIT"] = CloseWaitState(self) self.availableStates["LASTACK"] = LastAckState(self) print "Transitioning To Closed State" self.setState("CLOSED") # transition to the closed state # functions to call the transition functions for the state that the machine is current in def passive_open(self): return self.currentState.passive_open() def syn(self): return self.currentState.syn() def ack(self): return self.currentState.ack() def rst(self): return self.currentState.rst() def syn_ack(self): return self.currentState.syn_ack() def close(self): return self.currentState.close() def fin(self): return self.currentState.fin() def timeout(self): return self.currentState.timeout() def active_open(self): return self.currentState.active_open() if __name__ == '__main__': server = TCPServer()
788bebf8e78dbd0600509c76eb9fdff81917a896
Sophie-WH/exercises
/chapter-2/ex-2-3.py
813
4.34375
4
# Programming Exercise 2-3 # # Program to convert area in square feet to acres. # This program will prompt a user for the size of a tract in square feet, # then use a constant ratio value to calculate it value in acres # and display the result to the user. # Variables to hold the size of the tract and number of acres. # be sure to initialize these as floats tract = 0 acres = 0 # Constant for the number of square feet in an acre. sFeetInAcres = 43560 # Get the square feet in the tract from the user. # you will need to convert this input to a float tract = float(input("How many square feet? ")) # Calculate the number of acres. acres = tract / sFeetInAcres # Print the number of acres. # remember to format the acres to two decimal places printer = str.format("{:.2f} Acres", acres) print (printer)
97ef4410bde664fb094719fcb1338c02de6e2eef
ceddyzhang/demopython
/a7q2.py
3,102
4.0625
4
## ##************************************************************* ##Assignment 7 Question 2 ##Cedric Zhang ##Caesar Code ##************************************************************* ## A = ['_','.','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'] ##encypt_char: str[len=1] -> str ##Purpose: Encrypts a single character s to caesar code ##Examples: encrypt_char('z')=>'a' ##encrypt_char('a')=>'d' def encrypt_char(s): return A[(A.index(s)+3)%28] ##Testing ##encrypt_char('a')=>'d' print 'encrypt_char Test 1' answer=encrypt_char('a') expected='d' print answer == expected ##encrypt_char('z')=>'a' print 'encrypt_char Test 2' answer=encrypt_char('z') expected='a' print answer == expected ##encrypt_char('x')=>'_' print 'encrypt_char Test 3' answer=encrypt_char('x') expected='_' print answer == expected ##caesar_encrypt: str -> str ##Purpose: Consumes plain text, and encrypts it to caesar code ##Example: caesar_encrypt('') => '' ##caesar_encrypt('hello._goodbye.') => 'khoorcbjrrge.hc' def caesar_encrypt(plain): if plain=='': return '' else: return encrypt_char(plain[0]) + caesar_encrypt(plain[1:]) ##Testing ##caesar_encrypt('') => '' print 'caesar_encrypt Test 1' answer = caesar_encrypt('') expected = '' print answer == expected ##caesar_encrypt('hello._goodbye.') => 'khoorcbjrrge.hc' print 'caesar_encrypt Test 2' answer = caesar_encrypt('hello._goodbye.') expected = 'khoorcbjrrge.hc' print answer == expected ##caesar_encrypt('hot') => 'krw' print 'caesar_encrypt Test 3' answer = caesar_encrypt('hot') expected = 'krw' print answer == expected ##decrypt_char: str[len=1] -> str ##Purpose: Consumes a single str and decrypts it ##Examples: decrypt_char('e')=>'b' ##decrypt_char('_')=>'x' def decrypt_char(s): return A[(A.index(s)-3)%28] ##Testing ## decrypt_char('e')=>'b' print 'decrypt_char Test 1' answer = decrypt_char('e') expected = 'b' print answer == expected ## decrypt_char('_')=>'x' print 'decrypt_char Test 2' answer = decrypt_char('_') expected = 'x' print answer == expected ## decrypt_char('b')=>'_' print 'decrypt_char Test 3' answer = decrypt_char('b') expected = '_' print answer == expected ##caesar_decrypt: str -> str ##Purpose: Consumes a cipher text and decrypts it ##Examples: caesar_decrypt('') => '' ##caesar_decrypt('khoorcbjrrge.hc') => 'hello._goodbye.' def caesar_decrypt(cipher): if cipher=='': return '' else: return decrypt_char(cipher[0]) + caesar_decrypt(cipher[1:]) ##Testing ##caesar_decrypt('') => '' print 'caesar_decrypt Test 1(empty text)' answer = caesar_decrypt('') expected = '' print answer == expected ##caesar_decrypt('khoorcbjrrge.hc') => 'hello._goodbye.' print 'caesar_decrypt Test 2' answer = caesar_decrypt('khoorcbjrrge.hc') expected = 'hello._goodbye.' print answer == expected ##caesar_decrypt('krw') => 'hot' print 'caesar_decrypt Test 3' answer = caesar_decrypt('krw') expected = 'hot' print answer == expected
72b71653a855aefbbde266a67363d0515954bd27
wolf-tickets/pythonthehardway
/ex18.py
346
3.59375
4
def print_two(*args): arg1, arg2 = args print "arg1: %r, arg2: %r." % (arg1, arg2) def print_two_again(arg1, arg2): print "arg1: %r, arg2: %r." % (arg1, arg2) def print_one(arg1): print "arg1: %r." % arg1 def print_name(): print "I got nothin." print_two("Al", "Smith") print_two_again("Al", "Smith") print_one("First") print_name()
9b309f3747cc660d82b82371cf6b6d3c28b9ee73
Vigyrious/python_fundamentals
/Functions-More-Exercises/Tribonacci-Sequence .py
442
4.125
4
number = int(input()) def tribonnacci(num): tribbonacci_list = [1, 1, 2] if num == 1: print("1") elif num == 2: print("1 1") elif num == 3: print("1 1 2") else: print("1 1 2",end=" ") for i in range(number-3): result = sum(tribbonacci_list[len(tribbonacci_list) - 3:]) tribbonacci_list.append(result) print(result,end=" ") tribonnacci(number)
82bfa686b0ba2ad97c73982ea98d174e5df9658e
s3465535/s3465535
/latlon_5.py
3,330
3.5
4
#!/usr/bin/python #latlon_5.py import re #do this to downoad the function regular expression def decimalat(DegString): #functions must be defined before you can use it (def=define) SearchStr='(\d+) ([\d\.]+) (\w)' #this requires that you open the InFile later, because they belong together # Result=re.search(SearchStr,ElementList[2]) #the result should search for ElementList[2] which the program has to find Result=re.search(SearchStr,DegString) # DegreeString=Result.group(1) #(1) means the same like $1 in jEdit # MinuteString=Result.group(2) # Compass=Result.group(3) print Result.group(2) Degrees=float(Result.group(1)) Minutes=float(Result.group(2)) Compass=Result.group(3).upper() DecimalDegree = Degrees + Minutes/60 #/60 because of sec. & hours if Compass=='S' or Compass=='W': #south and west DecimalDegree=-DecimalDegree return DecimalDegree #return means, which function it has to send back, has to stand before the for loop & before the program is readed InFileName='Marrus_claudanielis.txt' #now open the file OutFileName='dec_'+InFileName WriteOutFile= True InFile=open(InFileName,'r') HeaderLine='dive\tdepth\tlatitude\tlongitude\tdate\tcomment' print HeaderLine #write the Headliner for the list you are building #all in all you this script copys choosen parts out of the different ElementLists and paste them into a new list/table if WriteOutFile: OutFile=open(OutFileName,'w') OutFile.write(HeaderLine+'\n') LineNumber=0 for Line in InFile: #read files (ElementLists) in a for loop with if statements... if it like... than...and than add the placemarkers &after that LineNumber+=1 to start again at the beginning. if LineNumber>0: Line=Line.strip('\n') ElementList=Line.split('\t') Dive=ElementList[0] #here you define what you copy and paste (s.a.) Date=ElementList[1] Depth=ElementList[4] Comment=ElementList[5] print "Look here", ElementList[2], ElementList[3] LatDegrees=decimalat(ElementList[2]) #define Latitude and Longitude, so that the program can recognize them LonDegrees=decimalat(ElementList[3]) print "Look here after decimalar", LatDegrees, LonDegrees print 'Lat: %f, Lon:%f' %(LatDegrees,LonDegrees) #print for check PlacemarkString=''' <Placemark> <name>Marrus - %s</name> <description>%s</description> <Point> <altitudeMode>absolute</altitudeMode> <coordinates>%f, %f, -%s</coordiantes> <Point> </Placemark>''' % (Dive,Line,LonDegrees,LatDegrees,Depth) if WriteOutFile: OutFile.write(PlacemarkString) else: print PlacemarkString LineNumber+=1 InFile.close() if WriteOutFile: print'Saved',LineNumber,'records form',InFileName,'as',\ OutFileName OutFile.write('\n</Documents>\n</kml>\n') OutFile.close() else: print '\n</Document>\n</kml>\n' #here you modify the latlon_4.py script, so that it can be used for Google Earth #you want translate in KML = Keyhole Markup Language #because not all data are KML yet, you should change them all & put all data from the inputfile into the outputfile #but the placemarker is used to generate a header #so that you now generate headeer & fooder within a loop #the resulting string also has to include the line-endings \n #as you see in the following you can insert all 5 values at once, what is faster & shorter than do it one by one #you parse strings of other files into your list
b928d90b98d705d89f462edfeb2b26e071ebc97b
balupabbi/Practice
/DS_and_ALG/DP_recusion_backtrack/BuySellStocks.py
1,534
3.515625
4
""" Buy Sell stocks: https://www.youtube.com/watch?v=mj7N8pLCJ6w Buy Sell stockII: https://www.youtube.com/watch?v=blUwDD6JYaE """ def maxProfit(s): """ O(n^2) solution for only one transaction :param s: :return: """ #Brute Force p = 0 days = [] for i in range(len(s)): for j in range(i,len(s)): diff = s[j]-s[i] if diff > p: p = diff days = [i,j] return p, days def maxProfit2(prices): """ O(n) solution where theres is only one transaction :param s: :return: """ if not prices: return 0 max_profit = float("-inf") #profit min = float("inf") for i in range(len(prices)): if prices[i] < min: min = prices[i] max_profit = max(max_profit,prices[i]-min) return max_profit def buysell2(prices): """ Multiple transactions for max profit :param prices: :return: """ mp = 0 #sum(cmax-cmin) if not prices: return mp for i in range(len(prices)-1): if prices[i]<prices[i+1]: cp = prices[i+1] - prices[i] mp += cp return mp def buysell_faster(prices): profit = 0 prev = prices[0] for curr in prices[1:]: if curr > prev: profit += curr - prev prev = curr return profit if __name__ == "__main__": s = [7,1,5,3,4,6] #s = [] #s= [7,6,4,3,1] #s = [2,4,1] #print(maxProfit2(s)) print(buysell2(s))
a18a2e364c0bf61010546c0f09e8b5155cf4a951
nerewarin/adventofcode2019
/12.py
4,673
3.828125
4
""" --- Day 12: The N-Body Problem --- https://adventofcode.com/2019/day/12 """ import os import re import itertools from dataclasses import dataclass @dataclass() class _Moon: x: int y: int z: int vx: int = 0 vy: int = 0 vz: int = 0 @property def coords(self): return self.x, self.y, self.z @coords.setter def coords(self, xyz): self.x, self.y, self.z = xyz @property def velocity(self): return self.vx, self.vy, self.vz @velocity.setter def velocity(self, xyz): self.vx, self.vy, self.vz = xyz def __repr__(self): return f'pos=<x={self.x}, y={self.y}, z={self.z}>, vel=<x={self.vx}, y={self.vy}, z={self.vz}>' @staticmethod def _get_velocity(a, b): if a > b: return -1 elif a < b: return 1 return 0 @property def potential_energy(self): return sum(abs(coord) for coord in self.coords) @property def kinetic_energy(self): return sum(abs(coord) for coord in self.velocity) @property def total_energy(self): return self.potential_energy * self.kinetic_energy def __str__(self): return f'pot: {self.potential_energy}; kin: {self.kinetic_energy}; total: {self.total_energy}' @dataclass class Moon(_Moon): def update_velocity(self, moon: _Moon): self.vx += self._get_velocity(self.x, moon.x) self.vy += self._get_velocity(self.y, moon.y) self.vz += self._get_velocity(self.z, moon.z) def move(self): self.x += self.vx self.y += self.vy self.z += self.vz class NbodyProblem: inp_rexp = re.compile(r'<x=(-*\d+), y=(-*\d+), z=(-*\d+)>\s*') dim = 3 def __init__(self, moons=None): if moons is None: with open(os.path.join('inputs', '{}.txt'.format(__file__.split('/')[-1].split('.')[0]))) as f: lines = f.readlines() else: lines = [line for line in moons.split('\n') if line.strip()] moons = [map(int, self.inp_rexp.match(moon).groups()) for moon in lines] self.moons = [Moon(*coords) for coords in moons] self.tick = 0 self.history = [ [] for x in range(self.dim) ] self.periods = [ 0 for x in range(self.dim) ] @property def period_found(self): return all(self.periods) def _update_history(self): for idx in range(self.dim): if self.periods[idx]: continue coord = tuple(moon.coords[idx] for moon in self.moons) vel = tuple(moon.velocity[idx] for moon in self.moons) state = (coord, vel) if state in self.history[idx]: self.periods[idx] = self.tick -1 if not self.history[idx]: self.history[idx].append(state) @property def total_energy(self): return sum(moon.total_energy for moon in self.moons) def simulate(self, steps): for x in range(steps): self.tick += 1 for moon1, moon2 in itertools.permutations(self.moons, 2): moon1.update_velocity(moon2) self._update_history() for moon in self.moons: moon.move() return self.total_energy def find_period(self): while not self.period_found: self.simulate(1) return nok2( nok2(*self.periods[:2]), self.periods[2] ) inp = ''' <x=-1, y=0, z=2> <x=2, y=-10, z=-7> <x=4, y=-8, z=8> <x=3, y=5, z=-1> ''' inp2 = ''' <x=-8, y=-10, z=0> <x=5, y=5, z=10> <x=2, y=-7, z=3> <x=9, y=-8, z=-3> ''' def test(test_num): if test_num == 1: res = NbodyProblem(inp).simulate(10) assert res == 179, 'test{} failed!: {}'.format(test_num, res) if test_num == 2: res = NbodyProblem(inp).find_period() assert res == 2772, 'test{} failed!: {} USE simulate(2772) TO TEST!'.format(test_num, res) if test_num == 3: res = NbodyProblem(inp2).find_period() assert res == 4686774924, 'test{} failed!: {}'.format(test_num, res) return 'test{} ok'.format(test_num) def part1(*args, **kwargs): pr = NbodyProblem(*args) pr.simulate(1000) return pr.total_energy def part2(*args, **kwargs): pr = NbodyProblem(*args) return NbodyProblem().find_period() from math import gcd def nok2(a, b): return a * b // gcd(a, b) if __name__ == '__main__': for res in ( # test(1), # part1(), # test(2), # test(3), part2(), ): print(res)
83ccd36e9c83fd3878b598b6ed246eeb6d1a4c9d
john-m-hanlon/Python
/Sentdex Tutorials/Intermediate Python 3 Tutorial [Sentdex]/09 - Writing our own Generator.py
1,422
4
4
""" This file contains code for use with "Intermediate Python Programming" by Sentdex, available from https://www.youtube.com/user/sentdex/ Transcribed by: John Hanlon Twitter: @hanlon_johnm LinkedIn: http://bit.ly/2fcxlEw Github: bit.ly/2fSDp4J """ def simple_gen(): ''' A simple generator that allows us to iterate over the yielded components Parameters ========== Takes no parameters Returns ======= Returns nothing ''' yield 'Oh' yield 'hello' yield 'there' for i in simple_gen(): print(i) correct_combo = (3, 6, 1) found_combo = False for c1 in range(10): if found_combo: break for c2 in range(10): if found_combo: break for c3 in range(10): if (c1, c2, c3) == correct_combo: print('Found the combo: {}'.format((c1, c2, c3))) found_combo = True break print(c1, c2, c3) def combo_gen(): ''' Yields thing in a stream Parameters ========== Takes no parameters Returns ======= Returns nothing ''' for c1 in range(10): for c2 in range(10): for c3 in range(10): yield (c1, c2, c3) for (c1, c2, c3) in combo_gen(): print(c1, c2, c3) if (c1, c2, c3) == correct_combo: print('Found the combo: {}'.format((c1, c2, c3))) break print(c1, c2, c3)
005bfaca231df5ef59675f62d3d7deed421435df
manojkumar-github/books
/professional-python/part-2-classes/metaclasses/writing_metaclasses.py
3,498
4.0625
4
""" Classes are just objects and metaclasses are just classes. Any class that subclasses "type" is capable of functioning as a metaclass """ """ Rule 1: Never attempt to declare or use a metaclass does not subclass "type". This will cause havoc in Python's multiple inheritence Rule 2: Python's inheritence model requires any class to have exactly one metaclass. Inheriting from two classes with different metaclass is acceptable if and only if one of the metaclasses is a direct subclass of other. (in which case, the subclass is used). Rule 3: Attempting to implement metaclass that does not subclass "type" will break multiple inheritence with any classes that use that metaclass , along with any classes that use "type" Rule 4: a custom metaclass must define a __new__ method. This method handles the creation of the class and must return the new class. The arguments sent to __new__ method in custom metaclasses must mirror the argument sent to type's __new__ method which takes four positional arguments """ """ __new__ method arguments: 1) first argument is metaclass itself. By convention this argument is called "cls". 2) Second, the desired name of the class as string(name) 3) A tuple of class's superclasses(bases) 4) A dictionary of attributes that the class should contain(attrs) Most custom implementation of __new__ method in metaclasses should ensure that they call the superclass implementation, and perform whatever work is needed in the code around that """ """ __new__ versus __init__: In classes and metaclasses __new__ method is responsible for creating and returning an object. Conversely, __init__ method is responsible for customizing the object after it has been created and returns nothing. Generally, in ordinary classes we dont really define __new__ method as the implementation of __new__ in "object" superclass is suffice whereas we do customize and implement __init__ for the ordinary classes. Whereas for the metaclasses, we dont really bother about __init__ implementation most of the times. In custom metaclasses, generally we should override the __new__ method carefully as we should "always must" call superclass implementation. "type"'s implementation of __new__ will actually provide us with the object we need to do work on and return """ """ A trivial Metaclass """ class Meta(type): def __new__(cls, name, bases, attrs): return super(Meta, cls).__new__(cls, name, bases, attrs) # A class that uses metaclass "Meta" C = Meta('C',(object,), {}) print "type of C is : ", type(C) # where as a normal class class N(object): pass print (type(N)) """ MetaClass Inheritence """ class D(C): pass print "type of D is: ", type(D) class Z(C, N): pass print "type of Z is : ", type(Z) """ In this case, the python interpreter examines C and realizes that it is an instance of "Meta". Then it examines "N", and realizes that it is an instance of "type". This is a POTENTIAL CONFLICT. (the two superclasses have different metaclasses) However, python interpreter also realizes that the "Meta" is a direct subclass of "type". Therefore, it knows that it can safely use "Meta". If above two metaclasses are not subclass of one on other. Check out below """ class OtherMeta(type): def __new__(cls, name, bases, attrs): return super(OtherMeta, cls).__new__(cls, name, bases, attrs) OtherC = OtherMeta('OtherC', (object, ), {}) print "type of OtherC is: ", type(OtherC) class Invalid(C, OtherC): pass
1a7b7b02424aa20ee690275367e914da94dbca42
WinrichSy/HackerRank-Solutions
/Python/SymmetricDifference.py
328
3.53125
4
#Symmetric Difference #https://www.hackerrank.com/challenges/symmetric-difference/problem first = int(input()) a = set([int(i) for i in input().split()]) second = int(input()) b = set([int(i) for i in input().split()]) diff = [i for i in a.difference(b)] + [i for i in b.difference(a)] diff.sort() for i in diff: print(i)
70c22d5a2eaeee3e37a9cdc242cf91b9bef66857
Aman-Achotani/Python-Projects
/Snake_Water_gun.py
2,929
3.96875
4
import random print("\t WELCOME TO SNAKE , WATER , GUN GAME") p_name = input("Please enter your name :\n") c_win = 0 c = ["Snake","Water","Gun"] p_win = 0 rounds = 1 ties = 0 print("This game will have 5 rounds") print("Lets start the game",p_name) while (rounds!= 6): c_choice = random.choice(c) p_choice = input("For snake enter : 's'\nFor Water enter : 'w'\nFor Gun enter : 'g' \n") print("Round ",rounds) if p_choice == "s": if c_choice == "Snake": print(p_name,"choice is Snake and computer also choosed Snake ") print("Round tied") rounds = rounds+1 ties = ties +1 elif c_choice == "Water": print(p_name,"choice is Snake and computer choosed Water") print(p_name,"Won!!!") rounds = rounds+1 p_win = p_win+1 elif c_choice == "Gun": print(p_name,"choice is Snake and computer choosed Gun ") print("Computer won") rounds = rounds+1 c_win = c_win+1 elif p_choice == "w": if c_choice == "Water": print(p_name,"choice is Water and computer also choosed Water ") print("Round tied") rounds = rounds+1 ties = ties +1 elif c_choice == "Gun": print(p_name,"choice is Water and computer choosed Gun") print(p_name,"Won!!!") rounds = rounds+1 p_win = p_win+1 elif c_choice == "Snake": print(p_name,"choice is Water and computer choosed Snake ") print("Computer won") rounds = rounds+1 c_win = c_win+1 elif p_choice == "g": if c_choice == "Gun": print(p_name,"choice is Gun and computer also choosed Gun ") print("Round tied") rounds = rounds+1 ties = ties +1 elif c_choice == "Snake": print(p_name,"choice is Gun and computer choosed Snake") print(p_name,"Won!!!") rounds = rounds+1 p_win = p_win+1 elif c_choice == "Water": print(p_name,"choice is Gun and computer choosed Water ") print("Computer won") rounds = rounds+1 c_win = c_win+1 else : print("Invalid choice") print() print("Results:") print(p_name,"won",p_win,"rounds") print("Computer won",c_win,"rounds") print("Rounds tied :",ties) if p_win>c_win: print("Congrats",p_name,"you won the match!!!") elif p_win<c_win: print("Computer won the match!!!") elif p_win == c_win: print("Match tied !!!") print("***Thank you for playing this game",p_name,"***")
558835d030e015d52e34552da8d649d72c9f2878
TestowanieAutomatyczneUG/projekt-1-wiktormorawski
/tests/test_morse_asserpy.py
1,898
3.515625
4
from main import Main import unittest from assertpy import assert_that 'only unittest and assertpy morse' class TestMain(unittest.TestCase): def setUp(self): self.temp = Main() """Morse coding tests""" def test_morse_coding_value_equal_wiktor(self): expected = '.-- .. -.- - --- .-. ' self.assertEqual(expected, self.temp.Morse_coding('wiktor')) def test_morse_coding_value_equal_ryba(self): expected = '.-. -.-- -... .- ' self.assertEqual(expected, self.temp.Morse_coding('ryba')) def test_morse_coding_polish_letters(self): assert_that(self.temp.Morse_coding).raises(Exception).when_called_with('śćżźąę€ółń') def test_morse_coding_with_sentence(self): assert_that(self.temp.Morse_coding('Ala ma kota')).is_equal_to('.- .-.. .- -- .- -.- --- - .- ') """Morse decoding tests""" def test_morse_decoding_to_text_without_space_between_equal(self): expected = 'mrozonka' assert_that(self.temp.Morse_decoding('-- .-. --- --.. --- -. -.- .-')).is_equal_to(expected) def test_morse_decoding_to_sentence(self): expected = 'ahoj zabawa i jedziemy dalej' assert_that(self.temp.Morse_decoding( '.- .... --- .--- --.. .- -... .- .-- .- .. .--- . -.. --.. .. . -- -.-- -.. .- .-.. . .---')).is_equal_to( expected) def test_morse_decoding_Exception_when_wrong_space_in_code(self): assert_that(self.temp.Morse_decoding).raises(Exception).when_called_with( '.- .... --- .--- --.. .- -... .- .-- .-') def test_morse_decoding_Exception_when_morse_code_doesnt_exist(self): assert_that(self.temp.Morse_decoding).raises(Exception).when_called_with( '.------ -----...') def tearDown(self): self.test_object = None if __name__ == '__main__': unittest.main()
9799a093125dba3bb7aa2a9730b5c5f33c3879bc
adgp97/NNandDL
/A2/perceptron.py
1,335
3.515625
4
import torch.nn as nn import torch import sys class Perceptron(nn.Module): """ Simplest unit of Neural Networks """ def __init__(self, input_size, output_size, learning_rate, mode): """ Constructor """ super(Perceptron, self).__init__() self.learning_rate = learning_rate self.mode = mode self.layer = nn.Linear(input_size, output_size) def forward(self, data, check_data): """ Feed data to Perceptron. Calculate the estimated output and Cost function using Sigmoid as activation function """ if self.mode == 1: # Estimate the output activation_fn = nn.Sigmoid() self.output = activation_fn(self.layer(data)) # Cost function calculation loss_fn = nn.BCELoss() self.cost = loss_fn(self.output, check_data) elif self.mode == 2: # Estimate the output self.output = self.layer(data) # Cost function calculation loss_fn = nn.MSELoss() self.cost = loss_fn(self.output, check_data) else: print('Error: Mode not supported. Aborting...') sys.exit() def back_prop(self): """ Correction of weights and bias """ # Declare the optimizer optimizer = torch.optim.SGD(self.parameters(), self.learning_rate) # Reset the gradients optimizer.zero_grad() # Calculate the gradients self.cost.backward() # Update parameters optimizer.step()
8bc6794daea3dfc129912db2e274653d0a56b3d6
MalliyawaduHemachandra/HacktomberfestHelloWorld
/Python/1first.py
168
4.03125
4
a=int(input("enter number 1;")) b=int(input("enter number 2;")) if(a==b): print("both are equal") elif a>b: print(a,"is larger") else: print(b,"is larger")
a8793ebf8701d5df92f8c381aa188a5dcabf782f
Baoyx007/my_leetcode
/fullPermution.py
283
3.65625
4
# -*- coding: utf-8 -*- __author__ = 'PCPC' def permution(prefix, str): if len(str) <= 0: print(prefix) else: for i in range(len(str)): permution(prefix + str[i],str[0:i] + str[i + 1:] ) def combination(str): pass permution('', '12345')
01f5d29eb8c88ce7a0fa3840f56fad0701631725
ZdenekPazdersky/python-academy
/Lesson6/6.36_chessboard.py
1,079
4.1875
4
# ###2DO # # Write a program that prints a chessboard of given size to the terminal. The program will need: # # # # the length of board's edge and # # character that will serve to fill in the black squares # # Example of running the program for the edge length of 5 and fill character "#": # # ###### # f_char = input('Please enter the character string:') # f_len = int(input('Please enter integer for length of your chessboard:')) # # for i in range(0, f_len): # for j in range(0, f_len): # if (i+j) % 2 == 0: # print(f_char, end='') # else: # print(' ', end='') # print('') #ENGETO SOLUTION: size = 5 sym = ['#',' '] desk = [] for row in range(size): line = [] for cell in range(size): i = (row+cell) % len(sym) line.append(sym[i]) desk.append(''.join(line)) print(''.join(line)) #sjednoti list naprovo do stringu nalevo print('Line: ', line) #print('desk: ', desk) print(desk) print('\n'.join(desk)) #sjednoti jednotlive polozky listu, zde s odsazenim na novy radek print() ################
169fad274392b50f2ca3ea57f97788435b8c437c
sampathgoparaju/pythonpractice
/Exception3.py
450
3.984375
4
#!/usr/bin/python # Exception handling try: x=input("Enter any number:") y=input("Enter any number:") print 'The values of x and y are', x,y res=x/y print 'The output of the division is', res print "I have executed" except ZeroDivisionError: print 'Error encountered, trying to divide number by zero' except NameError,e: print 'The given variable is not defined in program' print 'The default message is ',e
58e766413e8c7472c4f2b87b560845d2f6ebb7fd
mdh111/python
/pluralsight5.py
196
3.8125
4
shoppingList = [] shoppingList.append("Apples") shoppingList.append("Milk") print(shoppingList) shoppingList[1] = "Bread" print(shoppingList) anotherList=list("characterlist") print(anotherList)
5a8415063edee44d834589481c6249e04cf8e7b8
jordanvtskier12/Birthday-quiz
/birthday.py
3,471
4.5625
5
""" birthday.py Author: Jordan Credit: none Assignment: Your program will ask the user the following questions, in this order: 1. Their name. 2. The name of the month they were born in (e.g. "September"). 3. The year they were born in (e.g. "1962"). 4. The day they were born on (e.g. "11"). If the user's birthday fell on October 31, then respond with: You were born on Halloween! If the user's birthday fell on today's date, then respond with: Happy birthday! Otherwise respond with a statement like this: Peter, you are a winter baby of the nineties. Example Session Hello, what is your name? Eric Hi Eric, what was the name of the month you were born in? September And what year were you born in, Eric? 1972 And the day? 11 Eric, you are a fall baby of the stone age. """ name=str(input("Hello, what is your name? ")) month=str(input("Hi "+name+", what was the name of the month you were born in? ")) year=int(input("And what year were you born in, "+name+"? ")) day=int(input("And the day? ")) months = ["" , "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ""] winter=["December","January","February"] spring=['March','May','April'] summer=['June','July','August'] fall=['September','October','November'] from datetime import datetime from calendar import month_name todaymonth = datetime.today().month todaydate = datetime.today().day birthmonth = months[todaymonth] if month==birthmonth and day==todaydate: print("Happy birthday!") elif month=="October" and day==31: print("You were born on Halloween!") elif month in winter and year>=2000: print(str(name + ", you are a winter baby of the two thousands.")) elif month in spring and year>=2000: print(str(name + ", you are a spring baby of the two thousands.")) elif month in summer and year>=2000: print(str(name +", you are a summer baby of the two thousands.")) elif month in fall and year>=2000: print(str(name + ", you are a fall baby of the two thousands.")) elif month in winter and year>=1990 and year<= 2000: print(str(name + ", you are a winter baby of the nineties.")) elif month in spring and year>=1990 and year<= 2000: print(str(name + ", you are a spring baby of the nineties.")) elif month in summer and year>=1990 and year<=2000: print(str(name + ", you are a summer baby of the nineties.")) elif month in fall and year>=1990 and year<=2000: print(str(name + ", you are a fall baby of the nineties.")) elif month in winter and year>=1980 and year<= 1990: print(str(name + ", you are a winter baby of the eighties.")) elif month in spring and year>=1980 and year<= 1990: print(str(name + ", you are a spring baby of the eighties.")) elif month in summer and year>=1980 and year<=1990: print(str(name + ", you are a summer baby of the eighties.")) elif month in fall and year>=1980 and year<=1990: print(str(name + ", you are a fall baby of the eighties.")) elif month in winter and year<=1980: print(str(name + ", you are a winter baby of the Stone Age.")) elif month in spring and year<=1980: print(str(name + ", you are a spring baby of the Stone Age.")) elif month in summer and year<=1980: print(str(name +", you are a summer baby of the Stone Age.")) elif month in fall and year<=1980: print(str(name + ", you are a fall baby of the Stone Age."))
b5d6340b58fb122f620c16de020415bfe22f1247
skailasa/practice
/ctc/ch01-arrays/8-zero-matrix.py
682
3.96875
4
""" Write an algorithm st if an element in an MxN matrix is zero, so are its entire row and column """ def zero_matrix(M): zero_cols = set() zero_rows = set() nvec = [0 for _ in range(len(M[0]))] for idx, vector in enumerate(M): for jdx, component in enumerate(vector): if component == 0: zero_cols.add(idx) zero_rows.add(jdx) for col in zero_cols: M[col] = nvec for col in zero_cols: for row in zero_rows: M[col][row] = 0 def main(): M = [ [0, 1, 2, 3, 22], [1, 3, 0, 123, 1] ] print(zero_matrix(M)) if __name__ == "__main__": main()
68ed7679ae83be3946c2aa468c34b1f9e8e7dc19
AdityaBelani/Learning-Python
/30.06.2018/1. Selection Sort.py
289
3.9375
4
def selsort(lst): for i in range(0,len(lst)-1): for j in range(i,len(lst)): if lst[j]<lst[i]: t=lst[j] lst[j]=lst[i] lst[i]=t print('The new List') print(lst) lst=input("Enter List: ") selsort(list(lst))
ed0341e7cb552ee351d31215d8d13eab982ba21c
jaycoskey/IntroToPythonCourse
/PythonSrc/Unit3_HW_src/banana.py
95
3.65625
4
#!/usr/bin/env python3 s = 'banana' for k in range(0, len(s)): print(s[0]) s = s[1::]
6ed4d624129ea68d75afd873c233444dd5e36e37
charlie2104/PyGame_TicTacToe
/Button.py
346
3.546875
4
import pygame class Button: text = "" def __init__(self, x, y, width, height, colour): self.x = x self.y = y self.width = width self.height = height self.colour = colour def displayButton(self, screen): pygame.draw.rect(screen,self.colour,[self.x,self.y,self.width,self.height])
6af5b2309bba64405aa3b71161ddb577b7c61c7f
gittil/soulcode-datetime
/at_date.py
367
3.84375
4
from datetime import date # Importado a class date do modulo datetime (manipulação de datas). # (ano, mes, dia) Padrão gregoriano. data = date(2021, 2, 2) print(data) # -> 2021-02-02 configurada print('Data Atual: {}'.format(date.today())) print('Dia: {}'.format(data.day)) print('Mês: {}'.format(data.month)) print('Ano: {}'.format(data.year))
c0388d4a85d71c5ce73533ec001fdab84df57edc
taanh99ams/taanh-fundamental-c4e15
/SS02/random_num.py
93
3.546875
4
from random import randint x = randint(0, 100) print("A random number from 0 to 100 is", x)
fce7f84b709fa91c6f62770714d5159578e9e187
MrHamdulay/csc3-capstone
/examples/data/Assignment_9/cxxrog002/question2.py
901
3.859375
4
"""change text to equal a correct format Roger Cox 14 May 2014""" text_im=input("Enter the input filename:\n") f=open(text_im,"r") #opens the correct file text=f.read() text_out=input("Enter the output filename:\n") g=open(text_out,"w") #n_text=text.replace("\n\n","chr(1)") n1_text=text.replace("\n"," ") #n2_text=n1_text.replace("chr(1)","\n\n") length_of_line=eval(input("Enter the line width:\n")) #prints the length you want words= n1_text.split(" ") f.close() lin_counter =1 # go through list of words and check if it should be on that line or not for word in words : len_w=len(word) if (lin_counter+len_w) <=length_of_line : print(word,end=" ",file=g) lin_counter+=len_w +1 else : print(file=g) print(word,sep="",end=" ",file=g) lin_counter=1 + len_w g.close()
39dc935222f897a437010d11e07f2aac25c891f9
ametthapa/python
/2Dlist_task.py
246
3.90625
4
#wap to remove the duplicates from the list number=[1,4,6,8,5,3,2,1,3] output=[] for item in number: if item not in output: output.append(item) output.sort() print(output) print(number) set_2 = {1,2,3,3,4,5} print(set_2)
76b37fdad5dfc2650aa39e40b7662c4ccafc1d53
fractal1729/CS_PRIMES_2016
/utils.py
765
3.75
4
# Converts two-parent-list graph storage scheme to adjacency list def tpl_to_adj(tpl): # optional error-throwing mechanism in case the inputs are not of the same length; this really should need to be triggered in any case # if(len(parent1) != len(parent2)): # print("Error: input parent lists do not have same length") # return parent1 = tpl[0] parent2 = tpl[1] adj = [] for i in range(len(parent1)): adj.append([parent1[i],parent2[i]]) return adj # Returns the union of two lists. Designed for b to be a very small list. def union(a, b): c = a for e in b: if(e not in c): c.append(e) return c # Returns all numbers in range(0,a) that are not in S def complement1(a, S): b = [] for i in range(a): if(i not in s): b.append(i) return b
fbf618df66b4c255e8f7eaea3594c759f2874911
shubhamrocks888/python_oops
/Methods.py
1,402
4.5625
5
## Methods Function that belongs to a class is called an Method. All methods require ‘self’ parameter. If you have coded in other OOP language you can think of ‘self’ as the ‘this’ keyword which is used for the current object. It unhides the current instance variable.’self’ mostly work like ‘this’. '''The self''' : 1. Class methods must have an extra first parameter in method definition. 2. We do not give a value for this parameter when we call the method, Python provides it If we have a method which takes no arguments, then we still have to have one argument – the self. See fun() in above simple example. 3. this is similar to this pointer in C++ and this reference in Java. ##When we call a method of this object as myobject.method(arg1, arg2), this is automatically ##converted by Python into MyClass.method(myobject, arg1, arg2) – this is all the special self is about. '''myobject.method(arg1, arg2) = MyClass.method(myobject, arg1, arg2)''' # A Python program to demonstrate working of class methods class Vector2d: x = 0 y = 0 def set(self,x,y): self.x = x self.y = y def output(self): print ("bye") vec = Vector2d() vec.set(1,2) print (vec.x,vec.y) print (Vector2d.x,Vector2d.y) vec.output() Vector2d.output(vec) #Output: 1 2 0 0 bye bye
e181cfe4d13e92495911a6554d4f804e8d484466
ljia2/leetcode.py
/solutions/dfs/079.Word.Search.py
2,072
4.0625
4
class DFSSolution: def exist(self, board, word): """ Given a 2D board and a word, find if the word exists in the grid. The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once. Example: board = [ ['A','B','C','E'], ['S','F','C','S'], ['A','D','E','E'] ] Given word = "ABCCED", return true. Given word = "SEE", return true. Given word = "ABCB", return false. :type board: List[List[str]] :type word: str :rtype: bool typical dfs search problem. iterate over each cell and dfs over K steps where k is the length of given word. T: O(m*n*4^len(word)) S: O(m*n) """ if not board or not board[0] or not word: return False ans = [False] for r in range(len(board)): for c in range(len(board[0])): self.dfs(board, word, 0, r, c, ans) if ans[0]: return ans[0] return False def dfs(self, board, word, level, r, c, ans): # out of bound if r < 0 or c < 0 or r >= len(board) or c >= len(board[0]): return # avoid visited cell if board[r][c] == "#": return # exceed word length if level >= len(word): return # do not match if board[r][c] != word[level]: return # find the last index if level == len(word) - 1: ans[0] = True return # start the standard backtracking via dfs search. # mark visit to avoid circle tmp = board[r][c] board[r][c] = "#" for nr, nc in [(r, c+1), (r, c-1), (r+1, c), (r-1, c)]: self.dfs(board, word, level + 1, nr, nc, ans) if ans[0]: return board[r][c] = tmp return
0b4fbd675472f6f3bda5d3006a1bfa3aaed61207
dely2p/Leetcode
/231.power-of-two.py
460
3.65625
4
# # @lc app=leetcode id=231 lang=python3 # # [231] Power of Two # # @lc code=start class Solution: def isPowerOfTwo(self, n: int) -> bool: result = False power = 1 if n == 1: return True while True: power = 2 * power if power == n: result = True break elif power > n: break return result # @lc code=end
ddf4d3bc999bcd93278baa93fbc48e2452e1b65d
ayivima/face_landmarks
/models.py
4,421
3.8125
4
"""Implements a Convolutional Neural Network(CNN) for the detection of facial landmarks""" import torch import torch.nn as nn import torch.nn.functional as F from torchvision import models __author__ = "Victor Mawusi Ayi <ayivima@hotmail.com>" class Net(nn.Module): def __init__(self): """Initializes the neural network state""" super(Net, self).__init__() # starting out with very few output channels # is good for efficiency and might be a first step # to preventing overfitting self.conv1 = nn.Conv2d(1, 8, 5, 1, 2) self.conv2 = nn.Conv2d(8, 16, 5, 1, 2) self.conv3 = nn.Conv2d(16, 32, 5, 2) self.conv4 = nn.Conv2d(32, 64, 3, 1, 1) self.conv5 = nn.Conv2d(64, 64, 3, 1, 1) self.dense1 = nn.Linear(6*6*64, 256) self.dense2 = nn.Linear(256, 136) self.pool = nn.MaxPool2d(2, 2) self.drop = nn.Dropout(p=0.3) def forward(self, x): """Implements the forward pass of an image tensor through the neurons. Arguments --------- :x: an image tensor """ x = F.selu(self.conv1(x)) x = self.pool(x) x = F.selu(self.conv2(x)) x = self.pool(x) x = F.selu(self.conv3(x)) x = F.selu(self.conv4(x)) x = self.pool(x) x = F.selu(self.conv5(x)) x = self.pool(x) x = x.view(x.size(0), -1) x = self.drop(F.selu(self.dense1(x))) # selu is self normalizing and it did serve a good purpose, # even though it looks odd that the outputs of the last layer # gets passed through an activation. x = F.selu(self.dense2(x)) return x class Net2(nn.Module): def __init__(self): """Initializes the neural network state""" super(Net2, self).__init__() # starting out with very few output channels # is good for efficiency and might be a first step # to preventing overfitting self.conv1 = nn.Conv2d(1, 8, 5, 1, 2) self.conv2 = nn.Conv2d(8, 16, 5, 1, 2) self.conv3 = nn.Conv2d(16, 32, 5, 2) self.conv4 = nn.Conv2d(32, 64, 3, 1, 1) self.conv5 = nn.Conv2d(64, 128, 3, 1, 1) self.conv6 = nn.Conv2d(128, 256, 3, 1, 1) self.conv7 = nn.Conv2d(256, 512, 3, 1, 1) self.conv8 = nn.Conv2d(512, 512, 3, 1, 1) self.dense1 = nn.Linear(3*3*512, 1024) self.dense2 = nn.Linear(1024, 136) self.pool = nn.MaxPool2d(2, 2) self.drop = nn.Dropout(p=0.3) def forward(self, x): """Implements the forward pass of an image tensor through the neurons. Arguments --------- :x: an image tensor """ x = F.selu(self.conv1(x)) x = self.pool(x) x = F.selu(self.conv2(x)) x = self.pool(x) x = F.selu(self.conv3(x)) x = F.selu(self.conv4(x)) x = self.pool(x) x = F.selu(self.conv5(x)) x = F.selu(self.conv6(x)) x = self.pool(x) x = F.selu(self.conv7(x)) x = F.selu(self.conv8(x)) x = self.pool(x) x = x.view(x.size(0), -1) x = self.drop(F.selu(self.dense1(x))) # selu is self normalizing and it did serve a good purpose, # even though it looks odd that the outputs of the last layer # gets passed through an activation. x = F.selu(self.dense2(x)) return x class resNet(nn.Module): def __init__(self): """Sets up a pre-trained ResNet model for use for project.""" super(resNet, self).__init__() resnet = models.resnet50(pretrained=True) # Prevent given layers from undergoing backpropagation. for param in resnet.parameters(): param.requires_grad_(False) # Remove the linear layer of resnet50 modules = list(resnet.children())[:-1] # Replace the first convolutional layer of the resnet50 modules[0] = nn.Conv2d(1, 64, 7, 2, 3) self.resnet = nn.Sequential(*modules) self.linear = nn.Linear(resnet.fc.in_features, 136) def forward(self, x): x = self.resnet(x) x = x.view(x.size(0), -1) x = self.linear(x) return x
600d9cb87e0f64d726f19e6893561eee03f1c516
mukundoff07/age_predictor
/app.py
1,110
3.53125
4
# streamlit run app.py --server.port 9993 import streamlit as st st.title("Age Predictor") number = st.selectbox("Please Select Any Number", (2, 3, 4, 5, 6, 7, 8, 9, 10, )) st.write("You Have Selected", number) new_number = number * 2 new_number1 = new_number + 5 new_number2 = new_number1 * 50 # st.write(new_number) # st.write(new_number1) # st.write(new_number2) birthday_celebration = st.radio("Have You Already Celebrated Your Birthday ?", ("Yes", "No")) if birthday_celebration == "Yes": new_number3 = new_number2 + 1770 # st.write(new_number3) born_age1 = st.number_input("When Did You Born") # st.write(born_age1) final_step = new_number3 - born_age1 st.write(final_step) if birthday_celebration == "No": new_number4 = new_number2 + 1769 # st.write(new_number4) born_age2 = st.number_input("When Did You Born") # st.write(born_age2) final_step1 = str(new_number4 - born_age2) st.write("Your Age is ", final_step1[1:3])
237ad1e96484abd542e84a08bbc471e7cf9b7922
rafaelperazzo/programacao-web
/moodledata/vpl_data/425/usersdata/308/92288/submittedfiles/dec2bin.py
119
3.96875
4
# -*- coding: utf-8 -*- p = input('Insira P: ') q = input('Insira Q: ') if p in q: print('S') else: print('N')
11391e2aec7f64046ff18d6c77946402e5ccfc9c
zuxinlin/leetcode
/leetcode/editor/cn/[面试题 04.06]后继者-successor-lcci.py
1,478
3.890625
4
#! /usr/bin/env python # coding: utf-8 # 设计一个算法,找出二叉搜索树中指定节点的“下一个”节点(也即中序后继)。 # # 如果指定节点没有对应的“下一个”节点,则返回null。 # # 示例 1: # # 输入: root = [2,1,3], p = 1 # # 2 # / \ # 1 3 # # 输出: 2 # # 示例 2: # # 输入: root = [5,3,6,2,4,null,null,1], p = 6 # # 5 # / \ # 3 6 # / \ # 2 4 # / # 1 # # 输出: null # Related Topics 树 深度优先搜索 # 👍 56 👎 0 # leetcode submit region begin(Prohibit modification and deletion) # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def inorderSuccessor(self, root, p): """ :type root: TreeNode :type p: TreeNode :rtype: TreeNode """ pre = None while root.val != p.val: if root.val < p.val: root = root.right else: pre = root root = root.left if not root.right: # 假如没有右子树 return pre else: root = root.right while root.left: root = root.left return root # leetcode submit region end(Prohibit modification and deletion) if __name__ == '__main__': solution = Solution()
894fae13639b2fe280766f34bb94740658bd92b1
loosecanon/Project-Euler
/problem7.py
317
3.734375
4
import math #compute 10001st prime number i = 1 # first prime num = 2 #number under examination storage variable while i < 10001: num+=1 for j in range(2,num): #print("j = ", j, " num = ", num," i = ", i) if num%j == 0: break else: i+=1 print("100001st prime = ", num)
fafefdc67caef3de9a80a1f7d9f27bd61523ed85
osanpozuki/competitive-programming
/competitive.py
292
3.8125
4
def is_prime(n): if n < 2: return False for k in range(2, int(n ** (1/2)) + 1): if n % k == 0: return False return True # using: 1 2 3 => [1, 2, 3] def input_parse_int(): return [int(i) for i in input().split(' ')] if __name__ == '__main__': pass
87385a73f28d04e1f87cd59d0a67290a1daf0322
bitbybitsth/automation_login
/bitbybit/interview_assignments/list_assignments.py
624
3.96875
4
l = ['(', '[', '{', '}', ']', ')'] def is_balanced(l): stack = [] # -> [(,[,{, opening_brackets = ('(', '{', '[') closing_brackets = (')', '}', ']') for i in l: if i in opening_brackets: stack.append(i) if i in closing_brackets: x = stack.pop() # x = '[' index = closing_brackets.index(i) # 2 if x != opening_brackets[index]: return False if len(stack) == 0: return True else: return False if is_balanced(l): print("paranthesis is balanced") else: print("paranthesis are not balanced")
db1218470a67df8234d8acc866f75e373b5baed4
Ian84Be/Intro-Python-II
/src/player.py
3,288
3.5625
4
from gameObj import GameObj from color import Color class Player(GameObj): def __init__(self, name, loc, desc='n/a', holding=[]): super().__init__(name, desc, holding) self.loc = loc def startGame(self): # DRAMATIC INTRO print('\n') self.crawlText('You awaken suddenly.') self.crawlText(f'Your body is aching and your clothes are stained with mud. You {Color.PURPLE}look{Color.END} around to see a locked iron gate behind you, and a gravel pathway before you. How did you get here? You touch your head and feel a lump, it is wet, and sticky. You can see a {Color.RED}Flashlight{Color.END} on the gravel nearby. It\'s YOUR flashlight.', delay=0.03) self.loc.getItem('flashlight', self) self.crawlText(f'{Color.PURPLE}It is wet with blood. Did someone knock you out with your own flashlight?{Color.END}', 0.02) self.crawlText(f'{Color.PURPLE}You can see your name engraved on the handle: {Color.RED}{self.name.upper()}{Color.END}', 0.02) self.crawlText(self.loc.desc, 0.02) def drop(self, thisItem): index = None for i, item in enumerate(self.holding): if item.name.lower() == thisItem.lower(): index = i if index != None: thisItem = self.holding.pop(index) self.loc.holding.append(thisItem) self.crawlText(f'You dropped the {Color.RED}{thisItem.name}{Color.END}') else: print(f'You cannot see a {Color.RED}{thisItem}{Color.END}') def use(self, thisItem): index = None for i, item in enumerate(self.holding): if item.name.lower() == thisItem.lower(): index = i if index != None: thisItem = self.holding[index] thisHappened = thisItem.useItem(room=self.loc.name) if thisItem.name == 'Flashlight': self.loc.isDark=False if thisItem.name == 'Key' and self.loc.name == 'Treasure Chamber': self.crawlText(f'{Color.RED}{thisHappened}{Color.END}') self.quitGame() print('\n') self.crawlText(f'{Color.RED}{thisHappened}{Color.END}') else: print(f'You are not holding {Color.RED}{thisItem}{Color.END}') def go(self, there): if there not in ['north','east','west','south','up','down']: print(f'{Color.PURPLE}{there}{Color.RED} is not an option{Color.END}') else: goTo = there[0] + '_to' newRoom = getattr(self.loc, goTo) if newRoom != None: self.loc = newRoom if self.loc.seen == False: self.loc.seen = True print('\n') self.crawlText(f'{Color.PURPLE}{self.loc.name}{Color.END}',0.03) self.crawlText(self.loc.desc,0.02) else: print('\n') self.crawlText(f'{Color.PURPLE}You have been here before{Color.END}',0.03) print(self.loc) else: print(f'{Color.RED}You cannot go {Color.PURPLE}{there}{Color.RED} from here{Color.END}') def __str__(self): return f'++ {self.name} is at the {self.loc.name} ++'
5cd6f6b504c23e5473b64c5093375d04e654c08d
alegalviz/RSA
/rsa
2,687
3.796875
4
#!/usr/bin/python3 import random d = {1:'a',2:'b',3:'c',4:'d',5:'e',6:'f',7:'g',8:'h',9:'i',10:'j',11:'k',12:'l',13:'m',14:'n',15:'o',16:'p',17:'q',18:'r',19:'s',20:'t',21:'u',22:'v',23:'w',24:'x',25:'y',26:'z'} # Función de Euler def lcm(x, y): # choose the greater number if x > y: greater = x else: greater = y l = 0 while(True): if(greater % x == 0) and (greater % y == 0): l = greater break greater += 1 return l def egcd(a, b): if a == 0: return (b, 0, 1) else: g, y, x = egcd(b % a, a) return g, x - (b // a) * y, y def modinv(a, m): g, x, y = egcd(a, m) if g != 1: raise Exception('El inverso del modulo no existe') else: return x % m def esprimo(n): if n == 2 or n == 3: return True if n < 2 or n%2 == 0: return False if n < 9: return True if n%3 == 0: return False r = n**0.5 f = 5 while f <= r: if n%f == 0: return False if n%(f+2) == 0: return False f +=6 return True def sieveOfEratosthenes(n): """sieveOfEratosthenes(n): return the list of the primes < n.""" # Code from: <dickinsm@gmail.com>, Nov 30 2006 # http://groups.google.com/group/comp.lang.python/msg/f1f10ced88c68c2d if n <= 2: return [] sieve = list(range(3, n, 2)) top = len(sieve) for si in sieve: if si: bottom = (si*si - 3) // 2 if bottom >= top: break sieve[bottom::si] = [0] * -((bottom - top) // si) return [2] + [el for el in sieve if el] def selec2prime(fin=100): if fin < 47: primoshasta = 100 else: primoshasta = fin primos = sieveOfEratosthenes(primoshasta) print(primos) while 1: x, y = random.sample(primos, 2) if x*y > fin: return x, y else: continue def seleccoprime(inicio=1, fin=100): while 1: x = random.randint(inicio,fin) if esprimo(x): if x % fin == 0: continue else: return x else: continue valor = int(input('numero a cifrar: ')) p , q = selec2prime(valor) # p = 61 # q = 53 print('valor de p: ', p) print('valor de q: ', q) n = p*q print('valor de n: ', n) phy = lcm((p-1), (q-1)) print('valor de phy: ',phy) # tiene que ser coprimo y no divisible e = seleccoprime(1, phy) # e = 17 print('valor de e: ',e) # modular multiplicative inverse of e (mod λ(n)) d = modinv(e, phy) print('valor de d: ',d) c = valor**e%n print('numero ' + str(valor) + ' cifrado: ',c) desc = c**d%n print('numero ' + str(valor)+ ' descifrado: ',desc)