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
2a9849f6d1bccb0f01b738aca69132c5bfe73817
c42-arun/leetcode
/src/add_two_numbers/solution.py
1,481
3.953125
4
# from list_node import ListNode # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def addTwoNumbers(self, l1, l2): "...
bca8f17a5f46a0933088a4668016666e95516321
palomaYPR/Introduction-to-Python
/CP_P25_TablasAuto.py
205
3.71875
4
# EUP que calcule las tablas de multiplicar en automatico del 1 - 10 print('Tablas ') for i in range(1,11): print('\nTABLA DEL ',i) for j in range(0,11): print(i,' x ',j,' = ',(i*j))
8017cf993539357b68d5c0ca3fa4d1ed9a90d997
palomaYPR/Introduction-to-Python
/CP_P21-2_NumerosLetra.py
655
3.96875
4
#EUP que pida ingresar números del 1-10 y te regrese ese numero en letra. Si el número se sale del rango debera mandar # un mensaje advirtiendo esto. number = int(input('Ingresa un número entre 1-10: ')) if number == 1: print('Uno') elif number == 2: print('Dos') elif number == 3: print('Tres') ...
a18806eeb1213b7fae5c963fdbf08a307d7d3fc2
palomaYPR/Introduction-to-Python
/CP_P21-1_TipoOperadores.py
418
4.125
4
# EUP que permita ingresar dos números y un operador, de acuerdo al operador ingresado se realizara la debida # operacion. num1 = int(input('Ingresa el 1er número: ')) num2 = int(input('Ingresa el 2do número: ')) ope = str(input('Ingresa el operador: ')) if ope == '*': res = num1 + num2 elif ope == '/': ...
f9c25e2e6239587a86696c5e868feca3ab8beac0
palomaYPR/Introduction-to-Python
/CP_P14_AreaCirculo.py
282
4.125
4
# Elabora un programa que calcule el area de un circulo # Nota: Tome en cuenta que la formula es A = (pi * r^2) import math message = input('Ingresa el radio del circulo: ') r = int(message) area = math.pi * r**2 #area = math.pi * math.pow(r,2) print('El area es: ',area)
05e29979c5f56e8b81848f90bea8c0079a0a4650
palomaYPR/Introduction-to-Python
/CP_P32_ListaPos.py
492
3.78125
4
# EUP que pida ingresar y se detenga cuando se ingrese uno postivo. Mostrar cuantos se ingresaron en total y cuantos # positivos y negativos. num = [] pos = 0 neg = 0 n = int(input('Ingresa un números (0 para finalizar): ')) while n != 0: if n > 0: pos += 1 else: neg += 1 num....
cc0ef2f43fecae492ce286cafdeef3a153266d83
neetukumari4858/function
/que 7.py
162
4.0625
4
function=input("enter string") name=input("enter string") def string(x,y): if len(x)>len(y): print(x) else: print(y) string(function,name)
d4a8cd543636b4375918bfe64430df051604c4da
nachoaz/Data_Structures_and_Algorithms
/Stacks/balanced_brackets.py
745
4.15625
4
# balanced_brackets.py """ https://www.hackerrank.com/challenges/balanced-brackets """ from stack import Stack def is_balanced(s): if len(s) % 2 == 1: return 'NO' else: stack = Stack() counterparts = {'{':'}', '[':']', '(':')'} for char in s: if char in c...
3a6a59691cea9f4a66c6d714ff102be381599577
nachoaz/Data_Structures_and_Algorithms
/Arrays/check_permutation.py
1,897
3.921875
4
# given two strings, check if one is a permutation of the other # string_a is a permutation of string_b if it's made up of the same letters, # just in different order. # to determine if string_a and string_b are made up of the same characters, we # could compare sorted(string_a) and sorted(string_b). # another thing ...
eb50a25f2527c3a5f4f473274ba29ab838e35dd0
nachoaz/Data_Structures_and_Algorithms
/Stacks/stack_with_max_api.py
692
3.640625
4
# stack_with_max_api """ Implements a stack with a O(1)-time operation to get the max of the stack. """ from stack import Node, Stack class StackWithMaxAPI(Stack): def __init__(self, node=None): super(StackWithMaxAPI, self).__init__(node) self.maxs = Stack(node) def push(self, data): ...
2b8596603b363eac7b4f0e85cc06405b2c8df87b
nachoaz/Data_Structures_and_Algorithms
/Linked_Lists/singly_linked_list.py
2,828
3.90625
4
# singly_linked_list.py class SinglyLinkedListNode(): """A node with a data and next attribute.""" def __init__(self, dat, next_node=None): self.data = dat self.next = next_node def __str__(self): return "| {} |".format(self.data) def __repr__(self): return self.__str...
e4a6dafd7b4971ce1630310eacdf133b767aa5fe
5l1v3r1/Learning-Python
/py4e-exercise-7.11-1.py
255
4.0625
4
prompt = str.lower(input('What is the name of the file to read? ')) try: fhand = open(prompt) except: print('Please choose an existing file') exit() for line in fhand: #if line.startswith('From:'): line = line.upper() print(line)
57fcb2897f806a3b77f5935294190cf7991b0b80
5l1v3r1/Learning-Python
/p4e-pg-81.py
359
3.890625
4
prompt = str.lower(input('What is the name of the file to read? ')) try: fhand = open(prompt) except: print('Please choose an existing file') exit() count = 0 for line in fhand: if line.startswith('From:'): line = line.rstrip() count = count + 1 #print(line) print('Total count i...
440ed54a0706c75f07a42b5f9da346cb4bba1321
Anupam-2309/Numerical-analysis
/Inverse Power method.py
1,211
3.53125
4
from sympy import * A=Matrix([[-1,1,0],[1,-1,1],[0,1,-1]]) M=A**-1 X0=Matrix([[1], [1],[1]]) Zero=zeros(3,1) print("Your Matrix is A =: ") a=pprint(M) print(" ") print("Intial Vectors is X0 =: ") b=pprint(X0) print(" ") print("------------Iteration-0------------") AX=M*X0 print("A*X0 = ",AX.eva...
71e18ee05051d083fa00285c9fbc116eca7fb3f3
bayl0n/Projects
/stack.py
794
4.25
4
# create a stack using a list class Stack: def __init__(self): self.__stack = list() def __str__(self): return str(self.__stack) def push(self, value): self.__stack.append(value) return self.__stack[len(self.__stack) -1] def pop(self): if len(self.__stack) > 0...
cf82efd8c4ce0f6afb1d647c240b6e2d0d3bc01c
belwalter/clases_programacion_i
/clase3.py
3,278
4.15625
4
#! CICLOS - FUNCIONES y MODULOS - ESTRUCTURAS DE DATOS - STRING #! Array o vectores (estatico) --> Listas dinamicas import mis_funciones datos = [2, 3, 4, 7, 0, 1, 56, 6] mis_funciones.agregar(datos, 100) print(datos) #! Ciclos while (condicionado) for (finito) # nombre = input('ingrese su nombre ') # while(nom...
16ad91f6e6452bd77f78d2083ffb5d54f140044a
belwalter/clases_programacion_i
/clase_poo.py
5,245
3.875
4
#! Programación orientada a objetos #! Componentes: Clases, Objetos y Mensajes #! Caracteristicas: Encapsulamiento, Herencia, Polimorfismo #! Sobrecarga, Constructor, Ocultamiento de la informacíon class Persona(object): """Clase que representa a una persona.""" def __init__(self, apellido, nombre, edad=...
fb0a30bbb716607382307096a431e1bcc190c88e
qiaostone/simple_search_engine
/CloudProject/mapperword.py
975
3.890625
4
#!/usr/bin/env python # Use the sys module import sys # 'file' in this case is STDIN def read_input(file): # Split each line into words for line in file: words_list = line.split(";") # tr = temp_sec[2].split(" ") # tres = tr[1][1:] # # print(res) # res = tres.split("?"...
75aa041bb410a16855ce0101a9f576c57731e51a
alpyspayzhansaya/sprint2-TDD
/Client.py
705
3.671875
4
""" private protected economy memory slots """ class Client(object): """ Why client? """ __slots__=('__dict__','_id') def __init__(self, id, card_number): """ :param id: :param card_number: """ self._id = id # protected variable self.__card_numb...
649d99f1102245585adaa9c43bf2aa7f7628b269
Tribruin/AdventOfCode
/2019/Day22.py
1,468
3.765625
4
#!/usr/local/bin/python3 deckSize = 10007 checkValue = 2019 class Deck: def __init__(self, sizeOfDeck): self.deck = list(range(sizeOfDeck)) return # def size(self): # return len(self.deck) def printDeck(self): print(self.deck) def reverseShuffle(self): print...
425d1c80339adac44ee5a37f9cab83a2855c0106
Toodoi/Tic-Tac-Toe-Game
/tic_tac_toe.py
2,698
3.921875
4
import sys class TicTacToeGame(object): board = [[None, None, None], [None, None, None], [None, None, None]] turn = True # Use boolean switching to alternate between turns instead of -1 and 1 def reset_game(self): print('\n Game reset') # Reset turn self.turn = True # Reset self.board for i in...
15198370140d3b04074d6647eda200767cc2479d
rahulpawargit/UdemyCoursePractice
/Tuples.py
290
4.1875
4
""" Tuples are same as list. The diffferance between list and tuples. Tuples are unmutalble. Tuples add using parenthesis """ my_tuple=(1, 2, 3, 4,3, 3, 3) print(my_tuple) print(my_tuple[1]) print(my_tuple[1:]) print(my_tuple[::-1 ]) print(my_tuple.index(3)) print((my_tuple.count(3)))
cfec128cbbbcdc608bd8ff51da135a0e8b1ede28
rahulpawargit/UdemyCoursePractice
/ListManage.py
468
3.765625
4
""" Lists are orderder items witch comes with brackets and seperated with comma """ lst=['Rahul', 'Mahesh', 'Vishal'] print(lst) lst[1]="Gaurav" print(lst) print(lst[::-1]) print lst2=[1,4,5,6,7,8,] sum_lst=lst2[1]+ lst2[4] print(sum_lst) sum_lst2=lst[1]+lst[2] print(sum_lst2) print("**************") list=["b...
4f76902788467b5463d0f2f69cf1dc19282eb42a
rahulpawargit/UdemyCoursePractice
/Class_Object.py
349
3.8125
4
""" Object is a instace of class """ class car(object): def __init__(self, make,year): self.makeof_Car=make, self.year=year # c1=car("bmw") # print(c1.makeof_Car) # c1=car("hyundai") # print(c1.makeof_Car) c2=car('Maruti', 2019) print(c2.makeof_Car) print(c2.year) c3=car("Innova", 2020) print(c3....
dc4d5579d9154b73b3a5f55c6b58463f83269f10
SProv7615/UNCO-Projects
/Pre-2021/2018Python_Final_Project/Python Final Project/Scene3DragonWings.py
13,551
3.734375
4
################################################################################ # Dragon Wings Class # # # # PROGRAMMER: Kevin Ritter & Stephen Provost ...
992a9f723d43e27012f62d83e67d7a488741feb1
marcossilvaxx/ExercicioPosGreve
/ExercicioPosGreve/Questao4.py
155
3.90625
4
numero = eval(input("Informe o nmero:\n")) soma = 0 for i in range(1, numero + 1): soma = soma + i print("O resultado obtido foi:", soma)
eaf66f2ee31f24966109d140a68b825fd834c8e5
Charlie-lusie/codes
/LastKNumbers.py
1,059
3.515625
4
# -*- coding:utf-8 -*- import random class Solution: def GetLeastNumbers_Solution(self, tinput, k): # write code here result = [] if (len(tinput) == 0 or k <= 0 or k > len(tinput)): return result pos, start, end = -1, 0, len(tinput) - 1 while(pos != k - 1): if (po...
eb850b1cea873c9e77d028604c8e3fafb5e33e73
darksoul985/Algorithms
/lesson_7_task_1.py
1,579
3.921875
4
#-*-coding: utf-8-*- ''' 1). Отсортируйте по убыванию методом пузырька одномерный целочисленный массив, заданный случайными числами на промежутке [-100; 100). Выведите на экран исходный и отсортированный массивы. Примечания: ● алгоритм сортировки должен быть в виде функции, которая принимает на вход массив данных, ● по...
a7a71f54738641283bb9cbf763d581cdea778666
darksoul985/Algorithms
/lesson_3_task_3.py
1,011
3.78125
4
# -*- coding: utf-8 -*- ''' 3. В массиве случайных целых чисел поменять местами минимальный и максимальный элементы. ''' from random import randint SIZE = 10 MIN_ITEM = 0 MAX_ITEM = 100 arr = [randint(MIN_ITEM, MAX_ITEM) for _ in range(SIZE)] arr_copy = [] for i in arr: # Создаем список уникальных ...
8cab0d9b484ed21bbc1501b40c2d1881c23e5685
taeryu0627/face_mask_detector
/lab_data/image_paste.py
1,038
3.546875
4
#마스크 이미지를 원본 이미지에 합성하는 코드 import face_recognition from PIL import Image, ImageDraw #이미지 열어주기 image_path = '../data/without_mask/0.jpg' mask_image_path = '../data/mask.png' face_image_np = face_recognition.load_image_file(image_path) # 이미지를 일단 불러오기만,, face_locations = face_recognition.face_locations(face_image_np, mod...
df0dc20b8cf0e323deb906f3aaee6b22fce8d985
cgMuro/auto-image-captioning
/app/app.py
1,932
4.03125
4
import streamlit as st from PIL import Image # Import functions to make the prediction from predict import model, tokenizer, maxlength from predict import extract_features, generate_description # Call all the necessary function needed to generate the caption def get_caption(img): # Extract features with st.sp...
e882447582ce286a0adce06d98c27203b0f595f4
TheDitis/TurtleFun
/TurtleFun/outward_turtle_1.0.py
1,011
3.5625
4
import turtle angle = 5 collist2 = ['red', 'crimson', 'orangered', 'darkorange', 'orange', 'gold', 'yellow', 'greenyellow', 'lawngreen', 'limegreen', 'springgreen', 'mediumspringgreen', 'aquamarine', 'turquoise', 'aqua', 'deepskyblue', 'dodgerblue', 'mediumslateblue', 'mediumpurple', 'blueviolet', 'darkviolet', 'purpl...
f8be6b325e51f76b7ff82ff402bfd16a16d621f3
iceterminal/python
/Phone Bill.py
829
4
4
###Cell Phone Bill Calculator### print ("")###Just to add more space### print ("")###Just to add more space### print ("The Economy plan includes $30 unlimited voice and text, 1 GB data for $10, and $6 for every GB over.") print ("The Normal plan includes $30 unlimited voice and text, 5 GB data for $30, and $4 f...
2ddc2876dc0797dfb98135926df05b4ab408060e
putheac/python-fun
/data_structures/tuples.py
848
4.0625
4
#10.2 Write a program to read through the mbox-short.txt and figure out #the distribution by hour of the day for each of the messages. You can #pull the hour out from the 'From ' line by finding the time and then #splitting the string a second time using a colon. #From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 ...
54749a99e2d1d13fa81cc857fc94adc4aa572e0b
Bryson14/AdvancedAlgo
/src/Final/prob1.py
2,608
3.78125
4
""" You have solar panels that are mounted on a pole in your front yard. They have three settings that tip the panels at different angles with respect to the horizontal. As the seasons change, the settings allow you to capture more solar energy by better aligning the tipping angle of the panels with the position of t...
186ea3c70994726a8b6fe9ea2d00c44e116cbc16
zaochnik555/Python_1_lessons-1
/lesson_02/home_work/hw02_easy.py
2,044
4.125
4
# Задача-1: # Дан список фруктов. # Напишите программу, выводящую фрукты в виде нумерованного списка, # выровненного по правой стороне. # Пример: # Дано: ["яблоко", "банан", "киви", "арбуз"] # Вывод: # 1. яблоко # 2. банан # 3. киви # 4. арбуз # Подсказка: воспользоваться методом .format() print("Задача 1") frui...
6db8951807791fd2c0cd6abd598c3099aeaf8a44
ranisharma20/My_file
/village_qu4.py
607
3.671875
4
def file1(): file1=open("delhi.txt","r") c=0 for i in (file1): c=c+1 print(i) file1.close() def file2(): file2=open("shimla.txt","r") d=0 for j in (file2): d=d+1 print(j) file2.close() def file3(): file3=open("others.txt","r") e=0 for k in (fil...
a667df21ea15fc0c732eacbbe7499bf997663a2b
deepanshu3131/Project-Euler
/2.py
302
3.609375
4
# -*- coding: utf-8 -*- # @Author: deepanshu # @Date: 2016-05-02 03:42:40 # @Last Modified by: deepanshu # @Last Modified time: 2016-05-02 03:45:17 t=int(input()) for i in range (t): n=int(input()) a,b,sum=1,2,0 while b<=n: if b%2==0: sum+=b a , b = b , a+b print(sum)
cac5be02d171d144119f1b42fa090e2c47a3e0f0
lgknasupra/fichas
/Exercicios/FP1/ex2.py
108
3.828125
4
num1 = int(input("Numero 1:")) num2 = int(input("Numero 2:")) valor = int((num1 - num2) * num1) print(valor)
ec8ba36cf075cfaf41c5df51a943564de1703c84
wqdchn/geektime
/algorithm-40case/array-linkedlist/swap_nodes_in_pairs.py
1,204
3.734375
4
# @program: PyDemo # @description: https://leetcode.com/problems/swap-nodes-in-pairs/submissions/ #Given a linked list, swap every two adjacent nodes and return its head. #You may not modify the values in the list's nodes, only nodes itself may be changed. #Example: # #Given 1->2->3->4, you should return the list...
f3c5782e00d49413ffec55a8503235e35cc7ac33
wqdchn/geektime
/algorithm-40case/array-linkedlist/remove_linked_list_elements.py
1,333
3.53125
4
# @program: PyDemo # @description: https://leetcode.com/problems/remove-linked-list-elements/ # @author: wqdong # @create: 2019-11-06 21:09 # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def removeElements...
c0c34cd6ff8852436f2762e9ea3bf21617397291
wqdchn/geektime
/algorithm-40case/array-linkedlist/container_with_most_water.py
1,442
3.53125
4
# @program: PyDemo # @description: https://leetcode.com/problems/container-with-most-water/ # @author: wqdong # @create: 2019-11-05 08:48 class Solution: def maxArea_1(self, height): # Time Limit Exceeded result = 0 for i in range(0, len(height)): for j in range(i + 1, len(hei...
918b830a1adfc0f24b16879e956f0c1769acde12
wqdchn/geektime
/algorithm-40case/array-linkedlist/intersection_of_two_linked_list.py
1,056
3.609375
4
# @program: PyDemo # @description: https://leetcode.com/problems/intersection-of-two-linked-lists/ # @author: wqdong # @create: 2020-01-31 09:48 class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: # Runtime: 164 ms, faster than 75.79% of Python3 ...
5c62584177146dbd867f534923fe37e38d865051
bogdan-evtushenko/codes_competition
/algorithms/battleship/Algorithm1.py
665
3.859375
4
def shipsPlacement(): # (size (1-4), [coords (x, y)(0-9) )], route ('left', 'right', 'top', 'bottom') ) return ( [4, [0, 0], 'right'], [3, [2, 0], 'right'], [3, [9, 2], 'top'], [2, [0, 5], 'bottom'], [2, [0, 9], 'bottom'], [2, [7, 9], 'left'], [1, [0, 7], ...
8958e044b9a14f969edbe14eba49a06de6858277
jnotor/data_encoding_2021
/arithmetic+coding_quiz/a_code.py
928
3.984375
4
def calc_interval(freq, word): low = 0 high = 1 for char in word: Range = high - low high = low + Range * freq[char]['higher'] low = low + Range * freq[char]['lower'] print(char, ':', low, high) return low, high def get_char_freq(word): freq = {} for char in...
8b13cb1e0cf41374ae16f29a8c2b3570cad9d309
nagamiya/AtCoder
/ABC162/162a.py
95
3.5
4
import re # input n = input() if (re.match('.*7.*', n)): print("Yes") else: print("No")
f0a24a3a5150c95a39f0ee1c578e7e9c3dcf1379
devakar/codes
/coding/fib.py
136
3.640625
4
def fib(n): if n==1: return 1 elif n==0: return 0; else: return (fib(n-1)+fib(n-2)) for i in range(10): print fib(i)
717ffcdd4454ea3efa2ae03c5b19c25521830f88
Rohit-dev-coder/AlgoCodes
/MigratingBirds0.py
733
3.578125
4
#!/bin/python3 import math import os import random import re import sys # Complete the migratoryBirds function below. def migratoryBirds(arr): dict = {} for no in arr: if no not in dict.keys(): add = {no: arr.count(no)} dict.update(add) mvalue = 0 mkey = 0 print(di...
d30ab0a04c542d2f169c3c3a6a0b0abca68b43cd
suastegui10/lps_compsci
/problem_sets/loops.py
191
3.984375
4
print("enter your favorite number") n = int(raw_input()) while n != 14: print("i don't like that number- please try another number") else: n == 14 print("that is the best number")
4a1a96234f55b6e74cbf7b814ecb9161d3eec217
marinamarsh/lab2
/lab2.py
416
3.59375
4
mas = [4, 7, 2, 3, 1, 5, 9, 8] def find_min(mas): min = mas[0] for z in mas: if z < min: min = z return min def arf_min(mas): s = 0 for z in mas: s = s + z s = s / len(mas) return s print("Mинимума в массиве:", (find_min(mas))) print("Сре...
a16da30994782b43ce082c038e006c5edbd9c7a2
rkhood/advent_of_code
/2021/day01.py
389
3.65625
4
""" Count the number of times a depth measurement increases """ def num_increases(report): depths = report.split() return sum(d2 > d1 for d1, d2 in zip(depths, depths[1:])) if __name__=="__main__": report = """ 199 200 208 210 200 207 240 2...
80f74d2267de5fc393563cbd211272282be690d3
LiChan239/Lottery-QuickPick
/lottery.py
3,521
3.9375
4
""" Program: lottery.py Anthor: Li Chan Project: Lottery Quick Pick This program generates 5 random numbers between 1 and 50. By clicking the Quick Pick button,the computer randomly selects the numbers for you. """ from tkinter import * import random # This function generates 5 random numbers between 1 an...
2452f2ac0ccceb1cdb02880202bb70918eba9f03
dumalang/python-cheatsheet
/1.5.classes.py
622
3.921875
4
class myClass(): def method1(self): print("myClass method 1") def method2(self, someString): print("myClass method 2 " + someString) def method3(self, someString=""): print("myClass method 3 " + someString) class childClass(myClass): def method1(self): myClass.method1...
f7ec1c0eca2e27e733473040f284640f75c37a80
flahlee/Coding-Dojo
/pythonFundamentals/string_list.py
586
4.125
4
#find and replace words = "It's thanksgiving day. It's my birthday, too!" day = 'day' print words.find(day) print words.replace(day, "month") #min and max x = [2,54,-2,7,12,98] print min(x) print max(x) #first and last x = ["hello", 2, 54, -2, 7, 12, 98, "world"] newX= [x[0],x[7]] print newX #new list '''sort list f...
15c90b67aa7916557275303e16bd8d69f0d8f919
Zangdarr/PPD_calcul_de_pi
/part_of_pi.py
647
3.53125
4
""" Calcul d'une partie du nombre pi Stockera le resultat dans un fichier tmp_result{numero de l'unité de calcul} """ import sys if __name__ == "__main__" : starting_value = int(sys.argv[1]) step_value = int(sys.argv[2]) max_value = int(sys.argv[3]) FILE_TMP = "tmp_result" + str(starting_value) p...
91b6ea82c9d5900f456618f178c0725bb9cca9b8
shuaijunchen/Python3
/basic/recu.py
212
3.921875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- def fact(n): return fact_iter(n, 1) def fact_iter(num, porduct): if num == 1: return porduct return fact_iter(num-1, num * porduct) print(fact_iter(1000,1))
75f2c8f77f19883b41af604e0bb70318243efcd5
Sameer19A/Python-Basics
/HelloWorld.py
243
4.28125
4
#Compulsory Task 3 name = input("Enter your name: ") age = input("Enter your age: ") print(name) #prints user entered name print(age) #prints user entered age print("") #prints a new empty line print("Hello World!")
286cb30b15f984cb922dc229773e6e2eda569ddd
Shreyasi2002/CODE_IN_PLACE_experience
/Section2-Welcome to python/8ball.py
954
4.1875
4
""" Simulates a magic eight ball. Prompts the user to type a yes or no question and gives a random answer from a set of prefabricated responses. """ import random RESPONSES = ["As I see it, yes.", "Ask again later.", "Better not to tell you now." , "Cannot predict now.", "Concentrate and ask again.", "Don't count on i...
91cc4ff7b8e7e275ba61d799d81c8eecb7587b7c
Shreyasi2002/CODE_IN_PLACE_experience
/CoreComplete/leap.py
930
4.4375
4
""" Example of using the index variable of a for loop """ def main(): pass def is_divisible(a, b): """ >>> is_divisible(20, 4) True >>> is_divisible(12, 7) False >>> is_divisible(10, 10) True """ return a % b == 0 def is_leap_year(year): """ Returns Boolean indicating ...
99e5183af9ac4d1eb9f7d3579de5884ab707cc5a
Shreyasi2002/CODE_IN_PLACE_experience
/Assignment1/Midpoint.py
1,061
3.578125
4
from karel.stanfordkarel import * """ File: Midpoint.py ------------------------ Place a beeper on the middle of the first row. """ def main(): """ Your code here """ paint_corner(CYAN) move_to_wall() paint_corner(CYAN) turn_around() move_if() while corner_color_is(BLANK): ...
ff64e3d1c5a24b8bb632ea566b77f57f105895fd
Shreyasi2002/CODE_IN_PLACE_experience
/Files/dictwriter_example.py
336
3.53125
4
import csv def write_data(): with open("data.csv", "w") as f: columns = ['x', 'y'] writer = csv.DictWriter(f, fieldnames=columns) writer.writeheader() writer.writerow({'x': 1, 'y': 2}) writer.writerow({'x': 2, 'y': 4}) writer.writerow({'x': 4, 'y': 6}) def main(): write_data() if __name__ == "__main...
96ca5bd25da8c95b57dd8e40220403795d4113fc
eduardoleyvah/calculadora2017
/TestCalculadora.py
6,764
3.5625
4
import unittest from calculadora import Calculadora class CalculadoraTest(unittest.TestCase): def setUp(self): self.operaciones = Calculadora() def test_sumar_2_mas_2_igual_4(self): self.operaciones.suma(2, 2) self.assertEquals(self.operaciones.obtener_resultado(),4) def test_sumar_1_mas_12_igual_13(self)...
163378723f74ed14830c7d8962b2ad8dab2fdd2c
elaeon/dama_ml
/src/dama/utils/seq.py
343
3.734375
4
from itertools import islice, chain def grouper_chunk(n, iterable): "grouper_chunk(3, '[1,2,3,4,5,6,7]') --> [1,2,3] [4,5,6] [7]" it = iter(iterable) while True: chunk = islice(it, n) try: first_el = next(chunk) except StopIteration: return yield cha...
d3c9754c8666e8bf95f191e7e4bba9249a10df59
Maryam200600/Task2.2
/4.py
299
4.21875
4
# Заполнить список ста нулями, кроме первого и последнего элементов, которые должны быть равны единице for i in range(0,101): if i==0 or i==100: i='1' else: i='0' print(i, end=' ')
b36d16ad2ad7b809319c1fd8104215429cf55365
AnthonyChupin/homework2
/HW5/05_5.py
542
3.8125
4
"""Создать (программно) текстовый файл, записать в него программно набор чисел, разделенных пробелами. Программа должна подсчитывать сумму чисел в файле и выводить ее на экран""" f_obj = open('05_5.txt', 'w+', encoding='utf-8') my_str = '10 1 20 49 4' f_obj.write(''.join(my_str)) f_obj.seek(0) my_list = f_obj.readline(...
6409f7f1edd4ddf0c97f02bfa6ef05eee998fdb5
AnthonyChupin/homework2
/HW6/06_4.py
3,089
4.125
4
""" Реализуйте базовый класс Car. У данного класса должны быть следующие атрибуты: speed, color, name, is_police (булево). А также методы: go, stop, turn(direction), которые должны сообщать, что машина поехала, остановилась, повернула (куда). Опишите несколько дочерних классов: TownCar, SportCar, WorkCar, PoliceCar. До...
c57ba040e3a4ecf48cb8042a90838bf53e036967
AnthonyChupin/homework2
/HW5/05_4.py
950
3.546875
4
"""Создать (не программно) текстовый файл со следующим содержимым: One — 1 Two — 2 Three — 3 Four — 4 Необходимо написать программу, открывающую файл на чтение и считывающую построчно данные. При этом английские числительные должны заменяться на русские. Новый блок строк должен записываться в новый текстовый файл."...
dfbc9f808feea559a989c356afd6f44b9fd016bd
eignatenkov/adventofcode2018
/day_01.py
584
3.5625
4
def sum_up(filename): total = 0 with open(filename) as f: for line in f: total += int(line) return total def first_twice(filename): seen_freqs = {0} cur_freq = 0 while True: with open(filename) as f: for line in f: cur_freq += int(line) ...
3431b3a8e248affafafabd9b346f9ca145564a96
dnlglsn/hacker_rank
/coin_change_problem.py
1,920
3.640625
4
# https://www.hackerrank.com/challenges/coin-change def mocked_raw_input(fpOrString): def set_raw_input_string(fpOrString): if type(fpOrString) is str: for line in fpOrString.split('\n'): yield line else: for line in open(fpOrString): yield l...
edf4a58d87d2c5cef9a6e06e2ace05ad5096268d
djoo1028/Euler
/euler01.py
1,636
4.3125
4
''' If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. ''' def findSum(arg1): a = arg1 # input value will be range for the summation arr3 = [] # multip...
558abfaa8a01ab53b54a2b2caed49b9364000a71
sls19050/proj_wrangle_osm
/find_best_place_to_live/query.py
4,426
4.15625
4
""" Uses the CustomSeattle.db and finds the best apartment to live in Capitol Hill, Seattle by minimizing cost of living, where cost of living is defined by the sum of the following two metrics; -Daily cost of walking to work -Daily cost of losing sleep """ import sqlite3 from math import sin, cos, sqrt, atan2, radia...
d3ad13106495f12e8dabe861f3af24a37063584b
abhijeet811/Programming_for_Data_Science_using_Python
/Project -2/Abhijeet Dutta Python Project/bikeshare.py
9,966
3.921875
4
import time import pandas as pd import numpy as np import json CITY_DATA = {'chicago': 'chicago.csv', 'new york': 'new_york_city.csv', 'washington': 'washington.csv'} def get_filters(): """ Asks user to specify a city, month, and day to analyze. Returns: 1. (str) city - n...
0a186e9f92527a8509f7082f2f4065d3b366e957
vinnyatanasov/naive-bayes-classifier
/nb.py
3,403
3.6875
4
""" Naive Bayes classifier - gets reviews as input - counts how many times words appear in pos/neg - adds one to each (to not have 0 probabilities) - computes likelihood and multiply by prior (of review being pos/neg) to get the posterior probability - in a balanced dataset, prior is the same for both, so we ignore it...
39e15681eadf3a931be47d00d69dc194e6ded96b
Heraklesss/RepositorioPython_005
/ciclofor.py
501
4.03125
4
#crear un ciclo for que permita ingresar para n numeros, donde n es un numero ingresado x teclado. #calcular y mostrar: cantidad de numero pares y cantidad de numeros impares. veces = int (input("Cuantos numeros ingresa?: ")) par=0 impar=0 for x in range(veces): nume = int (input("ingrese un numero : ")) if (n...
e6902a6ee31baa299a2e41068bdb4c9da4763e66
vivian2yu/leet-code
/leet-code-idea/TowSum.py
531
3.59375
4
__author__ = 'vivian' class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ left = {}; if len(nums) < 2: return False for i in range(len(nums)): if nums[i] in ...
1a816e03c814853db8ee05bb5d64b3318222a81a
osmangani37/Python_Tutorial
/IBM_NLP/Test.py
703
3.6875
4
import re findout=re.compile("i*") print(findout.findall("Osman is a good boy")) print(re.split("[a-e]", "Hi this is Osman")) print(re.sub("shi", "dim", "I am Shirin. yes it is Shirin",flags=re.IGNORECASE)) regex=r"([a-zA-Z]+) (\d+)" match=re.search(regex, "I was born on June24") try: print(match.start(),mat...
37a422387d9c238dd9c5d48d01597e3c28c18404
izabela9525/BIM-BOOM
/Functions2.py
158
3.53125
4
def welcome(): print("Hello... Welcome to Python...") welcome() def sum(a, b): c = a + b print("Sum of 2 Numbers: - " + str(c)) sum(25, 25)
f82be2fec1efde894d62dabbbe9b7c1d3fbd514b
izabela9525/BIM-BOOM
/Loops in python.py
136
4.03125
4
# For Loop with Final Range # take input from the user number = input("Pls enter number - ") for i in range(int(number)): print(i)
c1265ee93618e43cbec0d174c381ba280be4de31
izabela9525/BIM-BOOM
/increment_loop.py
333
3.90625
4
# For Loop with Starting and Final Range # Increment - 3 pozycja wyświetla co drugą liczbe #for i in range(1,10,2): # print(i) # Aby wyświetlać numeracje wstecz 3 liczba musi być na minusie. #for i in range(10,0,-1): # print(i) number = input("PLS enter number - ") for i in range(10,0,-1): print(int(num...
068fb7a95c0d33b8e9fbc9e90ec77d9590e307a1
izabela9525/BIM-BOOM
/and.py
152
4.03125
4
num = input("Please enter your number - ") num = int(num) if(num != 100): print("This is Valid number ") else: print("This is INvalid number ")
d1cb1b922a83a6e94b9d61c13f37887804178988
TonyJenkins/cfs2160-2018-python-public
/02/circle.py
165
4.4375
4
""" Find the area of a circle. """ from math import pi radius = float (input ('Enter the radius of the circle: ')) print ('The area is', pi * radius * radius)
2e1027f23d83f26820df819c55dc50c725414f37
TonyJenkins/cfs2160-2018-python-public
/04/sweet_divider.py
283
3.890625
4
sweets = int (input ('How many sweets are there? ')) bag_size = int (input ('How many sweets fit in each bag? ')) full_bags = sweets // bag_size left_over = sweets % bag_size print ('You will get', full_bags, 'full bags.') print ('There will be', left_over, 'sweets spare.')
f0b39ddce7802ef09e39599f494c3461fc18007f
rati90/mjeraarmjera
/service/trustorNot.py
2,590
4.15625
4
def hands_table_clear(table, said_cards): """ for some decisions clears table and say lists :param tuple player_hands_table_say not cleared table and say :return tuple player_hands_table_say cleared table and say """ table.clear() said_cards.clear() return table, said_cards def do_yo...
c041cb6faa773a16878b086c289196b9bd1c46b6
Alex112525/Neural-Network-with-Python
/Neural_Network.py
3,454
3.671875
4
import numpy as np import matplotlib.pyplot as plt from sklearn.datasets import make_circles # Create layers class NeuralLayer: # Receive number of connections, number of neurons and activation function def __init__(self, n_connections, n_neurons, act_fun): self.act_fun = act_fun # self.bias ...
303d1f821d682538ac66f94ba978a242294b3c00
domarps/Siruseri_Advertising_Hoardings
/siruseriSkyline.py
2,132
3.9375
4
import collections import re class SetElement: def __init__(self): self.parent = self def root(self): if self.parent is self: return self else: return self.parent.root() def union(self, other): self.root().parent = other.root() # Building has w...
d960c27c5ae53bc1ae5cf65445dab2265fc7d7e4
mohitsharma98/LeetCode30DayChallenge
/HappyNumber.py
870
3.5625
4
""" Write an algorithm to determine if a number is "happy". A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cy...
76c546a57cef782b6d6abcf5bccfc09a4d8c1f34
mingyyy/python-spark-tutorial
/rdd/sumOfNumbers/SumOfNumbersProblem.py
551
3.734375
4
import sys from pyspark import SparkContext if __name__ == "__main__": ''' Create a Spark program to read the first 100 prime numbers from in/prime_nums.text, print the sum of those numbers to console. Each row of the input file contains 10 prime numbers separated by spaces. ''' sc = SparkCont...
b9a6c4a74fff98eb517712d57e184c601bdf55ff
bluewhale1207/my_leetcode
/python/find_val_from_matrix.py
704
3.609375
4
#在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。 #请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。 def func(arr, value): length = len(arr) i =0 j = length - 1 while True: if arr[i][j] == value: return True while j >= 0 and arr[i][j] > value: j -= 1 while i <= len...
5922c587ef2d0ecd4e8aed3a87b910368a14f335
bluewhale1207/my_leetcode
/python/search_range.py
2,471
3.90625
4
''' https://leetcode.com/problems/search-for-a-range/ Given a sorted array of integers, find the starting and ending position of a given target value. Your algorithm's runtime complexity must be in the order of O(log n). If the target is not found in the array, return [-1, -1]. For example, Given [5, 7, 7, 8, 8, ...
6ab7e7c0e911cfdd2374988300fdc5a05016f225
jaredalbright/simplePasswordGenerator
/generator.py
1,451
4.0625
4
import random class Password: def __init__(self,sequence,limit): ''' No return initializes variables ''' self.sequence = sequence self.limit = limit def create_password(self): ''' Returns password Opens the text file for the word list an...
288424c361175aeef3d0b2dcaa55304ee9b5f05c
alinalihassan/nordcloud-assignment
/test/test_point.py
709
3.921875
4
import unittest from src.main import Point class PointTestCase(unittest.TestCase): def test_point_validity(self): point = Point(7, -14) self.assertEqual(point.x, 7) self.assertEqual(point.y, -14) def test_point_equality(self): point1 = Point(0, 0) point2 = Point(0, 0...
36ef9e91bf2e7b65d9a253fcb3dc0fe1f96b290e
segejung/webapptest2
/app/lib/parsers/api_parser.py
1,061
3.59375
4
from json import JSONDecodeError import requests import pandas as pd from flatten_json import flatten class APIParser: """Takes in url and json_format (flat, structured)""" def __init__(self, url, json_format): self.url = url self.json_format = json_format def parse(self): """Pa...
3493e43f4475187b025b8d3d6fc2a96d5fd1c9b8
Iris11/MITx--CMITx--6.00.1x-Introduction-to-CS-and-Programming-Using-Python
/Problem Set 2_3.py
644
3.875
4
##Problem Set 2-2 ##20150627 #balance, annualInterestRate epsilon = 0.01 lower = balance / 12 upper = balance * ((1 + annualInterestRate / 12.0) ** 12) / 12.0 result = (lower + upper) / 2.0 def rest(monthlyPayment): rest_balance = balance for m in range(12): interest = (rest_balance - monthlyPayment) ...
e370e41e77e42d4d753c3dd0fc0d6749205b1b17
orbicularis/UMpython
/python09/pythonCH9.py
2,914
4.03125
4
##fr2eng = dict() ##fr2eng['one'] = 'un' ##print(fr2eng['one']) ##vals = list(fr2eng.values()) ##word = 'brontosaurus' ##d = dict() ##for letter in word: ## if letter not in d: ## d[letter] = 1 ## else: ## d[letter] = d[letter] + 1 ## ##print(d) ##counts = { 'chuck': 1, 'annie': 42, 'jan': 100} ##...
34db48d075ff3f9aefc37f1caf019bb613ffce1d
orbicularis/UMpython
/python14/party.py
299
3.71875
4
## THIS IS A STANDALONE PROGRAM TO DEMONSTRATE INHERITANCE - party6.py LINKS TO IT class PartyAnimal: x = 0 name = '' def __init__(self, nam): self.name = nam print(self.name,'constructed') def party(self) : self.x = self.x + 1 print(self.name,'party count',self.x)
b6da7440bda14d20522ac823b3a2ea8c2c8f7d26
fstoltz/P-uppgift2019
/koden MED MasterRegister/registerMall.py
3,552
3.5
4
""" Författare: Fredrik Stoltz Datum: 17/11-2019 """ import time class Register(): def __init__(self, namn, personLista=None): #“””Skapa register””” self.__namn = namn self.__personLista = [] #denna lista ska innehålla person objekt def skrivUtAlla(self): #Skriver ut alla per...
5c58debe7983432af51176392a8969ce8a7260e2
xbx1/useful
/python/threading-python3/timer.py
462
3.5625
4
#!/usr/bin/python3 from threading import Thread import time count = 0 def timer(name, n): global count while True and count < 10: print("{} : {} ".format(name, time.strftime('%Y-%m-%d %X',time.localtime()))) time.sleep(n) count += 1 if __name__ == "__main__": t1 = Thread(target=t...
38e5299bf0a90a134e918328b8d915c73a53d3c0
li563042811/Job_test
/wenyuan_test.py
658
3.5
4
import sys def Find_minnum(list,sum,num): if len(list)==0: return -1 if sum in list: num+=1 if sum < list[0] and sum != 0: return -1 if sum>list[0] and sum<list[-1]: for i in range(len(list)): if list[i]>sum: list.pop(i) if ...
ab6848a5ae9fdc7c67c92feebb9f00c8a77f5899
li563042811/Job_test
/cars.py
338
3.9375
4
cars=['bmw','audi','toyuta'] cars_1='bmm' print(cars_1 in cars) alien={'color':'green','points':5} print(alien['color']) print(alien['points']) print(alien) alien['x']=1 alien['y']=2 print(alien) alien['color']='red' print(alien) for key,value in alien.items(): print('\nkey:'+key) print('val...
08879034ad9098f49eb98e6f7b618b40419e0e41
ychang0821/mycode
/rpggame/game.py
6,121
3.625
4
#!/usr/bin/python3 import random fuel_level = 20 #an rocksack, which is initially empty rocksack = [] # unnecessary item list pool item_list = ['water','coffee','rifle','camelbak','knife', 'alexa echo','boots','tent','key','laptop', 'asu','flashlight','food', 'pfizer vaccine','sword', ...