blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
5fe617888604e6f055a33366111e42bc9dd0a5f9 | JuanSebastianOG/Analisis-Numerico | /Talleres/PrimerCorte/PrimerTaller/Ejercicio13.py | 611 | 3.9375 | 4 | #Algoritmo que permite calcular una aproximación a la raiz n-esima de un número
def raizN( n, N, x ):
tol = 10e-8
it = 0
xn = 1
while abs(xn) > tol:
it = it + 1
xn = ((N / (x ** (n - 1))) - x ) / n
x = x + xn
print("La raiz", n, "-esima del numero", N, "e... |
b5a229b2ab30b0efc4c2718be4ac8f4d99742b55 | innovationcode/Sorting | /project/iterative_sorting.py | 1,975 | 4.34375 | 4 | # Complete the selection_sort() function below in class with your instructor
def selection_sort( arr ):
# loop through n-1 elements
for i in range(0, len(arr) - 1):
cur_index = i
smallest_index = cur_index
# TO-DO: find next smallest element
# (hint, can do in 3 loc)
for... |
27b5953e8b4dff1c7d41c461d5b74a9623761fdc | Roderich25/mac | /design-patterns/poultry.py | 777 | 3.578125 | 4 | class Duck:
def quack(self):
print("Quack")
def fly(self):
print("I'm flying")
class Turkey:
def gobble(self):
print("Gobble gobble")
def fly(self):
print("I'm flying a short distance")
class TurkeyAdapter:
def __init__(self, adaptee):
self.adaptee = ... |
4366b965dc637f5beeda2bfdcdd64755782d2641 | chrisxue815/leetcode_python | /problems/test_0572_recursive_dfs.py | 1,437 | 3.578125 | 4 | import unittest
from typing import Optional
import utils
from tree import TreeNode
def height(root):
if not root:
return -1
return 1 + max(height(root.left), height(root.right))
def match(a, b):
if not a:
return not b
if not b:
return False
return a.val == b.val and matc... |
3d90b07fdf4d813c986ddc2ca998e6ad1579faf1 | tabeatheunicorn/general_pythondebugging | /generichelpermodule/Decorators/simpledebug.py | 1,743 | 3.65625 | 4 | import functools
import time
def decorator(func):
"""Boilerplate decorator code"""
@functools.wraps(func) # this ensures that the functions metadatat is not messed up.
def wrapper_decorator(*args, **kwargs):
# Do something before
value = func(*args, **kwargs)
# Do something after
... |
aada262d4ea96da6898f6282de30a72cbbd73871 | Vaild/python-learn | /learn/day_19/1_加锁.py | 670 | 3.609375 | 4 | #!/usr/bin/python3
# coding = UTF-8
# code by va1id
import threading
import time
NUM = 0
lock1 = threading.Lock()
lock2 = threading.Lock()
def work1(num):
global NUM
for i in range(num):
lock1.acquire()
NUM += 1
lock1.release()
print(NUM)
def work2(num):
global NUM
for i in... |
3baef6e68bb38bd39dddee92d9a667cae7c37e13 | lazyxu/pythonvm | /tests/dict.py | 64 | 3.546875 | 4 | d = {1: "hello", "world": 2}
print d
print d[1]
print d["world"] |
b4ca0ad1b04bf810e24a05b5cbbf57ff3546985a | kirane61/letsUpgrade | /Day4/Day4Assignmnet.py | 725 | 4.1875 | 4 | # Assignmnet for Day 4
# You all are pilots, you have to land a plane, the altitude required for landing a plane is 1000ft,
# if it is less than that tell pilot to land the plane, or it is more than that less than 5000ft ask the pilot to "come down to 1000ft",
# else if it is more than 5000ft ask the pilot to "go ar... |
56021e5ab57897b6dd942de4f78bf29c0a3ed81c | stefanonu/Python | /Lab5/Lab5Package/Addition.py | 201 | 3.65625 | 4 | def addition(list):
c=1;
for iterator in list:
c=c+iterator
return c
def additionWithParam(number,list):
c=1;
for iterator in list:
c=c+iterator+number
return c |
8360a27e23aebf55d63fbb9bd0d17067921f19f7 | gsiegman/Tic-Tac-Toe | /tic_tac_toe.py | 2,955 | 3.984375 | 4 | class Player(object):
"""
A Tic-Tac-Toe Player
"""
SYMBOLS = ('X', 'O',)
PLAYER_TYPES = ('human', 'computer',)
def __init__(self, symbol, player_type, game):
if symbol not in self.SYMBOLS:
# better validation could be done to
# ensure uniqueness to other pla... |
d1623519ab0638ca54ff7dff7f97787aee87151d | L16H7/coding_bootcamp_algo_data_structure_python | /Sprial_matrix.py | 350 | 3.953125 | 4 | def spiral_matrix(size):
number = 0
matrix = [[0]*3 for i in range(size)]
for row in range(size):
for col in range(size):
if col
print(row,col)
matrix[row][col] = number + 1
col += 1
return matrix
if __name__ == '__main__':
n_matrix = 3
... |
3bcfe608f3ec275aca13670a487320dc19205989 | ievagaj/ED-D4-DIAMOND | /main.py | 529 | 4.09375 | 4 | row = int(input("Enter the number of rows:"))
for i in range(row):
print(" "*(row-i) + " *" *(i+1))
for j in range(row-1):
print(" "* (j+2) + " *"* (row-1-j))
row = int(input("Enter the number of rows:"))
for i in range(row):
print(" "*(row-i-1) + " *"*(i+1))
for j in range(row-1,0,-1):
print(" "*(row-j) + " ... |
80ef4106ab61798ced52bb1258d45bfa4918a0cf | IvanFekete/fatic-dialogue | /dialog.py | 2,499 | 3.53125 | 4 | import random
#download information will be used from files
commonQuestions = []
commonAnswers = []
questionsWithPattern = []
answersWithPattern = []
invitePhrases = []
byePhrases = []
words = []
isQuestion = lambda sentence: sentence.find("?") != -1
containsPattern = lambda sentence: sentence.find("*") != -1
def d... |
61c5272ceaff822a23f81dda8a4bb30f20c5efc6 | eneopetoku/Learning-Python | /continue example 2.py | 124 | 3.875 | 4 | var=10
while var>0:
var=var-1
if var ==5:
continue
print('Current value :',var)
print('See you again')
|
e70e383871978f0dd9ca6b82091f5d474e3ea3f0 | Enhory/practicas | /programacion2/ejercicio2_Operadores/ejercicio02.py | 177 | 3.78125 | 4 | cadena = input("Escribe tu Nombre: ")
r = len(cadena)
print("Longitud: ", r)
print("¿La longitud de tu nombre es mayor o igual que 3 y menor que 10?: ", r >= 3 and r < 10)
|
e9228fcc3fda45bb6cdede77736e895eec7a003a | kaka0525/Leet-code-practice | /shortestWordDistance.py | 901 | 4.28125 | 4 | def shortest_word_distance(l, word1, word2):
"""
Given a list of words and two words word1 and word2, return the shortest
distance between these two words in the list.
For example,
Assume that words = ["practice", "makes", "perfect", "coding", "makes"].
Given word1 = "coding", word2 = "practic... |
cd720b18aafd5ab8de8f5a972d920eab6fe6ed78 | vedantvajre/Day8-and-Day9-Homework | /9.8.py | 1,552 | 3.78125 | 4 | class User():
def __init__(self, first_name, last_name, password, username, email):
self.first_name = first_name
self.last_name = last_name
self.password = password
self.username = username
self.email = email
def describe_user(self):
print("First name: "... |
9f223e8369f38a15f71daa20cacb6eaf431d46e7 | chriszhuu/Imaginary-Bus-Network | /bus system1/bus.py | 1,082 | 3.859375 | 4 | class Bus(object):
num = 0
all = [] # list of all objects in Bus
def __init__(self, route):
self.ID = Bus.num
self.route = route # bus route is a list with 3 items
self.origin = route[0] # bus origin is the first item in the list
self.destination = route[1:] # bus destinatio... |
aba4c6d2b2ce1ae970317d7a2a4b1d030859cfb6 | vijeeshtp/python22 | /dict4.py | 1,208 | 3.609375 | 4 | data = {
"123" : {
"name" : "anand",
"marks" : {
"sem1" : {
"sub1" :1,
"sub2" :2,
"sub3" :3
},
"sem2" : {
"sub1" :1,
"sub2" :2,
"sub3" :3
},
"s... |
3989074ae61a266750f3532f18d120494a7d09ea | GabriellAlmeidaa/Python_UNIESI | /NP1/Equação_de_segundo_grau.py | 305 | 3.734375 | 4 | a = float(input('Insira o valor de A: '))
b = float(input('Insira o valor de B: '))
c = float(input('Insira o valor de C: '))
delta = b**2 - 4*a*c
print ('Delta = ', delta)
rdel = delta**0.5
print ('Raiz de delta = ', rdel)
x1 = (-b+rdel)/(2*a)
x2 = (-b-rdel)/(2*a)
print ('x1 = ', x1)
print ('x2 = ', x2) |
8939527185f38ab89bbd7dfe7c2125b03b61493c | shahnwaz123/python-exam-prepration-edyoda- | /FOR LOOP & WHILE LOOP.py | 1,525 | 4.40625 | 4 | #!/usr/bin/env python
# coding: utf-8
# # FOR LOOP & WHILE LOOP
# In[8]:
# Example:Lets try iterating for loop with list-
# In[9]:
list1= ['harry','marry','larry']
for item in list1:
print(item)
# In[ ]:
# Lets try to iteratting for loopwith tuple-
# In[10]:
list2= ('harry','marry','larry')
for item... |
5bb5f1c88dcb8ca4d3c1a86762aa922619182850 | josejpalacios/codecademy-flask | /Module 01: Introduction to Flask/Lesson 02: Build Your First Flask App/Exercise 06: Review.py | 776 | 3.609375 | 4 | # Learned:
# - Import Flask class
# - Create Flask application object
# - Create routes for handling requests from different URLs
# - Create variable rules to handle dynamic URLS
from flask import Flask
app = Flask(__name__)
@app.route('/')
@app.route('/home')
def home():
return '<h1>Hello, World!</h1>'
@app.... |
23df2c764181c0858befc52b0fd395674dfbd59a | shuzhancnjx/leetcode- | /Programming-Algorithm/Max Points on a Line.py | 1,668 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jul 31 09:54:33 2015
@author: ZSHU
"""
# Definition for a point.
# class Point:
# def __init__(self, a=0, b=0):
# self.x = a
# self.y = b
class Solution:
# @param {Point[]} points
# @return {integer}
def maxPoints(self, points):
if le... |
2b84d7054bd23a14734558c3276e90ab36ae84a3 | ashish3x3/competitive-programming-python | /Hackerrank/Algorithms/Strings/finding_no_of_common_character_in_all_substring.py | 663 | 3.671875 | 4 |
# https://www.hackerrank.com/challenges/gem-stones/problem
import sys
from collections import defaultdict
def gemstones(arr):
mp = defaultdict(list)
for i in xrange(len(arr)):
for j in arr[i]:
if j not in mp:
mp[j].append(i)
elif j in mp and i not in mp[j... |
bf79472a4d45b131914940fb4cefaadc79031951 | HenleyChiu2/HackerRank-Solutions-Python | /Problem Solving/Plus_Minus.py | 636 | 3.671875 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the plusMinus function below.
def plusMinus(arr):
pos_count = 0
neg_count = 0
zero_count = 0
for num in arr:
if num > 0:
pos_count += 1
elif num == 0:
zero_coun... |
05163253b930fae1fdcb88df0d0fd9555da19d5f | beppe2hd/Explainable_AI_investigation | /single_pred.py | 2,017 | 3.6875 | 4 | '''
The code allow the user to test single features vector in the validation dataset
It takes as input the row of the features vector of interest in the validation dataset
It returns the analyzed vector and plots the corresponding plot
'''
import sys
import pandas as pd
import numpy as np
from sklearn import preproce... |
9d918db516e620732d9453c407cd9915b1fc2a54 | madeibao/PythonAlgorithm | /PartB/py是否存在重复的元素.py | 534 | 3.640625 | 4 |
class Solution(object):
def containsNearbyDuplicate(self, nums, k):
d={}
for ix,num in enumerate(nums):
if num not in d:
d[num]=ix
# 如果已经存在了这个元素的话,就字典的操作。
else:
if ix-d[num]<=k:
return True
els... |
7b6c36767fa4e1edfbf6218175d1545e3bcaceb2 | WesGtoX/Intro-Computer-Science-with-Python-Part02 | /Week2/Tarefa 02/Exercicio_02_ordem_lexicografica.py | 917 | 3.671875 | 4 | def primeiro_lex(lista):
lexico = ''
i = 0
for palavra in lista:
if lexico == '':
lexico = palavra
else:
if ord(palavra[i]) < ord(lexico[i]):
lexico = palavra
elif ord(palavra[i]) == ord(lexico[i]):
letra_igual(palavra, lexi... |
c1016735f558ecab91be457a742f1267b3144f96 | jy100aaa/tictactoe | /tictactoe.py | 4,514 | 3.84375 | 4 | import sys
import os
"""
python 2.7 compatible code
"""
def str_to_int(val):
try:
return int(val)
except Exception as e:
return ''
def main(argv=sys.argv):
os.system('cls' if os.name == 'nt' else 'clear')
turn = 1
while True:
print 'Enter board size (NxN): '
s... |
57a35fa4e182974a46aa439d387f6390b2ecddfe | kimi9527/chess-yi | /chess/chess_piece.py | 2,256 | 3.828125 | 4 | # coding=utf-8
MAX_X = 8
MAX_Y = 9
class ChessPiece(object):
"""
棋子类
"""
def __init__(self, x: int, y: int, is_red: bool, is_north: bool):
self._x = x
self._y = y
self._is_red = is_red # 是否红方
self._is_north = is_north # 是否北方
@property
def is_red(self):
... |
7fe63b361147d407ce9209bdb3b76612d87dcfbc | Nihileshnatarajan/Class-12-Practicals | /Practicals/4.py | 867 | 4.0625 | 4 | ID = ['ABC','DEF','GHI'] #list containing the bike ID's in string
OUT = [9.55,10.11,10.23] #list containing the time the bike was taken in float
def add_bike():
bikeId = input("Enter bikeID ")
if bikeId == 'ZZZ':
print('Goodbye, Have a nice day')
raise SystemExit
ID.append(bikeId)... |
fd6a4ae981e959c59fd94cdf09f59dc399f72d11 | vijaysawant/Python | /PatternPrinting/pattern3.py | 290 | 3.65625 | 4 | '''
input = 4
*
* *
* * *
* * * *
'''
def pattern(row):
for i in range(0,row):
for j in range(0,row):
if (i+j+1 < row):
print " \t",
else: # (i+j+1 >= row)
print "*\t",
print
if __name__ == "__main__":
row = input("Enter num of rows : ")
pattern(row) |
72139f0aabad0dd28b9e1f762243322ee6f219dc | alphawaseem/MultiUserBlog | /passwordlib.py | 1,102 | 4.375 | 4 | """
This module helps to hash passwords with random salts
"""
# Import neccessary modules
import random
from string import letters
import hashlib
def make_salt(length=5):
"""
returns a random salt of default length of 5
"""
return ''.join(random.choice(letters) for x in range(length))
def make_pw_h... |
39c86a6a27c4d5f8ce61217a5877949ce8c158ee | SerjVankovich/BANX_parser | /take_banks.py | 1,426 | 3.625 | 4 | # The func which build dict with banks
def take_banks(array_vklads, array_cont):
banks_array = []
banks_names = get_banks_names(array_vklads)
banks_names = list(set(banks_names + get_banks_names(array_cont)))
print(banks_names)
for name in banks_names:
bank = Bank(name)
... |
e93312d47abfe2cb41b45edee0101d30851b5dcf | linheimx/python_master | /fluent_python/contextmanager/mirror.py | 1,013 | 3.59375 | 4 | import sys
class LookingGlass(object):
def __enter__(self):
self.original_write = sys.stdout.write
sys.stdout.write = self.reverse_write
return "ABCDEFG"
def reverse_write(self, text):
self.original_write(text[::-1])
def __exit__(self, exc_type, exc_val, exc_tb):
... |
61b0365d754a53986e3c68df82dc19b29be24b69 | CypherING/python_work | /rivers.py | 331 | 4.125 | 4 | rivers = {
'nile': 'egypt',
'hwang ho': 'china',
'indus': 'india'
}
for river, country in rivers.items():
print("The " + river.title() + " flows through " +
country.title())
print("\nRivers: ")
for river in rivers.keys():
print(river.title())
print("\nCountries: ")
for country in rivers.values():
print(count... |
08580d9149ec457aac1c510aef63b8ba420c7da0 | apalala/exercism | /python/clock/clock.py | 565 | 3.640625 | 4 |
class Clock():
def __init__(self, hours, minutes):
self.minute_of_the_day = (hours * 60 + minutes) % (24 * 60)
def add(self, minutes):
return Clock(0, self.minute_of_the_day + minutes)
def _hours_and_minutes(self):
return (self.minute_of_the_day // 60, self.minute_of_the_day % 60... |
d3b4a2ca5ab04d0fba293b6d070fb082d888d038 | pynoor/exercism | /pangram.py | 411 | 3.6875 | 4 | def is_pangram(sentence = "This is a sentence"):
count = 0
new = str.lower(sentence)
alphabet = ["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"]
for x in alphabet :
if x in new :
count = count + 1
if c... |
7b67fd41e42a3262007ff0a44aa211cc2512de23 | dgu12/Russian-BS | /russian.py | 14,424 | 3.640625 | 4 | # Daniel Gu
'''
This program allows the user to play a the game Russian BS versus an AI
opponent.
'''
import sys
import random
# Define some useful constants.
BELIEVE = 0
BS = 1
# Global list of ranks.
ranks = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]
# Global list of aliases for cards.
dca... |
c2f0a1b969ff51321362d7c48c4004d18b09bf90 | huxiaolei1997/PythonWork | /Python进阶/2-3.py | 353 | 3.84375 | 4 | # -*- coding: utf-8 -*-
import math
def add(x, y, f):
return f(x) + f(y)
print (add(25, 9, math.sqrt))
# 这里传入了一个math.sqrt作为函数的变量,所以add函数实际执行的代码是abs(25) + abs(9)
# 或者也可以写
def sqrt1(a):
return math.sqrt(a)
def add2(x, y, f):
return f(x) + f(y)
print (add2(25, 9, sqrt1)) |
4b93941db861c8fad04d890965e7c5cbbc114f50 | Shaunwei/Leetcode-python-1 | /String/RegularExpressionMatching/isMatchII.py | 2,215 | 4.15625 | 4 | #!/usr/bin/python
"""
Regular Expression Matching
Implement regular expression matching with support for '.' and '*'.
'.' Matches any single character.
'*' Matches zero or more of the preceding element.
The matching should cover the entire input string (not partial).
The function prototype should be:
bool isMatch... |
4e6d45077c3739b4e176765f104a4e231c3bf26a | 4ster/skillsmart-algo2 | /t1/trees.py | 6,854 | 3.71875 | 4 | class SimpleTreeNode:
def __init__(self, val, parent):
self.NodeValue = val # значение в узле
self.Parent = parent # родитель или None для корня
self.Children = [] # список дочерних узлов
class SimpleTree:
def __init__(self, root):
self.Root = root # корень, может быть No... |
2d900664f5a9c109c9bbef4b93a55be607062840 | adrianxplay/python_unittesting | /curp_calculator.py | 1,049 | 3.875 | 4 | # -*- coding: utf-8 -*-
def calculator(last_name, second_name, name, birth_date, gender):
vowel = ['a', 'e', 'i', 'o', 'u']
curp = ''
# First letter of last_name
if last_name[0] == 'ñ':
curp += "x"
else:
curp += last_name[0]
# First vowel of last_name
for letter in last_na... |
f91f2d2e40ad95039fc69f925773c1b51614f12e | Deepkumarbhakat/Python-Repo | /list2.py | 164 | 4.03125 | 4 | # Write a Python program to multiplies all the items in a list.
a=[int(i) for i in input( ).split()]
print(a)
mul = 1
for i in a:
mul = mul * i
print(mul)
|
4984edfc32a3187030b8ecd9db1d38f17afe2727 | qqmadeinchina/myhomeocde | /homework_zero_class/lesson15/读取大文件-times_2.py | 1,978 | 3.578125 | 4 | #!D:\Program Files\Anaconda3
# -*- coding: utf-8 -*-
# @Time : 2020/8/7 0:29
# @Author : 老萝卜
# @File : 读取大文件-times_2.py
# @Software: PyCharm Community Edition
# read()来读取内容的时候
# 它会直接将全部内容读取出来。如果要读取的内容比较大,会一次性加载到内存当中,这个时候就容易导致内存溢出
file_name = 'demo2.txt'
try:
with open(file_name,encoding='utf-8') as file_obj:
... |
ec96ec57cb0b92126e81e98adad28292f1524599 | emarteca/TurtleWalk | /selfAvoiding_randomDist.py | 6,434 | 3.734375 | 4 | from turtle import Turtle
import random
import math
import interceptInRange
# Like the second implementation of the fixed-distance self-avoiding walk, this walk
# is no longer angle-based (it's component-based instead, and got rid of the slow
# turtle.setHeading(...) command).
# The functionality is the same as for th... |
30c1c9ea2c8083b6962aa239a5c7b709f78cfb53 | ravinder79/python-exercises | /functions.py | 5,990 | 4 | 4 |
# 1. Define a function named is_two. It should accept one input and return True if the passed input is
#either the number or the string 2, False otherwise
#
def is_two(x):
if x == 2 or x == '2':
return True
else:
return False
# 2. Define a function named is_vowel. It should return True if... |
6d2647c4d84de679b030d61ee00da9622b77bfeb | lavifb/pyChess | /test.py | 16,230 | 3.921875 | 4 | import unittest
from Chess import Chess
from consts import EMPTY_SQUARE
class SimpleInputsTest(unittest.TestCase):
def setUp(self):
self.chess = Chess()
self.chess.setupBoard()
def test_move_e4(self):
"""
Simple e4 chess move
"""
self.chess.makeMove('e4')
self.assertEqual(self.chess.board[1][4], EMPT... |
55bdd6a318bb44fd0db418836f4ba4355f60a49f | geeveekee/100_days_of_Code | /d6.py | 2,060 | 3.671875 | 4 | import random
print("""
_
| |
| |__ __ _ _ __ __ _ _ __ ___ __ _ _ __
| '_ \ / _` | '_ \ / _` | '_ ` _ \ / _` | '_ \
| | | | (_| | | | | (_| | | | | | | (_| | | | |
|_| |_|\__,_|_| |_|\__, |_| |_| |_|\__,_|_| |_|
... |
1f1288274db10f50eb215d725662075b201b8666 | wagnersistemalima/Mundo-1-Python-Curso-em-Video | /pacote dawload/projetos progamas em Python/desafio023 Separando dígitos de um número.py | 884 | 4.125 | 4 | # Desafio023 Separando digitos de um número.
# Faça um progama que leia um numero de 0 a 9999 e mostre na tela cada um dos digitos separados.
# Ex: digite um numero 1834
# unidade: 4 / dezena: 3 / centena: 8 / milhar: 1
hipotese = True
while hipotese:
numero = int(input('Informe um número:')) #
unidade = ... |
578b3a135c5a8a9d82a260cfa53e75aa0b20982c | tjwilks/heartDiseasePrediction | /src/modelling/feature_selection.py | 3,747 | 3.578125 | 4 | from sklearn.ensemble import RandomForestClassifier
import re
class FeatureSelector:
"""
A class for searching selecting features based on
missing value proportion or feature importance rank
methods
Attributes
----------
X_data : pandas dataframe
pandas ... |
ceeacb2fe10ed2c58ab837dd8b7707822aa2eb15 | immortal0820/learn-python3 | /data_struct/reference.py | 523 | 4.09375 | 4 | #!/usr/bin/env python3
print("Simple arguments")
shoplist = ['apple', 'banana', 'mango']
print('Origner shoplist is', shoplist)
mylist = shoplist # 复制一个列表或者类似的序列或者其他复杂的对象,必须使用切片操作符来取得拷贝
# 列表的复制语句不创建拷贝
del shoplist[0]
print('shoplist is', shoplist)
print('mylist is', mylist)
print('Copy by making a full ... |
ae498ad0d2e48e8ba643cecb93d850f95492a9ad | LabharPL/python | /json_example.py | 2,013 | 3.734375 | 4 | # import json
#
#
# # some JSON:
# x = '{ "name":"John", "age":30, "city":"New York"}'
#
# # parse x:
# y = json.loads(x)
#
# # the result is a Python dictionary:
# print(y["city"])
#
#
# # a Python object (dict):
# x = {
# "name": "John",
# "age": 30,
# "city": "New York"
# }
#
# # convert into JSON:
# y = json... |
73ed661778442247a8220f0de7c59d56e410dfa1 | SURGroup/UQpy | /docs/code/distributions/user_defined/plot_user_defined.py | 3,161 | 3.71875 | 4 | """
User-defined Rosenbrock distribution
=====================================
This examples shows the use of the multivariate normal distributions class. In particular:
"""
import numpy as np
from UQpy.distributions import DistributionND
import matplotlib.pyplot as plt
#%% md
#
# Example with a custom distributio... |
84f3ddd7342143271b182ee05cbb4efebc3238ca | jing1988a/python_fb | /好咧,最后还是要搞google/medium/KnightProbabilityinChessboard688.py | 2,045 | 3.875 | 4 | # On an NxN chessboard, a knight starts at the r-th row and c-th column and attempts to make exactly K moves. The rows and columns are 0 indexed, so the top-left square is (0, 0), and the bottom-right square is (N-1, N-1).
#
# A chess knight has 8 possible moves it can make, as illustrated below. Each move is two squar... |
0cfba21ca82b1824fd987a86ad2009d0f2f46bf8 | Divisekara/Python-Codes-First-sem | /PA2/PA2 2013/PA2-18/Asitha/pa2-18-2013.py | 1,624 | 3.640625 | 4 | N=0
matrix=[]
def getText():
try:
fo=open("FileIn.txt","r")
L=[]
while True:
L.append(fo.readline().split())
if L[-1]==[]:
L.pop(-1)
break
fo.close()
except IOError:
print "File not found"
pass
else:
... |
eabd3fc5b251a797060ff9d55481eeccfb86fa4f | Simple2001/blood-donation | /bloodonation.py | 2,706 | 3.625 | 4 | import sys
import csv
reciever=[]
bankdata=[]
#making sure that we donot need to run the code again and again to do more than one things; im using while true here which is always true.
while True:
print('\n1. type info. of blood donor\n2. take info. of blood donor using unique id\n3. type ... |
ce483aabc39c2757e229147b1d05d051841a9db4 | priyankchheda/algorithms | /linked_list/remove_duplicates_singly.py | 1,786 | 3.96875 | 4 | """ Remove duplicates from singly linked list
input: 1 -> 6 -> 1 -> 4 -> 2 -> 2 -> 4
output: 1 -> 6 -> 4 -> 2
"""
class Node:
""" Node class contains everything related to Linked List node """
def __init__(self, data):
""" initializing single node with data """
self.data = data
... |
e4f83f29f3ffd84657835bac7242cd8ea1a45d48 | claudiogar/learningPython | /test.py | 691 | 3.9375 | 4 | from algos.quicksort import quicksort
from algos.mergesort import mergesort
from data_structures import tree
def tree_test():
root = tree.Tree(0)
child1 = root.addChild(1)
child2 = child1.addChild(2)
child3 = child1.addChild(3)
child4 = child2.addChild(4)
child5 = child4.addChild(5)
# 0
... |
16412c4b71e865794904f8b1294ba1a832639783 | UPan111/python | /casion.py | 416 | 3.65625 | 4 | #casion
import random
sMax = 0
for i in range(3):
print('round:', i + 1)
input('go')
d1 = random.randint(1, 6)
d2 = random.randint(1, 6)
if d1 + d2 > sMax:
sMax = d1 + d2
print('Player', '\tDice1:', d1, 'Dice2', d2, '\tscore:', d1 + d2)
d3 = random.randint(1, 6)
d4 = random.rand... |
82fd1c288d6b569380470a0753030bf09b7292a0 | amoghkapalli/ProjectEuler | /Problem4.py | 593 | 3.9375 | 4 | '''A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.'''
from math import ceil
first_num=100
max_product=0
def palindrome_checker(num):
s=str(num)
first_fr... |
8819a7c76c1376d974ac8450a5a0ea9abdc1877e | josejpalacios/codecademy-python3 | /Lesson 05: Loops/Lesson 01: Loops/Exercise 05: Break.py | 520 | 4.28125 | 4 | # You can stop a for loop from inside the loop by using break.
# When the program hits a break statement, control returns to the code outside of the for loop.
dog_breeds_available_for_adoption = ['french_bulldog', 'dalmatian', 'shihtzu', 'poodle', 'collie']
dog_breed_I_want = 'dalmatian'
# Create for loop
for dog_bre... |
15713a4aa17b0af607f4967edc241d1f1688c313 | xaviergoby/Python-Data-Structure | /OOP/Polymorphism/SuperMethod.py | 873 | 3.640625 | 4 | class SomeBaseClass(object):
def __init__(self):
print('SomeBaseClass.__init__(self) called')
class UnsuperChild(SomeBaseClass):
def __init__(self):
print('Child.__init__(self) called')
SomeBaseClass.__init__(self)
class SuperChild(SomeBaseClass):
def __init__(self):
print(... |
9e7a1c6a51d0cb40ed06a0aa71e504cca48a130b | jkaariain/python-exercises | /Kierros2/tehtava2.7.3.py | 147 | 3.5 | 4 | def main():
for i in range(1,11):
for j in range(1,11):
print("{:>4d}".format(i*j), end="")
print("")
main()
|
59847fe3139833438dff3c63e7d8eddb3ba96dab | andreishumeiko/shumeiko_project | /dz3_1.py | 292 | 3.59375 | 4 | def fdev(a, b):
try:
return a / b
except ZeroDivisionError:
return 'You cannot devide a by b=0'
try:
print(fdev((float(input('Enter the first number: '))), (float(input('Enter the second number: ')))))
except ValueError:
print('You have to use only numbers')
|
6aefafdf3fa5412adc81e00e62c147e0c446c5fc | KennyTC/Algorithm | /String/NextClosetTime.py | 1,521 | 3.921875 | 4 | # Given a time represented in the format "HH:MM", form the next closest time by reusing the current digits. There is no limit on how many times a digit can be reused.
# You may assume the given input string is always valid. For example, "01:34", "12:09" are all valid. "1:34", "12:9" are all invalid.
# Example 1:
# Inpu... |
8e309a1872270b81477e6567002c506a07b0053c | kangli-bionic/leetcode-1 | /94.py | 695 | 3.96875 | 4 | #!/usr/bin/env python
# coding=utf-8
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
ret = []
def inorderTraversal(self, root):
"""
:type ... |
ff0e11f6cab0ec1454d48c31c9771d2d8664e2a8 | chptcleo/PythonPractice | /com/string/string_reverse.py | 389 | 3.84375 | 4 | # print string.count('abc','c')
my_str = "abcde"
print(my_str.find("c"))
str_size = len(my_str)
# print my_str.find("e")
list = []
for i in range(str_size):
reversed_i = str_size - i - 1
list.append(my_str[reversed_i])
print("".join(list))
print(my_str.replace('a', 'x'))
print(my_str)
delimiter = ','
mylist = ... |
c36716740ef029ef19a6362a9291d214441f5932 | ujwala14/Python-Lab | /8a.py | 367 | 4.1875 | 4 | '''Define a python function generate_n_chars()
that takes an integer n and a character c and returns a string,
n characters long. For example, generate_n_chars(5,"x") should
return the string "xxxxx“ using keyword only parameters.'''
def generate_n_chars(n,c):
return c*n
c=input('Enter char: ')
n=int(input('En... |
e3a438207a13cb5750242ba94609e7e9224f0b8d | rahaf19-meet/meet2017y1lab4 | /Fruit_sorter.py | 221 | 4.3125 | 4 | bin1='Apples'
bin2='Oranges'
bin3='olives'
new_fruit=input('What fruit am i sorting')
if new_fruit==bin1:
print('Bin1')
elif new_fruit==bin2:
print('Bin2')
else:
print('Error! I do not recognize this fruit!')
|
c46764966de46e0ed0f1d24d80c6ac8082fb7e98 | Diefex/PyGroup | /Ejercicio3.py | 209 | 4.0625 | 4 | def is_even (k):
if (k % 2):
return False
else:
return True
if(is_even(int(input("ingresa un numero ")))):
print("este es un numero par")
else:
print("este es un numero impar") |
a4205a9c35e92a5e14a0d698b30e1b487b86d859 | irounik/Patterns.py | /4th.py | 343 | 3.90625 | 4 | n = 5
for i in range(2*n-1):
if(i < (2*n-1)//2):
for j in range(n-1-i):
print(' ', end=' ')
for j in range(i+1):
print('*', end=' ')
else:
for j in range(i-(2*n-1)//2):
print(' ', end=' ')
for j in range(n-i+(2*n-1)//2):
print('*', ... |
df22c274c8e84aa3d885b2ea83db0ea0025ad246 | KlaytonSouza/URI-PYTHON | /1010.py | 282 | 3.65625 | 4 | codP1,numP1,valP1 = input().split(" ")
codP2,numP2,valP2 = input().split(" ")
codP1 = int(codP1)
numP1 = int(numP1)
valP1 = float(valP1)
codP2 = int(codP2)
numP2 = int(numP2)
valP2 = float(valP2)
total = (numP1 * valP1) + (numP2 * valP2)
print("VALOR A PAGAR: R$ %.2f" % total)
|
2e545c894b10789be10c1bb7114e45d28a576986 | JHughes9802/Capstone_Week_2_Lab | /Student_Dataclass_Practice.py | 1,145 | 3.953125 | 4 | from dataclasses import dataclass
@dataclass
class Student:
# I don't know if I should feel weirded out or comforted by
# needing to declare data types for variables in Python.
# Furthermore, I'm curious why the datatype comes AFTER the
# variable AND why the variable needs a colon after itself.
na... |
227d56a32ec35eb351ceefa3e0ede4ec45d3b0a5 | okurz/schatznenner | /schatznenner.py | 1,372 | 3.609375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import random as r
adjektiven = [['süßer ','süße ','süßes '],
['lieber ', 'liebe ', 'liebes '],
["lieblicher ", "liebliche ", "liebliches "],
["holder ","holde ","holdes "]]
pr = [['mein ', 'meine ','mein '],
['','',''],
... |
21c2af6fc2313fe4a4d1b47a0f035acb72071197 | opello/adventofcode | /2015/python/08.py | 375 | 3.5625 | 4 | #!/usr/bin/env python
import re
length = 0
unEscapeLength = 0
escapeLength = 0
with open('../inputs/08.txt') as f:
for line in f:
line = line.rstrip()
length += len(line)
unEscapeLength += len(line[1:-1].decode('string_escape'))
escapeLength += len('"{0}"'.format(re.escape(line)))
print (... |
75f3b191c83223933b686e6d8a1ec28462d8a598 | reed-qu/leetcode-cn | /MoveZeroes.py | 1,232 | 3.859375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/11/20 上午10:08
# @Title : 283. 移动零
# @Link : https://leetcode-cn.com/problems/move-zeroes/
QUESTION = """
给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序
示例:
输入: [0,1,0,3,12]
输出: [1,3,12,0,0]
说明:
必须在原数组上操作,不能拷贝额外的数组。
尽量减少操作次数。
"""
THINKING = """
有... |
079a5cf5f46cd9f34c29010c025fa957d1c6d68e | NyntoFive/Reporter | /backend/excel_writer.py | 1,092 | 3.765625 | 4 | import xlsxwriter
def create_workbook(filename):
"""Create a new workbook on which we can work."""
workbook = xlsxwriter.Workbook(filename)
return workbook
def create_worksheet(workbook):
"""Add a new worksheet in the workbook."""
worksheet = workbook.add_worksheet()
return worksheet
def writ... |
224ec53e24cbfc34d0a625a5ea116313a3264c61 | AdamSlayer/ximena_lessons | /python files/Ximena_lessons/16-exercise3.py | 138 | 3.5625 | 4 | keys = ["ten", "twenty", "thirty"]
values = [10,20,30]
dict1 = {}
for key in range(len(keys)):
dict1=dict1+(keys[key],values[key]) |
d4240e81674ff14054a99f592bdcfb8680316067 | smartinsert/CodingProblem | /algorithmic_patterns/dynamic_programming/rod_cutting.py | 913 | 3.734375 | 4 | """
Cutting rod to maximize profit. Given available lengths and the value at which they are selling,
how will you divide the length to make maximum profit.
"""
def rod_cutting(available_lengths, price_of_each_length, length_of_the_rod):
if length_of_the_rod == 0:
return 0
dp = [[0 for _ in range(lengt... |
ebbfafc87bb9510d141faf3f234c9b50caf90824 | nateychau/leetcode | /other/1-4-21.py | 1,301 | 4.28125 | 4 | # Merge Two Sorted Lists
# Merge two sorted linked lists and return it as a sorted list. The list should be made by splicing together the nodes of the first two lists.
# Example 1:
# Input: l1 = [1,2,4], l2 = [1,3,4]
# Output: [1,1,2,3,4,4]
# Example 2:
# Input: l1 = [], l2 = []
# Output: []
# Example 3:
# Input:... |
63dff0106208a17ba810b5f26ae20c7cab3ebfb5 | crileiton/curso_python | /4 Colecciones de datos/2 Conjuntos.py | 2,207 | 3.984375 | 4 | # Son colecciones desordenadas de elementos unicos, se utiliza normalmente para hacer pruebas de pertenencia a
#grupos y eliminación de elementos duplicados
# Tambien soportan operaciones matematicas avanzadas (posterior)
# Se declara asi...
conjunto = set()
print(conjunto)
# Podemos crear un conjunto con varios elem... |
b38f6be24fdb1529b13d64a9fd4a26ffa722676c | Kimbbakar/Uva-Solutions | /Uva 10200/Uva 10200.py | 814 | 3.59375 | 4 | import math
def isPrime2(n):
if n==2 or n==3: return True
if n%2==0 or n<2: return False
l = int(n**0.5)
for i in range(3,l+1,2): # only odd numbers
if n%i==0:
return False
return True
mark = [ [0] for i in range(0,10003) ]
for i in range(10002):
mark[i]=0
for i in... |
ff98ec227277e100eb37448c95f182f901a00bf2 | earamosb8/holbertonschool-higher_level_programming | /0x03-python-data_structures/5-no_c.py | 173 | 3.546875 | 4 | #!/usr/bin/python3
def no_c(my_string):
new_string = ""
for l in my_string:
if l not in "cC":
new_string = new_string + l
return(new_string)
|
9fe9bb01d924f0dd04905b91149bf0f0ed191d05 | faizsh/Assignments-SA | /ASSIGNMENT NUMBER 1/Assignment 1.5.py | 139 | 4.03125 | 4 | x=int (input('Enter the first number:'))
y=int (input('Enter the second number:'))
print('Exponential of the provided number is:',x**y)
|
c3ee6f3307644c6411e251448ac5b048911e6d2d | clara3445/javavara-assignment | /2nd week/3rd week/list_comprehensions.py | 503 | 3.515625 | 4 | x = int(input("Type a natural number: 1"))
y = int(input("Type a natural number: 1"))
z = int(input("Type a natural number: 1"))
n = int(input("Type a natural number: 2"))
answer1 = [[i, j, k] for i in range(0, x + 1) for j in range(0, y + 1) for k in range(0, z + 1)]
answer2 = [[i, j, k] for [i, j, k] in answer1 if i ... |
86ab768d14bb26733c98abfd9a4d704af8fa83e0 | liyong1995/pythons | /day03/demo11.py | 1,185 | 3.625 | 4 | if __name__ == '__main__':
klist = [
"good ", "good ", "study",
" good ", "good", "study ",
"good ", " good", " study",
" good ", "good", " study ",
"good ", "good ", "study",
" day ", "day", " up",
" day ", "day", " up",
" day ", "day", " up",
... |
6c271d3559a55ecb8ae0de8fea71f43a73403b85 | Bibin22/pythonpgms | /comprehensions/3.list mul.py | 100 | 3.609375 | 4 | A = ['a', 'b', 'c']
B = [1, 2, 3, 4]
AxB = [(x, y) for x in A for y in B]
for i in AxB:
print(i) |
84389ff242a022cc579f638088767209fe728d87 | indexcardpills/python-labs | /04_conditionals_loops/04_00_star_loop.py | 506 | 4.40625 | 4 | '''
Write a loop that for a number n prints n rows of stars in a triangle shape.
For example if n is 3, you print:
*
**
***
'''
n = 5
numbers = range(6)
for x in numbers:
if x == 1:
print("*")
if x == 2:
print("**")
if x == 3:
print("***")
if x == 4:
print("****")
... |
cb48d2e12eb7e209f4c9811552afd3fa95332119 | arsal-imran/python-basics | /all-random-stuff/ASSIGNMNT.py | 1,998 | 3.921875 | 4 | def usrinfo(x,y):
print("Hello " + x + "," + "you are " + str(y) + " years old.")
print("Next year you will be ", str(y+1))
def smallest(x,y,z):
RESULT= min(x,y,z)
return RESULT
def largest(x,y,z):
RESULT= max(x,y,z)
return RESULT
def pwr(x,y):
RESULT= x**y
print(str(x) + " rasie to t... |
c282c6ea4e2e37968b78a3eb4859dcc8659f6dba | DomomLLL/newpy | /jiaoben/panduan.py | 126 | 3.859375 | 4 | #!usr/bin/share
a = int(input('please input:'))
b = int(a / 2)
if a == 2*b:
print('oushu')
else:
print('jishu')
|
be7b98d039e01793f3ae20bb028cfc2cff91cc3a | armasog/Monty_Hall_Simulation | /main.py | 773 | 3.734375 | 4 | from random import randint, choice
def monty_hall(ignorant=False, iterations=100000):
player_wins = 0
for i in range(iterations+1):
car_door = randint(1, 3)
player_door = randint(1, 3)
remaining_door = 6 - car_door - player_door
if not ignorant:
if player_door != car... |
fd7062926456c0d839d363007888b6c1e7cc1991 | jonggukim/Python-for-Trading | /About Python/about function.py | 728 | 3.703125 | 4 | # 함수 만들기
# a3()의 이름을 가진 함수 만들기 - a를 3번 출력하는 함수
def a3():
print('aaa')
a3()
def a4():
return 'bbb'
print(a4()*3)
def a5():
print('before')
return ('ccc') # 함수 a5()읠 결과 값으로 ccc 를 저장. & 해당 함수(a5()를 종료시킨다
# 즉, return 이후의 구문은 실행되지 않는다.
print('after') # return뒤에 존재하기에 실행 되지 ... |
56d191fdaf63fffa2d54f00a66eace4b6b76e3c9 | eunjins/python | /string/case.py | 151 | 3.90625 | 4 | # upper case & lower case
str_a = "Hello Python Programming...!"
str_upper = str_a.upper()
str_lower = str_a.lower()
print(str_upper)
print(str_lower) |
aa21c287c30a56d1eac965e7b68d3962fdf64dfd | SarathM1/matlab-project | /bw1.py | 260 | 3.5625 | 4 | from PIL import Image
col = Image.open("MARS1.JPG")
gray = col.convert('L') # Converts image to grayscale
bw = gray.point(lambda x: 0 if x<128 else 255, '1') # Uses lambda function to convert image to b&w (128=255/2)
bw.save("bw1_Result.JPG")
bw.show()
|
1dc4a678fb734d4953538876f17f13d2bbe5f045 | Idris01/learn_git | /car.py | 536 | 3.9375 | 4 | class Car:
# set the numbers of Car object created
# count is a class variable and to access it
# within and outside the class use Car.count or
# <Car instance name>.count
count=0
def __init__(self,maker,name,wheel=4):
self.maker=maker
self.wheel=wheel
self.name=nam... |
e94713275cbba1e3487a6a3f51fe0543e09f2da6 | divyabiyani/Python-Practice- | /2.py | 98 | 3.890625 | 4 | a=input('Enter a no.')
c=float(a) ** 0.5
print('The square root of %0.3f is %0.3f'%(float(a),c)) |
37659d8d5eec95d33aa52d2cfb7dcff5731df579 | RECKLESS6321/Github-Gist-solution | /Excrise 1.py | 160 | 4.09375 | 4 | name = input("What is your name ?:")
age = int(input("What is your age? :"))
age1 = (2020 - age) + 100
print(f"{name} you will turn 100 year old in {age1}.")
|
04e88efd95a534ea4c0e939a397f02547713e143 | EduMeurer999/Algoritmos-Seg- | /78.py | 237 | 3.796875 | 4 | senhaCorreta = "12345"
senha = input('Informe a senha: ')
c=1
while senha != senhaCorreta:
c = c+1
print("Senha inválida\n")
senha = input('Informe a senha novamente: ')
print("Você errou a senha "+str(c-1)+" vezes")
|
cc1925d6e04e4c9fd30866be100d4ccca03143a0 | krishna6991/DailyCodingProblem | /DCP-04.py | 704 | 4.15625 | 4 | """
maximum value of each subarray of length k ,
in o(n) time complexity and o(k) space complexity
"""
from collections import deque
def printMaxWindowElement(arr,n,k):
DQ = deque()
max_arr= []
for i in range(k):
while DQ and arr[i] >= arr[DQ[-1]]:
DQ.pop()
DQ.append(i)
f... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.