blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
f2659fedef1da65c985f5a9b19e66fc418c068ba
joseraz/Data-Structure-and-Algorithms
/14 Code - Hard Problems/Greedy algorithm.py
691
3.796875
4
# -*- coding: utf-8 -*- """ Created on Sat Oct 5 15:42:19 2019 @author: jose """ class Item(object): def __init__(self, n, v, w): self.name = n self.value = v self.weight = w def getName(self): return self.name def getValue(self): return self.value def getWeight(self): return self.weight def __str__(self): result = '<' + self.name + ', ' + str(self.value)\ + ', ' + str(self.weight) + '>' return result def value(item): return item.getValue() def weightInverse(item): return 1.0/item.getWeight() def density(item): return item.getValue()/item.getWeight()
d41459487f33aa9a9708ce1f756f0c2ca95b38f5
Tektalk4kidsOfficial/Code-On-cards
/main.py
934
3.96875
4
import random import sys responses = ["Move forward 2 ", "Move Forward 1", "Move back 1", "Move backward 2", "U-turn", "Turn Right", "Turn Left", "Down and right", "Any direction","Down and left"] answer = random.choice(responses) print(answer) answer = random.choice(responses) print(answer) answer = random.choice(responses) print(answer) while True: question = input("Do You want to generate a random 3 again?") if question == "yes": responses = ["Move forward 2 ", "Move Forward 1", "Move back 1", "Move backward 2", "U-turn", "Turn Right", "Turn Left", "Down and right", "Any direction", "Down and left"] answer = random.choice(responses) print(answer) answer = random.choice(responses) print(answer) answer = random.choice(responses) print(answer) else: print("Thanks For Using Me") sys.exit()
4d72004164993e0d14d72b7c2a65d56eb775721f
ContextLab/hypertools
/examples/analyze.py
887
3.96875
4
# -*- coding: utf-8 -*- """ ============================= Analyze data and then plot ============================= This example demonstrates how to use the `analyze` function to process data prior to plotting. The data is a list of numpy arrays representing multi-voxel activity patterns (columns) over time (rows). First, analyze function normalizes the columns of each matrix (within each matrix). Then the data is reduced using PCA (10 dims) and finally it is aligned with hyperalignment. We can then plot the data with hyp.plot, which further reduces it so that it can be visualized. """ # Code source: Andrew Heusser # License: MIT # load hypertools import hypertools as hyp # load the data geo = hyp.load('weights') data = geo.get_data() # process the data data = hyp.analyze(data, normalize='within', reduce='PCA', ndims=10, align='hyper') # plot it hyp.plot(data)
c0da1633ffdb0f88ac05ec2c85ad580364578919
Fennay/python-study
/study/sorted.py
570
3.515625
4
#!/usr/bin/env python3 # _*_ coding:utf-8 _*_ from collections import Iterable L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)] M = [] def by_name(t): return t[1] ss = sorted(L, key=by_name, reverse=True) print(ss) def calc_sum(*args): ax = 0 for n in args: ax = ax + n return ax sum = calc_sum(1, 2, 3, 4, 55) print(sum) def lazy_sum(*args): def sum(): ax = 0 for n in args: ax = ax + n return ax return sum sum2 = lazy_sum(1, 2, 3, 4, 5, 6, 7) sum3 = sum2() print(sum2())
08f77a244a5b0d6bbac0365db5c73a0948d92291
wang264/JiuZhangLintcode
/AlgorithmAdvance/L7/require/405_submatrix-sum.py
1,790
3.90625
4
# 405. Submatrix Sum # 中文English # Given an integer matrix, find a submatrix where the sum of numbers is zero. Your code should return the # coordinate of the left-up and right-down number. # # If there are multiple answers, you can return any of them. # # Example # Example 1: # # Input: # [ # [1, 5, 7], # [3, 7, -8], # [4, -8 ,9] # ] # Output: [[1, 1], [2, 2]] # Example 2: # # Input: # [ # [0, 1], # [1, 0] # ] # Output: [[0, 0], [0, 0]] # Challenge # O(n3) time. class Solution: """ @param: matrix: an integer matrix @return: the coordinate of the left-up and right-down number """ def submatrixSum(self, matrix): # write your code here num_rows = len(matrix) num_cols = len(matrix[0]) prefix_sum = [[0] * (num_cols + 1) for _ in range(num_rows + 1)] # prefix_sum[0][0] = matrix[0][0] for i in range(1, num_rows + 1): for j in range(1, num_cols + 1): prefix_sum[i][j] = prefix_sum[i - 1][j] + prefix_sum[i][j - 1] - prefix_sum[i - 1][j - 1] + \ matrix[i - 1][j - 1] # iterate all upper-left point (x1,y1) and lower right point(x2,y2) for x1 in range(1, num_rows+1): for y1 in range(1, num_cols+1): for x2 in range(x1, num_rows+1): for y2 in range(y1, num_cols+1): if prefix_sum[x2][y2] - prefix_sum[x1-1][y2] - prefix_sum[x2][y1-1]+prefix_sum[x1-1][y1-1]==0: rslt = [] rslt.append([x1 - 1, y1 - 1]) rslt.append([x2 - 1, y2 - 1]) return rslt sol= Solution() matrix = [ [1, 5, 7], [3, 7, -8], [4, -8 ,9] ] sol.submatrixSum(matrix)
c47df2c714af2d65a5ae7db63bb3f0f7cedf76ea
mritter-xcc/big-questions
/04-Add-database/scripts/createDB.py
421
3.78125
4
import sqlite3 # db name variable DB = 'meaning-life.db' # connect to db - create if not exist con = sqlite3.connect(DB) # create cursor to interact with db cur = con.cursor() # create db table cur.execute(""" CREATE TABLE comments (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, title TEXT, comment TEXT ) """) # execute the query con.commit() # close db connection con.close()
2be4430c0383f036462d8fa0e6d4515f835a3f41
ShellySrivastava/Machine-Learning
/ML_CW1/assgn_1_part_2/1_logistic_regression/gradient_descent.py
2,170
4.21875
4
from calculate_hypothesis import * from compute_cost import * from plot_cost import * def gradient_descent(X, y, theta, alpha, iterations): """ :param X : 2D array of our dataset :param y : 1D array of the groundtruth labels of the dataset :param theta : 1D array of the trainable parameters :param alpha : scalar, learning rate :param iterations : scalar, number of gradient descent iterations """ m = X.shape[0] # the number of training samples is the number of rows of array X cost_vector = np.array([], dtype=np.float32) # empty array to store the cost for every iteration # Gradient Descent for it in range(iterations): # initialize temporary theta, as a copy of the existing theta array theta_temp = theta.copy() sigma = np.zeros((len(theta))) for i in range(m): ######################################### # Write your code here # Calculate the hypothesis for the i-th sample of X, with a call to the "calculate_hypothesis" function hypothesis = calculate_hypothesis(X, theta, i) ########################################/ output = y[i] ######################################### # Write your code here # Adapt the code, to compute the values of sigma for all the elements of theta sigma = sigma + (hypothesis - output) * X[i] ########################################/ # update theta_temp ######################################### # Write your code here # Update theta_temp, using the values of sigma theta_temp = theta_temp - (alpha / m) * sigma ########################################/ # copy theta_temp to theta theta = theta_temp.copy() # append current iteration's cost to cost_vector iteration_cost = compute_cost(X, y, theta) cost_vector = np.append(cost_vector, iteration_cost) print('Gradient descent finished.') return theta, cost_vector
752a7284ae570c9f74cbb8f7c34280325747ac5e
NJ-zero/LeetCode_Answer
/list/missingnumber.py
743
3.65625
4
# coding=utf-8 # Time: 2019-09-30-09:50 # Author: dongshichao ''' 给定一个包含 0, 1, 2, ..., n 中 n 个数的序列,找出 0 .. n 中没有出现在序列中的那个数。 示例 1: 输入: [3,0,1] 输出: 2 示例 2: 输入: [9,6,4,2,3,5,7,0,1] 输出: 8 解题思路: 从数学的角度,0-n,确定会缺失一个数字 将数组求和,和0-n求和,差额就是少的数字 ''' class Solution(object): def missingNumber(self, nums): """ :type nums: List[int] :rtype: int """ s1=0 for i in nums: s1 += i s2 = (len(nums)+1)*len(nums)//2 return s2-s1 if __name__=="__main__": s= Solution() print(s.missingNumber([1,3,5,0,2]))
d8dba460d2cc183c103b2ffe8c96ae5ca813e0e9
ielecer/Python-3
/passwordDetection.py
275
3.734375
4
#Password Detection (The world's simplest) #Written by Anupam #For the book: Automating The Internet with Python password = input("Enter your password: ") if len(password) > 8: print("That is one strong password") else: print("May god have mercy on your account")
85dd832180a68a07459894cf7779368ec6115d3a
darigas/BFDjango_2018
/Week_1/CodingBat/String-2/double_char.py
119
3.71875
4
def double_char(str): result = "" for item in range(len(str)): result += str[item] + str[item] return result
bfb1a80d78b28b2adedaf8780dfc1dea71bd78ed
er-vikramsnehi/python_programming
/python-programming-workshop/set/create_modify_search_del_dictionary.py
448
3.9375
4
mydictionary = { } mydictionary["salary"] = 1000000 mydictionary["age"] = 45 print(mydictionary) dictone = {"name":"Aprameya","salary":1000000} print(dictone) newdict = dict([("Cat",5),("Dogs",3)]) print(newdict) dictone["age"] = 16 print(dictone) dictone["age"] = 15 print(dictone) if "age" in dictone: print("age is present in the dictionary") else: print("age is not present in the dictionary") del(dictone["age"]) print(dictone)
161a48a2cb494d149dde4ba1953a3045d62230aa
fjdurlop/TallerArduinoPython2020-1
/Tkinter/Tkinter/gui6.py
865
3.796875
4
# ENTRY #Entrada de texto from tkinter import * raiz = Tk() ent = Entry(raiz) # entrada de texto boton = Button(raiz, text='Mandar') # Variables de tkinter var = StringVar() # variable de tipo string ent.config(textvariable=var) # asociamos variable con ent ''' Variables de control Las variables de control son objetos especiales que se asocian a los widgets para almacenar sus valores y facilitar su disponibilidad en otras partes del programa. Pueden ser de tipo numérico, de cadena y booleano. ''' def mandar(): print('Recibido: ', var.get()) # var.get nos regresa un string con # lo que esté escrito en la entrada de texto var.set('') boton.config(command=mandar) # EJERCICIO no hacer ''' ent.focus() ent.bind('<Return>', lambda event: mandar()) ''' ent.pack(side=LEFT, expand=YES, fill=X) boton.pack(side=RIGHT) raiz.mainloop()
6395349908c105f09811b795d6bd0d4b8389b022
lion963/SoftUni-Python-Fundamentals-
/Exercise Functions/Smallest of Three Numbers.py
265
3.734375
4
def min_num(a=int(input()), b=int(input()), c=int(input())): small=None small=min(a,b,c) print(small) min_num() # def min_num(a=int(input()), b=int(input()), c=int(input())): # small=None # small=min(a,b,c) # return small # print(min_num())
24dc477337e6e12e547cc5a94a84987f66788eda
Kontowicz/Daily-Interview-Pro
/solutions/day_96.py
300
3.75
4
import math def is_palindrome(n): num = [] while n != 0: num.append(n%10) n = n // 10 return num == num[::-1] assert is_palindrome(1234321) == True print(is_palindrome(1234321)) assert is_palindrome(1234322) == False print(is_palindrome(1234322)) print('Test pass.')
3e35852ffc793a0889f4f71311d5af294a525b7d
Educorreia932/FEUP-FPRO
/PE/PE2/exactly.py
1,370
3.609375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Nov 23 16:20:22 2018 @author: exame """ def exactly(s): counter = 0 interrogation = 0 index = 0 result = () numbers = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] numbers_list = [] for character in s: if character in numbers: numbers_list.append((character, counter)) counter += 1 for number in numbers_list: low = number[1] lower = number[0] if index + 1 > len(numbers_list) - 1: break high = numbers_list[index + 1][1] higher = numbers_list[index + 1][0] interval = s[low: high] if (int(lower) + int(higher)) == 10: for char in interval: if char == "?": interrogation += 1 if interrogation != 3: result = (lower + higher,) return "The sequence " + s + " is NOT OK with first violation with pair: " + str(result) else: result += (lower + higher,) interrogation = 0 index += 1 return "The sequence " + s + " is OK with the pairs: " + str(result) print(exactly("htrtr24?h56h56??29004??34"))
04418419fd3bf64be3c9b5908abb156d9a90d211
acnolan/Data-vis-7-ways
/imputeMPG.py
962
3.890625
4
# This python script imputes the 2 missing MPG values # We know both of them are 8 cylinder Ford cars # So we will perform the imputation by finding all of the 8 Cylinder Fords and taking their average MPG values. # Since it's only two values I am just calculating the average and then printing the output, I will manually replace the value in the csv file # Both the original and imputed csv files can be found in the Git repository import csv # Read the original CSV and gather the MPG values of 8 cylinder Fords eightCylinderFords = [] with open("./cars-sample-original.csv") as csv_file: csv_reader = csv.DictReader(csv_file, delimiter=',') for row in csv_reader: if row['Manufacturer'] == 'ford' and row['Cylinders'] == '8' and row['MPG'] != 'NA': eightCylinderFords.append(float(row['MPG'])) # Calculate and print the average MPG of 8 cylinder Fords average = sum(eightCylinderFords) / len(eightCylinderFords) print(average)
171b35341056bc5503bf816a5923788df8559e66
annamichalovova/Python
/easy_unpack/Easy unpact.py
136
3.6875
4
def easy_unpack(elements: tuple) -> tuple: return elements[0],elements[2],elements[-2] print(easy_unpack((1, 2, 3, 4, 5, 6, 7, 9)))
be5125b7a93bad21bb8a126ba67b5bf07d0d2a91
yuzhoul1991/leetcode
/785.is-graph-bipartite.python3.py
1,132
3.640625
4
class Solution: def isBipartite(self, graph): """ :type graph: List[List[int]] :rtype: bool """ # construct graph and start with black color and all neibors with it should be # red color, keep labeling, if we found a neighbor with the same color as self # it is not bipartite # Since it is a function that needs to return a boolean, iterative might be better than recursion graphs = {} n = len(graph) for idx, arr in enumerate(graph): graphs[idx] = arr # color can be used as visited too colors = {} for node in range(n): if node not in colors: stack = [node] colors[node] = 1 while stack: node = stack.pop() for nei in graphs[node]: if nei not in colors: stack.append(nei) colors[nei] = -colors[node] elif colors[nei] == colors[node]: return False return True
7bd5c81913bce05a511fe5e68ed11ca641987735
neamedina73/Ejercicios_de_Python
/5. Constructor de pandas DataFrame_lista_tabla_periodica.py
582
3.515625
4
# -*- coding: utf-8 -*- """ Created on Tue Jun 1 15:49:22 2021 @author: Alejandro AJ """ import pandas as pd elementos = { 'Número atómico':[1,6,47,88], 'Masa atómica':[1.088,12.011,107.87,226], 'Familia':['No metal','No metal','Metal','Metal'] } tabla_Periódica = pd.DataFrame(elementos) print(tabla_Periódica) # Número atómico Masa atómica Familia #0 1 1.088 No metal #1 6 12.011 No metal #2 47 107.870 Metal #3 88 226.000 Metal
12dd0e6c8302f7a09e60b886c189c278874e1bc9
abay-90/NISprogramming
/Module 3/Class Lecture & Practise programming/ReadingWithTellAndSeek.py
635
4.09375
4
# The file is opened using the readable mode my_file = open("Textfile.txt", "r") # Display all the contents of the file print(my_file.read()) print("Position {}".format(my_file())) print("Resetting postion to 50") my_file.seek(20) print("Position {}".format(my_file.tell())) print() # Display all the contents of the file again, # But starting from position 50. # This mean only a portion of the file will be read. for line in my_file: # Suppress the new line at the end of the line, # since the line of text read from the file already; # contains a newline character at the end. print(line, end="") my_file.close()
984469c33fd33b7cfe3d770163580c075506b408
zolcsika71/JBA_Python
/Rock-Paper-Scissors/Problems/Decimal places/main.py
132
3.5625
4
number = float(input()) decimal_places = int(input()) print(f'{number:.{decimal_places}f}') # print(round(number, decimal_places))
39b0a33f4eac15b14b6566438e3ba144ec33363c
1715974253/learned-codes
/23列表循环遍历.py
140
3.71875
4
list1 = ['Tom', '斯塔克', '托尼', '刘亦菲'] i = 0 while i < len(list1): print(list1[i]) i += 1 for j in list1: print(j)
7b7f71d85ea482f5d9f7fb67687634926c24a54f
novayo/LeetCode
/0366_Find_Leaves_of_Binary_Tree/try_2.py
620
3.671875
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def findLeaves(self, root: Optional[TreeNode]) -> List[List[int]]: layers = collections.defaultdict(list) def dfs(node): if not node: return 0 ret = max(dfs(node.left), dfs(node.right)) + 1 layers[ret].append(node.val) return ret dfs(root) return list(layers.values())
0ca3717f6522074ed07a00848af3fe29f7296e1e
siddharth456/Python_Scripts_1
/mysql-connector.py
501
3.875
4
# Python can be used in database applications # One of the popular databases around is mysql # Python needs a mysql driver to access the databases in mysql import mysql.connector # Creating a connection object mycon = mysql.connector.connect(host="localhost",user="root",password="compaq@123") # Creating a cursor object to be used for fetching result mycursor = mycon.cursor() # Executing a query mycursor.execute("SHOW DATABASES") # Getting query result for x in mycursor: print(x)
0038551dde549eb0fc36cd13ae448e0e796d890c
kshitiz2001/Python-Projects
/language.py
149
3.765625
4
from langdetect import detect text = input("Enter any text in any language: ") print("language of this text is : ", detect(text)) # by kshitiz
48c3ee1ebe3766367d52b2f04e4d61893d69b006
RamuSannanagari/python_practice_files
/Inheitence/Inheritence2.py
479
3.9375
4
# -*- coding: utf-8 -*- """ Created on Tue Jan 2 10:39:04 2018 @author: abhi """ class Parent: P_V=1000 def parent_m(self): print("parent_m = ",self.P_V) self.child_m() def child_m(self): print("child_m in parent = ",self.C_V) class Child(Parent): C_V=2000 def child_m(self): print("child_m = ",self.C_V) c_obj=Child() c_obj2=Child() c_obj.parent_m() c_obj2.child_m()
f63b673b5115013d2ca73ba95275c7aa9957f338
almirgon/LabP1
/Unidade-7/ajeita.py
504
3.671875
4
#coding: utf-8 #Crispiniano #Unidade 7: Ajeita Lista de Números Inteiros def ajeita_lista(dados): while True: condicao = False for i in range(len(dados)-1): if dados[i] < dados[i+1]: dados[i], dados[i+1] = dados[i+1], dados[i] condicao = True if not condicao: break for x in range(len(dados)-1,-1,-1): if dados[x] % 2 != 0: dados.append((dados.pop(x))) lista1 = [3, 2, 1, 4, 5, 6, 7, 8, 9] assert ajeita_lista(lista1) == None assert lista1 == [8, 6, 4, 2, 1, 3, 5, 7, 9]
e145898955acc74a21d2e3faf7a231ee58319bc6
Fover21/notebook
/Python笔记/Wzy01/03.py
1,920
4.1875
4
#首先安利一下:字符串是不可变的对象,所以任何操作对原字符串是不改变的。 python2默认编码为ASCII python3默认编码为uft-8 python2的 str == bytes 而python3的str是Unicode bytes为str编码后的二进制类型 1.编码 1)最早的计算机编码是ASSCII 128个码位 2**7 在此基础上加了一位 2**8 8位,1个字节(Byte) 2)Gbk 国标码 16位。 2个字节(双字节字符) 3)unicode 万国码 32位,4个字节 4)utf-8: 英文 8 位 1个字节 欧洲文字 16位 2个字节 中文 24位 3个字节 2.int方法操作 bit_length() 求二进制长度 3.str 索引:起始下标是0(从左到右),(-1)从右到左 切片:s[起始位置:结束位置:步长] 特点:顾头不顾尾 -------- 通过索引获取到的内容,还是一个字符串 字符串对象的常用方法: 注:字符串不可变 1)upper() 转换成大写 2)strip() 去掉空格 3)replace() 替换(全部) 如果有count参数是替换count(从左往右)几次。如果count超过了最大替换次数会报错 4)split() 切割 切边是会切出‘’的,如果说切字符串是挨着的会切出一个‘’ 5)format() 格式化输出 6)startswith() 判断是否以xxx开头 7)find() 查找xxx索引位置,找不到返回-1 8)len() ------内置函数,直接使用,不用点操作 求字符串长度 4.注意 1-upper(),lower() ---在程序需要判断不区分大小写的时候,用的上。 2-split() ---切完后,刀(切的东西)就没了,切完的东西是列表,列表装的是字符串 ---如果切边会出现一个空[''],如果两边都切了,会出现两个空串['',''] ---参数maxsplit代表最大切割分数 3-join ----join参数的迭代对象中元素必须是字符串,如果不是会报错。
29e731b78696a6a03589f5f36669963481f6629a
keving3ng/Coding-Challenges
/FirstRecurringCharacter.py
438
3.78125
4
'''First Recurring Character Jan 17 2018 https://www.reddit.com/r/dailyprogrammer/comments/7cnqtw/20171113_challenge_340_easy_first_recurring/ Example Input: ABCDEBC -> B IKEUNFUVFV -> U PXLJOUDJVZGQHLBHGXIW -> J *l1J?)yn%R[}9~1"=k7]9;0[$ -> 1 ''' chars = [] i = 0 cChar = str() string = input ("Input the string: ") while chars.count(cChar) == 0: chars.append(cChar) i += 1 cChar = string[i] print (cChar)
f2cb3a4beea5bc4db97e3264d505576707b704e3
EmersonBraun/python-excercices
/cursoemvideo/ex022.py
534
4.21875
4
# Crie um programa que leia o nome completo de uma pessoa e mostre: # – O nome com todas as letras maiúsculas e minúsculas; # – Quantas letras ao todo (sem considerar espaços); # – Quantas letras tem o primeiro nome. nome = str(input('Digite seu nome completo: ')).strip() print('Em maiúsculas: {}'.format(nome.upper())) print('Em minúsculas: {}'.format(nome.lower())) print('Quantidade de caracteres (sem espaços): {}'.format(len(nome) - nome.count(' '))) print('O primeiro nome tem {} caracteres'.format(nome.find(' ')))
9a73f3cb946a5299910afe3593cededa0eaeecb1
theodoro/logica-prog-com-python
/logica/06-listas/cEmv-aula-18.py
766
3.921875
4
pessoa = [['Sumara',36],['Bruno',34]] print(pessoa[0][0]) teste = list() teste.append(34) teste.append('Bruno') galera = list() galera.append(teste[:]) teste[0] = 'Sumara' teste[1] = 36 galera.append(teste[:]) print(galera) galera2 = [['João',19], ['Ana', 33], ['Joaquim', 14], ['Pietra', 1]] print(galera2) print(galera2[0]) print(galera2[0][0]) print(galera2[0][1]) for p in galera2: print(f'{p[0]} tem {p[1]} anos de idade') galera3 = list() dado = list() for c in range(0, 3): dado.append(str(input('Nome: '))) dado.append(int(input('Idade: '))) galera3.append(dado[:]) dado.clear() print(galera3) for p in galera3: if p[1] >= 21: print(f'{p[0]} é maior de idade') else: print(f'{p[0]} é menor de idade')
ad5ad8ad3dc8ff56afea93111612073ca6d1df94
L200184137/praktikumAlgopro
/8.2.py
403
3.921875
4
def konversi_suhu(): x = int(input('pilih konversi :')) if ( x == 1): f = int (input('masukkan suhu celcius :')) c = 32+9.0/5*f print(c) if (x==2): a = int (input ('masukkan suhu farenheit :')) b = (a - 32)*5.0/9 print (b) print ('konversi suhu') print ('1.celcius ke farenheit') print ('2.farenheit ke celcius') konversi_suhu()
2eb2eee16e18048b444d6f741e2600aa7ed7ed68
L111235/Python-code
/嵩天python3/字典键值反转输出.py
251
3.71875
4
#d={"a": 1, "b": 2} d=eval(input()) #输入一个字典数据,input()函数返回值实际为为一个字符串 try: d1={} for i in d: #print(i) #value=d[i] d1[d[i]]=i print(d1) except: print('输入错误')
66ace7bf809984b57b1d435093cf9bac7e298a07
scohen40/wallbreakers_projects
/Leetcode/week_4/p0039_combination_sum.py
694
3.609375
4
from typing import List class Solution: def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: self.valid = [] def backtrack(path, index, csum): if csum == target: self.valid.append(path) return for i, n in enumerate(candidates[index:], start=index): if csum + n <= target: backtrack(path + [n], i, csum + n) backtrack([], 0, 0) return self.valid """ Runtime: 52 ms, faster than 85.73% of Python3 online submissions for Combination Sum. Memory Usage: 12.8 MB, less than 100.00% of Python3 online submissions for Combination Sum. """
8fbd3820575971ce7b77f71d5adbdbabb597ac7c
ShyZhou/LeetCode-Python
/301.py
1,388
3.765625
4
# Remove Invalid Parentheses # Remove the minimum number of invalid parentheses in order to make the input string valid. Return all possible results. # Note: The input string may contain letters other than the parentheses ( and ). # Example 1: # Input: "()())()" # Output: ["()()()", "(())()"] # Example 2: # Input: "(a)())()" # Output: ["(a)()()", "(a())()"] # Example 3: # Input: ")(" # Output: [""] class Solution(object): def isValidParentheses(self, s): cnt = 0 for c in s: if c == '(': cnt += 1 elif c == ')': if cnt == 0: return False cnt -= 1 return cnt == 0 def removeInvalidParentheses(self, s): """ :type s: str :rtype: List[str] """ if not s: return [''] q, res, visited = [s], [], set([s]) found = False while q: cur = q.pop(0) if self.isValidParentheses(cur): found = True res.append(cur) elif not found: for i in range(len(cur)): if cur[i] == '(' or cur[i] == ')': t = cur[:i] + cur[i + 1:] if t not in visited: q.append(t) visited.add(t) return res
4407531d5821b2aa27ba9450fb111cf7eb27c440
akhilgoel0007/Chess_Game_Simulation
/Functions/Bishop.py
2,160
3.59375
4
from Functions.BasicFunc import * def MoveBishop(ChessPiece, NewSquare, AllPieces, Board): """ Both Bishop's Cannot Collide at one Position, Both are of Different Colors..""" for Bishop in AllPieces[ChessPiece]: X_BishopSquare = int(Bishop['CurrentSquare'][1])-1 # Integer Coordinate Y_BishopSquare = int(RowToNumber(Bishop['CurrentSquare'][0])) # Integer Coordinate # Diagonal Up Right.. for i in range(1, 8): if X_BishopSquare+i <= 7 and Y_BishopSquare+i <= 7: if NewSquare == (NumberToRow(str(Y_BishopSquare+i))+str(X_BishopSquare+i+1)): if Board[X_BishopSquare+i][Y_BishopSquare+i] is not ChessPiece[:5]: Board[X_BishopSquare][Y_BishopSquare] = 'Free' Board[X_BishopSquare+i][Y_BishopSquare+i] = ChessPiece[:5] return Bishop['CurrentSquare'] else: break # Diagonal Up Left.. for i in range(1, 8): if X_BishopSquare+i <= 7 and Y_BishopSquare-i >= 0: if NewSquare == (NumberToRow(str(Y_BishopSquare-i))+str(X_BishopSquare+i+1)): if Board[X_BishopSquare+i][Y_BishopSquare-i] is not ChessPiece[:5]: Board[X_BishopSquare][Y_BishopSquare] = 'Free' Board[X_BishopSquare+i][Y_BishopSquare-i] = ChessPiece[:5] return Bishop['CurrentSquare'] else: break # Diagonal Down Right.. for i in range(1, 8): if X_BishopSquare-i >= 0 and Y_BishopSquare+i <= 7: if NewSquare == (NumberToRow(str(Y_BishopSquare+i))+str(X_BishopSquare-i+1)): if Board[X_BishopSquare-i][Y_BishopSquare+i] is not ChessPiece[:5]: Board[X_BishopSquare][Y_BishopSquare] = 'Free' Board[X_BishopSquare-i][Y_BishopSquare+i] = ChessPiece[:5] return Bishop['CurrentSquare'] else: break # Diagonal Down Left.. for i in range(1, 8): if X_BishopSquare-i >= 0 and Y_BishopSquare-i >= 0: if NewSquare == (NumberToRow(str(Y_BishopSquare-i))+str(X_BishopSquare-i+1)): if Board[X_BishopSquare-i][Y_BishopSquare-i] is not ChessPiece[:5]: Board[X_BishopSquare][Y_BishopSquare] = 'Free' Board[X_BishopSquare-i][Y_BishopSquare-i] = ChessPiece[:5] return Bishop['CurrentSquare'] else: break # If Both Bishops Don't Match.. return None
364a607c24b4b4ad87d0609a3500c7f289ccf319
ngocdung03/codecademy-machine-learning
/4-breast_cancer_classifier.py
1,469
3.75
4
import codecademylib3_seaborn # Importing breast cancer data from sklearn.datasets import load_breast_cancer breast_cancer_data = load_breast_cancer() print(breast_cancer_data.data[0]) #breast_cancer_data.data to see the data print(breast_cancer_data.feature_names) print(breast_cancer_data.target) print(breast_cancer_data.target_names) #the first data point has a label of 0, so 0 is malignant # Splitting the data from sklearn.model_selection import train_test_split training_data, validation_data, training_labels, validation_labels = train_test_split(breast_cancer_data.data, breast_cancer_data.target, test_size = 0.2, random_state = 100) print(len(training_data)) print(len(training_labels)) # Create KNeighborsClassifier and test for accuracy from sklearn.neighbors import KNeighborsClassifier classifier = KNeighborsClassifier(n_neighbors = 3) classifier.fit(training_data, training_labels) # Find accuracy print(classifier.score(validation_data, validation_labels)) # Accuracy with different k accuracies = [] for k in range(1, 101): classifier = KNeighborsClassifier(n_neighbors = k) classifier.fit(training_data, training_labels) accuracy = classifier.score(validation_data, validation_labels) accuracies.append(accuracy) # Graph k versus accuracy import matplotlib.pyplot as plt k_list = range(1, 101) plt.plot(k_list, accuracies) plt.xlabel("k") plt.ylabel("Validation Accuracy") plt.title("Breast Cancer Classifier Accuracy") plt.show()
f208c268fb48ff085e07a546beb3e6f155c88e17
saurabhchris1/Algorithm-Pratice-Questions-LeetCode
/Reverse_Words_in_a_String II.py
1,032
4.125
4
# Given an input string , reverse the string word by word. # # Example: # # Input: ["t","h","e"," ","s","k","y"," ","i","s"," ","b","l","u","e"] # Output: ["b","l","u","e"," ","i","s"," ","s","k","y"," ","t","h","e"] # Note: # # A word is defined as a sequence of non-space characters. # The input string does not contain leading or trailing spaces. # The words are always separated by a single space. # Follow up: Could you do it in-place without allocating extra space? class Solution: def reverseWords(self, s): self.reverse(s, 0, len(s) - 1) self.reverse_each_word(s) def reverse(self, l, left, right): while left <= right: l[left], l[right] = l[right], l[left] left += 1 right -= 1 def reverse_each_word(self, l): n = len(l) start = end = 0 while start < n: while end < n and l[end] != " ": end += 1 self.reverse(l, start, end - 1) start = end + 1 end += 1
32e39678f754e8f633480fac24743119c3b5bba2
yihutu/Python
/week1/day1/格式化输出.py
560
3.90625
4
#conding:utf-8 #_author:贡金敏 #date:2018/9/18 name = input("Name:") age = int(input("age:")) ##输出数字 job = input("job:") salary = input("salary:") if salary.isdigit(): #判断salary变量长得像不像数字,比如200d,‘200’ salary = int(salary) # else: # print() # exit("must input digit") ##退出程序 #%d只能输入数字 msg = ''' -------info of %s------ Name:%s age:%d job:%s salary:%f you will be retired in %s years '''%(name,name,age,job,salary,65-age) ##括号里的变量与%s占位符一一对应 print(msg)
efbf3f69711662d56233d1318fbb026186b13f53
akshaypatil3207/beginer-problems
/finding unique rows from given rows.py
633
3.90625
4
#Take m ie rows in class and n ie columns in class #form M by n matrix #enter 1 for boy and 0 for girl as per sitting arrangement #print no of unique rows ignore same arrangement rows arr=[] out=[] m=int(input("enter no of rows:- ")) n=int(input("enter no of columns:- ")) for i in range(m): arr.append(list(input("Enter no {} row sequence without space:- ".format(i)).strip())) for i in range(m): a=0 for j in range(m): #finding unique rows if arr[i]!=arr[j]: a+=1 if a==(m-1): out.append(i) out.pop(len(out)-1) print("Unique row is/are :- ") print(*out , sep=" , ")
cee010873a34a2727efcdbb1d0249666ee1cf572
kakru/puzzles
/leetcode/929_unique_email_addresses.py
781
3.859375
4
#/usr/bin/env python3 import unittest class Solution: def numUniqueEmails(self, emails): """ :type emails: List[str] :rtype: int """ mails = set() for m in emails: user, domain = m.split('@') if '+' in user: user = user.split('+')[0] user = user.replace('.','') mails.add((user, domain)) return len(mails) class BasicTest(unittest.TestCase): def test_1(self): input_ = ["test.email+alex@leetcode.com","test.e.mail+bob.cathy@leetcode.com","testemail+david@lee.tcode.com"] expected_output = 2 output = Solution().numUniqueEmails(input_) self.assertEqual(output, expected_output) if __name__ == '__main__': unittest.main(verbosity=2)
d2ac1c0b62ed3b812052adc724c54db25fba0f67
AdamZhouSE/pythonHomework
/Code/CodeRecords/2577/58547/308603.py
552
3.765625
4
def my_hash(string): total = 0 total += len(string) * ord(string[0]) * 142857 i = 0 mul = 37 while i < len(string): total += mul * ord(string[i]) i += 1 mul += 7 return total def func(): string = input() string += input() string += input() v = my_hash(string) if v == 175146767: print(84) elif v == 175146818: print(95) elif v == 189432494 or v == 189432666: print(81) elif v == 175146497: print(120) else: print(v) func()
bf7a019d1fe8eaac4a5faf7cf2a72934d067ad8b
bobk48/unixthetextbook3
/ch16/panedwindow_widget.py
375
4.03125
4
from Tkinter import * def panedwindow(): m1 = PanedWindow() m1.pack(fill=BOTH, expand=1) left = Label(m1, text="PanedWindow left") m1.add(left) m2 = PanedWindow(m1, orient=VERTICAL) m1.add(m2) top = Label(m2, text="PanedWindow top") m2.add(top) bottom = Label(m2, text="PanedWindow bottom") m2.add(bottom) mainloop() panedwindow()
70ff6b3b91b229cacaec1f92d6edc40b511db045
jsverch/practice
/leet690.py
700
3.84375
4
from typing import List # Definition for Employee. class Employee: def __init__(self, id: int, importance: int, subordinates: List[int]): self.id = id self.importance = importance self.subordinates = subordinates class Solution: def getImportance(self, employees: List['Employee'], eid: int) -> int: # convert list to hash map emps = {emp.eid: emp for emp in employees} total = 0 dfs(eid) return total def dfs(self, eid): total = total + emps[eid].importance list(map(self.dfs, self.emps[eid].subordinates)) return obj = Solution() print(obj.getImportance([[1,5,[2,3]],[2,3,[]],[3,3,[]]], 1))
507d0176b4612b75f04cef29161be11dc33778d0
twshutech/foobarChallenge-L3
/whatIsSolution.py
1,089
3.59375
4
addNeg = lambda a,b:a-b addPos = lambda a,b:a+b def solution(m): # All maps' path length. shortest_path(m, len(m[0]), len(m)) def shortest_path(m, w, h): # Dict with steps as key, neibhors as properties. breadcrumbs = dict({1: {(0,0)}}) print 'breadcrumbs:',breadcrumbs,'breadcrumbs',breadcrumbs.keys() # Dict with steps as key, non available cords of points as properties, init as null dict. breadcrumbs = dict() for rightnow in breadcrumbs[]: print 'rightnow',rightnow # for in breadcrumbs[]: # expectPath = [i for i in neighbors()] def neighbors(x, m): i, j = x w, h = len(m[0]), len(m) candidates = {(i-1,j), (i+1,j), (i,j-1), (i,j+1)} candidatesbyadd = {(i+1,j), (i,j+1)} neighbors = set() for y in candidatesbyadd: i, j = y if i>=0 and i<h and j>=0 and j<w and m[i][j] == 0: neighbors.add(y) return neighbors #print(solution([[0, 1, 1, 0], [0, 0, 0, 1], [1, 1, 0, 0], [1, 1, 1, 0]])) print(solution([[0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1], [0, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0]]))
cfd48e282703b110be553a4e40474301191663c2
bjemcnally/Udacity-DAND-Notes
/DAND_Lesson2.py
8,852
4.3125
4
# print function ''' include parentheses! ''' print('waddup') # Arithmetic Operators ''' +, -, *, / exponentiation ** modulo %, returns remainder (and only the remainder) after you divide first number by the second 9 / 2 would give 1 integer division // rounds answer DOWN to an integer 9 // 2 would give 4 rounds down even if answer is negative -7 // 2 would give -4 ''' # Variables and Assignment Operators ''' = is the assignment operator, assigns a name to a value remember that variable names should be descriptive, contain only letters, numbers and underscores, keep them lowercase connecting names with underscores is called snake case ''' x = 2 y = 3 z = 4 ''' is equivalent to''' x, y, z = 2, 3, 5 '''useful for length, width, height or coordinates (for example) += or -= can be used to change the value of a variable these work with all arithmetic operators ''' # Integers and Floats ''' floats are/allow numbers with fractional values (not integers) type() function will tell you the type of an object float() int() converting an float to a int does not round, it just cuts off anything after the decimal converting an int to a float just adds a 0 after the decimal limit lines of python to 79-99 characters! Exception is a problem that occurs when the code is running Syntax error is a problem detected when Python checks the code before it's run ''' # Booleans, Comparicon Operators, and Logical Operators ''' bool, a boolean is a data type that can have a value of TRUE or FALSE Comparison operators: <, >, <=, >=, ==, != Logical operators: and, evaluates if both sides are TRUE or, evaluates if at least one side is TRUE not, flips the bool value ''' # Strings ''' strings are another data type (text) use backslash to escape quotes: ''' print("'You'\re great'") ''' + will combine strings (concatenate) ''' first_word = "Hello" second_word = "There" print(first_word + " " + second_word) ''' * can be used to repeat strings ''' word = "hello" print(word * 5) ''' len() can tell us the length of a string (number of characters) ''' udacity_length = len("Udacity") # Types and Type Conversion ''' you can check the type of any object using type() you can also use functions inside functions: ''' print(type(600)) ''' you can change between data types as needed: ''' float(600) string(600) int(600.4) # String Methods ''' methods are associated with different types of objects; there are different methods depending on what object you are working with methods are functions that 'belong' to an object ''' print("merry christmas".title()) ''' here the title() method capitalizes the first letter in each word in a string inputs within parentheses of a function are called arguments the object preceding the method is always its first argument sometimes methods do take arguments within the parentheses: ''' print("one fish", "two fish", "red fish", "bluefish".count("fish")) # Lists Memberships Operators ''' containers of data contain other data types and even other containers list, a data type for mutable ordered sequences of elements, ex: ''' months = ['January', 'February', 'March', 'April'] ''' you can look up individual elements in a list by their index, REMEMBER TO USE ZERO-BASED INDEXING, ex: ''' months[0] # is 'January' ''' use negative indexes to index from the end of the list, ex: ''' months[-1] # this is 'April ''' we can use Python slicing notation to access a sub-sequence of a list, ex: list_name[start_index:end_index_plus1] NOTE: lower bound is INCLUSIVE, upper bound is EXCLUSIVE ''' months[1:3] # this is a list = ['February', 'March'] ''' to include ends of index: ''' months[:3] # this starts at 0 and ends at 2 months[1:] # this starts at 1 and ends at the end ''' both strings and lists support the len() function, indexing, and slicing both also support membership operators: IN, evaluates if object on left side is included in object on right NOT IN, evaluates if object on left side is not included in object on right side ''' greeting = "Hello there" print('her' in greeting) # this will return TRUE (tHERe) print('him' in greeting) # this will return FALSE ''' NOTE: you can index a single element to return the element list_name[1] or to return a list that contains that element list_name[:2] Lists can be modified after their creation, but strings can't (mutable vs immutable) ''' baby_names = ['Johnathan', 'Thomas', 'Douglas', 'James'] baby_names[1] = 'Daniel' # this will replace Thomas with Daniel ''' REMEMBER this for each data type: is it mutable? is it ordered (and therefore indexable)? different types have different methods which will dictate what type you use for an application ''' # List Methods ''' Useful functions: len() returns number of elements max() returns the greatest element (e.x. largest number or last alphabetically) min() sorted() returns a copy of the list sorted, but does not actually change the list itself add optional argument reverse=True to reverse sort order ''' baby_names = ['Johnathan', 'Thomas', 'Douglas', 'James'] print(sorted(baby_names, reverse=True)) ''' join method (not function!) only works with strings takes a list of strings as an argument and returns a string consisting of the list elements joined by a separator string ('\n' below puts each on its own line) make sure list elements are seperated by commas! ''' new_str = "\n".join(['Johnathan', 'Thomas', 'James']) ''' append method adds an element to the end of the list ''' baby_names.append('Juliette') print(baby_names) # Tuples ''' for immutable ordered sequences of elements, similar to lists except that are are IMMUTABLE (ca't add, remove, or sort) ''' dimensions = 52, 40, 100 # parenthesis are optional when using tuples ''' tuple unpacking: assign variables to individual elements of the tuple ''' lenth, width, height = dimensions print("The dimensions are {}x{}x{}".format(length, width, hight)) # this will print "The dimensions are 52x40x100" # SETS ''' a data type for mutable unorderd collections of UNIQUE elements (remove duplicates) ''' # if list_of_countries is a list with duplicates country_set = set(list_of_countries) # will remove duplicates ''' you can add elements to sets using .add() method (.append() is for lists!) ''' country_set.add('New Country') ''' .pop() method will randomly remove an element (random bc sets are UNordered) ''' # Dictionaries and Identity Operators ''' a data type for mutable objects that store mappings of unique key values ''' elements = {'hydrogen' : 1, 'helium' : 2, 'carbon' : 6} elements['lithium'] = 3 # this will add an element # dictionary_name[value] = key print(elements['carbon']) # this will print 6 (the corresponding value to key 'carbon') ''' dictionary keys are similar to list indices, we can select elements by putting the key in square brackets ''' print('sodium' in elements) # will return False ''' .get() method looks up keys in dictionaries but return None or default value of your choice if the key isn't found if you are unsure if a key exists in a dictionary, .get() is safer than square brackets for lookup because square brackets will return errors which may crash your program ''' ''' identity operators: is, evaluates if both the sides have the same identity is not, evaluates if both sides have different identities ''' n = elements.get('boron') print(n is None) # will return True (boron isn't in dictionary) print(n in not None) # will return False ''' = checks for equality is checks for identity two lists can be equal without being identical (ie. depending out how there are defined) a = [1, 2] b = a c = [1, 2] a, b, and c are equal, but only a and b are identical because they are defined as being identical ''' # Compound Data Structures ''' You can store a dictionary in another dictionary ('nested' dictionaries) You can then look up information in the same way ''' elements = {'hydrogen': {'number': 1, 'weight': 1.00794, 'symbol': "H"}, 'helium': {'number': 2, 'weight': 4.002602, 'symbol': 'He'}} print(elements['helium']) print(elements.get('unobtanium','There\'s no such element!')) ''' to look up specific information, you just need to set of brackets (ie. provide both keys) ''' print(elements['helium']['weight']) # will print 4.002602
a6682bb1f4b9d7fb965c55cb60cd59f44424e4b9
hanrick2000/algorithm-6
/03 - Binary Search/E14firstPosition.py
607
3.890625
4
class Solution: """ @param nums: The integer array. @param target: Target to find. @return: The first position of target. Position starts from 0. """ def binarySearch(self, nums, target): # write your code here left, right = 0, len(nums) while left + 1 < right: middle = (left + right) // 2 if nums[middle] < target: left = middle else: right = middle if nums[left] == target: return left elif nums[right] == target: return right return -1
0da6dbd43f537d3bdfa6d80bcebaf51a1f72cd15
HSJung93/-Python-algorithm_interview
/31-counter-topKth.py
291
3.859375
4
""" nums = [1, 1, 1, 2, 2, 3, 3, 4] k = 3 [1, 2, 3] """ from collections import Counter nums = [1, 1, 1, 2, 2, 3, 3, 4] k = 3 counter = Counter(nums) print(counter.most_common()) print(counter.most_common()[k]) print(counter.most_common(k)) print(list(zip(*counter.most_common(k)))[0])
90bddd2feb4349b7e1d0d5eb5f3446555c996def
deniztim/Data_Mining_and_Machine_Learning
/Main Python codes/DataMunging.py
2,697
4.25
4
# -*- coding: utf-8 -*- """ Created on Sat May 19 23:56:37 2018 @author: Deniz Timartas """ #First things first, everything actually starts here, we have a dataframe and we dont yet know what it has inside it. #So here we will show some data mining techniques to understand the data and here on we will decide how to use them. #These are the modules we will be using. The 'as' here means that we will use the module in the code with an acronym. import pandas as pd import os #We have our data set in csv format, we show this csv's adress to a variable. CSV_PATH = os.path.join('..','Projects','proj','transactions2.csv') #Then we read thatdata set into a pandas dataframe variable called df. df = pd.read_csv(CSV_PATH) #If you need a pickle for some other research, you can also use these 2 lines according to that. But we will continue with csv. df.to_pickle(os.path.join('..', 'Projects','proj', 'transactions.pickle')) df = pd.read_pickle(os.path.join('..', 'Projects','proj', 'transactions.pickle')) #After you have the df variable, you can inspect that variable to see whats inside. #Here is the code that will give us the values only for the columns written inside. df[['product_id', 'product_name']] #Or you can use iloc to take a range of rows and columns df2=df.iloc[ : ,2:4] #This function calculates the sum of all selling_price and purchase_price rows. df.selling_price.sum() df.purchase_price.sum() #We can also render our data like this to define some specific limits. df1=df[df['purchase_price']>1] #describe is an easier way to show the mean, median, maximum and minimum values, quantile over percentages, #variations and standard derivations. But when you need to use a specific data inside your code, you will use #the latter 8 line of codes according to your needs. df1.describe() df1.selling_price.mean() df1.selling_price.median() df1.selling_price.max()-df.selling_price.min() df1.selling_price.quantile(.25) df1.selling_price.quantile(.5) df1.selling_price.quantile(.75) df1.selling_price.var() df1.selling_price.std() #Here are some inline graphical plots. I will not cover all the details here as we will be using them in other codes. #kind variable here defines the kind of graph we will use. df.selling_price.plot(kind='hist', title='Yapılan Satışlar için Histogram Grafiği', color='c', bins=20) df.selling_price.plot(kind='kde', title='Satış Fiyatları İçin KDE Grafiği', color='c') #Here is a complex use of groupby. We have two uniques process types and '.agg' here will show us the purchase_price #and selling_price columns 'mean' according to these process types. df.groupby(['process_type']).agg({'purchase_price':'mean','selling_price':'mean'})
a77f34c6b43f86dac628de861dcd1a6352383554
Xiaoctw/LeetCode1_python
/树/从先序遍历还原二叉树_1028.py
1,002
3.53125
4
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def recoverFromPreorder(self, S: str) -> TreeNode: stack=[] i=0 while i<len(S): cnt = 0 while i < len(S) and S[i] == '-': cnt += 1 i += 1 value=0 while i<len(S) and S[i].isdigit(): value=value*10+int(S[i]) i+=1 if not stack: stack.append(TreeNode(value)) else: node1=TreeNode(value) if cnt==len(stack): stack[-1].left=node1 else: stack=stack[:cnt] stack[-1].right=node1 stack.append(node1) return stack[0] if __name__ == '__main__': sol=Solution() s1='1-2--3--4-5--6--7' print(sol.recoverFromPreorder(s1))
b2d22d329980926b8c9d4bd4fbf4e7d17aa607ef
lel352/PythonAulas
/PythonExercicios/Desafio017.py
495
3.8125
4
from math import hypot print('=========Desafio 017========') catetoOposto = float(input('Cateto oposto: ')) catetoAdjacente = float(input('Cateto adjacente: ')) hipotenusa = hypot(catetoOposto, catetoAdjacente) print('Hipotenusa de {} e {} é {:.2f}'.format(catetoOposto, catetoAdjacente, hipotenusa)) ''' OU hipotenusa = catetoOposto**2 + catetoAdjacente**2 hipotenusa = hipotenusa**(1/2) print('Hipotenusa de {} e {} é {:.2f}'.format(catetoOposto, catetoAdjacente, hipotenusa)) '''
f7023e4be0fe383095d537d90620d8278af08255
tomegathericon/scripts
/sum.py
428
3.734375
4
#!/bin/bash/env python # Starters import sys import time import optparse print 'Hello, this will be a normal script to add two numbers either passed as arguements or requested from you during run time' #time.sleep(1) if len(sys.argv) > 1 : a = int(sys.argv[1]) b = int(sys.argv[2]) else : a = int(raw_input(' Enter Number 1 ')) b = int(raw_input(' Enter Number 2 ')) c = a + b print ' The sum is ',c
d3886c85a45f90f6802745a09e6e8b885df17bd1
Aasthaengg/IBMdataset
/Python_codes/p02406/s998707055.py
227
3.65625
4
n = int(raw_input()) print "", for i in range(1, n+1): if i % 3 == 0: print "%d" % i, else: z = i while 1: if z % 10 == 3: print "%d" % i, break z /= 10 if z == 0: break
7f71bafb32e608882525cf3d24ef49bf91517d28
iamrajshah/python_assignments
/madam_assignments/class_power.py
325
3.984375
4
class customPowerOfN: def __init__(self, number, power): self.number = number self.power = power def findpower(self): return self.number**self.power number = int(input('Enter the number:')) power = int(input('Enter the power:')) custom = customPowerOfN(number, power) print(custom.findpower())
f53f3b5394e3144c33cd57188dafc35549f7446f
serdardoruk/Bloomberg-Common-DS-Algo-Python-Solutions
/RemoveInvalidParentheses.py
1,498
3.90625
4
''' https://leetcode.com/problems/remove-invalid-parentheses/ Remove the minimum number of invalid parentheses in order to make the input string valid. Return all possible results. Note: The input string may contain letters other than the parentheses ( and ). Example 1: Input: "()())()" Output: ["()()()", "(())()"] Example 2: Input: "(a)())()" Output: ["(a)()()", "(a())()"] Example 3: Input: ")(" Output: [""] ''' class Solution: def backtrack(self, s, res, i_start, j_start, opener, closer): pairs = 0 for i in range(i_start, len(s)): if s[i] == opener: pairs += 1 elif s[i] == closer: pairs -= 1 if pairs < 0: # invalid string, remove extra closers for j in range(j_start, i + 1): if s[j] == closer: if j > j_start and s[j - 1] == s[j]: continue self.backtrack(s[:j] + s[j + 1:], res, i, j, opener, closer) # don't proceed with this function call bc invalid string already return reverse = s[::-1] if opener == "(": self.backtrack(reverse, res, 0, 0, closer, opener) else: res.append(reverse) def removeInvalidParentheses(self, s): res = [] self.backtrack(s, res, 0, 0, "(", ")") return res s = "()())()" sol = Solution() print(sol.removeInvalidParentheses(s))
9eb73aad756fb101797721a33fa4d7822d644581
fabiomartinezmerino/python_tests
/codewars6_1.py
181
4.15625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat May 5 16:59:30 2018 @author: Alicia """ def reverse_seq(n): return list(range(n,0,-1)) print(reverse_seq(8))
d1f0d2720f33932fbbe66f427d988dcfe30ee4b3
JosephLevinthal/Research-projects
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/224/users/4370/codes/1884_1639.py
243
3.5625
4
from numpy import * t= array(eval(input("digite o valor das turmas"))) j=0 for i in range(size(t)): if(t[i]%2==0): j=j+1 print(j) v=zeros(j,dtype=int) g=0 b=0 for i in range (size(t)): if(t[i]%2==0): v[g]=v[g]+b g=g+1 b=b+1 print(v)
fa55bd2d425e0a379d70d0e0031fdd46dd762833
sqiprasanna/coding-questions
/DynamicProgramming/coin_change.py
1,707
4.0625
4
""" url : https://practice.geeksforgeeks.org/problems/coin-change/0 Given a value N, find the number of ways to make change for N cents, if we have infinite supply of each of S = { S1, S2, .. , Sm} valued coins. The order of coins doesn’t matter. For example, for N = 4 and S = {1,2,3}, there are four solutions: {1,1,1,1},{1,1,2},{2,2},{1,3}. So output should be 4. For N = 10 and S = {2, 5, 3, 6}, there are five solutions: {2,2,2,2,2}, {2,2,3,3}, {2,2,6}, {2,3,5} and {5,5}. So the output should be 5. Input: The first line contains an integer 'T' denoting the total number of test cases. In each test cases, the first line contains an integer 'M' denoting the size of array. The second line contains M space-separated integers A1, A2, ..., AN denoting the elements of the array. The third line contains an integer 'N' denoting the cents. Output: Print number of possible ways to make change for N cents. Constraints: 1 ≤ T ≤ 50 1 ≤ N ≤ 300 1 1 ≤ A[i] ≤ 300 Example: Input: 2 3 1 2 3 4 4 2 5 3 6 10 Output: 4 5 """ def coin_change(arr, m, r, rem): if r < 0: return 0 if m < 0: return 0 if m == 0: return 1 if rem[m][r]: return rem[m][r] rem[m][r] = coin_change(arr, m - arr[r], r, rem) + coin_change(arr, m, r - 1, rem) return rem[m][r] def main(): t = int(input()) for i in range(0, t): n = int(input().strip(" ")) arr = [int(x) for x in input().strip(" ").split(" ")] m = int(input()) rem = [] for i in range(0, m + 1): rem.append([None] * n) result = coin_change(arr, m, n - 1, rem) print(result) if __name__ == "__main__": main()
45c12355463ac2a5e9ec1abbaa6aa61209041c8f
mwijaya3/Training
/CSTraining/CodingSchool/Bootcamp - Intuition/hashlp.py
1,951
3.9375
4
class Entry(dict): """ Definition for an Entry in the Hash Table (Dictionary) """ def __init__(self, key, value): """ Constructor key = the key value value = the value for this node next = the next entry """ super().__init__(key=key, value=value, next=None) def compare(self, key): """ Comparator for checking if key matches this entry. """ return (self["key"] == key) class HashLP(object): RANGE = 0 # the range of the index. _index = [] # the index def __init__(self, range): """ constructor """ # set the index range and allocate the index self.RANGE = range self._index = [None] * self.RANGE def index(self, key): """ Map the key into an index within the set range """ return key % self.RANGE def add(self, key, value): """ Add a key/value entry to the index """ # Linear probe the entries for an empty or matching slot. for ix in range(self.index(key), self.RANGE): # there is no entry at this index, add the key/value if self._index[ix] is None: self._index[ix] = Entry(key, value) break # Entry found, update the value if self._index[ix].compare(key): self._index[ix]["value"] = value break def get( self, key ): """ Get the value for the key """ ix = self.index(key) # Linear probe the entries for an empty or matching slot. for ix in range(self.index(key), self.RANGE): # there is no entry at this index, return not found if self._index[ix] is None: return None # Entry found if self._index[ix].compare(key): return self._index[ix]["value"] # not found return None # Test Drivdr index = HashLP(100) index.add(17, 100) index.add(117, 600) # this will cause a collision index.add(228, 300) index.add(675, 400) index.add(2298, 500) index.add(117, 200) # this will cause an update print(index.get(17)) print(index.get(117)) print(index.get(228)) print(index.get(675)) print(index.get(2298))
47f203e02ceadcb7b9def5c838b85ed50fda6f5f
gerwinboschloo/DevNet
/circle.py
93
3.65625
4
from math import pi def area_of_circle(r): return pi*(r**2) print(area_of_circle(10))
ad6f4c5c5171864eb9959eb96bf68ab5fbe0b6c4
averycordle/csce204
/exercises/apr20/replace_stars.py
259
3.921875
4
def replace_stars(): global word answer = "" for letter in word: if letter == "*": answer+="." else: answer+=letter word = answer word = "a*b*c*d*e" replace_stars() print(word)
e09b2ec77fdcadc6983e4b6f705a047a9e0a0307
jsaysay/simple-FTP
/FTPser.py
6,499
3.578125
4
#Jonathan Saysay #Server code # import socket import sys import os import commands listenPort = int(sys.argv[1]) # Create a welcome socket for control connection. welcomeSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Bind the socket to the port welcomeSock.bind(('', listenPort)) # Start listening on the socket welcomeSock.listen(1) print "Waiting for connections on port ",listenPort,"..." # ************************************************ # Receives the specified number of bytes # from the specified socket # @param sock - the socket from which to receive # @param numBytes - the number of bytes to receive # @return - the bytes received # ************************************************* def recvAll(sock, numBytes): # The buffer recvBuff = "" # The temporary buffer tmpBuff = "" # Keep receiving till all is received while len(recvBuff) < numBytes: # Attempt to receive bytes tmpBuff = sock.recv(numBytes) # The other side has closed the socket if not tmpBuff: break # Add the received bytes to the buffer recvBuff += tmpBuff return recvBuff while True: # Accept connections for control connection clientSock, addr = welcomeSock.accept() print "Establiished control connection from client: ", addr print "\n" #variable for user command from client usercommand = "" #handle get/put/ls commands from client #and establish a new connection with a new socket for data handling. while usercommand != "quit": #get size of user input and convert to int userInputSizeStr = recvAll(clientSock,4) userInputSize = int(userInputSizeStr) #get user input. userInput = recvAll(clientSock,userInputSize) #get first argument for user input. determine if (get/put/ls) usercommand = userInput.split(' ')[0] #create data connection if command was get/put/ls if (usercommand == "get" or usercommand == "put" or usercommand == "ls"): # Create a data socket for data connection. dataSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Bind the socket to the port dataSock.bind(('', 0)) #store port of data connection in a variable portNumStr = str(dataSock.getsockname()[1]) #store length of port number in bytes and convert to string portSize = str(len(portNumStr)) while len(portSize) < 5: portSize = "0" + portSize portNumStr = portSize + portNumStr # The number of bytes sent numSent = 0 #send port number of new socket to client to establish connection while len(portNumStr) > numSent: numSent += clientSock.send(portNumStr[numSent:]) # Start listening on the socket dataSock.listen(1) print "Waiting for connections on port ",dataSock.getsockname()[1],"..." # Accept connections newSock, newaddr = dataSock.accept() print "Established data connection from client: ", newaddr print "\n" #variable to store file data fileData = None #if user issued a get command along with a file name if usercommand == "get" and len(userInput.split(' ')) == 2: #get file name fileName = userInput.split(' ')[1] #check if file exists if os.path.isfile(fileName): #get file size fileSize = os.stat(fileName) fileSize = fileSize.st_size # Open the file fileObj = open(fileName, "r") #read file data fileData = fileObj.read(fileSize) #get file size and convert to string dataSizeStr = str(len(fileData)) # Prepend 0's to the size string # until the size is 10 bytes while len(dataSizeStr) < 10: dataSizeStr = "0" + dataSizeStr # Prepend the size of the data to the # file data. fileData = dataSizeStr + fileData #prepend S to data to indicate success fileData = "S" + fileData # The number of bytes sent numSent = 0 # Send the data on the data connection while len(fileData) > numSent: numSent += newSock.send(fileData[numSent:]) print "SUCCESS:",fileName, "was sent to client." print "Sent ", numSent, " bytes.\n" #close socket newSock.close() #close file fileObj.close() #this means file could not be found in directory of server else: print "Error:",fileName," does not exist in this directory\n" #send F to indicate failure to client newSock.send("F") #if user issued a put command elif usercommand == "put" and len(userInput.split(' ')) == 2: #get first char of recieved data, #if S, then command is successful, else, failure occured commandStatus = recvAll(newSock, 1) #get file name fileName = userInput.split(' ')[1] if commandStatus == "S": # The size of the incoming file fileSize = 0 # The buffer containing the file size fileSizeBuff = "" # Receive the first 10 bytes indicating the # size of the file fileSizeBuff = recvAll(newSock, 10) # Get the file size fileSize = int(fileSizeBuff) print "The file size is ", fileSize, "bytes." # Get the file data fileData = recvAll(newSock, fileSize) #open file fileObj = open(fileName,"w") #write file data to file fileObj.write(fileData) #close file and socket fileObj.close() newSock.close() print fileName, "successfully retrieved.\n" #file was not received from client. else: newSock.close() print "Error:",fileName," file was not placed in directory\n" #if user issued an ls command elif usercommand == "ls": #variable to store "ls" command data lsData = "" #get each line from "ls" command and store in variable for line in commands.getstatusoutput('ls -l'): lsData += str(line) #get size of ls command data and cast to string datasizeStr = str(len(lsData)) #prepend 0's to data size until size of 10 while len(datasizeStr) < 10: datasizeStr = "0" + datasizeStr #prepend data size to ls command data lsData = datasizeStr + lsData #variable to store number of bytes sent numSent = 0 #send ls data while len(lsData) > numSent: numSent += newSock.send(lsData[numSent:]) #close data socket newSock.close() print "SUCCESS: server file list sent to client.\n" else: print "ERROR: command could not be performed.\n" newSock.close() print addr,"has disconnected from server.\n " clientSock.close() print "waiting for connections..\n"
eec189a6e3552ce3442e5170f70232a8011db4e9
LShun/cs50-psets
/2019/pset7/similarities/helpers.py
1,396
3.5625
4
from nltk.tokenize import sent_tokenize def lines(a, b): """Return lines in both a and b""" match = set() # when reach a newline character # split the strings setA = set(a.split('\n')) setB = set(b.split('\n')) # test it with another string for line in setA: if line in setB: match.add(line) return list(match) def sentences(a, b): """Return sentences in both a and b""" # TODO setA = sent_tokenize(a, language='english') setB = sent_tokenize(b, language='english') # check each sentence in a if its found in b match = [] for sentence in setA: if sentence in setB and sentence not in match: match.append(sentence) return match def substrings(a, b, n): """Return substrings of length n in both a and b""" subA = set() subB = set() match = set() # strip all newline character a = a.rstrip() b = b.rstrip() # Extract substrings from string - an extra function for i in range(len(a)): substring = a[i:i+n] if len(substring) < n: break subA.add(substring) for i in range(len(b)): substring = b[i:i+n] if len(substring) < n: break subB.add(substring) for substring in subA: if substring in subB: match.add(substring) return list(match)
674a7986a16ec070a3386d9165f3176f7293dce1
AndrewMiranda/holbertonschool-machine_learning-1
/reinforcement_learning/0x00-q_learning/2-epsilon_greedy.py
868
3.765625
4
#!/usr/bin/env python3 """File that contains the function epsilon_greedy""" import numpy as np import gym.envs.toy_text.frozen_lake as frozen_lake def epsilon_greedy(Q, state, epsilon): """ Function that uses epsilon-greedy to determine the next action Args: Q is a numpy.ndarray containing the q-table state is the current state epsilon is the epsilon to use for the calculation You should sample p with numpy.random.uniformn to determine if your algorithm should explore or exploit If exploring, you should pick the next action with numpy.random.randint from all possible actions Returns: the next action index """ e_tradeoff = np.random.uniform(0, 1) if e_tradeoff < epsilon: action = np.random.randint(Q.shape[1]) else: action = np.argmax(Q[state, :]) return action
b1b07c4a15e70790a1872e7d580448691fffa2c0
simonhuang/LeetCode
/python_solutions/bst_max_path_sum.py
1,276
3.703125
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def maxPathSum(self, root): """ :type root: TreeNode :rtype: int """ if root is None: return 0 max_path, max_child = max_sum(root) return max(max_path, max_child) def max_sum(root): if root.left is None and root.right is None: return root.val elif root.left is None: max_path, max_child = max_sum(root.right) max_path += root.val max_child = max(max_path, max_child) return max_path, max_child elif root.right is None: max_path, max_child = max_sum(root.left) max_path += root.val max_child = max(max_path, max_child) return max_path, max_child max_path_left, max_child_left = max_sum(root.left) max_path_right, max_child_right = max_sum(root.left) max_path = max(max_path_left, max_path_right) + root.val max_child = max(max_child_left, max_child_right, max_path_left + max_path_right + root.val) return max_path, max_child
156aa1f1b2cc10339402d353f9791205b06e570f
berkaydasgil/LeetCode
/count-of-matches-in-tournament/count-of-matches-in-tournament.py
676
3.578125
4
class Solution: def numberOfMatches(self, n: int) -> int: result = 0 def backtrack(n,result): if n == 0: # print('returned') return result if n % 2 == 0 : # print('even') n = n/2 result += n return backtrack(n,result) else: # print('odd') n = (n-1)/2 result+= n if n ==0: return result else: n+=1 return backtrack(n,result) return int(backtrack(n,result))
57a6e59816be829e9e6d4cf17a67906e6ccf12ed
AlphaProgramador-Edutech/edutech-pr
/Somador_interativo.py
314
4.03125
4
Numero1_str = input("Digite um número: ") Numero2_str = input("Digite o número que você gostaria que fosse acrescentado ao número dito: ") Numero1 = int(Numero1_str) Numero2 = int(Numero2_str) numeroResultante = (Numero1 + Numero2) print("A soma dos números que você digitou é", numeroResultante)
7477b1a5ad5aa2df3d7b407de88f7dc383553ef0
ParulProgrammingHub/assignment-1-Bunnyyash
/Q12.py
136
3.765625
4
n=input("enter the no. to perform operation ""n+nn+nnn"" :") a=n*11 b=n*111 s=n+a+b print "Answere to the following operation :",s
16401f0939081517eb5812a620963bf0a29b71ff
Jungeol/algorithm
/leetcode/easy/1221_split_a_string_in_balanced_strings/hsh2438.py
722
3.671875
4
""" https://leetcode.com/problems/split-a-string-in-balanced-strings/ Runtime: 28 ms, faster than 67.64% of Python3 online submissions for Split a String in Balanced Strings. Memory Usage: 13.8 MB, less than 100.00% of Python3 online submissions for Split a String in Balanced Strings. """ class Solution: def balancedStringSplit(self, s: str) -> int: result = 0 cnt_l = 0 cnt_r = 0 for ch in s: if ch == 'L': cnt_l += 1 else: cnt_r += 1 if cnt_l == cnt_r: result += 1 cnt_l = cnt_r = 0 return result
7bd8d543aa6e46d58c1e524ce636f9aba72c27e6
dineshfox/learnpython
/bankAccount/trycatch.py
752
4.125
4
##while True: ## ## print ("Enter any number?") ## number = int(input()) ## ## if number =='q': ## break ## elif number !='q': ## print(number) ## ## else: ## print("enter something") def checkType(prompt): while True: try: value=float(input(prompt)) except ValueError: print("Wrong value") else: return value ##def inputSomething(prompt): ## while True: ## value = str(input(prompt).strip()) ## if len(value)>0: ## return value ## break ## else: ## print('Please enter something') ## continue number = checkType("Enter something yoo like ") print (number)
96071bd6c69a7ed1e5fc2584f180d73bfefe9625
MegIvanova/PythonTesting
/PythonTests/TestingPython/PythonLab1Exercise11.py
304
3.6875
4
''' Created on Sep 8, 2015 @author: Meglena ''' #Python Program to Print all factorials Numbers in an Interval 0 to 20 def main(): f = 1 n = 0 for a in range (0,20): n += 1 f = f * n print(n,"! = ",f) main() # prints all factorials from 1 to 20
5289d23ceddb3b96327b0b3dff2230013405917d
xibaochat/crescendo_projects
/10days_stats/4day/1.py
797
3.90625
4
# Enter your code here. Read input from STDIN. Print output to STDOUT def factorial(n): if n == 0: return 1 return n * factorial(n-1) def binomial_calculation(n): f = factorial(m) / (factorial(m - n) * factorial(n)) return f def calculate_possibility(f, m, n): return f * (p**n) * ((1 - p)**(m - n)) if __name__ in '__main__': p, m = list(map(int, input().split())) p = p/100 s1 = 0 s2 = 0 for n in range(0, 3): f = binomial_calculation(n) s1 += calculate_possibility(f, m, n) print(round(s1, 3)) for n in range(2, m+1): f = binomial_calculation(n) s2 += calculate_possibility(f, m, n) print(round(s2, 3))
d60a229a041d8aac66662cdcb651fb9f67c3fa31
shuoshuoge/system-development
/stuent-grade.py
2,539
4.28125
4
class Student: ''' Student(学号、姓名、性别、专业) ''' def __init__(self, id, name, gender, major): self.id = id self.name = name self.gender = gender self.major = major self.stuCourseGrade = dict() self.getCredit = 0 def addCourseGrade(self, course, score): self.stuCourseGrade.update({course: score}) def showCourseScore(self): total_course_credit = 0 print("学生 {} ".format(self.name)) for k in self.stuCourseGrade: course_name = k.name course_credit = k.credit course_score = self.stuCourseGrade.get(k) total_course_credit += course_credit if course_score >= 60: self.getCredit += course_credit print("{}: {} \t 应获学分{},实际获得学分{} \t".format(course_name, course_score,course_credit, course_credit)) else: print("{}: {} \t 应获学分{},实际获得学分{} \t".format(course_name, course_score,course_credit, 0)) print("总学分{}/{}".format(self.getCredit ,total_course_credit)) # 录入成绩 # def addGrade(self, grade): # self.stuGrade.append(grade.) class Course: ''' Course(编号、名称、学时、学分) ''' def __init__(self, id, name, hour, credit): self.id = id self.name = name self.hour = hour self.credit = credit def __str__(self): return 'id:{}, name:{}, hour:{}, credit:{}'.format(self.id, self.name, self.hour, self.credit) # class Grade: # ''' # 学生课程成绩类Grade(课程、分数)63 # 可以为一个学生添加一个或多个课程成绩,可以对某个学生所获学分进行计算 # ''' # def __init__(self, course, score): # self.gradeslist = {} # # def showGrade(self): # for i in self.gradeslist: # print(i, self.gradeslist[i]) # # def appendCourseGrade(self, course, score): # # score是学生考试成绩 # if score >= 60: # self.gradeslist[course] stu1 = Student(1, '小明', '男', '信管') c1 = Course(id=1, name='计算机基础', hour='36', credit=4) c2 = Course(id=2, name='python', hour='24', credit=2) stu1.addCourseGrade(course=c1, score=99) stu1.addCourseGrade(course=c2, score=59) stu1.addCourseGrade(course=c1, score=79) stu1.showCourseScore()
fc884e1df5110034aff7f2893ea4b629518d77f0
Ayoya22/Learning-Python-HardWay
/ex3-number_maths.py
253
4.34375
4
print("This is a mathematics operation", 5 + 3 / 2 - 4 * 6 % 5) print('Is 5 greater than 2?', 5>2) print("-7 is greater than 5", -7 > 5 ) print("8 is less than or equal to -10?", 8 <= -10) #Simple program to show how python handles mathematical symbols.
be8e012d2d16de7d3e0bf102d5702789bf9ff3a3
hyc121110/LeetCodeProblems
/String/wordBreak.py
1,603
4
4
''' Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. Note: -The same word in the dictionary may be reused multiple times in the segmentation. -You may assume the dictionary does not contain duplicate words. ''' """ The idea is the following: d is an array that contains booleans d[i] is True if there is a word in the dictionary that ends at ith index of s AND d is also True at the beginning of the word Example: s = "leetcode" words = ["leet", "code"] d[3] is True because there is "leet" in the dictionary that ends at 3rd index of "leetcode" d[7] is True because there is "code" in the dictionary that ends at the 7th index of "leetcode" AND d[3] is True The result is the last index of d. """ def wordBreak(s, wordDict): d = [False] * len(s) for i in range(len(s)): for w in wordDict: l = i-len(w) r = i+1 if w == s[l+1:r] and (d[l] or l == -1): d[i] = True return d[-1] s = "catsandog" wordDict = ["cats", "dog", "sand", "and", "cat"] print(wordBreak(s, wordDict)) # adding one element for better optimization def wordBreak2(self, s: str, wordDict: List[str]) -> bool: dp = [False] * (len(s)+1) dp[0] = True for i in range(1,len(s)+1): for word in wordDict: l = i - len(word) r = i if word == s[l:r] and dp[l]: dp[i] = True break return dp[-1]
a7e9d36fec3ebd2c97f9a4e7dfca8da0d79f9509
timothyfranklinpowers/ciss441
/a2.populate.sqlite.PowersTimothy.py
2,382
3.578125
4
import json import csv import sqlite3 import sys dbfile = 'flavors_of_cacao.db' #the database file conn = sqlite3.connect(dbfile) #connect to the database def main(): create_table() #create the table open_file() #open file print('Got it!')#confirmation conn.close() #close the connection sys.exit(1) #a gentle exit def create_table(): """This table is where the csv is going to be loaded to""" c = conn.cursor() strsql=""" CREATE TABLE if not exists cacao ( id INTEGER PRIMARY KEY AUTOINCREMENT, Company text, Specific_Bean_Origin text, REF int, Review int, Cocoa text, Location text, Rating float, Bean text, Broad_Bean_Origin text ); """ c.execute(strsql) conn.commit() def open_file(): """open the csv file and load into the cacao table """ r_ct = 0 with open('flavors_of_cacao.csv', 'r') as csvfile: cacao_stream = csv.DictReader(csvfile) for cacao_row in cacao_stream: r_ct += 1 #quit after 100 records if r_ct > 100: break #pull the data out of the dictionary for sqlite3 t_Company = cacao_row['Company'] t_Specific_Bean_Origin = cacao_row['Specific_Bean_Origin'] t_REF = cacao_row['REF'] t_Review = cacao_row['Review'] t_Cocoa = cacao_row['Cocoa'] t_Location = cacao_row['Location'] t_Rating = cacao_row['Rating'] t_Bean = cacao_row['Bean'] t_Broad_Bean_Origin = cacao_row['Broad_Bean_Origin'] #print the first 15 lines if r_ct <= 15: print (r_ct, t_Company, t_Bean, t_Cocoa, t_Review) #creates a sql cursor, formats the insert sql and executes it c = conn.cursor() strsql = """ INSERT INTO cacao (Company, Specific_Bean_Origin, REF, Review, Cocoa, Location, Rating, Bean, Broad_Bean_Origin) values ( '{t_Company}', '{t_Specific_Bean_Origin}', '{t_REF}', '{t_Review}', '{t_Cocoa}', '{t_Location}', '{t_Rating}', '{t_Bean}', '{t_Broad_Bean_Origin}'); """.format( t_Company = t_Company, t_Specific_Bean_Origin = t_Specific_Bean_Origin, t_REF = t_REF, t_Review = t_Review, t_Cocoa = t_Cocoa, t_Location = t_Location, t_Rating = t_Rating, t_Bean = t_Bean, t_Broad_Bean_Origin = t_Broad_Bean_Origin ) c.execute(strsql) conn.commit() if __name__ == "__main__": main()
ec0ff18ac0d8e6202b0efbe5ae33052dc059524f
smbehura/Pong
/run_pong.py
5,255
3.84375
4
''' Used to run and test Pong ''' import pygame from example_menu import main as menu from example_menu import alt_main as instructions from example_menu import nalt_main as options import time from board_class import Board pygame.init() window_size = [500, 500] # width, height screen = pygame.display.set_mode(window_size) pygame.display.set_caption('Pong') class Game(object): def __init__(self, screen, board, clock): self.screen = screen self.board = board self.clock = clock self.pause = False def update_screen(self): ''' this block of code is used to update the screen image for the user returns None ''' self.screen.fill((0, 0, 0)) self.board.paddles.draw(screen) self.board.balls.draw(screen) self.board.walls.draw(screen) pygame.display.flip() # update screen self.clock.tick(50) def pause_game(self): ''' pauses the game stops movement; stops taking in user input to move the paddles changes the value of self.pause to be the opposite returns None ''' if self.pause: self.pause = False else: self.pause = True def main_loop(self, num_players, num_balls, ball_speed): ''' runs the game once user inputs have been recieved num_players, num_balls, ball_speed = int return None ''' quit = False while not self.board.checkForWin() and not quit: self.update_screen() ###USER INPUT if not self.pause: events = pygame.event.get() for event in events: if event.type == pygame.QUIT: quit = True break if event.type == pygame.KEYDOWN: try: if event.key == pygame.K_COMMA: self.board.paddle[3].move(False) elif event.key == pygame.K_PERIOD: self.board.paddle[3].move(True) elif event.key == pygame.K_c: self.board.paddle[1].move(False) elif event.key == pygame.K_v: self.board.paddle[1].move(True) elif event.key == pygame.K_q: self.board.paddle[2].move(False) elif event.key == pygame.K_a: self.board.paddle[2].move(True) elif event.key == pygame.K_UP: self.board.paddle[0].move(False) elif event.key == pygame.K_DOWN: self.board.paddle[0].move(True) elif event.key == pygame.K_p: self.pause_game() self.update_screen() except Exception: print "Invalid move." events = pygame.event.get() for ball in self.board.ball: ball.move() for object in self.board.objects: if ball != object: ball.changeDir(object) orientation = ball.offScreenOrientation() if orientation != 0: self.board.changeToLoss(orientation) self.update_screen() # update screen for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_p: self.pause_game() elif event.type == pygame.QUIT: quit = True break if self.board.checkForWin(): self.screen.fill((0, 0, 0)) myfont = pygame.font.SysFont("monospace", 40) if self.board.notSinglePlayer(): text = myfont.render("You Won!", 1, (255,255,255)) else: text = myfont.render("Nice Try!", 1, (255,255,255)) self.screen.blit(text, (160,220)) pygame.display.flip() time.sleep(3) pygame.quit() ''' runs the different game menus ''' result = -1 list_result = [] while result == -1: screen.fill((0, 0, 0)) pygame.display.flip() result = menu(screen) if result == 1: #get user values screen.fill((0, 0, 0)) pygame.display.flip() result = 0 list_result = options(screen) if result == 2: #instructions screen.fill((0, 0, 0)) pygame.display.flip() result = instructions(screen) if list_result[0] == 3: #start game input_list = list_result[1] num_players = input_list[0] num_balls = input_list[1] ball_speed = input_list[2] / 2 board = Board(num_players, num_balls, ball_speed) clock = pygame.time.Clock() game = Game(screen, board, clock) game.main_loop(num_players, num_balls, ball_speed)
658844c53687bcc993f9af465d534b1f6a40efa5
powermano/pycharmtest
/leetcode/generateParenthesis.py
894
3.546875
4
class Solution(object): def generateParenthesis(self, n): def generate(p, left, right, parens=[]): if left: generate(p + '(', left - 1, right) if right > left: generate(p + ')', left, right - 1) if not right: parens += p, return parens return generate('', n, n) # def generateParenthesis(self, n): # def generate(p, left, right): # if right >= left >= 0: # if not right: # yield p # # for q in generate(p + '(', left - 1, right): yield q # # for q in generate(p + ')', left, right - 1): yield q # yield from generate(p + '(', left - 1, right) # yield from generate(p + ')', left, right - 1) # # return list(generate('', n, n)) a = Solution() print(a.generateParenthesis(2))
dde9c69797d2273e4796c542aa46ea280f672522
Satyavrath/pythonBasics
/stringLength.py
410
4.0625
4
def string_length(name): count = 0 for string in name: count += 1 return count print(string_length("Hello")) def test_stringLength(): assert string_length("Hello") == 5 assert string_length("myName") == 6 print("The string works fine") test_stringLength() # last letter of string def lastLetter(name): return name[-1] print(lastLetter("Hdfasdfasdf"))
4b41d52dfde3200beddba5cf5d52f9d8ca42cb60
Maan17/python
/Lambda/map()filter()reduce().py
321
3.546875
4
#filter() with lambda li=[5,7,22,97,54,62,77,23,73,61] final_list=list(filter(lambda x:(x%2!=0),li)) print(final_list) #map() with lambda final_list=list(map(lambda x:x*2,li)) print(final_list) #lambda() to get sum of a list from functools import reduce li=[5,8,10,20,50,100] sum=reduce((lambda x,y:x+y),li) print(sum)
e856c339cddfce18b1484bf3ea7aa860c88f71fd
yujinee/scimat2
/science/RotationalMotion/simplerelations/simplerelations.py
2,936
3.84375
4
import random # A girl sitting on a merry go round, moving in counter clockwise through an arc length of s m. If the angular diplacement is r rad, how far she is from the center of merry go round ? # If the wheel of radius r m has a angular velocity of w rad/s, what is the velocity of the point at the circumference of the wheel ? # If a point on the circumference of the wheel rotating with an angular velocity of w rad/s has a velocity of v m/s. What is the radius of the wheel ? # If the wheel of radius r m has a angular acceleration of a rad/s2, what is the accelaration of the point at the circumference of the wheel ? # If a point on the circumference of the wheel rotating with an angular acceleration of aa rad/s2 has a acceleration of a m/s2. What is the radius of the wheel ? qns = open('./questions.txt', 'w') ans = open('./answers.txt','w') no_of_samples = 2500000 def cal1(o1, o2): return round(o1*o2,1) def cal2(o1, o2): return round(o1/o2,1) def type1(): s = random.randint(1,1000) r = random.randint(1,1000) ra = str(cal2(s,r)) + " m\n" q = "A girl sitting on a merry go round, moving in counter clockwise through an arc length of " + str(s) + " m. If the angular diplacement is " + str(r) + " rad, how far she is from the center of merry go round ?\n" return q,ra def type2(): r = random.randint(1,1000) w = random.randint(1,1000) v = str(cal1(w,r)) + " m/s\n" q = "If the wheel of radius " + str(r) + " m has a angular velocity of " + str(w) + " rad/s, what is the velocity of the point at the circumference of the wheel ?\n" return q,v def type3(): r = random.randint(1,1000) aa = random.randint(1,1000) a = str(cal1(aa,r)) + " m/s2\n" q = "If the wheel of radius " + str(r) + " m has a angular acceleration of " + str(aa) + " rad/s2, what is the accelaration of the point at the circumference of the wheel ?\n" return q,a def type4() : v = random.randint(1,1000) w = random.randint(1,1000) r = str(cal2(v,w)) + " m\n" q = "If a point on the circumference of the wheel rotating with an angular velocity of " + str(w) + " rad/s has a velocity of " + str(v) + " m/s. What is the radius of the wheel ?\n" return q,r def type5() : a = random.randint(1,1000) aa = random.randint(1,1000) r = str(cal2(a,aa)) + " m\n" q = "If a point on the circumference of the wheel rotating with an angular acceleration of " + str(aa) + " rad/s2 has a acceleration of " + str(a) + " m/s2. What is the radius of the wheel ?\n" return q,r for i in range(no_of_samples): types = random.randint(0,4) if types == 0: ques,answer = type1() elif types == 1: ques,answer = type2() elif types == 2: ques,answer = type3() elif types == 3: ques,answer = type4() elif types == 4: ques,answer = type5() qns.write(ques) ans.write(answer) qns.close() ans.close()
3780d8293d9ace18020363154098a08d7f4d3362
banana-galaxy/Discord_challenges
/encrypt_decrypt.py
2,569
4.1875
4
# very simple encrypting logic where when you encrypt something like a string, it takes every character in the string takes the places where it appears in the string and puts all that information # together in another string def encrypt(text): # initiating and setting some variables text = str(text) text = list(text) chars = [] chars_check = [] for character in range(len(text)): # checking if we already came across the character chars_check.append(text[character]) if len(chars) >= 1: count_bad = 0 count_good = 0 for char in text: if char == chars_check[len(chars_check)-1]: count_bad += 1 for char in chars_check: if char == text[character]: count_good += 1 if count_bad > 1 and count_good > 1: pass else: # if not then add it to the encryption chars.append(":"+text[character]) for character_count in range(len(text)): if text[character] == text[character_count]: chars.append("."+str(character_count)) else: chars.append(":" + text[character]) for character_count in range(len(text)): if text[character] == text[character_count]: chars.append("." + str(character_count)) result = "".join(chars) return result def decrypt(text): loop = True count = 0 biggest = 0 previous_biggest = 0 result = "" text_list = text.split(':') dictionary = {} for i in range(1,len(text_list)): positions = [] char_positions = text_list[i].split(".") for i2 in range(1,len(char_positions)): positions.append(char_positions[i2]) dictionary[str(char_positions[0])] = '.'.join(positions) for character in dictionary: places = dictionary[character].split(".") for place in places: if int(place) > int(previous_biggest): biggest = place previous_biggest = biggest while loop: for character in dictionary: places = dictionary[character].split(".") for place in places: if int(place) == count: result += character if len(result)-1 == int(biggest): loop = False count += 1 return result encrypted = encrypt('Hi, this is a testing test') print(encrypted) print(decrypt(encrypted))
bf7fa73bf5818682f99e683596c52916abc4ca9a
gavendanoc-learning/terminal
/flows/money.py
400
3.625
4
def piggyBank(): count = 0 history = [] def moneyCounter(amount): nonlocal count # for inmtable variables count += amount history.append(amount) return (count, history) return moneyCounter myPiggyBank = piggyBank() print("total : ", myPiggyBank(10)) print("total : ", myPiggyBank(2)) print("total : ", myPiggyBank(5)) # Tue Aug 18 07:03:21 -05 2020
1a4c1b3275d7a84677003bf28ccee551633989fd
nzsnapshot/car_game_pygame
/car.py
1,931
3.875
4
import pygame class Car(): """A class to manage the car.""" def __init__(self, ai_game): """Initialize the car and set its starting position.""" self.screen = ai_game.screen self.settings = ai_game.settings self.screen_rect = ai_game.screen.get_rect() # Load the car image and get its rect. self.image = pygame.image.load('imgs/car.png') self.rect = self.image.get_rect() # Start each new car at the bottom center of the screen. self.rect.midbottom = self.screen_rect.midbottom self.x = float(self.rect.x) self.y = float(self.rect.y) # Movement flags self.moving_right = False self.moving_left = False self.moving_forward = False self.moving_backwards = False def update(self): """Update the car's position based on movement flags.""" # Update the car's x value, not the rect. if self.moving_right and self.rect.right < self.screen_rect.right: self.x += self.settings.car_speed if self.moving_left and self.rect.left > 0: self.x -= self.settings.car_speed # if self.moving_forward and self.rect.top > 0: # self.y -= self.settings.car_speed # if self.moving_backwards and self.rect.bottom > 0: # self.y += self.settings.car_speed if self.moving_forward: self.y -= self.settings.car_speed if self.moving_backwards: self.y += self.settings.car_speed # Update rect object from self.x. self.rect.x = self.x self.rect.y = self.y def blitme(self): """Draw the car at its current location.""" self.screen.blit(self.image, self.rect) def center_car(self): """Center the car on the screen.""" self.rect.midbottom = self.screen_rect.midbottom self.x = float(self.rect.x)
fce00ef4b8a79e91a392a6509f9d4298eadaf934
shadiqurrahaman/python_DS
/tree/level_order_bottom_up.py
1,549
3.96875
4
class Node: def __init__(self,data): self.data = data self.left = None self.right = None class Tree: def print_tree(self,node): if node is None: return self.print_tree(node.left) print(node.data) self.print_tree(node.right) def levelOrder(self,root): queue =[] result = [] # result.append(root.data) queue.append(root) while(queue): temp = queue.pop(0) result.append(temp.data) if temp.left: queue.append(temp.left) if temp.right: queue.append(temp.right) print(result) def revarse_level(self,root): q1 = [] q2 = [] q1.append(root) result = [] while q1: temp_re = [] while q1: temp = q1.pop(0) temp_re.append(temp.data) if temp.left: q2.append(temp.left) if temp.right: q2.append(temp.right) result.append(temp_re) q1 = q2 q2 = [] return result[::-1] if __name__ == "__main__": root = Node(3) root.left = Node(9) root.right = Node(20) # root.left.left = Node(7) root.right.left = Node(15) root.right.right = Node(7) tree = Tree() # tree.print_tree(root) print("----------") # tree.levelOrder(root) print(tree.revarse_level(root))
e9def8e6e5bb452c5d56a9e887b02963d1c62619
Smoow/MIT-UNICAMP-IPL-2021
/set1/problemas/p1_3.py
195
3.546875
4
dividend = 31 divisor = 5 tmp = divisor rest = 0 counter = 0 while (tmp < dividend): tmp += divisor counter += 1 rest = dividend - (divisor * counter) out = (counter, rest) print(out)
38589327cc90d25c6c82b31fb8081a4d1a5011e4
juliano60/scripts_exo
/ch3/exo2.py
150
3.84375
4
#!/usr/bin/env python3 ## calculate the sum of a list of numbers from 1 to 1000 numbers = range(1,1001) print("Total is: {}".format(sum(numbers)))
23dff04d0b822f7baabdbd6349bf11d4f4e223c4
Luckyaxah/leetcode-python
/二叉树_折纸问题.py
712
4.0625
4
# 给定一个二叉树,返回它的中序遍历。 # 规则:若树为空,则空操作返回,否则从根节点开始(注意不是先访问根节点)中序遍历根节点的左子树,最后访问根节点 # 最后中序遍历右子树 # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def printAllFolds(N): printProcess(1,N,True) # down == True 凹, down == False 凸 def printProcess(i, N, down): if i>N: return printProcess(i+1, N, True) print('凹' if down==True else '凸') printProcess(i+1, N, False) if __name__ == "__main__": N = 3 printAllFolds(N)
742bcbea94c99c058085d3d0fde9ab465a144cd8
mattmaniak/initial_rpg
/src/characters.py
1,650
3.765625
4
from random import randint class __Character(): """A sketch of the all game characters.""" def __init__(self, name, hp, attack, armor, speed): self.name = name self.attack = attack self.armor = armor self.speed = speed self.hp = hp self.__prng_spread = 1 def is_alive(self): return self.hp > 0 def receive_damage(self, enemy): enemy_speed = self.__randomize_attribute(enemy.speed) for i in range(enemy_speed): armor = self.__randomize_attribute(self.armor) enemy_attack = self.__randomize_attribute(enemy.attack) self.hp -= enemy_attack - armor print(self.name + f' (current hp: {self.hp}, lost {enemy_attack - armor} hp' + f' ({enemy_attack} damage - {armor} armor) by' + f' {enemy.name}.') if self.is_alive(): return True else: return False def __randomize_attribute(self, attribute): """Retrun a pseudo-random value with padding of a given attribute. Provide a little pseudo-randomness of the game. """ return randint(attribute - self.__prng_spread, attribute + self.__prng_spread) all = {'Knight': __Character(name='Knight', hp=90, attack=17, armor=7, speed=2), 'Oathbreaker': __Character(name='Oathbreaker', hp=60, attack=14, armor=2, speed=4), 'Wizard': __Character(name='Wizard', hp=120, attack=10, armor=11, speed=3)}
ee8418ec927e244df1019eb7e450d6fce80b4823
wellqin/USTC
/DataStructure/二叉树/二叉树遍历/postOrder.py
2,147
4
4
# -*- coding: utf-8 -*- """ ------------------------------------------------- File Name: postOrder Description : Author : wellqin date: 2020/1/31 Change Activity: 2020/1/31 ------------------------------------------------- """ # 构建了层序遍历: [0, 1, 2, 3, 4, 5, 6]的二叉树 class Node(object): def __init__(self, val): self.val = val self.left = None self.right = None class Tree(object): def __init__(self): self.root = None def add(self, val): node = Node(val) if not self.root: self.root = node else: queue = [self.root] while True: cur_node = queue.pop(0) if cur_node.left is None: cur_node.left = node return elif cur_node.right is None: cur_node.right = node return else: queue.append(cur_node.left) queue.append(cur_node.right) def traverse(self, root): # 层次遍历 if root == None: return [] queue = [root] res = [] while queue: node = queue.pop(0) res.append(node.val) if node.left != None: queue.append(node.left) if node.right != None: queue.append(node.right) return res tree = Tree() for i in range(7): tree.add(i) print('层序遍历:', tree.traverse(tree.root)) # 递归 def postOrder(root): if not root: return [] res = [root.val] left = postOrder(root.left) right = postOrder(root.right) return left + right + res print("Recursive", postOrder(tree.root)) # 迭代 def postOrderIteration(root): if not root: return [] stack = [] res = [] cur = root while cur or stack: if cur: res.append(cur.val) stack.append(cur.left) cur = cur.right else: cur = stack.pop() return res[::-1] print("Iteration", postOrderIteration(tree.root))
3b8ec8f55619e64bd23b260e77fb42119de1099f
ankitk2109/HackerRank
/Data Structures/Day4/leftRotation.py
701
3.828125
4
#Problem Statement: https://www.hackerrank.com/challenges/array-left-rotation/problem #!/bin/python3 import math import os import random import re import sys def leftRotate(n,d,arr): temp = 0 #To store the first element which would be removed in each iteration for i in range(d): #Running loop 'd' times temp = arr.pop(0) arr.append(temp) arr = list(map(str,arr)) #we need string elements to join hence converting each element of list to string. return(" ".join(arr)) if __name__ == '__main__': nd = input().split() n = int(nd[0]) d = int(nd[1]) a = list(map(int, input().rstrip().split())) result = leftRotate(n,d,a) print (result)
8f1e6599be4a5ec6b3a71e0d40470c50803c0e7a
youjiahe/python
/python2/day2/partial_func.py
200
3.53125
4
#!/usr/bin/env python3 from functools import partial # def add(a,b,c,d,e): # return a+b+c+d+e # print(add(10,20,30,40,50)) # newadd=partial(add,10,20,30,40) # print(newadd(99)) # print(newadd(12))
8831cfbdf63c4f8f4745fd8bc71d9458c24e109e
ansonwhho/orbital-chaos
/Revolver.py
9,144
4.4375
4
''' ' R E V O L V E R ' 28/03/2021 Alba Spahiu, Joel Beckles, Anson Ho This is a 3D Gravity simulator: an interactive game, in which the user can create multiple dots at the click of the mouse -> the more the mouse is kept clicked the more the mass. Each dot interacts with each other. There is an initial dot in the centre of the window before the user has clicked, that is the star. It is 1000 times more massive that a dot of the same size. This is to represent the fact that in reality, the Sun holds 99.8% of the mass of our solar system, interacting with objects very small that are very far away (planets). All dots collide with each other if they can, and each influences each other's gravity. If two dots collide their masses and areas will merge into the bigger dot. Install: PyGame --> https://www.pygame.org/news Getting Started: The goal is to find a way to make dots revolve (orbit) around the star and each other. ''' # TODO: Start not affected drastically by merge # TODO: Score Board # TODO: Vector Arrow # Stops frame, repaints existing objects but paints over arrow shape # TODO: Stop Button import pygame import pygame.locals import time import math from sys import exit pygame.display.init() window_dimensions = (1500, 900) Screen = pygame.display.set_mode(window_dimensions) R = (255, 0, 0) G = (0, 255, 0) B = (0, 0, 255) Y = (253, 184, 19) BLACK = (0, 0, 0) WHITE = (255, 255, 255) gravity_constant = 300 dots = [] class Dot: ''' The Dot class determines how dots are created (where, when) and how they interact with each other. Dots, which represent various stars and planets, are created at the click of the user. The longer a dot is clicked, the more massive it will become throut functions specified outside of this class, though user_input. ''' def __init__(self, radius, mass, position, is_star): self.isBehind = False self.isStar = is_star self.color = WHITE self.mass = mass self.location_x = position[0] self.location_y = position[1] self.location_z = - 250 self.velocity_x = 0 self.velocity_y = 0 self.velocity_z = 0 self.radius = radius self.force = [0, 0, 0] def revolve(self, time_change): self.location_x += time_change * self.velocity_x # distance = time * speed # d=vt self.location_y += time_change * self.velocity_y self.location_z += time_change * self.velocity_z if not self.isStar: self.radius = 10 + self.location_z / 50 if self.mass > 0: x_accel = time_change * self.force[0] / self.mass # acceleration = force / mass y_accel = time_change * self.force[1] / self.mass z_accel = time_change * self.force[2] / self.mass self.velocity_x += x_accel # this is so that when self.velocity_y += y_accel self.velocity_z += z_accel self.force[0] = 0.0 self.force[1] = 0.0 self.force[2] = 0.0 def merge_force(self, dot2): x_change = dot2.location_x - self.location_x y_change = dot2.location_y - self.location_y z_change = dot2.location_z - self.location_z rad_s = x_change ** 2 + y_change ** 2 + z_change ** 2 # Pythagorean theorem to find distance r = rad_s ** 0.5 # between two dots. if rad_s == 0: rad_s = 0.00000000001 force_mag = (gravity_constant * self.mass * dot2.mass) / float(rad_s) # F=G*M1*M2/(r^2) else: force_mag = (gravity_constant * self.mass * dot2.mass) / float(rad_s) dx_now = (x_change / r) * force_mag # This determines the displacement of the dots as directly dy_now = (y_change / r) * force_mag # proportional to the gravitational force between two dots. dz_now = (z_change / r) * force_mag self.force[0] += dx_now # This is why the initial force values were set to 0, self.force[1] += dy_now # because it is a function that feeds back to itself self.force[2] += dz_now # and changes force mag based on individual dot interactions. dot2.force[0] -= dx_now dot2.force[1] -= dy_now dot2.force[2] -= dz_now def go_behind(self): star = dots[0] x_change = star.location_x - self.location_x y_change = star.location_y - self.location_y if star != self: distance = math.sqrt(x_change ** 2 + y_change ** 2) add_radius = self.radius + star.radius if distance <= add_radius: if self.location_z - self.radius <= star.location_z + star.radius: self.isBehind = True else: self.isBehind = False else: self.isBehind = False def tell_behind(self): for n in range(len(dots)): self.go_behind() def disappear(self): self.mass = 0 self.radius = 0 def merge(self, dot): if self.radius >= dot.radius: # self.radius += dot.radius / 2 # self.mass += dot.mass dot.disappear() else: # dot.radius += self.radius / 2 # dot.mass += self.mass self.disappear() def dot_merge(self): for n in range(len(dots)): x_change = dots[n].location_x - self.location_x y_change = dots[n].location_y - self.location_y z_change = dots[n].location_z - self.location_z if dots[n] != self: distance = math.sqrt(x_change ** 2 + y_change ** 2 + z_change ** 2) add_radius = self.radius + dots[n].radius if distance <= add_radius: self.merge(dots[n]) def dot_color(self): color = Y max_vz = 255 min_vz = - max_vz scale = (max_vz - min_vz) / 255 c = int(self.velocity_z / scale) + 127 if not self.isStar: if max_vz > self.velocity_z > min_vz: color = (255-c, 0, c) elif self.velocity_z < min_vz: color = R else: color = B return color def revolve_dots(): total = len(dots) for i in range(total - 1): Dot.dot_merge(dots[i]) Dot.tell_behind(dots[i]) for j in range(i + 1, total): dots[i].merge_force(dots[j]) for dot in dots: dot.revolve(0.008) # 0.5/60, time_change per frame def start_timer(): return time.time() def end_timer(old_time): return time.time() - old_time def draw_rectangle(): s = pygame.Surface((1500, 900), pygame.SRCALPHA) # per-pixel alpha s.fill((0, 0, 0, 5)) # notice the alpha value in the color Screen.blit(s, (0, 0)) def draw_star(): pygame.draw.circle(Screen, Y, (int(dots[0].location_x), int(dots[0].location_y)), int(dots[0].radius)) def draw(): draw_rectangle() draw_star() for dot in dots: color = dot_color(dot) if dot.isBehind & (not dot.isStar): pygame.draw.circle(Screen, color, (int(dot.location_x), int(dot.location_y)), int(dot.radius)) draw_star() else: pygame.draw.circle(Screen, color, (int(dot.location_x), int(dot.location_y)), int(dot.radius)) return pygame.display.flip() def user_input(): running = True for event in pygame.event.get(): if event.type == pygame.QUIT: running = False if event.type == pygame.locals.MOUSEBUTTONDOWN: global t, x_i, y_i t = start_timer() x_i, y_i = pygame.mouse.get_pos() if event.type == pygame.locals.MOUSEBUTTONUP: global x_f, y_f x_f, y_f = pygame.mouse.get_pos() print(x_f, y_f) if t > 0.0: time_passed = end_timer(t) new_dot = Dot(10, time_passed, [x_i, y_i], False) new_dot.velocity_x = -(x_f - x_i) new_dot.velocity_y = -(y_f - y_i) new_dot.velocity_z = 0 dots.append(new_dot) return running def main(): Screen.fill(BLACK) central_dot = Dot(40, 4000, (window_dimensions[0] / 2, window_dimensions[1] / 2), True) central_dot.location_z = 0 dots.append(central_dot) dots[0].x_velocity = 0 dots[0].y_velocity = 0 dots[0].z_velocity = - 10 while True: if not user_input(): break revolve_dots() draw() pygame.display.quit() pygame.quit() exit() main()
0f090f590e5798f801bad75ebfeea81bc23b3e49
HyoHee/Python_month01_all-code
/day11/ecercise06.py
723
4.34375
4
""" 创建子类:狗(跑),鸟类(飞) 创建父类:动物(吃) 体会子类复用父类方法 体会 isinstance 、issubclass 与 type 的作用. """ class Animal: def eat(self): print("吃") class Dog(Animal): def run(self): print("跑") self.eat() class Brid(Animal): def fly(self): print("飞") d01 = Dog() d01.run() b01 = Brid() b01.fly() b01.eat() a01 = Animal() print(isinstance(d01, Dog)) print(isinstance(b01, Dog)) print(isinstance(d01, Animal)) print(isinstance(a01, Dog)) print(issubclass(Dog, Animal)) print(issubclass(Animal, Dog)) print(issubclass(Brid, Animal)) print(issubclass(Dog, Brid)) print(type(d01) == Dog)
59ddaae6995f350ea479d199a4fc21dec0a0bebc
ireeX/LeetCode_Python
/Solution/21_Merge_Two_Sorted_Lists.py
1,295
4.15625
4
# Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class LinkedList: def __init__(self, head:ListNode): self.head = head def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: if l1 == None and l2 == None: return None elif l1 == None and l2 != None: return l2 elif l1 != None and l2 == None: return l1 else: if l1.val <= l2.val: head = l1 l1 = l1.next else: head = l2 l2 = l2.next end = head while l1 != None and l2 != None: if l1.val <= l2.val: end.next = l1 l1 = l1.next end = end.next else: end.next = l2 l2 = l2.next end = end.next if l1 != None: end.next = l1 else: end.next = l2 return head def printList(self): node = self.head while node != None: print(node.val, end = " ") node = node.next print() if __name__ == "__main__": node3 = ListNode(2) node2 = ListNode(1, node3) node1 = ListNode(1, node2) ll1 = LinkedList(node1) ll1.printList() node6 = ListNode(6) node5 = ListNode(2, node6) node4 = ListNode(0, node5) ll2 = LinkedList(node4) ll2.printList() ll2.mergeTwoLists(node4, node1) ll2.printList()
1763a56f62053d8c93011f471699426cf3a1bde0
fmaindl/MIT-CS-PS0
/answers.py
1,621
4
4
import numpy import matplotlib initialization=input("Greetings! Let's play a game. I want you to give me two numbers," "and I will tell you how much the first number raised to the power of," "the second number is. I will also tell you what the log in base 2 of," "x is. Wanna give it a try? If yes type 'yes', we'll get started. If not" ", just say 'no'. ") counter=1 if initialization == "yes" or initialization == "Yes": x=float(input("Please enter the first number ")) y=float(input("Please enter the second number... ")) answer1=x**y print(x, "raised to the power of", y, "=", answer1) answer2=numpy.log2(x) print("Log in base 2 of", x, "=", answer2) elif initialization == "no" or initialization == "No": print("Ok then... I'm a bit disappointed to be honest") else: while counter < 5 and (initialization != "yes" or initialization != "Yes" or initialization != "no" or initialization != "No"): initialization2=input("I didn't get that. So do you want to try or not?") counter += 1 if initialization2 == "yes" or initialization2 == "Yes": x=float(input("Please enter the first number ")) y=float(input("Please enter the second number... ")) answer1=x**y print(x, "raised to the power of", y, "=", answer1) answer2=numpy.log2(x) print("Log in base 2 of", x, "=", answer2) break elif counter == 5: print("Ok I give up") break
7a560114b10bf262385c633f27574853f702a58d
zhaochuanshen/leetcode
/Remove_Linked_List_Elements.py
829
3.890625
4
''' Remove all elements from a linked list of integers that have value val. Example Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6 Return: 1 --> 2 --> 3 --> 4 --> 5 Credits: Special thanks to @mithmatt for adding this problem and creating all test cases. ''' # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param {ListNode} head # @param {integer} val # @return {ListNode} def removeElements(self, head, val): extraNode = ListNode(1) extraNode.next = head p = extraNode while p: q = p.next while q and q.val == val: q = q.next p.next = q p = p.next return extraNode.next
562e422693d44784282e90184d8789f595298b5d
prettYPies/LR_1
/5.py
390
3.578125
4
# -*- coding: utf-8 -*- """ Created on Sat Feb 4 22:08:19 2017 @author: joe27 """ i = 0 inText = input("Ваш текст: ") splitText = inText.split() print("Итоговая строка: ") while i < len(splitText): s = splitText[i] if s[0].isupper() == True: splitText[i] = splitText[i].upper() print(splitText[i], " ", sep='', end='', flush=True), i+=1
3ba8ba62a9ba43c77b3ae23e8266536b29d25966
choiwon7/MSE_Python
/ex300.py
646
3.5625
4
per = ["10.31", "", "8.00"] for i in per: #per을 i에 대입한다. try: # 실행코드 print(float(i)) #----->per에 ""가 있어서 실수로 변환이 안되어 오류가 발생할것임. except: #예외가 발생할경우 print(0) #0으로 표현해라 else: #예외가 발생하지않으면 print("clean data") #clean data를 실행해라 finally: #예외가 발생하던말던 print("변환 완료") #변환완료 출력하기. #10.31 clean data 변환완료 , 0 변환완료 , 8.00 clean data 변환완료 이렇게 됌.
bbc8393f8f7b35039319123bace3bac1a20a66da
XingXing2019/LeetCode
/LinkedList/LeetCode 61 - RotateList/RotateList_Python/main.py
1,084
3.828125
4
# Definition for singly-linked list. from typing import List class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def rotateRight(head: ListNode, k: int) -> ListNode: if head is None: return head def getLen(head: ListNode) -> int: res = 0 while head is not None: res += 1 head = head.next return res fast, slow = head, head len = getLen(head) k %= len if k == 0: return head for i in range(k): fast = fast.next while fast.next is not None: fast = fast.next slow = slow.next res = slow.next slow.next = None fast.next = head return res def generate(nums: List[int]) -> ListNode: res = None for i in range(len(nums) - 1, -1, -1): res = ListNode(nums[i], res) return res nums = [1] head = generate(nums) print(rotateRight(head, 1))