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
1d8a72ca967b535316af5da98e010f349846da8c
tammytdo/Self_Paced-Online
/students/mkdir01/lesson03/list_lab.py
3,513
4.15625
4
#!/usr/bin/env python3 #SERIES 1 # Create a list that contains “Apples”, “Pears”, “Oranges” and “Peaches”. fruits = ["Apples", "Pears", "Oranges", "Peaches"] # Display the list (plain old print() is fine…). print(fruits) # Ask the user for another fruit and add it to the end of the list. response_fruits = input("Ty...
16f91cade4d7a6e4c5a362c23438e72bf84390a7
jerzycup/fractions
/fraction.py
2,303
4.1875
4
""" This file contains definition of a fraction class. You should put complete class here. It must be named `Fragion` and must have the following properties: - four basic mathematical operators defined; - elegant conversion to string in the form '3/2'; - simplification and clean-up on construction: both attribute div...
0e720665d741634b9a82958c626996afdc1d14f1
nonyeezekwo/cs-module-project-algorithms
/moving_zeroes/moving_zeroes.py
766
4.21875
4
''' Input: a List of integers Returns: a List of integers ''' def moving_zeroes(arr): # Your code here # check to see if you are not a zero cur_index = 0 zero_count = 0 while cur_index < len(arr): if arr[cur_index] != 0: # count how many zeros you have passed swap_in...
80abe80821720f8aa95efbf8376c1be140d08b9d
erinmsong/Hangman
/HangmanGame.py
1,990
3.84375
4
""" Erin Song 7.12.21 Hangman Game (fruits) """ import random MAX_STRIKES = 5 def get_random_word(): words = ['apple', 'banana', 'coconut', 'dill', 'eggplant', 'fruit', 'grape', 'mango', 'pear', 'strawberry'] ind = random.randint(0, len(words)-1) return words[ind].upper() def update_blanks(gues, targ, t_...
7774128d24471a95359e15439f34b30457e3c7ef
lisha1992/LeetCode
/leetcode-4.py
1,985
3.859375
4
# -*- coding: utf-8 -*- """ Created on Fri Sep 23 14:20:00 2016 There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). Example 1: nums1 = [1, 3] nums2 = [2] The median is 2.0 Example 2: nums1 = [1, 2]...
361c2a5a213c47df9777107daebbc19ab18e7e31
NobuhiroHoshino/stock_and_python_book
/chapter2/csv_to_db.py
1,346
3.765625
4
# -*- coding: utf-8 -*- import csv import glob import datetime import os import sqlite3 def generate_price_from_csv_file(csv_file_name, code): with open(csv_file_name, encoding="shift_jis") as f: reader = csv.reader(f) next(reader) # 先頭行を飛ばす for row in reader: d =...
41f78e09b087ffea0bc830eab6503acc8b00eb57
Telcoltar/AdventOfCodeDay16
/Field.py
1,070
3.515625
4
class Field: def __init__(self, identifier: str, first_range: str, second_range: str): self.identifier = identifier first_range_first_number: str first_range_second_number: str second_range_first_number: str second_range_second_number: str first_range_first_number, f...
9d32a76a46de5c7b974f70e9bce07c58f1135efe
VasilenkoStep/DangerTerritory
/home_work_5/Zadacha_2.py
389
3.609375
4
import random print("Введите число, которое создаст МОЩНЕЙШИЙ СПИСОК ") n = [random.randint(0,10) for _ in range(15)] print ("Получившийся список:" + " "+ str(n)) while 0 in n: n.remove(0) print(print ("Получившийся список без нулей:" + " "+ str(n))) print ("Задание 2 выполнено :D")
7ca752b80e8c430cf614c7d05e4acc221ee38f02
willbryk720/cracking-the-coding-interview-python
/chap_01_arrays_and_strings/is_unique.py
1,089
4.28125
4
''' Implement an algorithm to determine of a string has all unique characters. A: Create hashtable of possible ascii characters. Run through characters and check if character has already been hashed. ''' def is_unique(s): chars = [False] * 256 for c in s: ascii_value = ord(c) if chars[ascii_v...
d0efdd00184e2592b1c6802f24a2f69e8f63e77b
PedroHTeixeira/Nautilus_Cap
/Python OO/brasileirao.py
1,451
4.03125
4
# PYTHON OO 17/11/2020 17:00 Part-1 HW class Team(): def __init__(self,name,punctuation,matches,victories,draws,defeats): self.name = name self.punctuation = punctuation self.matches=matches self.victories=victories self.draws=draws self.defeats=defeats def __r...
ab6116d3c73a45d72edf5808adc0372e736687a0
glissader/Python
/ДЗ Урок 6/main3.py
1,769
3.96875
4
# Реализовать базовый класс Worker (работник). # - определить атрибуты: name, surname, position (должность), income (доход); # - последний атрибут должен быть защищённым и ссылаться на словарь, содержащий # элементы: оклад и премия, например, {"wage": wage, "bonus": bonus}; # - создать класс Position (должность) на баз...
011469992c360c67b091e9de8573b96f71c7649f
abrosua/ml-with-numpy
/benchmarks/pca_bench.py
1,333
3.578125
4
import numpy as np from sklearn.decomposition import PCA as PCA_sk from models.pca import PCA as PCA_np if __name__ == "__main__": num_components = 2 A = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]], dtype="float") print(A) # create the PCA instance print("\n\nPCA with sk...
2338bacf5ea87613cd951cf37475c98efbeb833a
rocketpy/tricks
/API_example.py
785
3.640625
4
import json import requests url = "https://api.github.com" response = requests.get(url) print("Status code is : ", response.status_code) response_json = response.json() print(response_json) # working with JSON # save data to JSON def storeJSON(fileName, data = {}): with open(fileName, 'w') as fd: js...
235f34a09178932a48e5f0000b42f203dee00bf8
RAVURISREESAIHARIKRISHNA/Python-2.7.12-3.5.2-
/Resizing_Labels.py
537
3.875
4
from Tkinter import* obj=Tk() Label1 = Label(obj,text="LABEL 1",bg="black",fg="white") Label2 = Label(obj,text="LABEL 2",bg="yellow",fg="blue") Label3 = Label(obj,text="LABEL 3",bg="green",fg="red") Label4 = Label(obj,text="LABEL 4",bg="red",fg="black") BottomFrame = Frame(obj) BottomFrame.pack(side=BOTTOM...
357b8fcfdde35741a07b7a0d193ce8e4e0b9e4e4
hafeez1988/msc-ai-assignment-2
/AIAssignment2/AlgoExperiment.py
9,344
3.953125
4
#!/usr/bin/python ### Data Structures # # Sample current states for testing is shown below. # Add following lines one by one into state.txt for testing: # # 8 1 7 2 4 6 3 0 5 # 1 0 7 8 2 6 3 4 5 # 8 1 7 0 2 6 3 4 5 # 8 1 7 3 2 6 4 0 5 # 8 1 7 0 2 6 3 4 5 # 8 1 7 0 2 6 3 4 5 # 8 1 7 2 6 0 3 4 5 # 8 0 7 2 1 6 3 4 5 # 8 1...
f40ff81d77a8c4029f77cc6422fc16afb46bae8b
enrico-spada/py4e
/access_data_web/xml_parse_2.py
600
3.625
4
import xml.etree.ElementTree as ET input = ''' <stuff> <users> <user x="2"> <id>001</id> <name>Chuck</name> </user> <user x="7"> <id>009</id> <name>Brent</name> </user> </users> </stuff>''' stuff = ET.fromstring(input) #let's search for all the user tags below users user_l...
d09a10a4770405d70d4fd4dc5657297a45ccd6f8
joshnroy/computationalLinguisticsIndependentStudy
/pythonSecondAttempt/unigramGenerator.py
702
3.71875
4
# Declare input text file textfile = "furniture.txt" # Create a dictionary to store unigrams Unigrams = {} # Open and read file for line in open(textfile): line = line.rstrip() # tokenize the text tokens = line.split() #loop over the unigrams for word in tokens: # Check to see if the unig...
e02f13a263881ff8441f1940203eada223f3ac7d
lambainsaan/Drone-CSV-and-KML-Generator
/code/srt.py
1,681
3.515625
4
""" This module contains functions to read and parse the srt file for cordinates. """ def path_from_srt_file(srt_file): """Reads all the srt files in the path and returns the latitude and longitude of the path of the drone as a list Arguments: srt_file_path {string} -- The path to be s...
f3a7116f908005874f8115b7476d32d1c295adfa
aswinichejarla/pythonprogramm
/pl55.py
116
3.703125
4
s1,s2=map(str,raw_input().split()) s11=s1.lower() s12=s2.lower() if(s11==s12): print "yes" else: print "no"
e7eff18c2c7aff6377beddd975c803c498790a54
vishalkumar95/ECE-4802-Cryptography-and-Communication-Security
/Vigenere_Cipher.py
1,998
3.875
4
# This function is an implementation of the Vigenere cipher algorithm. def decryptVigenere(ciphertext, key): ciphertextbreak = [] ciphertextbreakextra = [] finalplaintext = ' ' Letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' smallLetters = 'abcdefghijklmnopqrstuvwxyz' keylength = len(key) ciphertex...
37ce54c9e12405b79927a59738cd656acbda663f
mcmoralesr/Learning.Python
/Code.Forces/P0287A_IQ_Test.py
564
3.5
4
__copyright__ = '' __author__ = 'Son-Huy TRAN' __email__ = "sonhuytran@gmail.com" __doc__ = '' __version__ = '1.0' def can_paint(wall: list) -> bool: for i in range(3): for j in range(3): temp = wall[i][j] + wall[i + 1][j] + wall[i][j + 1] + wall[i + 1][j + 1] if temp.co...
178a0896c850acb06ec008709dc06e4fbe1907fc
angusmit/Hackerrank
/String Formatting.py
636
4.125
4
# ======================== # Information # ======================== # Direct Link: https://www.hackerrank.com/challenges/python-string-formatting/problem # Difficulty: Easy # Max Score: 10 # Language: Python # ======================== # Solution # ======================== def print_formatted(number): ...
3c8575707937d05c78722ce4f2cd1017f86524d2
jmarcelonunes/PseudoSO
/modules/file_system.py
3,984
3.53125
4
# -*- coding: utf-8 -*- ''' Módulo do Sistema de Arquivos ''' ''' Classe FileSystem ''' from modules import process class FileSystem(): def __init__(self, filename): self.disk = [] self.ftable = {} with open(filename, 'r') as f: # Leitura de parâmetros do sistema de arquivos ...
51314de1a5a1c59e87bc70e823d07dedf0dbafbd
Diakakodo/classrooms
/api/BST.py
3,242
3.65625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ November 2018 BST: S2#-API """ from algopy import bintree # BST -> list def __bst2list(B, L): if B != None: __bst2list(B.left, L) L.append(B.key) __bst2list(B.right, L) def bst2list(B): L = [] __bst2list(B, L) return ...
1a9d8b14c31d86db3cc0a1d7e5255d8d33a782df
kamit17/Python
/Think_Python/Chp4/Examples/distance_between_points.py
340
4.25
4
def distance(x1,y1,x2,y2): """ Program to find distance between 2 points given by the coordinates using Pythagorean theorem sqrt((x2-x1)**2 + (y2-y1)**2). """ dx = x2-x1 dy = y2 - y1 dsquared = dx + dx + dy + dy result = dsquared**0.5 return result # returns a float value prin...
33b8797da617ea26336ca43317ace8149e550132
ArtemYurlov/ucl_MachineVision
/01_FittingProbDistribs_Python_mysol/log_normal.py
575
3.578125
4
import numpy as np from normal import normal def log_normal(X, mu, sigma): """Return log-likelihood of data given parameters" Computes the log-likelihood that the data X have been generated from the given parameters (mu, sigma) of the one-dimensional normal distribution. Args: X: vector o...
2736f12ae3af8b2bff5fc0aa90dcc8ee89c34399
twinkle2002/Python
/operator_dunder.py
911
4.125
4
class Employee: no_of_leaves = 8 def __init__(self, name, salary, role): #Dunder method self.name = name self.salary = salary self.role = role def printdetails(self): return f"name is {self.name}. salary is {self.salary}. and role is {self.role}" @classmethod def ...
ff1dbfde3303a6b7cefad18677224e8f4a3ade27
andresparrab/Python_Learning
/A_Numpys/about_nummpy.py
680
4.0625
4
import numpy as np #creates a array of type numpy with lists a = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]]) #creates a np array from 0-99 b= np.arange(0,100) #creates a np list with zeros. with dimention 3 rows and 5 columms c= np.zeros((3,5)) #printing the ndimentionals arrays print(a) print(b) print(c) #Creates...
f7e0c1a6996617d9e22e5feaacae0b30967ad060
Rabbi50/PythonPracticeFromBook
/primeNumber4.py
525
4.0625
4
import math def is_prime(n): if n<2: return False if n==2: return True if n%2==0: return False m=math.sqrt(n) m=int(m)+1 for y in range(3,n,2): if n%y==0: return False return True number1=input('Plese enter first number: ') number2=input('Plese enter second number: ') number1=int(number1) number2=int...
ab9281a2657ffc891c35261a37f0c02c9b897337
supriyamarturi/pyphonprograming
/42.py
103
3.515625
4
a1,a2=map(str,raw_input().split()) if a1==a2: print a1 elif a1>a2: print a1 else: print a2
0c90e81a1d6fb51c30bf8fe09e8f388235192d76
GeoVa19/ai-examples
/minimax and alpha-beta/minimax.py
676
3.828125
4
from tree import tree def minimax(node, maxPlayer): # base case of recursion: returns when node is of int type if isinstance(node, int): return node if maxPlayer: # MAX player value = -999 # an arbitrary low value for child in node: v = minimax(child, False) ...
fea1ea6ae619706ec888ab632eba4f4b7ab0c31d
RexAevum/Python_Learning
/input.py
964
4.375
4
# Getting user input in python and string formatting # To get user input command name = input("Enter your name: ") print(name) # All inputs will be of type str, so if you will have to cast it to another type # To cast x = input("Enter number: ") temp1 = int(x) temp2 = float(x) # Need to be carfull, since if user inpu...
b0b0b2b53de925a0c2b10ebc0759a5e21eb3f02d
karlweir/python-exercises
/python3/collatzFunction.py
363
4.1875
4
def collatz(number): if (number % 2) == 0: # checks if the parameter passed to the collatz function is an even number number = number // 2 print(number) return number else number = 3 * number + 1 print(number) return number print('Enter number:') try: i = int(input()) except: print('Must enter an in...
183ffb6a3cea3b6538fbc512d42c8b9cc7b7edd4
11031/project-canteen
/canteen database.py
2,054
3.859375
4
import sqlite3 con=sqlite3.connect('canteen124543.db') cursor=con.cursor() cursor.execute('CREATE TABLE IF NOT EXISTS Cold_Dish(Id integer primary key,name text, price real, quantity real)') cursor.execute('CREATE TABLE IF NOT EXISTS Hot_Dish(Id integer primary key, name text, price real,quantity real)') curso...
5c9522289c23988f6bf489e5b9ab7ebc3cc698b2
Sergii-Kravets/Learn-Python
/02_Functions/Done-task/01_hw.py
3,626
3.8125
4
''' Некоторые встроенные функции в Python имеют нестандартное поведение, когда дело касается аргументов и их значений по умолчанию. Например, range, принимает от 1 до 3 аргументов, которые обычно называются start, stop и step и при использовании всех трех, должны указываться именно в таком порядке. При этом только у ар...
2d22fe129aa49061607345493392c28865f7f348
RobertCurry0216/AoC
/2018/day8.py
1,087
3.578125
4
## part 1 ##with open('day8.txt') as f: ## data = f.read() ## ##def next_int(data): ## while len(data) > 1: ## n, data = data.split(maxsplit=1) ## yield int(n) ## yield int(data) ## ##def branch(d): ## ## child = next(d) ## meta = next(d) ## total = 0 ## for __ in range(child): ## ...
db84dc2a7512f4c3e03b19dd75aa5ef191c078c9
detroyejr/2018-advent-of-code
/src/02.py
1,158
3.84375
4
""" Day 2 """ # Part 1 def read_input(x): x = open(x).readlines() x = [x.replace("\n", "") for x in x] x = [x.replace("+", "") for x in x] return x def appears_twice(x): counter = 0 for v in x: for i in set(v): n = v.count(i) if n == 2: counter ...
35ece92f1ff62d868f3e7dd1001155e3b1fe86ca
gabriellaec/desoft-analise-exercicios
/backup/user_082/ch15_2020_03_04_20_43_39_298970.py
152
3.828125
4
qual_o_nome= input('Qual o seu nome? ') if qual_o_nome == Chris print ("Todo mundo odeia o Chris") else: print ("Olá, {0}".format(qual_o_nome))
c8d6f0ff57d95d6b892de1aa880ac4a8ab9b1c41
jkfer/LeetCode
/Reversed_Lined_List.py
910
4.0625
4
""" 206. Reverse a singly linked list. Example: Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both? """ class ListNode: def __init__(self, val): self.val = val self.next = None # defining a ...
27a4afe060a50407f989288c0c8e6aacb93a278f
staug/OrangeLord
/Utilities.py
1,623
3.71875
4
#Utilities.py module # CONSTANT and UTILITIES FILES import pygame # set up the window SPRITEWIDTH = 24 # Ref for the default sprite size SPRITEHEIGHT = 32 # Ref for the default sprite size SPRITEDELAY = 0.1 # Ref for the default sprite delay NBTILEX = 30 # Define the world game max size (unit: a sprite width) NBTILE...
11fa3cc6434bc2f62afe85baf567628d07661271
jwkimani/Project-Euler
/id3_largest_prime_factor.py
516
3.796875
4
__author__ = 'James W. Kimani' ''' The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ? ''' def largestprimeFactor(number): primes = [] for num in range(2,number): if number%num == 0: if isPrime(num) == 'true': primes...
29b7a5cf13bf5dca7103e885dac669144968ad36
priyank-py/GettingStarted
/PythonBatch-(M-P-N-K-A-R)/retext1.py
301
3.546875
4
import re target_text= ''' 12 jan 2019 12/06/1998 22-10-2013 5 July, 2018 ''' #pattern = re.compile("\d\d[-]\w\w[-]\d\d\d\d") pattern = re.compile("\d\d?( |/|-)(\d\d)|(\w+)[ |/|,] ?\d\d\d\d") matches = pattern.finditer(target_text) for match in matches: print(match)
7f31573b7e43ed8bfefd2ff5e39ba5ee008facb5
ampinzonv/covid19-CO
/funciones.py
1,727
3.84375
4
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ === PLOTME ==== Funcion para plotear #x: eje X. y: Array con los datos del eje Y labels = titulos de cada una de los datos en Y tile: Título de la gráfica #Lista de markers y demas formatting: #https://matplotlib.org/api/_as_gen/matplotlib.p...
48888e69eb9bcf067a152949e51686c104832be1
Akshay-agarwal/DataStructures
/General/FibCalls.py
438
3.796875
4
class Counter(object): def __init__(self): self.counter = 0 def increment(self): self.counter += 1 def __str__(self): return str(self.counter) def fib(n,counter): counter.increment() if n<3: return 1 else: return fib(n-1,counter)+fib(n-2,counter) c...
01908f074f5c89c82f2e3e3417d79a600beb78e2
apiotrowski255/cs1531-lab03
/numberGuesser.py
2,630
4.0625
4
''' Number Guessing Game. Guesses are made until all numbers are guessed. The game reveals whether the closest unguessed number is higher or lower than each guess. Numbers are distinct. Typing 'q' quits the game. ''' import random MIN = 0 MAX = 10 NUM_VALUES = 3 def handle_guess(guess, values): # This function ...
293a6ff33d74f680e11a6fb86ea650a51365dd1f
gapav/face_recognition
/blur_implementations/blur_image.py
648
3.71875
4
from blur_implementations.blur_2 import Blur_2 import cv2 import numpy as np def blur_image(input_filename, output_filename = None): """ Args: input_filename(string) : filename of original image output_filename = None(string)(optional) : filename of output image Return: Integer 3...
2331ead212581b5551962c9c72eea19b045ee524
max180643/PSIT-IT
/Week-10/MissingCard I 3.0.py
306
3.734375
4
""" MissingCard I Author : Chanwit Settavongsin """ def main(key, card): """ Find missing card """ _ = [card.append(rank + suit) for rank in key for suit in "SHDC"] _ = [card.remove(input()) for i in range(51)] print(card[0]) main(["A", "K", "Q", "J", "10", "9", "8", "7", "6", "5", "4", "3", "2"], [])
b1ed798590bbccd3e0be77338bf23e703ad4117c
sirius206/LeetcodePython
/0204-Count_Primes.py
411
3.671875
4
class Solution: def countPrimes(self, n: int) -> int: if n <= 2: return 0 isPrime =[True] * n isPrime[0], isPrime[1] = False, False for i in range(2, int((n - 1)**0.5) + 1): if isPrime[i]: for j in range(i * i, n, i): ...
46f1902c945c6c1fd1d0f90e7fce2d2b1ed52fd1
Kiseloff/algorithms
/move_zeroes.py
278
3.609375
4
nums = [0, 1, 3, 0, 12] # new_arr = [num for num in arr if num != 0] # new_arr.extend([0 for i in range(arr.count(0))]) # # print(new_arr) j = 0 for num in nums: if num != 0: nums[j] = num j += 1 for i in range(j, len(nums)): nums[i] = 0 print(nums)
60ff379e0336b0a90d895b0bda1051fb8c1055f1
atvinodhkumar/Images_OpenCV
/draw_rectangle_put_text_on_image.py
1,534
3.96875
4
""" This script draws a rectangle and puts text anywhere on the image using OpenCV. The edited image can be viewed during the run-time and saved in the desired location. Syntax to draw a rectangle on an image: cv2.rectangle(image, starting_point_coordinates, ending_point_coordinates, color, thickness) cv2.rec...
1a5d4e2732d0237947b0541da82fcd0d2abd65e3
songlin1994/myedu-1904
/day02/list_type.py
2,549
4.09375
4
# 这就是一个列表的数据类型,英文 是 list, 也叫 数组 alist = ['是打发',2,'你好',6,7,1,3] # 访问list def list_sel(): # 通过索引访问 顺序取值: 从0开始数 print(alist[0]) # 访问倒数第三位 ,# 倒序取值: 从 -1 开始数 print(alist[-3]) # 通过切片访问, 语法: 前索引值 : 后索引值 取的时候取到后索引值的前一位 print(alist[2:3]) # 访问 从第五个开始到后面的所有 print(alist[4:]) # 不填值的话 从第一个...
a823faab998a3b1d892dbaba46496853f80a6b9e
manjusha18119/manju18119python
/python/stslup.py
1,155
4.40625
4
string="hello python" print(string) print(string[0:3].upper()+string[3:7]+string[7:9].upper()+string[9:10]+string[10:11].upper()+string[11:12]) print(len(string)) #Retruns length of the given string. print(string.upper()) #Converts string to uppercase. print(string.lower()) print(string.startswith('he')) #Returns True...
825e24e62cdbba41d67a6dba0ae91c0409a70460
johnehunt/PythonCleanCode
/08-functions/Product.py
1,291
4.125
4
from typing import List credit = 10 class Product: def __init__(self, name, price): self.name = name self.price = price Cart = List[Product] def calculate_price(products: Cart) -> float: """Returns the final price of all selected products""" price = 0 for product in products: ...
e60b51bd9201b17f4487d67099afb31da410f5e6
zixuedanxin/100
/12素数.py
344
3.65625
4
#素数(101,200) import math print(int(12.90877)) a=0 loop = 1 for i in range(101,201): k=int(math.sqrt(i)) for j in range(2,k+1): #这里要注意+1 , int是取整 if i%j==0: loop = 0 break if loop == 1: print(i) a+=1 loop = 1 print('%d个' %a) print(int(math.sqrt(121)))
a0079163eab467a228cc904133dda4b3904ce862
hqqiao/pythonlearn
/8-Advanced features1-slice.py
4,479
3.65625
4
# -*- coding: utf-8 -*- #1-构造一个1, 3, 5, 7, ..., 99的列表,可以通过循环实现: L =[] n =1 while n<=99: L.append(n) n+=2 print(L) #2-取一个list或tuple的部分元素 #取前N个元素,也就是索引为0-(N-1)的元素,可以用循环 ''' python range()函数可创建一个整数列表,一般用在for循环中。 函数语法 range(start, stop[, step]) 参数说明: start:计数从start开始。默认是从0开始。例如range(5)等价于range(0, 5); stop:计数到 stop...
0dec9069bae1139d85c726a0f21aa795acb5e955
josejpalacios/codecademy-python3
/Lesson 05: Loops/Lesson 02: Code Challenge: Loops/Exercise 03: Greetings.py
713
4.46875
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. #...
2f13e842d6ce1d32ff34a0026228bf2041c14bcd
msayin/python-challenge
/pyPoll.py
1,686
3.59375
4
# coding: utf-8 # In[71]: # Dependencies import csv # Files to load and output (Remember to change these) file_to_load = "Downloads/election_data.csv" file_to_output = "Downloads/pythonchallenge2.txt" total_votes = 0 number_candidates = 0 candidate_list = [] candidate_votes = {} maxvotes = -1 # Read the csv a...
cfe3464f7b141b0f837fc36692f1aee2ca2203ec
evelinRodriguez/tareaProgramacion
/operadores logicos.py
522
4.125
4
#operadores logicos print("conjuncion (and)") num1=int(input("escriba un numero mayor que 2 y menor a 5")) if num1 > 2 and num1 < 5 : print("el numero " , num1 , " cumploe condicion ") else: print("no se cumple") print("disyuncion (or)") palabra= input("para cumplir escriba si o yes") if palabra == "si" o...
ccc535645885edeab24d8fe5f4b9961f8dc4eff1
marinka01126/hw_Marina
/Lesson_2/_4_practice.py
779
4.375
4
""" Пользователь вводит что-нибудь с клавиатуры. Если какие-нибудь данные были введены, то на экране должно выводиться сообщение "Данные записаны." Если данные не были получены, а пользователь просто нажал Enter, то программа выводит сообщение "Данных не обнаружено." """ data = input("Введие данные...
451ef42260f6c17ba9b9f1f7ded071247be19809
Nelinger91/Projects
/intro2cs/ex11/node.py
506
3.546875
4
class Node(object): def __init__(self, task, next = None): self.task = task self.next = next self.task.priority = self.task.get_priority() def get_priority(self): return self def set_priority(self, new_priority): self.priority = new_priority return self.task.priority def get_task(self): return sel...
532bceb4f8026cab4fe002b8be8431d045b298fa
ArunShishodia/Smaller-Programs
/Advanced_Python_Class/Exercisesheet 1/Exercise 3.5.py
387
4.375
4
# Exercise 3.5 """Here python copies each list by reference""" a_list = [5] * 4 a_list[2] = 1 print(a_list) """This means that now when you change the elements of one sublist, then python uses the elements of the inner list and applies the same reference to the outer lists as well""" a_list = [[5]] * 4 a_list[2][0]...
6b17c9494319faef8c955445f8d74ab331c9a53f
Kyohei-1/first
/knock22.py
2,175
3.5625
4
# coding: utf-8 import sys import re path = sys.argv[1] # ファイルのパス def isCategory(splitedWord): # # カテゴリー行を正規表現で判定 a = '' pattern = ( r'\[\[Category:(.+)\]\]' # \[\[Category: # []はエスケープが必要だった気がするので\を付けて # [[Category から始まって ]] で終わる 3 桁以上の文字列なので、.+ ) a = re.match(patt...
fb8ffa22b3cf24f0631e605b38d2a7ea6383308a
MyVeli/ohjelmistotekniikka-harjoitustyo
/src/logic/investment_revenue.py
497
3.625
4
class YearlyRevenue: """Class for holding revenue items for one year. Is used by InvestmentPlan class. """ def __init__(self, rev): self.year = rev[2] self.revenue = list() self.rev_sum = 0 self.add_revenue(rev) def add_revenue(self, rev): self.revenue.append((re...
aba7b468da1a76fcb924949d6fe36da4043af6cd
gronkyzog/Puzzles
/problems/Euler180.py
547
3.515625
4
from fractions import Fraction import itertools def f(n,x,y,z): # due to Fermat's last theorem only n in (-2,-1,1,2) will yield zero for x,y,z <> 0 return (x+y+z)*(x**n + y**n - z**n) A = set([Fraction(a,b) for b in range(1,36) for a in range(1,b)]) counter = 0 solution = set() for n in range(-2,3): AN = {a**n:...
044bfca8747eeede6eb7a56c5740f7658a2b06e9
rojiani/algorithms-in-python
/divide-and-conquer/mergesort.py
985
3.890625
4
# assume length(A) > 0 def mergesort(A): n = len(A) if n == 1: return A else: mid = int(n/2) left = mergesort(A[0:mid]) right = mergesort(A[mid:n]) return merge(left, right) def merge(left, right): n_left = len(left) n_right = len(right) aux = [None] ...
80842ef082a3ebfd5a79cc82651b4bcd0f9eeec6
jamwine/Data-Structures-and-Algorithm
/DataStructures/DoubleLinkedList.py
4,804
4.1875
4
class DoublyLinkedListNode: def __init__(self,value): self.info=value self.prev=None self.next=None class DoubleLinkedList: def __init__(self): self.start=None def display_list(self): if self.start is None: print("List is empty.") ...
30d46281f7df3e5ddf1565751aff5c5c5b236854
xieh1987/MyLeetCodePy
/Reorder List.py
936
3.78125
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param head, a ListNode # @return nothing def reorderList(self, head): if not head or not head.next: return front, rear = head,...
5421a1cbbcd6499cb7833a8f9c761e2670155f73
anilized/Coding-Interview-Python
/Tests/test3.py
565
3.90625
4
def binToDec(bin_value): bin_value = int(bin_value) # converting binary to decimal decimal_value = 0 count = 0 while(bin_value != 0): digit = bin_value % 10 decimal_value = decimal_value + digit * pow(2, count) bin_value = bin_value//10 count += 1 # returnin...
375f15eaaab4750ee669f26089896fb653324e01
borislavstoychev/Soft_Uni
/soft_uni_basic/Nested Loops/lab/05. Travelling.py
274
3.984375
4
while True: destination = input() if destination == 'End': break budget = float(input()) curent_money = 0 while curent_money < budget: money = float(input()) curent_money += money print(f'Going to {destination}!')
64229d94c5a92310d71502856a5671bebd9e2514
jih3508/study_ml
/Numpy/2D_arry.py
208
3.546875
4
#2D Array with Numpy import numpy as np t = np.array([[1., 2., 3.], [4. , 5., 6.], [7., 8., 9.], [10., 11., 12.]]) print(t) print('Rank of t: ', t.ndim) # print('shape of t: ', t.shape) #
4f85222ca09d09136e093166b121f47b173018e1
wayde-P/python_study
/day2_161016/list.py
323
3.71875
4
names = ["tom", "jerry", "shuke", "beita", ""] names.insert(2, "bbb") # 插入到index的前面 # 删除 names.remove("bbb") del names[3] names.pop() # 删除并返回删除的值 # 改 names[1] = '汤姆' # 查 names[1] names[-3:] # 获取最后3个元素 names.index() # 取下标 names.extend() # 合并字符串
a2b25c4d698bb543ae5b97e59df137cf5bb6b7ca
kailunfan/lcode
/242.有效的字母异位词.py
1,221
3.734375
4
# # @lc app=leetcode.cn id=242 lang=python # # [242] 有效的字母异位词 # # https://leetcode-cn.com/problems/valid-anagram/description/ # # algorithms # Easy (59.44%) # Likes: 206 # Dislikes: 0 # Total Accepted: 109.9K # Total Submissions: 182.3K # Testcase Example: '"anagram"\n"nagaram"' # # 给定两个字符串 s 和 t ,编写一个函数来判断 t 是否...
5e33a9f8aecfc470f683ced39fae30f29879737f
jaeho310/algorithm
/algorithm50.py
334
3.640625
4
def solution(numbers): answer = '' cache = [] for i in numbers: temp = list(map(str,str(i))) cache.append(temp) sortedNum = sorted(cache,key=lambda x: x*3,reverse=True) for i in sortedNum: for j in i: answer += str(j) return str(int(answer)) print(solut...
24f9e282a9374a9a66746502afbc9c431c5943e8
isimic95/leetcoding
/concatenation_sum.py
148
3.65625
4
def concatenationsSum(a): result = 0 for x in a: for y in a: result += int("".join([str(x), str(y)])) return result
15fa9048c99c7f6f17c74fb16463d84e85ca5397
ynikitenko/lena
/lena/structures/hist_functions.py
21,710
3.65625
4
"""Functions for histograms. These functions are used for low-level work with histograms and their contents. They are not needed for normal usage. """ import collections import copy import itertools import operator import re import sys if sys.version_info.major == 3: from functools import reduce as _reduce else: ...
7dc25a1cdbe8aa1d3de6749ec46a7c6168102b60
niccolozy/Snake
/Snake.py
350
3.65625
4
#!/usr/bin/env python class Snake: def __init__(self,body): self.body = [] for i in body: self.body.append(i) def moveTo(self,position,food=False): self.body.append(position) if not food: self.body.pop(0) def getHead(self): return self.body[-1] def getTail(self): return self.body[0] def get...
a808a33c6adcb71bbd1d22c7eaf0c65def77fc2a
harrisonBirkner/PythonSP20
/Lab4/Lab4/PenniesForPay.py
497
3.84375
4
daysWorked = int(input('How many days did you work? ')) totalPennies = 1 print(' Salary/Day ') print('------------') print('1 . $ 0.01') for day in range(2, daysWorked + 1): if totalPennies == 1: totalPennies = 2 dailyPennies = 2 else: dailyPennies *= 2 totalPennies += da...
2bd57172eef759520b0ab7917d1d9bcd08fa554e
seungbin-lee0330/2021
/programmers_coding_test/72410.py
1,008
3.53125
4
def solution(new_id): #문자열은 리스트 함수 사용한 수정이 안되고 슬라이싱으로 새롭게 정의해주는게 좋다 answer = '' #1 new_id = new_id.lower() # .lower()는 원본에 영향을 미치지 않는다 #2 for c in new_id: if c.isalpha() or c.isdigit() or c in ['-','_','.']: answer += c #3 while '..' in answer: # 생각하기 어렵다 아니면 리스트로 바꿔서 적당히...
d1d9484d883502e4d2d5a706bc471f6c926e19d0
ElliottBarbeau/Leetcode
/Problems/Subarrays With Product Less than a Target.py
1,122
3.765625
4
from collections import deque ''' def find_subarrays(arr, target): result = [] curr_product = 1 window_start = 0 n = len(arr) for window_end in range(n): curr_product *= arr[window_end] while (curr_product >= target): curr_product /= arr[window_start] windo...
de916963c4d73d0e8fabe103902b5d8e3c825629
verlisa/python-challenge
/PyBank/TotalRevenue.py
493
3.578125
4
# import modules import csv import os # Lists to store data date =[] revenue = [] # Open the CSV file and read the data with open('budget_data_1.csv', newline="") as csvfile: csvreader = csv.reader(csvfile, delimiter=",") # Skip header row next(csvreader, None) # Add date from each row ...
7e3b38690652c5b9021b76b10fd6f05a51dd537b
wncowan/python2_algorithms
/merge_sort.py
2,718
4.1875
4
def merge(list1, list2): print "merge called", list1, list2 sorted_list = [] reps = len(list1) + len(list2) for i in range(0, reps): if list1 == []: sorted_list.append(list2[0]) elif list2 == []: sorted_list.append(list1[0]) elif list1[0] < list2[0]: ...
5a371ebd9e98be90fa34ecc5f22f5c2eae006ff6
dynnoil/diving-in-python
/week2/lists_and_tuple_example.py
446
3.71875
4
from random import randint import statistics numbers = [] numbers_size = randint(15, 20) for _ in range(numbers_size): numbers.append(randint(10, 20)) print(numbers) # mutates list numbers.sort() half_size = len(numbers) // 2 median = None if numbers_size % 2 == 1: median = numbers[half_size] else: me...
8d51ceab384f4cd70413b73ff78e948408c22499
WhoisBsa/Curso-de-Python
/3 - Estruturas Compostas/desafio 75, tupla teclado.py
702
4.1875
4
""" Desenvolva um programa que leia quatro valores pelo teclado e guarde-os em um tupla. No final, mostre: A - Quantas vezes apareceu o valor 9; B - Em que posição foi digitado o primeiro valor 3; C - Quais foram os números pares. """ n = (int(input('1º numero: ')), int(input('2º numero: ')), int(input('3º numero...
81fe87f856c5f74713dec24a8acb618ea3514edf
gitank007/python-assignmnet
/assgn5/pr2.py
169
3.921875
4
# table of user choice x=int(input("print of table of user choice by entering the intial of the table ")) print("The table is ") for i in range(1,11): print(x*i)
899a6a810897dbb5feafa9272a69208a183b6921
Jason0221/backup
/HOME/笔记/python/Python基础代码-T/Trangle-Area-F.py
451
3.703125
4
#!/usr/bin/python #coding=utf-8 ''' #输入三角形三条边求面积 先判断两边之和是否大于第三边,符合条件,进行运算 运算公式为 s=(a+b+c)/2 面积为 s*(a+b)*(b+c)*(a+c) 在进行开方 ''' import math a = input() b = input() c = input() if a + b < c or a + c < b or b + c < a: print "input error" exit() s = (a + b + c) / 2 area = math.sqrt(s * (s - a) * (s - b) * (...
0d310bf719a92cfb35a26e1b5b986ed99274b592
TDewayneH/CTI110
/CTI-110/M7-Functions/M7HW1_TestGrades_Hicks.py
1,136
4.15625
4
#A program to show the average test scores and give a grade #15NOV17 #CTI-110 M7HW1 Test Average and Grade #Dewayne Hicks def main(): totalTest = getGrade() grade = giveGrade(totalTest) print("You average of your test is", totalTest, ". Which gives you a"\ " grade score of", grade) ...
079b7f0f6b066a1832f636f01ea7d119d9d5571b
prakritii/python_practice
/random_number.py
941
4.625
5
# 1. When the game starts. Print the name of game and ask the user for his/her name. # 2. randomly generate a number between 1 to 10 and ask the user to guess the number # 3. If user's guess is correct print win message else print loss message import random game = "Random selection of Number" print(game) user = input(...
658ea93f8e7a039dc7ad6e64ca44526e0584817d
Jeevan1351/Python_Bootcamp
/Activity_17.py
357
3.546875
4
def get_lot(): line = input()[2:-2] return [tuple(t[1:-1].split("\', \'")) for t in line.split('), (')] def lot_to_cs(listOfTuples): string = "" for (a, b) in listOfTuples: string += a+"="+b+";" return string def display(l): print(l) def main(): lot = get_lot() cs = lot...
765b8c6ba0b7534ebf6a0dd82dbc90a439353a4b
CSant04y/holbertonschool-higher_level_programming
/0x02-python-import_modules/3-infinite_add.py
198
3.734375
4
#!/usr/bin/python3 if __name__ == "__main__": import sys length = len(sys.argv) num1 = 0 for i in range(1, length): num1 += int(sys.argv[i]) print("{:d}".format(num1))
87c3a2086dd1e5cf6b59a90e1f010b4ec7508d25
Arturogv15/Compilador
/Tabla LR1/TablaLR.py
3,224
3.5
4
from pila import Pila as pila from Lexico import Lexico as lexico from numpy import array class TablaLR: def __init__(self): self.aceptacion = False self.tabla = array([[2,0,0,1], [0,0,-1,0], [0,3,-3,0], [...
a3b8aac905e52a4488b3bd26e70cd76f3ff2d626
Rahul7656/Coding
/GeeksforGeeks/BST/7.BinaryTreeToBST.py
1,343
4.09375
4
''' Given a Binary Tree, convert it to a Binary Search Tree. The conversion must be done in such a way that keeps the original structure of Binary Tree ''' class Node: def __init__(self,data): self.data = data self.left = self.right = None def storeInorder(root,a): if root: s...
ca583f8d897b318b7e97ef9f99b2cee575896de0
mladmon/CtCI
/02-linked_lists/2.3-delete_mid.py
761
4.125
4
from linked_list import * # O(1) runtime, O(1) space - trick is it doesn't work at the end def delete_middle(node): if node is not None and node.next is not None: node.data = node.next.data node.next = node.next.next # Let's test it! foo = Node(5) foo.append(7) foo.append(9) foo.append(13) print_list(foo) print...
2e9661559017fd1334f1aaf1eba1c5f97816a024
Densatho/Python-2sem
/aula13/usuarios.py
819
3.65625
4
class User: def __init__(self, fname, lname, rg1, cpf1, saudacao): self.first_name = fname self.last_name = lname self.rg = rg1 self.cpf = cpf1 self.saudacao = saudacao def describe_user(self): print(f'RG: {self.rg}') print(f'CPF: {self.cpf}')...
c7f2497c3722fd2c715a86a077aa8e6137c049c9
JIANZM/algorithm
/symmetricalTree.py
935
4.0625
4
""" 对称二叉树 实现一个函数判断是否是对称二叉树 if __name__ == "__main__": a = TreeNode('a') b1 = TreeNode('b') b2 = TreeNode('b') c1 = TreeNode('c') c2 = TreeNode('c') a.left = b1 a.right = b2 b1.left = c1 b2.right = c2 s = Solution() print(s.isSymmetrical(a)) """ class TreeNode: def __ini...
9250848e6b11e5fc9e3eb7b01173a74a37afc3b4
joaopver10/Python-EstruturaDeDados
/Aula 12/aula12.py
435
4.03125
4
dicionarioAluno = {} for i in range(1,3): nome = input('Digite o nome do aluno: ') nota = float(input('Digite a nota do aluno: ')) dicionarioAluno[nome] = nota with open('texto.txt', 'w') as texto: for nome, nota in dicionarioAluno.items(): texto.write(f'{nome}, {nota}\n') with open('C:/User...
88ee5c33f13d311343e09f6c38deef7e179d7f5c
murphsp1/ProjectEuler_Python
/p19.py
325
3.875
4
#Counting Sundays import calendar def main(): years = xrange(1901, 2001) months = xrange(1,13) count = 0 for y in years: for m in months: days = [calendar.weekday(y,m,d+1) for d in range(calendar.mdays[m])] if days[0]==6: count += 1 print(m,y) print(count) if __name__ == ('__main__'): m...
2698a17ae1ca8ec08044bf93e86b787c358c32de
slayers80/python-text-analysis
/WordSearch/code.py
1,789
3.78125
4
# -*- coding: utf-8 -*- """ Created on Tue May 15 21:05:15 2018 @author: lwang """ def exist(board, word): """ :type board: List[List[str]] :type word: str :rtype: bool """ def dfs(board, coord, subword, m, n): #print coord, subword, visited if len(subword) == 1: ...
212adc5337a2c8c1894d74468af4589518af94e5
andyjliang/HackerEarthProblems
/algorithms/graphs/problems/utkarsh_in_gardens.py
1,629
4
4
''' Utkarsh has recently put on some weight. In order to lose weight, he has to run on boundary of gardens. But he lives in a country where there are no gardens. There are just many bidirectional roads between cities. Due to the situation, he is going to consider any cycle of length four as a garden. Formally a garden ...
d9b7adf8f2262425fbc6a90af04f90e94866df0c
imvivek71/Machine-Learning
/LinearRegression/SimpleLinearRegression.py
1,398
3.796875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Feb 9 14:13:34 2019 @author: vivek """ # Importing the dataset import numpy as np import pandas as pd import matplotlib.pyplot as plt # Importing the dataset dataset = pd.read_csv('/home/vivek/Desktop/Salary_Data.csv') x = dataset.iloc[:,:-1].valu...
8a7233739b5a00d9d7d0b065a3ccd05d0995df93
YeswanthRajakumar/LeetCode_Problems
/Easy/day-4/Maximum 69 Number.py
529
3.765625
4
''' 1. change input to string 2. iterate through string 3.change 6 to 9 (or) 9 to 6 4. store to max(output,curr val) 5 finally,return the output ''' num = 9669 output = num str_num = str(num) for i in range(len(str_num)): #'9 6 6 9 ' check_num = list(str(num)) if check_num[i] == '6': check_num[i] = ...