blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
c19bcf90ac65cff5f8855d1507bbe7c24b6d59bb | esn89/azlyricgrabber | /urlchecker.py | 2,088 | 3.53125 | 4 | #!/usr/bin/python2.7
import requests
import sys
from lxml import html
# this is just an URL for testing, please remove
urlheader = "http://search.azlyrics.com/search.php?q="
def generateURL(artist, title):
"""Generates an URL based on the user's artist and song title
Args:
artist -- artist of the s... |
e61128196cc9b688198b89bba1d32e7ff993884f | antonioqc/Programacion1920 | /primerTrimestre/introduccion_programacion_python/2alternativas_py/ej19alt.py | 1,004 | 4 | 4 | # Programa: ej19alt.py
# Propósito: Escribe un programa que pida un número entero entre uno y doce e
# imprima el número de días que tiene el mes correspondiente.
#
# Autor: Antonio Quesada
# Fecha: 23/10/2019.
#
# Variables a usar:
# * num
#
# Algoritmo:
# Leer numero de mes como entero
# Si es el 1,3,5,7,8,10,12 e... |
cc66757e63c735a55f543b9914ed76bc3f73cc86 | alexandradecarvalho/artificial-intelligence | /python-programming/sortingAlgorithms.py | 3,693 | 4.09375 | 4 | #1 - Function that, given a list of numbers, executes selection sort
def numSelectionSort(lista):
if len(lista) > 1:
potencial_trader = min(lista[1:])
if potencial_trader < lista[0]:
lista[lista.index(potencial_trader)], lista[0] = lista[0], potencial_trader
return [lis... |
feb7fc1bcaa9d4fb9694969bee9706b15e89a382 | yemre-aydin/VS-Code-Python | /01_python_giris/0408_list_operasyonlari.py | 280 | 4.15625 | 4 |
"""
listem =[2,4,6,8]
temp=listem[1]
listem[1]=listem[2]
listem[2]=temp
listem[1],listem[2]=listem[2],listem[1]
print(listem)
"""
#slice
url="www.azizbektas.com"
print(url[-3:])
print(url[0:3])
#iterable
print(url[0])
print(url[1])
print(url[2])
print(url[3])
print(url[4])
|
b5187cd59c3cf45cfb2de457c86de9111eda62a1 | chrisnorton101/myrpg | /battlescript.py | 2,379 | 3.640625 | 4 | from Classes.characters import *
from Classes.abilities import *
import time
player = player
enemy = beg_enemies[random.randrange(0,4)]
def battle():
print("A {} has attacked!".format(enemy.name))
time.sleep(1)
running = True
while running:
print("==================")
... |
2bff56880662b264b4e478114f96544931dbd869 | benamoreira/PythonExerciciosCEV | /desafio058.py | 246 | 3.859375 | 4 | from random import randint
numpc = randint(0,10)
print(numpc)
chute = 0
contachute = 0
while chute != numpc:
chute = int(input('Qual seu paupite?'))
contachute += 1
print('Voçê precisou de {} chutes para acertar!'.format(contachute)) |
89a210fc77841d194ffe0dab78765499ba7eef2d | wdahl/Newtons-Method | /newtons_method.py | 510 | 3.671875 | 4 | import math
def f(x):
return .5 + math.sin(x) - math.cos(x)
def div_f(x):
return math.cos(x) + math.sin(x)
x0 = 1
converges = False
count = 1
while count <= 4:
x1 = x0 - f(x0)/div_f(x0)
print(f'Iternation {count}:')
print(f'x0 = {x0}')
print(f'x1 = {x1}')
print(f'f(x0) = {f(x0)}')
pr... |
878eef66a416529e61f2b572e411dc26b4571c9a | suarezluis/DB_ClassRepo | /fkumi/COSC1336 - Programming Fundamentals I/Programming Assignments/Program 11/Program11-Template.py | 2,445 | 3.640625 | 4 | #***************************************************************
#
# Developer: <Your full name>
#
# Program #: <Assignment Number>
#
# File Name: <Program11.py>
#
# Course: COSC 1336 Programming Fundamentals I
#
# Due Date: <Due Date>
#
# Instructor: Fred Kumi ... |
c7de2f1e63870846a3b30b2fdb30172c1be8b217 | matheuscordeiro/random-problems | /Cracking the Coding Interview/Cap 1/1.6-string-compression.py | 425 | 3.921875 | 4 | #!/usr/local/bin/python3
# String compression
def string_compression(s):
before = ''
final = ''
count = 0
for key, character in enumerate(s):
if character != before:
if key != 0:
final = f'{final}{count}{before}'
count = 1
before = character
else:
count += 1
final = f'{final}{count}{be... |
4e1f19ae1becc203ce35103f0817da22cb2c43c2 | LalithK90/LearningPython | /privious_learning_code/String/String title() Method.py | 407 | 4.125 | 4 | str = "this is string example....wow!!!"
print(str.title())
# Description
#
# The method title() returns a copy of the string in which first characters of all the words are capitalized.
# Syntax
#
# Following is the syntax for title() method −
#
# str.title();
#
# Parameters
#
# NA
#
# Return Value
#
# This method retu... |
68d46b305a23614954d5821032a32bbaad56e611 | baiyang0223/python | /testunittest/testcls.py | 954 | 3.515625 | 4 | '''
@Author: Baiy
@Date: 2018-11-11 21:35:41
@LastEditors: Baiy
@LastEditTime: 2018-11-11 22:06:57
@Email: yang01.bai@horizon.ai
@Company: Horizon Hobot
@Description: python中cls方法和self方法
'''
class A(object):
a = 'a'
@staticmethod
def foo1(name):
print('hello', name)
def foo2(self, name)... |
573ddd641ec68b75a15c9369d22abe4f57670629 | NikilReddyM/python-codes | /itertools.permutations().py | 215 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Nov 16 20:38:29 2017
@author: HP
"""
from itertools import permutations
a = input().split()
for i in permutations(sorted(a[0]),int(a[1])):
print(''.join(i))
|
c83ded3eb546fe151ea46e56e01f7917efe2bb0c | awatimc/python-programming | /a.py | 274 | 3.890625 | 4 | userinput = input()
count ={"UPPER":0,"LOWER":0}
for i in userinput:
if userinput.isupper():
count["UPPER"]+=1
elif userinput.islower():
count["LOWER"]+=1
else:
pass
print("Upper case letter",count["UPPER"])
print("LOWER case letter",count["LOWER"])
|
5550c76a7aab923312db91d112a9f20f540bbd47 | marcvifi10/Curso-Python | /Python 1/2 - Condicionales/18 - Estructura if-elif-else/Estructura if-elif-else.py | 289 | 4.21875 | 4 | # Condicionales
numero = int(input("Entra un numero: "))
if numero > 0:
print("\nEl numero es positivo!!!")
elif numero < 0:
print("\nEl numero es negativo!!!")
elif numero == 0:
print("\nEl numero es igual a 0")
else:
print("ERROR!!!")
print("\nFIN DEL PROGRAMA!!!") |
ed2bf6994d7983ae389d7bd19a9878695fd6b913 | fabianrmz/python-course | /basic-funcions/slicing.py | 199 | 4.25 | 4 |
# slicing
x = "computer"
print(x[1:4])
# 1 to 6 in a step of 2
print(x[1:6:2])
# 3 to the end of string
print(x[3:])
# 0 to end by a step of -1
print(x[::-1])
# last item of string
print(x[-1])
|
3e8b6f5203e35b6558a2fe91a23e600d4b919d46 | MindongLab/PyHokchew | /pyhokchew/utils.py | 435 | 3.859375 | 4 | import unicodedata
def normalise(s) -> str:
"""
Normalise the Foochow Romanized string, by replacing combining characters with a combined character.
['e', '̤', '́', 'u', '̤', 'k'] normalize ---> ['é', '̤', 'ṳ', 'k']
:param s: The original string to be normalized.
:return: string
"""
retur... |
f93a554347d9222d8ad438168a7dc5cea1d7bee9 | julissaf/Python-Code-Samples-6 | /Problem2NumList10.py | 162 | 3.546875 | 4 | #Julissa Franco
#03/14/2019
#Create a number list L using a while loop
L=[]
counter=0
while counter < 11:
L.append(counter)
counter += 1
print(L)
|
ac349eb4da08279d11d242bf2bb67556729f4393 | zeirn/Exercises | /Week 4 - Workout.py | 815 | 4.21875 | 4 | x = input('How many days do you want to work out for? ') # This is what we're asking the user.
x = int(x)
# These are our lists.
strength = ['Pushups', 'Squats', 'Chinups', 'Deadlifts', 'Kettlebell swings']
cardio = ['Running', 'Swimming', 'Biking', 'Jump rope']
workout = []
for d in range(0, x): # This is ... |
c3719ad3e54f8ba02b24d884a79d39e6d94030b1 | 316513979/thc | /Clases/Programas/Tarea05/Problema9L.py | 149 | 3.640625 | 4 | def divisibilidad(a):
i=1
L=[]
while 1<=i and i<=a:
r=a%i
if r == 0:
L.append (i)
i=i+1
return L
|
f74b51feceef66761df0439c6e5610fc1eb5ab55 | bosea949/Reinforcement-Learning | /Bandits algorithms/exp3.py | 2,055 | 3.578125 | 4 | import random
import math
def categorical_draw(probs):
z = random.random()
cum_prob = 0.0
for i in range(len(probs)):
prob = probs[i]
cum_prob += prob
if cum_prob > z:
return i
return len(probs) - 1
class Exp3():
def __init__(self,weights,learning_rate):
self.weights = weights
sel... |
0f1a3a75169e0fc6c2397bcc8516c5656b926123 | mike-hmg/learnpythehardway | /exercises/ex9.py | 470 | 3.984375 | 4 | ## Exercise #9
days = "Mon Tue Wed Thu Fri Sat Sun"
# \n denotes new line
months = "Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug\nSep\nOct\nNov\nDec"
print ("Here are the days: ", days)
print ("Here are the months", months)
# 3 double quotes lets everything work multiline
print ("""
Theres something going on here.
With the... |
e6aaf45f5f393393e6c1cfc3d0c6388e7d6dbfed | Zahidsqldba07/codesignal-46 | /findSubStrings.py | 4,488 | 3.953125 | 4 | '''
Input:
words: ["Apple",
"Melon",
"Orange",
"Watermelon"]
parts: ["a",
"mel",
"lon",
"el",
"An"]
Expected Output:
["Apple",
"Me[lon]",
"Or[a]nge",
"Water[mel]on"]
'''
'''
iterate through words find out if parts are in it
iterate through parts find out if parts are in parts
replace instaces of parts within... |
f3080b02323a1793589bc7d72751220dbc3c61d5 | MrHamdulay/csc3-capstone | /examples/data/Assignment_6/clleli002/question2.py | 1,427 | 3.828125 | 4 | """basic vector calculations in 3 dimensions
Elizabeth Cilliers
20/04/2014"""
def vcalc():
InputVectorA = input ("Enter vector A:\n")
vectorA = InputVectorA.split (" ")
InputVectorB = input ("Enter vector B:\n")
vectorB = InputVectorB.split (" ")
#Addition
answer=[]
... |
a3d89cf93c38e1f4e8de147ebbc514d10c4e9ca8 | ericachesley/guessing-game | /game.py | 4,142 | 4.0625 | 4 | """A number-guessing game."""
# Put your code here
from random import randint
def round(name, mini, maxi, guesses):
number = randint(mini, maxi)
print(f"\nOk, {name}, I'm thinking of a number between {mini} and {maxi}. You have {guesses} guesses. Can you guess my number?")
count = 0
while count < gue... |
b5317d17aae9f6322773736897fcffd4c17695c0 | Unst1k/GeekBrains-PythonCourse | /DZ4/DZ4-4.py | 838 | 4.09375 | 4 | # Представлен список чисел. Определить элементы списка, не имеющие повторений.
# Сформировать итоговый массив чисел, соответствующих требованию. Элементы вывести в порядке их следования
# в исходном списке. Для выполнения задания обязательно использовать генератор.
from random import randint
numbers = [randint(1, 10)... |
4de32a5c4d1e84ae597dfe51d2e5f8f55f37f5ea | Dmdv/CS101 | /Unit6/fibonacci.py | 211 | 3.921875 | 4 | __author__ = 'dmitrijdackov'
dic = {0:0, 1:1}
def fibonacci(n):
if n in dic:
return dic[n]
value = fibonacci(n - 1) + fibonacci(n-2)
dic[n] = value
return value
print (fibonacci(36)) |
28810b100bf3be3f5f20a587a8457ded1a7036a4 | sharonsabu/pythondjango2021 | /file/file_read.py | 312 | 3.671875 | 4 | f=open("demo","r")
lst=[]
#to print all in demo
for lines in f:
print(lines)
#to append into list
lst.append(lines.rstrip("\n")) #rstrip is used to remove \n from right side of output and if \n is in left side lstrip is used
print(lst)
#to avoid duplicates (convert into set)
st=set(lst)
print(st)
|
5ac2c0302065ce8f55e3728d186a109eab658e96 | matusino221/AdventofCode_2020 | /day5.py | 3,999 | 3.921875 | 4 | import math
import re
import sys
def read_file(filename):
try:
with open(filename) as f:
content = f.readlines()
# I converted the file data to integers because I know
# that the input data is made up of numbers greater than 0
content = [info.strip() for info in conten... |
72251039560f19ab0a3ab2f7bfb52f8c18fe399f | Paupau18me/EjerciciosPatitoPython2021 | /Sesion intrductoria/p2130.py | 323 | 3.546875 | 4 | cad = input()
cad_aux = cad.split()
vowels = ['a', 'e', 'i', 'o', 'u']
vow = ''
cons = ''
for i in range(len(cad_aux)):
if cad_aux[i][0] in vowels:
vow = vow + cad_aux[i]+ ' '
else:
cons = cons + cad_aux[i]+ ' '
print(vow[:-1])
print(cons[:-1])
print(cad)
print('Espacios en blanco:',len(cad_aux)... |
96b199caae8336c5aa38c52fa0aac87e55d5d067 | Sanjeev589/HackerRank | /Python/Lists.py | 1,152 | 4.53125 | 5 | '''
Consider a list (list = []). You can perform the following commands:
1. insert i e: Insert integer e at position i.
2. print: Print the list.
3. remove e: Delete the first occurrence of integer e.
4. append e: Insert integer at the end of the list.
5. sort: Sort the list.
6. pop: Pop the last element from the lis... |
bd3e5e0ed17443bbd5d2f22792a9f5df9e5d7982 | raga22/etl-airflow | /init_db.py | 1,139 | 3.546875 | 4 | import sqlite3
from sqlite3 import Error
#Constant DB
DBDISASTER = r"/home/pratama/project/week1/dags/db/disaster.db"
#Constant table
TBLDISASTER = """ CREATE TABLE IF NOT EXISTS disaster (
id integer NOT NULL PRIMARY KEY,
keyword text NULL,
... |
2be4dbd5b2fe600562951a01fed971fcaa280611 | UAECETian/SelfLearning | /LC4 Median of Two Arrays/main.py | 426 | 3.84375 | 4 | from typing import List
class Solution:
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
nums3 = sorted(nums1 + nums2)
if len(nums3) % 2 != 0:
return nums3[len(nums3) // 2]
else:
return (nums3[len(nums3) // 2] + nums3[len(nums3) // 2 -... |
30d865d647eaba0056c8a534c768639480f22c77 | ggsant/pyladies | /iniciante/Mundo 03/Anotações das Aulas e Desafios/Aula 03 - 18/Código 05 - Variáveis Compostas (Listas - Parte 2).py | 1,526 | 4.125 | 4 | galera = list() # Cria uma nova lista vazia "galera"
dado = list() # Cria uma nova lista vazia "dado"
totmai = totmen = 0 # Cria duas variáveis simples "totmai" e "totmen" com valor 0
for c in range(0, 3): # Cria um laço "for" que será executado 3 vezes (números de 0 a 2)
dado.append(str(input('Nome: '))) # A... |
b0ba63c6016e748fc61eb12bf1d2ed3efe9546c9 | ozkanparlakkilic/PythonExercises | /IleriSeviyeModuller/dövizHesaplama.py | 993 | 3.609375 | 4 |
import requests
import sys
from bs4 import BeautifulSoup
url = "https://www.doviz.com/"
response = requests.get(url)
html_icerigi = response.content
soup = BeautifulSoup(html_icerigi,"html.parser")
values = soup.findAll("span",{"class":"value"})
kullanici_para_miktari = float(input("Paranızı giriniz : "))
if ku... |
f646c6c0dec112ccf6ee17f8162916f4731f8025 | RahulAnand-raone/Acadview-Python | /day4.py | 2,219 | 4 | 4 | l=[1,2,3,4,5]
l.append(6) #to insert 1 value in list
l.extend([7,8,9]) #add list in list
l+[10,11,12] # add list
l.insert(0,0) #add element from oth index
l.pop() #del last element from the list
l.pop(1) #delete 1st index from the list
l.clear #to empty the list
l.sort(reverse=True) #sort in reverse order
l... |
01fdf47c6c58c51a197ccbb4e6206b04c82b610e | erenkulaksiz/changeString | /changestr.py | 1,729 | 3.78125 | 4 | # Mode 0 : word mode
# Mode 1 : i cant name this mode but it changes wOrDs LiKe ThIs
# Mode 2 : setup
mode = 1
# Word for mode 0
word = "bruh"
def reverse(args):
return not args
def main():
if mode == 0:
#since python does not have switch case, i should use if else statement
print("Starting mode"... |
1c0c27da1a5ffd2ada1e238f96d4179c01990331 | RuzimovJavlonbek/anvar.nazrullayevning-mohirdev.uz-platformasidagi-dasturlash.asoslari.python-kursidagi-amaliyotlar | /sariq_dev/darslar/10_dars_uy_ishi_5_.py | 96 | 3.765625 | 4 | a = float(input("a="))
if a < 0:
print(" Manfiy son")
else:
print(" Musbat son")
input()
|
1478d70c3b3b288e70abce6700e7ebfe587976dd | fadim21-meet/meetyl1 | /meetinturtle.py | 1,125 | 4.28125 | 4 | import turtle
# Everything that comes after the # is a
# comment.
# It is a note to the person reading the code.
# The computer ignores it.
# Write your code below here...
turtle.penup()
turtle.goto(-200,-100)
turtle.pendown()
#draw the M
turtle.goto (-200,-100+200)
turtle.goto (-200+50,-100)
turtle.goto (-200+100,-... |
f4f47a9aff66dbee2b675bdeff9023267403460a | GunjanAS/Partial-Sensing | /agent1.py | 12,067 | 3.6875 | 4 | import pandas as pd
import numpy as np
from math import sqrt
import heapq
from matplotlib import pyplot
from copy import deepcopy
def create_grid(p, dim):
'''
:param p: probability with which a node is blocked
:param dim: dimension of the matrix
:return: a 2d list denoting grid where 1 = traversable n... |
43d540f0d64460c41d97defb78367518db407215 | mwesthelle/artificial-neural-network | /artificial_neural_network/base_model.py | 392 | 3.5625 | 4 | from abc import ABC, abstractmethod
from typing import Iterable, List
class BaseModel(ABC):
@abstractmethod
def fit(self, data_iter: Iterable[List[str]], labels: List[str]):
"""
Train model using data_iter
"""
@abstractmethod
def predict(self, test_data: Iterable[List[str]]):
... |
065dd388ddd934d8eb982dfe4ef34653bc18add7 | Beelthazad/PythonExercises | /EjerciciosBasicos/ejercicio4.py | 834 | 4.03125 | 4 | def esPar(numero):
if numero%2 != 0:
return bool(0)
else:
return bool(1)
def esMultiplo(num1, num2):
num3 = num1/num2
if float(num3).is_integer() == bool(1):
print(num1,"es múltiplo de", num2)
else:
print(num1,"no es múltiplo de", num2)
num = int(input("Introduce un numero a comp... |
f62ee904e1d813890815d0c9aed20c29b86fd2cb | jordanyoumbi/Python | /liste/items.py | 525 | 4 | 4 | # methode Items permet d' acceder au clé et valeur d' un dictionnaire plus facilement
#cet Exemple va nous permettre d' afficher la clé et la valeur des elements dans un dictionnaire
# Pour cela ontilisaera une boucle pour
fruits = {
"banane":9,
"orange":15,
"kiwi":4
}
# nous venon de definir le dictionn... |
6e8a20e8e262cdb063fea8e15fbf55904d3b069f | harishsakamuri/python-files | /basic python/looping1.py | 145 | 3.78125 | 4 | a=input()
for i in a:
if i == "b":
print(a.index(i))
for i in range(0,len(a)):
if a[i] == "b":
print(i)
|
d91e7a23a32b01bf17a7611b933e051ec41ea539 | rafaelperazzo/programacao-web | /moodledata/vpl_data/5/usersdata/67/2926/submittedfiles/atm.py | 187 | 3.59375 | 4 | # -*- coding: utf-8 -*-
from __future__ import division
import math
#COMECE SEU CODIGO AQUI
a=input("Digite o valor:")
c20=a/20
c10=a%20/10
b=int(c20)
c=int(c10)
print(b)
print(c)
|
95a6d6cc14cf4ccc8034b48c2b0febd831ba9f6e | Minta-Ra/CS50x_2021 | /Pset_6/MarioMore/mario.py | 605 | 4.15625 | 4 | while True:
while True:
try:
# Get height from the user
height = int(input("Height: "))
break
# If I get ValueError
except ValueError:
# Ask again for an input - continue returns the control to the beginning of the while loop
conti... |
5c40f1b8d3a0938c3da996a64b7e5c93c8cb0d29 | vishnurapps/MachineLearningEndavour | /02_simple_linear_regression/Simple_Linear_Regression.py | 1,753 | 3.90625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 5 22:31:06 2018
@author: vishnu
"""
"""
Simple linear regression deals with equations of the form y = b0 + b1x, where b0 is the y intercept
and b1 is the slope of the line. Here y is the dependent variable and x is the independent variable
The be... |
e9e52647125379c5bd0ecf1d8ffd87b8c8dbf46b | orengoa0459/CSC-121 | /CSC-121-Python/Module2/OrengoAnthony_M2Lab/OrengoAnthony_game_functions.py | 8,911 | 4.59375 | 5 | import random
# This program is a version of the "Rock", "Paper", "Scissors" game, using the python
#console. The user will have the option to play a 1, 2, or 3 round game. The winner will
#be display to the user upon completion of the game.
# Date 05/31/2021
# CSC121- M2Lab Code Modularizing
# Anthony Orengo
#Ps... |
dc8989b59adada18c1aa31bcfad34c5f6d6e3915 | apetri/GoogleJam | /src/fileFixIt/fileFixIt.py | 1,222 | 3.796875 | 4 | #!/usr/bin/env python
import sys
class DirectoryTree(object):
def __init__(self):
self.root = dict()
#Add a directory to the path
def mkdir(self,path):
#Split path into single directories
directories = path.split("/")[1:]
#Initial step
node = self.root
nof_mkdir = 0
#Cycle over directories
fo... |
1bbcf31f6fd90fa73f6ec155eae6b4c41c6af593 | skybohannon/python | /w3resource/string/49.py | 351 | 3.8125 | 4 | # 49. Write a Python program to count and display the vowels of a given text.
def count_vowels(s):
vowels = "aeiouAEIOU"
vcount = len([letter for letter in s if letter in vowels])
vlist = [letter for letter in s if letter in vowels]
print(vcount)
print(vlist)
count_vowels("The quick brown fox ju... |
064c5360530bb50f17aaa8bc37f76e64d0f5009a | MasterKali06/Hackerrank | /Problems/medium/Implementation/extra_long_factorial.py | 400 | 4.25 | 4 | '''
Calculate and print the factorial of a given integer.
n! = n * n-1 * n-2 .... 3 * 2 * 1
'''
def extraLongFactorials(n):
len = n
final_res = 0
res = n
if n == 1 or n == 2:
res = n
else:
for i in range(len - 1):
next_op = n - 1
res = res * (next_op... |
4bacb68250c5f1ff732a73415f2fc30877941daa | xiaoku521/xiaolaodi | /generate_fruit.py | 397 | 3.5625 | 4 | lst = [ 'apple', 'orange', 'banana' ]
num = 6 # 多少个水果
import random
s = ''
for i in range(num):
w = random.choice(lst) # 随机在lst中选一个元素
if i % 3 == 0: # 百分号%代表模
s += ' ' + w.upper()
if i % 3 == 1:
s += ' ' + w.title()
if i % 3 == 2:
s += ' ... |
ffce7103d3329c3dafcb7b7ad63c2a0b2d657e02 | syurskyi/Python_Topics | /070_oop/008_metaprogramming/examples/Abstract Classes in Python/a_001.py | 2,812 | 4.3125 | 4 | # An abstract class can be considered as a blueprint for other classes, allows you to create a set of methods
# hat must be created within any child classes built from your abstract class. A class which contains one or abstract
# methods is called an abstract class. An abstract method is a method that has declaration b... |
1bfa8a330385f87a9b8b6a6011962bb0f9ecea85 | hsmwm/python_test | /list.py | 1,090 | 3.796875 | 4 | # #从'don't panic!'中获取'on tap'
# phrase="don't panic!"
# plist=list(phrase)#转换成list
# for i in range(4):#连续删除四次最后的单词
# plist.pop()
# #print(plist)#don't pa
# plist.pop(0)#删除第一位 on't pa
# plist.remove("'")#ont pa
# plist.extend(([plist.pop(),plist.pop()]))#追加两个先a再p 做到交换pa
# #print(plist)
# plist.insert(2,plist.pop(3)... |
ac69169a9b04cecce544f813795e4e2546608c8f | RahulDV/Compiler | /fpj626_dantuluri/Block.py | 921 | 3.59375 | 4 | class Block:
def __init__(self, block_name=None):
self.block_name = block_name
self.instructions = []
self.next_blocks = []
self.visited = False
self.revisited = False
def get_block_name(self):
return self.block_name
def set_block_name(self, block_name):
... |
45027e03744c66f33d68cdcbb2ca604d4b761c85 | luomingmao/Python_Follish | /Others/continue.py | 176 | 3.9375 | 4 | #!/usr/bin/python
#File name: continue.py
while True:
s = input('Enter something:')
if s == 'quit':
break
if len(s) < 3:
continue
print('Input is ofsufficient length') |
e4a2daf03e497405d6f3d970d6ad02ac0f633822 | QuantumApostle/InterviewProblems | /leetcode/searchRange.py | 1,323 | 3.671875 | 4 | def searchRange(A, target):
if len(A) == 0:
print [-1, -1]
return
if len(A) == 1:
if A[0] == target:
print [0, 0]
return
else:
print [-1, -1]
return
if target < A[0] or target > A[-1]:
print [-1, -1]
return
u... |
6ed689dd8d34e54c443f326cb4c132ea21154251 | harman666666/Algorithms-Data-Structures-and-Design | /Algorithms and Data Structures Practice/LeetCode Questions/MOST IMPORTANT PROBLEMS/1458. Max Dot Product of Two Subsequences.py | 2,038 | 3.859375 | 4 | '''
1458. Max Dot Product of Two Subsequences
Hard
308
8
Add to List
Share
Given two arrays nums1 and nums2.
Return the maximum dot product between non-empty
subsequences of nums1 and nums2 with the same length.
A subsequence of a array is a new array which is formed from
the original array by deleting some (ca... |
685783d2b43c13a2b9326b51d07f7b2c144c3cda | sconde/data-structure-and-algorithms-nanodegree | /02-data-structures/xx-projects/problem_5.py | 3,017 | 3.8125 | 4 | """
Problem 5: Blockchain
"""
import hashlib
import time
import pprint
class Block(object):
def __init__(self, data, timestamp, previous_hash=0):
self.timestamp = timestamp
self.data = data
self.prev = None
self.previous_hash = previous_hash
self.hash = self.calc_hash(dat... |
1e7bc9a775d0c2aa79472a97bc48aa92e9ab7620 | CaineSilva/Python2ObfCCompiler | /test_files/factorielle.py | 580 | 3.9375 | 4 | def nothing():
s = "Nothing"
print(s)
def factorielle(n) :
if n==1 or n==0 :
return 0
else :
return factorielle(n-1)
def factorielle_while(n) :
result = 1
i = 1
while i < n :
result *= i+1
i += 1
return result
def factorielle_for(n) :
... |
bdf65f9571001154765656df7ff404e8d87e2976 | sezgincekerekli/sezginCekerekli | /sezginCekerekli.py | 185 | 3.53125 | 4 | import json
dosya = open("sezginCekerekli.json", "r")
json_dosya= json.load(dosya)
print("kimlik : " ,json_dosya["kimlik"])
# Fill in this file with the code from parsing JSON exercise
|
7fff7c2a0d06bff960e9442cd044d9e7727859cb | wenjie711/Leetcode | /python/094_BT_In_TVL.py | 746 | 3.71875 | 4 | #!/usr/bin/env python
#coding: utf-8
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def inorderTraversal(self, root):
result = []
if(root == None):
return result
if(root.left != None):
... |
da43801efd7c40696be8162a7cbce129aee07f51 | fakontello/py_algo | /Python_algorytms/Lesson_08/Lesson_08_ex_1.py | 622 | 3.703125 | 4 | # 1. На улице встретились N друзей. Каждый пожал руку всем остальным друзьям (по одному разу). Сколько рукопожатий было?
graph = [
[0, 1, 1, 1],
[1, 0, 1, 1],
[1, 1, 0, 1],
[1, 1, 1, 0]
]
# n * (n - 1) / 2
b = 0
for i in range(len(graph)):
# длину графа умножить на количество единиц в одном элеме... |
92ade505d4f5f2d13f647c4f13f947ec39f97a75 | JiageWang/Note | /MachineLearning/LinearRegression/线性回归.py | 3,528 | 3.6875 | 4 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
class LinearRegression(object):
def __init__(self):
self.theta = None
self.loss_list = []
def fit(self, X, y, lr=0.001, iters=1000):
"""train the model with input X and y"""
... |
47a5f436f649316f839653a080c1ea95cf86b516 | unutulmaz/foodfie_flask | /Analysis/Notifications/test.py | 1,064 | 3.734375 | 4 | # from sklearn import neural_network.
#
# class Python:
#
# vips = 'aa'
#
# def __init__(self, name, age):
# self.name = name
# self.age = age
#
# def print_data(self):
# print(self.name, self.age)
#
# @classmethod
# def print_class(cls):
# print(Python... |
77e3c9796a823e66d4f7a456df7d043a8552af65 | shivam675/Quantum-CERN | /venv/Lib/site-packages/examples/coins/coins.py | 1,070 | 3.6875 | 4 | #!/usr/bin/python
#
# 100 coins must sum to $5.00
#
# That's kind of a country-specific problem, since depending on the
# country there are different values for coins. Here is presented
# the solution for a given set.
#
from constraint import Problem, ExactSumConstraint
import sys
def solve():
problem = Problem()... |
aa69dd86aaee9798ff154dec4b832ababf08ad92 | JoaoPedroPiotroski/School-Stuff | /atvd19.py | 339 | 3.921875 | 4 | condition = True
soma = 0
numero = []
while condition:
num=int(input('Digite o numero: '))
if (num) != 0 and 0 < num <= 1000 :
soma += (num)
numero.append(num)
else:
break
print('Soma: ' +str(soma))
print('menor valor: %d' %(min(numero)))
print('maior valor: %d' %(max... |
8bb6032b64f07df63cfc9a60c029cda10d3493de | mfitzp/smrtr | /apps/resources/isbn.py | 5,795 | 3.9375 | 4 | #!/usr/bin/env python
# isbn.py
# Code for messing with ISBN numbers
# Especially stuff for converting between ISBN-10 and ISBN-13
# Copyright (C) 2007 Darren J Wilkinson
# Free GPL code
# Last updated: 14/8/2007
import sys,re
__doc__="""Code for messing with ISBN numbers. Stuff for validating ISBN-10 and
ISBN-13 num... |
c87e50068527cb1602d78f73c4274fada49748c9 | ElianEstrada/Cursos_Maury_C | /Codigos/08 - condicion_if_elif_else.py | 463 | 3.859375 | 4 | # Sintaxis del if - elif - else
#Los corchetes ([]) indican opcionalidad
# 'if' '(' condicion ')' ':'
# ' ' bloque_codigo':'
# ' ' bloque_codigo] -> se
# ['elif' '(' condicion2 ')' puede repetir n veces.
# ['else' ':'
# ' ' bloque_codigo]
#Identificar que un número x
#es positivo, 0 o negativo... |
d01aa234204bd19ab9e6fb73fb884079046da4a8 | gabriellaec/desoft-analise-exercicios | /backup/user_393/ch60_2020_10_05_18_32_07_312707.py | 267 | 3.8125 | 4 | def eh_palindromo(lista):
i= 1
lista_invertida= ''
while i <= len(lista):
lista_invertida= lista_invertida + lista[-i]
i = i + 1
print(lista_invertida)
if lista_invertida== lista:
return True
else:
return False
|
6defe8a28b1aa986a36652e7d17267b71371eaa7 | HarshSharma12/ProjectEulerPython | /Ques_7.py | 578 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Solved on - 1/8/2011
@author: Harsh Sharma
10001st prime
Problem 7
Published on Friday, 28th December 2001, 06:00 pm; Solved by 195407
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10 001st prime number?
Answer: 104743
... |
fc08971348295106774e280eccebcf793d221c8f | tiantian123/Algorithm | /Python/LeetCodePractice/Day1_DeleteListRepeat.py | 1,711 | 4.15625 | 4 | #!/usr/bin/env python
# -** coding: utf-8 -*-
# @Time: 2020/3/10 21:05
# @Author: Tian Chen
# @File: Day1_DeleteListRepeat.py
"""
26.删除有序数组中的重复值
给定一个排序数组,你需要在 原地 删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。
不要使用额外的数组空间,你必须在 原地 修改输入数组 并在使用 O(1) 额外空间的条件下完成。
示例:
给定数组 nums = [1,1,2], 函数应该返回新的长度 2, 并且原数组 nums 的前两个元素被修改为 1, 2。你不需要考虑... |
8cfa18155511b23de159c44a28ee551757067e2d | k8godzilla/-Leetcode | /1-100/L109.py | 2,182 | 4.03125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 16 06:35:39 2019
@author: sunyin
"""
'''
给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。
本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。
示例:
给定的有序链表: [-10, -3, 0, 5, 9],
一个可能的答案是:[0, -3, 9, -10, null, 5], 它可以表示下面这个高度平衡二叉搜索树:
0
/ \
-3 9
... |
323680559b3f84c5140029508a588907c5822f68 | ana-romero/mega2021-kenzo-sage | /finite_topological_spaces.py | 75,578 | 3.65625 | 4 | r"""
Finite topological spaces
This module implements finite topological spaces and related concepts.
A *finite topological space* is a topological space with finitely many points and
a *finite preordered set* is a finite set with a transitive and reflexive relation.
Finite spaces and finite preordered sets are basic... |
8529374df4895a7013a341c97bb797e53290b5cc | karankrw/LeetCode-Challenge-June-20 | /Week 3/Search_in_BST.py | 1,591 | 4.09375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 16 01:12:08 2020
@author: karanwaghela
"""
"""
Given the root node of a binary search tree (BST) and a value.
You need to find the node in the BST that the node's value equals the given value.
Return the subtree rooted with that node. If such nod... |
bc87113f0c65a138e7d5e0c205297285f90453c7 | yamadathamine/300ideiasparaprogramarPython | /008 Controle de tela/menu.py | 662 | 4.25 | 4 | # encoding: utf-8
# usando python 3
# Menu posicionado - Implemente um programa que mostra um menu a partir de uma linha lida do teclado
import os
os.system('clear')
linha = int(input("Digite a linha: "))
coluna = int(input("Digite a coluna: "))
print("\033["+str(linha)+";"+str(coluna)+"H Menu relatórios")
linha +=... |
3f17f8f241e1955c667cee7d5bf34276ad4f294c | mottaquikarim/pydev-psets | /pset_challenging_ext/exercises/solutions/p45.py | 451 | 4.09375 | 4 | """
Write a program which can filter even numbers in a list by using filter function. The list is: [1,2,3,4,5,6,7,8,9,10].
"""
"""Question:
Write a program which can filter even numbers in a list by using filter function. The list is: [1,2,3,4,5,6,7,8,9,10].
Hints:
Use filter() to filter some elements in a list.
Use l... |
7a296304e3146720199718e0f0b322b6a704c5d8 | maurovasconcelos/Ola-Mundo | /Python/ex112/utilidadescev/moeda/__init__.py | 1,498 | 3.953125 | 4 | def aumentar(preco = 0, taxa = 0, formato=False):
'''
-> Calcula o aumento de um determinado preço,
retornando o resultado com ou sem formatação.
:param preco: o preço que se quer reajustar.
:param taxa: qual é a porcentagem do aumento.
:param formato: quer a saida formatada ou nao ?
:return... |
d6a89112d0378a05a995a00072e35dcc957cf94d | JonathanAngelesV/EstructuradeDatos---Unidad2 | /Examen Unidad 2 - Ejercicio 2.py | 313 | 3.96875 | 4 | #Forma recursiva de elevar 2 a la n potencia
#Angeles Valadez Jonathan - 15211883
#Fecha: 10/5/2018
def potencia(numero):
potenciaN = input("A que potencia deseas elevar 2?: ")
Num = int(potenciaN)
operacion = pow(2,Num)
print(str(operacion))
print(" ")
potencia(numero)
po... |
faf546c308d6aff54b2ff341883c94005e54263b | lucasharzer/Teste_Python | /ex3.py | 162 | 3.9375 | 4 | n1 = float(input('Digite a primeira nota: '))
n2 = float(input('Digite a segunda nota: '))
m = (n1+n2)/2
print('A média das duas notas é igual a {}'.format(m))
|
1f61f5abb842126258a989d0f22d471a5bb687b6 | ziyadalvi/PythonBook | /5Numeric Types/7Comparisions(Normal and Chained).py | 927 | 3.921875 | 4 | #Comparisions:Normal and Chained
print(1<2)
print(2.0 >= 1) #mixed types are allowed in numeric expressions (only)
print(2.0 == 2.0)
print(2.0 != 2.0)
#Python also allows us to chain multiple comparisons together to perform
#range tests. Chained comparisons are a sort of shorthand for larger Boolean expressions.
X ... |
c8f9cdd9cf855801112ef8da11567e1ae95ad916 | shahidshabir055/python_programs | /leapyears.py | 430 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Nov 28 11:35:39 2019
@author: eshah
"""
def find_leap_years(given_year):
# Write your logic here
leap=[]
while(len(leap)<=15):
if((given_year%4==0 and given_year%100!=0) or given_year%400==0):
leap.append(given_year)
... |
2710406174139c89f526ed98855d883089c7d41d | RamonFidencio/exercicios_python | /EX044.py | 450 | 3.515625 | 4 | preco= float (input ("Preço: "))
pag = int(input('Pagemnto: \n1 - A vista (10%' 'de desconto)\n2- Cartão 1x (5%' 'de desconto)\n3- Cartão 2x (Preço normal)\n4- Cartão 3x (20%' 'de Acrescimo)\n'))
if pag == 1:
print('Você pagará: {}'.format(preco*0.9))
elif pag == 2:
print('Você pagará: {}'.format(preco*0.95))
e... |
c76cebf6bcc8d369ba71ca3a8b9c7b0c065eaa65 | nishantk2106/python_more-learning | /pairwithgivensum.py | 364 | 3.8125 | 4 | # Find pair with given sum in the array
from array import *
def sum(ar,arr_size,s):
for i in range(arr_size):
for j in range(i+1,arr_size):
if (ar[i]+ar[j]==s):
print(ar[i],ar[j])
else:
print("there is no match with the sum")
#
ar=[1,2,2,3,4,4,5,6,7,7]
... |
d1982a2610c4dbcf7130c841b44f646dc8b7804d | RishitAghera/internship | /python/scrabble-score/scrabble_score.py | 541 | 3.5625 | 4 | def score(word):
s1=["A", "E", "I", "O","U", "L", "N", "R","S", "T"]
s2=["D","G"]
s3=["B","C","M","P"]
s4=["F","H","V","W","Y"]
s5=["J","X"]
s6=["Q","Z"]
cnt=0
for i in word.upper():
if(i in s1):
cnt+=1
elif(i in s2):
cnt+=2
elif(i in s3):... |
4a4bedebb70de3935d1b40862b43b6bba2013ca7 | TanjillaTina/Python-for-Data-Science | /Week1/PythonObjectsAndMaps.py | 2,226 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Oct 23 12:01:47 2017
In The name of Allah,The Beneficent and The Merciful
@author: TINA
advanced Python Objects and Maps
"""
##Objects in Python don't have any private or protected members,if u instantiate a class u can have access to the entire class
class Person:
dep... |
f68d8f476a92e6b42b2b4277f75bb6c41d8dbad2 | fleetster22/silentAuction | /main.py | 2,940 | 3.859375 | 4 | # Day 9 of 100 Days of Code - The Complete Python Pro Bootcamp for 2021
from time import sleep
from art import logo
# programming_dictionary = {
# "Bug": "A spider in your computer",
# "Function": "A piece of code that you can easily call repeatedly",
# "Loop": "The action of doing something repeatedly",
#... |
883a66d3cfd1562a6500ce1045be029445cba060 | saleed/LeetCode | /365_best.py | 947 | 3.546875 | 4 | class Solution(object):
def canMeasureWater(self, jug1Capacity, jug2Capacity, targetCapacity):
"""
:type jug1Capacity: int
:type jug2Capacity: int
:type targetCapacity: int
:rtype: bool
"""
vis=set()
return self.dfs(jug1Capacity,jug2Capacity,0,0,target... |
0f145eed10730f52dd0311db4c7987842a3f8327 | Maerig/advent_of_code_2017 | /day8/condition.py | 776 | 3.734375 | 4 | class Condition(object):
def __init__(self, register, operator, operand):
self.register = register
self.operator = operator
self.operand = int(operand)
def is_valid(self, registers):
register_value = registers[self.register]
if self.operator == '<':
return r... |
591dc8ffbf7da8a52b6001d15220fcb72dff51a6 | evanmiles/sure-awesome | /volAreaSphere.py | 547 | 4.65625 | 5 | #volAreaSphere.py
# 1.1 This program calculates the volume and surface area of a sphere using radius input by the user.
#import math package to use math.pi for the value of PI
import math
#take radius of the sphere from user
r=float(input("Enter the radius of the sphere"))
#calculate the surface area of sphere
s_are... |
3fa362226a5a33dfc89978a0c05e62c719d22dcb | MichalWlodarek/Tic-Tac-Toe | /TTT.py | 6,232 | 4.0625 | 4 | import tkinter.messagebox
try:
import tkinter
except ImportError:
import Tkinter as tkinter
# Declaring button's functions. Empty button when pressed will display 'X', click will turn to False and the next
# button press will produce a 'O' and the click will turn back to True. Count is used to determine... |
8abf0ca4f47c373e88ebf9e56228f6a20ccb5786 | xuan-linker/linker-python-study | /basic/Basic_Dictionary.py | 750 | 3.796875 | 4 | # Dictionary like Java's map
dict = {}
dict['one'] = "1 - Linker"
dict[2] = "2 - xlccc"
testDict = {'name': 'linker', 'web': 'xlccc', 'macro': 'micro'}
print(dict['one'])
print(dict[2])
print(testDict)
print(testDict.keys())
print(testDict.values())
testDict = ([('Xlccc', 1), ('Google', 2), ('Taobao', 3)])
print(test... |
d2f1e3783f9f44df4f13e0c2cbe7c2a2807c7fa6 | toadereandreas/Babes-Bolyai-University | /1st semester/Fundamentals-of-programming/Assignment 2/Complex_Number.py | 18,273 | 4.46875 | 4 | import math
def create_complex_number(a, b ):
'''
Function that creates a complex number c given its real part a and imaginary part b.
c = a + ib with a, b € R.
Input : a, b
Preconditions : a, b - are float
Output : c
Postconditions : c - complex number
the real part... |
57fdb5646f2496ef65ff55951c255d3a46a36254 | iamfrank22/cmsc125-operating_systems | /time_sharing.py | 4,568 | 3.75 | 4 | import random
import time
import os
class Resource:
def __init__(self, name, id):
self.id = id
self.name = "Resource " + name
self.user_list = []
self.current_user = None
self.is_available = True
def printName(self):
print(self.name)
class User... |
1ef8b00918375ff2e1a8e60b0e44cef0bddf69a4 | sandeep256-su/python | /atmadv.py | 3,005 | 3.921875 | 4 | #atm system
class atm:
"""docstring for atm."""
i=1 #transaction fail attempts
j=1 #pin attempts
bal = 20000.00 #innitial balance
def __init__(self, pin):
self.pin = pin
def security(self):
z=int(8888) # ATM pin
if self.pin==z:
... |
649406f3861c6f2a67cef1b850ad5b7c16bd4560 | thinhntr/JetbrainsAcademySmartCalculator | /smart_calculator.py | 6,760 | 3.984375 | 4 | from collections import deque
def merge_operators(operators):
minus_operator_count = 0
for operator in operators:
if operator != '-' and operator != '+':
return False
if operator == '-':
minus_operator_count += 1
return '+' if minus_operator_count % 2 == 0 else '-'
... |
0459b7bcc5146ea04d52a7ed25487c62382395f6 | zerebom/AtCoder | /AOJ/algorithm_data1/3D_double_linked_list.py | 1,019 | 3.703125 | 4 | class Cell:
def __init__(self, value):
self.value = value
self.next = None
self.prev = None
class DoublyLinekdList:
def __init__(self):
self.head = None
def insert(self, value):
new = Cell(value)
#番兵。ここを起点にデータが追加されていく
tmp = self.head
... |
4fba4841450d77e46da3be2c780c7da274157f64 | sudhirgamit/Python-Learning | /Main1.py | 1,334 | 4.09375 | 4 | print("Hello World..!")
# This Is A Single Line Comment
'''A Multiple Line
Are The Excute
In This Code'''
name="Sudhir Gamit"
ch="A"
num=134
point=15.7
pointm=15.77848967463
print(type(name)," : ",name)
print(type(ch)," : ",ch)
print(type(num)," : ",num)
print(type(point)," : ",point)
print(type(poi... |
a2aab9e2a586a237df57d5baa0012f3457ee2f5a | AssiaHristova/SoftUni-Software-Engineering | /Programming Fundamentals/mid_exam_preparation/the_final_quest.py | 1,308 | 3.75 | 4 | words = input().split()
command = input()
while not command == "Stop":
command_list = command.split()
if 'Delete' == command_list[0]:
index = int(command_list[1])
if index in range(0, len(words)):
words.pop(index + 1)
elif 'Swap' == command_list[0]:
word_1 = command_list... |
033dc80360d80492469b512ea357b93c7b1cc729 | aravinve/PySpace | /ipp.py | 941 | 3.703125 | 4 | def greet_user():
print("Hi There!")
print("Welcome Aboard")
def greet_user_special(name):
print("Hi " + name)
def greet_user_full(f_name,l_name):
print("Hi " + f_name + " " + l_name)
def sqaure(number):
return number * number
# Default Return Value is None
def cube(number):
print(numbe... |
c6163489cdd0301d9224ad6014703fe3c863010a | TobyBoyne/fourier-animation | /fourier.py | 2,037 | 4.0625 | 4 | """
Calculates the Fourier coefficients for a given set of data points
"""
import matplotlib.pyplot as plt
import numpy as np
class Fourier:
def __init__(self, points, N):
# self.c stores all coefficients of the fourier series
# self.n stores the value of n that each coefficient corresponds to
# self.n == [... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.