blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
39baec9f40896641f461881cc473c979be0fd9d3
kakapapa252/lecture4
/class0.py
995
3.703125
4
class Flight: id_counter = 1 def __init__(self, origin,destination,duration): self.origin = origin self.destination = destination self.duration = duration self.id = Flight.id_counter Flight.id_counter += 1 self.passengers = [] def print_info(self): print(f"id : {self.id}") print(f"origin : {se...
edd4ee6f2319f83b74051293a6be2d4f20dc1811
TimLatham/BookLearning
/Hands-On Python/suitcase.py
1,296
3.59375
4
# -*- coding: utf-8 -*- """ Created on Wed Mar 08 08:49:41 2017 @author: tim.latham """ weight = input('How many pounds does your suitcase weigh? ') if weight > 50: print 'There is a $25 charge for luggage that heavy.' print 'Thank you for your business' temperature = input('What is the temperature? ...
0d2a7907f22ac78c224c4ca4e5a20a01ca75af79
WolfgangHall/python_data_visualizations
/scatter_squares.py
1,238
3.75
4
import matplotlib.pyplot as plt #plots a single point, must pass (x,y) value #s argument sets the size of the dots # plt.scatter(2, 4, s=200) #set multiple values # matplotlib reads one value from each list as it plots each point # x_values = [1, 2, 3, 4, 5] # y_values = [1, 4, 9, 16, 25] # plt.scatter(x_values, y_v...
a68274522cc4a926b2edbc23a2fc34038ef18df8
cxapython/leetcode
/021.合并两个有序链表/solution.py
1,194
4.09375
4
class ListNode: def __init__(self,x): self.val = x self.next = None class Solution: def merge_two_list(self,l1:ListNode,l2:ListNode)->ListNode: #pre是哨兵节点,head是每次要移动的 pre=head = ListNode(0) while l1 and l2: if l1.val <= l2.val: #head的next指向l1 ...
5e5a77abd7ff390bac508a10e6a0f8658c7999e9
IdiosyncraticDragon/Reading-Notes
/Python Parallel Programming Cookbook_Code/Chapter 2/determine_the_current_thread.py
1,102
3.546875
4
import threading import time def first_function(): print (threading.currentThread().getName()+\ str(' is Starting \n')) time.sleep(2) print (threading.currentThread().getName()+\ str( ' is Exiting \n')) return def second_function(): print (threading.currentThread(...
85f97b068d8b587532e9ae7e550b6935b172337b
IdiosyncraticDragon/Reading-Notes
/Python Parallel Programming Cookbook_Code/Chapter 1/hello_Python_WithThreads.py
1,089
4.09375
4
## To use threads you need import Thread using the following code: from threading import Thread ##Also we use the sleep function to make the thread "sleep" from time import sleep ## To create a thread in Python you'll want to make your class work as a thread. ## For this, you should subclass your class from t...
daa494470896d9b8e5fd4264112ec11da8df5bc9
lospejos/python3-samples
/enum/simple_intenums.py
684
4.53125
5
#------------------------------------------------------------------------------- # Basic examples of using IntEnum. # # Eli Bendersky (eliben@gmail.com) # This code is in hte public domain #------------------------------------------------------------------------------- from enum import IntEnum class Request(IntEnum): ...
d9e5241af5483f69a7c78f30a8e618446fea6feb
vectormars/Python-for-Everybody
/Course 1. Programming for Everybody/Assignment_Functions.py
337
3.71875
4
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Fri May 19 10:44:00 2017 @author: jiexue """ def computepay(h,r): if h<40.0: return h*r else: return (h*r*1.5)-(20*r) hrs = raw_input("Enter Hours:") rate = raw_input("Enter Rate:") h = float(hrs) r = float(rate) p = computepay(h,...
561b2c59744ddc059d3f37f59f0694182f38fd11
BrunoZarjitsky/URI
/2235.py
462
3.6875
4
creditos = input().split(" ") for i in range(len(creditos)): creditos[i] = int(creditos[i]) lista = [creditos[0]+creditos[1], creditos[0]-creditos[1], creditos[0]+creditos[2], creditos[0]-creditos[2],\ creditos[2]+creditos[1], creditos[2]-creditos[1]] for i in range(3): if creditos[i] in lista or creditos[0...
869cf924c641dd750fc9fee372cd942521237729
AlmasSinev/SimpleAlgorithms
/appp.py
2,852
3.84375
4
from tkinter import * def main(q, q1, q2, e, a, b, c): def fibonacci(num): if num in (1, 2): return 1 return fibonacci(num - 1) + fibonacci(num - 2) def equalization(x): return round(a * x ** 2 + b * x + c, 4) def L(num): return fibonacci(num) / fibonacci(num...
68378374120d698c05b7e0d38607291590daf3a6
kevcastle/Machine-Learning-Classification
/Game_of_Thrones.py
27,340
3.53125
4
# -*- coding: utf-8 -*- """ Created on Wed Mar 20 14:21:12 2019 @author: Kevin """ #Loading Libraries import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split # train/test split import statsmodels.formula.api as smf # logistic regression ...
bcc0f3ed5a0c696955dfb2288ef2a043c320b1ef
k-davis/FriendNET
/Menu.py
750
3.625
4
class Menu: _menu_options = [] def __init__(self): pass def create_menu_option(self, option_text, option_func): self._menu_options.append({'text': option_text, 'func': option_func}) def display(self): print() print('Select an option') for idx, option in enume...
586d29429923db0ed2e48d6f279e091d29f86c65
MYwzy/naruto
/功能自动化day01.py
2,141
3.796875
4
"""邬宗圆的功能自动化day01任务代码""" # 任务一:百度搜索一个东西 # from selenium import webdriver # import time # driver = webdriver.Chrome() # driver.get("http://www.baidu.com") # driver.maximize_window() # driver.find_element_by_xpath('//*[@id="kw"]').send_keys("MY邬宗圆") # driver.find_element_by_xpath('//*[@id="su"]').click() # tim...
70a96a4b000057e2de73db5d7bbfdff495d73911
JJ-PC-Tech341/Charles-2.0-Python-Bot
/chatbot.py
4,952
3.6875
4
import smtplib import datetime import webbrowser import os import wikipedia import pyjokes def chatbot(): operation = input(''' Hi there I Am Charles your personal Chatbot Do You Want to Talk with me type Y for Yes and N for No ''') if operation == 'Y': wishme() elif o...
8faf953ae9d33db280350da8a1d4b52ef2a853de
mehdizit/holbertonschool-higher_level_programming
/0x0C-python-almost_a_circle/models/rectangle.py
3,445
3.765625
4
#!/usr/bin/python3 """Defines a rectangle class.""" from models.base import Base class Rectangle(Base): """Represent a rectangle.""" def __init__(self, width, height, x=0, y=0, id=None): """Initialize a new Rectangle.""" self.width = width self.height = height self.x = x ...
ee978ac55e3fe7e8010f56d0eb9410c9001586c0
ahusarova/lab1
/lab1.py
1,044
3.65625
4
class Student: def __init__(self): print Student created def getName(self): return self.name def setName(self, name): self.name = name def getSurname(self): return self.surname def setSurname(self, surname): self.surname = surname def getFathersName(self): return self.fathersName def setFathersName(s...
6575a800fa6e2375a659e4cbc5dac509bc86a746
kruzda/project_euler_solutions
/euler004.py
580
3.5
4
#!/usr/bin/python def ispal(n): return int(str(n)[::-1])==n results=[] """ for i in range(100,999): for j in range(100,999): if ispal(i*j): results.append(i*j) results.sort() print(results[-1]) """ """ palindrome algebra: abccba 100000a + 10000b + 1000c + 100c + 10b + a 100001a + 10010b + 1100c 11(9091a + 9...
88dbd1d2a54c96813583a6e049a1a82be9b875a9
Cryptoriser7/CursoPython-Mundo-2
/ex045.py
2,148
4.21875
4
'''Crie um programa que faça o computador jogar jokenpô (pedra, papel, tesoura) com voce''' print(' \033[34m<<\033[31mJO\033[33mKEN\033[32mPÔ\033[34m>>\033[0m') #Importação de random.choice, para ser usado na automação da escolha do computador #Recebe input numerico do user que mais tarde é convertido para ...
e86479cefacf96510ae1d38709a3bfb2217f35e7
VNemchenko/decoder
/main.py
449
3.90625
4
key = list(input('type the first alphabet')) unkey = list(input('type the second alphabet')) encode1 = input('type information to encode') encode2 = input('type information to decode') decode1 = '' decode2 = '' diction = {} for i in range(len(key)): diction.update({key.pop():unkey.pop()}) for i in encode1: deco...
e8e9d2475ab74c150e2429d00217a81174711e7d
AjithThanam/COMP472-A2
/node.py
940
3.515625
4
class Node: state: [] parent: None depth: None f_score: None def __init__(self, state, parent, depth, f_score): self.state = state self.parent = parent self.depth = depth self.f_score = f_score def get_state(self): return self.state def get_f_score(...
12d11e7f1969da6ba2ccffb51669ff29b9660719
shmiko/big-fat-python-tests
/hello35.py
2,588
3.921875
4
#!/usr/bin/python -tt # Copyright 2010 Google Inc. # Licensed under the Apache License, Version 2.0 # http://www.apache.org/licenses/LICENSE-2.0 # Google's Python Class # http://code.google.com/edu/languages/google-python-class/ """A tiny Python program to check that Python is working. Try running this program from t...
9d651aa4c6023be4a8778d83a9ce35e42be93433
shmiko/big-fat-python-tests
/basic/rename_prank.py
1,948
3.890625
4
import os from os import listdir # import glob # print glob.glob("~/Downloads/prank") vDir = "/Users/pauljones/Downloads/prank" # os.listdir(vDir) # filenames = next(os.walk(vDir))[2] # print (filenames) def get_filepaths(directory): """ This function will generate the file names in a directory tree by w...
369a093df4daa72bbfc963f1abf7a0d6a1a226ab
bzhang57/Twitcmd
/twitcmd
4,200
4
4
#!/usr/bin/env python # By Bryan Zhang from twitter import * from Tkinter import * import sys t = Twitter( auth=OAuth('key1', 'key2', 'key3', 'key4')) def showTweets(x, num): for i in range(0, num): line1 = (x[i]['user']['screen_name']) line2 = (x[i]['text']) print ...
8939385bbdaa794e5e54a4d64deb24bdf8f64f90
yxlee245/learning-decorators
/example1.py
791
3.5
4
from typing import Callable, Any import time def timer(func: Callable[[Any], Any]) -> Callable[[Any], Any]: def inner(*args: Any, **kwargs: Any) -> Any: time_start = time.time() ret = func(*args, **kwargs) duration = time.time() - time_start print( f'Time taken for func...
03ade91e2921ba8f898179108c58a912068ba4af
SinduMP/Algoritma_Data_Base
/Jobsheet10_Pencarian.py
4,358
4.34375
4
#bubble sort #Searching # insertion sort def insertionSort(arr): for i in range(1, len(arr)): key = arr[i] # Move elements of arr[0..i-1], that are greater than key, # to one position ahead of their current position j = i-1 while j >=0 and key < arr[j] : arr[j+1] = arr...
c7d4157fbdaeb5b0fd88a2d0be643e792419a655
junzhao680/PyCheckio
/Mine/box_probability.py
1,111
3.578125
4
#!/usr/bin/python # -*- coding: utf-8 -*- def p_nstep(p_sum, black, white): total = black + white return [[black * p_sum, black - 1 if black > 1 else 0, white + 1], [white * p_sum, black + 1, white - 1 if white > 1 else 0]] def checkio(marbles, step): black = marbles.count('b') white = marbles.count('...
9f22f4031fb789f293fc328f5e037a8c6fa133d7
junzhao680/PyCheckio
/ScientificExpedition/common_words.py
526
3.6875
4
#!/usr/bin/python # -*- coding: utf-8 -*- def checkio(first, second): return ','.join(sorted(list(set([f for f in first.split(',') for s in second.split(',') if f==s])))) #These "asserts" using only for self-checking and not necessary for auto-testing if __name__ == '__main__': assert checkio("hello,world", "...
6806389961ea5657f5a560db3505b05916028b67
junzhao680/PyCheckio
/OReilly/longest_non_repeat.py
882
4.03125
4
#!/usr/bin/python # -*- coding: utf-8 -*- def non_repeat(line): """ the longest substring without repeating chars """ # your code here try: longest = line[0] for i in range(len(line)): nr_str = line[i] for j in range(i+1, len(line)): if li...
4e83ec13c4f499b9a32543cb4000220d09bed596
smfinn/Python-Bible
/Vowel and consonant counter.py
709
4
4
# Vowel and consonant counter switch = "on" print("Welcome to the vowel and consonant counter!") while switch == "on" : word = input("What word would you like to ask about?: ").strip() vowels = 0 consonants = 0 for letter in word : if letter.lower() in "aeiou" : vowels = vowels ...
a0811e081736001249561f6dcf714b997459134d
younusimran/Practice
/7segmentdisplay.py
860
3.765625
4
import re l1 ={ 1:['###','#','###','###','# #','###','###','###','###','###' ], 2:['# #','#',' #',' #','# #','# ','# ',' #','# #','# #' ], 3:['# #','#','###','###','###','###','###',' #','###','###' ], 4:['# #','#','# ',' #',' #',' #','# #',' #','# #',' #' ], 5:['###','#','###','###',' ...
8135f4eb5a8235f45c5eeb38d5f305804abeb3d2
smitkiri/pytorch-applications
/utils.py
855
3.796875
4
import sys def drawProgressBar(current, total, string = '', barLen = 20): ''' Draws a progress bar, something like [====> ] 20% Parameters ------------ current: int/float Current progress total: int/float The total from which the current progress is made ...
7cd92814221c6a1e9a0b4f2c7993c50f2551ba1d
laowantong/customsort
/customsort.py
1,850
4.03125
4
#! /usr/bin/env python2.7 from collections import OrderedDict def to_ascii(s): return unicodedata.normalize('NFD', s.lower()).encode('ASCII', 'ignore') def make_custom_sort(orders): """ Sort in a specified order any dictionary nested in a complex structure. Especially useful for sorting a JSON file i...
e8efc6b7cc7e30103f6ccdb387d0d979736f3f3d
trixtun/Competetive-programming-interview
/nested list.py
955
3.65625
4
#if __name__ == '__main__': # s=[] # n=[] # for _ in range(int(input())): # name = input() # n.append(name) # score = float(input()) # s.append(score) # k = sorted(s) # temp=1 # secondLowestScore = 0 # if k[0]==k[temp]: # temp=temp+1 # else: # ...
8f0f3287277bbf968ba208b0d397c1ad0a23eeee
jlaw9/problem-solving-2018
/src/utils.py
463
3.671875
4
import os def checkDir(directory): """ Analagous to mkdir -p directory from the command line """ if not os.path.isdir(directory): print("Dir %s doesn't exist. Creating it" % (directory)) try: os.makedirs(directory) except OSError: # if multiple parallel proc...
3bd46304cca2f0f98f0bac045df1ab31ba84ebbd
kv3n/gaimeface
/scripts/behavior.py
9,602
3.875
4
import random class Behavior: def __init__(self): self.expected_outcome = 0 # player expected it to succeed or fail self.utility = 0.0 # The utility of that play being successful self.probability = 0.0 # The probability of that play being successful def __str__(self): ...
ac58120aaf1997b0c33be128d1aac921ff7f8476
zenvisuals/DesignPatterns
/TemplateMethodPattern.py
1,328
4.34375
4
""" Template Method Pattern - define a set of algorithms while allowing its subclasses to override some methods in order to work with a particular object. Example - The making of caffeine beverages such as tea and coffee have similar processes except a few that might need a little tweak. These processes ...
060e361c035919101cbd85d5280dbae393489c5c
zenvisuals/DesignPatterns
/CommandPattern.py
3,423
3.890625
4
""" Command Pattern - encapsulates a request as an object, which provides the client the benefit of having multiple different requests. The request will be executed by another entity that knows how to interact with it. Example - The text editor has a set of commands we sometimes use, the cut, copy, past...
744415ba19163be8e3fda9e59733c675ffa329bf
MPTauber/DataMining
/my_lambdas.py
1,846
4.25
4
remainder = lambda num: num % 2 ## remaineder expects one argument (num) and does the calculation print(remainder(5)) # Multiple arugments: product = lambda x,y: x * y print(product(2,3)) #####################################################################################################################...
121dc1b59ff77887906a19343bdd5b93e4e6efeb
deepak1725/FedUni-MoneyManager
/main.py
18,087
3.53125
4
import tkinter as tk from tkinter import * from pylab import plot, show, xlabel, ylabel from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg from matplotlib.figure import Figure from collections import defaultdict import matplotlib.pyplot as plt from tkinter import messagebox from moneymanager import...
b7d43f8da07af0cb6b35c207b7b093dab06bf354
barbaraperim/ROSALIND
/bioinformatics_stronghold/rabbits_and_recurrence.py
329
3.890625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Dec 12 20:05:03 2019 @author: Bárbara Perim """ def rabbits(months, n_pairs): if (months < 1): return 0 if (months == 1): return 1 else: return rabbits(months-1, n_pairs) + n_pairs * rabbits(months-2, n_pairs) print...
481396fb11e5c9d69701654f3b8d5396d87369be
AnthonyAkentiev/cs373
/2-kalman_filters/2-measurement_update.py
972
3.78125
4
# Measurement Update #The new belief will be more certain than either the previous belief OR the measurement. #The takeaway lesson here: more measurements means greater certainty. # This can be hard to wrap your head around, but multiple measurements ALWAYS gives us a more certain (and therefore taller and narrower) ...
1702fca3ed982fb4cf862ac1066e0122661adf93
eferrer686/Aprendizaje-Automatico
/class-14-08/Main.py
3,770
4.625
5
import numpy as np # 1. Let's create a numpy array from a list. # a. Import the "numpy" library as "np". # b. Create a list with values 1 to 10 and assign it to the variable "x". # c. Create an integer array from "x" and assign it to the variable "a1". # d. Create an array of floats from "x" and assign it to the vari...
20eaab0e4cfc2a54092f092bd6022dee07626d8c
BrenoTeodor-o/Python
/listas1.py
992
4.4375
4
# @Author: Breno Ribeiro Teodoro # Listas # Na seção de strings, introduzimos o conceito de sequencia em Python. As listas podem ser pensadas na versão mais geral ed uma sequência em Python. # Ao contrário das strings, elas são mutáveis, o que significa que os elementos dentro de uma lista podem ser alterados # Nessa...
252e4722a9a38d4989ed0a693e874f6c5f7b260a
candytale55/add_greetings
/add_greetings.py
511
4.34375
4
# Create a function named add_greetings() which takes a list of strings named names as a parameter. # In the function, create an empty list that will contain each greeting. # Add the string "Hello, " in front of each name in names and append the greeting to the list. # Return the new list containing the greetings. ...
021eab79098b8e569a470248d4dd12dab967b668
agnaite/hb_dicts-restaurants-ratings
/restaurant-ratings.py
1,475
4.1875
4
# your code goes here import random the_file = open('scores.txt') restaurant_ratings = {} for line in the_file: line = line.rstrip().split(":") restaurant_ratings[line[0]] = line[1] the_file.close() # new_restaurant = raw_input("Enter new restaurant here: ") # new_score = int(raw_input("Enter new score he...
44e445d6d6853733f7afc88d35c6d68bd20384c9
chandibhandari1/RecommendationEngine
/JaccardSimilarity_CooccuranceMatrix/PersonalizedRecommender.py
6,073
3.53125
4
""" Teaching Recommendation for ML Students: Collaborative Filtering using: Jaccard Similarity and Cooccurance This class has Similarity based Personalized recommender: when we need to recommend the item similarity user-item similarity. """ import numpy as np import pandas as pd # Define a class for popularit...
290a08fa8e305f17089b98718522aa83652b234e
choiyounggi/python
/pakage01/python-quiz/D08_saveResilt.py
2,325
3.5625
4
# 가위바위보 게임을 컴퓨터와 진행하도록 만들고 # 승패를 파일에 기록해보세요 (10개마다 \n으로 개행) # 기록 예시 > 승승패패패승패승패승승패패패... import random as ran rsp = ('가위', '바위', '보') c = 0 while True: com = ran.choice(rsp) user = input('가위, 바위, 보 중 하나를 입력하세요> ') if user not in rsp: print('잘못된 입력입니다') else: if user == com...
ba857f4be9484ba4cf5d2845c6cddb60cd80f238
choiyounggi/python
/pakage01/A03_variable.py
1,619
4.09375
4
# 변수란? # - 값을 담아둘 수 있는 공간 # - 담아둔 값을 나중에 꺼내서 자유롭게 사용할 수 있다 # - 한번 값을 담아두면 변경할 때 까지 계속 값이 유지된다 # 프로그래밍 언어의 = (대입연산) # - 여태까지 알고있는 =의 의미 : 왼쪽 값과 오른쪽 값이 같다 # - 프로그래밍 언어에서 =의 의미 : 왼쪽의 변수에 오른쪽의 값을 넣어라 (10 = x 는 불가능) x = 10 print(x) print(x + x) print('x에 들어있는 값 : ', x) # 변수에 들어갈 수 있는 값들 x = 10 ...
7962288eda51f05427fe5b3ae78cd411e23e2de0
choiyounggi/python
/pakage01/python-quiz/D05_InheritPractice.py
1,818
3.671875
4
# 클래스를 하나 정의하고 # 해당 클래스를 상속받은 클래스를 하나 생성해보세요 # 그리고 자식 클래스에 오버라이드 메서드와 # 자식 클래스에만 있는 메서드도 추가하고 테스트 해보세요 class Car: def __init__(self, color='흰색', type='승용차', fuel='휘발유'): self.color = color self.type = type self.fuel = fuel def introduce(self): print(f'내 차는 {self.colo...
82152cdc31c52a767176020fef97f98e53ec50af
tututen/leetcode_ans
/125.py
253
3.671875
4
import re class Solution: def isPalindrome(self, s: str) -> bool: v = re.sub(r'[^a-z0-9]+', '', s.lower()) return v == v[::-1] print(Solution().isPalindrome("A man, a plan, a canal: Panama")) print(Solution().isPalindrome("0P"))
aaf0f0154fd9d41327f0288271c4c3df9b86836b
mitchjacksontech/hackerrank-solutions
/ctci/ctci-queue-using-two-stacks.py
852
3.96875
4
#!/usr/bin/env python3 from sys import stdin # Hacker Rank Queues: A Tale of Two Stacks # mitch@mitchjacksontech.com # https://www.hackerrank.com/challenges/ctci-queue-using-two-stacks # # The solution calls for implementing a queue object interacting with it. class my_queue(object): def __init__(self): ...
85113c0b3b04c8d544057c29efa634d7b658a64e
gaurav7goyal/pyramid_framework
/SqlAlchemy/App/Model/user_model.py
1,080
3.546875
4
''' purpose: create a user table in database ''' from sqlalchemy import ForeignKey from sqlalchemy.orm import relationship from connection import Base from sqlalchemy import Column, String, Integer class User(Base): __tablename__ ='users' id = Column(Integer,primary_key=True) name = Column(String) fu...
716f432f9fa3b4a37bee62c55fbe6b6a8fe01af5
Zdrzewielski/Python-Intern-
/hack_power.py
1,902
4.125
4
""" Module allows to calculate value of power of hacks. """ def hack_calculator(hack: str, letters: dict = None, phrases: dict = None): """Function calculate and return value of power of hacks. Keyword arguments: hack -- string which contain combinations of letters letters -- dictionary which...
93f52bcdfd717ea70ff28a72d6e83d2e84b82099
daniel-koehler/leetcode
/Python/Algorithms/0088_MergeSortedArray.py
934
3.859375
4
# Using sort() # Time: O((m+n) log(m+n)) # Space: O(m+n) class Solution: def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: """ Do not return anything, modify nums1 in-place instead. """ nums1[m:m+n] = nums2 nums1.sort() # Two pointers # Time: O(m...
f9e7c88d402fb6ea7b5e8968a198437404f6c554
daniel-koehler/leetcode
/Python/Algorithms/0086_PartitionList.py
1,523
3.984375
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next # Single pass with new lists # Time: O(n) # Space: O(n) # Create a linked list for both partitions respectively and concatenate them # after adding all elements of th...
ce04e3deb2772503af7c2acf0d754aca7a89739f
daniel-koehler/leetcode
/Python/Algorithms/0073_SetMatrixZeros.py
1,618
3.921875
4
# Hashing rows and cols # Time: O(m*n) # Space: O(m+n) # Straight-forward approach saving rows and cols to be set to zero in dicts class Solution: def setZeroes(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ rows = {} ...
efdafddcd3da5751ade747b4248f06d9db1c1f1d
Anuragvadarevu/pythonintro
/lab2.py
239
3.796875
4
sports=['cricket','badminton','squash','racquetball','tennis'] print(sports) print(len(sports)) for i in range(len(sports)) : print(i,sports[i]) #replace position 2 with 'football sports[2]='football' print(sports)
3df8fb52e5c90e2adcd2ee3e5cc5499de1c564a9
PrasannaMuppidi/cerner-2-to-the-5th
/Cerner 2 ^ 5 2018/CSV2JSON - Day 2/CSV2JSON.py
368
3.703125
4
# cerner_2^5_2018 # Program to convert a CSV file to a JSON file import csv,json csvfile = open('Details_Test.csv', 'r') jsonfile = open('Details_Test.json', 'w') fieldnames = ("Benefit Plan","Coverage Begin Date","Deduction Begin Date","Coverage") reader = csv.DictReader(csvfile, fieldnames) for row in reader: j...
25c8fd3df4bd6bd620c9163aea2e6f61933b0257
ytliuyunhan/hackerrank-solutions
/algorithms/utopian_tree.py
378
3.53125
4
def get_growth(n): height = 1 springs = (n+1) // 2 summers = n // 2 for i in range(summers): height *= 2 height += 1 if springs > summers: height *= 2 return height t = int(input().strip()) results = [] for a0 in range(t): n = int(input().strip()) results.append...
9384a1fc9edcad0b3e31ef788ee45c45950d1a06
ytliuyunhan/hackerrank-solutions
/artificial-intelligence/bot_save_princess.py
712
3.578125
4
def displayPathtoPrincess(n, grid): m_i, m_j = find(grid, 'm') p_i, p_j = find(grid, 'p') horizontal = m_j - p_j vertical = m_i - p_i if horizontal >= 0: h_move = ['LEFT'] * horizontal else: h_move = ['RIGHT'] * (-horizontal) if vertical >= 0: v_move = ['UP'] * verti...
07299a02f07670dc62effbdc408f183b81670032
MatheusCoxxxta/fatec
/Random/Lista 4/lista4_2.py
248
3.515625
4
import random num = random.sample(range(1, 100), 20) impar = [] par = [] for i in range(len(num)): if(num[i] % 2==0): par.append(num[i]) else: impar.append(num[i]) print(f"Numeros: {num} \nPares: {par} \nImpares: {impar}")
6d3a5d0fa7e2a6e7c4dcd00885c546e698091d95
MatheusCoxxxta/fatec
/Str/word_1.py
118
3.796875
4
word = str(input()) drow = word[::-1] if(drow != word): print("Não palindrome") else: print("Palindrome")
84336201081d1231e3613f59887f071d34f22042
LucasMartins007/estudos_python
/exercicios iniciais com Python/questao8.py
2,026
4.03125
4
def main(): conta = [] saldo_inicial = 0 conta.append(saldo_inicial) opcao = 0 while opcao != "D": opcao = mostrar_perguntas() if opcao == "A": print("Seu saldo atual é: " + str(consulta_saldo(conta)) + "\n") elif opcao == "B": sacar(co...
7a8174f2de7f246539d15c89f344c06c814d58cc
iarrowned/calc
/simple.py
339
3.703125
4
import math n = int(input("Введите положительное значение int n > ")) x = float(input("Введите значение x > ")) p = - math.exp(math.cos(abs(x))) for k in range(2, n + 1): p *= ((k - 1) / k) - math.exp(math.cos(abs(k * x))) result = math.pow(n, 1 / 3) * math.pow(x, 1 / 2) - p print(result)
eb7d7bb2a87ae4e797c47a0781c40218d29be540
taiebchaabini/holbertonschool-higher_level_programming
/0x0B-python-input_output/2-read_lines.py
563
4.21875
4
#!/usr/bin/python3 """ function that reads n lines of a text file (UTF8) and prints it to stdout: """ def read_lines(filename="", nb_lines=0): """ function that reads n lines of a text file (UTF8) and prints it to stdout: """ i = 0 with open(filename, "r", encoding='utf-8') as f: ...
b553e386902d3e1d1b5dca4839f6fa823fb19ecf
taiebchaabini/holbertonschool-higher_level_programming
/0x0B-python-input_output/9-add_item.py
655
3.984375
4
#!/usr/bin/python3 """ a script that adds all arguments to a Python list, and then save them to a file: """ import sys save_to_json_file = __import__("7-save_to_json_file").save_to_json_file load_from_json_file = __import__("8-load_from_json_file").load_from_json_file filename = "add_item.json" current_list = []...
e5a0d254231aebea14e6d5f55df82340ba339685
jagrvargen/holbertonschool-higher_level_programming
/0x01-python-if_else_loops_functions/8-uppercase.py
255
3.90625
4
#!/usr/bin/python3 def uppercase(str): for i in range(len(str)): c = ord(str[i]) if ord(str[i]) >= 97 and ord(str[i]) <= 122: c = c - 32 if i < len(str): print('{}'.format(chr(c)), end='') print('')
65726731454c2bac668f8d9d90e9c11b07ffa668
jagrvargen/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/3-say_my_name.py
552
4.3125
4
#!/usr/bin/python3 """A module conataining a function that prints the phrase 'My name is {} {}'. first_name (string): A non-empty string value. last_name (string): A string value. """ def say_my_name(first_name, last_name=""): """ A function that prints 'My name is {} {}'. """ if not isinstan...
b211e15e4f15031545544cb76a43e63e294d9532
jagrvargen/holbertonschool-higher_level_programming
/0x06-python-classes/1-square.py
284
3.953125
4
#!/usr/bin/python3 class Square: """An empty class that defines a square""" pass def __init__(self, size): """Instantiates Square class with a size attribute Args: size (int): An integer denoting size. """ self.__size = size
c5da06e39c541a763b28bf90cf960b30f5a727d3
jagrvargen/holbertonschool-higher_level_programming
/0x0B-python-input_output/2-read_lines.py
409
4.125
4
#!/usr/bin/python3 """ This module contains a function which reads n number of lines from a text file. """ def read_lines(filename="", nb_lines=0): """Reads n lines of a text file""" with open(filename, encoding="utf-8") as fp: if nb_lines <= 0: print(fp.read().rstrip()) else...
8d54045f1e9ed2d01357dbf37fbc1ec94d58f265
jagrvargen/holbertonschool-higher_level_programming
/0x0B-python-input_output/8-load_from_json_file.py
277
3.53125
4
#!/usr/bin/python3 """ This module contains a function which creates an Object from a JSON file. """ import json def load_from_json_file(filename): """Creates an Object from a JSON file.""" with open(filename, encoding="utf-8") as fp: return json.load(fp)
ec8e1000ba09c53b8bb1fb820f84a8d4fefc03ab
zabutabatu/Final-
/sıralama5.py
277
3.71875
4
asal = [2,3] limit = 50 for i in range(5,limit +1,2): bolundu = False for a in asal: if i%a ==0 : bolundu = True break if not bolundu: print("Al sana asal sayı kanki{}".format(i)) asal += [i] print(asal)
baa80c13ff93c2c1a54f3ae93417278ac5ea34ca
isaacprates/IsaacTeste
/Ponto.py
1,582
3.8125
4
from datetime import datetime class hora_entrada_saida: def entrada(): get_ha = datetime.now() get_ha = get_ha.strftime("%d/%m/%Y %H:%M") # define formatação do data e horas print(get_ha) ha = input("deseja usar o dia e hora atual, sim ou não?") # ha == hora atual pega o ho...
ea21b87bfbc3ab19773ce315ff29e660dd0e41ed
1136863240/Python3-Learn
/source/class5/shizhan.py
244
3.765625
4
A = float(input('请输入您带的钱数:')) B = int(input('请输入您要买几包零食:')) lingshi = 8 if A - lingshi * B > 0: print('找回' + str(A - lingshi * B) + '元') else: print('还差' + str(lingshi * B - A) + '元')
a7aff448d0666aa6b700f7e77c340d814a205d6f
aishaniiiiiiiiiiiiiiiiiiiiiiiiiiiii/IntroToPython
/myfirstprogram.py
163
3.6875
4
print("Hello world aishani is awesome") #lol name = raw_input("Enter your name:") print("Hello,"), (name) x= 1 y = 2 x == y name = "hello" print name[0:5]
d2fdd1e1040224dd593ea4be65b491b0a195d0b7
dkhaupt/coursera
/assignment1/assignment1/test_swap_k.py
767
3.640625
4
import a1 import unittest class TestSwapK(unittest.TestCase): """ Test class for function a1.swap_k. """ def test_no_swap(self): nums = [1, 2, 3, 4, 5, 6] nums_expected = [1, 2, 3, 4, 5, 6] k = 0 a1.swap_k(nums,0) self.assertEqual(nums, nums_expected) def test_ma...
520007735d6dbded441589a958ae1064eaba7a86
crliu3227/design_pattern
/bridge.py
1,983
4.21875
4
# 在一个画图程序中,常会见到这样的情况:有一些预设的图形,如矩形、圆形等, # 还有一个对象-画笔,调节画笔的类型(如画笔还是画刷,还是毛笔效果等)并设定参数(如颜色、线宽等), # 选定图形以及画笔,就可以在画布上画出想要的图形了。要实现以上需求,先从最抽象的元素开始设计,即形状和画笔 class Shape(): def __init__(self, name, *param): pass def get_name(self): return self.name def get_param(self): return self.name, self...
51a14cbced89939e7f4262cfd99ad8df6d6175de
VigineshVaibhav/Simple-NN
/Neural-Net.py
2,698
3.609375
4
import numpy as np class Neural_Network(object): def __init__(self): # Define Hyperparameters self.yHat = 0 self.inputLayerSize = 2 self.outputLayerSize = 1 self.hiddenLayerSize = 3 # Weights (parameters) self.W1 = np.random.randn(self.inputLayerSize, self.h...
cbc95409a379cce27fa314f595e37ab49c71bbab
BRbIS/BoringPy
/Test2.py
1,051
3.65625
4
#! /usr/bin/python3 import re # check 8 char ch8Regex = re.compile(r'(.{8})+') #mo = ch8Regex.search('1234567, 2, 3123456789fgfgfgf, 4, 5, 6, 7, 8') #print('Phone number found: ' + mo.group()) # check Lower\Upper case upRegex = re.compile(r'([A-Z])+') lowRegex = re.compile(r'([a-z])+') #mo1 = lowRegex.search('pasSwor...
6843413d440e2d5b435688bd5a51d9591ae55f9d
BRbIS/BoringPy
/Files/MadLibs/MadLib.py
297
3.84375
4
# TODO нужно доделать упражнение # Enter words to replace adjective = input('Enter an adjective: ') noun1 = input('Enter a noun: ') verb = input('Enter a verb: ') noun2 = input('Enter a noun: ') # Find and replace textFile = open('text.txt', 'r') textFile.close()
37b5c495a6d358f582f78b6be9f70c9893fc2ad0
ibmlih/generate_parentheses
/generateParentheses.py
472
3.640625
4
def generateParenthesis(N): results = [] def backtrack(parenthesis, opening, closing): if len(parenthesis) == 2 * N: results.append(parenthesis) return if opening < N: backtrack(parenthesis + '(', opening + 1, closing) # generate opening bracket if ...
32527c43813788ab15beb450fd84a371ec47623e
joschkaweiss/joschkaweissde
/mergeSort.py
1,764
3.515625
4
# Erstelle zwei Subarrays von arr[]. # Erstes Subarray ist arr[l..m] # Zweites Subarray arr[m+1..r] def merge(arr, l, m, r): n1 = m - l + 1 n2 = r- m # Erstelle temporäre Arrays L = [0] * (n1) R = [0] * (n2) # Kopiere die Daten in die temporären Arrays L[] and R[] for i in ran...
4766de51edac8ddb2c2972efc8b412ee914e97a3
sejalsksagar/PPL
/PPL Lab/count_articles.py
762
4.1875
4
#12/05/21 #PPL LAB#7 #Write a Python program to count the number of articles in a given text. import string text = input("Enter text: \n") #removes punctuation text = text.translate(str.maketrans('', '', string.punctuation)) #converts entered string to lowercase text = text.lower() #split splits the string about ...
1d5d733d39478ee577314af25f675280f07a47af
AndresReyesRangel/Tarea_04
/areaRectangulo.py
1,238
3.921875
4
# Autor:. Andrés Reyes Rangel # Descripción: Calcular el área de un triangulo def calcularArea(base, base2, altura, altura2): mayor = () area1 = base * altura area2 = base2 * altura2 if area1 == area2: mayor = "Las áreas son iguales" elif area1 > area2: mayor = "El primer rectangu...
7f5471005f36ba7aa28a7df7336418d8e598195f
Benjamin-coder1/Fake_news_detector
/FakeNewsDetector/part1.py
2,363
3.765625
4
import compte import color as c import rech import data from math import exp # Ce module permet de lancer le programme fait pour la partie 1 sans nlp def scooring_1(article) : """ DESCRIPTION this function is the final function of the part 1, it is used in order to give a note to an article in order...
362684233df15946e39ffedc807ba92a08734563
kiamboon/Google-IT-Automation-with-Python-Professional-Certificate
/2. Using Python to Interact with the Operating System/2.4.4b Qwiklabs Assessment - Working with Log Files.py
1,494
4.375
4
''' Imagine one of your colleagues is struggling with a program that keeps throwing an error. Unfortunately, the program's source code is too complicated to easily find the error there. The good news is that the program outputs a log file you can read! Let's write a script to search the log file for the exact error, t...
33c11904c7a6b301a39455caa64a74beccd8b0ba
kiamboon/Google-IT-Automation-with-Python-Professional-Certificate
/2. Using Python to Interact with the Operating System/2.2.4b Qwiklabs Assessment - Handling Files.py
1,571
4.21875
4
''' For this lab, imagine you are an IT Specialist at a medium-sized company. The Human Resources Department at your company wants you to find out how many people are in each department. You need to write a Python script that reads a CSV file containing a list of the employees in the organization, counts how many peop...
a39595220de7235f9a7b12ab581c863f023c9262
MattJud/csme_assignment_1
/Exercise1/Exercise1/nn.py
9,445
3.921875
4
import numpy as np import time class TwoLayerNet(object): """ A two-layer neural network with the architecture: input - fully connected layer - activation function (ReLU) - fully connected layer - softmax The neural network performes a classification over C classes. The output is a score of ...
57b91cab97a530d2c5c3d3ea382cd284e96f1073
henper/crafts
/goldbach.py
1,805
4.125
4
#!/usr/bin/env python ''' Disprove the Christian Goldbach hypothesis: all odd composite numbers can be written as the sum of a prime and twice a square. oddComposite = prime + 2 * X^2 Also known as the OTHER Goldbach conjecture. THE Goldbach conjecture was disproven in the previous version of this fil...
a918ae6b8325087b68fbcf96bb1df0114f86883a
QuoInsight/cronchk
/waitNext.py
808
3.640625
4
while (True) : import datetime currentTime = datetime.datetime.now() #currentTime = datetime.datetime(2018, 10, 3, 15, 45, 0) #nextMinute = currentTime.replace(microsecond=0, second=0) + datetime.timedelta(minutes=1) offsetMinutes = 3 intervalMinutes = 15 thisMinutes = currentTime.timetuple().t...
8e9afd8ce90919e7f981fe1b5c4991f27a4a0e66
ethen8181/programming
/big-data/MRjob/6_SocialGraph/BFS.py
1,429
3.828125
4
# making breadth first search a map reduce problem # all the original nodes start out with distance infinite # and for the nodes that we've already come across # convert the color from "white" to "gray" import sys # sys.argv is a list of strings representing the arguments # on the command line, index [0] is the ...
c5d3a10a2db5cfd061ff1fe4d84c9df0fbc2c843
ethen8181/programming
/svm/svm.py
3,429
3.84375
4
import numpy as np class SVM: """ Multi-class Support Vector Machines (SVM) using gradient descent Parameters ---------- learning_rate : float, default 1e-3 Learning rate for optimization. reg : float, default 1e-5 Regularization strength. n_iters : int, 100 Numb...
da1ede4fdf2d0c6f2c7ece52b6aee1b6d719fe8d
ethen8181/programming
/typing1.py
4,929
4.21875
4
""" # We can introduce optional typing to our python code to enhance readability, # and use mypy on our program to catch potential errors without actually running it. # The following code is based on the series of excellent blog post by daftcode. pip install mypy mypy typing1.py References ---------- - https://blog.d...
0dfef8147c602999d41e2faea39e6487b61b7108
hiddennin/mhshuffle
/mhshuffle.py
2,480
3.703125
4
#!/usr/bin/env python import sys from random import randint pairs = ['A', 'A', 'B', 'B', 'C', 'C', 'D', 'D', 'E', 'E', 'F', 'F', 'G', 'G', 'H', 'H', 'I', 'I'] board = [] def find(needle, haystack): i = len(haystack) - 1 while i > 0 and needle != haystack[i]: i -= 1 return i def isSolved(board, bo...
00f3ee78381b10d92687d6f7adc4e77e9b8c3d02
gp22/How-to-Think-Like-a-Computer-Scientist
/ch9/ex_7_11.py
349
4.0625
4
# Write a function sum_of_squares(xs) that computes the sum of the # squares of the numbers in the list xs. For example, # sum_of_squares([2, 3, 4]) should return 4+9+16 which is 29. def sum_of_squares(xs): total = 0 for num in xs: square = num ** 2 total = total + square return total prin...
6bafc3b0d47585a55211e130bdfab13ddf22b911
gp22/How-to-Think-Like-a-Computer-Scientist
/ch15/classes_q3.py
1,981
3.984375
4
# Add a method area to the Rectangle class that returns the area of # any instance: # r = Rectangle(Point(0, 0), 10, 5) # test(r.area(), 50) import math class Point: """ Point class for representing and manipulating x,y coordinates. """ def __init__(self, initX, initY): """ Create a new point at the ...
14f0d9e7f3f0921a28aa38c4519a6be57ee0b172
gp22/How-to-Think-Like-a-Computer-Scientist
/ch8/ex_8_19.py
443
4.15625
4
# Write a function called remove_dups that takes a string and creates # a new string by only adding those characters that are not already # present. In other words, there will never be a duplicate letter # added to the new string. def remove_dups(astring): newStr = '' for c in astring: if newStr.count(...
acc02ebe82781afdaff81d655484a8e01ff60d11
gp22/How-to-Think-Like-a-Computer-Scientist
/ch14/ch_cl_02.py
1,026
4
4
# Add a method reflect_x to Point which returns a new Point, one which # is the reflection of the point about the x-axis. # For example, Point(3, 5).reflect_x() is (3, -5) import math class Point: """ Point class for representing and manipulating x,y coordinates. """ def __init__(self, initX, initY): ...
e6867c6542ddddb57008914208b39c6b6881b0a9
abrichr/oncovid19
/app/forms/__init__.py
663
3.796875
4
from wtforms.validators import ValidationError class Unique(): ''' Custom validator to check an object's attribute is unique. For example users should not be able to create an account if the account's email address is already in the database. This class supposes you are using SQLAlchemy to qu...
0ddd540fcc00d30c7f3b0c9fda8377c8d3c80371
geekidharsh/tilt-python
/pandas-notes/pandas_codes/pd_getcol_mean_from_hyphen.py
1,460
3.71875
4
import pandas as pd # Given a sample input or arrays, obtain mean of the each number at every index, including for hyphen values etc. so 30-34 will become 32 sampleInput = ['12', '13', '14','15','16','17','18','19','20','21','22-23','24-25','26-29','30-34','35-49','50-64','65+'] testdf = pd.DataFrame({'ages': sample...