blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
350577069c64762c5e082f0bbac3d2da88f64cdf
youwantsy/DeepLearningPractice
/Basiccodes/Matplotlib/example01.py
637
3.53125
4
import matplotlib.pyplot as plt import numpy as np x = np.arange(0.1, 1, 0.01) y = (1/(2*np.pi)*x)*np.exp(-1/2*x*x) plt.plot(x, y) plt.show() #%% x = np.arange(0, 2*np.pi, 0.1) y1 = np.sin(x) y2 = np.cos(x) plt.figure(1) plt.plot(x, y1) plt.figure(2) plt.plot(x, y2) plt.show() #%% plt.plot(x,y1) plt.plot(x,y2) plt.show() #%% x = np.arange(0, 100, 0.5) y1 = x**2 y2 = x**3 plt.xlabel("x") plt.ylabel("y") plt.xlim(0, 5) plt.ylim(0, 100) plt.xticks(np.arange(0, 5.5, step=0.5)) plt.yticks(np.arange(0, 110, step=10)) plt.grid(linestyle=":") plt.plot(x, y1, label="x**2") plt.plot(x, y2, label="x**3") plt.legend() plt.show()
476500fa204f2bfd2f9661e1dee3d97c9e7aa15c
Mazzya/Aprendiendo-Python
/Estructuras de datos/adivina.py
1,266
4.0625
4
#Importar una libreria de números aleatorios import random def leer_numero(): es_numero = False while es_numero==False: try: usuario = int(input("Adivina el número: ")) es_numero=True except ValueError: print("No ha introducido un número. Vuelva a intentarlo") return usuario #Inicializamos las vidas vidas = 5 print("¡Bienvenido a adivina el número!") continuar = True while continuar: print("***************Te quedan {} vidas***************".format(vidas)) print("Estoy pensando un número entre el 1 y el 10") #Generar un número aletorio entre 1 y 10 numero = random.randint(1,10) #Leer el dato del usuario usuario = leer_numero() #Comprobar si ha acertado if numero==usuario: print("¡Has acertado!") vidas = vidas + 1 else: print("Te has confundido el número era: {}".format(numero)) vidas = vidas - 1 if vidas == 0: continuar = False print("Lo sentimos, se te han acabado las vidas.") break #División del texto para mejor visibilidad input() print() print("------------------------------------------------") print()
c1c62b821d00af9a1510c8fe2f76b2d295d5c6c9
sarahvestal/ifsc-1202
/Unit 1/01.03 Square.py
100
3.625
4
firstnumber = input("First number is: ") square = int(firstnumber) * int(firstnumber) print (square)
7f31cef3e2fb000c0e72bad5c4c2edc6521744a0
gomtinQQ/algorithm-python
/codeUp/codeUpBasic/1563.py
446
3.5625
4
''' 1563 : [기초-함수작성] 함수로 세 정수 중 중간 값 리턴하기 int 형 정수 세 개를 입력 받아 중간 값을 출력하시오. 단, 함수형 문제이므로 함수 mid()만 작성하여 제출하시오. ''' def mid(x, y, z): lst = [x,y,z] maxNum = max(lst) minNum = min(lst) sumNum = sum(lst) return sumNum-maxNum-minNum x, y, z = input().split() x = int(x) y = int(y) z = int(z) print(mid(x,y,z))
e9a1c66225f08ed8917d69956543f0c8af83441e
keyllalorraynna/Desafios
/Desafio4/inverteValores.py
268
4.03125
4
''' Faça um programa que peça um numero inteiro positivo e em seguida mostre este numero invertido. •Exemplo: 12376489 => 98467321 ''' insere_valor = input('Digite os valores que devem ser invertidos: ') for i in reversed(insere_valor): print (f'{i}', end = '')
0ca55f7c90b11b13685da73bcb6360608d16930b
githubMay/myTest
/truple/draw_five_star.py
925
4.0625
4
import turtle def drawFiveStar(t,b): """画五角星函数,t是画板的形式参数,b是五角星的边长""" #t.pendown() t.begin_fill() t.fillcolor('yellow') for i in range(0,5): t.speed(1) t.forward(b) t.left(72) t.forward(b) t.right(144) t.penup() t.end_fill() def drawPentagram(m,angle,l,a): #angle是所画五角形起点与大五角形中心连线与x轴的夹角,l是起点与大五角形中心的距离,a是所画五角形起点与此五角形中心的距离 m.penup() m.goto(50,-50) m.left(angle) m.forward(l*10) if a==3: b=2.1;angle1=162#angle1是画笔画大五角形,到达第一个起点后偏转的角度,偏转后画第一笔 else: b=1.19;angle1=-18#画其他小五角的偏转的角度 print(b,angle1,angle) m.right(angle1) drawFiveStar(m,b*10) m.setheading(0)
60b2eae752ca6fabf1b17d80d711e90f3cfc4e53
StpdFox/HU_ALDS_Ref
/ALDS_Week_1/alds_w1_1.py
422
4.34375
4
def max(arr): """ Function that finds and returns the maximum value of array(list) arr Time complexity O(n) :param arr: array(list) containing integers :return highest: integer containing highest number in arr """ tempMax = float("-inf") for nr in arr: if nr > tempMax: tempMax = nr return tempMax list = [4,7,9,4,1,613,717,82] print(max(list))
e94f04933bb5df33727afed811438811ce89778c
ayushchitrey/Think-Code
/Python_Programming - 360DigiTMG/Assignment1_DataTypes_Q3.py
812
4.21875
4
''' Q3. Create a data dictionary of 5 states having state name as key and number of covid-19 cases as values. a. Print only state names from the dictionary. b. Update another country and it’s covid-19 cases in the dictionary.''' dictionary={"Maharashtra":990795,"Andhra Pradesh":537687,"Tamil Nadu":486052,"Karnataka":430947,"Uttar Pradesh":292029} print("Dictionary :" , dictionary) #Printing only the State names from the dictionary print ("State Names : %s" % dictionary.keys()) # or print(dict.keys()) # Updating another key and its value in the dictionary dictionary2={"United States":6990000} print("Country that has to be updated in Dictionary :", dictionary2) dictionary.update(dictionary2) print("Dictionary after Updation of another Country & its Covid-19 cases : ", dictionary)
1345195d6aac48e0241044693c7543aa98ab8671
ReZeroE/Leetcode-Answers
/Medium/2. Add Two Numbers/solution.py
1,389
3.78125
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: num1 = [] num2 = [] result = 0 while l1 != None: num1.append(l1.val) l1 = l1.next while l2 != None: num2.append(l2.val) l2 = l2.next if len(num1) > len(num2): length = len(num1) else: length = len(num2) temp_result = 0 for i in range(length): if i >= len(num1): temp_result += (0 + num2[i]) * (10 ** i) continue elif i >= len(num2): temp_result += (num1[i] + 0) * (10 ** i) continue else: temp_result += (num1[i] + num2[i]) * (10 ** i) result = str(temp_result)[::-1] linked = ListNode(0) r = linked print(linked.val) for c in range(len(result)): if c == 0: linked.val = int(result[c]) continue linked.next = ListNode(int(result[c])) linked = linked.next return r
19e9de9e533d0c6e7ee5a88ae21628014e6214e5
SumMuk/data-struct-algo
/turing.py
129
3.53125
4
def comp(nums): m = float("-inf") for n in nums: if n > m: m+= 1 return m print(comp([1,2,3]))
8ac27295fa2e7e6915bb5f3092207ffd41ba2231
fjfhfjfjgishbrk/AE401-Python
/zerojudge/e621.py
412
3.515625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Apr 27 10:30 2020 @author: fdbfvuie """ n = int(input()) for i in range(n): a = [int(j) for j in input().split(" ")] noPark = True for j in range(a[0] + 1, a[1], 1): if j % a[2] != 0: print(j, end=" ") noPark = False if noPark: print("No free parking spaces.", end = "") print()
38f0493a5d45384f2530c79e695e612624138c57
zhouchuang/pytest
/test24.py
292
4.0625
4
""" 题目:有一分数序列:2/1,3/2,5/3,8/5,13/8,21/13...求出这个数列的前20项之和。 程序分析:请抓住分子与分母的变化规律 """ fz=2 fm=1 sum = 0 for i in range(0,20): sum = sum + fz/fm tempfz = fz fz = fz+fm fm = tempfz print(sum)
45a61aa8c2af758566cd093b18e8639a05f3c1ae
DomPedrotti/python-exercises
/4.1_python_introduction_exercises.py
516
4.53125
5
# Create a hello world program. Create a text file named 4.1_python_introduction_exercises.py and write a program that prints "Hello, World!" to the console. Run this program from the command line. # Inside of your hello world program, create a variable named greeting that contains the message that you will print to the console. Run your script interactively and view the contents of the greeting variable. print('hello world') greeting = 'hello world, and people, and plants, and everything!' print(greeting)
811912d2f507d5771a5b654d400c0c8f69287ef7
rexhzhang/LeetCodeProbelms
/BFS/LeetCode200_NumberOfIslands.py
1,427
3.859375
4
""" Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. Example 1: 11110 11010 11000 00000 Answer: 1 Example 2: 11000 11000 00100 00011 Answer: 3 """ class Solution(object): def numIslands(self, grid): """ :type grid: List[List[str]] :rtype: int """ if grid is None or len(grid) == 0 or len(grid[0]) ==0: return 0 row, column = len(grid), len(grid[0]) count = 0 for y in range(row): for x in range(column): if grid[y][x] == "1": self.BFS(grid, y, x, row, column) count += 1 return count def BFS(self,grid, yy, xx, row, column): q = [[yy,xx]] while q: y, x = q.pop(0) dX = [0,0,1,-1] dY = [1,-1,0,0] for i in range(4): X = x + dX[i] Y = y + dY[i] if self.insideGrid(Y, X, row, column) and grid[Y][X] == "1": q.append([Y,X]) grid[Y][X] = "0" def insideGrid(self, y, x, row, column): return y>=0 and x>=0 and y < row and x < column
3f50e703f26bfc88620dc8d9240cc5fc77225b6a
ambika0203/NLP
/Preprocessing.py
1,440
3.78125
4
# -*- coding: utf-8 -*- """ Created on Tue Apr 16 01:15:57 2019 @author: Ambika """ # Word tokenization import nltk nltk.download('punkt') from nltk.tokenize import word_tokenize my_text = "Hi Mr. Smith! I’m going to buy some vegetables (tomatoes and cucumbers) from the store. Should I pick up some black-eyed peas as well?" print(word_tokenize(my_text)) #Sentence Tokeniation from nltk.tokenize import sent_tokenize my_text = "Hi Mr. Smith! I’m going to buy some vegetables (tomatoes and cucumbers) from the store. Should I pick up some black-eyed peas as well?" print(sent_tokenize(my_text)) #Tokenization - Ngrams from nltk.util import ngrams my_words = word_tokenize(my_text) # This is the list of all words twograms = list(ngrams(my_words,3)) # This is for two-word combos, but can pick any n print(twograms) ################################### #Tokenization - Regex from nltk.tokenize import RegexpTokenizer my_text = "Hi Mr. Smith! I’m going to buy some vegetables (tomatoes" \ " and cucumbers) from the store. Should I pick up some black-eyed " \ " peas as well?" whitespace_tokenizer = RegexpTokenizer("\s+", gaps=True) print(whitespace_tokenizer.tokenize(my_text)) # Tokenization - Regex - Only Capitalized words from nltk.tokenize import RegexpTokenizer # RegexpTokenizer to match only capitalized words cap_tokenizer = RegexpTokenizer("[A-Z]['\w]+") print(cap_tokenizer.tokenize(my_text))
498fcb32cbd75682e4b94ab6dde60d19f7a81c04
pragmatizt/Intro-Python-I
/src/05_lists.py
1,311
4.6875
5
# For the exercise, look up the methods and functions that are available for use # with Python lists. x = [1, 2, 3] y = [8, 9, 10] # For the following, DO NOT USE AN ASSIGNMENT (=). """this is a good link for some list methods: https://lucidar.me/en/python/insert-append-extend-concatanate-lists/""" # Change x so that it is [1, 2, 3, 4] # YOUR CODE HERE x.insert(3, 4) print(x) # Using y, change x so that it is [1, 2, 3, 4, 8, 9, 10] # YOUR CODE HERE """It becomes a list within a list, so that's not right""" x.extend(y) print(x) # Change x so that it is [1, 2, 3, 4, 9, 10] """Removing element from lists: https://note.nkmk.me/en/python-list-clear-pop-remove-del/""" x.pop(4) print(x) # Change x so that it is [1, 2, 3, 4, 9, 99, 10] """Inserting elements in python lists: https://developers.google.com/edu/python/lists""" x.insert(5,99) print(x) # Print the length of list x # YOUR CODE HERE print(len(x)) # Print all the values in x multiplied by 1000 """multiplying elements in a list by a number: https://stackoverflow.com/questions/35166633/how-do-i-multiply-each-element-in-a-list-by-a-number/35166717""" """Does this solution count?""" product = [] for i in x: product.append(i*1000) print(product) # Asked someone else how they did it, this was their code: print([i * 1000 for i in x])
a77052a511316c58742ba11369c4d17d5dc2dc7f
Crasti/Homework
/Lesson6/Task6.3.py
1,972
4.1875
4
""" Реализовать базовый класс Worker (работник), в котором определить атрибуты: name, surname, position (должность), income (доход). Последний атрибут должен быть защищенным и ссылаться на словарь, содержащий элементы: оклад и премия, например, {"profit": profit, "bonus": bonus}. Создать класс Position (должность) на базе класса Worker. В классе Position реализовать методы получения полного имени сотрудника (get_full_name) и дохода с учетом премии (get_full_profit). Проверить работу примера на реальных данных (создать экземпляры класса Position, передать данные, проверить значения атрибутов, вызвать методы экземпляров). """ class Worker: def __init__(self, name, surname, position, _income): self.name = name self.surname = surname self.position = position self._income = _income class Position(Worker): def get_full_name(self): print(f"Full name is: {self.name + ' ' + self.surname}") def get_full_profit(self): print(f"Full profit is: {self._income['profit'] * self._income['bonus']:0.2f}") def main(): while True: try: worker = Position(input('Enter name: '), input('Enter surname: '), input('Enter position: '), {"profit": int(input('Enter profit: ')), "bonus": float(input('Enter bonus like 1.3 or etc: '))}) worker.get_full_name() worker.get_full_profit() break except ValueError as v: print(f'{v} wrong data!') if __name__ == "__main__": main()
6c41a294d04e3562c258375eb6079f512c5267e3
EnriPython/Enri_Python
/Algebra_Vectorial.py
5,572
4.21875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import math import time import os import sys def limpiar(): """Limpia la pantalla""" if os.name == "posix": os.system("clear") elif os.name == "ce" or os.name == "nt" or os.name == "dos": os.system("cls") def salir(): print"" print" Saliendo del programa .........." time.sleep(2) limpiar() sys.exit() def magnitud(): print"" print" Escriba las coordenadas cartesianas, numero positivo, negativo o cero con dos decimales" print"" x = float(input(" Ingrese el valor del vector < x > ")) y = float(input(" Ingrese el valor del vector < y > ")) z = float(input(" Ingrese el valor del vector < z > ")) mg = math.sqrt(x**2 + y**2 + z**2) mag = round(mg, 2) print"" print" La magnitud del vector", x, y, z, "es: ", mag print"" print"" raw_input(" Presione <ENTER> para volver al menu principal ---->") main() def angulos(): print"" print" escriba las coordenadas cartesianas, numero positivo, negativo o cero con dos decimales" print"" x = float(input(" Ingrese el valor del vector < x > ")) y = float(input(" Ingrese el valor del vector < y > ")) z = float(input(" Ingrese el valor del vector < z > ")) Ar = math.atan2(y, x) A = math.degrees(Ar) Br = math.atan2(math.sqrt(x**2 + y**2), z) B = math.degrees(Br) print"" print" Los angulos A y B en grados del vector", x, y, z, " son: A=", round(A, 2), " B=", round(B, 2) print"" print"" raw_input(" Presione <ENTER> para volver al menu principal ---->") main() def mas_menos(): print"" print" Escriba las coordenadas cartesianas, numero positivo, negativo o cero con dos decimales" print"" x1 = float(input(" Ingrese el valor del vector < x1 > ")) y1 = float(input(" Ingrese el valor del vector < y1 > ")) z1 = float(input(" Ingrese el valor del vector < z1 > ")) x2 = float(input(" Ingrese el valor del vector < x2 > ")) y2 = float(input(" Ingrese el valor del vector < y2 > ")) z2 = float(input(" Ingrese el valor del vector < z2 > ")) suma = x1 + x2, y1 + y2, z1 + z2 resta = x1 - x2, y1 - y2, z1 - z2 print"" print " La suma y la resta de los vectores", x1, y1, z1, "y", x2, y2, z2, "es, SUMA:", suma, " RESTA:", resta print"" print"" raw_input(" Presione <ENTER> para volver al menu principal ---->") main() def producto(): x1 = float(input(" Ingrese el valor del vector < x1 >")) y1 = float(input(" Ingrese el valor del vector < y1 >")) z1 = float(input(" Ingrese el valor del vector < z1 >")) x2 = float(input(" Ingrese el valor del vector < x2 >")) y2 = float(input(" Ingrese el valor del vector < y2 >")) z2 = float(input(" Ingrese el valor del vector < z2 >")) punto = x1*x2+y1*y2+z1*z2 crus = round(y1*z2-y2*z1, 3), round(x2*z1-x1*z2, 3), round(x1*y2-x2*y1, 3) mag1 = math.sqrt(x1**2+y1**2+z1**2) mag2 = math.sqrt(x2**2+y2**2+z2**2) magcrus = math.sqrt((y1*z2-y2*z1)**2+(x2*z1-x1*z2)**2+(x1*y2-x2*y1)**2) ang12r = math.acos(punto/(mag1*mag2)) angulo12 = math.degrees(ang12r) angle21r = math.asin(magcrus/(mag1*mag2)) angle21 = math.degrees(angle21r) print"" print" El producto escalar es:", round(punto, 2), "y el producto vectorial:", crus print"" print" Los angulos V1 y V2:", round(angulo12, 2), round(angle21, 2) print"" print" Si los valores son diferentes, analice un diagrama vectorial y decida." print"" print"" raw_input(" Presione <ENTER> para volver al menu principal ---->") main() def main(): limpiar() print"" print"" print" ###########################################################################" print" # #" print" # Enri_Python #" print" # #" print" # ALGEBRA VECTORIAL v1.0 #" print" # #" print" # Magnitud, angulos, suma, resta y productos #" print" # #" print" ###########################################################################" print"" print"" print" 1- MAGNITUD ---> " print"" print" 2- ANGULOS" print"" print" 3- MAS_MENOS" print"" print" 4- PRODUCTO" print"" print" 0- Salir --> " print"" opcion = raw_input(" Ingresa un numero del menu -> ") print"" if opcion != "1" and opcion != "2" and opcion != "3" and opcion != "4" and opcion != "0": print " Opcion incorrecta, presione <ENTER> para volver al menu ...." raw_input() main() if opcion == "1": magnitud() if opcion == "2": angulos() if opcion == "3": mas_menos() if opcion == "4": producto() if opcion == "0": salir() main()
113750e0e386d1fa102c715d4b64eac139efba22
captainblobbles/python
/Logix/Palindrome Detector.py
308
4.46875
4
user_string = input("Please enter a string.") reversed = "" # It is looping from String length back to -1. for item in range(len(user_string) - 1, -1, -1): reversed += user_string[item] if user_string == reversed: print("The entered is a palindrome.") else: print("The entered is not a palindrome.")
74f5f6fc331d26e19ed327f9052d65e7489c27c4
mrfreer/57Exercises
/Program15.py
144
3.515625
4
import getpass pw = getpass.getpass('What is the password?') if pw == "abc$123": print("Welcome!") else: print("I don't know you.")
05ab68ee0b02aae8b268b357b3dcd657281efe42
reema-eilouti/python-problems
/CA11/problem3.py
499
4.15625
4
# Problem 3 # You are given a list of words. Write a function called find_frequencies(words) which returns a dictionary of the words along with their frequency. # Input: find_frequencies(['cat', 'bat', 'cat']) # Return: {'cat': 2, 'bat': 1} my_dict={} my_list=['cat' , 'cat' , 'dog' , 'bat' ,'bat'] def find_frequencies(words): for i in range(len(words)): number = words.count(words[i]) my_dict[words[i]] = number find_frequencies(my_list) print(my_dict)
c9b8f321d964ef1d965756b28079799c87662cfe
cpe202spring2019/lab1-jwalla13
/lab1.py
2,089
4.09375
4
l = [1, 2, 3, 8, 4, 5, 6] """finds the max of a list of numbers and returns the value (not the index) If int_list is empty, returns None. If list is None, raises ValueError""" def max_list_iter(int_list): # must use iteration not recursion if int_list is None: raise ValueError if type(int_list) != list: raise ValueError for item in int_list: if type(item) != int: raise ValueError if len(int_list) == 0: return None else: max = int_list[0] for i in range(len(int_list)): if max < int_list[i]: max = int_list[i] return max """recursively reverses a list of numbers and returns the reversed list If list is None, raises ValueError""" newList = [] def reverse_rec(int_list): # must use recursion global newList if int_list == None: raise ValueError if type(int_list) != list: raise ValueError for item in int_list: if type(item) != int: raise ValueError if int_list == []: int_list = newList newList = [] return int_list else: newList.append(int_list.pop()) return (reverse_rec(int_list)) """searches for target in int_list[low..high] and returns index if found If target is not found returns None. If list is None, raises ValueError """ def bin_search(target, low, high, int_list): # must use recursion if int_list is None: raise ValueError if type(int_list) != list: raise ValueError for item in int_list: if type(item) != int: raise ValueError int_list.sort() check = int_list[(low + high) // 2] idx = int_list.index(check) if check == target: return idx elif check > target and idx==0: return None elif check < target: if int_list[idx + 1] == target: return idx+1 elif idx+1 == len(int_list)-1: return None return bin_search(target, idx, high, int_list) elif check > target: return bin_search(target, low, idx, int_list)
16f1a1c044e98033d96efa83e9725da4779b5f1f
mataralhawiti/Online_Courses
/Udacity - Data Analyst Nanodegree/P05_Identifying_Fraud_From_Enron_Email/Lessons/Features_Scaling/features_scaling.py
960
3.921875
4
""" quiz materials for feature scaling clustering """ ### FYI, the most straightforward implementation might ### throw a divide-by-zero error, if the min and max ### values are the same ### but think about this for a second--that means that every ### data point has the same value for that feature! ### why would you rescale it? Or even use it at all? from __future__ import division from sklearn.preprocessing import MinMaxScaler import numpy as np def featureScaling(arr): scaled_features = [] min_arr = min(arr) max_arr = max(arr) for i in arr: x = (i-min_arr) / (max_arr-min_arr) #decimal #x = (i-min_arr) // (max_arr-min_arr) #interger scaled_features.append(x) return scaled_features ## tests of your feature scaler--line below is input data #data = [115, 140, 175] #print featureScaling(data) weights = np.array([[115.], [140.], [175.]]) scaler = MinMaxScaler() rescaled_weight = scaler.fit_transform(weights) print rescaled_weight
ed64b744759533fa3de3da57c9281bac6836c09d
mr-zhouzhouzhou/LeetCodePython
/剑指 offer/把字符串转换成整数.py
910
3.640625
4
""" 题目描述 将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0 """ """ 微软面试的时候 考过这题 """ # -*- coding:utf-8 -*- class Solution: def StrToInt(self, s): # write code here if s == None or len(s) ==0 : return 0 flag = True s = s.strip() if s.startswith("+") or s.startswith("-"): flag = True if s.startswith("+") else False s = s[1:] sum = 0 for item in s: if item >= "0" and item <= "9": sum = sum * 10 + int(item) else: return 0 if flag: return sum else: return - sum s = " 123" solution = Solution() result = solution.StrToInt(s) print(type(result)) print(result) print(len(s))
959cdcceb2e45b74a5fafeb1e9b4090838b7b6da
antoinebelley/Phys512_assignments
/Final_Project/ode.py
694
3.625
4
import numpy as np def leap_frog(x,v,f_now,f_next,dt): """Update the particles position and momenta using the leap frog method -Arguments: - x (array): The current position of the particles - v (array): The current momenta of the particles - f_now (array): The forces on the particles - f_next (array): The evolved forces on the particles - dt (float): Time step to take to evolve -Retruns: -x_new (array): The new positions of the particles -v_new (array): The new momenta of the particles""" x_new = x+v*dt + 0.5*f_now*dt**2 v_new = v+0.5*(f_now+f_next)*dt return x_new,v_new
dc92d898735b8bdeb3200661dc2e20ba21b9d495
fromgopi/DS-Python
/v2/src/search/linear_search.py
532
3.5
4
import random import timeit def linear_search(array, key): for index, value in enumerate(array): if value == key: return index return -1 if __name__ == '__main__': array = [random.randrange(1, 99999, 1) for i in range(10000)] key = 12 start = timeit.default_timer() res = linear_search(array=array, key=key) stop = timeit.default_timer() if res != -1: print(key, " is found at ", res, "th index") else: print("not found") print('Time: ', stop - start)
77ad82105dd78ee0021754167b78a0171922f3f5
biagioboi/Programmazione-Avanzata
/esempioYield.py
794
3.921875
4
# Quando lo yield viene messo ad un assegnamento ex. x = yield allora aspetterà una send per ricevere # il valore da assegnare a x, contestualmente potrebbe anche restituire un valore 'yield x', # che restituisce il valore di x def raddoppia(): while True: # viene restiuito none in quanto non è specificato nulla dopo lo yield # allo stesso tempo si aspetta una send() per dare un valore a x yield # print("stampa tra un yield e l'altro del corpo del while. x = ", x) x = yield # se al precedente yield non è stato assegnato nulla a x, la seguente operazione # non è fattibile perchè None * int non si puo' fare x = yield x*2 print("x = ", x) g = raddoppia() r = next(g) next(g) g.throw(TypeError) print (r)
c6527c92aed55fcef6da6bc1b3e741883de4bab3
Sunghwan-DS/TIL
/Python/BOJ/BOJ_2937.py
756
3.75
4
def MergeSort(lst): if len(lst) == 1: return lst left = MergeSort(lst[:len(lst)//2]) right = MergeSort(lst[len(lst)//2:]) L, R = 0, 0 sorted_list = [] while L < len(left) and R < len(right): if left[L] <= right[R]: sorted_list.append(right[R]) R += 1 sorted_list.append(left[L]) L += 1 else: sorted_list.append(left[L]) L += 1 if L == len(left): sorted_list.extend(right[R:len(right)]) else: sorted_list.extend(left[L:len(left)]) return sorted_list N = int(input()) arr = list(map(int,input().split())) arr = MergeSort(arr) ans = 0 for idx in range(N): ans = max(ans, arr[idx] + idx + 2) print(ans)
3ad048c48e9553b893552da486aff5442543f208
rlavanya9/cracking-the-coding-interview
/recursion/magic-array.py
798
3.71875
4
# def magic_array(myarr): # return magic_array_helper(myarr, 0) # def magic_array_helper(myarr, i): # if not myarr: # return -1 # while myarr: # if myarr[i] == i: # return i # magic_array(i+1) def magic_array(myarr, low, high): if high >= low: mid = (low+high)//2 if myarr[mid] == mid: return mid if myarr[mid] < mid: return magic_array(myarr, mid+1, high) elif myarr[mid] > mid: return magic_array(myarr, low, mid-1) else: return -1 arr = [-10, -1, 0, 3, 10, 11, 30, 50, 100] n = len(arr) print("Fixed Point is " + str(magic_array(arr, 0, n-1))) # print(magic_array([-10, -5, 0, 3, 7])) # print(magic_array([0, 2, 5, 8, 17])) # print(magic_array([-10, -5, 3, 4, 7, 9]))
a13193bb6057fd44d4050784f6d53c0a3a6e5c5d
Kimyehoon/python
/src/chap05/p222_bisection.py
693
3.96875
4
## # 이 프로그램은 이분법을 구현한다. # # 함수를 정의한다. def f(x): return(x**2-x-1) def bisection_method(a, b, error): if f(a)*f(b) > 0: print("구간에서 근을 찾을 수 없습니다.") else: while (b - a)/2.0 > error: # 오차를 계산한다. midpoint = (a + b)/2.0 # 중점을 계산한다. # print(midpoint) if f(midpoint) == 0: return(midpoint) elif f(a)*f(midpoint) < 0: b = midpoint else: a = midpoint return(midpoint) answer = bisection_method(1, 2, 0.0001) print("x**2-x-1의 근:", answer)
38775b101a5f6baaababbc220475d549420cf597
mciaccio/Introduction-To-Data-Analysis
/accessingElementsOfADataFrame.py
7,355
3.609375
4
import pandas as pd # Subway ridership for 5 stations on 10 different days ridership_df = pd.DataFrame( data=[[ 0, 0, 2, 5, 0], [1478, 3877, 3674, 2328, 2539], [1613, 4088, 3991, 6461, 2691], [1560, 3392, 3826, 4787, 2613], [1608, 4802, 3932, 4477, 2705], [1576, 3933, 3909, 4979, 2685], [ 95, 229, 255, 496, 201], [ 2, 0, 1, 27, 0], [1438, 3785, 3589, 4174, 2215], [1342, 4043, 4009, 4665, 3033]], index=['05-01-11', '05-02-11', '05-03-11', '05-04-11', '05-05-11', '05-06-11', '05-07-11', '05-08-11', '05-09-11', '05-10-11'], columns=['R003', 'R004', 'R005', 'R006', 'R007'] ) print("") # print("ridership_df ->") # print(ridership_df) # (ridership_df) - <class 'pandas.core.frame.DataFrame'> # print("(ridership_df) - {}".format(type(ridership_df))) print("") # Accessing elements if False: print("Begin Accessing elements ILOC required loc will not work") print("") # print (ridership_df.iloc[0]) # column headings - zeroth ROW, zero based indexing print("") x = ridership_df.iloc[0] # type(x) - <class 'pandas.core.series.Series'> # print("type(x) - {}".format(type(x))) print("") # print (ridership_df.iloc[9]) # column headings - ninth ROW, zero based indexing print("") # print (ridership_df.loc['05-05-11']) # column headings - fourth ROW, zero based indexing print("") # print (ridership_df['R003']) # row labels, zeroth COLUMN - zero based indexing print("") # print (ridership_df.iloc[1, 3]) # no headings or labels - first row, third column zero based indexing print("") print("End Accessing elements\n") # Accessing multiple rows if False: print("") #print (ridership_df.iloc[1:4]) # column headings, row labels - rows 1,2,3 - zero based indexing print("") # Accessing multiple columns if True: # print (ridership_df[['R003', 'R005']]) # column headings, row labels, column zero, column two - zero based indexing print("") # Pandas axis if False : df = pd.DataFrame({'A': [0, 1, 2], 'B': [3, 4, 5]}) print(df) print("") # print (df.sum()) # column headings - column sums print("") # print (df.sum(axis=1)) # row index - row sums print("") # x = df.values.sum() # type(x) - <class 'numpy.int64'> # print("type(x) - {}".format(type(x))) # print("") # print (df.values.sum()) # sum of all values in Data Frame - 15 print("") # Change False to True for each block of code to see what it does # DataFrame creation # print Data Frame df_1 = pd.DataFrame({'A': [0, 1, 2], 'B': [3, 4, 5]}) if False: # You can create a DataFrame out of a dictionary mapping column names to values # Dictionary key value pairs - value is df_1 = pd.DataFrame({'A': [0, 1, 2], 'B': [3, 4, 5]}) # type(df_1) - <class 'pandas.core.frame.DataFrame'> # print("type(df_1) - {}".format(type(df_1))) # print df_1 # print entire DataFrame Data Frame print("Entire Panda Data Frame df_1 -> ") print(df_1) print("") # print Data Frame Rows if False: print("First ROW df_1.loc[0] -> ") print(df_1.loc[0]) print("First ROW ILOC df_1.iloc[0] -> ") print(df_1.iloc[0]) print("") print("Second ROW df_1.loc[2] -> ") print(df_1.loc[2]) print("Second ROW ILOC df_1.iloc[2] -> ") print(df_1.iloc[2]) print("") # print Data Frame Columns if False: print("zeroth ILOC COLUMN df_1.iloc[:,0] -> ") print(df_1.iloc[:,0]) # zeroth column print("") print("first ILOC COLUMN df_1.iloc[:,1] -> ") print(df_1.iloc[:,1]) # zeroth column print("") # print Data Frame Elements if False: print("zero ROW, ZERO Column, df_1.loc[0][1] -> ") print(df_1.loc[0][1]) print("") print("zero ROW, ZERO Column, df_1.loc[2][0] -> ") print(df_1.loc[2][1]) print("") # print("zero ROW, ONE Column, df_1.loc[0][1] -> ") # print(df_1.loc[0][1]) # print("zero ROW, ONE Column, ILOC, df_1.iloc[0][1] -> ") # print(df_1.iloc[0][1]) # print("") # # print("...........52first ROW df_1.loc[:0] -> ") # print(df_1.loc[:0]) # print("") # print("first two ROWS df_1.loc[:1] -> ") # print(df_1.loc[:1]) # print("") # print("all three ROWS df_1.loc[:2] -> ") # print(df_1.loc[:2]) # print("") # print(".....61all ROWS first COLUMN df_1.loc[:3,0] -> ") # # print(df_1.loc[0]) # zeroth row # print(df_1.iloc[:,0]) # zeroth column # print(df_1.iloc[:,1]) # first column # print(df_1.loc[1]) # print(df_1.loc[0:0]) # print(df_1.loc[0:1]) # print(df_1.loc[1:]) # print(df_1.loc[0][0]) # print(df_1.loc[0][1]) # print("") # print("all ROWS second COLUMN df_1.loc[:3,1] -> ") # print(df_1.iloc[:3,1]) # print("") # print("df_1.loc[2] -> ") # print(df_1.loc[2]) # print("") # # You can also use a list of lists or a 2D NumPy array df_2 = pd.DataFrame([[0, 1, 2], [3, 4, 5]], columns=['A', 'B', 'C']) # print df_2 # print("Panda Data Frame df_2 -> ") # print(df_2) # print("") # Accessing elements if False: # print ridership_df.iloc[0] print("ILOC ridership_df.iloc[0]) -> ") print(ridership_df.iloc[0]) print("") # print ridership_df.loc['05-05-11'] print("ridership_df.loc['05-05-11'] -> ") print(ridership_df.loc['05-05-11']) print("") #print ridership_df['R003'] print("ridership_df['R003'] -> ") print(ridership_df['R003']) print("") # print ridership_df.iloc[1, 3] print("ridership_df.iloc[1, 3] -> ") print(ridership_df.iloc[1, 3]) print("") # Accessing multiple rows if False: # print ridership_df.iloc[1:4] print("ridership_df.iloc[1:4] -> ") print(ridership_df.iloc[1:4]) print("") # Accessing multiple columns if False: # print ridership_df[['R003', 'R005']] print("ridership_df[['R003', 'R005']] -> ") print(ridership_df[['R003', 'R005']]) print("") # Pandas axis if False: df = pd.DataFrame({'A': [0, 1, 2], 'B': [3, 4, 5]}) # print df.sum() print("df -> ") print(df) print("") # print df.sum() print("sum of A COLUMN, sum of B COLUMN - df.sum() -> ") print(df.sum()) print("") # print df.sum(axis=1) print("132 ... sum of all ROWS - df.sum(axis=1) -> ") print(df.sum(axis=1)) print("") #print df.values.sum() # print values of Data Frame print("SUM OF ALL VALUES in Data Frame df.values.sum() -> ") print(df.values.sum()) print("") def mean_riders_for_max_station(ridership): ''' Fill in this function to find the station with the maximum riders on the first day, then return the mean riders per day for that station. Also return the mean ridership overall for comparsion. This is the same as a previous exercise, but this time the input is a Pandas DataFrame rather than a 2D NumPy array. ''' overall_mean = None # Replace this with your code mean_for_max = None # Replace this with your code return (overall_mean, mean_for_max)
27052ad4ab4dede590aa17dc5f41e389afa8f0ee
spedas/pyspedas
/pyspedas/themis/common/check_args.py
1,956
4.21875
4
def check_args(**kwargs): """ Check arguments for themis load function Parameters: **kwargs : a dictionary of arguments Possible arguments are: probe, level The arguments can be: a string or a list of strings Invalid argument are ignored (e.g. probe = 'g', level='l0', etc.) Invalid argument names are ignored (e.g. 'probes', 'lev', etc.) Returns: list Prepared arguments in the same order as the inputs Examples: res_probe = check_args(probe='a') (res_probe, res_level) = check_args(probe='a b', level='l2') (res_level, res_probe) = check_args(level='l1', probe=['a', 'b']) # With incorrect argument probes: res = check_args(probe='a', level='l2', probes='a b') : res = [['a'], ['l2']] """ valid_keys = {'probe', 'level'} valid_probe = {'a', 'b', 'c', 'd', 'e'} valid_level = {'l1', 'l2'} # Return list of values from arg_list that are only included in valid_set def valid_list(arg_list, valid_set): valid_res = [] for arg in arg_list: if arg in valid_set: valid_res.append(arg) return valid_res # Return list res = [] for key, values in kwargs.items(): if key.lower() not in valid_keys: continue # resulting list arg_values = [] # convert string into list, or ignore the argument if isinstance(values, str): values = [values] elif not isinstance(values, list): continue for value in values: arg_values.extend(value.strip().lower().split()) # simple validation of the arguments if key.lower() == 'probe': arg_values = valid_list(arg_values, valid_probe) if key.lower() == 'level': arg_values = valid_list(arg_values, valid_level) res.append(arg_values) return res
471c2f3b259b7416f27efaa808b11c9b28a0a93c
lukebiggerstaff/simple-python-ds
/datastructures/binarytree/binarytree.py
4,101
3.921875
4
''' Python representation of binary tree ''' class Node(object): def __init__(self, data, parent=None, left=None, right=None): self.data = data self.parent = parent self.left = left self.right = right def _is_leaf_node(self): return not self.left and not self.right def _has_two_child_nodes(self): return self.left is not None and self.right is not None def _is_left_child(self): return self.parent.left == self def _is_right_child(self): return self.parent.left == self def _is_root(self): return self.parent is None def _has_left_child(self): return self.left is not None def _has_right_child(self): return self.right is not None def __repr__(self): return '<class Node data: {} >'.format(self.data) def __iter__(self): if self.left: yield from self.left yield self if self.right: yield from self.right class BinaryTree(object): def __init__(self, root=None): self.root = root def _find_replacement_node(self, node): if node.right is None: return node else: return self._find_replacement_node(node.right) def insert(self, data, current=None): if self.root is None: self.root = Node(data) return None if current is None: current = self.root if current.data == data: raise ValueError('Can not insert duplicate data.') if current.data > data: if current.left is None: current.left = Node(data, parent=current) else: return self.insert(data, current=current.left) if current.data < data: if current.right is None: current.right = Node(data, parent=current) else: return self.insert(data, current=current.right) def search(self, data, current=None): if self.root is None: return None if current is None: current = self.root if current.data == data: return current if current.data > data: if current.left is None: return None else: return self.search(data, current=current.left) if current.data < data: if current.right is None: return None else: return self.search(data, current=current.right) def delete(self, data): node = self.search(data) if node is None: return None if node._is_leaf_node(): if node._is_root(): self.root = None else: if node._is_left_child(): node.parent.left = None else: node.parent.right = None return None if node._has_two_child_nodes(): replacement = self._find_replacement_node(node.left) replacement_data = replacement.data self.delete(replacement.data) node.data = replacement_data return None if node._has_left_child(): node.left.parent = node.parent if node._is_root(): self.root = node.left else: if node._is_left_child(): node.parent.left = node.left else: node.parent.right = node.left return None if node._has_right_child(): node.right.parent = node.parent if node._is_root(): self.root = node.right else: if node._is_left_child(): node.parent.left = node.right else: node.parent.right = node.right return None def __iter__(self): if self.root.left: yield from self.root.left yield self.root if self.root.right: yield from self.root.right
f1b870fee8fb968d65fa0585ae3a744cc61f2ec3
avinav10/python_programs
/random_programming_primenumber.py
638
3.984375
4
##prime number---- 2,3,5,7,11 number is divisible by itself def prime_number(number): store=[] for i in range(2,number+1): isPrime = True for num in range(2,i): if (i%num)==0: isPrime = False if isPrime: store.append(i) return store print(prime_number(100)) def func(string): print(string) func("hello world") # def find_prime(number): # # if number==1: # return False # # for i in range(2,number): # if number%i==0: # return False # return True # # # for i in range(1,100): # print(i,find_prime(i))
a9fba55e5933093f0596c594386911b1c66a1762
soy-sauce/cs1134
/hw3/cz1529_hw3_q3.py
514
3.78125
4
def find_duplicates(lst): dic={} #create dictionary holding nums and how may times it appears dups=[] for i in range(len(lst)): item=lst[i] if item in dic: dic[lst[i]]+=1 #increase value if appears again else: dic[lst[i]]=1 for k,v in dic.items(): #return all items that appeared more than once if v>1: dups.append(k) return dups def main(): lst=[2,4,4,1,2] print(find_duplicates(lst)) main()
42819180eb1509b3681934319a2d25c680826e2c
zhangjiang1203/Python-
/009-class/test1.py
1,107
3.90625
4
message = "你好,python" print(message) message = "你好,开始学习python之路" print(message) #程序中可以随时修改变量的值,而python将始终记录变量的最新值 'This is a string' "This is also a string" name = "ada lovelace" #title() 是以首字母大写的方式显示每个单词,即将每个单词的首字母都改为大写 print(name.title()) print(name.upper()) print(name.lower()) first_name = "zhang" last_name = "jiang" print(first_name + " " + last_name) print("Python") print("\tPython") print("Languages:\nPython\nC\nJavaScript") #python能找出字符串末尾多余的空白,要确保字符串末尾没有空白,使用rstrip() #剔除字符串开头的空格 lstrip()函数 #同时剔除两端的字符串空白 strip() favorite_language = ' python' print(favorite_language) favorite_language = favorite_language.lstrip() print(favorite_language) print(3 ** 2) # **表示乘方运算 2表示乘方次数 #str 将整形转为字符串类型 age = 23 birthMsg = "Happy " + str(age) + "rd Birthday" print(birthMsg) print(5+3) print(2*4) print(4+4*2-4) print(16/2)
02f70a907c8c336dc807185241308604f3c35ac6
yuanguLeo/yuanguPython
/CodeDemo/shangxuetang/一期/序列/list列表/列表元素的访问和计数.py
686
3.890625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/8/23 9:42 # 通过索引直接访问 a = [10,20,30,10,40,50,60,20,20] print(a[2]) print("-----------------------------") # index() 获取指定元素的列表中首次出现的索引 print(a.index(20)) print("-----------------------------") # count() 获得元素在列表中出现的次数 print(a.count(20)) print("-----------------------------") # len() 返回列表的长度 print(len(a)) print("-----------------------------") # 成员资格的判断 in(简洁,推荐使用) 或 count print(a.count(20) > 0) print("-----------------------------") a = 20 in a print(a) print("-----------------------------")
ca4a7b4ba041da7714638f04e7bdd8140e7686bc
adrianmendez03/algos
/python/linked-list/mergetwolinkedlist.py
783
3.625
4
class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: result = None while(l1 or l2): if l1 and l2: if l1.val <= l2.val: t = ListNode(l1.val) l1= l1.next else: t = ListNode(l2.val) l2= l2.next elif l1: t = ListNode(l1.val) l1= l1.next elif l2: t = ListNode(l2.val) l2= l2.next if result ==None: result = t p2= result else: p2.next = t p2= p2.next return result
0c5038eef3fb5839dbe7d4a2a3499648ce79a27a
Viiic98/holbertonschool-machine_learning
/supervised_learning/0x06-keras/0-sequential.py
1,088
3.6875
4
#!/usr/bin/env python3 """ NN with Keras library """ import tensorflow.keras as K def build_model(nx, layers, activations, lambtha, keep_prob): """ builds a neural network with the Keras library @nx: is the number of input features to the network @layers: is a list containing the number of nodes in each layer of the network @activations: is a list containing the activation functions used for each layer of the network @lambtha: is the L2 regularization parameter @keep_prob: is the probability that a node will be kept for dropout You are not allowed to use the Input class Returns: the keras model """ model = K.Sequential() for i in range(len(layers)): model.add(K.layers.Dense(layers[i], activation=activations[i], input_shape=(nx,), kernel_regularizer=K.regularizers.l2(lambtha))) if i + 1 < len(layers): model.add(K.layers.Dropout(1 - keep_prob)) return model
fd8157fa5b553e05f64cd852373cbe943a593a5f
AlvaroRuizDelgado/L5R_4E_dice_roller
/roll.py
3,265
3.625
4
#!/usr/local/bin/python3 # Last edited: 18/08/15 import sys from random import randint def roll(argv): if (len(argv) == 0 or "--help" in argv or "-h" in argv): print_help() sys.exit(0) # Die characteristics die_range = 10 # Explode mechanic unskilled_flag = False explosion_threshold = 10 # Get the arguments (flag for unskilled, accept exploding result in case it's 9 --> same conditional?). roll_keep = argv.pop(0) roll = int(roll_keep[0:roll_keep.find('k')]) keep = int(roll_keep[roll_keep.find('k')+1:]) bonus = 0 while len(argv) > 0: if (argv[0] == "--unskilled" or argv[0] == "-u"): argv.pop(0) unskilled_flag = True elif (argv[0] == "--explosion" or argv[0] == "-e"): argv.pop(0) explosion_threshold = int(argv.pop(0)) else: bonus = int(argv.pop(0)) # 10 dice mechanic max_dice = 10 if roll > max_dice: difference = roll - max_dice while keep < 10: if difference > 1: keep += 1 difference -= 2 else: break bonus += 2 * difference roll = max_dice if keep > max_dice: bonus += 2 * (keep - max_dice) keep = max_dice if keep > roll: keep = roll # Show the actual values print("Roll:",roll, "Keep:",keep, "Bonus:",bonus, "Explosion value:", explosion_threshold, "Unskilled:",unskilled_flag) # Roll and save to a list. results = [] for i in range (0, roll): die_roll = randint(1,die_range) results.append(die_roll) if unskilled_flag == False: while die_roll >= explosion_threshold: die_roll = randint(1,die_range) results[i] += die_roll # Order the array and get the optimum result. Consider that there could be less dies rolled than kept. results.sort() # reverse=True) optimum = sum(results[roll-keep:]) + bonus # Show the optimum result in green (or perhaps a rotating color), with the other results in a row. The selected ones in white, the others in grey or something. class bcolors: PURPLE = '\033[95m' GREY = '\033[92m' ORANGE = '\033[91m' LIGHT_RED = '\033[35m' print(bcolors.GREY, results[0:roll-keep], bcolors.PURPLE, results[roll-keep:], bcolors.LIGHT_RED, "+", bonus, bcolors.GREY, "-->", bcolors.ORANGE, optimum, bcolors.GREY) return({'roll': roll, 'keep': keep, 'bonus': bonus, 'optimum_value': optimum}) def print_help(): print(" Pass number of dice to roll-keep (e.g. 6k3), followed by a bonus/penalty if applicable.") print(" ./roll 6k3 [12] [-u] [-e value]") print(" ./roll 6k3 [-5] [--unskilled] [--explosion value]") print(" Optional parameters:") print(" -u, --unskilled, dice explosion is disabled.") print(" -e, --explosion, threshold value for dice explosion (10 by default).") print(" When using a container, substitute './roll' for 'docker run -it --rm l5r_dice' in the examples above.") print(" docker run -it --rm l5r_dice 6k3 [12] [-u] [-e value]") if __name__ == "__main__": roll(sys.argv[1:])
b22f6aa7cd19e4c427df559ac971f2027dc47517
lukas9557/dw_matrix
/DW_Matrix01_MachineLearing.py
3,810
3.890625
4
#DataWorkShop - Matrix exercise. Analysis of Men's Shoe Prices, and simple perdiction model #on the basis of data.world/datafiniti/mens-shoe-prices file named 7004_1.csv. ########### DAY 3 ########## import pandas as pd import matplotlib.pyplot as plt import numpy as np def currency_bar_chart(x,y): #it's a function which will print out popularity of currencies x = x.to_frame() x.columns = ["Count"] #change of column name x = x['Count'].to_list() #convert to list y = y.tolist() #convert to list y = y[:13] #removing a single currency y_pos = np.arange(len(y)) plt.barh(y_pos, x, align='center') plt.yticks(y_pos, y) plt.title('Common of currencies') press_ent = input("Press enter to see bar chart which presents popularity of currencies. ") plt.show() ########## IMPORTING DATA ########## n = list() for i in range(0, 39): #chose how many columns we want to read n.append(i) data = pd.read_csv("7004_1.csv", skipinitialspace=True, usecols=n) #read only n columns print(data.columns) #check names of imported columns data.columns = data.columns.str.replace(".","_") #column's names has dots, we have to replace tem with underscore print(data.columns) #column names with _ instead of . ########## DATA PREPARATION ########## print(data.prices_currency.unique()) #check how much different currencies we have print(data.prices_currency.value_counts()) #check which currency is the most popular x = data.prices_currency.value_counts() y = data.prices_currency.unique() currency_bar_chart(x,y) #function calling print(data.prices_currency.value_counts(normalize = True)) #percentage of currencies #96% of currencies are USD, so we will use only USD to perform next steps df_usd = data[data.prices_currency == 'USD'].copy() #filter by currency = USD df_usd['prices_amountMin'] = df_usd['prices_amountMin'].astype(np.float) #change type to float press_ent = input("Press enter to see histogram which presents prices in USD. ") plt.hist(df_usd.prices_amountMin) #histogram of prices plt.show() filter = np.percentile(df_usd.prices_amountMin, 99) #99% of prices are less or equal to this value df_usd_filter = df_usd[df_usd.prices_amountMin < filter] print(df_usd_filter) press_ent = input("Press enter to see histogram which presents 99 percentile of prices, divided to 100 bins. ") plt.hist(df_usd_filter.prices_amountMin, bins=100) plt.show() #this is result of day 3 ########## DAY 4 ########## from sklearn.tree import DecisionTreeRegressor from sklearn.metrics import mean_absolute_error from sklearn.model_selection import cross_val_score def run_model(feats): x = df_usd[feats].values y = df_usd.prices_amountMin.values model = DecisionTreeRegressor(max_depth=5) scores = cross_val_score(model, x, y, scoring='neg_mean_absolute_error') return(("mean(scores): ", np.mean(scores),"std(scores): ", np.std(scores))) mean_price = np.mean(df_usd.prices_amountMin) print("Mean price is: ", mean_price) y_true = df_usd.prices_amountMin y_perd = df_usd.prices_amountMin.count() * [mean_price] print(mean_absolute_error(y_true, y_perd)) median_price = np.median(df_usd.prices_amountMin) print("Median price is: ", median_price) y_perd = df_usd.prices_amountMin.count() * [median_price] print(mean_absolute_error(y_true, y_perd)) lg_price = np.expm1(np.mean(np.log1p(df_usd.prices_amountMin))) print("Log mean price is: ", lg_price) y_perd = df_usd.prices_amountMin.count() * [lg_price] print(mean_absolute_error(y_true, y_perd)) df_usd['brandID'] = df_usd.brand.factorize()[0] #assigning ID to each brand df_usd['manufacturerID'] = df_usd.brand.factorize()[0] #assigning ID to each manufacturer print(run_model(['brandID', 'manufacturerID']))
3d8067944b972d2069584d8212d35446372cc465
amagid/EECS-293-Project-3
/gone/tile_types.py
246
3.53125
4
# TileTypes is an Enum representing the value contained in a tile on the board. # Every cell in the 2-D board array must always contain exactly one TileType. from enum import Enum class TileTypes(Enum): WHITE = 1 BLACK = 2 EMPTY = 3
686a15541f716a0b2b76600e5069bb3def41e747
laurocjs/criptomigo
/sorteio.py
2,939
3.546875
4
# coding= utf-8 import random from Crypto.PublicKey import RSA # Função para sortear os pares def sorteiaPares(listaDeParticipantes): # Recebe lista com nome dos participantes # e o valor é a chave pública dela dictSorteado = {} # Dict a ser retornado numeroDeParticipantes = len(listaDeParticipantes) # Apenas para tornar o código mais limpo e legível if numeroDeParticipantes < 2: print "Você deve ter pelo menos dois participantes!!" return # Geramos então uma lista de N números aleatórios de 0 a N-1, sendo N o número de participantes # Para evitar problemas na distribuição, o primeiro número não pode ser 0 # Caso seja, troco com algum outro número da lista sorteio = random.sample(xrange(numeroDeParticipantes), numeroDeParticipantes) if sorteio[0] == 0: rand = random.randint(1, numeroDeParticipantes-1) sorteio[0] = sorteio[rand] sorteio[rand] = 0 # Realiza uma distribuição em que cada participante recebe outro participante aleatório iterator = 0 for numero in sorteio: if iterator == numero: # A pessoa tirou ela própria # Nesse caso, ele troca com a pessoa anterior a ele na lista dictSorteado[listaDeParticipantes[iterator]] = dictSorteado[listaDeParticipantes[iterator-1]] dictSorteado[listaDeParticipantes[iterator-1]] = listaDeParticipantes[numero] else: dictSorteado[listaDeParticipantes[iterator]] = listaDeParticipantes[numero] iterator += 1 return dictSorteado # Função para criptografar o dict def criptografaSorteio(dictDeChaves, dictSorteado): # Recebe dict Presenteante -> Chave e Presenteante -> Presenteado dictCriptografado = {} for participante in dictDeParticipantes: pubKeyObj = RSA.importKey(dictDeParticipantes[participante]) # Pega a chave pública do participante msg = dictSorteado[participante] # Pega o presenteado sorteado para ele emsg = pubKeyObj.encrypt(msg, 'x')[0] # Encripta o nome do sujeito caminho = "sorteio/" + participante with open(caminho, "w") as text_file: text_file.write(emsg) # Início do programa: # Crie a sua lista de participantes da maneira preferida # A forma mais básica é: listaDeParticipantes = [] # Uma lista de participantes # Porém ler de um arquivo ou diretório também é interessante dictDeParticipantes = {} # Um dict vazio # Para cada participante, lê a sua chave e mapeia Participante -> Chave Pública for participante in listaDeParticipantes: with open("chaves/pubKey" + participante, mode='r') as file: key = file.read() dictDeParticipantes[participante] = key dictSorteado = sorteiaPares(listaDeParticipantes) # Recebe o dicionário que mapeia presenteante -> presenteado criptografaSorteio(dictDeParticipantes, dictSorteado)
ed6b067bd0c1eb3e4a5e737fdbf6eb7cb6aa3916
Prabhnometery/problem-set-codeforces
/231A - Team.py
282
3.625
4
# Solution to problem 231A - Team # Link - https://codeforces.com/problemset/problem/231/A n = int(input()) count = 0 for i in range(0,n): num = str(input()) if num == '1 1 0' or num == '1 0 1' or num == '1 1 1' or num == '0 1 1': count = count + 1 print(count)
1c609aa90f6dbb83e8ea4639ef8b7586ae94585f
ifern/Company-Search
/ScrapeTest.py
676
3.546875
4
import urllib import csv import requests wordsfile = csv.DictReader(open("words.csv")) #links = ['http://econpy.pythonanywhere.com/ex/001.html','http://www.itrade4profit.in/showscripfca0.htm?sym=APCOTEXIND'] #Search for every word in the words list in every URL in the links list. Print both word and the URL if found for word in wordsfile: curr_word = word['search_word'] linksfile = csv.DictReader(open("links.csv")) for link in linksfile: curr_link = link['url'] site = urllib.urlopen(curr_link).read() if curr_word in site: print(curr_word, " Present in", curr_link)
2a5b0dbb9987c01889f2c4aad183cb1957c78ec8
prashantpandey9/codesseptember2019-
/hackerearth/supernatural.py
433
4
4
import math def primeFactors(n): q=0 while n % 2 == 0: ## print(2) q+=1 n = n / 2 for i in range(3,int(math.sqrt(n))+1,2): while n % i== 0: ## print(i) q+=1 n = n / i # Condition if n is a prime # number greater than 2 if n > 2: ## print(n) q+=1 print(q) primeFactors(int(input()))
57149892524d8d172638a0e8beedd211ca9ce585
nguyen-viet-hung/tabml
/tabml/metrics.py
7,367
3.734375
4
import abc from typing import Collection, Dict, List, Union import numpy as np from sklearn import metrics as sk_metrics class BaseMetric(abc.ABC): """Base class for metrics. Usually, one metric returns one score like in the case of accuracy, rmse, mse, etc. However, in some cases, metrics might contain several values as precision, recall, f1. In these cases, method compute_scores will return a list of scores. Attributes: name: A string of class attribute, unique for each metric. is_higer_better: A bool value to tell if the higher the metric, the better the performance. The metric here is the first score in the output of compute_scores function. Note that, for some metrics like RMSE, lower numbers are better. need_pred_proba: A bool value to decide predict or predict_proba in model will be used. """ name: str = "" score_names = [""] is_higher_better: Union[bool, None] = None need_pred_proba: bool = False def compute_scores(self, labels: Collection, preds: Collection) -> Dict[str, float]: if self.is_higher_better is None: raise ValueError("Subclasses must define is_higher_better.") if len(labels) != len(preds): raise ValueError( f"labels (len = {len(labels)}) and preds (len = {len(preds)}) " "must have the same length" ) scores = self._compute_scores(labels, preds) if len(self.score_names) != len(scores): raise ValueError( f"self.score_names ({self.score_names}) and scores ({scores}) " "must have the same length." ) return dict(zip(self.score_names, scores)) def _compute_scores(self, labels: Collection, preds: Collection) -> List[float]: raise NotImplementedError class MAE(BaseMetric): """Mean Absolute Error.""" name = "mae" score_names = ["mae"] is_higher_better = False def _compute_scores(self, labels: Collection, preds: Collection) -> List[float]: return [sk_metrics.mean_absolute_error(labels, preds)] class RMSE(BaseMetric): """Root Mean Square Error.""" name = "rmse" score_names = ["rmse"] is_higher_better = False def _compute_scores(self, labels: Collection, preds: Collection) -> List[float]: return [sk_metrics.mean_squared_error(labels, preds) ** 0.5] class AccuracyScore(BaseMetric): """Accuracy for classification.""" name = "accuracy_score" score_names = ["accuracy_score"] is_higher_better = True def _compute_scores(self, labels: Collection, preds: Collection) -> List[float]: return [sk_metrics.accuracy_score(labels, preds)] class RocAreaUnderTheCurve(BaseMetric): """Area ROC under the curve for binary classification.""" name = "roc_auc" score_names = ["roc_auc"] is_higher_better = True need_pred_proba = True def _compute_scores(self, labels: Collection, preds: Collection) -> List[float]: # In some small groups of samples, labels might be all 0 or 1, which might cause # ValueError when computing ROC AUC. try: res = sk_metrics.roc_auc_score(labels, preds) except ValueError as error_message: if ( "Only one class present in y_true. " "ROC AUC score is not defined in that case." in repr(error_message) ): res = np.NaN else: raise ValueError(error_message) return [res] class F1Score(BaseMetric): """F1 score.""" name = "f1" score_names = ["f1", "precision", "recall"] is_higher_better = True need_pred_proba = False def _compute_scores(self, labels: Collection, preds: Collection) -> List[float]: _check_binary_list(labels) _check_binary_list(preds) labels = np.array(labels) preds = np.array(preds) eps = 1e-8 tps = np.sum(np.logical_and(preds == 1, labels == 1)) fps = np.sum(np.logical_and(preds == 1, labels == 0)) fns = np.sum(np.logical_and(preds == 0, labels == 1)) eps = 1e-8 precision = tps / np.maximum(tps + fps, eps) recall = tps / np.maximum(tps + fns, eps) f1 = 2 * precision * recall / np.maximum(precision + recall, eps) return [f1, precision, recall] class MaxF1(BaseMetric): """Maximum F1 score accross multiple thresholds.""" name = "max_f1" score_names = ["max_f1", "max_f1_threshold", "max_f1_precision", "max_f1_recall"] is_higher_better = True need_pred_proba = True def _compute_scores(self, labels: Collection, preds: Collection) -> List[float]: return compute_maxf1_stats(labels, preds) def compute_maxf1_stats(labels: Collection, preds: Collection) -> List[float]: """Computes max f1 and the related stats for binary classification. Args: labels: An iterable variable of binary labels preds: An iterable variable of probability predictions. preds are clipped into range [0, 1] before computing f1 score Returns: A tuple of (max f1, threshold at max f1, precision at max f1, recall at max f1). Raises: ValueError if labels contains non-binary values. """ num_thresholds = 1000 labels = np.array(labels).reshape((-1, 1)) # shape (N, 1) preds = np.clip(np.array(preds), 0, 1).reshape((-1, 1)) # shape (N, 1) _check_binary_list(labels) thresholds = np.arange(start=0, stop=1, step=1.0 / num_thresholds) # shape (T,) binary_preds = preds >= thresholds # shape (N, T) with T = num_thresholds tps = np.sum(np.logical_and(binary_preds == 1, labels == 1), axis=0) fps = np.sum(np.logical_and(binary_preds == 1, labels == 0), axis=0) fns = np.sum(np.logical_and(binary_preds == 0, labels == 1), axis=0) eps = 1e-8 precisions = tps / np.maximum(tps + fps, eps) recalls = tps / np.maximum(tps + fns, eps) f1s = 2 * precisions * recalls / np.maximum(precisions + recalls, eps) max_f1 = np.max(f1s) max_f1_index = np.argmax(f1s) max_f1_threshold = thresholds[max_f1_index] max_f1_precision = precisions[max_f1_index] max_f1_recall = recalls[max_f1_index] return [max_f1, max_f1_threshold, max_f1_precision, max_f1_recall] class SMAPE(BaseMetric): name = "smape" # symmetric-mean-percentage-error score_names = ["smape"] is_higher_better = False def _compute_scores(self, labels: Collection, preds: Collection) -> List[float]: nominator = 2 * np.abs(np.array(preds) - np.array(labels)) denominator = np.abs(labels) + np.abs(preds) return [100 * np.mean(np.divide(nominator, denominator))] def get_instantiated_metric_dict() -> Dict[str, BaseMetric]: res = {} for sub_class in BaseMetric.__subclasses__(): metric = sub_class() res[metric.name] = metric return res def _check_binary_list(nums: Collection) -> None: """Checks if a list only contains binary values. Raises an error if not. """ unique_vals = np.unique(nums) for label in unique_vals: if label not in [0, 1]: raise ValueError( f"Input must contain only binary values, got {unique_vals}" )
d9112bf6339b71aa43b0b5541aec6e7ef4c40d66
appym/hacker_rank_playground
/poissonExpectation.py
354
3.53125
4
# Enter your code here. Read input from STDIN. Print output to STDOUT import math lamA, lamB = [float(x) for x in raw_input().split()] # C = 160 + 40 * X^2 # E[C] = 160 + 40 * E[X^2] # E[C] = 160 + 40 ( Var(X) + (E[X])^2) ansA = 160 + 40 * (lamA + lamA ** 2) ansB = 128 + 40 * (lamB + lamB ** 2) print '{:0.3f}'.format(ansA) print '{:0.3f}'.format(ansB)
cf7cfcfef36fdd735b61d31a705e69bd6b1f7ad0
jiaojiening/AlignedReID-Re-Production-Pytorch
/aligned_reid/utils/distance.py
3,599
3.5625
4
"""NOTE the input/output shape of methods.""" import numpy as np def normalize(nparray, order=2, axis=0): """Normalize a N-D numpy array along the specified axis.""" norm = np.linalg.norm(nparray, ord=order, axis=axis, keepdims=True) return nparray / (norm + np.finfo(np.float32).eps) def compute_dist(array1, array2, type='euclidean'): """Compute the euclidean or cosine distance of all pairs. Args: array1: numpy array with shape [m1, n] array2: numpy array with shape [m2, n] type: one of ['cosine', 'euclidean'] Returns: numpy array with shape [m1, m2] """ assert type in ['cosine', 'euclidean'] if type == 'cosine': array1 = normalize(array1, axis=1) array2 = normalize(array2, axis=1) dist = np.matmul(array1, array2.T) return dist else: # shape [m1, 1] square1 = np.sum(np.square(array1), axis=1)[..., np.newaxis] # shape [1, m2] square2 = np.sum(np.square(array2), axis=1)[np.newaxis, ...] squared_dist = - 2 * np.matmul(array1, array2.T) + square1 + square2 squared_dist[squared_dist < 0] = 0 dist = np.sqrt(squared_dist) return dist def shortest_dist(dist_mat): """Parallel version. Args: dist_mat: numpy array, available shape 1) [m, n] 2) [m, n, N], N is batch size 3) [m, n, *], * can be arbitrary additional dimensions Returns: dist: three cases corresponding to `dist_mat` 1) scalar 2) numpy array, with shape [N] 3) numpy array with shape [*] """ m, n = dist_mat.shape[:2] dist = np.zeros_like(dist_mat) for i in range(m): for j in range(n): if (i == 0) and (j == 0): dist[i, j] = dist_mat[i, j] elif (i == 0) and (j > 0): dist[i, j] = dist[i, j - 1] + dist_mat[i, j] elif (i > 0) and (j == 0): dist[i, j] = dist[i - 1, j] + dist_mat[i, j] else: dist[i, j] = \ np.min(np.stack([dist[i - 1, j], dist[i, j - 1]], axis=0), axis=0) \ + dist_mat[i, j] dist = dist[-1, -1] return dist def meta_local_dist(x, y): """ Args: x: numpy array, with shape [m, d] y: numpy array, with shape [n, d] Returns: dist: scalar """ eu_dist = compute_dist(x, y, 'euclidean') dist_mat = (np.exp(eu_dist) - 1.) / (np.exp(eu_dist) + 1.) dist = shortest_dist(dist_mat[np.newaxis])[0] return dist # Tooooooo slow! def serial_local_dist(x, y): """ Args: x: numpy array, with shape [M, m, d] y: numpy array, with shape [N, n, d] Returns: dist: numpy array, with shape [M, N] """ M, N = x.shape[0], y.shape[0] dist_mat = np.zeros([M, N]) for i in range(M): for j in range(N): dist_mat[i, j] = meta_local_dist(x[i], y[j]) return dist_mat def parallel_local_dist(x, y): """Parallel version. Args: x: numpy array, with shape [M, m, d] y: numpy array, with shape [N, n, d] Returns: dist: numpy array, with shape [M, N] """ M, m, d = x.shape N, n, d = y.shape x = x.reshape([M * m, d]) y = y.reshape([N * n, d]) # shape [M * m, N * n] dist_mat = compute_dist(x, y, type='euclidean') dist_mat = (np.exp(dist_mat) - 1.) / (np.exp(dist_mat) + 1.) # shape [M * m, N * n] -> [M, m, N, n] -> [m, n, M, N] dist_mat = dist_mat.reshape([M, m, N, n]).transpose([1, 3, 0, 2]) # shape [M, N] dist_mat = shortest_dist(dist_mat) return dist_mat def local_dist(x, y): if (x.ndim == 2) and (y.ndim == 2): return meta_local_dist(x, y) elif (x.ndim == 3) and (y.ndim == 3): return parallel_local_dist(x, y) else: raise NotImplementedError('Input shape not supported.')
abec9d0c2c0abffdc5735c8f38d4ead87a684af5
Ondrej-Martinek/Algorithms-Coding-problems
/Daily Coding Problem/31. Palindrome integers.py
530
4.125
4
# Palindrome integers '''Given an integer, check if that integer is a palindrome. For this problem do not convert the integer to a string to check if it is a palindrome.''' def is_palindrome(num): res = [] div = 10 while div < num*10: res.append(int((num % div) // (div/10))) div *= 10 return all([True if num == num_rev else False for num, num_rev in zip(res, reversed(res))]) n1 = 121 n2 = 5432112345 n3 = 123 questions = [n1,n2,n3] for number in questions: print(is_palindrome(number))
e3952372576b876bd21f795b4845438c238043f1
JenZhen/LC
/lc_ladder/Adv_Algo/binary-search/Find_Peak_Element_II.py
6,806
3.78125
4
#! /usr/local/bin/python3 # https://lintcode.com/problem/find-peak-element-ii/description # There is an integer matrix which has the following features: # The numbers in adjacent positions are different. # The matrix has n rows and m columns. # For all i < m, A[0][i] < A[1][i] && A[n - 2][i] > A[n - 1][i]. # For all j < n, A[j][0] < A[j][1] && A[j][m - 2] > A[j][m - 1]. # We define a position P is a peek if: # A[j][i] > A[j+1][i] && A[j][i] > A[j-1][i] && A[j][i] > A[j][i+1] && A[j][i] > A[j][i-1] # Example # [ # [1 ,2 ,3 ,6 ,5], # [16,41,23,22,6], # [15,17,24,21,7], # [14,18,19,20,10], # [13,14,11,10,9] # ] # return index of 41 (which is [1,1]) or index of 24 (which is [2,2]) # Requirement O(m + n) where m is row count n is column count """ Algo: Bianry Search D.S.: matris Solution: Solution1: iteration for i in range(1, m - 1): for j in range(1, n - 1): if height[i][j] > (i j) up/down/left/right: return peak Time: O(m * n) Solution2: Search -- climb a mountian: to find the peak, follow the trail to go up hill Worse case Time O(m * n) (zigzag shape) Solution3: Semi binary search Row and column are equivalent. Binary search row: 1) find middle row; 2) find max in middle row; 3) compare max of middle row with its up/down neighbors 4) go to the bigger neighbor direction; will never across the middle row anymore; 5) iterate the process Time: O(logm) + O(n) + O(log(m/2)) + O(n) + ... O(logm * n) Solution4: binary search on rows and columns binary row -> binary column -> binary row -> bianry column -> ... -> findc the peak Assume m = n: T(n) = O(n) + O(n/2) + T(n/2) --> changed from n*n to (n/2) * (n/2) T(n) = 3/2O(n) + T(n/2) ... expand T(n) = 3O(n) So far the best solution, this is a hire standard Acceptable interview solutions are solution3 and solution4 Corner cases: """ class Solution3: # Time O(nlogn) -- n times of binary search # Binary on row, linear find max through each column # Failed lintcode.com time limit. """ @param: A: An integer matrix @return: The index of the peak """ def findPeakII(self, A): # write your code here if not A or not A[0]: return None m = len(A) n = len(A[0]) topRow = 1 # excluding first/last row bottomRow = m - 2 ans = [] while topRow <= bottomRow: midRow = (topRow + bottomRow) // 2 rowMaxCol = self.findRowMaxCol(A[midRow]) # O(n) if A[midRow][rowMaxCol] < A[midRow - 1][rowMaxCol]: bottomRow = midRow - 1 elif A[midRow][rowMaxCol] < A[midRow + 1][rowMaxCol]: topRow = midRow + 1 else: # find a peak point ans.append(midRow) ans.append(rowMaxCol) break return ans def findRowMaxCol(self, row): maxCol = 0 for i in range(len(row)): maxCol = i if row[i] > row[maxCol] else maxCol return maxCol """ -------- | | | | | | ------j-- | | | | i | -------- 1. make a m*n grid to 4 even pieces (size from m * n to m/2 * n/2) 2. Comparing with the middle cross point(as init comparison), iterate O(n) to find col max on axis of midRow, iterate O(m) to find row max on axis of midCol, --> find a pair of i, j that could make a posible candidate on 1/4 panels. 3. Search around (up/down/left/right) that candidate (in the climb mountain style). --> if fails one direction, move candidate to that direction --> if candidate is validated, return it's cooridation, else continue to next recursion level to break down the panel. (Based on current candidate to determine which panel to be broken down) 4. Break down (size from m/2 * n/2 to m/4 * n/4) """ class Solution4: # Time O(m + n) -- binary search on row and column """ @param: A: An integer matrix @return: The index of the peak """ def findPeakII(self, A): # write your code here if not A or not A[0]: return None m, n = len(A), len(A[0]) startRow, endRow = 1, m - 2 startCol, endCol = 1, n - 2 return self.helper(startRow, endRow, startCol, endCol, A) def helper(self, startRow, endRow, startCol, endCol, A): midRow = (startRow + endRow) // 2 midCol = (startCol + endCol) // 2 print("find mid [%s, %s]" %(midRow, midCol)) # init x and y at midRow, midCol x, y = midRow, midCol max = A[midRow][midCol] # Go through columns first for j in range(startCol, endCol + 1): if A[midRow][j] > max: max = A[midRow][j] x = midRow # no change y = j # Go through row for i in range(startRow, endRow + 1): if A[i][midCol] > max: max = A[i][midCol] x = i y = midCol # no change # Search around x,y print("candidate: %s" %A[x][y]) isPeak = True # up if A[x - 1][y] > A[x][y]: isPeak = False x -= 1 # down elif A[x + 1][y] > A[x][y]: isPeak = False x += 1 # left elif A[x][y - 1] > A[x][y]: isPeak = False y -= 1 # right elif A[x][y + 1] > A[x][y]: isPeak = False y += 1 # if find peak if isPeak: return [x, y] # if not find peak, continue to narrow down # top-left if startRow <= x < midRow and startCol <= y < midCol: return self.helper(startRow, midRow - 1, startCol, midCol - 1, A) # top-right if startRow <= x < midRow and midCol < y <= endCol: return self.helper(startRow, midRow - 1, midCol + 1, endCol, A) # bottom-left if midRow < x <= endRow and startCol <= y < midCol: return self.helper(midRow + 1, endRow, startCol, midCol - 1, A) # bottome-right if midRow < x <= endRow and midCol < y <= endCol: return self.helper(midRow + 1, endRow, midCol + 1, endCol, A) return [-1, -1] # Test Cases if __name__ == "__main__": testCases = [ [ [1, 2, 3, 4, 5], [16,41,23,22,6], [15,17,24,21,7], [14,18,19,20,8], [13,12,11,10,9] ], [ [1, 2, 4, 3], [5, 6, 8, 7], [9, 10,12,11], [13,14,16,15], [21,22,24,23], [17,18,20,19] ] ] s3 = Solution3() s4 = Solution4() for A in testCases: res3 = s3.findPeakII(A) print("res3: %s" %repr(res3)) res4 = s4.findPeakII(A) print("res4: %s" %repr(res4))
0aa64064c17c2e7225999f9cf0ce97145b4a87c0
PrettyCharity/Random-Walks-of-a-Drunk
/Simulation.py
5,942
3.9375
4
# -*- coding: utf-8 -*- """ Created on Tue Apr 6 16:17:08 2021 @author: ersoy """ import matplotlib.pyplot as plt import math from Location import * def walk(f, d, num_steps): """Assumes: f a Field, d a Drunk in f, and num_steps an int >= 0. Moves d num_steps times; returns the distance between the final location and the location at the start of the walk.""" start = f.get_loc(d) for s in range(num_steps): f.move_drunk(d) return start.dist_from(f.get_loc(d)) def sim_walks(num_steps, num_trials, d_class): """Assumes num_steps an int >= 0, num_trials an int > 0, d_class a subclass of Drunk Simulates num_trials walks of num_steps steps each. Returns a list of the final distances for each trial""" Homer = d_class() origin = Location(0, 0) distances = [] for t in range(num_trials): f = Field() f.add_drunk(Homer, origin) distances.append(round(walk(f, Homer, num_steps), 1)) return distances def drunk_test(walk_lenghts, num_trials, d_class): """Assumes walk_lenghts a sequence of ints >= 0 num_trials an int > 0, d_class a subclass of Drunk For each number of steps in walk_lenghts, runs sim_walks with num_trials walk and prints results""" for num_steps in walk_lenghts: distances = sim_walks(num_steps, num_trials, d_class) print(d_class.__name__, 'walk of', num_steps, 'steps: Mean =', f'{sum(distances)/len(distances):.3f}, Max =', f'{max(distances)}, Min = {min(distances)}') def sim_all(drunk_kinds, walk_lenghts, num_trials): for d_class in drunk_kinds: drunk_test(walk_lenghts, num_trials, d_class) def sim_drunk(num_trials, d_class, walk_lenghts): mean_distances = [] for num_steps in walk_lenghts: print('Starting simulation of', num_steps, 'steps') trials = sim_walks(num_steps, num_trials, d_class) mean = sum(trials)/len(trials) mean_distances.append(mean) return mean_distances def sim_all_plot(drunk_kinds, walk_lenghts, num_trials): style_choice = style_iterator(('m-', 'r:', 'k-.')) for d_class in drunk_kinds: cur_style = style_choice.next_style() print('Starting simulation of', d_class.__name__) means = sim_drunk(num_trials, d_class, walk_lenghts) plt.plot(walk_lenghts, means, cur_style, label = d_class.__name__) plt.title(f'Mean Distance from Origin ({num_trials} trials)') plt.xlabel('Number of Steps') plt.ylabel('Distance from Origin') plt.legend(loc = 'best') plt.semilogx() plt.semilogy() def get_final_locs(num_steps, num_trials, d_class): locs = [] d = d_class for t in range(num_trials): f = Field() f.add_drunk(d, Location(0, 0)) for s in range(num_steps): f.move_drunk(d) locs.append(f.get_loc(d)) return locs def plot_locs(drunk_kinds, num_steps, num_trials): style_choice = style_iterator(('k+', 'r^', 'mo')) for d_class in drunk_kinds: locs = get_final_locs(num_steps, num_trials, d_class) x_vals, y_vals = [], [] for loc in locs: x_vals.append(loc.get_x()) y_vals.append(loc.get_y()) meanX = sum(x_vals) / len(x_vals) meanY = sum(y_vals) / len(y_vals) cur_style = style_choice.next_style() plt.plot(x_vals, y_vals, cur_style, label = (f'{d_class.__name__} mean loc. = <' + f'{meanX}, {meanY} >')) plt.title(f'Location at End of Walks ({num_steps} steps)') plt.xlabel('Steps East / West of Origin') plt.ylabel('Steps North / South of Origin') plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left') def trace_walk(drunk_kinds, num_steps): style_choice = style_iterator(('k+', 'r^', 'mo')) # f = Field() f = Odd_field(1000, 100, 200) for d_class in drunk_kinds: d = d_class() f.add_drunk(d, Location(0, 0)) locs = [] for s in range(num_steps): f.move_drunk(d) locs.append(f.get_loc(d)) x_vals, y_vals = [], [] for loc in locs: x_vals.append(loc.get_x()) y_vals.append(loc.get_y()) cur_style = style_choice.next_style() plt.plot(x_vals, y_vals, cur_style, label = d_class.__name__) plt.title('Spots Visited on Walk (' + str(num_steps) +' steps)') plt.xlabel('Steps East / West of Origin') plt.ylabel('Steps North / South of Origin') plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left') ### CODE TESTRUNS # drunk_test((10, 100, 1000, 10000), 100, Usual_drunk) # sim_all((Usual_drunk, Cold_drunk, EW_drunk), (100, 1000), 10) # sim_all_plot((Usual_drunk, Cold_drunk, EW_drunk), (10, 100, 1000, 10000, 100000), 100) # plot_locs((Usual_drunk, Cold_drunk, EW_drunk), 100, 200) # trace_walk((Usual_drunk, Cold_drunk, EW_drunk), 200) trace_walk((Usual_drunk, Cold_drunk, EW_drunk), 500) # For Treachorus Fields example ### Finger exercise p365 # Lengths = [10, 100, 1000, 10000, 100000] # Sqrt = list(map(lambda x: math.sqrt(x), Lengths)) # Distance = [] # for steps in Lengths: # Result = sim_walks(steps, 100, Usual_drunk) # Distance.append(sum(Result)/len(Result)) # plt.clf() # plt.axes(xscale = 'log', yscale = 'log') # plt.ylabel("Distance from Origin", fontsize = 15) # plt.xlabel("Number of Steps", fontsize = 15) # plt.title("Mean Distance from Origin (100 Trials)", fontsize = 15) # plt.plot(Lengths, Distance, 'b-', label ='Usual_drunk', linewidth = 2.0) # plt.plot(Lengths, Sqrt, 'g--', label ='sqrt(steps)', linewidth = 2.0) # plt.legend(loc = 'upper left')
ef7d06c4058e1e518da97e3e2646b760a42acad3
mikereil80/cs581
/youtube_data.py
1,637
3.78125
4
# Author: Cheryl Dugas # youtube_data.py searches YouTube for videos matching a search term # To run from terminal window: python3 youtube_data.py from googleapiclient.discovery import build # use build function to create a service object # put your API key into the API_KEY field below, in quotes API_KEY = "AIzaSyB_hD_A2lCAc77NL0U6UfyZhJ_I5ghODfM" API_NAME = "youtube" API_VERSION = "v3" # this should be the latest version # function youtube_search retrieves the YouTube records def youtube_search(s_term, s_max): youtube = build(API_NAME, API_VERSION, developerKey=API_KEY) search_data = youtube.search().list(q=s_term, part="id,snippet", maxResults=s_max).execute() # search for videos matching search term; for search_instance in search_data.get("items", []): if search_instance["id"]["kind"] == "youtube#video": videoId = search_instance["id"]["videoId"] title = search_instance["snippet"]["title"] video_data = youtube.videos().list(id=videoId,part="statistics").execute() for video_instance in video_data.get("items",[]): viewCount = video_instance["statistics"]["viewCount"] if 'likeCount' not in video_instance["statistics"]: likeCount = 0 else: likeCount = video_instance["statistics"]["likeCount"] print("") print(videoId, title, viewCount, likeCount) # main routine search_term = "computer" search_max = 5 youtube_search(search_term, search_max)
d9a7f08bd5cd6353b2c4b2407f786ee26a36e595
Milktea17/python
/1-2장/doit_2-5-딕셔너리.py
1,985
3.6875
4
#딕셔너리 dic = {'name':'pey', 'phone':'0119993323', 'birth':'0118'} #value에 리스트도 넣을 수 있다. a={'a':[1,2,3]} #딕셔너리 쌍 추가 a={1:'a'} a[2]='b' print(a) #{1:'a', 2:'b'} a['name'] = 'pey' print(a) #{1: 'a', 2: 'b', 'name': 'pey'} #딕셔너리 요소 삭제하기 del a[1] print(a) #{2: 'b', 'name': 'pey'} #딕셔너리에서 key의 value를 얻기 print(a['name']) #pey a={2:'a', 1:'b'} print(a[2]) #a 변수의 index가 아닌 key값인것 주의 print("="*40) #주의사항1 a={1:'a', 1:'b'} print(a[1]) #b 동일한 key가 여러개면 1개를 제외하고 무시 #주의사항2 #a={[1,2]:'hi'} #key값은 리스트로 사용할 수 없다. b={(1,2):'hi'} #key값으로 튜플은 사용할 수 있다 #리스트와 튜플의 차이인 고정특징 유무 차이때문이다. print("="*40) #key 리스트 만들기 a={'name':'pey', 'phone':'0119993323', 'birth':'0118'} print(a.keys()) #dict_keys(['name', 'phone', 'birth']) key가 모아진 리스트(dict_keys)를 출력한다. print(list(a.keys())) #['name', 'phone', 'birth'] #value 리스트 만들기 print(a.values()) #dict_values(['pey', '0119993323', '0118']) print(list(a.values())) #['pey', '0119993323', '0118'] #key,value 쌍(items) 리스트 만들기 print(a.items()) #dict_items([('name', 'pey'), ('phone', '0119993323'), ('birth', '0118')]) print(list(a.items())) #[('name', 'pey'), ('phone', '0119993323'), ('birth', '0118')] #key:value 쌍 모두 지우기 a.clear() print(a) #{} print("="*40) #key로 value얻기 a={'name':'pey', 'phone':'0119993323', 'birth':'0118'} print(a.get('name')) #pey print(a.get('key')) #None a['key']를 사용했다면 실행시 key오류가 나는데 함수 사용시에는 None반환 #print(a['key']) #Key Error #만약 None이 아닌 값을 출력하게 하려면 두번째 파라미터에 원하는 값 입력 print(a.get('key','default')) #default #해당 key가 딕셔너리 안에 있는지 조사하기 print('name' in a) #True
1627bf47c3b3dadc7e0713ba3f68af3432b2e715
bbsngg/Introduction-to-ML
/Basic/hw 3/hw3-exercise.py
8,118
4.15625
4
#!/usr/bin/env python # coding: utf-8 # # 人工智能基础 Homework 3 # # # 机器学习 - 线性回归 # ## 一、一元线性回归 # In[1]: import numpy as np import pandas as pd import matplotlib.pyplot as plt # get_ipython().run_line_magic('matplotlib', 'inline') # In[1]: print("My Student Number and Name are: 171250628 宋定杰 ") #此处替换成你的学号和姓名 path = 'hw3data1.txt' data = pd.read_csv(path, header=None, names=['Population', 'Profit']) data.head() # In[ ]: data.describe() # 看下数据长什么样子 # In[ ]: data.plot(kind='scatter', x='Population', y='Profit', figsize=(6,4)) plt.show() # 现在让我们使用梯度下降来实现线性回归,以最小化代价函数。 # 首先,我们将创建一个以参数θ为特征函数的代价函数 # $$J\left( \theta \right)=\frac{1}{2m}\sum\limits_{i=1}^{m}{{{\left( {{h}_{\theta }}\left( {{x}^{(i)}} \right)-{{y}^{(i)}} \right)}^{2}}}$$ # 其中: # $${{h}_{\theta }}\left( x \right)={{\theta }^{T}}X={{\theta }_{0}}{{x}_{0}}+{{\theta }_{1}}{{x}_{1}}+{{\theta }_{2}}{{x}_{2}}+...+{{\theta }_{n}}{{x}_{n}}$$ # In[ ]: def computeCost(X, y, theta): inner = np.power(np.dot(X,theta.T)-y,2) # 填入一行代码,提示使用 np.power 和向量乘法 return np.sum(inner) / (2 * len(X)) # 让我们在训练集中添加一列,以便我们可以使用向量化的解决方案来计算代价和梯度。 # In[ ]: data.insert(0, 'Ones', 1) # 现在我们来做一些变量初始化。 # In[ ]: # set X (training data) and y (target variable) cols = data.shape[1] X = data.iloc[:,0:cols-1]#X是所有行,去掉最后一列 y = data.iloc[:,cols-1:cols]#y是所有行,最后一列 # 观察下 X (训练集) and y (目标变量)是否正确. # In[ ]: X.head()#head()是观察前5行 # In[ ]: y.head() # 代价函数是应该是numpy矩阵,所以我们需要转换X和Y,然后才能使用它们。 我们还需要初始化theta。 # In[ ]: X = np.matrix(X.values) y = np.matrix(y.values) theta = np.matrix(np.array([0,0])) # theta 是一个(1,2)矩阵 # In[ ]: theta # 看下维度 # In[ ]: X.shape, theta.shape, y.shape # 计算代价函数 (theta初始值为0). # ## 请注意,您需要按照作业要求提交下面的函数值。 # In[ ]: computeCost(X, y, theta) # # batch gradient decent(批量梯度下降) # $${{\theta }_{j}}:={{\theta }_{j}}-\alpha \frac{\partial }{\partial {{\theta }_{j}}}J\left( \theta \right)$$ # In[ ]: def gradientDescent(X, y, theta, alpha, iters): temp = np.matrix(np.zeros(theta.shape)) parameters = int(theta.ravel().shape[1]) cost = np.zeros(iters) for i in range(iters): error = (X * theta.T) - y for j in range(parameters): term = np.multiply(error, X[:,j]) temp[0,j] = theta[0,j] - ((alpha / len(X)) * np.sum(term)) theta = temp cost[i] = computeCost(X, y, theta) # 填入一行代码,计算每次迭代的代价函数值 return theta, cost # 初始化一些附加变量 - 学习速率α和要执行的迭代次数。 # In[ ]: alpha = 0.01 iters = 1000 # 现在让我们运行梯度下降算法来将我们的参数θ适合于训练集。 # ## 请注意,您需要按照作业要求提交下面的参数值。 # In[ ]: g, cost = gradientDescent(X, y, theta, alpha, iters) g # 最后,我们可以使用我们拟合的参数计算训练模型的代价函数(误差)。 # ## 请注意,您需要按照作业要求提交下面的函数值。 # In[ ]: computeCost(X, y, g) # 现在我们来绘制线性模型以及数据,直观地看出它的拟合。 # In[ ]: x = np.linspace(data.Population.min(), data.Population.max(), 100) f = g[0, 0] + (g[0, 1] * x) fig, ax = plt.subplots(figsize=(6,4)) ax.plot(x, f, 'r', label='Prediction') ax.scatter(data.Population, data.Profit, label='Traning Data') ax.legend(loc=2) ax.set_xlabel('Population') ax.set_ylabel('Profit') ax.set_title('Predicted Profit vs. Population Size') plt.show() # 由于梯度方程式函数也在每个训练迭代中输出一个代价的向量,所以我们也可以绘制。 请注意,代价总是降低 - 这是凸优化问题的一个例子。 # In[ ]: fig, ax = plt.subplots(figsize=(6,4)) ax.plot(np.arange(iters), cost, 'r') ax.set_xlabel('Iterations') ax.set_ylabel('Cost') ax.set_title('Error vs. Training Epoch') plt.show() # ## 多元线性回归 # 本练习还包括一个房屋价格数据集,其中有2个变量(房子的大小,卧室的数量)和目标(房子的价格)。 我们使用我们已经应用的技术来分析数据集。 # In[ ]: path = 'hw3data2.txt' data2 = pd.read_csv(path, header=None, names=['Size', 'Bedrooms', 'Price']) data2.head() # 对于此任务,我们添加了另一个预处理步骤 - 特征归一化。 这个对于pandas来说很简单 # In[ ]: data2 = (data2 - data2.mean()) / data2.std() data2.head() # 现在我们重复第1部分的预处理步骤,并对新数据集运行线性回归程序。 # In[ ]: # add ones column data2.insert(0, 'Ones', 1) # set X (training data) and y (target variable) cols = data2.shape[1] X2 = data2.iloc[:,0:cols-1] # 从数据集中取得 X,参考之前的一元线性回归练习代码即可 y2 = data2.iloc[:,cols-1:cols] # 从数据集中取得 y # convert to matrices and initialize theta X2 = np.matrix(X2.values) y2 = np.matrix(y2.values) theta2 = np.matrix(np.array([0,0,0])) # perform linear regression on the data set g2, cost2 = gradientDescent(X2, y2, theta2, alpha, iters) # get the cost (error) of the model computeCost(X2, y2, g2) g2 # ## 请注意,您需要按照作业要求提交上面的参数值。 # 我们也可以快速查看这一个的训练进程。 # In[ ]: fig, ax = plt.subplots(figsize=(6,4)) ax.plot(np.arange(iters), cost2, 'r') ax.set_xlabel('Iterations') ax.set_ylabel('Cost') ax.set_title('Error vs. Training Epoch') plt.show() # 我们也可以使用scikit-learn的线性回归函数,而不是从头开始实现这些算法。 我们将scikit-learn的线性回归算法应用于第1部分的数据,并看看它的表现。 # In[ ]: from sklearn import linear_model model = linear_model.LinearRegression() model.fit(X, y) # scikit-learn model的预测表现 # In[ ]: x = np.array(X[:, 1].A1) f = model.predict(X).flatten() fig, ax = plt.subplots(figsize=(6,4)) ax.plot(x, f, 'r', label='Prediction') ax.scatter(data.Population, data.Profit, label='Traning Data') ax.legend(loc=2) ax.set_xlabel('Population') ax.set_ylabel('Profit') ax.set_title('Predicted Profit vs. Population Size') plt.show() # # 4. normal equation(正规方程) # 正规方程是通过求解下面的方程来找出使得代价函数最小的参数的:$\frac{\partial }{\partial {{\theta }_{j}}}J\left( {{\theta }_{j}} \right)=0$ 。 # 假设我们的训练集特征矩阵为 X(包含了${{x}_{0}}=1$)并且我们的训练集结果为向量 y,则利用正规方程解出向量 $\theta ={{\left( {{X}^{T}}X \right)}^{-1}}{{X}^{T}}y$ 。 # 上标T代表矩阵转置,上标-1 代表矩阵的逆。设矩阵$A={{X}^{T}}X$,则:${{\left( {{X}^{T}}X \right)}^{-1}}={{A}^{-1}}$ # # 梯度下降与正规方程的比较: # # 梯度下降:需要选择学习率α,需要多次迭代,当特征数量n大时也能较好适用,适用于各种类型的模型 # # 正规方程:不需要选择学习率α,一次计算得出,需要计算${{\left( {{X}^{T}}X \right)}^{-1}}$,如果特征数量n较大则运算代价大,因为矩阵逆的计算时间复杂度为$O(n3)$,通常来说当$n$小于10000 时还是可以接受的,只适用于线性模型,不适合逻辑回归模型等其他模型 # In[ ]: # 正规方程 def normalEqn(X, y): theta = np.linalg.inv(X.T@X)@X.T@y#X.T@X等价于X.T.dot(X) return theta # In[ ]: final_theta2=normalEqn(X, y) #与批量梯度下降的theta的值略有差距 final_theta2 # ## 请注意,您需要按照作业要求提交上面的参数值。
aa320b737f60838e1c309db4b438f31bf607f0f3
linjunyi22/datastructures
/冒泡排序.py
653
4.0625
4
""" 冒泡排序,有 n 个数,每一个数比较一趟,那么就要比较 n-1趟 每一个数要跟其他数比较,每比较一次,下一个要比较的数的比较次数就少一次 """ l = [3,1,4,5,2,0,7,9] def bubble_sort(lists): for i in range(0,len(lists)-1): # n 个数,比较 n-1趟 for j in range(0,len(lists)-i-1): # 第一个数与 n-1个数比较,第二个数与 n-1-1个数比较,...,第 n 个数与 n-i-1个数比较 if lists[j+1] < lists[j]: # 比较,符合就调换,不符合就保留原位 temp = lists[j] lists[j] = lists[j+1] lists[j+1] = temp return lists test = bubble_sort(l) print(test)
a1c90696d3b7c9f23a28bcca421fd2e9853de004
nessie2013/electricitymap-contrib
/parsers/lib/config.py
641
3.828125
4
from datetime import timedelta def refetch_frequency(frequency: timedelta): """Specifies the refetch frequency of a parser. The refetch frequency is used to determine the how much data is returned by the parser. i.e. if we refetch from d1 to d2 and the frequency is timedelta(days=1), then we will only call the function once every day between d1 and d2. """ assert isinstance(frequency, timedelta) def wrap(f): def wrapped_f(*args, **kwargs): result = f(*args, **kwargs) return result wrapped_f.REFETCH_FREQUENCY = frequency return wrapped_f return wrap
16f53be0bd46fa1a711dd0b6abac4e56d9097dce
p-uday/Image-similarity-and-clustering
/avghash.py
1,714
3.546875
4
from sys import argv from sys import exit from PIL import Image from PIL import ImageStat def AverageHash(theImage): # Convert the image to 8-bit grayscale. theImage = theImage.convert("L") # 8-bit grayscale # Squeeze it down to an 8x8 image. theImage = theImage.resize((8,8), Image.ANTIALIAS) # Calculate the average value. averageValue = ImageStat.Stat(theImage).mean[0] # Go through the image pixel by pixel. # Return 1-bits when the tone is equal to or above the average, # and 0-bits when it's below the average. averageHash = 0 for row in range(8): for col in range(8): averageHash <<= 1 averageHash |= 1 * ( theImage.getpixel((col, row)) >= averageValue) return averageHash def loadImage(filename): try: theImage = Image.open(filename) theImage.load() return theImage except: print ("\nCouldn't open the image " + filename + ".\n") exit(1) if __name__ == '__main__': if len(argv) == 2 or len(argv) == 3: image1 = loadImage(argv[1]) hash1 = AverageHash(image1) print ("\nhash value: " + '%(hash)016x' %{"hash": hash1} + "\t" + argv[1]) if len(argv) == 3: image2 = loadImage(argv[2]) hash2 = AverageHash(image2) print("hash value: " '%(hash)016x' %{"hash": hash2} + "\t" + argv[2] + "\n") # XOR hash1 with hash2 and count the number of 1 bits to assess similarity. print (argv[1] + " and " + argv[2] + " are " + str(((64 - bin(hash1 ^ hash2).count("1"))*100.0)/64.0) + "% similar.") if len(argv) < 2 or len(argv) > 3: print ("\nTo get the hash of an image: python " + argv[0] + " <image name>") print ("To compare two images: python " + argv[0] + " <image 1> <image 2>\n") exit(1)
db462030f53d2ec8a7ac75b46de14729ef81c3c8
NickKletnoi/Python
/01_DataStructures/03_Trees/07_Lca.py
5,344
3.703125
4
#Copyright (C) 2017 Interview Druid, Parineeth M. R. #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. from __future__ import print_function import sys from PrintTreeHelper import PrintTreeHelper class TreeNode(object): def __init__(self, val = 0): self.data = val self.depth = 0 self.left = None self.right = None self.parent = None @staticmethod def construct_bst(parent, values, low, high, node_list) : if (low > high) : return None middle = (low + high) // 2 new_node = TreeNode() new_node.data = values[middle] new_node.parent = parent if (not parent): new_node.depth = 0 else: new_node.depth = parent.depth + 1 new_node.left = TreeNode.construct_bst(new_node, values, low, middle - 1, node_list) new_node.right = TreeNode.construct_bst(new_node, values, middle + 1, high, node_list) node_list[middle] = new_node return new_node #Find the Least Common Ancestor of a BINARY SEARCH TREE #ancestor: the current ancestor node (root node is passed by the caller for first time) #n1 and n2 are two nodes in the tree whose least common ancestor should be found #Return value - least common ancestor node of n1 and n2 @staticmethod def bst_lca(ancestor, n1, n2) : if (not ancestor or not n1 or not n2): return None #If the ancestor data is between n1 data and n2 data, then the #ancestor is the least common ancestor if (n1.data <= ancestor.data and ancestor.data <= n2.data): return ancestor if (n2.data <= ancestor.data and ancestor.data <= n1.data): return ancestor #If the ancestor data is greater than n1 data and n2 data, then #the LCA will be in the left subtrie of the ancestor if (ancestor.data > n1.data and ancestor.data > n2.data): return TreeNode.bst_lca(ancestor.left, n1, n2) #The ancestor data is less than n1 data and n2 data. So #the LCA will be in the right subtrie of the ancestor return TreeNode.bst_lca(ancestor.right, n1, n2) #n: node in the binary tree #Return value: depth of the node @staticmethod def find_depth(n) : depth = 0 while (n.parent) : n = n.parent depth += 1 return depth #Find the Least Common Ancestor of a BINARY TREE #n1 and n2 are two nodes in the tree #Return value: least common ancestor node of n1 and n2 @staticmethod def lca(n1, n2): depth1 = TreeNode.find_depth(n1) depth2 = TreeNode.find_depth(n2) # If n1 is deeper than n2, then move n1 up the tree #till the depth of n1 and n2 match while (depth1 > depth2) : n1 = n1.parent depth1 -= 1 # If n2 is deeper than n1, then move n2 up the tree #till the depth of n1 and n2 match while (depth2 > depth1) : n2 = n2.parent depth2 -= 1 #Move n1 and n2 up the tree until a common node is found while (n1 != n2 ) : n1 = n1.parent n2 = n2.parent return n1 MAX_NUM_NODES_IN_TREE = 10 def handle_error() : print('Test failed') sys.exit(1) if (__name__ == '__main__'): node_list = [None] * MAX_NUM_NODES_IN_TREE #number_list contains numbers in ascending order from 0 to MAX_NUM_NODES_IN_TREE number_list = [i for i in range(MAX_NUM_NODES_IN_TREE)] #Test for different number of nodes in the tree for num_elems in range(MAX_NUM_NODES_IN_TREE + 1) : #Construct the tree based on the data stored in the number list #the nodes will also be stored in the node_list root = TreeNode.construct_bst(None, number_list, 0, num_elems - 1, node_list) print('Printing the tree:') PrintTreeHelper.print_tree(root, num_elems) #Generate all pairs of nodes in the tree using the node_list for i in range(num_elems): for j in range(i+1, num_elems) : #Find the Least Common Ancestor for the two nodes #using the algorithm for the BINARY TREE. #We have created a Binary Search Tree which is also a Binary Tree #So we can apply the BINARY TREE algo for a BST lca1 = TreeNode.lca(node_list[i], node_list[j]) #There is a different algo to find the LCA that is #applicable only for BINARY SEARCH TREE. #Since we have created a Binary Search Tree, use the algo for BST lca2 = TreeNode.bst_lca(root, node_list[i], node_list[j]) #The two results should match if (lca1 != lca2): handle_error() print('Least Common Ancestor of {} and {} = {}'.format(node_list[i].data, node_list[j].data, lca1.data) ) print('_____________________________________________________') print('Test passed')
49e4493a59dc07b0978f68482f5e276f4e772954
kapoorsanj/python2-class
/Conditions.py
97
3.515625
4
rains="False" if(rains=='True'): print("Carry an Umberlla") else: print("Wear a hat")
05ad4a7e819f4ccbd74ae630c7743d9820f9a90d
victorsemenov1980/Coding-challenges
/encodeUrl.py
1,567
4.21875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jun 1 21:53:50 2020 @author: user """ ''' TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl and it returns a short URL such as http://tinyurl.com/4e9iAk. Design the encode and decode methods for the TinyURL service. There is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL. ''' class Codec: def __init__(self): self.dict = {} def encode(self, longUrl): """Encodes a URL to a shortened URL. :type longUrl: str :rtype: str """ import random len_code=6 shortUrl='' coding_string="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" for i in range(len_code): shortUrl+=random.choice(coding_string) self.dict[shortUrl]=longUrl return shortUrl def decode(self, shortUrl): """Decodes a shortened URL to its original URL. :type shortUrl: str :rtype: str """ if shortUrl in self.dict: return self.dict[shortUrl] codec=Codec() print(codec.encode('https://leetcode.com/problems/design-tinyurl')) print(codec.decode(codec.encode('https://leetcode.com/problems/design-tinyurl'))) # Your Codec object will be instantiated and called as such: # codec = Codec() # codec.decode(codec.encode(url))
5f38805c55a661a4fe7db24af1d37b22a4477a08
lidongze6/leetcode-
/784. 字母大小写全排列-2.py
468
3.53125
4
class Solution: def letterCasePermutation(self, S: str) -> List[str]: res=[] def helper(res,tmp,S): if not S: res.append(tmp) else: if S[0].isalpha(): helper(res,tmp+S[0].upper(),S[1:]) helper(res,tmp+S[0].lower(),S[1:]) else: helper(res,tmp+S[0],S[1:]) return helper(res,"",S) return res
774303a090723f2dbf50d98503de29f15382abe7
andreieftime/Full-Eftime-Poker
/core/HandStrength.py
11,581
3.65625
4
from enums.Number import Number #we will have separate functions to check for each poker combination def checkFlush(cards): suit = cards[0].suit for card in cards: if card.suit != suit: return 0 return 1 def checkStraight(cards): numbers = [0 for i in range(14)] for card in cards: x = card.number if x==0: numbers[0] += 1 numbers[13] += 1 else: numbers[x] += 1 #we will count how many consecutive cards we have consecutive = 0 for i in numbers: if i!=0: consecutive += 1 else: consecutive = 0 if consecutive==5: return 1 return 0 def checkStraightFlush(cards): if checkStraight(cards)==1 and checkFlush(cards)==1: return 1 else: return 0 def checkQuads(cards): numbers = [0 for i in range(13)] for card in cards: numbers[card.number] += 1 if numbers[card.number]==4: return 1 return 0 def checkFull(cards): numbers = [0 for i in range(13)] for card in cards: numbers[card.number] += 1 we_have_3 = 0 we_have_2 = 0 for i in numbers: if i==3: we_have_3 = 1 if i==2: we_have_2 = 1 if we_have_2==1 and we_have_3==1: return 1 else: return 0 def checkTrips(cards): numbers = [0 for i in range(13)] for card in cards: numbers[card.number] += 1 if numbers[card.number] == 3: return 1 return 0 def check2Pair(cards): numbers = [0 for i in range(13)] for card in cards: numbers[card.number] += 1 number_2 = 0 for i in numbers: if i == 2: number_2 += 1 if number_2==2: return 1 else: return 0 def checkPair(cards): numbers = [0 for i in range(13)] for card in cards: numbers[card.number] += 1 number_2 = 0 for i in numbers: if i == 2: number_2 += 1 if number_2 == 1: return 1 else: return 0 # this function will return how good a hand is # it will return the combination (straight, flush, two pair etc) # and something about the combination def Strength(cards): #Check for Straight flush if checkStraightFlush(cards)==1: return 8 if checkQuads(cards)==1: return 7 if checkFull(cards)==1: return 6 if checkFlush(cards)==1: return 5 if checkStraight(cards)==1: return 4 if checkTrips(cards)==1: return 3 if check2Pair(cards)==1: return 2 if checkPair(cards)==1: return 1 return 0 #for each combination we will have function that compares #hands with these combinations in order to decide who is better def analyseStraightFlush(cards): numbers = [0 for i in range(14)] for card in cards: x = card.number if x==0: numbers[0] += 1 numbers[13] += 1 else: numbers[x] += 1 consecutive = 0 for i in range(14): if numbers[i]==1: consecutive += 1 else: consecutive = 0 if consecutive==5: return i return -1 def analyseQuads(cards): numbers = [0 for i in range(13)] q = 0 kick = 0 for card in cards: if card.number==0: numbers[12] += 1 else: numbers[card.number - 1] += 1 for i in range(len(numbers)): if numbers[i]==4: q = i if numbers[i]==1: kick = i return q, kick def analyseFull(cards): numbers = [0 for i in range(13)] Value3 = 0 Value2 = 0 for card in cards: if card.number == 0: numbers[12] += 1 else: numbers[card.number - 1] += 1 for i in range(len(numbers)): if numbers[i] == 3: Value3 = i if numbers[i] == 2: Value2 = i return Value3, Value2 def analyseFlush(cards): numbers = [0 for i in range(13)] for card in cards: if card.number == 0: numbers[12] += 1 else: numbers[card.number - 1] += 1 return numbers def analyseStraight(cards): numbers = [0 for i in range(14)] for card in cards: x = card.number if x == 0: numbers[0] += 1 numbers[13] += 1 else: numbers[x] += 1 consecutive = 0 for i in range(14): if numbers[i] == 1: consecutive += 1 else: consecutive = 0 if consecutive == 5: return i return -1 def analyseTrips(cards): numbers = [0 for i in range(13)] for card in cards: if card.number == 0: numbers[12] += 1 else: numbers[card.number - 1] += 1 trip = 0 kick1 = 0 kick2 = 0 for i in range(13): if numbers[i]==3: trip = i if numbers[i]==1: kick2 = kick1 kick1 = i return trip, kick1, kick2 def analyse2Pair(cards): numbers = [0 for i in range(13)] for card in cards: if card.number == 0: numbers[12] += 1 else: numbers[card.number - 1] += 1 p1 = 0 p2 = 0 kick = 0 for i in range(13): if numbers[i]==1: kick = i if numbers[i]==2: p2 = p1 p1 = i return p1, p2, kick def analysePair(cards): numbers = [0 for i in range(13)] for card in cards: if card.number == 0: numbers[12] += 1 else: numbers[card.number - 1] += 1 p = 0 for i in range(13): if numbers[i]==2: numbers[i] = 0 p = i return p, numbers def analyseHighCard(cards): numbers = [0 for i in range(13)] for card in cards: if card.number == 0: numbers[12] += 1 else: numbers[card.number - 1] += 1 return numbers def HandCompare(cards1, cards2): if Strength(cards1)>Strength(cards2): return 1 if Strength(cards1)<Strength(cards2): return 0 if Strength(cards1)==Strength(cards2): if Strength(cards1)==8: if analyseStraightFlush(cards1)>analyseStraightFlush(cards2): return 1 if analyseStraightFlush(cards1)<analyseStraightFlush(cards2): return 0 if analyseStraightFlush(cards1)==analyseStraightFlush(cards2): return -1 if Strength(cards1)==7: q1, kick1 = analyseQuads(cards1) q2, kick2 = analyseQuads(cards2) if q1>q2: return 1 if q1<q2: return 0 if q1==q2: if kick1>kick2: return 1 if kick1<kick2: return 0 if kick1==kick2: return -1 if Strength(cards1)==6: t1, d1 = analyseFull(cards1) t2, d2 = analyseFull(cards2) if t1 > t2: return 1 if t1 < t2: return 0 if t1 == t2: if d1 > d2: return 1 if d1 < d2: return 0 if d1 == d2: return -1 if Strength(cards1)==5: poz1 = analyseFlush(cards1) poz2 = analyseFlush(cards2) verify = 0 for i in range(13): if poz1[12 - i]==1 and poz2[12 - i]==0: verify = 1 return 1 if poz2[12 - i]==1 and poz1[12 - i]==0: verify = 1 return 0 if verify==0: return -1 if Strength(cards1)==4: if analyseStraight(cards1)>analyseStraight(cards2): return 1 if analyseStraight(cards1)<analyseStraight(cards2): return 0 if analyseStraight(cards1)==analyseStraight(cards2): return -1 if Strength(cards1)==3: poz1 = analyseTrips(cards1) poz2 = analyseTrips(cards2) verify = 0 for i in range(3): if poz1[i]>poz2[i]: verify = 1 return 1 if poz1[i]<poz2[i]: verify = 1 return 0 if verify==0: return -1 if Strength(cards1)==2: poz1 = analyse2Pair(cards1) poz2 = analyse2Pair(cards2) verify = 0 for i in range(3): if poz1[i] > poz2[i]: verify = 1 return 1 if poz1[i] < poz2[i]: verify = 1 return 0 if verify == 0: return -1 if Strength(cards1)==1: p1, poz1 = analysePair(cards1) p2, poz2 = analysePair(cards2) if p1>p2: return 1 if p1<p2: return 0 if p1==p2: verify = 0 for i in range(13): if int(poz1[12 - i]) == 1 and poz2[12 - i] == 0: verify = 1 return 1 if poz2[12 - i] == 1 and poz1[12 - i] == 0: verify = 1 return 0 if verify == 0: return -1 if Strength(cards1)==0: poz1 = analyseHighCard(cards1) poz2 = analyseHighCard(cards2) verify = 0 for i in range(13): if poz1[12 - i] == 1 and poz2[12 - i] == 0: verify = 1 return 1 if poz2[12 - i] == 1 and poz1[12 - i] == 0: verify = 1 return 0 if verify == 0: return -1 #this function will display each combination def assess_hand(cards): if Strength(cards)==8: x = analyseStraightFlush(cards) return "You have a Straight Flush " + Number(x).name + " high" if Strength(cards)==7: x, y = analyseQuads(cards) return "You have four of a kind " + Number(x + 1).name if Strength(cards)==6: x, y = analyseFull(cards) return "You have a Full House " + Number(x + 1).name + "s with " + Number(y + 1).name + "s" if Strength(cards)==5: poz = analyseFlush(cards) for i in range(13): if poz[12 - i]!=0: return "You have a Flush " + Number(12 - i + 1).name + " high" if Strength(cards)==4: x = analyseStraight(cards) return "You have a Straight " + Number(x).name + " high" if Strength(cards)==3: x, y, z = analyseTrips(cards) return "You have three o a kind " + Number(x + 1).name + "s" if Strength(cards)==2: x,y, z = analyse2Pair(cards) return "You have two pairs " + Number(x + 1).name + "s" + " and " + Number(y + 1).name + "s" if Strength(cards)==1: x, y = analysePair(cards) return "You have a pair of " + Number(x + 1).name + "s" if Strength(cards)==0: poz = analyseHighCard(cards) for i in range(13): if poz[12 - i] != 0: return "You have a High Card " + Number(12 - i + 1).name + " high"
4d66f6280f86174799a489ae5adf39f79cfaaca7
ClintonTak/CodeChallengeAnswers
/Python/IslandPerimeter.py
2,099
3.75
4
''' This one was a lot of fun to work on and posed an interesting problem. I had to use pen and paper to quickly jot down the different cases. From Leetcode: You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water. Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells). The island doesn't have "lakes" (water inside that isn't connected to the water around the island). One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island.''' class Solution: def islandPerimeter(grid): """ :type grid: List[List[int]] :rtype: int [[0,1,0,0], [1,1,1,0], [0,1,0,0], [1,1,0,0]] = 16 """ count = 0 noIslandFlag = 1 oneBlockFlag = 0 for i in range(0, len(grid)): for j in range(0, len(grid[i])): points = 4 #if the block is alone then it is worth 4 points if grid[i][j] == 1: if (j>0): if (grid[i][j-1] == 1): #check left one cell points-=1 if (j<len(grid[i])): if (grid[i][j+1] == 1): #check right one cell points-=1 if (i > 0): if (grid[i-1][j] == 1): #check below one cell points-=1 if (i<3): if (grid[i+1][j] == 1): #check above one cell points-=1 count += points return count print(Solution.islandPerimeter([[1,1,0,0], [0,1,0,0], [0,0,0,0], [0,0,0,0]] )) ''' [0,1,0,0], [1,1,1,0], [0,1,0,0], [1,1,0,0]] [0,1,0,0], [0,0,0,0], [0,0,0,0], [0,0,0,0]]'''
72dfb4d2b92577a1d8deeabcdf575573085eae20
arthurDz/algorithm-studies
/SystemDesign/multithreading and concurrency/implementing_semaphore.py
1,928
4.21875
4
# Python does provide its own implementation of Semaphore and BoundedSemaphore, however, we want to implement a semaphore with a slight twist. # Briefly, a semaphore is a construct that allows some threads to access a fixed set of resources in parallel. Always think of a semaphore as having a fixed number of permits to give out. Once all the permits are given out, requesting threads, need to wait for a permit to be returned before proceeding forward. # Your task is to implement a semaphore which takes in its constructor the maximum number of permits allowed and is also initialized with the same number of permits. Additionally, if all the permits have been given out, the semaphore blocks threads attempting to acquire it. from threading import Condition class Semaphore: """Simulate Semaphore in Python.""" def __init__(self, max_permits=10, initial_permit=1): """Initiate a semaphore object.""" self.max_permits = max_permits self.current_permit = initial_permit self.lock = Condition() def acquire(self): """Acquire a permit. Block if the current permit is zero.""" self.lock.acquire() # wait when the current permit number is zero while self.current_permit == 0: self.lock.wait() self.current_permit -= 1 # notify potential release that one permit has been acquired self.lock.notify_all() self.lock.release() def release(self): """Release a permit. Block if the current permit is over the max number of permits.""" self.lock.acquire() # wait when the current permit number is equal to the max number of permits while self.current_permit == self.max_permit: self.lock.wait() self.current_permit += 1 # notify potential acquire that one permit has been released self.lock.notify_all() self.lock.release()
a22c0c1e6128e3c5f0e304f7f64c62b6996eea80
PanOrka/Metaheuristics
/Tabu_Search_Walking_Agent/wag.py
4,953
3.5
4
import time from random import randint def check_in_exit(cur_pos, crate): return crate[cur_pos[0]][cur_pos[1]] == '8' def check_cycle(step, prev_step): if step == 'U' and prev_step == 'D': return False elif step == 'D' and prev_step == 'U': return False elif step == 'L' and prev_step == 'R': return False elif step == 'R' and prev_step == 'L': return False else: return True def check_move(step, cur_pos, crate): if step == 'U' and crate[cur_pos[0]-1][cur_pos[1]] != '1': return True elif step == 'D' and crate[cur_pos[0]+1][cur_pos[1]] != '1': return True elif step == 'L' and crate[cur_pos[0]][cur_pos[1]-1] != '1': return True elif step == 'R' and crate[cur_pos[0]][cur_pos[1]+1] != '1': return True else: return False def move(step, cur_pos): if step == 'U': cur_pos[0] += -1 elif step == 'D': cur_pos[0] += 1 elif step == 'L': cur_pos[1] += -1 elif step == 'R': cur_pos[1] += 1 def random_moves(cur_pos, crate, n, m, max_steps): path = [] moves = ['U', 'D', 'L', 'R'] step = '' prev_step = '' while len(path) <= max_steps: step = moves[randint(0, 3)] while not check_cycle(step, prev_step) or not check_move(step, cur_pos, crate): step = moves[randint(0, 3)] prev_step = step for _ in range(randint(1, min([n, m]))): # losujemy dlugosc ciagu ktory chcemy dodac if not check_move(step, cur_pos, crate): break move(step, cur_pos) path += [step] if check_in_exit(cur_pos, crate): return path return path def traverse(cur_pos, path, crate): acc_path = [] for step in path: if check_move(step, cur_pos, crate): move(step, cur_pos) acc_path += [step] if check_in_exit(cur_pos, crate): return acc_path, True return acc_path, False # petla minela bez znalezienia wyjscia def find_way(agent_pos, crate, n, m, max_sec): best_path = [] cur_path = [] cur_pos = [] tabu = [] t_start = time.process_time() while time.process_time() - t_start < max_sec: cur_pos = agent_pos.copy() cur_path = [] while (not check_in_exit(cur_pos, crate)) and time.process_time() - t_start < max_sec: cur_pos = agent_pos.copy() cur_path = random_moves(cur_pos, crate, n, m, (n-2)+(m-2)) # agent zna rozmiary pola wiec ustalam maksymalna liczbe krokow na przejscie przez przekatna if len(best_path) == 0 or len(cur_path) < len(best_path): best_path = cur_path.copy() tabu += [cur_path.copy()] # wrzucamy sobie aktualne minimum do tabu temp_path = cur_path.copy() # tutaj nie tylko chcemy powstrzymac sie od unikania tych samych minimow lokalnych, ale rowniez na unikniecie niepotrzebnego spacerowania # po drogach ktore daja wynik niedopuszczalny, ustalamy male sasiedztwo, ktore probkujemy oraz ogromna tablice tabu for _ in range(min([n, m, len(best_path)])): # ustalamy nasze sasiedztwo na podstawie n, m lub dlugosci najlepszej drogi k = randint(0, len(temp_path)-2) j = randint(k+1, len(temp_path)-1) # probkujemy sasiedztwo temp = temp_path[k] temp_path[k] = temp_path[j] temp_path[j] = temp if not temp in tabu: path_after_swap, did_exit = traverse(agent_pos.copy(), temp_path, crate) if did_exit and len(path_after_swap) < len(best_path): best_path = path_after_swap.copy() tabu += [path_after_swap.copy()] elif len(temp_path) != len(path_after_swap): tabu += [temp_path.copy(), path_after_swap.copy()] else: tabu += [temp_path.copy()] while len(tabu) >= n*m: del tabu[0] return best_path def get_data(): frst_line = str(input()) lst = frst_line.split(" ") max_sec = float(lst[0]) n = int(lst[1]) m = int(lst[2]) agent_pos = [] crate = [] for i in range (n): line = str(input()) if '5' in line: agent_pos += [i] # wiersz agent_pos += [line.find('5')] # kolumna => agent = [wiersz, kolumna] temp = [] for letter in line: if letter != '\n': temp += [letter] crate += [temp] return (max_sec, n, m, crate, agent_pos) if __name__ == "__main__": max_sec, n, m, crate, agent_pos = get_data() best_path = find_way(agent_pos, crate, n, m, max_sec) for l in best_path: move(l, agent_pos) crate[agent_pos[0]][agent_pos[1]] = '█' for i in crate: print(i) print(len(best_path)) print(best_path)
f9cba9c0798d64d1fb58e4b46bede4d8aaf2199e
cnovacyu/python_practice
/automate_the_boring_stuff/Chapter8_MadLibs.py
1,380
4.0625
4
#! python 3 # Opens and reads a file that contains a mad lib. Ask a user for inputs # for placeholders in the mad lib. Create a new file that replaces the # placeholders in the mad lib with user inputs. Do not overwrite the original file. import os, re, pyperclip # Open the file and read the contents madLibFile = open(r'C:\Users\cnovacy\Documents\01 - Projects\python_practice\automate_the_boring_stuff\Test_Files\MadLibs.txt') madLibContent = madLibFile.read() madLibFile.close() print(madLibContent) # Create Regex to search for variables and replace with user input # loop through each variable in the mad lib variables = ['adjective', 'noun', 'verb', 'noun'] for var in variables: print("Enter a " + var + ':') libInput = input() madLibRegex = re.compile(var, re.IGNORECASE) #the sub function will take the matched Regex and replace it with user input #sub functions has count parameter to indicate how many subs should occur madLibFiller = madLibRegex.sub(libInput, madLibContent, 1) madLibContent = madLibFiller print(madLibContent) #Copy the completed mad lib and write to a new file pyperclip.copy(madLibContent) madLibResponseFile = open(r'C:\Users\cnovacy\Documents\01 - Projects\python_practice\automate_the_boring_stuff\Test_Files\madLibResponseFile.txt', 'w') madLibResponseFile.write(pyperclip.paste()) madLibResponseFile.close()
ba54333e64218d8f4b5b96a7ae6f6f333daf1d12
limisen/Programmering-1
/04/04-06.py
455
3.671875
4
X = float(input("Vänligen ange din ålder: ")) Y = float(input("Vad är din brutto inkomst? ")) Z = (input("Har du några kredit-anmärkningar?(ja eller nej) ")) if Z != "ja" and Z != "nej": Z = (input("Svara snälla med ja eller nej, tack!\n Har du några kredit-anmärkningar? " )) pass if X >= 18 and Y >= 120000 and Z == "nej": print("Fakturabetalning beviljad") else: print("Tyvär kan vi inte bevilja fakturabetalning")
dacb0452ab41263ec0143d5cadffe90a9c2565fc
eranraz1/DS
/recursive.py
748
3.5
4
# def recu_sum(numList): # if len(numList) ==1: # return numList[0] # return numList[0] + recu_sum(numList[1:]) # print(recu_sum([1,3,5,7,9])) # def b_(num): # if num == 1: # return -5 # return -5+ b_(num-1) + 9 # print(b_(4)) print('\n') def lookval(ls, look_val): nmax= len(ls) nmin = 0 if len(ls) ==1: if ls[0] == look_val: return True return False else: nmid= len(ls)//2 if look_val == ls[nmid]: return True elif look_val<ls[nmid]: nmax = nmid return lookval(ls[nmin:nmax],look_val) else: nmin = nmid return lookval(ls[nmin:nmax],look_val) flist = [1,2,3,4,5,6,8,9,10,11,14,16] print(lookval(flist,7))
31398f2d9eb46b50fae02e0cfb7661cc3bfc1d6c
NagahShinawy/problem-solving
/pynative/8_dictionary/ex_6.py
964
4
4
""" sampleDict = { "name": "Kelly", "age":25, "salary": 8000, "city": "New york" } keysToRemove = ["name", "salary"] Expected output: {'city': 'New york', 'age': 25} """ def remove_keys(dic, keys): result = dict() for key in dic: if key not in keys: result.update({key: dic[key]}) return result def remove_keys2(dic, keys): for key in keys: dic.pop(key, None) return dic sampleDict = { "name": "Kelly", "age": 25, "salary": 8000, "city": "New york" } keysToRemove = ["name", "salary"] print(remove_keys(sampleDict, keysToRemove)) print(remove_keys2(sampleDict, keysToRemove)) city = sampleDict.pop("city", None) # return removed value or None print("City", city) sampleDict = { "name": "Kelly", "age":25, "salary": 8000, "city": "New york" } keysToRemove = ["name", "salary"] sampleDict = {k: sampleDict[k] for k in sampleDict.keys() - keysToRemove} print(sampleDict)
d158b276d7bbe2369665260cfcd0f2c4264dfc2f
becodev/python-utn-frcu
/guia01python/ejercicio8.py
352
3.625
4
""" El entrenador de un equipo de básquet desea determinar la eficiencia en tiros de campo de un jugador "X". """ tirosTotal = int(input("Ingrese la cantidad total de tiros: ")) tirosAdentro = int(input("Ingrese cantidad de tiros embocados: ")) eficiencia = tirosAdentro / tirosTotal * 100 print("La eficiencia del jugador fue: ", eficiencia, "%")
1723df37a99d556ac3f1a6530bd8d3b0a82fb420
eyuparslana/substringIsland
/met_case1.py
1,232
3.765625
4
def get_all_substrings(entry): length = len(entry) return [entry[i:j + 1] for i in range(length) for j in range(i, length)] def get_island_count(entry, substring): s_len = len(substring) tmp_list = ['0'] * len(entry) for i in range(len(entry)): if entry[i] == substring[0] and entry[i: i + s_len] == substring[0:s_len]: for j in range(i, i + s_len): tmp_list[j] = entry[j] splited_islands = ''.join(tmp_list).split('0') island_count = 0 for island in splited_islands: if island: island_count += 1 return island_count, tmp_list def main(): entry = input("Enter a String: ") number = int(input("Enter a Number: ")) substrings = set(get_all_substrings(entry)) result = 0 print(substrings) print("{} has {} substrings".format(entry, len(substrings))) for substring in substrings: island_count, tmp_list = get_island_count(entry, substring) if island_count == number: result += 1 print(f'{tmp_list} -->> {substring}') print(f'There are {result} different substrings of "{entry}" that produce exactly {number} islands.') if __name__ == '__main__': main()
bb5dbb4cbcde0e47d02d3ab49ad2dbc61b080b97
linda-oranya/algo-rhymes
/hackerank/Easy/counting_valleys/solutions/python/solution.py
472
3.84375
4
def counting_valleys(n, path): valley_count, depth_tracker, sea_level = 0, 0, 0 paths_arr = list(path) for path in paths_arr: if path == "U": sea_level += 1 else: sea_level -= 1 if sea_level == -1: depth_tracker = sea_level if depth_tracker == -1 and sea_level == 0: valley_count += 1 depth_tracker = 0 return valley_count if __name__ == "__main__": pass
1dd8d790605c7bb69084218571cb52744f18c940
ohouse9009/rosalind
/prob4_FIB - Rabbits and Recurrence Relations.py
198
3.8125
4
#!/usr/bin/python # http://www.rosalind.info/problems/fib/ def fib(n,k): popn = 1 for gen in range(n): yield popn popn *= k+1 return n = 40 k = 5 print list(fib(n,k))
ede92a3d031703399bed4dc3e3b8642829125e0d
SamarpanCoder2002/Smart-Calculator-Dolly
/Scientific Calculator Dolly.py
22,814
3.65625
4
from tkinter import * from tkinter import messagebox import math class Calculator: def __init__(self,window): self.window=window self.text_value = StringVar() self.textoperator = StringVar() self.textoperator2 = StringVar() self.fact = 1 self.widget() def butn(self): self.plus = Button(self.window,text="+",width=3,font=("arial",15,"bold"),fg="red",bg="#262626", activebackground="#262626", command=lambda : self.opr("+"), relief=RAISED, bd=3) self.plus.place(x=535,y=240) self.subs = Button(self.window, text="-", width=3, font=("arial", 15, "bold"), fg="red",bg="#262626", activebackground="#262626", command=lambda : self.opr("-"), relief=RAISED, bd=3) self.subs.place(x=535, y=300) self.mul = Button(self.window, text="X", width=3, font=("arial", 15, "bold"), fg="red",bg="#262626", activebackground="#262626", command=lambda : self.opr("X"), relief=RAISED, bd=3) self.mul.place(x=535, y=360) self.div = Button(self.window, text="/", width=3, font=("arial", 15, "bold"), fg="red",bg="#262626", activebackground="#262626", command=lambda : self.opr("/"), relief=RAISED, bd=3) self.div.place(x=535, y=420) self.rad = Button(self.window, text="rad", width=3, font=("arial", 15, "bold"), fg="red",bg="#262626", activebackground="#262626", command=lambda : self.opr("Radian"), relief=RAISED, bd=3) self.rad.place(x=440, y=360) self.reci = Button(self.window, text="1/x", width=3, font=("arial", 15, "bold"), fg="red",bg="#262626", activebackground="#262626", command=lambda : self.opr("Reciprocal"), relief=RAISED, bd=3) self.reci.place(x=440, y=420) self.sqr = Button(self.window, text="X^2", width=3, font=("arial", 15, "bold"), fg="red",bg="#262626", activebackground="#262626", command=lambda : self.opr("Square"), relief=RAISED, bd=3) self.sqr.place(x=440, y=240) self.cube = Button(self.window, text="X^3", width=3, font=("arial", 15, "bold"), fg="red",bg="#262626", activebackground="#262626", command=lambda : self.opr("Cube"), relief=RAISED, bd=3) self.cube.place(x=440, y=300) self.equal = Button(self.window, text="=", width=11, font=("arial", 15, "bold"), fg="red",bg="#262626", activebackground="#262626", command=self.evaluation_opr, relief=RAISED, bd=3) self.equal.place(x=440, y=490) self.clear = Button(self.window, text="Information", width=11, font=("arial", 10, "bold"), activebackground="#262626", fg="red",bg="#262626",command=self.information, relief=RAISED, bd=3) self.clear.place(x=480, y=68) self.sqrt = Button(self.window, text="Square root", width=11, font=("arial", 15, "bold"), fg="red",bg="#262626", activebackground="#262626", command=lambda : self.opr("Square root"), relief=RAISED, bd=3) self.sqrt.place(x=10, y=240) self.cubert = Button(self.window, text="Cube root", width=11, font=("arial", 15, "bold"), fg="red",bg="#262626", activebackground="#262626", command=lambda : self.opr("Cube root"), relief=RAISED, bd=3) self.cubert.place(x=200, y=240) self.log2 = Button(self.window, text="log2", width=11, font=("arial", 15, "bold"), fg="red",bg="#262626", activebackground="#262626", command=lambda : self.opr("log2"), relief=RAISED, bd=3) self.log2.place(x=10, y=300) self.log10 = Button(self.window, text="log10", width=11, font=("arial", 15, "bold"), fg="red",bg="#262626", activebackground="#262626", command=lambda : self.opr("log10"), relief=RAISED, bd=3) self.log10.place(x=200, y=300) self.exponent = Button(self.window, text="e^x", width=3, font=("arial", 15, "bold"), fg="red",bg="#262626", activebackground="#262626", command=lambda : self.opr("Exponent"), relief=RAISED, bd=3) self.exponent.place(x=200, y=360) self.power = Button(self.window, text="X^Y", width=3, font=("arial", 15, "bold"), fg="red",bg="#262626", activebackground="#262626", command=lambda : self.opr("x^y"), relief=RAISED, bd=3) self.power.place(x=295, y=360) self.factorial = Button(self.window, text="n!", width=5, font=("arial", 15, "bold"), fg="red",bg="#262626", activebackground="#262626", command=lambda : self.opr("Factorial"), relief=RAISED, bd=3) self.factorial.place(x=10, y=360) self.mod = Button(self.window, text="Mod", width=4, font=("arial", 15, "bold"), fg="red",bg="#262626", activebackground="#262626", command=lambda: self.opr("Modulus"), relief=RAISED, bd=3) self.mod.place(x=94, y=360) self.reset = Button(self.window, text="Reset", width=5, font=("arial", 15, "bold"), fg="red",bg="#262626", activebackground="#262626", command=self.reset_now, relief=RAISED, bd=3) self.reset.place(x=10, y=420) self.reset = Button(self.window, text="Pi", width=4, font=("arial", 15, "bold"), fg="red",bg="#262626", activebackground="#262626", command=self.pi_val, relief=RAISED, bd=3) self.reset.place(x=95 ,y=420) self.sin = Button(self.window, text="sin", width=5, font=("arial", 15, "bold"), fg="red",bg="#262626", activebackground="#262626", command=lambda: self.opr("sin"), relief=RAISED, bd=3) self.sin.place(x=10, y=490) self.cos = Button(self.window, text="cos", width=4, font=("arial", 15, "bold"), fg="red",bg="#262626", activebackground="#262626", command=lambda: self.opr("cos"), relief=RAISED, bd=3) self.cos.place(x=95, y=490) self.tan = Button(self.window, text="tan", width=3, font=("arial", 15, "bold"), fg="red",bg="#262626", activebackground="#262626", command=lambda: self.opr("tan"), relief=RAISED, bd=3) self.tan.place(x=200, y=490) self.cot = Button(self.window, text="cot", width=3, font=("arial", 15, "bold"), fg="red",bg="#262626", activebackground="#262626", command=lambda: self.opr("cot"), relief=RAISED, bd=3) self.cot.place(x=295, y=490) self.bye = Button(self.window, text="Exit", width=47, font=("arial", 15, "bold"), bg="#262626", fg="green", activebackground="#262626", command=self.tata, relief=RAISED, bd=3) self.bye.place(x=10, y=560) self.lcm = Button(self.window, text="LCM", width=3, font=("arial", 15, "bold"), bg="#262626", fg="red", activebackground="#262626", command=lambda : self.opr("lcm"), relief=RAISED, bd=3) self.lcm.place(x=200, y=420) self.hcf = Button(self.window, text="HCF", width=3, font=("arial", 15, "bold"), bg="#262626", fg="red", activebackground="#262626", command=lambda : self.opr("hcf"), relief=RAISED, bd=3) self.hcf.place(x=295, y=420) def widget(self): Label(self.window,text="Scientific Calculator Dolly",font=("arial",25,"bold","italic"),fg="orange",bg="#141414").place(x=100,y=5) self.result_name = Label(self.window, text="Result: ", width=8, font=("arial", 16, "bold", "italic"), fg="#00FF00",bg="#141414") self.result_name.place(x=40, y=65) self.result = Entry(self.window,font=("Helvetica",20,"bold","italic"),textvar=self.text_value, bd=5, relief=SUNKEN, disabledbackground="#3d3d3d", disabledforeground="gold", state=DISABLED) self.result.place(x=140,y=55) self.butn() self.take_input() def take_input(self): Label(self.window, text="Number 1 ",width=8, font=("arial", 15, "bold","italic"),bg="#141414",fg="#00FF00").place(x=20, y=175) self.number1 = Entry(self.window,width=8,bg="#3d3d3d",font=("arial",20,"bold","italic"), insertbackground="gold", fg="gold",bd=3,relief=SUNKEN) self.number1.place(x=130,y=170) self.number1.focus() Label(self.window, text="Number 2 ", width=8, font=("arial", 16, "bold", "italic"), fg="#00FF00", bg="#141414").place(x=340, y=175) self.number2 = Entry(self.window, width=8, bg="#3d3d3d", font=("arial", 20, "bold", "italic"), insertbackground="gold", fg="gold", relief=SUNKEN, bd=4) self.number2.place(x=455, y=170) self.operator_name = Label(self.window, text="Operation ", width=12, font=("arial", 17, "bold", "italic"), bg="#141414", fg="#d96b6b") self.operator_name.place(x=100, y=120) self.operator = Entry(self.window, width=12, font=("arial", 20, "bold", "italic"), disabledbackground="#3d3d3d",disabledforeground="gold", state="disable",textvar=self.textoperator,bd=5,relief=SUNKEN) self.operator.place(x=250, y=117) def pi_val(self): messagebox.showinfo("Value of pi","The value of pi is: 3.14159265") def reset_now(self): self.textoperator.set(" ") self.text_value.set(" ") def tata(self): self.decision = messagebox.askyesno("Conformation","Do you want to exit right now?") if self.decision>0: window.destroy() else: pass def information(self): self.window_information = Toplevel() self.window_information.title("Information") self.window_information.geometry("500x400") self.window_information.iconbitmap("calculator.ico") self.window_information.maxsize(500,400) self.window_information.minsize(500,400) self.window_information.config(bg="#262626") Label(self.window_information,fg="#00FF00",font=("arial",11,"bold","italic"), text="1.Write number and select operator at first, then click on equal(=) sign.", bg="#262626").place(x=5,y=15) Label(self.window_information, fg="#00FF00", font=("arial", 12, "bold", "italic"), bg="#262626", text="2.For single digit operation(e.g. rad,exponent,Reciprocal(1/x),").place(x=5, y=50) Label(self.window_information, fg="#00FF00", font=("arial", 12, "bold", "italic"), bg="#262626", text="square,cube,square root,cube root,log,factorial(n!),exponent etc.)").place(x=5, y=70) Label(self.window_information, fg="#00FF00", font=("arial", 12, "bold", "italic"), bg="#262626", text="only write number input in the 'Number1' but not write ").place(x=5, y=90) Label(self.window_information, fg="#00FF00", font=("arial", 12, "bold", "italic"), bg="#262626", text="input in 'Number2' .After that select favourable operator and go.").place(x=5, y=110) Label(self.window_information, fg="#00FF00", font=("arial", 15, "bold", "italic"), bg="#262626", text="Best of luck!").place(x=180, y=200) Label(self.window_information, fg="#00FF00", font=("arial", 12, "bold", "italic"), bg="#262626", text="3.For single no. operation,if there is present two no. in 'Number1'").place(x=5, y=140) Label(self.window_information, fg="#00FF00", font=("arial", 12, "bold", "italic"), bg="#262626", text="and 'Number2', only input number in 'Number1' will taken.").place(x=5, y=160) self.window_information.mainloop() def opr(self,work): self.work = work self.textoperator.set(self.work) def evaluation_opr(self): self.n1 = (self.number1.get()) self.n2 = (self.number2.get()) self.work_done = self.textoperator.get() if self.work_done=="+": try: result_take = eval(self.n1)+eval(self.n2) self.text_value.set(int(result_take)) if int(result_take) == result_take else self.text_value.set(result_take) except: messagebox.showerror("Error","Something error in input.please check it.") self.information() self.reset_now() elif self.work_done=="-": try: result_take = eval(self.n1)-eval(self.n2) self.text_value.set(int(result_take)) if int(result_take) == result_take else self.text_value.set(result_take) except: messagebox.showerror("Error","Something error in input.please check it.") self.information() self.reset_now() elif self.work_done=="X": try: result_take = eval(self.n1)*eval(self.n2) self.text_value.set(int(result_take)) if int(result_take) == result_take else self.text_value.set(result_take) except: messagebox.showerror("Error","Something error in input.please check it.") self.information() self.reset_now() elif self.work_done=="/": try: result_take = eval(self.n1)/eval(self.n2) self.text_value.set(int(result_take)) if int(result_take) == result_take else self.text_value.set(result_take) except ZeroDivisionError: self.text_value.set("Can not divide by zero") except: messagebox.showerror("Error","Something error in input.please check it.") self.information() self.reset_now() elif self.work_done=="Reciprocal": try: result_take = round(1.0/eval(self.n1),2) self.text_value.set(int(result_take)) if int(result_take) == result_take else self.text_value.set(result_take) except ZeroDivisionError: self.text_value.set("Can not divide by zero") except: messagebox.showerror("Input Error","Please write number in the right position.Please read the information carefully") self.information() self.reset_now() elif self.work_done=="Square": try: result_take = eval(self.n1) ** 2.0 self.text_value.set(int(result_take)) if int(result_take) == result_take else self.text_value.set(result_take) except: messagebox.showerror("Error","Something error in input.please check it.") self.information() self.reset_now() elif self.work_done=="Cube": try: result_take = eval(self.n1) ** 3.0 self.text_value.set(int(result_take)) if int(result_take) == result_take else self.text_value.set(result_take) except: messagebox.showerror("Error","Something error in input.please check it.") self.information() self.reset_now() elif self.work_done=="Square root": try: result_take = eval(self.n1)**0.5 self.text_value.set(int(result_take)) if int(result_take) == result_take else self.text_value.set(result_take) except: messagebox.showerror("Error","Something error in input.please check it.") self.information() self.reset_now() elif self.work_done == "Cube root": try: result_take = round(eval(self.n1)**(1/3),2) self.text_value.set(int(result_take)) if int(result_take) == result_take else self.text_value.set(result_take) except: messagebox.showerror("Error","Something error in input.please check it.") self.information() self.reset_now() elif self.work_done == "Exponent": try: result_take = math.exp(eval(self.n1)) self.text_value.set(int(result_take)) if int(result_take) == result_take else self.text_value.set(result_take) except: messagebox.showerror("Error","Something error in input.please check it.") self.information() self.reset_now() elif self.work_done=="x^y": try: result_take = eval(self.n1) ** eval(self.n2) self.text_value.set(int(result_take)) if int(result_take) == result_take else self.text_value.set(result_take) except: messagebox.showerror("Error","Something error in input.please check it.") self.information() self.reset_now() elif self.work_done=="Factorial": try: for i in range(1,eval(self.n1)+1): self.fact= self.fact * i self.text_value.set(int(self.fact)) if int(self.fact) == self.fact else self.text_value.set(self.fact) self.fact=1 except: messagebox.showerror("Error","Something error in input.please check it.") self.information() self.reset_now() elif self.work_done=="lcm": try: if eval(self.n1)>eval(self.n2): result_take = (eval(self.n1)*eval(self.n2))/math.gcd(eval(self.n1),eval(self.n2)) self.text_value.set(int(result_take)) if int(result_take) == result_take else self.text_value.set(result_take) else: result_take = (eval(self.n2)*eval(self.n1))/math.gcd(eval(self.n2),eval(self.n1)) self.text_value.set(int(result_take)) if int(result_take) == result_take else self.text_value.set(result_take) except: messagebox.showerror("Error","Something error in input.please check it.") self.information() self.reset_now() elif self.work_done=="hcf": try: if eval(self.n1) > eval(self.n2): result_take = math.gcd(eval(self.n1),eval(self.n2)) self.text_value.set(int(result_take)) if int(result_take) == result_take else self.text_value.set(result_take) else: result_take = math.gcd(eval(self.n2), eval(self.n1)) self.text_value.set(int(result_take)) if int(result_take) == result_take else self.text_value.set(result_take) except: messagebox.showerror("Error","Something error in input.please check it.") self.information() self.reset_now() elif self.work_done == "log2": try: result_take = math.log2(eval(self.n1)) self.text_value.set(int(result_take)) if int(result_take) == result_take else self.text_value.set(result_take) except: messagebox.showerror("Error","Something error in input.please check it.") self.information() self.reset_now() elif self.work_done == "log10": try: result_take = math.log10(eval(self.n1)) self.text_value.set(int(result_take)) if int(result_take) == result_take else self.text_value.set(result_take) except: messagebox.showerror("Error","Something error in input.please check it.") self.information() self.reset_now() elif self.work_done == "Modulus": try: result_take = eval(self.n1)%eval(self.n2) self.text_value.set(int(result_take)) if int(result_take) == result_take else self.text_value.set(result_take) except: messagebox.showerror("Error","Something error in input.please check it.") self.information() self.reset_now() elif self.work_done == "Radian": try: self.text_value.set(round(math.radians(eval(self.n1)),3)) except: messagebox.showerror("Error","Something error in input.please check it.") self.information() self.reset_now() elif self.work_done == "sin": try: result_take = round(math.sin(math.radians(eval(self.n1))),1) self.text_value.set(int(result_take)) if int(result_take) == result_take else self.text_value.set(result_take) except: messagebox.showerror("Error","Something error in input.please check it.") self.information() self.reset_now() elif self.work_done == "cos": try: result_take = round(math.cos(math.radians(eval(self.n1))),1) self.text_value.set(int(result_take)) if int(result_take) == result_take else self.text_value.set(result_take) except: messagebox.showerror("Error","Something error in input.please check it.") self.information() self.reset_now() elif self.work_done == "tan": try: if eval(self.n1) == 90: self.text_value.set("Infinite") else: result_take = round(math.tan(math.radians(eval(self.n1))),1) self.text_value.set(int(result_take)) if int(result_take) == result_take else self.text_value.set(result_take) except: messagebox.showerror("Error","Something error in input.please check it.") self.information() self.reset_now() elif self.work_done == "cot": try: if eval(self.n1) == 0: self.text_value.set("Infinite") else: result_take = round(1/(math.tan(math.radians(eval(self.n1)))),1) self.text_value.set(int(result_take)) if int(result_take) == result_take else self.text_value.set(result_take) except: messagebox.showerror("Error","Something error in input.please check it.") self.information() self.reset_now() else: messagebox.showerror("Error","Please read the information carefully at first.") self.information() self.reset_now() self.number1.focus() if __name__ == '__main__': window = Tk() window.title("Smart Scientific Calculator") window.config(bg='#141414') window.iconbitmap("calculator.ico") window.geometry("600x620") window.maxsize(600,620) window.minsize(600,620) Calculator(window) window.mainloop()
2bd132689be7042f4e936516feafd3bfa4362c9a
OliviaFortuneUCD/Readingkagglecsv
/main.py
477
3.546875
4
#Read the file import pandas as pd covid_vaccination = pd.read_csv("country_vaccinations.csv") #Read hedings and 10 records print(covid_vaccination.head(10)) #Print the headings and their details print(covid_vaccination.info()) #print the values which are null print(info_covid = covid_vaccination.isnull().sum()) #which country is using which vacine covid_vaccination['country_vac'] = covid_vaccination['country'] + ' vaccine is used - ' + covid_vaccination['vaccines']
44cfc392f31a177ca6a24903b4e686d9a2dd0685
erindubuc/CS50
/pset6/bleep/bleep.py
1,551
3.984375
4
# Program that censors messages that contain words appearing on a list of supplied "banned words" from cs50 import get_string from sys import argv def main(): # Get the text file containing banned words if len(argv) != 2: print("Usage: python bleep.py dictonary(text)") exit(1) # Open text file of banned words # buffer = 1 to buffer 1 line at a time infile = argv[1] file_open = open(infile, "r", 1) # Store list of banned words in set structure banned_words = set(line.strip() for line in open(infile)) print(f"infile {infile} and this is the set {banned_words}") # Prompt user to provide a message message = get_string("What message would you like to censor? ") tokens = set(message.split(' ')) print(f"{tokens}") # Check to see if message words match any words from banned set banned = banned_words.intersection(tokens) # print(banned) for elem in banned: for i in elem: print('*', end="") print(' '.join(banned)) new_banned = ' '.join(banned) for i in new_banned: print('*', end="") for i in new_banned: print(message.replace(new_banned, '*')) # if str(banned in message: # for c in banned: # print("*", end="") # new_message = message.replace(for c in banned, "*") # for c in banned: # print(c.replace(c, '*') print(message.replace(str(banned), '*')) if __name__ == "__main__": main()
5fe78ebf8fcaa2ad062489f14e575b0c125c7500
jied314/IQs
/1-Python/Medium/missing_number.py
1,599
3.625
4
# 10/1 - Array, Math, Bit Manipulation (M) # Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, # find the one that is missing from the array. # For example, Given nums = [0, 1, 3] return 2. # Note: Your algorithm should run in linear runtime complexity. # Could you implement it using only constant extra space complexity? class MissingNumber(object): # Test on LeetCode - 60ms def missing_number(self, nums): """ :type nums: List[int] :rtype: int """ length = len(nums) standard_sum, true_sum = 0, 0 for i in range(0, length): standard_sum += i true_sum += nums[i] dif = true_sum - standard_sum return length - dif def missing_number_avoid_overflow(self, nums): """ :type nums: List[int] :rtype: int """ length = len(nums) true_sum = 0 for i in range(0, length): true_sum += nums[i] return ((length * (length + 1)) - 2 * true_sum) / 2 # Idea: cancel out the same number # Test on LeetCode - 64ms def missing_number_bit_manipulation(self, nums): length = len(nums) result = length for i in range(0, length): result ^= nums[i] result ^= i return result def main(): test = MissingNumber() print test.missing_number([0, 1, 3]) print test.missing_number([0]) print test.missing_number_avoid_overflow([0, 1, 3]) print test.missing_number_avoid_overflow([0]) if __name__ == '__main__': main()
e55d915996a607ed4db3c0c4abd1c7517975695b
jinxin0924/Algorithms-Design-and-Analysis
/Huffman's Algorithm.py
681
3.671875
4
__author__ = 'Xing' #greedy #not understand,unfamiliar with tree! from heapq import heapify, heappush, heappop from itertools import count def huffman(seq, frq): num = count() trees = list(zip(frq, num, seq)) # num ensures valid ordering heapify(trees) # A min-heap based on frq while len(trees) > 1: # Until all are combined fa, _, a = heappop(trees) # Get the two smallest trees fb, _, b = heappop(trees) n = next(num) heappush(trees, (fa+fb, n, [a, b])) # Combine and re-add them return trees[0][-1] seq = "abcdefghi" frq = [4, 5, 6, 9, 11, 12, 15, 16, 20] print(huffman(seq, frq))
3789bcd829d0a7b60782fd80ddff6ef5f1188288
pyxll/pyxll-examples
/highcharts/highcharts_xl.py
3,561
3.59375
4
""" Functions for display charts in Excel using Highcharts. Please be aware that the Highcharts project itself, as well as Highmaps and Highstock, are only free for non-commercial use under the Creative Commons Attribution-NonCommercial license. Commercial use requires the purchase of a separate license. Pop over to Highcharts for more information. This code accompanies the blog post https://www.pyxll.com/blog/interactive-charts-in-excel-with-highcharts """ from pyxll import xl_func, xl_app, xlfCaller from highcharts.highstock.highstock_helper import jsonp_loader from bs4 import BeautifulSoup import tempfile import timer import re import os def hc_plot(chart, control_name, theme=None): """ This function is used by the other plotting functions to render the chart as html and display it in Excel. """ # add the theme if there is one if theme: chart.add_JSsource(["https://code.highcharts.com/themes/%s.js" % theme]) # get the calling sheet caller = xlfCaller() sheet_name = caller.sheet_name # split into workbook and sheet name match = re.match("^\[(.+?)\](.*)$", sheet_name.strip("'\"")) if not match: raise Exception("Unexpected sheet name '%s'" % sheet_name) workbook, sheet = match.groups() # get the Worksheet object xl = xl_app() workbook = xl.Workbooks(workbook) sheet = workbook.Sheets(sheet) # find the existing webbrowser control, or create a new one try: control = sheet.OLEObjects(control_name[:31]) browser = control.Object except: control = sheet.OLEObjects().Add(ClassType="Shell.Explorer.2", Left=147, Top=60.75, Width=400, Height=400) control.Name = control_name[:31] browser = control.Object # set the chart aspect ratio to match the browser if control.Width > control.Height: chart.set_options("chart", { "height": "%d%%" % (100. * control.Height / control.Width) }) else: chart.set_options("chart", { "width": "%d%%" % (100. * control.Width / control.Height) }) # get the html and add the 'X-UA-Compatible' meta-tag soup = BeautifulSoup(chart.htmlcontent) metatag = soup.new_tag("meta") metatag.attrs["http-equiv"] = "X-UA-Compatible" metatag.attrs['content'] = "IE=edge" soup.head.insert(0, metatag) # write out the html for the browser to render fh = tempfile.NamedTemporaryFile("wt", suffix=".html", delete=False) filename = fh.name # clean up the file after 10 seconds to give the browser time to load def on_timer(timer_id, time): timer.kill_timer(timer_id) os.unlink(filename) timer.set_timer(10000, on_timer) fh.write(soup.prettify()) fh.close() # navigate to the temporary file browser.Navigate("file://%s" % filename) return "[%s]" % control_name @xl_func("string: object") def hc_load_sample_data(name): """Loads Highcharts sample data from https://www.highcharts.com/samples/data/jsonp.php.""" url = "https://www.highcharts.com/samples/data/jsonp.php?filename=%s.json&callback=?" % name return jsonp_loader(url) @xl_func("object: var", auto_resize=True, category="Highcharts") def hc_explode(data): """Explode a data object into an array. Caution: This may result in returning a lot of data to Excel. """ return data
fcffc6f94abb8ab7a54ce0473fae0ed67e74d4a7
UtsavRaychaudhuri/Learn-Python3-the-Hard-Way
/ex18.py
481
4.25
4
# unpacking args Notice how he unpacks args nice way of doing it def print_two(*args): arg1,arg2= args print(f"args1:{arg1},args:{arg2}") # This takes two arguments def print_two_again(arg1,arg2): print(f"arg1: {arg1},arg2: {arg2}") # This takes one argument def print_one(arg1): print(f"arg1:{arg1}") # This takes no argument def print_none(): print("I got nothin'.") print_two("Zed","Shaw") print_two_again("Zed","Shaw") print_one("First!") print_none()
8c009579fda6e1f6a93cbf3e07d06ec1861a56d7
DingChiLin/Practice
/test2.py
208
4.0625
4
from itertools import combinations dict1 = { "3": {"1":1, "2":3,"3":2}, "1": {"1":1, "2":3,"3":2}, "2": {"1":1, "2":3,"3":2}, "4": {"1":1, "2":3,"3":2} } res = combinations(dict1, 2) print(list(res))
6b8a232995f939426d8b04918fa9865598df1a3a
Ziqi-Li/Cracking-the-code-for-interview
/Ch2. Linked List/2.4.py
1,388
3.84375
4
''' Ziqi Li 2.4 You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in reverse order, such that the 1's digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list. EXAMPLE Input: (3 -> 1 -> 5), (5 -> 9 -> 2) Output: 8 -> 0 -> 8 ''' class node(object): def __init__(self, data,next): self.data = data self.next = next def printList(list): while list: print list.data list = list.next def addTwo(a,b): c = node(None,None) list = c temp = 0 while a or b: if not a: varA = 0 varB = b.data if not b: varB = 0 varA = a.data if a and b: varA = a.data varB = b.data sum = varA + varB + temp if sum >= 10: temp = 1 c.next = node(sum - 10 ,None) c = c.next else: temp = 0 c.next = node(sum,None) c = c.next if a: a = a.next if b: b = b.next if temp == 1: c.next = node(1,None) return list.next def main(): numA = node(9,node(9,node(9,node(9,None)))) numB = node(1,None) printList(addTwo(numA,numB)) if __name__ == "__main__": main()
becd182312bd65808704f3b11366c525e84f2d28
BabakAbdzadeh/Python-Class-Spring2019
/ClassWorks/Class , Q by teacher.py
710
3.796875
4
def quiz(input_string): i = 0 output_string = "" while i != len(input_string): ascii_input = ord(input_string[i]) if int(ascii_input) != 32 or int(ascii_input) != 121 or int(ascii_input) != 122: ascii_1char_out_put = int(ascii_input) + 2 if ascii_input == 121: ascii_1char_out_put += 1 if ascii_input == 122: ascii_1char_out_put = 97 if ascii_input == 32: ascii_1char_out_put == ascii_input char_out_put = chr(ascii_1char_out_put) output_string = output_string + char_out_put # string_output_list = list(string_output) i += 1 return output_string print(quiz("abcz"))
5f2a5396cbfe0a40a7aa9f739d4cad978df7c6a3
MastersAcademy/Programming-Basics
/homeworks/olexandr.datsenko_sashok15/homework-1/homework-1.py
395
4.03125
4
name = input("What is your name? ") age = int(input("How old are you? ")) city = input("Where do you live? ") university = input("Where do you study? ") say_for_self = ("My name is %s, my age is %i, " "i live in %s and i study in %s" % (name, age, city, university)) print(say_for_self) f = open('homework.txt', 'r') f = open('homework.txt', 'w') f.write(say_for_self) f.close()
1616db8108e7a4d0a1099ceb88d9f835bfbc0362
nurnisi/algorithms-and-data-structures
/leetcode/contests/biweekly-contest-3/4-1102. Path With Maximum Minimum Value.py
1,755
3.53125
4
# 1102. Path With Maximum Minimum Value class Solution: def maximumMinimumPath2(self, A) -> int: s = set() for i in range(len(A)): for j in range(len(A[0])): s.add(A[i][j]) arr = sorted(s) chset = set() for x in arr: chset.add(x) AC = [[0] * len(A[0]) for _ in range(len(A))] self.flag = False if not self.dfs(A, AC, chset, 0, 0, len(A), len(A[0])): return x return -1 def dfs2(self, A, AC, chset, i, j, r, c): if i < 0 or i >= r or j < 0 or j >= c or A[i][j] in chset or AC[i][j] == 1: return False if (i == r - 1 and j == c - 1) or self.flag: return True AC[i][j] = 1 for ii, jj in [(0, 1), (1, 0), (0, -1), (-1, 0)]: self.flag |= self.dfs(A, AC, chset, i+ii, j+jj, r, c) return self.flag def maximumMinimumPath(self, A) -> int: arr = [[-1] * len(A[0]) for _ in range(len(A))] def dfs(i, j, mn): if 0 <= i < len(A) and 0 <= j < len(A[0]) : if arr[i][j] == -1: arr[i][j] = max(mn, A[i][j]) else: arr[i][j] = min(mn, arr[i][j]) mn = arr[i][j] for ii, jj in [(0, 1), (1, 0), (0, -1), (-1, 0)]: dfs(i+ii, j+jj, mn) dfs(0, 0, 0) return arr[-1][-1] print(Solution().maximumMinimumPath([[1,1,0,3,1,1],[0,1,0,1,1,0],[3,3,1,3,1,1],[0,3,2,2,0,0],[1,0,1,2,3,0]])) print(Solution().maximumMinimumPath([[2,2,1,2,2,2],[1,2,2,2,1,2]])) print(Solution().maximumMinimumPath([[3,4,6,3,4],[0,2,1,1,7],[8,8,3,2,7],[3,2,4,9,8],[4,1,2,0,0],[4,6,5,4,3]]))
2493c3f034c8c584cfae2a8158df388599321ac8
kulalrajani/placement-training
/day2/p11.py
288
3.890625
4
# n = int(input("Enter number of pair of shoes : ")) # p = int(input("Enter maximum pair of shoes that purchaser can buy")) total_and_max = input().split(" ") n = int(total_and_max[0]) p = int(total_and_max[1]) array = [] for i in range(n): array.append(int(input())) print(array)
6e7ae6043fd1279f093847e54353911be00546e9
smn98/Python-notepad
/pytext.py
9,694
3.703125
4
from tkinter import * import tkinter.scrolledtext as Text1 #Text1 is an alias from tkinter.filedialog import * from tkinter.messagebox import * class notepad: def __init__(self): #CONSTRUCTOR FUNCTION self.root=Tk() #Creates a window root of the class Tk() self.root.title("pytext") #sets the title of the window self.root.geometry("400x400") #sets the default size of the window self.fontstyle="normal" self.font="Courier New" self.fontsize=12 self.text=Text1.ScrolledText(self.root,relief="sunken",bd=2,width=400,height=400) #Creates a text space which can be scrolled self.text.pack() # packs the text space in root self.firstsave=0 # variable to store save status of a file self.fontvar = StringVar() # font variable for radiobutton. self.fontvar.set(self.font) # sets self.fontvar to self.font self.style = StringVar() # font style variable for radiobutton self.style.set(self.fontstyle) self.text.config(font=(self.font, self.fontsize, self.fontstyle,)) # Set the font, font size and font style # MENU BAR menu = Menu(self.root) #creates a menubar named 'menu' under root self.root.config(menu=menu) #adds the menu bar to our program filemenu = Menu(menu,tearoff=0) #creates a menu in the menu bar menu.add_cascade(label="File", menu=filemenu) #adds the option file to the menu bar filemenu.add_command(label="New...", command=self.newFile, accelerator="Ctrl+N") filemenu.add_command(label="Open...", command=self.openFile,accelerator="Ctrl+O") filemenu.add_command(label="Save", command=self.saveFile,accelerator="Ctrl+S") filemenu.add_command(label="SaveAs..", command=self.saveAs,accelerator="Ctrl+Shift+S") filemenu.add_separator() #adds a separator in the submenu list filemenu.add_command(label="Exit", command=self.Exit,accelerator="Alt+F4") editmenu = Menu(menu,tearoff=0) menu.add_cascade(label="Edit", menu=editmenu) editmenu.add_command(label="Cut", command=self.Cut,accelerator="Ctrl+X") editmenu.add_command(label="Copy", command=self.Copy,accelerator="Ctrl+C") editmenu.add_command(label="Paste", command=self.Paste,accelerator="Ctrl+V") formatmenu = Menu(menu,tearoff=0) menu.add_cascade(label="Format", menu=formatmenu) formatmenu.add_command(label="Font", command=self.Font) formatmenu.add_command(label="Font Size", command=self.Fontsize) formatmenu.add_command(label="Font Style", command=self.Fontstyle) aboutmenu = Menu(menu,tearoff=0) menu.add_cascade(label="About", menu=aboutmenu) aboutmenu.add_command(label="Info.", command=self.info) #keyboard shortcuts self.root.bind("<Control-N>",self.newFile) self.root.bind("<Control-O>",self.openFile) self.root.bind("<Control-o>",self.openFile) self.root.bind("<Control-S>",self.saveFile) self.root.bind("<Control-s>", self.saveFile) self.root.bind("<Control-Shift-S>",self.saveAs) self.root.bind("<Control-X>",self.Cut) self.root.bind("<Control-C>",self.Copy) self.root.bind("<Control-V>",self.Paste) self.root.bind("<Alt-F4>",self.Exit) self.root.mainloop() # keeps the window on screen #filemenu functions def newFile(self,event=NONE): if self.firstsave==0: self.newsave() else: self.filename = "Untitled" self.text.delete(0.0, END) self.firstsave=0 def openFile(self,event=NONE): try: f=askopenfile(mode='r', filetypes=[("text file", "*.txt")]) self.filename=f.name t=f.read() self.text.delete(0.0,END) self.text.insert(0.0,t) self.firstsave=1 except: pass def saveFile(self,event=NONE): if self.firstsave==0: f = asksaveasfile(title="Save",defaultextension=".txt", filetypes=[("text file", "*.txt")]) t = self.text.get(0.0, END) try: f.write(t.rstrip()) self.firstsave = 1 except: pass else: t = self.text.get(0.0, END) f = open(self.filename, 'w') f.write(t) f.close() self.firstsave = 1 def saveAs(self,event=NONE): f = asksaveasfile(title="SaveAs",defaultextension=".txt", filetypes=[("text file", "*.txt")]) t = self.text.get(0.0, END) try: f.write(t.rstrip()) self.firstsave = 1 except: pass def newsave(self): f = asksaveasfile(title="Save current file!",defaultextension=".txt", filetypes=[("text file", "*.txt")]) t = self.text.get(0.0, END) try: f.write(t.rstrip()) self.firstsave = 1 self.newFile() except: pass def Exit(self,event=NONE): if self.firstsave==0 and self.text.get(0.0,END)!="\n": userinput=askquestion("File not saved.","Do you want to save this file?") if userinput=='yes': self.saveAs() self.root.quit() #editmenu functions def Copy(self,event=NONE): self.root.clipboard_clear() self.text.clipboard_append(string=self.text.selection_get()) def Cut(self,event=NONE): self.root.clipboard_clear() self.text.clipboard_append(string=self.text.selection_get()) self.text.delete(index1=SEL_FIRST,index2=SEL_LAST) def Paste(self,event=NONE): self.text.insert(INSERT,self.root.clipboard_get()) #format menu functions #font style-------------------------------------------------------------------- def Fontstyle(self): self.top = Toplevel() self.top.title("Font Style") label = Label(self.top, text="Please select a font style...", width=30) label.pack() styles = ( "normal", "bold", "italic") for style in styles: Radiobutton(self.top, text=style, value=style, variable=self.style).pack(anchor=W) frame = Frame(self.top) frame.pack() applyButton = Button(frame, text="Apply", command=self.applyfontstyle) applyButton.pack(side=LEFT) acceptButton = Button(frame, text="Accept", command=self.applyfontstyle_exit) acceptButton.pack(side=RIGHT) def applyfontstyle(self): self.fontstyle = self.style.get() self.text.config(font=(self.font, self.fontsize, self.fontstyle)) def applyfontstyle_exit(self): self.fontstyle = self.style.get() self.text.config(font=(self.font, self.fontsize, self.fontstyle)) self.top.destroy() # change font def Font(self): self.top = Toplevel() self.top.title("Font") label = Label(self.top, text="Please select a font...", width=30) label.pack() fonts = ( "Arial", "Courier New", "Verdana", "Times New Roman", "Comic Sans MS", "Fixedsys", "MS Sans Serif", "MS Serif", "Symbol", "System") for font in fonts: Radiobutton(self.top, text=font, variable=self.fontvar, value=font).pack(anchor=W) frame = Frame(self.top) frame.pack() applyButton = Button(frame, text="Apply", command=self.applyfont) applyButton.pack(side=LEFT) acceptButton = Button(frame, text="Accept", command=self.applyfont_exit) acceptButton.pack(side=RIGHT) def applyfont(self): self.font = self.fontvar.get() self.text.config(font=(self.font, self.fontsize, self.fontstyle)) def applyfont_exit(self): self.font = self.fontvar.get() self.text.config(font=(self.font, self.fontsize, self.fontstyle)) self.top.destroy() #font size def Fontsize(self): self.top = Toplevel() self.top.title("Font Size") label = Label(self.top, text="Please select a font size...", width=30) label.pack() self.scale = Scale(self.top, from_=8, to=72, orient=HORIZONTAL) self.scale.pack() self.scale.set(self.fontsize) frame = Frame(self.top) frame.pack() applyButton = Button(frame, text="Apply", command=self.applyfontsize) applyButton.pack(side=LEFT) acceptButton = Button(frame, text="Accept", command=self.applyfontsize_exit) acceptButton.pack(side=RIGHT) def applyfontsize(self): self.fontsize = self.scale.get() self.text.config(font=(self.font, self.fontsize, self.fontstyle)) def applyfontsize_exit(self): self.fontsize = self.scale.get() self.text.config(font=(self.font, self.fontsize, self.fontstyle)) self.top.destroy() #About menu---------------------------------------------------------------------------------- def info(self): showinfo("Information","This a text editor made using python :)") noteobj=notepad()
4e66d93532b8399b66a5d5e2bdd9571b18acab78
mdjibran/Algorithms
/HashTables/PalindromePermutation.py
566
3.59375
4
''' Palindrom string ''' from collections import defaultdict def SetDict(s: str): dict = defaultdict(str) for c in s: if c not in dict: dict[c] = 1 else: dict[c] = dict[c] + 1 return dict def CheckPalindrom(str1: str, str2: str): if len(str1) != len(str2): return False d1 = SetDict(str1) d2 = SetDict(str2) for k, v in d1.items(): if k not in d2 or d2[k] != v: return False return True print(CheckPalindrom("edified", "deified"))
c5343c882d57e0b5749c2d0a3f5c023e3a13ae2a
cozymichelle/algorithm_in_python
/jump_search.py
1,158
3.875
4
''' Jump Search Input: - arr: a given sorted array - x: an element to find - m: number of elements to jump ahead Output: index of the element x The optimal block size is m = sqrt(n). worst case scenario: (n / m) jumps + (m - 1) comparisons ''' def lin_search(arr, x, l, r): # do linear search on arr from index l to r # and find x for i in range(l, r + 1): if arr[i] == x: return i # if x not found return -1 def jump_search(arr, x, m): n = len(arr) # size of the array arr # if block size is greater than the size of arr if m > n: return -1 # if x is smaller than the min of arr # or x is greater than the max of arr if x < arr[0] or x > arr[n - 1]: return -1 jump = 0 # index to where we jump forward while arr[jump] <= x: if arr[jump] == x: # found x return jump prev = jump # index before jump jump += m jump = min(jump, n-1) # do linear search return lin_search(arr, x, prev + 1, jump - 1) arr = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610] print(jump_search(arr, 56, 4))
09f6e8a8deaa659a7a3f276e32f812e043e04f3c
lrlab-nlp100/nlp100
/moajo/chapter1/p02.py
254
3.828125
4
#!/usr/bin/env python def zip_str(s1, s2): if len(s1) == 0: return s2 if len(s2) == 0: return s1 return s1[0] + s2[0] + zip_str(s1[1:], s2[1:]) if __name__ == "__main__": print(zip_str("パトカー", "タクシー"))
c61d82b12c31ce6b65ee85cc365d1361a898b29c
kobyyoshida/pynative-solutions
/Lists/exercise2.py
366
3.90625
4
#Exercise 2: Concatenate two lists index-wise list1 = ["M", "na", "i", "Ke"] list2 = ["y", "me", "s", "lly"] solution = [] for i in range(0,len(list1)): newWord = list1[i] + list2[i] solution.append(newWord) print(solution) #list1 = ["M", "na", "i", "Ke"] #list2 = ["y", "me", "s", "lly"] #list3 = [i + j for i, j in zip(list1, list2)] #print(list3)
10491dd55bdf7abb2428ae6474037949c358137d
NataliaDiaz/BrainGym
/arrange-tiles.py
1,086
4.09375
4
""" How many different ways are there of covering a Nx3 grid having available infinite tiles of size 2x1 and 1x2 in a way that each tile in the grid is covered only once, and each part of the tile is covering one grid space. Return the result, as it will be a large number, modulo (10**9)+7. Example: Input: 10 Output: 571 """ def get_n_different_ways_arranging_2x1_1x2_tiles_in_Nx3_grid(N): #N = int(raw_input()) modulo = (10**9)+7 """ N ways in a: 0x3 grid: 0 1x3 grid: 0 2x3 grid: 3 3x3 grid: 0 4x3 grid: 9 5x3 grid: 0 6x3 grid: ... """ if N%3 ==0 or N==0 or N ==1: possible_ways = 0 else: if N%2 == 0: possible_ways = 3**(N) else: possible_ways = 0 #3**(N-1) result = possible_ways % modulo # print "Possible ways and modulo: ", possible_ways, result print result rturn result get_n_different_ways_arranging_2x1_1x2_tiles_in_Nx3_grid(0) get_n_different_ways_arranging_2x1_1x2_tiles_in_Nx3_grid(1) get_n_different_ways_arranging_2x1_1x2_tiles_in_Nx3_grid(6) get_n_different_ways_arranging_2x1_1x2_tiles_in_Nx3_grid(10)
4c54971f33c1902114e4a60486e872beaecd2419
chris-peng-1244/py4e
/11-Re.py
145
3.546875
4
import re filename = input("Enter file name:") h = open(filename) nums = [ int(num) for num in re.findall(r'\d+', h.read()) ] print(sum(nums))
99df53c3fda223a8189ccf8aef71c2854a8e90ee
anshul217/sortdict
/sortdict/__init__.py
561
3.828125
4
from operator import itemgetter def dict_sort(list_dict, sort_keys=None): """Get sorted list of dictonaries Keyword arguments: list_dict -- list of dictionary to be sorted eg:- [{'name':'alex', 'age':10}, {'name':'mike', 'age':20}] sort_keys -- list of key on to which sorting needs to be done. eg:- ['age'] @author : Anshul Gupta (anshulgupta217@gmail.com) """ if sort_keys is not None: return sorted(list_dict, key=itemgetter(*sort_keys)) else: print("Please provide sort_keys list to sort given dictionary") return None
3a64501fc828f6c8edc489edf3afb827a06f82b5
kis619/SoftUni_Python_Basics
/3.Conditional_statements_advanced/LAB/10. Invalid Number.py
161
4.03125
4
number = int(input()) if not(100 <= number <= 200 or number == 0): print("invalid") # a = 100 <= number <= 200 or number == 0 # if not a: # print("invalid")
1c43ce8aa4d191ab74d453e74e254638e0ad8398
Madhav2108/Python-
/if/el5.py
160
4
4
a=int(input("enter age")) if a>18: print("Greater than 18") else: print("Less 18")
f137062ac62d4e9b3199dfb7ff138b64108fbef9
konstantinagalani/ABLR_network
/BO_dataset/maximizer.py
1,447
3.78125
4
import numpy as np class RandomSampling(): def __init__(self, objective_function, lower, upper, init_d,n_samples=100, rng=None): """ Samples candidates uniformly at random and returns the point with the highest objective value. Parameters ---------- objective_function: acquisition function The acquisition function which will be maximized lower: np.ndarray (D) Lower bounds of the input space upper: np.ndarray (D) Upper bounds of the input space init_d : initial design object Object used to sample points from the dataset n_samples: int Number of candidates that are samples """ self.n_samples = n_samples self.init_d = init_d self.lower = lower self.upper = upper self.objective_func = objective_function self.rng = rng def maximize(self): """ Maximizes the given acquisition function. Returns ------- np.ndarray(N,D) Point with highest acquisition value. """ # Sample random points uniformly over the whole space X = self.init_d.initial_design_random(self.lower, self.upper,self.n_samples, self.rng) y = np.array([self.objective_func(X[i].reshape((1,X[i].shape[0]))) for i in range(self.n_samples)]) x_star = X[y.argmax()] return x_star
4352e8f6d6e026bb63a7a9b0beb9ec6402419dce
htmlprogrammist/kege-2021
/tasks_12/task_12_10290.py
236
3.671875
4
s = '1' + '8' * 80 while '18' in s or '288' in s or '3888' in s: if '18' in s: s = s.replace('18', '2', 1) elif '288' in s: s = s.replace('288', '3', 1) else: s = s.replace('3888', '1', 1) print(s)
fa2a5453391a2e5227411c3d986289b114c324b4
lihongwen1/XB1929_-
/ch09/except_tpye.py
226
3.578125
4
def check(a,b): try: return a/b except ZeroDivisionError: #除數為0的處理程序 print('除數不可為0') a=int(input('請輸入被除數:')) b=int(input('請輸入除數:')) print(check(a,b))