blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
5a0a880abc862a06253c1e6c263de6c6c285944a | nicolagardo/Desafio_Dirmod | /teclado_v2.py | 1,780 | 3.703125 | 4 | from funciones import mensaje_valido
def mapear_caracteres(mensaje):
letras = [' ', ('a', 'b', 'c'), ('d', 'e', 'f'),('g', 'h', 'i'), ('j', 'k', 'l'), ('m', 'n', 'o'), ('p', 'q', 'r', 's'), ('t', 'u', 'v'), ('w', 'x', 'y', 'z') ]
print("....")
print(next((i for i, x in enumerate(letras) if x[0] == "a")... |
cf385d16b2e62a59ebeb2d33b95571c1c9d39350 | jormelcn/asignaciones-programacion | /BasicScripting/web-info/web-info.py | 1,479 | 3.515625 | 4 | # ***************************************** Ejercicio **************************************************
# Diseñar y codificar un script en Python que permita hacer peticiones “GET” a un conjunto de sitios web.
# De la respuesta a la petición web extraiga información detallada del sitio
import socket
import reques... |
ae36d42b6cbd5c75f3d9f441aeec3962eb1c5b57 | prof-asiedu/projects | /day-3-love-calcus.py | 1,076 | 3.859375 | 4 | lover_one = input("First lover: ")
lover_two = input("Second Lover: ")
combine_names = lover_one.lower() + lover_two.lower()
# check for the number of times true loves comes
t = combine_names.count("t")
r = combine_names.count("r")
u = combine_names.count("u")
e = combine_names.count("e")
# check for the number of ti... |
809584362c9f89e35c255b477abd4a2ec3dbe1e3 | max-yagch/yagch_python | /对象/test_class.py | 653 | 3.578125 | 4 | class Dog:
"""
表示狗的类
"""
def __init__(self, name, age, gender, height):
self.hidden_name = name
self.hidden_age = age
self.hidden_gender = gender
self.hidden_height = height
def jiao(self):
"""
狗的叫法
"""
print("汪汪汪~~~~~")
... |
414377006754c4b3aadff32fc5c8832dc2799d67 | alvin-qh/leetcode-work | /92.反转链表-ii.py | 1,900 | 3.734375 | 4 | #
# @lc app=leetcode.cn id=92 lang=python3
#
# [92] 反转链表 II
#
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
# @lc code=start
class Solution:
def reverseBetween(self, head: ListNode, left: int, right: int) -> ListNode... |
98844e2ad4017bcc3592810cf8a600d894d31cd5 | mostafagafer/Pandas----Dataschool-tutorial | /20-how to make pandaframe faster .py | 1,026 | 3.6875 | 4 | import pandas as pd
drinks = pd.read_csv('http://bit.ly/drinksbycountry')
drinks.head()
drinks.info() # take about 7.6 + kb
drinks.info(memory_usage='deep') # take19.9 kb
drinks.memory_usage() # gives every one how many bites
drinks.memory_usage(deep=True) # gives the actual every one how many bites
drinks.memory... |
3002cb703ce4e2abdc4d2208254541c1f3a10f44 | dasm/AdventOfCode | /2015/day3/day3.py | 1,152 | 3.5625 | 4 | #!/usr/bin/env python3
from collections import defaultdict
import sys
def load_data(filename):
with open(filename) as file_:
directions = file_.read().strip()
return directions
DIRECTIONS = {
"v": lambda x, y: (x, y+1),
">": lambda x, y: (x+1, y),
"<": lambda x, y: (x-1, y),
"^": lambd... |
b741a613bcdc03ac2014bb673ab16149d1fc808f | dasm/AdventOfCode | /2015/day1/day1.py | 386 | 3.828125 | 4 | #!/usr/bin/env python3
with open('input') as file_:
brackets = file_.read().strip()
basement = False
floor = 0
for index, letter in enumerate(brackets):
if not basement and floor < 0:
basement = True
print("basement", index)
if letter == '(':
floor += 1
elif letter == ")":
... |
57eb6b023787e24fe5a1276100abba1feb2ab547 | aamerino/Ejercicios-Iniciacion-Programacion | /1.py | 221 | 3.921875 | 4 | print("Introducir numero")
numero = int(input())
numeroDoble = numero * 2
numeroTriple = numero * 3
print("Numero introducido " + str(numero))
print("Doble " + str(numeroDoble))
print("Triple " + str(numeroTriple))
|
66f5472cc690bc143fb653d414ce7c04be47d6c4 | aamerino/Ejercicios-Iniciacion-Programacion | /11.py | 585 | 3.828125 | 4 | print("Introducir numero A")
primerNumero = int(input())
print("Introducir numero B")
segundoNumero = int(input())
print("Introducir numero C")
tercerNumero = int(input())
print ("Números introducidos: " , primerNumero , "\t" , segundoNumero , "\t" , tercerNumero)
if primerNumero + segundoNumero == tercerNumero:
p... |
3d0767ee036ff65825b4293de538c41fc606b4ac | aamerino/Ejercicios-Iniciacion-Programacion | /19.py | 566 | 4.03125 | 4 | """Lee por teclado 5 números enteros positivos, y escribe cuál es el mayor de los números introducidos. """
def comprobarNumeros(listNum):
numeroMayor = listNum[1]
for num in listNum:
if(num > numeroMayor):
numeroMayor= num
return (numeroMayor)
listNum=[]
for num in range (1 , 6):
print("Introducir numero")... |
b76a99d33a8834306649360bd724fed96c720064 | pritam1997/python-test-7 | /q4.py | 159 | 3.78125 | 4 | n = int(input("Enter no. : "))
sum =0
if n>0:
for i in range(1,n+1):
sum += i/(i+1)
else:
print("Number must be greater than 0")
print(round(sum,2)) |
85f240abe4f8240091958defea0b75d0f6594b55 | vano144/django_convert_ascii_service | /ascii_app/ascii_converter/log_system/log.py | 1,075 | 3.59375 | 4 | import logging
import sys
##
# Initializing log
# How to use log:
#
# logger.critical('This is a critical message.')
#
# logger.error('This is an error message.')
#
# logger.warning('This is a warning message.')
#
# logger.info('This is an informative message.')
#
# logger.debug('This is a low-level debug message.')
... |
ba4f71b675445846489a9803ad7f8685e5140f29 | raghavgr/Leetcode | /Perfect_squares_279.py | 1,453 | 3.703125 | 4 | """
Given a positive integer n,
find the least number of perfect square numbers
(for example, 1, 4, 9, 16, ...) which sum to n.
For example, given n = 12,
return 3 because 12 = 4 + 4 + 4;
given n = 13,
return 2 because 13 = 4 + 9.
"""
import math
import sys
class Solution(object):
def numSquares(self, n):
... |
ad28b0b43045cae7068fb71ce2759ddf22a16b25 | raghavgr/Leetcode | /buy_and_sell_stock_with_fee_714.py | 1,506 | 4.0625 | 4 | """
Your are given an array of integers prices,
for which the i-th element is the price of a given stock on day i;
and a non-negative integer fee representing a transaction fee.
You may complete as many transactions as you like,
but you need to pay the transaction fee for each transaction.
You may not buy more tha... |
54ee94ce38690a2caffd9c36b698be4a17839ad8 | raghavgr/Leetcode | /valid_perfect_square367.py | 558 | 4.09375 | 4 | """
Given a positive integer num, write a function
which returns True if num is a perfect square else False.
Note: Do not use any built-in library function such as sqrt.
Example 1:
Input: 16
Returns: True
Example 2:
Input: 14
Returns: False
"""
class Solution:
def isPerfectSquare(self, num):
"""
... |
47f5e052808e5a77df1a15980e1ea37fad4756e4 | raghavgr/Leetcode | /reverse_string344.py | 862 | 4.3125 | 4 | """
Write a function that takes a string as input and returns the string reversed.
Example:
Given s = "hello", return "olleh".
"""
class Solution:
""" 2 solutions """
def reverseString(self, s):
"""
in-place reverse string algorithm
i.e. another string is not used to store the result
... |
1f00a2ea5f73e1aadc64a3b5ce600853b804a7a3 | thedeathcoder/someone | /enc_denc.py | 204 | 4.03125 | 4 | print('Number encryption')
num = int(input("Enter a number"))
primary_key = 1111111112
en = num ^ primary_key
print("Encrypted number "+str(en))
den = en ^ primary_key
print("Decrypted number "+str(den))
|
58feab3ba9eeb52e19232d1028c7ae4aa6fc56ff | felixniemeyer/pv-trade-analysis | /how-many-square-meters-of-solar-panels-for-the-world.py | 964 | 3.5 | 4 | import math
# https://www.tf.uni-kiel.de/matwis/amat/iss/kap_8/advanced/a8_3_1.html
yearly_avg_W_per_h_and_m2 = 200 # W/m2
panel_efficiency = 0.15
Wh_per_year_per_m2 = 365.25 * 24 * panel_efficiency * yearly_avg_W_per_h_and_m2
print("Wh generation per year per square meter", Wh_per_year_per_m2)
# bp report
world_con... |
2c995baab2b7c6ad91a9070887b3ab02115bac1e | topaz1874/pynotes_excercises | /min_of_list.py | 495 | 3.875 | 4 | def get_min(numbers):
""" Return a new list with the smallest value in the input list.
Before returning the new list, remove the value from the original list.
>>> nums = [3, 4, 1]
>>> get_min(nums)
>>> [1]
>>> nums
>>> [3, 4]
"""
# your code here
min_n = min(numbers... |
4ca41edee467369c91bf26d69e917311799e07b6 | Louis-Saglio/ReinforcementLearningCourse | /sandbox/markov_decision_process.py | 1,706 | 3.59375 | 4 | from typing import Tuple, List
class Action:
def __init__(self, from_state, to_states: List[Tuple["State", float]]):
assert sum([to[0] for to in to_states]) == 1
self.from_state = from_state
self.to_states = to_states
class State:
def __init__(self, name, reward: float):
self... |
49cd3f4f63f2a6037cbbbb2050dfe8eacdeabfa7 | learningsomethingnew/palaHW | /Homework/userstats/notes.py | 229 | 3.75 | 4 | user_list = range(1,1000if )
def multiples_of_3_or_5(a_list):
v_sum = 0
for number in a_list:
if number%3 == 0 or number%5 == 0:
v_sum += number
return v_sum
print(multiples_of_3_or_5(user_list)) |
fcdf20ec25f18831f87358b9d137814097ea7a5b | luzcalder/programacion_python | /laboratorio3/tb3.py | 436 | 3.953125 | 4 | #luz maria calderon aguilera
import math as math
h= input("pedir latitud")
g=input("pedir longitud")
j= input("pedir latitud")
k= input("pedir longitud")
def funcion(t1,t2,g1,g2):
pi=3.1416
t1= (h*pi/180)
g1= (g*pi/180)
t2=(j*pi/180)
g2= (k*pi/180)
distancia=6371.01*math.acos(math.sin(t1)*mat... |
95956f6285116159ae6acbc002532194ff60fd2c | luzcalder/programacion_python | /laboratorio1/tarea3.py | 210 | 3.515625 | 4 | #!/usrbin/env python
# _*_ coding: utf-8 _*_
#tarea 3
#LUZ MARIA CALDERON AGUILE
entradaj=input("Introduzca un radio ")
def v(x):
pi=3.1416
Area=pi*x*x
Volumen=(3*pi*x*x*x)/4
print Area
print Volumen
salida=v(entradaj)
|
d2e2fc6a5cc0d0a476495ca8c9b81932d825f668 | miguel262/info175_miguelnahuelpan | /Ejercicio1.py | 318 | 3.828125 | 4 | def Numeros():
x=input("ingrese un numero: ")
y=input("ingrese un numero: ")
resultado=""
if(x==y):
resultado="iguales"
return resultado
elif(x>y):
resultado="el mayor es: "+str(x)
return resultado
else:
resultado="el mayor es: "+str(y)
return resultado
print Numeros()
|
7a460ccd2c821e2df155016fd3952202d9d25aaa | ErenKrkc/Patika-Python-Temel-Projesi | /Patika Python Temel Proje/python temel proje 2.py | 150 | 3.765625 | 4 | l = [[2, 4], [6, 8], [10, 12, 14]]
for i in range(len(l)):
if type(l[i]) == type([]):
l[i].reverse()
l.reverse()
print(l) |
e5f78c643b62829b2a31011fbb95436ad21c1bdf | OS-Shoaib/100-Day-of-Python | /Day 002/main.py | 674 | 3.953125 | 4 | # Day 002
# tip calculator
def tip_calc():
print("Welcome to the tib calculator.\n")
total_bil = float(input("What was the total bill? $"))
people_number = int(input("How many people to split the bill? "))
per_tip = int(input("what percentage tip would you like to give? "))
total_amount = t... |
ce2d6dad1a419f52c7904453f30542a7ad718668 | python-discord/code-jam-5 | /aesthetic_ants/penguin/utils.py | 1,631 | 4 | 4 | # Contains utility functions
import math
import typing
import pyglet
def angle_between(x1: float, y1: float, x2: float, y2: float) -> float:
"""
Returns the angle between the coordinates (x1, y1) and (x2, y2) in radians
"""
dx = x2 - x1
dy = y2 - y1
# We return negative because pyglet and ma... |
29df104742d8d0077a1937c50590cdda12e9377c | python-discord/code-jam-5 | /aesthetic_ants/penguin/spawner.py | 1,137 | 3.578125 | 4 | import random
from .object import Object
class Spawner(Object):
def __init__(self, player):
# Required for enemy tracking
self.player = player
self.spawn_points = []
self.wave = None
self.delay = 0
self._done = False
def add_spawn_point(self, x: float, y: flo... |
7b23bce1a202109f496e083fca6a4671613d3017 | python-discord/code-jam-5 | /various_vipers/project/utils/singleton.py | 413 | 3.53125 | 4 | class Singleton(object):
"""Singleton pattern class."""
_instances = {}
def __new__(class_, *args, **kwargs):
"""Create new instance if it does not already exist; else reuse."""
if class_ not in class_._instances:
class_._instances[class_] = super(Singleton, class_).__new__(
... |
57b4918877b804462001fbf7bf92e834b008265b | jamescryptocode/UCLA-SDP-2019-CS | /2.1.3-variables-convo.py | 100 | 4.1875 | 4 | x = int(input("Type a number."))
if (x % 2) == 0:
print("x is Even")
else:
print(x, "is Odd")
|
c834fd40f3a86542a2d81ea0297c71d1cf1853fd | JoshMez/Python_Intro | /Dictionary/Empty_Dict.py | 245 | 4.21875 | 4 | #Aim: To learn about empty dictionaries
#
#Creating an empty dictionary.
dict = {} #Put two curly braces. #No space between them.
#
#Adding values to the empty dictionay.
#
dict['Jason'] = 'Blue'
dict['Belle'] = 'Red'
dict['John'] = 'Black'
#
#
|
64ae17e8464d1f0961e5f2b57eed8721001d8fc0 | JoshMez/Python_Intro | /Functions/Key_Word_Arguments.py | 618 | 3.5 | 4 | #Using Key_Word Aruguments.
#
#
#Name-value pair when you write a function.
##Creating a variable of my fav Marvel, DC/
#
def Marvel_DC(studio, charecter ):
"""Seeing if a character is Marvel or DC"""
print(f"Charecter name: {charecter}")
print(f"\nStudio name: {studio}\n\n")
#Calling the function
Marvel_DC... |
c7136ec6647afc0f3044059082e63a55d80506d5 | JoshMez/Python_Intro | /Programming_Flow/List_Comprehension.py | 298 | 4.25 | 4 | #Basic demonstration of list comprehension.
#Variable was declared.
#List was create with the square brackets.
#value ** 2 was created.
#The a for loop was created ; NOTICE : THere was not the semi:colon as the end.
squares = [ value ** 2 for value in range(1,11) ]
print(squares)
|
25c3ca3c1c65e30c86974644efb173dcbe3338a8 | JoshMez/Python_Intro | /Functions/Default_Values.py | 777 | 3.75 | 4 | #When you write a function you can assign a default value to a parameter.
#
#
#Dont think of think of the default value of being set in stone.
#It will only be used when you have not see anything else.
############################################################
#
def Charecter(charecters, studio='Marvel' ):
"""See... |
bfd57f6ad775a8c6cd91ba2db417421d9716a415 | JoshMez/Python_Intro | /Functions/Exercies_8.py | 1,645 | 4.75 | 5 | #8-1. Message: Write a function called display_message() that prints one sentence
#telling everyone what you are learning about in this chapter. Call the
#function, and make sure the message displays correctly.
#Creating a function.
def display_message():
"""Displaying the chapter focuses on"""
print("In this ... |
f77853c57409d16a7d23731165daa4fb70a2bf20 | JoshMez/Python_Intro | /While_Input/Dict_User_Input.py | 714 | 4.25 | 4 | #Creating an empty dictionary.
#
#Creating an empty dictionary.
responses = {}
#
#Creating a flag.
polling_active = True
####
#
while polling_active:
#Prompting the user for input.
naming = input("Whats your name: ")
response = input("Which mountain do you want to visit: ")
#Store the responses in the ... |
a0f6073ebcf2f8159b91f630968acb177b9b561b | JoshMez/Python_Intro | /Dictionary/Loop_Dict.py | 1,293 | 4.90625 | 5 | #Aim: Explain Loop and Dictionaries.
#
#
#There are several ways to loop through a dictionary.
#Loop through all of Key-pair values.
#Loop through keys only.
#Loop though values only.
#
#
############Example of looping through all dictionary key-pair values####################
#
#Creating a dictionary of a ... |
93300c8d4e6ea97ae52b9e9c0ac48fb06cb070d4 | JoshMez/Python_Intro | /Functions/Orders_Matters_Postional.py | 422 | 3.71875 | 4 | #Creating a function where indication of displaying the order matters.
#
#creating a definiton.
def pet_name(animal_type, animal_name):
"""Function will display pet name and type."""
print(f"Pet type: {animal_type}")
print(f"Animal type: {animal_name}")
#Calling the function
pet_name("Dog", "Kush")
#######
... |
c0639830ea805fe51e5e092ab2ee3ead53628df4 | JoshMez/Python_Intro | /Programming_Flow/if_statements/Basic_if/Execsise_if.py | 637 | 4.0625 | 4 | #This is just a simple program to test basic if statement skills.
#
print("Imagine an Alien was just shot down in a game.\nCreate a variable called 'alien_color'")
print("Assign the variable a value of green, blue, yellow or red.\n")
print("Write an If statememt to test if the colors of the alien is green.\nIf program ... |
f95e10517f70584b947de934b5fa33dee7d149bc | JoshMez/Python_Intro | /Dictionary/Nesting_2.py | 601 | 4.1875 | 4 | aliens = []
#Basically creating the variable 30 times over.
#
#The range just tells Python how many times we want to loop and repeat.
#Each time loop occurs, we create a new alien and append it to the new alien list.
for alien in range(30):
new_alien = {'color': 'green',
'points': 5,
... |
1068634872d3d4acb23453519b7f6e3b9069bcae | JoshMez/Python_Intro | /Programming_Flow/Number_Lists.py | 1,243 | 4.53125 | 5 | #Creating lists that contain number in Python is very important.
#Making a list with even numbers in it.
even_numbers = list(range(0,11,2)) #The list function has been used to say that a lists is being created. #Passing the range arguments in that , stating arugments in that.
print(even_numbers)
#Creating ... |
3976b30d12c80e7424d7d50bce065ceaee984ef3 | younjae5/we_dont_know_algo | /soojeong/num1972.py | 815 | 3.5 | 4 | def surprising_str(str_sup):
if len(str_sup) == 1:
print('{} is surprising.'.format(str_sup))
return
for i in range(len(str_sup)-1):
c_list = []
state = False
for j in range(len(str_sup)-1-i):
a = [str_sup[j], str_sup[j+1+i]]
if a in c_list:
... |
12a8a0e7fcb0c123a2e8098bfd9d9bd0760fc10f | shbrief/Coursera-Bioinformatics1-wk1 | /6. Computing_Frequencies.py | 657 | 3.53125 | 4 | nucleotide = {"A":0, "C":1, "G":2, "T":3}
def pattern_to_number(Pattern):
if len(Pattern) == 0:
return 0
symbol = Pattern[-1]
prefix = Pattern[0:-1]
return (4 * pattern_to_number(prefix) + nucleotide.get(symbol))
def computing_frequencies(Text, k):
frequency_array = [0 for i in ... |
170b81c95440d3e3b418d2ae47a5fd74a654dd88 | AnmolKhullar/training-2019 | /Day10A.py | 984 | 4.1875 | 4 | """This module is for calculate Employee salary"""
class Employee:
"""This is class Employee
Hello world"""
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print("Total E... |
64bb540e09fa45fc3e87d874c2ddddbff97ab69b | AnmolKhullar/training-2019 | /Day3L.py | 530 | 3.828125 | 4 | def fun1():
largest_no = int(input('Enter largest number of series:'))
for i in range(0, largest_no + 1, 1):
print(i, end=',')
def fun2():
largest_no = int(input('\nEnter largest number of series:'))
for i in range(largest_no, -1, -1):
print(i, end=',')
def fun3():
largest_no = i... |
c7c7f5d06163206c293453b9501400af91969f59 | AnmolKhullar/training-2019 | /Day6K.py | 253 | 4.0625 | 4 | items = ['egg', 'milk', 'butter', 'peanuts', 'oats', 'honey']
for i in enumerate(items):
print(i, end=',') # tuples with index and element of iterator
print('a')
items = ['cup', 'pen', 'book']
for i in enumerate(items, 100):
print(i, end=',')
|
337ce90fbe4b46191ec3485e1019a67799c83902 | AnmolKhullar/training-2019 | /Day8J.py | 1,736 | 3.75 | 4 | x = set('A Python Tutorial')
print(x)
print(type(x))
x = set(['Perl', 'Python', 'Java'])
print(x)
cities = set(('Paris', 'Lyon', 'London', 'Berlin', 'Paris', 'Birmingham'))
print(cities)
# cities=set(('Python','Perl'),('Paris','Berlin','London'))
print(cities)
cities = set(['Frankfurt', 'Basel', 'Freiburg'])
print(citi... |
bc5c2f07ee725618865abbc5aec45bdd60330085 | milapour/palm | /palm/base/parameter_optimizer.py | 379 | 3.59375 | 4 | import abc
class ParameterOptimizer(object):
"""
ParameterOptimizer is an abstract class. The role of a ParameterOptimizer
is to adjust the values of a set of parameters to improve the score given
by a scoring function.
"""
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def optimize_p... |
4c8654ad8342859b2b1fbc50614b3a10e9ea900b | MarcusRainbow/pypyrust | /tests/dictionaries.py | 1,171 | 3.546875 | 4 | from typing import List, Dict
def create_dict(keys: List[str], values: List[str]) -> Dict[str, str]:
d = { k: v for k, v in zip(keys, values)}
return d
def access_dict(keys: List[str], dictionary: Dict[str, str]) -> List[str]:
result = []
for key in keys:
if key in dictionary:
resu... |
44b1c33d2966aff0f3df23ecd9befc5e95f16327 | MarcusRainbow/pypyrust | /tests/sets.py | 1,362 | 3.546875 | 4 | from typing import Set
def create_set(a: int, b: int) -> Set[int]:
return {i for i in range(a, b)}
def set_check_and_add(a: Set[str], item: str) -> bool:
if item in a:
return True
else:
a.add(item)
return False
def create_static_set() -> Set[str]:
a = { "one", "two", "three" }... |
d71458f0ed1ac6a03a00a8d545177eef50169afc | Luong-Minh-Quang/VFTReader | /writer/ReportWriter.py | 710 | 3.859375 | 4 |
from abc import abstractmethod
class ReportWriter:
"""Interface for all writer classes.
"""
@abstractmethod
def write(self, reportList, filepath):
"""Writes a list of VFT reports to a file.
Args:
reportList (List[VFTReport]): The list of reports to be saved to a file.
... |
0480ee694331d4c245cb80e75288bb477956dade | AlexSuv-Tob/hpmework_6 | /3.py | 659 | 3.609375 | 4 | incom = {"wage": 20000, "bonus": 5000}
class Worker:
def __init__(self):
self.name = 'Имя'
self.surname = 'Фамилия'
self.position = 'Должность'
self.__income = incom
class Position(Worker):
def get_full_name(self, position, name, surname):
return (position, n... |
d9d481f4b42f97b611df5854220e3ea717d7cb68 | tirth-ke-codes/dsa | /Prac-03/L5.py | 155 | 3.5 | 4 | # Insert 12 before 78 index
l1=[12,45,78,3,5,4]
print(l1)
element=12
beforeelement=78
index=l1.index(beforeelement,0,5)
l1.insert(index,element)
print(l1)
|
9693a3d6093d80860d0ccbdb9996372ac1a56646 | cee22/Food-And-Health-website | /python/user.py | 528 | 3.984375 | 4 | print("Hello World")
print("My name is Comfort")
myName = "Comfort"
myOccupation = "Software"
age = 22
isEmployed = True
isNotEmployed = False
isNotFromAfrica = False
print("my name is ", myName)
print("My name is %s I am a %s" % (myName, myOccupation))
dataTypeOfName = type(myName)
print("The name variable is of ... |
7ac9c06345e7f4a6ea6bffe3f11dfefa2e6d2cad | howarjm/mypython | /jmh.traingle.py | 978 | 3.96875 | 4 | def area(base, height):
'''(number, number) -> number
Return the area of a traingle with given base and height.
>>> area(10, 40)
200.0
>>> area(3.4, 7.5)
12.75
'''
return base * height / 2
def perimeter(side1, side2, side3):
... |
f5208702e2afd78cb1da29eaae3c36dc81022a6d | JordanAlexanderSmith/2.CreativeSystemsModule | /2task1.py | 1,276 | 3.609375 | 4 | import RPi.GPIO as GPIO
import sys
import time
from colorama import Fore, Back, Style
GPIO.setmode(GPIO.BCM)
GPIO.setup(20, GPIO.IN) #Switch
GPIO.setup(21, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) #Button
GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) #Stick
x = 1 #Button Clicks
BG = 0 #Background flipper
RGB = 0 # ... |
38936a50b1ef5570cef7a9cd19e1774ddc7e21ce | shekhar270779/Learn_Python | /prg_OOP-05.py | 2,388 | 4.5625 | 5 | '''
Class Inheritance: Inheritance allows a class to inherit attributes and methods from parent class.
This is useful as we can create subclass which inherits all functionality of parent class, also if required
we can override, or add new functionality to sub class without affecting parent class
'''
class Employ... |
04f0ad0cd050d391f3d5cb74427c5a4ebe50803a | shekhar270779/Learn_Python | /prg_OOP_04.py | 1,044 | 4.03125 | 4 | '''
Static Methods:
Static methods don't pass either instance or class as parameter to method.
They behave like normal functions.
Static method knows nothing about the class and just deals with the parameters.
'''
class Employee:
def __init__(self, fname, lname, sal):
self.fname = fname
... |
cba3197c4da85d4839710f486efeddeac785a8e4 | ZachAlford/cTurtle2 | /House.py | 3,204 | 3.59375 | 4 | import cTurtle
import math
def rectangle(turtle, length, width):
turtle.forward(length)
turtle.right(90)
turtle.forward(width)
turtle.right(90)
turtle.forward(length)
turtle.right(90)
turtle.forward(width)
def polygon(turtle, sides, size=100):
angle=360/... |
769638361b0d7670c8947b6ff24868cdb359c658 | cpe202fall2019/lab1-jgilbe14 | /lab1_test_cases.py | 3,729 | 3.859375 | 4 | import unittest
from lab1 import *
class TestLab1(unittest.TestCase):
def test_max_list_iter(self):
"""Test for max_list_iter function"""
tlist = None
with self.assertRaises(ValueError): # used to check for exception
max_list_iter(tlist)
self.assertEqual(max_list_iter(... |
2a0e5dead95c63a0678e969a1610e16a2ced6f26 | helsonxiao/exercises | /linkedlist.py | 4,005 | 4 | 4 | class Node(object):
'''
data:节点的数据
_next:保存下个节点对象(包含下个节点数据和下下个节点对象)
'''
def __init__(self, data, _next=None):
self.data = data
self._next = _next
def __repr__(self):
'''
定义Node的字符输出
print(Node)时输出data
'''
return str(self.data)
class Link... |
d44bb7f79cdd81ede8a030424a000a3aa0155741 | adam1996/JetBrains-Zookeeper | /Problems/Order!/task.py | 216 | 3.984375 | 4 | number_1 = int(input())
number_2 = int(input())
number_3 = int(input())
#check to see if in ascending order, if so print True.
ascending_order_check = number_1 <= number_2 <= number_3
print(ascending_order_check)
|
2ffbae3fd994bf83100b3409e5703754132032f1 | Joaoloula/stanford_algo_psets | /course1/week1/karatsuba.py | 872 | 3.84375 | 4 | def karatsuba(x, y):
""" Takes two multiple digit integers and outputs their product"""
# Handle base case
if x < 10 and y < 10:
return x * y
str_x = str(x)
str_y = str(y)
len_x = len(str_x)
len_y = len(str_y)
if len_x > len_y:
str_y = '0'*(len_x - len_y) + str_y
... |
bc03cd87d62e04475c632d2a8117036f5c956602 | arnulfosegura/Prueba | /ejercicio 2.py | 294 | 3.953125 | 4 | while True:
a = int(input("Ingrese un numero entero de dos digitos: "))
if a > 9 and a < 100:
b = a % 10
a = a // 10
print(a)
print(b)
else:
print("El numero ingresado debe ser un entero entre 10 y 99 ")
|
c04664cabe8158cb328c33e523cfbdd3b59924ce | SenlisO/Project-Euler | /1_Multiples_of_3_and_5.py | 1,745 | 3.75 | 4 | """
Project Euler problem #1
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.
answer: 233168
technique:
add together the summation of 3x and 5x and then
subtract the summation of ... |
45fbe847809241cf6a54f08e9919aef674fe2861 | amitkcodes/Work_with_Python | /string.py | 227 | 3.78125 | 4 | first_name="amit"
last_name="kaushik"
full_name=first_name+" "+last_name
# print(full_name)
# print(first_name+3)#error
print(first_name+str(3))#no error
print(first_name+"3")#no error
print(first_name*3)#multipale print |
b03059cc29b6a987207e0fc489d9a8b70de88a6a | SiTh08/naan-project-2 | /run_naan_factory.py | 1,817 | 4.03125 | 4 | # Functions
# def make_dough(ingredient1, ingredient2):
# if (ingredient1 == 'wheat' or 'water') and (ingredient2 == 'water' or 'wheat'):
# return 'dough'
# elif (ingredient1 != 'wheat' or 'water') and (ingredient2 != 'water' or 'wheat'):
# return 'not dough'
def make_dough(ingredient1, ingredi... |
c7238386a1120911f6aa86fa56811d63da61973a | Volzhanin37/Artezio-Academy | /Lesson I/03.py | 88 | 3.875 | 4 | S = input('enter the string: ')
if len(S)>=2:
print(S[:2]+S[-2:])
else:
print()
|
4b8224daa2274a63f871bb0e92eab20a210c1426 | Volzhanin37/Artezio-Academy | /Lesson VI/5.py | 205 | 3.703125 | 4 | def chain(*args):
for arg in args:
for i in arg:
yield i
a = chain([1, 2, 3], [4, 5, 6])
print(next(a))
print(next(a))
print(next(a))
print(next(a))
print(next(a))
print(next(a))
|
db587544e683640581a1e7fd295aca72e00b8045 | stiven2763/programacion-3 | /Tarea 1 completa -c.py | 2,407 | 3.765625 | 4 | if __name__ == "__main__":
print("Lista de Supermercado")
sm = {}
contador = 0
archivo = open("super.txt", "r")
for linea in archivo:
linea = linea.strip()
llave = linea.split(',')[0] #Se declara la variable llave para poder crear el diccionario
valor = int(linea.sp... |
a78f11ea4ae4faae68d193d74c4ab69aaa0828ac | Punyah38070/Manunchaya-CS01 | /CS01-12.py | 101 | 3.546875 | 4 | N = ["Manunchaya","Nunchia","38070"]
x = N[0]
for x in ["Manunchaya","Nunchia","38070"]:
print(x) |
9d70319f737b9c4b9e1fa845b0b6b00b17f3733d | jakubpoltoraczyk/ProjectNetflix | /srcback/movie/movie.py | 4,271 | 4.0625 | 4 | from date import Date
from dateutils import DateUtils
from director import Director
import datetime
now = datetime.datetime.now()
class Movie:
"""Class, which represents movie object with some basic information"""
def __init__(self, actors, director, description, release_date, rating):
"""Create new... |
37f449176d8cfa2809fdf5836f7a5760bc50ad43 | Carolinacapote/AirBnB_clone_v2 | /tests/test_models/test_city.py | 783 | 3.75 | 4 | #!/usr/bin/python3
"""Unittest module of the City class that inhrits from Base_model"""
from tests.test_models.test_base_model import test_basemodel
from models.city import City
class test_City(test_basemodel):
"""Class test_city to test the City class"""
def __init__(self, *args, **kwargs):
""" Init... |
7fd257b0faaf39aeb3241545e17d00a582cab624 | pk8642/HTTP-client | /parse_line.py | 2,262 | 3.515625 | 4 | import argparse
def create_parser():
parser = argparse.ArgumentParser(
prog='HTTP client',
description='''This is a client for receiving and sending data via
HTTP protocol'''
)
parser.add_argument('uri',
metavar='web-address',
... |
8bdc82cc4590b320da4b8f2e8462b3db0960ea59 | andu1989anand/vtu-1sem-cpl-lab-in-python | /palindrome1.py | 450 | 4.34375 | 4 | print "\n Python program to reverse a given integer number and check whether it is a"
print "PALINDROME or not. Output the given number with suitable message\n\n"
num=input("Enter a valid integer number:")
temp = num
rev=0
while(num != 0):
digit=num % 10
rev=rev * 10 + digit
num=num / 10
print "\n\n The rev... |
eaa8e5da435544cd8e07457a6e90e79c5a59591c | pilifengmo/Electrical-Consumption-Prediction-System | /PROJECT/website/model.py | 1,776 | 4.125 | 4 | import sqlite3 as sql
class Database(object):
""" Create database if not exist """
def __init__(self):
con = sql.connect("database.db")
cur = con.cursor()
cur.execute("create table if not exists users (id integer primary key autoincrement, username text not null UNIQUE, email text not... |
be702bd562a70bdf6968938fc970885f20ad5c61 | d0xkb/python | /learning/cycle.py | 473 | 3.796875 | 4 | # cycles (how many times to repeat and with condition on start)
# how many times to repeat: range using (start, stop, step)
for x in range(5,0,-1):
print(x)
quit()
# radrange using (start, stop, step)
from random import randrange
while True:
if (randrange(1, 100000, 1)) == 10:
break
print('MATC... |
2572fabb2d78bdea83f5a8e4f3bd5a0b40d1f076 | muthonilucy/october_project | /operators.py | 225 | 3.84375 | 4 | print(10+10)
print("\tLucy" *10)
#power
print(2**4)
print(100%3)
#equality operator
print(10==20)
print("\n", 20>20.1)
print(20 >= 19,"20 is greater than 19")
print("\n","Uchumi" > "Tuskeys", "Uchumi is greater than Tuskeys") |
061278d3b8e76f2a02c1c6c46524e19c081ad7d4 | kevinsudo/Study_python | /第七天/线程加锁.py | 296 | 3.59375 | 4 | import threading
import time
num=0
def work():
print("线程开始")
for i in range(20000):
global num
if suo.acquire():
num+=1
suo.release()
suo=threading.Lock()
for i in range(2):
th=threading.Thread(target=work)
th.start()
print(num)
|
e9d5619d853a46cfe7f3e26f693d56ae14768567 | hashncrash/IS211_Assignment1 | /assignment1_part2.py | 559 | 4.1875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"IS 211 Assignment 1, part 2. Dave Soto"
class Book(object):
author = " "
title = " "
"Book Class information"
def __init__(self, author, title):
self.author = author
self.title = title
"Function to dsiplay the book author and title"
def... |
7297e630b824b779f37cd3427ee3483704182e5e | KingOsean/shiyanlou-code | /jump7.py | 153 | 3.53125 | 4 | num = range (1,101)
for i in num:
if i%7 ==0:
continue
elif i%10==7:
continue
elif i//10==7:
continue
print (i)
|
460beedcfca1403fb8278a8e06409c9b66da98b2 | Akshatha-Udupa/AITPL2108-database | /metrocities.py | 658 | 3.515625 | 4 | #metrocities
import csv
with open('Metro city.csv') as csv_file:
readcsv = csv.reader(csv_file, delimiter=',')
line = csv_file.readline()
print(len(line))
next(readcsv)
for row in readcsv:
print(row)
'''outpt
25
['Chennai', '13.0827', '80.2707']
['Delhi', '28.7041', '77.1025']
['Bangalore',... |
cbd7e01f59cc3c3e648608b5ec54106738ebe192 | BachQuangMinh/PracticeProjects | /linear regression/wiki-prices - final.py | 4,293 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue May 8 17:58:10 2018
@author: DELL
"""
import pandas as pd
import math
import numpy as np
from sklearn.model_selection import train_test_split
import statsmodels.api as sm
import matplotlib.pyplot as plt
#Preprocessing steps, selecting and calculating necessary columns and ... |
436f4284edba28c59a436e7458b8c5eb4ea4f746 | neilmarshall/nmutils | /nmutils/sqrt_expansion.py | 2,832 | 3.84375 | 4 | from fractions import Fraction
class SqrtExpansion():
"""
Generates square root expansion of an irrational number
>>> expansion = SqrtExpansion(24)
>>> expansion.root
4
>>> expansion.key
(1, 8)
>>> expansion = SqrtExpansion(25)
Traceback (most recent call last):
...
... |
8f3b5afc0cc401951efec1fe005e25f0c7be8588 | ovasquezz/python | /Practica 5/ejer 9.py | 179 | 3.84375 | 4 | a=int(input("Escriba la anchura del triangulo: "))
b=int(input("Escriba la altura del triángulo: "))
print("*"*a)
for i in range(b-2):
print("*"," "*(a-4),"*")
print("*"*a)
|
6f9b8e1d7498fc5f514ef4a44cafdc60f0bc7f93 | ovasquezz/python | /Practica 5/ejer 8.py | 128 | 3.953125 | 4 | a=int(input("Escriba la altura del triangulo: "))
for i in range(a):
print("*"*i)
for i in range(a):
print("*"*(-i+a))
|
4d1eaf65bb074e5d608d5c98a195d9ff9647c9e3 | ovasquezz/python | /Practica 3/ejer 2.py | 181 | 3.875 | 4 | s=float(input("Escribe el espacio recorrido del coche en km: "))
t=float(input("Escribe le tiempo que ha tardado en horas: "))
v=s/t
print ("La velocidad del coche es: ",v, "km/h")
|
aeea6c0d9e8763f11c32f28d6456a8782483af28 | sysulj/leetcode | /easy/string/563. 二叉树的坡度.py | 2,342 | 4.15625 | 4 | """
给定一个二叉树,计算整个树的坡度。
一个树的节点的坡度定义即为,该节点左子树的结点之和和右子树结点之和的差的绝对值。空结点的的坡度是0。
整个树的坡度就是其所有节点的坡度之和。
示例:
输入:
1
/ \
2 3
输出: 1
解释:
结点的坡度 2 : 0
结点的坡度 3 : 0
结点的坡度 1 : |2-3| = 1
树的坡度 : 0 + 0 + 1 = 1
注意:
任何子树的结点的和不会超过32位整数的范围。
坡度的值不会超过32位整数的范围。
"""
# Definition for a binary tree node.
# class Tree... |
2a41999906367714884677f9dd75923590856311 | ethanroday/gpa | /gpa.py | 2,140 | 3.859375 | 4 | letters = {
'A': 4.0,
'A-': 3.7,
'B+': 3.4,
'B': 3.1,
'B-': 2.8,
'C+': 2.5,
'C': 2.2,
'C-': 1.9,
'D': 1.6,
'F': 1.3
}
def gpaForGrade(grade):
return letters[grade]
def qpsForGradeHrs(grade,hrs):
return hrs*gpaForGrade(grade)
def gpa(hrs,qps):
return (qps/(hrs*... |
a7f06c13a8603d0a2468f377c84a79804eccac98 | songszw/python | /python小栗子/t120.py | 223 | 3.78125 | 4 | def int_input(num = ''):
while True:
try:
int(input(num))
break
except ValueError:
print('输入证书啦,损塞')
int_input('请输入一个整数:')
|
61f33b333408e0f9ade2b8d6ac6eb54ca3d86d9c | songszw/python | /python小栗子/t118.py | 192 | 3.5625 | 4 | try:
for i in range(3):
for j in range(3):
if i==2:
raise KeyboardInterrupt
print(i,j)
except KeyboardInterrupt:
print('I Quent') |
d787d43b62879f0bbf859252719841e4f64f6eb3 | songszw/python | /python小栗子/t4.py | 190 | 3.765625 | 4 | def funn(n):
if n==1:
return 1
else:
return n*funn(n-1)
number = int(input('please enter a number:'))
sum = funn(number)
print("%d 的阶乘是:%d" % (number,sum))
|
4770d44868cbd22345796e9096ccb74fd5e82c65 | songszw/python | /python小栗子/t69.py | 599 | 3.59375 | 4 | def file_compare(file1,file2):
f1 = open('F:\\'+file1+'.txt')
f2 = open('F:\\'+file2+'.txt')
count = 0
differ = []
for line1 in f1:
line2 = f2.readline()
count+=1
if line1 != line2:
differ.append(count)
f1.close()
f2.close()
return differ
file1 = input('请输入第一个文件名:')
file2 = input('请输入第二个文... |
6c50d54681b1aecab23161420e131063f0976152 | songszw/python | /python小栗子/t33.py | 485 | 3.8125 | 4 | def findstr(words,needfind):
length = len(words)
count = 0
if needfind not in words:
print('he\'s died, i can\'t find it')
else:
for each in range(length):
if words[each]==needfind[0]:
if words[each+1]==needfind[1]:
count+=1
... |
f1aae7db4e3d44c3d8326d16157ca52aaa5a1673 | songszw/python | /python小栗子/t152.py | 179 | 3.53125 | 4 | class Ball:
def __init__(self,name):
self.name = name
def say(self):
print('你好,世界,我是%s'%self.name)
a = Ball('songzhiwen')
a.say()
|
c8ca9d7ae46143a176c97356fec7657d37780ab5 | songszw/python | /python小栗子/t20.py | 854 | 3.65625 | 4 | pwd= input('请输入需要检查的密码组合')
length = len(pwd)
symbols = r'''`!@#$%^&*()_+-=/*{}[]\|'";:/?,.<>'''
chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
nums = '0123456789'
qdc=0
qdq = 0
while(pwd.isspace()or length==0):
pwd = input('您输入的密码为空(或空格),请重新输入')
length = len(pwd)
if length<=8:
... |
01377f0f8c48cef79f8e272891db01bf5818dd74 | songszw/python | /python小栗子/t9.py | 404 | 4.0625 | 4 | a = '8'
answer = input('please enter a number:')
while True:
if answer > a:
print('bigger')
print('wrong, try it again')
answer = input('please enter a number:')
elif answer < a :
print('small')
print('wrong, try it again')
answer = input('please enter a number:'... |
63e588d25dd49d06b2ad65ee21f5f5cfe3150ef4 | songszw/python | /python小栗子/t41.py | 1,316 | 3.6875 | 4 | origin = (0, 0) # 原点
legal_x = [-100, 100] # x轴的移动范围
legal_y = [-100, 100] # y轴的移动范围
def create(pos_x=0, pos_y=0):
# 初始化位于原点为主
def moving(direction, step):
# direction参数设置方向,1为向右(向上),-1为向左(向下),0为不移动
# step参数设置移动的距离
nonlocal pos_x, pos_y
new_x = pos_x + direction[0]... |
013c82f9411dac873c50d545150e9bcd2a10db68 | songszw/python | /python小栗子/t119.py | 698 | 3.640625 | 4 | import random
secret = random.randint(1,10)
try:
temp = input('请输入一个数字:')
num = int(temp)
except (ValueError,EOFError):
print('那是啥玩意,我特么要一个数字')
num = secret
while num!=secret:
if secret == num:
print('哦哟哟哟哟,猜对啦')
else:
if secret>num:
print('哦哟哟哟哟,小了... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.