blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
3116e38d76b7c3fc580a2ae08210590554b2a8e9
ivanrp05/Ivanindra-Rizky-Pratama_I0320054_Tiffany-Bella_Tugas9
/I0320054_Exercise9.8.py
403
3.546875
4
#Mulai print("") print("Exercise 9.8") print("Nama : Ivanindra Rizky P") print("NIM : I0320054") print("") print("===========================") print("") print("Jawab :") >>> #mengonversi list ke dalam array.array >>> li = [10,20,30,40,50] >>> C = array.array('i') >>> C.fromlist (li) >>> type(C) <type 'ar...
5fdf4320e124078dff1eb7cfaa77a4519668f218
tomcroll/mitpython
/isIn.py
789
4.03125
4
def isIn(char, aStr): ''' char: a single character aStr: an alphabetized string returns: True if char is in aStr; False otherwise ''' # Your code here if aStr == '': return False mid = len(aStr) / 2 if aStr[mid] == char: return True elif char < aStr[mid]: ...
12daee0834e9d08d29f2716dc8cace74dd710e1a
DincerDogan/Hackerrank-Codes
/Python/company-logo.py
1,779
4.1875
4
''' Company Logo https://www.hackerrank.com/challenges/most-commons/problem A newly opened multinational brand has decided to base their company logo on the three most common characters in the company name. They are now trying out various combinations of company names and logos based on this condition. Given a strin...
82a3c58149dbf05008e7845185134c5060196adf
Uditendu/Python_Files
/Count_Occurance.py
535
4
4
"""Module to count how many times check appears in a String """ def count_occurance(txt, check): Alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ-123456789' txt+=' ' l = len(check) n=0 i=0 j=0 while i<(len(txt)-l+1): if txt[i]==check[0]: if txt[i:i+l]==check and txt[i-1].upper() n...
7d900b9d8a49c9f3b4753b7c8effd72764ddbbf6
sweenejp/learning-and-practice
/treehouse/python-beginner/monty_python_tickets.py
1,349
4.15625
4
SERVICE_CHARGE = 2 TICKET_PRICE = 10 tickets_remaining = 100 def calculate_price(number_of_tickets): # $2 service charge per transaction return (number_of_tickets * TICKET_PRICE) + SERVICE_CHARGE while tickets_remaining > 0: print("There are only {} tickets remaining!\nBuy now to secure your spot for th...
ed0990ab618588058e59a675e1e1b48c19384b6a
RoncoLuis/artificial_neural_net
/scripts/SIngle-Layer Net.py
356
3.671875
4
""" Single-Layer Net -> red de capa simple """ x1 = [1,1,0,0] x2 = [1,0,1,0] w1 = 1 w2 = 1 umbral = 2 for i in x1: sum = (x1[1]*w1)+(x2[i]*w2) print("sumatoria: ",sum) if sum > umbral: print("se dispara neurona ->",1,":",i) elif sum <= umbral: print("no se disparo neurona ->",0,":",i) ...
b2993132593b941ba3da41fae670e742755edb8b
chaecramb/exercism
/python/clock/clock.py
889
3.734375
4
class Clock: def __init__(self, hours, minutes): self.hours = hours self.minutes = minutes self.time = None def __str__(self): return self.clock_time() def __eq__(self, other): if isinstance(other, self.__class__): return self.clock_time() == other.clock_time() else: ret...
88ee6cb20d480c28058469fd99b5dca8243ca1b1
Kaifee-Mohammad/labs
/PythonLab/datas.py
523
3.9375
4
# tuples days = ('Sun', 'Mon', 'Tues', 'Wed', 'Thur', 'Fri', 'Sat') # print(type(days)) # print(days) # lists junk = ['this is a string', 'second word', 22, 44, 5.5] # print(type(junk)) # print(junk) # dictionary emp = {"Kaifee Mohammad": "kaifee@microsoft.com", "Chris": "chris@microsoft.com"} # print(type(emp...
cece0912a682e6a162e2c19da04069d5bc140977
ShinW0330/ps_study
/01_Brute_Force/Level4/9663.py
1,033
3.5
4
# N-Queen # https://www.acmicpc.net/problem/9663 # 힌트 : 세로줄은 column 값으로 확인가능 # 대각선(\)은 row - column + N - 1 값으로 확인 가능. # Skew-대각선(/)은 row + column 값으로 확인 가능. # 해당 방법은 pypy3으로 컴파일 해야 시간 초과되지 않음. def dfs(r): global answer if r == N - 1: answer += 1 return for j in range(N): ...
4c3dad60ea0dee8ed68c6c7ee8f612e99235febc
demeth0/REPO_CS_P2024
/Python Project/TD/Archive/Samuel/fibonacci.py
278
3.5625
4
# -*- coding: utf-8 -*- """ Spyder Editor """ #suite de fibonacci def fibonacci(n): f0 = 0 f1 =1 fi = 0 if(n == 1): fi = f1 for i in range(2, n+1): fi = f0 +f1 f0 = f1 f1 = fi print(fi)
4bae997e61c31f0a5987411c1778eaac703c10fa
JosephLevinthal/Research-projects
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/223/users/4184/codes/1595_825.py
307
3.796875
4
# Teste seu codigo aos poucos. # Nao teste tudo no final, pois fica mais dificil de identificar erros. # Nao se intimide com as mensagens de erro. Elas ajudam a corrigir seu codigo. from math import* r=float(input("insira o valor de r:")) a= pi*(r**2) v= 4/3*pi*(r**3) print(round(a,3 )) print(round(v,3 ))
c1d083198693ddb34e9cb53e4c87110ee7d75609
tazeemsyed/python-flask-assignment
/day2.py
1,904
4.53125
5
#code for changing data type from integer to string using python n = 12 print (type(n),n) n = str (n) print (type(n),n) #code for changing data type from integer to float using python n = 12 print (type(n),n) n = float (n) print (type(n),n) #code for changing data type from integer to boolean using python n ...
bd3feeafc0b5377b88dd4fba42fc905f63fc242e
indranildchandra/ML101-Codelabs
/src/linear_regression_example1.py
2,552
3.671875
4
import collections stepSize = 0.01 # learning rate def read_data() : data = open("./../resources/vehicle_sale_data.csv" , "r") gdp_sale = collections.OrderedDict() for line in data.readlines()[1:] : record = line.split(",") gdp_sale[float(record[1])] = float(record[2].replace('\n', "")) ...
27c9edf0ec8926443c66e98dc6eb9a9fd748dcf3
michelgalle/hackerrank
/CrackingTheCodingInterview/20-BitManipulation-LonelyInteger.py
285
3.546875
4
#!/bin/python3 import sys def lonely_integer(a): n = 0 for i in a: #xor negando os numeros, assim sobra somente o numero unico n ^= i return n n = int(input().strip()) a = [int(a_temp) for a_temp in input().strip().split(' ')] print(lonely_integer(a))
1770806d218ad6c114727f4244274cc2236c6ec9
HyeonJun97/Python_study
/Chapter08/Chapter8_pb1.py
575
3.640625
4
number=input("주민번호를 입력하세요: ").strip() if len(number)!=14: print("주민번호가 올바르지 않습니다.") else: for i in range(len(number)): test=True check=ord(number[i]) if i==6: if check!=45: test=False else: if check<48 and check>57: ...
cdf82c036d1761d8887960b12c685dd96adb81fa
frclasso/acate18122018
/01_Sintaxe_Basica/11_set.py
893
4
4
#!/usr/bin/env python3 # Sets cs_courses = {'History', 'Math', 'Physics', 'CompSci', 'Chemistry'} art_courses = {'History', 'Design', 'Art', 'Math'} '''Interseção (tem em ambos)''' print(cs_courses.intersection(art_courses)) # Math, History '''Diferença, o que tem em cs_courses e nao tem art_courses''' print(cs_...
1d1bfcd574c19cfa0810728e2579fb04ea3edf01
danielliu000/MyPythonLearning
/7_Reverse_Integer.py
754
3.890625
4
'''Given a 32-bit signed integer, reverse digits of an integer.''' class Solution: def reverse(self, x: int) -> int: import math if -math.pow(2,31) < x < math.pow(2,31)-1: if x > 0: result = int(str(x).rstrip('0')[::-1]) if result < math.pow...
0bd66d6bcb68afe3c44995adee36ee5f95c58386
YoByron/generative-art
/src/utils/unsplash.py
1,075
3.640625
4
import urllib import requests def query_unsplash( api_key: str, search_term: str, max_number_of_images: int = 30, page_number: int = 1 ) -> dict: """ Given a search term, queries pixabay for free-use images, returning less than or equal to the max_number_of_images. :param api_key: (str...
f3a4a1ce6cf8d44c74b7756882fbc8953b7cf1ac
Rivarrl/leetcode_python
/leetcode/offer/36.py
1,046
3.546875
4
# -*- coding: utf-8 -*- # ====================================== # @File : 36.py # @Time : 2020/5/6 20:54 # @Author : Rivarrl # ====================================== # [面试题36. 二叉搜索树与双向链表](https://leetcode-cn.com/problems/er-cha-sou-suo-shu-yu-shuang-xiang-lian-biao-lcof/comments/) from algorithm_utils import * ...
31e2a60896dc26743492494e8e887bed429f9814
mbreedlove/project-euler
/Python/euler3.py
315
3.5
4
#!/usr/bin/env python3 from math import sqrt num = 600851475143 p = 1 for i in range(2, int(sqrt(num))): if num % i == 0: is_prime = True for n in range(2, int(sqrt(i)) + 1): if i % n == 0: is_prime = False if is_prime == True: p = i print(p)
b2a8c9b9590a13570ee4b04e69693b155632db30
nashashibi/coding-interview-solutions
/py/BST_zigzag_order_traversal.py
1,350
3.640625
4
from collections import deque class Node(object): def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right def zigzag_order(self): q = deque([None, self]) popLeft = False order = [] while len(q): if popLeft: node = q.popleft() else: ...
03007a91f57356bf2f8bcfb6649020f08666f59e
Zugwang/PrepaGithub
/TD2/ex7.py
886
3.640625
4
def addition(i): return i + 2 def apply_function_global(t,f): for i in range(len(t)): t[i] = f(t[i]) def apply_function(t,f): t2 = t.copy() for i in range(len(t2)): t2[i] = f(t[i]) return t2 def triplet_des(): list = [] for i in range(1,7): for j in range(1,7): ...
d4fc9bc982916da6bb8a7f16f86b150804acb3a5
aviadr1/learn-python3
/content/_build/jupyter_execute/08_test_driven_development/exercise/questions.py
2,353
3.71875
4
#!/usr/bin/env python # coding: utf-8 # # <a href="https://colab.research.google.com/github/aviadr1/learn-advanced-python/blob/master/content/08_test_driven_development/exercise/questions.ipynb" target="_blank"> # <img src="https://colab.research.google.com/assets/colab-badge.svg" # title="Open this file in Goo...
9ab57a37c993a7f3216244d5e13f8f996a095b23
dr-ehret/examples
/regarding_args.py
379
3.671875
4
def print_twice(bruce): # parameter bruce is for definition only. print(bruce) print(bruce) print_twice('caleb') # It can be any argument. tosh = "Peter Tosh, that is..." # Use of variable. print_twice(tosh) ## def cat_twice(part1, part2): cat = part1 + part2 print_twice(cat) y = "Hey, hey, my, ...
0222b8403a51a1b50eeccf0e47bfb213b1f345f8
kwintasha/bataille-navale
/bataille navale/bataille navale amin.py
1,925
3.578125
4
from random import randint,choice from turtle import * reset() setup(405,405,50,50) speed(10) hideturtle() ordi1=() ordi2=() colonnes=("a","b","c","d","e","f","g","h") lignes=("1","2","3","4","5","6","7","8") def plouf(col,lign,coul): up() x=-160+(ord(col)-97)*40 y=160-(ord(lign)-48)*40 ...
eea378921a111c7a93a483b104deb3857a473b80
ArthurGini/EstudosPython
/Processsos Estagio/Strings.py
534
3.875
4
import re #Determinar a maior palavra em uma string print ("\nprograma 1: Exibir a maior palavra ") string = "Aquela boa e velha frase" string = string.split() print(max(string, key=len)) #Transformar a string em Camel Case print ("\nprograma 2: Editar frases para Camel Case") camel = "camel case bom e velho" camel ...
3dbd10a141f84dfd148cd0de86aec7e5ea5a5aec
mabogunje/preschool-poker
/PreschoolPoker.py
5,642
3.59375
4
''' author: Damola Mabogunje contact: damola@mabogunje.net summary: This program allows the user to pit a Reinforcement learning AI against one of four opponents in a game of PreschoolPoker multiple times to allow the AI to learn an optimal strategy. ''' import argparse; from poker import StudPoker...
42e463c60b8cca356ae31d70542b98bed9b4691c
GaryVermeulen/gdata
/data_structures/tree3.py
7,756
4.15625
4
# Data and structures (classes, lists, tuples, hashes, dicts, hybirds) # class Node: def __init__(self, data): self.left = None self.right = None self.data = data def insert(self, data): # Compare the new value with the parent node # Original recursive code ...
10489d194279d9da63df299d9a7a0e5061a21c27
JoelAtDeluxe/DailyCodingProblem
/7/solution.py
2,010
3.8125
4
# Given: # coding = { # "a": "1", # "b": "2", # ... # "z": "26" # } # how many ways are there to decode a particular message? # for example, we could be given the message: # "abc", which encoded is "123" # But going in reverse, to decode, we could end up with: # (a, b, c), (a, w), (l, c) # Given "cab" (312) we could on...
2d126c0c9623452ad88783cd6de9f0595acd17da
Vitalismirnov/Problem_Set
/problem9.py
850
3.9375
4
# This is a work by # Vitalijs Smirnovs # Stydent ID # g00317774 # Problem 9: Write a program that reads in a text file and outputs evry secondline. # The program should take the filename from an argument on the command line. # open a text file, save as openfile # openfile = open('theinvisibleman.txt') # to read fi...
54122d064370dc4e4e5f84adbd5c78c862128b3d
libo-sober/LearnPython
/day24/__call__方法.py
563
3.90625
4
# callable(对象) # 对象() 能不能运行,就是callabele判断的事 class A: def __call__(self, *args, **kwargs): print('---------------') obj = A() print(callable(obj)) obj() # 对象加括号调用类中的__call__方法 # A()() # __len__ class Clas: def __init__(self, name): self.name = name self.students = [] def __len__(se...
be07019bc55be95a2a00065a83a6fe413fdde0c4
suhanacharya/student-db-demo
/database.py
644
3.703125
4
import sqlite3 def init_db(): with sqlite3.connect("student.db") as conn: c = conn.cursor() c.execute(""" CREATE TABLE Students( name TEXT, usn TEXT PRIMARY KEY, sem INT ); ...
9825987008b446218528fd008985ff8609a386cf
jonathf/numpoly
/numpoly/array_function/square.py
1,798
3.875
4
"""Return the element-wise square of the input.""" from __future__ import annotations from typing import Any, Optional import numpy from ..baseclass import ndpoly, PolyLike from ..dispatch import implements from .multiply import multiply @implements(numpy.square) def square( x: PolyLike, out: Optional[ndpoly...
704a26c6cb9e86a4ccf61abe9aeeb04615bad60a
Seezium/Algorithms
/GetTheMiddleChar/GetTheMiddleChar.py
250
3.78125
4
def get_middle(s): x = len(s)//2 if len(s) % 2 == 0: return "{}{}".format(s[x-1],s[x]) else: return s[x] print(get_middle("test")) print(get_middle("testing")) print(get_middle("middle")) print(get_middle("A"))
6133c44c5f99072ba95ce384aea4d9a619791aab
ISFP1021/Lecture7inclass
/L7E4.py
153
3.8125
4
def printlist(title, alist): print (title) for i in alist: print (i) somelist=[1,45,87,'go'] title="The Title" printlist(title,somelist)
ee5cbf7e426223a464a8770d03e958d9abce3118
MarkintoshZ/FontTransformer
/demo/gui.py
5,122
3.796875
4
import pygame, math, sys pygame.init() from model import evaluate, refresh import numpy as np X = 900 # screen width Y = 600 # screen height WHITE = (255, 255, 255) BLACK = (0, 0, 0) RED = (255, 50, 50) YELLOW = (255, 255, 0) GREEN = (0, 255, 50) BLUE = (50, 50, 255) GREY = (200, 200, 200) ORANGE = (200, 100, 50) ...
25b7ab214d5628a0246a6e63226323789a46fb94
Alkhithr/Mary
/BUCI057N0/recap/exam2014.py
1,379
3.8125
4
def compute_sum(L): total = 0 for i in range(0, len(L)): if i % 2 == 0: total += L[i] else: total -= L[i] return total def get_fib(n): fib = [0, 1, 1] i = 3 while len(fib) <= n: fib.append(fib[i-1] + fib[i-2]) i += 1 return fib[n], fi...
096120ce265e99413660d6ee1974782b351e4ee3
ItamarHavenstein-zz/Python
/Exercicio41a50/ex049.py
145
3.734375
4
tabuada = int(input('Digite a tabuada que vc deseja: ')) for c in range(1, 11): print('{} X {} = {}'.format(tabuada, c, (tabuada * c)))
0dd6822ea8b887d410e9da7f526ac8d69f12f629
Pattol/20F_CST8279_300-Intro-to-Comp.-Prog.-using-Python
/Random.py
295
4.03125
4
# Pattol Albadry # Sep 17.2020 # Lab 2: Demo code from random import randint roll = input("press Y to roll the dice, press N to quit") while roll.lower () == "y": print(randint(1,10)) roll = input("press Y to roll again, press N to quit") print("okay, we'll put the dice away.")
e131cb909698c19f74df6babd2cb2da072ec6993
varunverma760/Python
/patterns.py
158
4.15625
4
print("Enter the value of n") n=int(input()) i=1 while i<=n: j=1 while j<=n: #print the jth column print('*',end='') j=j+1 print() i=i+1
8fdb8cbe0a0f0db586c55dc6bb4e483b4e1d3953
ASKJR/URI-judge
/Python/2803.py
262
3.515625
4
''' Problem: Estados do Norte URI Online Judge | 2803 Solution developed by: Alberto Kato ''' northStates = ['roraima', 'acre', 'amapa', 'amazonas', 'para', 'rondonia', 'tocantins'] if input() in northStates: print('Regiao Norte') else: print('Outra regiao')
c1e5dba8045f1443b7a9693a0663c109a40657d0
eladeliav/PythonProjects
/School2018PY/Slicing2.py
480
3.96875
4
"""Slicing Exercises Elad Eliav""" def analyze_number(): """ gets number and analyzes """ num = raw_input("Enter num: ") diglist = list(num) # Create list of ints for the number sum_of_digs = sum([int(r) for r in diglist]) print("You entered: " + num) print("The digits: " + ", ".j...
551c877a2da034b6ea820791ab5bb22f7decba17
MayankHirani/PowerWorld2019
/PowerWorld Work Summer 2019/Other/old_method.py
1,030
3.5
4
# Old way of timing (Outdated) # Number of values that the average will be calculated from. The more # values used, the more accurate results will be. Adjust this value if # runtime is too long or too short precision = 100 # Make a list of timings to get a more accurate mean timings = [ timeit.timeit('solve...
e19b7ab0f7defb696c9f8185c5c74399190051d7
jgathogo/python_level_1
/week3/problem6.py
3,980
4
4
import os import sys import math """ Notes: - Excellent job! I'm glad that you figured out the correct equations to compute the internal angles. I see that this has also forced you to read up on Python math library. This is exactly the kind of activity by which someone grows, not just attending class but solving pro...
53694c19010288180b97649fd680afe56e3c2bc2
harihavwas/pythonProgram
/fUNCTIONAL PROGRAMMING/Lambda/demo.py
387
3.9375
4
# To reduce code ''' def cb(n): print("Result : ",n**3) n=int(input("Enter number : ")) cb(n) ''' # Cube ''' cube=lambda n:n**3 print(cube(5)) ''' # Addition ''' add=lambda a,b:a+b print(add(2,3)) ''' # String ''' str=lambda s:s[0] print(str(input("Enter String : "))) ''' #even or not demo=lambda n:n%2 if(dem...
1dd51c30c17143c7ecd61ae1125b7fd1c4dab7de
u101022119/NTHU10220PHYS290000
/student/101022109/mydate.py
1,529
3.921875
4
class Date : def __init__(self,x,y,z): self.day = int(x) self.month = int(y) self.year = int(z) def print_date(self): print '{0} / {1} / {2}'.format(self.month,self.day,self.year) def increment_date(self,n = 0): x,y,z = self.day , self.month , self.year x += n...
75613981f87492df53ecd826667419a8255f7477
muffinsofgreg/mitx
/6.1/fibN.py
341
4.15625
4
from math import sqrt N = int(input("\n List Fibonacci sequence to nth place.\n What is your n: ")) def fib(n): #Binet's formula fib_list = [] root = sqrt(5) phi = (1 + root) / 2 for n in range(0, n): bin = str(round(phi ** n / root)) fib_list.append(bin) return fib_li...
436ec22015f1ccd88e286cf95e4adfbd727738ac
pyc-ycy/PycharmProjects
/untitled/类的特有方法/WeatherSearch.py
1,629
3.609375
4
#!/usr/bin/env python3.7 # -*- coding: utf-8 -*- # @Time : 2018/9/8 10:15 # @Author : 御承扬 # @Site : # @File : WeatherSearch.py # @Software: PyCharm class WeatherSearch(object): def __int__(self, input_daytime): self.input_daytime = input_daytime def search_visibility(self): visible_lea...
5ce92b5223a88d2961572192a10d9b13ead2ed39
domagojeklic/lunchbot
/orders.py
6,456
3.953125
4
class Meal: ''' Holds information about individual meal orders ''' def __init__(self, name: str, price: float, user: str): self.name = name self.price = price self.users = [user] def add_user(self, user: str): self.users.append(user) def total_number(self) -...
db76a6dd791a2fd8c487bd027286e32b5dee7570
sidaker/dq
/python_ques/global_scope.py
1,068
3.984375
4
## Question. What happens if you don't define a variable as global. ## Scopre can be ## - LOCAL(inside current function), Enclosing, GLOBAL, Built-in (LEGB) ## you bind a name to an object ## Name resolution to objects is manged by scopes and scoping rules. # https://www.programiz.com/python-programming/names...
7d232966299b1355d974d4395e58e40f2fcacc08
jamil-said/code-samples
/Python/Python_code_challenges/digitsProduct.py
826
3.765625
4
""" digitsProduct Given an integer product, find the smallest positive (i.e. greater than 0) integer the product of whose digits is equal to product. If there is no such integer, return -1 instead. Example For product = 12, the output should be digitsProduct(product) = 26; For product = 19, the output sh...
1f91d44ec43d5038a0379e57dd79660fcc719f2f
baejinsoo/algorithm_study
/algorithm_study/DataStructure/07_스택_완전구현.py
891
3.828125
4
## 함수 선언부 def isStackEmpty(): global stack, top, SIZE if (top <= -1): return True else: return False def isStackFull(): global stack, top, SIZE if (top >= SIZE - 1): return True else: return False def push(data): global stack, top, SIZE if (isStackFull...
1acb2b936ee727d7bfa1062d299f1404488cb08a
lingdingjun/learngit
/fxxcx.py
140
3.9375
4
def f(x): if x==0: return x else: return f(x-1)*2+x*x x = int(raw_input ('请输入x:')) #需要用int,否则为str print f(x)
437b356a1b598f6dcb02fbf532b256162bf76e0e
DragonfireX/python-_exercises_and-notes
/range_over_looping.py
591
4.375
4
for num in range(1, 10): print(num) for num in range(1, 10, 2): print(num) """ looping through ranges set number of times you want to loop through the data set but limit it the code on top range takes 2 -3 arguments add the colon at the end it iterates over the range and prints 1 2 3 4 5 6 7 8 9 a range work...
a08da175eea635569bafac40cbf8976825bbe6ce
arita37/eai-spellchecker
/spellchecker/helpers.py
5,662
3.75
4
import csv import re from os import path from typing import List def null_distance_results(string1, string2, max_distance): """Determines the proper return value of an edit distance function when one or both strings are null. """ if string1 is None: if string2 is None: return 0 ...
6b465f1a90aafe2bf3eaa9ee7ca4ec66cba18c09
BrainLiang703/Python-
/Dict
1,143
3.5625
4
#!/usr/bin/env python #coding:utf-8 a = {'name':'Brain','age':'4'} print(len(a)) #len显示字典里元素的数量 b = a print(b) c = a.copy() # 效果和b = a 一样 print(c) c.clear() # clear 把整个字典删除 print(c) del c #删除整个字典,内存也释放。再调用这个元组就会报错 print(a.get("name")) # get通过键获取值,取不到值则返回空值,但是如果用a["name"],假如找不到值,会出现异常。 a.setdefault("Addr","HUIZHOU") #...
c3a5b3dc982e02d760d3eb979a23ee9f7f86fec7
pb1729/differential-equations
/stringtofunc.py
1,646
3.65625
4
import math ''' #testing code: class dummy: val = 0.0 def __init__(self, v): self.val = v print tofunction("( + ( sin a ) pi )")({"a":dummy(1)}) ''' def tofunction(s): tokens = s.split() return listtofunc(tokens, []) def isnumber(s): try: a = float(s) return True excep...
741cfac01914981433e664a2c58e4faf9970cfe3
hyeinkim1305/Algorithm
/SWEA/D2/SWEA_5178_노드의합.py
1,079
3.640625
4
''' 10 5 2 8 42 9 468 10 335 6 501 7 170 ''' def nodesum(idx): # 후위방식 global tree if idx <= N: nodesum(idx * 2) nodesum(idx * 2 + 1) if idx * 2 + 1 <= N: # 자식 노드가 N안에 있으면 tree[idx] = tree[idx * 2] + tree[idx * 2 + 1] if idx * 2 == N: # 자식...
90cf38209c965dba5aaf7c226f0ede2292af77b1
Alf0nso/NN-Games
/NN/nn_sum_demo.py
1,036
4.34375
4
# Neural Network Demo # # @Author: Afonso Rafael & Renata # # Demo demonstrating neural network implementation # learning how to sum two numbers, (exciting I know). # Can be used to understand how can be used and # altered to be able to map other functions. import neural_net as nn import numpy as np from random import...
c8875efdcd1664a5258c47d99d2c846fada728f7
abrahamsk/ml_naive-bayes-classification
/src/naive_bayes.py
6,001
3.90625
4
#!/usr/bin/env python # coding=utf-8 # Machine Learning 445 # HW 4: Naive Bayes Classification # Katie Abrahams, abrahake@pdx.edu # 2/25/16 from __future__ import division from probabilistic_model import * import math import timing # time program run """ 3. Run Naïve Bayes on the test data. - Use the Naïve Bayes alg...
3f8ae31e6c67fd1eb75d0023bbe97e6918649602
rgeos/rss
/classRSS.py
3,310
3.640625
4
#!/usr/bin/env python # _*_coding: utf-8 _*_ import feedparser as rss import classRegex as reg class classRSS(object): """ Retrieving some of the elements of an RSS feed """ def __init__(self): self.urls = "" # the URLs will be in a string self.feed = {} # a dictionary of f...
da1b95842fc8d3f7ddc782f47cfd01a0fb0097d6
KJanmohamed/Year9DesignCS4-PythonKJ
/GUIRadioButtons.py
767
3.59375
4
import tkinter as tk root = tk.Tk() v = tk.IntVar() tk.Label(root, text="""Choose a player:""", justify = tk.LEFT, padx = 20).pack() tk.Radiobutton(root, text="Player 1", padx = 20, variable=v, value=1).pack(anchor=tk.W) tk.Radiobut...
c5ea69cd9429b22a09ddc2f03d278659bb73ff3b
staryjie/Full-Stack
/test/score_demo.py
361
3.828125
4
#!/usr/bin/env python # -*- coding:utf-8 -*- score = int(input("Pls enter yur score: ")) if score > 100: print("分数不能超过100!") elif score >= 90: print("A") elif score >= 80: print("B") elif score >= 60: print("C") elif score >= 40: print("D") elif score >=0: print("E") elif score < 0: print(...
fa4180706cff4f283bbfe228a12702eccc23c1ce
lsn199603/leetcode
/27-最小路径和.py
946
3.640625
4
""" 给定一个包含非负整数的 m x n 网格 grid ,请找出一条从左上角到右下角的路径,使得路径上的数字总和为最小。 说明:每次只能向下或者向右移动一步。 输入:grid = [[1,3,1],[1,5,1],[4,2,1]] 输出:7 解释:因为路径 1→3→1→1→1 的总和最小 四种情况: 1. i=0, j=0 dp[i][j] = grid[i][j] 2. i=0, j!=0 dp[i][j] = grid[i][j] + dp[i][j-1] 3. i!=0, j=0 dp[i][j] = grid[i][j] + dp[i-1][j] 3. i!=0, j!=0 dp[i][j] = min(grid[i]...
905ff0c1ca0d7a4a47e94d6913486279ce35c2c4
Benzsoft/Python-Stuff
/Apps/Mario_kart.py
2,092
3.609375
4
racers_list = [{'name': 'Peach', 'items': ['green shell', 'banana', 'green shell', ], 'finish': 3}, {'name': 'Bowser', 'items': ['green shell', ], 'finish': 1}, {'name': None, 'items': ['mushroom', ], 'finish': 2}, {'name': 'Toad', 'items': ['green shell', 'mushroom'], 'fini...
c7c0d89415503cfed42baf4b8280e052a918f062
MEng-Alejandro-Nieto/Python-for-Data-Science-and-machine-Learning-Udemy-Course
/15. E-commerce purchases Exercises with pandas.py
2,240
4.28125
4
import pandas as pd table=pd.read_csv('/home/alejandrolive932/Desktop/Udemy_Data_Science_and_Machine_Learning/Refactored_Py_DS_ML_Bootcamp-master/04_Pandas_Exercises/Ecommerce Purchases') print(table.info()) # 1. Check the head of the DataFrame print(table.head()) # 2. How many columns and rows there are print(f"...
95da4189cd1ddd2aaeee6737b2b3d93461d3dd92
01-Jacky/ConnectedEmployers
/connected_employer/sandbox.py
657
4.03125
4
class Data(object): """ Data Store Class """ products = { 'milk': {'price': 1.50, 'quantity': 10}, 'eggs': {'price': 0.20, 'quantity': 100}, 'cheese': {'price': 2.00, 'quantity': 10} } def __get__(self, obj, klas): print("(Fetching from Data Store)") return {'pr...
71d6e4ceed4e2d2d56f3e758f3f1ff3adf22c002
wallacewd/Brick-s-Instant-Messenger-v0.1
/client.py
1,479
3.546875
4
""" Basic Instant Messaging Application Version 0.1 Author: Dan Wallace (danwallaceasu@gmail.com). Creates a peer to peer connection on a local network allowing real-time chat. Server.py must be running in order for both files to run. Server.py creates a server that is only active when the code is running. 08/23/2020 "...
02f578deff28fa7b32125e550584a0a7d9f2a20b
suhas-nithyanand/Text-Summarization-MMR
/sentence.py
842
3.75
4
class sentence(object): '''This module is a sentence data structure''' def __init__(self, docName, stemmedWords, OGwords): self.stemmedWords = stemmedWords self.docName = docName self.OGwords = OGwords self.wordFrequencies = self.sentenceWordFreqs() def getStemmedWords(sel...
2e457180eb42bc06f9c4319b460fc36654cc0448
Hunter-Dinan/cp1404practicals
/prac_09/sort_files_1.py
1,416
4.15625
4
"""Program that sorts files into directories based on their file type.""" import os import os.path import shutil FILE_TYPE_INDEX = 1 def main(): """Program that creates directories for each file type and stores the corresponding files within it.""" os.chdir('FilesToSort') file_names = os.listdir('.') ...
dc42e33e5a831ab6b6fce6d6ad2e2199682d280d
ArnoutSchepens/Python_3
/Oefeningen/OOP python/OOP 2/OnlyIntegers.py
340
3.640625
4
from functools import wraps def only_ints(fn): @wraps(fn) def wrapper(*args, **kwargs): if not all([isinstance(x, int) for x in args]): return "Please only invoke with integers" return fn(*args) return wrapper @only_ints def add(x, y): return x + y print(add(1, 2)) ...
5d9a500f7a7b95cf932827d5a9e271839cc26832
nicoleorfali/Primeiros-Passos-com-Python
/p37.py
619
3.890625
4
# Cálculo de IMC peso = float(input('Digite o seu peso (kg): ')) altura = float(input('Digite a sua altura (m): ')) imc = peso / (altura ** 2) if imc <= 18.5: print(f'O IMC é de {imc:.2f}\nVocê está Abaixo do Peso') elif imc <= 25: print(f'O IMC é de {imc:.2f} \nVocê está no Peso Ideal') # também dá p...
e9ea3fdaa9b2b02622fd7a22f5b6e6afdaaef566
Sergei-Morozov/Stanford-Algorithms
/NP-Complete/week12/tsp.py
3,023
3.625
4
""" Travelling salesman input: complete undirected graph with nonnegative edge costs output: a minimum cost tour that visit every vertex exactly once """ """ Build the graph _____0____ / | \ 10C / |20C \ 15C / _____ 3____ \ / /25C ...
0fd7797f30a0630d047ba16c605bb8e6399d2246
messerzen/Pythont_CEV
/aula06a.py
179
3.828125
4
n1=int(input('Digite um valor: ')) n2=int(input('Digite outro:')) s=n1+n2 # print('A soma entre', n1, '+', n2, 'vale', s) print('A soma entre {0} e {1} vale {2}'.format(n1,n2, s))
34cb9db96c2218f59f663f30a2f2e60936a6f047
benoitmaillard/scallion-python-parser
/src/test/resources/input/pprint.py
842
3.625
4
async def f(): return 0 def f(): return 0 async for x in test: print(x) for x in test: print(x) for (x, y, z) in test: print(x) with test as f: print(x) async with test as f: print(x) if (x): print(x) x = [1, 2, 3] try: raise x except D: print(x) except C: print(x) e...
5e4b4e3a5f4eed41df98ab83585e31a6bb505086
johnfelipe/progress
/courses/cs101/lesson02/problem-set/median.py
602
4.15625
4
# Define a procedure, median, that takes three # numbers as its inputs, and returns the median # of the three numbers. # Make sure your procedure has a return statement. def bigger(x, y): if x > y: return x else: return y def biggest(x, y, z): return bigger(x, bigger(y, z)) ...
16818e23cb3a7eb9b8de66b5da352d78d96ea793
goodday451999/Machine-Learning
/Linear Regression/ML_Linear_Regression.py
495
3.515625
4
import numpy as np import matplotlib.pyplot as plt import pandas as pd # read csv file dataset = pd.read_csv('Position_Salaries.csv') X = dataset.iloc[:, 1:2] y = dataset.iloc[:, 2] # linear regression classifier from sklearn.linear_model import LinearRegression linear_reg = LinearRegression() linear_reg.fit(X, y) ...
60691c9f1d8b93b3fdf063ec1be632a042a37ffa
dengyungao/python
/老男孩python全栈开发第14期/python基础知识(day1-day40)/python协程+多路复用机制/yield实现并发的假象.py
1,171
4.0625
4
import time # 在单线程中,如果存在多个函数,如果有某个函数发生IO操作,我想让程序马上切换到另一个函数去执行 # 以此来实现一个假的并发现象。 # 总结: # yield 只能实现单纯的切换函数和保存函数状态的功能 # 不能实现:当某一个函数遇到io阻塞时,自动的切换到另一个函数去执行 # 目标是:当某一个函数中遇到IO阻塞时,程序能自动的切换到另一个函数去执行 # 如果能实现这个功能,那么每个函数都是一个协程 # # 但是 协程的本质还是主要依靠于yield去实现的。 # 如果只是拿yield去单纯的实现一个切换的现象,你会发现,根本没有程序串行执行效率高 d...
8b12273e6c9944d2f390fc720ffd16d54f699a83
mahmud-sajib/30-Days-of-Python
/L #24 - Inheritance & Super.py
1,281
4.34375
4
## Day 24: Inheritance and Super ## Concept: Inheritance and Super # Creating a Parent Class class Music: def __init__(self,band,genre): self.band = band self.genre = genre def info(self): print(f"{self.band} is my favorite band & they play {self.genre} music") # Creating a Child...
762e58978d378b15d23d7425b461dbbfed10bd7f
danielsamfdo/twitter_topic_summarization
/misc/Programs/LR/parse json/subtopic detection.py
1,134
3.5625
4
import nltk #----------------------------------------- #global variables stop=[] #----------------------------------------- def getstopwords(): file1=file("stop.txt","r"); lines=file1.readlines(); for line in lines: print line stop.append(line[:len(line)-1]); print stop ...
315c96d894155072ce50dc7e0b6d0bc7d2700c77
KaranMuggan/myGitRepo
/poly.py
2,685
3.796875
4
'''The following code displays a polynomial regression model which takes into account employees salaries along with the number of years of experience they have and shows us the relationship ''' import numpy as np import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression from sklearn.preprocessi...
bd013ca25eb6a37d1cdd08177ff6fa200a5ef11a
ZX1209/gl-algorithm-practise
/leetcode-gl-python/leetcode-30-串联所有单词的子串.py
5,033
3.546875
4
# leetcode-30-串联所有单词的子串.py # 题目描述 # 提示帮助 # 提交记录 # 社区讨论 # 阅读解答 # 给定一个字符串 s 和一些长度相同的单词 words。找出 s 中恰好可以由 words 中所有单词串联形成的子串的起始位置。 # 注意子串要与 words 中的单词完全匹配,中间不能有其他字符,但不需要考虑 words 中单词串联的顺序。 # 示例 1: # 输入: # s = "barfoothefoobarman", # words = ["foo","bar"] # 输出:[0,9] # 解释: # 从索引 0 和 9 开始的子串分别是 "barfoor" 和 "foobar" ...
0acf6c68b2eac13d7b8f4ca6864d47731af913c8
key1024/codelearn
/pythoncode/ds_reference.py
267
4.03125
4
print('Simple Assignment') shoplist = ['apple', 'banana', 'carrot', 'mango'] mylist = shoplist del shoplist[0] print('shoplist is', shoplist) print('mylist is', mylist) mylist = shoplist[:] del shoplist[0] print('shoplist is', shoplist) print('mylist is', mylist)
3d2d68f95968be2ae00135dfb22e49b046ea0051
jinwoo123/MyPython
/Ch01/Ex04.py
194
3.6875
4
import turtle t = turtle.Turtle() t.shape("turtle") a=100 b=90 t.forward(a) t.left(b) t.forward(a) t.right(b) t.forward(a) t.right(b) t.forward(a) t.left(b) t.forward(a)
632020af0a08b3c4c572e7ad9d198410c31e773a
Sindhu9527/CoursePython
/mbox-short.py
631
3.65625
4
# -*- coding: utf-8 -*- """ Created on Tue Jan 29 23:56:26 2019 @author: sindh """ #assignment 8.5 fname = input("Enter file name: ") #if len(fname) < 1 : fname = "mbox-short.txt" fd = open("C:\\Users\\sindh\\Desktop\\COURSERA\\PyDSC\\Asisgnment 8.4\\Assgnment 8.5\\mbox-short.txt") count = 0 for line in f...
b8eb6cf7ce4b2f3993736c6ae0b698ed60b0b759
saidrobley/Python_Challenges
/PalindromeNumber.py
424
3.984375
4
# Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward. class PalindromeNumber: def isPalindrome(self, x: int) -> bool: new_x = str(x) i = 0 j = len(new_x) - 1 while i < j: if new_x[i] == new_x[j]: ...
1f0ff92d240868394ff915f032f36eca7feb5a23
cluntsao/python-learning
/ArithmeticProgression.py
693
3.875
4
from Progression import Progression class ArithmeticProgression(Progression): """Iterator producing an arithmetic progression""" def __init__(self, increment = 1, start = 0): """Create a new arithmetic progression increment: the fixed constant to add to each term (default 1) start: th...
4a336467effd5aa0dda4d9b4af845bf6ecd3ceb2
ComplicatedBread/python-notes
/thing.py
1,793
3.890625
4
time = 1800 place_of_work = "Highview" town_of_home = "Ramsbottom" if time == 700: print(town_of_home) elif time == 900: print(place_of_work) else: print("commuting") password = "hi" print (len(password)) if (len(password)) <8: print("Password is too short") else: print(password)...
ef56a4fbeee09889bcdaef580d997981880c2bac
rohanwarange/Python-Tutorials
/built_in_function/map_and_lamada.py
263
3.515625
4
# number=[1,2,3,4,5,6,7,8,9,11,22,33,44,55,66,77,32,43,54,65,78,89,444,567] # print(list(map(lambda a:a*a,number))) n=int(input("Enter the Number")) l=[] for i in range(n): a=list(map(int,input().strip().split())) print(a) l.append(a) print(l)
e3d7a1d0530498c256133f36fe94b2189c8ab604
Saurabh-Singh-00/data-structure
/sorting/quick_sort.py
685
3.796875
4
# Enter numbers space separated array = list(map(int, input().split())) def partition(array, start=0, end=0) -> int: x = start pivot = array[start] for i in range(start+1, len(array)): if pivot > array[i]: x += 1 array[x], array[i] = array[i], array[x] array[start], arr...
7291965505d9d04537b9dca3ad53bcfd3ea76e0c
ShristiC/Python-Games
/BlackJackGame/Objects.py
4,072
4.34375
4
""" Objects File which has the initial OOP code for Card, Deck, and Player Card Class: designates the card's rank, suit, and value Deck Class: designated a deck of cards Player Class: defines how the Player operates """ import random # Program Constants # dictionary of card value pairs values = { 'Two' : 2,...
b6ab8044d9330b388e5c82016af90ff887b00116
jwoojun/CodingTest
/src/main/python/study/boj/dp/BOJ-10422.py
309
3.5
4
import sys import math input = sys.stdin.readline N = int(input()) def catal(N): return math.factorial(2 * N) // (math.factorial(N) * math.factorial(N + 1)) for i in range(N): number = int(input()) if number % 2 != 0: print(0) else: print(catal(number // 2) % 1000000007)
a24133b2af89941f10a7d16f5e78e99f25455496
rzhou10/Leetcode
/800/832.py
339
3.609375
4
''' Flipping an Image Runtime: 48 ms ''' class Solution: def flipAndInvertImage(self, A: List[List[int]]) -> List[List[int]]: for i in A: i.reverse() for i in range(len(A)): for j in range(len(A[i])): A[i][j] = 1 if A[i][j] == 0 else 0 ...
f480149cd8a229c9df936832df5e33f25083a22b
deeph4ze/ProjectEuler
/9.py
592
3.765625
4
# pythagorean triplet a < b < c where a**2 + b**2 = c**2 # #find the only one for which a+b+c = 1000 # # # import time start = time.time() def find_answer(): for a in range(1, 998): for b in range(a+1,998): for c in range(b+1,998): if (a+b+c != 1000): continue else: if (a**2 ...
ff4c1c2688f18a0ac26a21d7d5290077c9f917d3
jglantonio/learnPython
/scripts/ej_006_for.py
351
4.125
4
lista = ['perro','gato','conejo'] for elemento in lista : print(elemento) for x in range(0, 3): print(x) for elemento in range(1,11,1) : print(elemento) ## CAPITALIZA UN ARRAY lista = ['perro','gato','conejo'] aux = [] for elemento in lista : aux.append(elemento.title()) print(aux) print(list(range...
be10e01d47657cd346cbdb7bc672ca53df670b3b
eant/PDD-MJ-N-287
/Clase 02/norma_fechas.py
437
3.5
4
from datetime import datetime #fecha salida = "13-02-2019" fecha = '13/2/2019' objeto_fecha = datetime.strptime(fecha, "%d/%m/%Y") fecha_normalizada = datetime.strftime(objeto_fecha, "%d-%m-%Y") print(fecha, objeto_fecha, fecha_normalizada) fecha = '2/13/2019' objeto_fecha = datetime.strptime(fecha, "%m/%d...
fe1b68c65834c99e21da6e2c75fe3bf68b059f7e
aasparks/cryptopals-py-rkt
/cryptopals-py/set5/c39.py
4,058
3.96875
4
""" **Challenge 39** *Implement RSA* There are two annoying things about implementing RSA. Both of them involve key generation; the actual encryption/decryption in RSA is trivial. First, you need to generate random primes. You can't just agree on a prime ahead of time, like you do in DH. You can write this algorithm...
5d5cc3f255d43c2f2fb507c794a70c7cd4c6bd89
wangleixin666/Python2.7
/test.py
569
4.0625
4
#!/usr/bin/env python # -*- coding: utf-8 -* def binarysearch(list, item): low = 0 high = len(list) - 1 while low <= high: mid = (low + high) / 2 # print mid if list[mid] > item: high = mid # print 'big' elif list[mid] < item: low = m...
3bb5a2369c5b73a569c03c31d76f1669667b4400
Daithi303/finalProjectBlePeripheral
/firmata.py
1,192
3.625
4
# A simple loop that reads values from the analog inputs of an Arduino port. # No Arduino code is necessary - just upload the standard-firmata sketch from the examples. #This file is heavily based on code found online which can be found here: #https://github.com/rolanddb/sensor-experiments/blob/master/firmata-read-an...
8f3a25bc8a32cade82e06065607fe77bb4a9dfb6
wangjiaxin24/youknow_whatiwant
/leet_code/do_it.py
1,231
3.78125
4
1.两数求和 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。 你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。 class Solution: def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ dict_num = {} for index,num in en...