blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
0497e4dca2c5e64b7cb1c737a15dc18fc3c1443e
FATIZ-CH/mundiapolis-ml
/0x01-classification/1-neuron.py
723
3.578125
4
#!/usr/bin/env python3 import numpy as np class Neuron: def __init__(self, nx): '''INTEGER & >1 CONDITION''' if type(nx) != int: raise TypeError('nx must be an integer') elif nx < 1: raise ValueError('nx must be a positive integer') else: self.__W ...
9d746d03cb9c99ab929176c5003194e1e2ff82ee
Viinky-Kevs/ClasesPython
/sesion7.py
1,679
3.859375
4
""" Mientras Que Como vimos anteriormente, en Python, el ciclo Mientras Que se maneja con "while". Por ejemplo: """ def ejemplo1(): i = 1 while i < 6: print(i) i += 1 #ejemplo1() def actividad1(): print("actividad1") # Continuemos integrando los conceptos que hemos ...
bfb4b2bc263d17db3e7ddac1f5023cf6fca39be0
FireAmpersand/231PythonProjects
/ex7.py
419
3.625
4
def flatten(list, newList): for i in range(len(list)): if type(list[i]) is type([]): newList = flatten(list[i], newList) else: newList.append(list[i]) return(newList) def testSuite(): print(flatten([2,9,[2,1,13,2],8,[2,6]], [])) print(flatten([[9,[7,1,13,2],8],[7,6]], [])) print(flatten([[9,[7,1,13,2],...
2456276e34d2435e631e142878b8d67d563bd6f7
FireAmpersand/231PythonProjects
/turtleMethods.py
211
3.5
4
import turtle wn = turtle.Screen() alex = turtle.Turtle() alex.write("Hello") #Alex writes Hello on the screen alex.penup() alex.goto(200,200) alex.begin_fill() alex.circle(20) alex.end_fill() wn.mainloop()
5212b4e60d7f376019fd415f4b912e162bd28c06
FireAmpersand/231PythonProjects
/ex8.py
422
3.625
4
def main(): strn = input("Enter text: ").lower() letterCount = {} for letter in strn: letterCount[letter] = letterCount.get(letter, 0) + 1 if letter == " ": del(letterCount[letter]) letterItems = list(letterCount.items()) letterItems.sort() print(letterItems) for i in range(len(letterItems)): tup = lett...
c25d7652a815aeed4457282f41f638e2c7ec1520
FireAmpersand/231PythonProjects
/pytest.py
147
3.625
4
a = int(input("Enter A: ")) for x in range(1, 1000): for z in range (1,1000): y = a if x*x == y*y + z*z: if y < z < x: print(y,z,x)
894ddfec618f02fcda53b13ab5b3003b0565cd11
FireAmpersand/231PythonProjects
/ex6.py
406
3.9375
4
def replace(s , old , new): "Replaces the old letter with the new one" word = s.split(old) newWord = new.join(word) print(newWord + "\n") return(newWord) def testSuite(): print("Mississippi","i","I") replace("Mississippi","i","I") s = "I love spom! Spom is my favorite food. Spom, spom, yum!" print(s,"om", ...
4a009a684956c1d21060c660e04db79ba7b287d5
JasonJieJay/0211
/0219-01.字符串操作.py
519
3.671875
4
#coding=utf-8 a='hello big chui!' print(a[0]) print(a[-2]) #print(a[30]) #切片 print(a[0:4]) print(a[:4]) print(a[4:]) print(a[3:-1]) print('*****************') #字符串的拼接 m='simida' n='kangsang' print(n+m) print(n,m) #字符串的遍历 for i in m: print(i) #成员运算 if 'i' in m: print('i is here') #去空格 #strip() 取消所有空格 #lsrtip(...
7c06ca915aaa4a0ed4a15a28ff17934f9b243f74
czunigamunoz/ahorcado_python
/juego.py
5,707
3.671875
4
from tkinter import * from tkinter import Canvas from random import randint from tkinter.messagebox import* letrasUsadas=[] vidas=6 letrasAcertadas=0 ''' Verifica si la letra que se ingreso en el entry pertenece a la palabra del archivo plano y cuantas veces esta ''' def probarletra(): global vidas global let...
4aabc7df24869143d5018d3d0e757e0704b90061
jgbarreda/software-para-construccion
/objeto_hueco.py
1,111
3.9375
4
''' En este ejemplo he creado una clase hueco, con un atributo 'tipo' que puedes definir como un string y un constructor con la medidas del hueco. Los métodos alfeizar y carpintería te dan las medidas de estos elementos en un string''' class Hueco: tipo='' def __init__(self, a, b): s...
27d0745e6199185dc5b1fb8d9739b2d0226fd606
letaniaferreira/guessinggame
/game.py
1,554
4.1875
4
"""A number-guessing game.""" # greet player # get player name # choose random number between 1 and 100 # repeat forever: # get guess # if guess is incorrect: # give hint # increase number of guesses # else: # congratulate player import random name = raw_input("Welcome, what is yo...
24200966c29778f717b014e37e55b0d0ba7576fb
psshankar64/PiGitFolderFDC
/Tutorial_Backup/Tutorial_4/justcode_bouncingblits.py
4,325
3.6875
4
''' This script loads an image, creates ball objects and then bounces them around the display surface ''' import sys import random import math import pygame import pygame.gfxdraw from pygame.locals import * pygame.init() ''' DISPLAY SETUP -----------------------------------------------------------------...
033e0562f0ef0da6b48a768f2bff23238e5aeb52
psshankar64/PiGitFolderFDC
/Tutorial_Backup/Tutorial_3/justcode_random_rect.py
1,836
3.765625
4
# This script will randomly place rectangles on the display surface, each with a random color # WARNING: if you suffer from photo-sensitive epilepsy then I'd not recommend running this script! import sys import random import math import pygame import pygame.gfxdraw from pygame.locals import * #Define some...
24b374d64dfab5739802512709e3f299f5692199
juannumo/Momento2_NuevTecn
/momento2_2.py
521
3.84375
4
# 2. Escribir una función que cuente la cantidad de apariciones de cada carácter en una cadena de texto, y los devuelva en un diccionario. from collections import defaultdict texto2 = "esto es un ensayo para contar caracteres" contador = defaultdict(int) for c in texto2: if(c.isalpha()): contador[c] +=...
395f4ef257a4edea0f608d00a21825391d5c9719
12qw1q2w/Solving-SE-with-DL
/01_random_fourier.py
466
3.640625
4
import numpy as np import matplotlib.pyplot as plt N = 100 def summation(f, n0, N): s = 0 for n in range(n0, N+1): s += f(n) return s def random_fourier(x, nmax): a = np.random.random(nmax+1)-0.5 b = np.random.random(nmax+1)-0.5 return summation(lambda n: a[n]*np.sin(n*np.pi*x) + b[n]...
770f554dff3a6a44359af3b86c26a3f8d17188e9
lipengyuan1994/computer-science-station
/MITx-6.00.1x/problem set2/q2.py
889
4.03125
4
balance = 4773 annualInterestRate = 0.2 monthlyInterestRate = annualInterestRate / 12 monthlyPayment = 0 updatedBalance = balance counter = 0 # Will loop through everything until we find a rate that will reduce updatedBalance to 0. while updatedBalance > 0: # Was stated that payments needed to happen in increments of...
05d6b70390bafc07721444c4d81a729fcacce719
Rapt0r399/HackerRank
/Python/Strings/Find a string.py
202
3.59375
4
# Enter your code here. Read input from STDIN. Print output to STDOUT s1 = raw_input() s2 = raw_input() count =0 for i in range (0, len(s1)-2) : if(s1[i:i+len(s2)]==s2) : count = count+1 print count
734393a5223b988fda14b57c5d7d1595509744c6
puzzleVerma/numerical-methods
/regula_falsi.py
994
3.859375
4
def factorial(a): result = 1 for i in range(1, a+1): result = result * i return result def e(n): e = 0.0 for i in range(0, n + 1): e = e + (1/factorial(i)) # print("iteration -", i, " ", e) return e #print(e(10)) def f(x): # return (e(10)**x) - (5*(x)**2) # return(x*...
fcb90c66edc8178db5934fdf86061120a16cff9a
borislavtotev/SoftUni-Python
/Exam/04_city_with_empty_data.py
1,401
3.78125
4
import csv import iso8601 from datetime import date try: file_name = 'city-temperature-data.csv' #input() cities = set() data = {} with open(file_name, encoding='utf-8') as f: for line in f: line = line.strip() if line: line_elements = line.sp...
0db51041a8cee9c2550908fd41b2c07ae0294e25
borislavtotev/SoftUni-Python
/Lecture1/firstExample.py
117
3.578125
4
test = "alabalanica turska panica" if len(test) > 10: print(''.join(test[0:10]) + '...') else: print test
8864c82483aeec033fa453c2245866c96f41aaa4
vokoramus/GB_python1_homework
/Homework__5/HW5_4.py
1,264
3.75
4
''' 4. Создать (не программно) текстовый файл со следующим содержимым: One — 1 Two — 2 Three — 3 Four — 4 Необходимо написать программу, открывающую файл на чтение и считывающую построчно данные. При этом английские числительные должны заменяться на русские. Новый блок строк должен записываться в новый текстовый файл. ...
8a128cd92a015b23e48966c5b77a5d803761b9e1
vokoramus/GB_python1_homework
/Homework__5/HW5_3.py
1,007
4.09375
4
'''3. Создать текстовый файл (не программно), построчно записать фамилии сотрудников и величину их окладов. Определить, кто из сотрудников имеет оклад менее 20 тыс., вывести фамилии этих сотрудников. Выполнить подсчет средней величины дохода сотрудников.''' salary_average, salary_sum = 0, 0 n, n_min = 0, 0 SALARY_MIN ...
005743d2ecbfe890ae852dffdec1c4e7779cdff8
vokoramus/GB_python1_homework
/Homework__4/HW4_4.py
781
3.84375
4
''' Представлен список чисел. Определите элементы списка, не имеющие повторений. Сформируйте итоговый массив чисел, соответствующих требованию. Элементы выведите в порядке их следования в исходном списке. Для выполнения задания обязательно используйте генератор. Пример исходного списка: [2, 2, 2, 7, 23, 1, 44, 44, 3, ...
567566abb3fad5fb82f4944fb222941988bf8fc8
vokoramus/GB_python1_homework
/Homework__1/HW1-4.py
458
4.25
4
'''4. Пользователь вводит целое положительное число. Найдите самую большую цифру в числе. Для решения используйте цикл while и арифметические операции.''' n = int(input("Введите n: ")) max_char = n % 10 while n > 0: last_chr = n % 10 if last_chr > max_char: max_char = last_chr n //= 10 print("max =...
edf2dc110ef2e76abd0f62335249dfaee1396ae4
dnlarson/Reverse_complement_DNA
/DNA-example.py
2,152
4.0625
4
#!/usr/bin/env python3 """ Author: Danielle Larson Purpose: Output the reverse-complement of the given DNA strand """ import os import sys import argparse # -------------------------------------------------- def get_args(): """get arguments""" parser = argparse.ArgumentParser( description='Reverse com...
11e76a2cdb4033107a6c3bb44b435d002c2edefd
SaishNarvekar/recommendation-system
/server/itinerary.py
2,052
3.546875
4
from server.route import Route from server.connection import Connection from server.util import Util util = Util() class Itinerary: def __init__(self,travelType,days,prefernce,state): self.travelType = travelType self.days = days self.prefernce = prefernce self.state...
2b6a314f7e7ea8b26c44c84db441fa98095e84fc
noveoko/thecalculatorgamesolver
/parse.py
551
3.78125
4
import re def parse_all(string): regex = re.compile(r"((?P<add>\+\d+)|(?P<multiply>x\d+)|(?P<divide>\/\d+)|(?P<balance>\(\d+\))|(?P<subtract>\-\d+)|(?P<remove_digit>\<\<)|(?P<first_digit_to_second>(\d+)\=\>(\d+))|(?P<insert_number>\d))") match = regex.match(string) groups = match.groupdict() return [(a...
cd6dd1fe1eb4dc3b1f8a392b57423896da780acc
adams164/python-problems
/Digital-Dice/Gamow-Stern-elevator.py
1,334
3.546875
4
import numpy as np #When waiting at the 2nd floor in a 7 story building, what is the probability that the first elevator to arrive comes from above? #Simulate waiting for an elevator, returning true if it arrives from above. def fromAbove(numFloors,numElevators): rng = np.random.default_rng() elevatorPositio...
dd8701107b306c12fd49dcb864ce35d29bc517c9
dk88/leet_practise_py
/src/binary_tree.py
4,867
3.859375
4
# encoding:utf-8 import sys __author__ = 'zhaoxiaojun' reload(sys) sys.setdefaultencoding('utf-8') # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def pre_order_traversal(sel...
7c9c2eb4f86bc4cc3df032d855dcf8b12ed32312
Brown0101/python_scripts
/reports/CSV_XLSX/convert_csv_to_xlsx_format.py
1,285
3.515625
4
import sys import csv import os import xlsxwriter # Get file name without extension file_name = os.path.splitext(os.path.basename(r"<file_location.csv>"))[0] + '.xlsx' # if we read f.csv we will write f.xlsx wb = xlsxwriter.Workbook("<filename_you_choose.xlsx") ws = wb.add_worksheet(file_name) # your worksheet titl...
1532020913bb3d12e049d871a9d544fb0d5f4abc
KD4/TIL
/Algorithm/merge_two_sorted_lists.py
1,227
4.1875
4
# Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. # splice 꼬아 잇다 # 주어준 링크드리스트 두 개를 하나의 리스트로 만들어라. 두 리스트의 노드들을 꼬아서 만들어야한다. # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x ...
c86b88b4c4f461561ad8030a64bfc7bd6dff4afa
Feynming/python_learning
/try_except.py
309
3.59375
4
#try except finally try: print('try...') x = 10 / 0 print('result:', x) except ZeroDivisionError as e: print("except:", e) finally: print("finally") print("End...") #raise def MyError(ValueError): pass def foo(s): n = int(s) if n == 0: raise MyError("invalid value:%s" % s) return 10 / n foo("0")
973fb85e4536fd264b43dc99339eb3c23310cebe
Feynming/python_learning
/dictSet.py
373
3.75
4
#dict常用api(大括号) d={'fey':'飞','ming':'明'} #print(d) print(d.get('fey')) d['sun']='孙' print(d) for (k,v) in d.items(): print("key:",k,"value:",v) #set s=set(range(10)) print(s) l=['fey','ming','sun','n'] t=set(s.upper() for s in l if isinstance(s,str)) print(t) t.add('HA') from collections import Iterable print(isinsta...
a5b4d29025f3141ca47057696c33a803958567ea
DevinKlepp/leetcode
/Easy/Tree/question98.py
621
3.765625
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # https://leetcode.com/problems/validate-binary-search-tree/solution/ class Solution: def isValidBST(self, root): return self.check(root, float("...
e7b86176bd6ed8aa3677c438ad41b29cdc89c720
DevinKlepp/leetcode
/Easy/Basic Logic/question88.py
531
3.671875
4
class Solution: def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: i, j = 0, 0 while n > 0 and m > 0: if nums1[m - 1] > nums2[n - 1]: nums1[m + n - 1] = nums1[m - 1] m -= 1 else: nums1[m + n - 1] = nums...
a6609406b527bae70d5176900ebbf350d785417f
tbrotz/ProjectEuler
/Problem0047.py
1,241
3.59375
4
#~ Distinct primes factors #~ Problem 47 #~ The first two consecutive numbers to have two distinct prime factors are: #~ 14 = 2 * 7 #~ 15 = 3 * 5 #~ The first three consecutive numbers to have three distinct prime factors are: #~ 644 = 2^2 * 7 * 23 #~ 645 = 3 * 5 * 43 #~ 646 = 2 * 17 * 19. #~ Find the first four co...
620f7c0b48e2c62ef6ce6a062d08b663c272bef9
tbrotz/ProjectEuler
/Problem0043.py
1,237
3.5
4
#~ Sub-string divisibility #~ Problem 43 #~ The number, 1406357289, is a 0 to 9 pandigital number because it is made up of each of the digits 0 to 9 in some order, but it also has a rather interesting sub-string divisibility property. #~ Let d1 be the 1st digit, d2 be the 2nd digit, and so on. In this way, we note the...
b6364e51af1472c1eec2b3bef4e9aa5d68f4e2e4
CHuber00/Simulation
/Sprint-1-Python_and_Descriptive_Statistics/Deliverables/MoreCalculations.py
2,014
4.25
4
""" Christian Huber CMS 380, Fall 2020 / Sprint 1 / MoreCalculations This script reads a text file's values and calculates and prints the mean, median, variance, and standard deviation. """ from math import sqrt import matplotlib matplotlib.use("Agg") from matplotlib import pyplot as plt def mean(x): ...
c9a709465ac644fd3bf62e82d97f20b195f24cfc
CHuber00/Simulation
/Sprint-3-Monte_Carlo_Simulation/Deliverables/LesPoissons.py
1,522
3.890625
4
""" Christian Huber CMS 380, Fall 2020 / Sprint 3 / The Ticket Problem This script plots the results of a binomial process and the poisson pmf for a series of coin flips """ from random import random import matplotlib matplotlib.use('Agg') from matplotlib import pyplot as plt from math import e from math...
baa582d919fa1f8ce36e82cf17de8cebcde36c85
Jasoncho1125/PythonTest
/py_p114-1.py
267
3.6875
4
from datetime import datetime thisYear = datetime.today().year age = int(input("올해 나이는 : ")) nextAge = 2050 - thisYear + age + 1 print("올해는 " + str(thisYear) + "년 입니다.") print("2050년은 %s살 이시네요" % str((2050 - thisYear + age)))
43d77f6121e5932ca60a1490d3f26a0ea8a6cf63
katelynarenas/order_dog_food
/food_order.py
1,837
4.03125
4
MAX_CAPACITY = 30 #the maximum amount of dogs the shelter can hold SMALL_DOG_MULTIPLIER = 10 #the amount of food to order per small dog MEDIUM_DOG_MULTIPLIER = 20 #the amount of food to order per medium dog LARGE_DOG_MULTIPLIER = 30 #the amount of food to order per large dog def order_dog_food(small_dogs: int, mediu...
3a362ffa47ce0f41a33420c216daea735dc32772
Pradeep-Sulam/ProjectEuler
/12_triangle_number.py
988
3.515625
4
# The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be: # 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... # Let us list the factors of the first seven triangle numbers: # 1: 1 # 3: 1,3 # 6: 1,2,3,6 # 10: 1,...
996654eccdb296f862f69b1652bee2d0da7189f2
Pradeep-Sulam/ProjectEuler
/7_nth_prime_number.py
350
3.984375
4
number = int(input("Enter the number ")) n = 1 prime_number_list = [] while len(prime_number_list) < number: counter = 0 for i in range(1, n+1): if n % i == 0: counter = counter + 1 if counter == 2: prime_number_list.append(n) n = n + 1 print("Length - ", len(prime_number_l...
b134ea99ee47a894bfb0206b206731aaaa0df369
facundo-hm/my-idea-of-fun
/color_shape_text/color_shape_text.py
2,605
3.671875
4
from typing import Dict, Tuple, Iterable from itertools import product import string import random # 8-bit colors COLORS_AMOUNT = 256 MAX_COLORS_TO_COMPUTE = 36 ITERATION_NUM = 3 MAX_TEXT_LENGTH = round(MAX_COLORS_TO_COMPUTE / ITERATION_NUM) letters = list(string.ascii_lowercase) colors = tuple(range(COLORS_AMOUNT)) ...
0779044e55eb618e79e6cc91c7d8d59e614713dc
yamiau/Courses
/[Udemy] Web Scraping with Python - BeautifulSoup, Requests, Selenium/00 Data Structures Refresher/List Comprehension 2.py
777
4.21875
4
'''Nested lists''' carts = [['toothpaste', 'soap', 'toilet paper'], ['meat', 'fruit', 'cereal'], ['pencil', 'notebook', 'eraser']] #or person1 = ['toothpaste', 'soap', 'toilet paper'] person2 = ['meat', 'fruit', 'cereal'] person3 = ['pencil', 'notebook', 'eraser'] carts = [person1, person2, person3] print(carts) fo...
bee679f46721866386f7365357602dfebe1d16a5
tom-borowik/A-Fun-Problem
/python/short.py
232
3.609375
4
def aSillyFunctionShort(list): '''A function that will sort a list of dictionaries and group them alphabetically by brand then type''' #Most compact solution return sorted(list, key=lambda k:(k['brand'], k['type']))
2e094d45956feada8fcc4c8fa79f7814dd3854ac
aleksei-g/11_duplicates
/duplicates.py
2,935
3.59375
4
import os import argparse def validate_dir(directory): message = None if not os.path.exists(directory): message = 'Directory \"%s\" not found!' % directory else: if not os.path.isdir(directory): message = 'Enter path \"%s\" is not directory!' % directory return message de...
1e2f75864c4a4c30650ca7137eca2c2accd2245e
lithiumspiral/python
/list.py
382
3.625
4
import random import math def fillList(count) : list = [] for i in range(0, count) : list.append(random.randint(0,10)) return list def printList(lst) : for val in lst: print(val) def sumList(lst) : sum = 0 for val in lst: sum += val return sum myList = fillList(25...
16ab5543da15a3db9c80b7526c55e3745eadf2af
lithiumspiral/python
/calculator.py
1,196
4.25
4
import math print('This calculator requires you to enter a function and a number') print('The functions are as follows:') print('S - sine') print('C - cosine') print('T - tangent') print('R - square root') print('N - natural log') print('X 0- eXit the program') f, v = input("Please enter a function and a value ").spl...
f0f22c7b782e95dd4cdba5fab35e35b6f204c32c
lithiumspiral/python
/listGen.py
565
3.90625
4
import random def createList(count) : list = [] for i in range(0, count) : list.append(random.randint(1,100)) return list def printList(lst) : for val in lst: print(val) def smallLarge(lst) : smallest = lst[0] largest = lst[0] for val in lst: if smallest > val : ...
b1ff25530c6cf88241d32edb8d7e2d1472a31d9f
AmalyaSargsyan/HTI-1-Practical-Group-1-Amalya-Sargsyan
/Homework_3/rectangle_perimeter.py
876
3.796875
4
# Ստեղծել ծրագիր, որի միջոցով օգտագործողը կմուտքագրի ուղղանկյան անկյունների կոորդինատները # (x1, y1, x2, y2, x3, y3, x4, y4) որպես իրական թվեր և ծրագիրը կտպի ուղղանկյան պարագիծը։ # Ստեղծել և լուծման մեջ օգտագործել segment_length անունով ֆունկցիա, որը կստանա x1, y1, x2, y2 արգումենտներ # և կվերադարձնի նշված ծայրերով կող...
739595d7e26f53842b00e744c069f128a3fda0b6
AmalyaSargsyan/HTI-1-Practical-Group-1-Amalya-Sargsyan
/Homework_3/missing_number.py
928
3.953125
4
# Ստեղծել ծրագիր, որի միջոցով օգտագործողը կմուտքագրի իրարից բացատով առանձնացված N-1 քանակությամբ թվեր, # որոնք գտնում են [1, N] միջակայքում և չեն կրկնվում։ Դա նշանակում է, որ այդ միջակայքում կա մի թիվ # որը բացակայում մուտքագրված արժեքի մեջ։ Ծրագիրը պետք է գտնի և տպի այդ թիվը։ def missing_number(numbers): numbers ...
9da94e9ef7ddcad683065fc65294e8a07a4ab1a2
ajithkumarkr1/AddSkill
/solutions/21. Merge Two Sorted Lists.py
414
3.5625
4
class Solution:    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:        if l1 == None:            return l2        elif l2 == None:            return l1        if l1.val < l2.val:            return ListNode(l1.val,self.mergeTwoLists(l1.next,l2))                    else:            return Li...
a673953ddc1b34392d59af17f7f383d81809bf5a
ajithkumarkr1/AddSkill
/solutions/23. Merge k Sorted Lists.py
656
3.78125
4
# Definition for singly-linked list. # class ListNode: #     def __init__(self, val=0, next=None): #         self.val = val #         self.next = next class Solution:    def mergeKLists(self, lists: List[ListNode]) -> ListNode:        ans=[]        for l in lists:            temp=l            while temp:         ...
d341acf0d4baf56501b0a4da2b6d87cc6b7e7022
ajithkumarkr1/AddSkill
/solutions/206. Reverse Linked List.py
476
3.8125
4
class Solution:    def reverseList(self, head: ListNode) -> ListNode:        self.head = head        current_node = self.head        prev_node = None        next_node = None        while current_node is not None:            next_node = current_node.next            current_node.next = prev_node            prev_...
40ddcaa8400a349a31e597c8b605387ec91f662c
alazarovieu/functions
/class/circle.py
168
4.25
4
import math print("This program calculates the area of any circle") r=input("Please enter a radius in cm: ") n=int(r) r=(n**2)*math.pi print(str(r)+" cm^2") print("x")
1e789177c591ca2aa7107fd0a83b3345de35c8f1
alazarovieu/functions
/functions/sumOfRandNums.py
188
3.640625
4
import random def fun(): total = 0 for i in range(0, 11): i = random.randint(0, 1000) total += i print("The total sum of the 10 numbers is: ", total) fun()
65804b4d3a11c893a722e50b3fa690dfa23b0c28
alazarovieu/functions
/functions/odd_or_even.py
225
4.0625
4
def fun2(number, odd=True): if number % 2 == 0: odd = False print(number, "is an even number!") else: print(number, "is an odd number") i = input("Please enter a number: ") n = int(i) fun2(n)
cde81feda8b326b3368d63a4351c0996f1fafea9
Emma-2016/introduction-to-computer-science-and-programming
/lecture06.py
2,253
3.890625
4
def squareRootBi(x, epsilon): assert x >= 0, 'x must be non-negative, not ' + str(x) assert epsilon > 0, 'epsilon must be postive, not ' + str(epsilon) low = 0 high = max(x, 1.0) #this sovle previous problem guess = (low + high) / 2.0 ctr = 1 while abs(guess**2 - x) > epsilon and ctr <= 100...
d508ae43c03ea8337d2d5dcfeb3ccfc75555df4d
Emma-2016/introduction-to-computer-science-and-programming
/lecture15.py
1,958
4.34375
4
# Class - template to create instance of object. # Instance has some internal attributes. class cartesianPoint: pass cp1 = cartesianPoint() cp2 = cartesianPoint() cp1.x = 1.0 cp2.x = 1.0 cp1.y = 2.0 cp2.y = 3.0 def samePoint(p1, p2): return (p1.x == p2.x) and (p1.y == p2.y) def printPoint(p): print '(' + ...
cc9986910553695a94fa4c0c837a3932cec73711
lloistborn/ans-chk
/answerchecker/shingle.py
187
3.609375
4
class Shingle(): def wordshingling(self, word): shingle = [] for i in range(0, len(word) - 2): shingle.append(word[i] + " " + word[i + 1] + " " + word[i + 2]) return shingle
16cccf3ea59693570bf2f56f136c351802586e9b
JoseHGT/Practca_Python
/Hoja_de_Trabajo_01.py
281
4.03125
4
# Python 3: Hoja de trabajo 0 peso = input ("¿Cuál es su peso en Kg?") estatura = input ("¿Cuál es su estatura en metros?") #Para calcular IMC = peso/(estatura*estatura) imc= round(float (peso)/float (estatura)**2,2 ) print(" Su indice de masa corporal es: IMC =",imc)
1f2ab55236635dec043ad89cbf109f76f4779d21
Ibrian93/mathematic-modelling
/lorenz-attractor/lorenz_attractor_1.py
1,568
3.984375
4
import numpy as np import matplotlib.pyplot as plt def lorenz(x, y, z, s=10, r=28, b=2.667): """ Given: x, y, z: a point of interest in three dimensional space s, r, b: parameters defining the lorenz attractor Returns: x_dot, y_dot, z_dot: values of the lorenz attractor's partial ...
1a67c7a2594ff16b19e440727ddf80949a0b20a1
smflorentino/whiteboarder
/LinkedListRep.py
917
4.0625
4
# back end for maintaining opjects that will represent the nodes # and arrows on the "whiteboard" import numpy as np class node: def __init__(self, data): self.datum = data # contains the data self.nodes = None # contains the reference to the next node def add_node(self,node): np.inser...
c97c982f8c696edaa1dee4e1a38911c06e67929b
zedikram/I0320116_Zedi-Ikram-El-Fathi_Abyan_Tugas5
/I0320116_soal1_tugas5.py
241
3.921875
4
nama = (input('Harap masukan nama anda: ')) jenis = (input('Harap masukan jenis kelamin anda P/L: ')) # memeriksa bilangan if jenis =="P": print('Selamat datang, Bunda', nama ) else: print('Selamat datang, Papah', nama ) print()
d187e911c063e5d384b284a832cea22260191ab0
Smokebird/CS-365-final-project
/test.py
243
3.5625
4
x='3 + y*5' print(x) y=0 x = int(x) print (x) ###this does not work as i planed it would. If this had worked the equation could have been entereed as an string then when it access from the tabel turn into a int the manliptat it
f31062ef7b5bd7f95aeb66af868689d95b65e6a7
DChason/scripts-and-configs
/scripts/hdelete
1,329
3.515625
4
#! /usr/bin/python3 import argparse import os import subprocess import sys def create_parser(): parser = argparse.ArgumentParser( description="Simple tool to find and delete hidden OS files like thumbs.db or ds_store.") parser.add_argument("--d", dest="directory", default=os.getcwd(), type=str, ...
6afe3be82d2d82d9e9473cdfb7eb3d0592e429d0
aakshay001/Loan_calculator
/project92.py
1,190
3.578125
4
import streamlit as st @st.cache() def calculate_emi(p,n,r): n = n*12 r = r/12 emi = p*(r/100)*((1+(r/100))**n)/(((1+(r/100))**n)-1) return round(emi,3) def calculate_outstanding_balance(p,n,r,m): n = n*12 r = r/12 R = (1+(r/100)) balance = (p*(R**n - R**m))/((R**n) - 1) return round(b...
6ff862cd669330fd672f46d259f844c04af1557f
JulioCCQ/AprendiendoPython.py
/Acumulado.py
607
3.8125
4
#se declara variables int y str acumulado=int(0) numero=str("") #En este ciclo se utiliza while with true #como condicion en el cual se formara un ciclo #infinito hasta que el numero sea vacio # y se utilice el comando break while True: numero=input("Dame un numero entero: ") if numero=="": #E...
fd7ca17cc8add406f52f3f8007ff5e806b70fa1a
Ithric/hypertorch
/hypertorch/searchspaceprimitives.py
1,349
3.515625
4
class SearchSpacePrimitive(object): pass class IntSpace(SearchSpacePrimitive): def __init__(self, from_int, to_int, default=None): self.from_int = from_int self.to_int = to_int self.default = default def __str__(self): return "IntSpace(from_int={}, to_int={})".format(self....
6803c5e0ea81704b8ab6b34af918d8e9db7df6f8
fredssbr/MITx-6.00.1x
/example-conditional.py
229
3.953125
4
565645# -*- coding: utf-8 -*- """ Created on Sat Sep 10 18:17:16 2016 @author: frederico """ x = int(input('Enter an integer:')) if x%2 == 0: print('Even number.') else: print('Odd number.') print('Finished execution.')
3f835498966366c4a404fc4eb00725bbca57fee9
fredssbr/MITx-6.00.1x
/strings-exercise2.py
304
4.1875
4
# -*- coding: utf-8 -*- """ Created on Sat Sep 10 19:59:32 2016 @author: frederico """ #Exercise 2 - Strings str1 = 'hello' str2 = ',' str3 = 'world' print('str1: ' + str1) print('str1[0]: ' + str1[0]) print('str1[1]: ' + str1[1]) print('str1[-1]: ' + str1[-1]) print('len(str1): ' + str(len(str1)))
ab79d66c5431f9f808e7973e5fd3cc8093a84ffe
fredssbr/MITx-6.00.1x
/charIsInRecursive.py
907
3.75
4
# -*- coding: utf-8 -*- """ Created on Mon Sep 26 18:43:20 2016 @author: frederico.x.silva """ def isIn(char, aStr): ''' char: a single character aStr: an alphabetized string returns: True if char is in aStr; False otherwise ''' #print("String: ", aStr) lower = "" higher = "" ...
00ce7ddd2e3fe18691908492ddd2de4ebde05559
ckceddie/OOP
/OOP_Bike.py
878
4.25
4
# OOP Bike # define the Bike class class bike(object): def __init__ (self , price , max_speed): self.price = price self.max_speed = max_speed self.miles = 0 def displayInfo(self): print "bike's price is " + str(self.price) print "maximum speed : " + str(self.max_speed...
d5ec93909c1d754b2d559e4b8b461f118f79b16b
ehpessoa/Python
/Automate-The-Boring-Stuff-With-Python/Chapter 04 - Lists/character_picture_grid.py
766
3.5625
4
#! python3 # character_picture_grid.py - Converts a list to a rotated printout grid = [ ['.', '.', '.', '.', '.', '.'], ['.', '0', '0', '.', '.', '.'], ['0', '0', '0', '0', '.', '.'], ['0', '0', '0', '0', '0', '.'], ['.', '0', '0', '0', '0', '0'], ['0', '0', '0', '0', '0', '.'], [...
75392d96521ad4f5676e65cf82bdee6b25e3c0f1
ehpessoa/Python
/Automate-The-Boring-Stuff-With-Python/Chapter 13 - Working with PDF and Word Documents/pdf_paranoia.py
3,150
3.5625
4
#! python3 # pdf_paranoia.py # usage: python pdf_paranoia {encrypt or decrypt} {folder_path} {password} import os import sys import PyPDF2 from PyPDF2.utils import PdfReadError def encrypt(folder_path, password): """ Encrypts all pdf files in given directory with given password :param folder...
6b20406d423409b7a977d67e670b61022f4f0976
ehpessoa/Python
/Automate-The-Boring-Stuff-With-Python/Chapter 03 - Functions/the_collatz_sequence.py
329
4.4375
4
#! python3 # the_collatz_sequence.py - Take user input num and prints collatz sequence def collatz(num): print(num) while num != 1: if int(num) % 2: num = 3 * num + 1 else: num = num // 2 print(num) user_num = input('Enter a number ') collatz(us...
e2d745324b2465f7cfb709bf924d97638742456b
jkbstepien/ASD-2021
/graphs/exercises/09_02_ob_find_cycle_4.py
827
3.6875
4
def bfs(G): n = len(G) for i in range(n): queue = [i] distances = [-1] * n distances[i] = 0 visited = [False] * n parent = [None] * n while queue: v = queue.pop(0) for j in range(n): if G[v][j] == 1 and not visited[j]: ...
639a47c01e32c471b846092125d32ddd23461a1e
jkbstepien/ASD-2021
/trees/bst-tree.py
9,647
4.125
4
class BSTNode: """ Class represents a single node of binary tree. """ def __init__(self, key, value): self.left = None self.right = None self.parent = None self.key = key self.value = value self.count_elem = 1 class BSTree: """ Class representing...
e573f700709125ccfd74996c4eac12b7c30dbece
jkbstepien/ASD-2021
/graphs/ford-fulkerson.py
1,609
3.75
4
from queue import PriorityQueue def bfs(graph, s, t, parent) -> bool: queue = PriorityQueue() visited = [False for _ in range(len(graph))] queue.put(s) visited[s] = True while not queue.empty(): u = queue.get() for idx in range(len(graph[u])): if visited[idx] is False ...
6604cf3f68749b72d0eeb22a76e03075d2b87a02
jkbstepien/ASD-2021
/graphs/cycle_graph_adj_list.py
1,087
4.125
4
def cycle_util(graph, v, visited, parent): """ Utility function for cycle. :param graph: representation of a graph as adjacency list. :param v: current vertex. :param visited: list of visited vertexes. :param parent: list of vertexes' parents. :return: boolean value for cycle function. "...
2938c36dff020bbdc9b01d7bc17cb29c81f61b1a
heeyeon456/chagokchagok
/python/basic/10.반복문.py
255
3.828125
4
#while, for, do~while(x) a = 1 while a<=5: if a==3: break print("a=", a) a += 1 else: print("반복문 정상탈출") print("반복문 강제탈출 ") n = 0 while n<5: n += 1 if n == 3: continue print("n=", n)
7de069cd334c90f1d71ce8cbc3b624b7bc02f9c1
heeyeon456/chagokchagok
/python/sqlite/dbTools.py
1,136
3.90625
4
import sqlite3 class DBTools: def __init__(self, dbname, table_name): self.dbname = dbname self.tablename = table_name def createTable(self): try: conn = sqlite3.connect(self.dbname) sql = 'create table if not exists {}(name var(20), ' \ '...
55ef8b25082b22e3878894c1cdf94d4bae6d23b1
heeyeon456/chagokchagok
/python/class/22.special_method.py
1,361
4.0625
4
# special method # object 의 멤버함수 class Test: #object def __init__(self): print("init call") self.a = 0 self.b = 0 self.myDic = {} #공백 dictionary def setData(self,x,y): self.a = x self.b = y def show(self): print(self.a, self.b) # 상위 클래스 object 에 있...
6ab8af2dc1a37cb5cb05b723cab2b3a8bfee7591
heeyeon456/chagokchagok
/python/sqlite/12.database_1.py
3,218
4
4
import sqlite3 as sql3 # DB가 없으면, 생성후 접송 # DB가 있으면, 접솝 def createTable(): try: conn = sql3.connect('test.db') sql_command = 'create table if not exists student(name var(20),' \ 'age int, birth date)' conn.execute(sql_command) conn.close() print("테이블 생성 성공") e...
4f939ce42d7d1c263cf67adc968c1dda300928f9
heeyeon456/chagokchagok
/python/basic/08.삼항연산자.py
280
3.640625
4
a = 5 rst = 100 if a>0 else 200 print(rst) rst = [200, 100][False] print(rst) rst = {True:100, False:200}[a>0] print(rst) score = input("점수 입력:") score = int(score) result = "합격" if score >= 70 else "불합격" result=["불합격", "합격"][score>=70] print(result)
56aa944ae7790c902fecef53123f9fc2649ea828
heeyeon456/chagokchagok
/python/basic/06.대입연산자.py
91
3.8125
4
a=3 # a = a+2 # a +=2 # a = a**2 a**=2 print(a) n = 1 # n = n+1 n +=1 # n++ (X) print(n)
968aed0029a1689771d090fce423d427ed330b3a
heeyeon456/chagokchagok
/python/regex/05.매칭메타문자.py
411
3.59375
4
import re s1 = 'apple kiwi banana straw' s2 = 'apple kiwi banana application' try: #match = re.search('ap+le|straw|melon', s1) #print( match.group() ) #my = re.findall('ap+le|straw|melon', s1) #print(my) #matchs = re.finditer('ap+le|straw|melon', s1) #for m in matchs: # print( m ) my ...
2894f3ac5c5270423e33b9d63732ff0485a4fc41
heeyeon456/chagokchagok
/python/class/14.class_basic.py
1,006
3.53125
4
class Test: # 생성자 함수 def __init__(self): print("init call") self.a = 10 self.b = 20 def setData(self, x, y): print('setData self 주소', id(self)) self.a = x self.b = y def show(self): print('show self 주소', id(self)) print(self.a, self.b) # h...
a6b8fb03fbae70083b96048fdedb701d0d2587e3
umashankar43631/python-duplicate_list_program
/number_duplication.py
1,042
4.09375
4
#program to seperate the duplicate items and no duplicate items in the given list and to display the count lst1 = [1,2,3,4,5,6,2,1,5,6,7,8,4,12,11,10,5,5,5,1,1,2,8] no_duplicates=[] duplicate_items=[] print ("Original list is : ",lst1) lst1.sort() print("After Sorting : ",lst1) duplicate_count = [] dup_count =...
a87996752698edb6022666a131c1c8d08bc0d071
harleymayes/HomemadeEncryption
/key.py
396
3.796875
4
import random def generatekey(): keystore = open("key.txt", 'w') word = input("Enter encryption word:") length = len(word) multiplier = random.randint(1,length) key = length * multiplier keystore.write(str(key)) keystore.close() return(key) def retrievekey(): keystore = open("ke...
e79c3953658bfb4d394f2f91e08e1655e36e3be7
okipriyadi/NewSamplePython
/SamplePython/samplePython/database/MongoDB/_06_find_and_query.py
6,878
4.25
4
""" You can use the find() method to issue a query to retrieve data from a collection in MongoDB. All queries in MongoDB have the scope of a single collection. Queries can return all documents in a collection or only the documents that match a specified filter or criteria. You can specify the filter or criteria in a d...
d64c67795595e66b99cb36a1458443a6ebc52486
okipriyadi/NewSamplePython
/SamplePython/samplePython/Networking/_celery/tasks.py
6,648
3.546875
4
#create celery application tasks """ In order to use celery's task queuing capabilities, our first step after installation must be to create a celery instance. This is a simple process of importing the package, creating an "app", and then setting up the tasks that celery will be able to execute in the background. """ ...
d661472a0e0a43d481e4788780f20c3187f86f2f
okipriyadi/NewSamplePython
/SamplePython/samplePython/database/SQLite/sqliteEx.py
3,929
3.75
4
import sqlite3 con = sqlite3.connect('Toko.db') # prepare a cursor object using cursor() method cur = con.cursor() #Query put Here cur.execute('SELECT SQLITE_VERSION()') # Fetch a single row using fetchone() method. data = cur.fetchone() #print the data print "SQLite version: %s" % data #Create tabel #cur.execute('...
830aaaa0664c6d8f993de0097927ff4c385c6d4e
okipriyadi/NewSamplePython
/SamplePython/samplePython/Modul/memcache/_01_Using_memcache.py
1,261
4.21875
4
""" kesimpuan sementara saya, memcache digunakan untuk menyimpan sebuah value di memori cache sehingga program lain bisa mengambil value tersebut dengan cara mencari key yang telah ditetapkan coba lihat value di file ini bisa didapatkan oleh file _02_test.py It's fairly simple. You write values using keys and expiry...
3f398d75509ca53fc9b9d907f1121ea6233b5f37
okipriyadi/NewSamplePython
/SamplePython/Basic Source /Dasar/variableAndCasting.py
1,007
3.765625
4
print 9/4 #karna keduanya integer maka menghasilkan INTEGER print 9.0/4 #menghasilkan float karna salah satunya float print float(9)/4 #pake casting juga bisa print int(9/4) #hasilnya int, int akan membulatkan kebawah print round(9.0/4) #hasilnya adalah hasil dengan pembulatan berdasarkan angka setelah koma. lbh kecil ...
03d41b53695b5cd140934c7d2ad4f3e6344e5002
okipriyadi/NewSamplePython
/SamplePython/samplePython/Modul/os/_11_TempFile_Write.py
400
3.71875
4
""" By default, the file handle is created with mode ’w+b’ so it behaves consistently on all platforms, and the caller can write to it and read from it. After writing, the file handle must be “rewound” using seek() in order to read the data back from it. """ import os import tempfile with tempfile.TemporaryFile() as ...
dc191b7153e036ca6050a135c668b195cd2558d2
okipriyadi/NewSamplePython
/SamplePython/Basic Source /ifForWhile/for.py
603
3.921875
4
for nomor in [1,2,"tiga",4,5]: print nomor tabel = [ [1, "dua", 3], ["siji",2,"telu"], ["hiji","dua", "tiga"] ] for nomor in tabel : print nomor print "bandingkan dengan for yg ini\n" for nomor in tabel : for number in nomor: print number ...
d93db45bbff954b5957cf7d8b62363877c7b0e84
okipriyadi/NewSamplePython
/SamplePython/build_in_modul/_04_getattr.py
678
4.5625
5
""" Objects in Python can have attributes. For example you have an object person, that has several attributes: name, gender, etc. You access these attributes (be it methods or data objects) usually writing: person.name, person.gender, person.the_method(), etc. But what if you don't know the attribute's name at the ...
747a7106f59a9e54aec3c2b87089bc380cd9ccb4
okipriyadi/NewSamplePython
/SamplePython/samplePython/Modul/os/_17_previlage_level_and_run_as_different_user.py
1,899
3.609375
4
""" The first set of functions provided by os is used for determining and changing the process owner ids. These are most frequently used by authors of daemons or special system programs that need to change permission level rather than run as root . This section does not try to explain all the intricate details of UNIX ...