blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
e849f13233b3351c17fcb5db84d3c626d3381ccc
geekcomputers/Python
/Sorting Algorithms/Sorted_Inserted_Linked_List.py
1,339
4.1875
4
class Node: def __init__(self, data): self.data = data self.next = None class Circular_Linked_List: def __init__(self): self.head = None def Sorted_Insert(self, new_node): current = self.head if current is None: new_node.next = new_node self...
81804e565b97ce919ee415f2ba9c4044ea1f8f1c
Yashasvini18/MLDL
/check_vowel.py
196
4.15625
4
vowels = ["a","e","i","o","u"] def check_vowel(): letter = input("Enter any character: ") if letter in vowels: print("True") else: print("False") check_vowel()
c05f09abf3eeaf1413311ff01ff0d47ba965bde7
Mateus-AAC/Renomeador_de_arquivos
/rename.py
1,159
3.609375
4
import re import os import shutil print("//////////////////////////////////") print("/ /") print("/ renomeador /") print("/ /") print("//////////////////////////////////") main_folder = input(r'coloque o diretorio:') os.system('cls') d...
84123a9ab4d6950594ed342018736a5b20473594
kakashihatakae/Linked-List-2
/problem1.py
781
3.6875
4
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class BSTIterator: def __init__(self, root): self.stack = [] while root: self.stack.append(root) root = root.left def next(s...
a208c2a5471642aad937b41ba59a8809e5f2711c
vibhorgoyal18/ai_training
/control_structures_and_functions/list_map_count.py
247
4.03125
4
# Using the function Map, count the number of words that start with ‘S’ in input_list. input_list = ['San Jose', 'San Francisco', 'Santa Fe', 'Houston'] count = sum(list(map(lambda str: 1 if str[0] is 'S' else 0, input_list))) print(count)
e6a8551259841edc4e66860927b13b7ac1800e36
samthan/practice
/ds/stack/stack.py
2,229
3.6875
4
from array import * from node import Node # stack implementation with list...kind of cheating # stack supports 4 basic operations and is Last In First Out class Stack: def __init__(self): self.top = None self.stack = [] def add(self, data): self.stack.append(data) def remove(self): return self.stack.pop(...
9a95072b14c39d7cab13962ec52fd4b5aa5dc599
taomee517/python-basic
/basic/data_model/Bin_Dec_Hex.py
572
3.609375
4
# 2进制,8进制,10进制,16进制 # 2进制写法,以0b(零B)开头,逢2进1,只包含0,1 x = 0b1010 print("2进制的0b1010等于:", x) # 8进制写法,以0o(零O)开头,逢8进1,只包含0~7 y = 0o517 print("8进制的0o517等于:", y) # 16进制写法,以0x(零X)开头,逢G进1,只包含0~F z = 0xf8c print("16进制的0xf8c等于:", z) # 类型转化,字母不能直接转能整型,会报错 a = int(3.14) print(a) b = int("123") print(b) c = int(True) print(c) d...
ba202a65c6055b7b0b34cf1692127b3ec536e1dd
sajan02/python-excercise
/04-getattr-and-getattributes.py
633
3.625
4
class Person(object): def __init__(self,name): self.name = name def __getattr__(self,attrname): print "intercepting undefined attribute access" if attrname == 'profession': return "Dev" else : raise AttributeError("undefined attribute : {}".format(attrnam...
6b8f5e3ffe26cc7a5ba52c96948b646c48e28f9a
dilbwagsingh/PractiseML
/ML/7_logistic_reg/Exercise/my_solution.py
2,075
3.640625
4
import pandas as pd; import numpy as np; import matplotlib.pyplot as plt; from sklearn.linear_model import LogisticRegression as lr; from sklearn.model_selection import train_test_split as tts; from sklearn.preprocessing import LabelEncoder; # loading Data from file df = pd.read_csv("HR_comma_sep.csv"); # print(df.h...
9258d632641a9b60820690c41ff7736cd68fa4ef
pierofre/python-school
/pythonesercizio.py
557
3.5
4
import csv from collections import Counter with open('sacramento_crime.csv', 'r') as esercizi: crime = csv.reader(esercizi) #nome della lista: stats stats = [] for row in crime: #"append" metodo inserisce gli elementi in una lista. stats.append(row) crime_type =[] for row in stats: c...
e7fe0d1c89b97e3977a992de32a377f88ac30e2e
salladr/Programming_Challenges
/06-22-15/mangle.py
479
4.09375
4
#!/usr/bin/python import string sentence = raw_input().split() for word in sentence: punctuation = [ ( i, p ) for i, p in enumerate( word ) if p in string.punctuation ] capitals = [ i for i, c in enumerate( word ) if c.isupper() ] for p in string.punctuation: word = word.replace( p, "" ) word = sorted( word.l...
82ad6f80c59f66bd0f74824940e427eb64f35e2c
JY-Dev/AlgorithmStudy-1
/기본 문제/10주차_분할 정복/18222_투에-모스 문자열/강승훈.py
299
3.5
4
# 입력. n = int(input()) # 투에모스 공식을 그대로 구현한 재귀 함수. def recursion(n): if n == 0: return 0 if n == 1: return 1 if n % 2: return 1 - recursion(n // 2) else: return recursion(n // 2) # 출력. print(recursion(n - 1))
7e5176c618476e5e22307ecfa3e89ea2f3b76065
Johnny1725/Johnathon
/Homework5BM.py
1,369
3.53125
4
# Name: Johnathon Terry # Date: October 24, 2020 # Homework 5 import matplotlib.pyplot as plt import pandas as pd import statistics as statistics import numpy as np import scipy.stats as stats import random data = pd.read_csv('bodyfat.csv',delimiter = ',') data.head() f1 = plt.figure(figsize = (15,5)) ...
b1070ce8e409df83c765c82d696ca552461f9137
sdotpooh/puzzles
/Easy/Racing_Chars/racing_chars.py
4,100
4.34375
4
__author__ = "Sean R. Vinas" __date__ = "3 December 2014" __doc__ = """In this challenge you will be given a file where each line is a section of a race track with obstructions, gates and checkpoints. The goal is to find a way of passing this track, using the following rules: Each section contains only a single gate or...
1b71d9b310ec87a20ae55640437cfaf9d2d5f3a7
StepanyanAlbert/python
/cracker.py
1,016
3.734375
4
import sys,hashlib def get_hash_word(filename=sys.argv[1:2]): """Function returns filename where hash word is located. Gets only one argument filename""" try: f_n=''.join(filename) f=open(f_n) except IOError: print ('Couldn\'t find the path to %s' % filename) sys.exit() else: hash_word=f....
8f57e36a0a4dce3d2f01c1c3ab56fbccd4158cb2
Dududenis/pw1-2021-1
/aula06/03.py
186
3.984375
4
# copia de listas L=[1,2,3,4,5] V=L # atribuicoes apenas fazem ambas as variaveis apontarem para a mesma lista print(V) print(L) V[0]=6 print(V) print(L) V=L[:] V[0]=1 print(V) print(L)
cf8f6d7d9880847564963ef43048a9e91ec6c21f
iam-smza/teeny-tiny-projects
/ROCK PAPER SCISSORS/rock_paper_scissor.py
1,679
4.3125
4
# coding=utf-8 # this is a game of rock, paper, scissor import random # taking inputs from the user while True: ans = 0 while ans > 3 or ans < 1: try: print('Enter your choice:') print('\t1. Rock\n\t2. Paper\n\t3. Scissor') ans = int(input('>>> ')) except V...
a145766aa062640d14748e5adcb4ad129d68f26d
lucasgameiroborges/lista-4-ces22
/q1.py
1,546
3.84375
4
# Classes pai que será ponte: Motor class Motor: def motor_tipo(self): pass # Classes filhas do motor class Eletrico(Motor): def motor_tipo(self): print("Eu carrego um motor do tipo elétrico") class Hibrido(Motor): def motor_tipo(self): print("Eu carrego um mo...
92afd4db89e45de6f6cf3e1cfd7d9359ca3a061e
itamar20-meet/meet2018y1lab6
/fizzbuzz.py
238
4
4
count= input ('type a number') if count % 3 == 0 and count % 5 == 0 : print('fizzbuzz') elif count % 5 == 0: print("buzz") elif count % 3 == 0 : print ('fizz') else: print('sorry! wrong answer')
92752679acd1162947e9a2e2f48cdc659c3fc5b3
ArV29/CODECHEF
/PEC2021F/BNSRCH2.py
1,644
3.96875
4
import sys def find_pos(x): print('1 ' + str(x)) sys.stdout.flush() t = int(input()) return t # ----------------- Do not modify anything above this line ----------------------- # Complete this function count(n, x), this returns 0 always and hence is wrong, it should return the number of occurrences of...
ffc4b329ed120c9ba968ab62afe0e5129bd1345b
sasakisho/python
/chapter3/funcargs.py
147
3.703125
4
def func1(*args): sum_v = 0 for n in args: sum_v += n return sum_v print(func1(5,4,3,2,1)) print(func1(10,9,8,7,6,5,4,3,2,1))
34c6593840261973f205bc1e5247d20bcad022d4
sirishsilpakar/eadd-creational-patterns
/login/login_abstract.py
553
3.765625
4
# Python on its own doesn't provide abstract class. It comes with 'abc' module that provides the basis for defining Abstract Base Classes # This modules also provides the decorators for defining a class method as abstract method. from abc import ABC, abstractmethod class LoginGateway(ABC): """This is an interface ...
ba03c1426031515bb622b24e2ecac9ca949190f6
PathShare/pathshare
/backend/pathshare_api/decorators.py
585
3.609375
4
# -*- coding: utf-8 -*- """Custom decorator functions.""" from functools import wraps from threading import Thread from typing import Callable def thread_task(f: Callable) -> Callable: """Defines a wrapper that will decorate a function. Parameters ---------- f : Callable The function to be wrapped. Return...
b4baf6cd78a3a7a8a214e8ca8a10bc79bfd29b61
rcchen0526/UVA
/uva_11356.py
1,185
3.953125
4
days=[0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] months=["", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] def Find_Month(m): for i in range(1, 13): if m==months[i]: return i return 0 def leap(Y): day=0 ...
b100420c3d64bd91760d495902bc6e26e6973c15
mahakmakharia/Online-Dating-App
/tinder.py
13,904
3.546875
4
from tkinter import * #importing tkinter import mysql.connector #importing connector class Tinder: def __init__(self): #connecting to the database self.conn = mysql.connector.connect(host="localhost", user="root", password='', database="tinderb1") self.mycursor = self.conn.cursor()...
03ebc08629328810f4403b9c8f6158ac7a655f3e
juiyangchang/LeetCoding
/python/355_Design_Twitter.py
1,958
3.921875
4
import itertools from collections import deque, defaultdict import heapq class Twitter: ''' https://discuss.leetcode.com/topic/47838/python-solution ''' def __init__(self): """ Initialize your data structure here. """ self.timer = itertools.count(step=-1) self.p...
25441b846dd6dde879b6b7278abf97e67a4cc41c
knut0815/autofit_workspace
/notebooks/howtofit/chapter_phase_api/src/plot/line_plots.py
1,823
4.15625
4
import os from os import path import matplotlib.pyplot as plt """ This is the `plot_line` function we saw in chapter 1. """ def figure( xvalues, line, title=None, ylabel=None, errors=None, color="k", output_path=None, output_filename=None, output_format="show", ...
749512422292edabf7e1f9e611caa2bfd83eee67
azez-alhoot/data-structures-and-algorithms-python
/data_structures_and_algorithms_python/data_structures/tree/tree.py
7,100
4.3125
4
# import sys # sys.path.append('/home/aziz/401/data-structures-and-algorithms-python') # from data_structures_and_algorithms_python.data_structures.stacks_and_queues.stacks_and_queues import Queue class Node: def __init__(self,value): self.value= value self.left = None self.right = None ...
dbe2403dc3ebfc486023539f434728d80b77d961
caiespin/edx_Introduction_to_Computer_Science_Using_Python
/polysum.py
450
3.71875
4
# -*- coding: utf-8 -*- """ Created on Mon May 28 17:32:43 2018 @author: Carlos Isaac """ def polysum(n, s): ''' Calculate the sum of the area and the square of the perimeter of the a regular polygon. n: positive integer. s: int or float. Returns float rounded to 4 decimal places. '...
5a3749eea80767fc3acb535b8f9e97d04a929012
max-moazzam/pythonCoderbyte
/evenNumbers.py
472
4.3125
4
#Function takes in a number input and will return a list of all even numbers between 0 and that number (inclusive) def evenNumbers(num): i = 0 output = [] #While loop will go through every number while i <= num: #If the number is even then it will be added to the output variable (even number / 2 will h...
eff34bcc4e0eb297df05ab8c9383eb9ab6eabc6a
vaneguti110/pythonprojects
/for.py
465
4.25
4
#Project to know how many vowels and consonants are in the word Hello, using python 3.7.2 vowels = 0 consonants = 0 print("In the word 'Hello', how many vowels and consonants has:") for letter in "Hello": if letter.lower() in "aeiou": vowels = vowels + 1 elif letter == "": pass ...
3b2b37987df892e0f8f1488c9a72a694ca0054e5
hackstarsj/PythonBasicCheatSheet
/PythonCheatSheet.py
4,257
4.3125
4
#print a Message in Python print("Hello World in Python") #store data in variable variable="Hello world in Variable" #print a variable print(variable) #create integer variable integervariable=10 integervariable2=20 #do arithmetic operation on integer print(integervariable+integervariable2) string1="Hello" string2=...
41cf1763bf389f89a3ef6a6d47123e8a1d509e7c
geekoss/TD8_bench_RV
/TD_benchmark.py
5,256
3.671875
4
from random import randint from time import time from sys import setrecursionlimit setrecursionlimit(500_000) # def bubble_sort(table): # pass # def quick_sort(table): # pass # def merge_sort(table): # pass def generate_random_table(table_size): ''' - FUNCTION ...
cd26b13c98bb46de150c233baaf3061806e41ad0
nasawangd/Nim
/Derekn4_project2.py
6,902
3.9375
4
#Derek Nasawang #TCSS 142 #Project 2 import random import sys def nimSumFunc(stoneList): #We are going to make a copy of the stoneList so that we are sure that it wont interfere with the board stoneList2 = stoneList[:] stoneList3 = [] pileNum = max(stoneList2) nim = 0 nimSum_1 = 0 #Hint step #F...
5cf2131acd3a0def0871191439dff63a5d07a2ef
Aasthaengg/IBMdataset
/Python_codes/p00003/s950762312.py
704
3.8125
4
def solve(): data = read() result = think(data) write(result) def read(): n = int(input()) data = [] for i in range(n): data.append(read_data()) return data def read_data(): return list(map(int, input().split(' '))) def think(data): result = [] for d in data: ...
dd4d40ea07dd294cd10f320c99e4f68d2d9dcc1a
mbaeumer/fiftyseven
/part1/ex3-print-quotes.py
163
3.71875
4
#!/usr/bin/python print("Exercise 4: ") print("") quote = input("What is the quote? ") person = input("Who said it? ") print("%s says, \"%s\"" % (person, quote))
0d80cd66a337e827024f3f3f74ec23d2da19c11c
leohck/secretchallenge
/game/player.py
4,777
3.515625
4
from random import choice from game.estate import Estate # CONSTANTE QUE ARMAZENA OS TIPOS DE COMPORTAMENTO BEHAVIORS = { 1: (1, "impulsivo"), 2: (2, "exigente"), 3: (3, "cauteloso"), 4: (4, "aleatorio") } class Player: """ Jodador """ def __init__(self, id_, behavior, balance=300)...
c18bbff841f02ba6f7ee1d973345897f866818c3
chowhan/CS342
/homework_06/homework/models.py
3,919
3.5625
4
import torch from torch import nn # Unlike previous classes, don't use these classes directly in train.py # Use the functions given in main.py # However, model definition still needs to be defined in these classes class Block(nn.Module): ''' Your code for resnet blocks ''' def __init__(self, in_channe...
feb9d69135253447274e82ccd2ff2117effa21b8
austinwellman3/Project
/Read and Writing Files in Python/textbasedgame-1.py
4,538
4.34375
4
Created by: Austin Wellman # This is a text based quiz app based on methods import time # We are allowing user to enter "T", "t","True" or "F","f","False" def setTrueAndFalse(): true = ["T", "t", "True"] false = ["F", "f", "False"] # now we are returning them to main return true, false ...
a120cbc19c7a72c360ce3e4650f48887b02a39e5
konakallaANUSHA/python-deep-learning
/lab-1/CODE/TASK-4.py
2,006
3.5625
4
from bs4 import BeautifulSoup import requests import csv # Step 1: Sending a HTTP request to a URL url = "https://scikit-learn.org/stable/modules/clustering.html#clustering" # Make a GET request to fetch the raw HTML content html_content = requests.get(url).text # Step 2: Parse the html content soup = BeautifulSoup(h...
e825170b0b35d4f9bcce303d52a13dbddcc39f16
Mr-Perfection/coding_practice
/Python/Practices/SortingAndSearching/sorted_merge.py
719
4.03125
4
""" Sorted Merge: You are given two sorted arrays, A and B, where A has a large enough buffer at the end to hold B. Write a method to merge B into A in sorted order. a = [1,2,4,6,None,None] b = [3,5] result = [1,2,3,4,5,6] O(n) n is length of A """ def sorted_merge(A,B): if len(A) == 0 or len(B) == 0: ...
e8c4b7ed026133c54a50c80b13a3aa7e1f47709e
nasima-akter-tania/Problem-Solve
/codeforce/a_boy_girl.py
139
3.5625
4
name_input = input().lower() sum = list(set(name_input)) if len(sum) %2 == 0: print("CHAT WITH HER!") else: print("IGNORE HIM!")
718e19cf1073331d1217bb4eb3c893155f17ee36
tony-andreev94/Python-Fundamentals
/07. REGEX/01. Capture the Numbers.py
403
4.25
4
# Write a program that finds all numbers in a sequence of strings. # The output is all the numbers, extracted and printed on a single line – each separated by a single space. import re def find_numbers(string): regex = r"([\d]+)" result = re.finditer(regex, string, re.MULTILINE) return " ".join(each.grou...
8f163ea585cc6d6cb5a9a70b5ed1ea47a76802d7
daniellevin233/Python_projects
/Nand2Tetris/08_vm_parser_II/vm_parser.py
6,230
3.671875
4
""" Parser Class for reading from vm file and parsing its commands """ from enum import Enum class VMParser: """ Parser Class dealing with parsing of VM files """ COMMENT_STRING = '//' class CommandTypes(Enum): """ Class enumerating all possible commands types ...
76c88444c14a1398a94e0e82cc61b3af26abf2fd
rjh-mopjones/scripts-ml
/confusion_matrix.py
8,150
3.65625
4
import numpy as np def confusion_matrix(prediction, annotation, class_labels=None): """ Computes the confusion matrix. Parameters ---------- prediction : np.array an N dimensional numpy array containing the predicted class labels annotation : np.array an N dimensional nu...
73c0f78e745679b1c564d1d932432154abf51324
bww7448/baekjoon_solution
/if, for, while, 실습1, 1차원배열/2446.py
315
3.671875
4
# N = int(input()) # for i in range (1, N): # s = "*"*(2*N-2*i+1) # print(s.center(2*N-1)) # for j in range(1, N+1): # s="*"*(2*j-1) # print(s.center(2*N-1)) N = int(input()) for i in range (1, N): print(" " * (i), "*" * (2*(N-i)-1)) for i in range (1, N-1): print(" "*(N-1-i), "*"*(2*i+1))
6542f22b8c16ad176c590a0946160910b04e6dbf
SourTofu/Python-learning
/week1/九九乘法表.py
321
3.765625
4
for i in range(1,10): for j in range(1,i+1): print(str(j)+"x"+str(i)+"="+str(j*i)+'\t',end=' ') print() print("") for i in range(1,10): a = '' for j in range(i,10): a += '{}*{}={:<3}'.format(j,i,i*j) print("{:>70}".format(a)) # print(str(i)+"x"+str(j)+"="+str(j*i)+'\t',end=' ')...
bed7a92d7e2430da1222c283ecb2654a17ebaa4e
zhan3680/Gamoku
/gamoku.py
21,839
4.25
4
"""Gomoku starter code You should complete every incomplete function, and add more functions and variables as needed. Note that incomplete functions have 'pass' as the first statement: pass is a Python keyword; it is a statement that does nothing. This is a placeholder that you should remove once you modify the ...
97c0fd1e32a3358fece20deaed84b9e61f8dbd17
YiseBoge/CompetitiveProgramming
/CodeForce/Contest/Round613/just_eat_it.py
553
3.640625
4
def is_yasser_happy(length, tastiness): total = sum(tastiness) count = 0 for i in range(length - 1): count += tastiness[i] if count <= 0 or count >= total: return "NO" return "YES" def solution(inp1, inp2): return is_yasser_happy(inp1, inp2) def main(): inp1 = in...
03282898cd98fc2b8ba5270bcb915d71ac96930b
VCloser/CodingInterviewChinese2-python
/16_Power.py
670
4.0625
4
def power(base, exponent): if base == 0 and exponent == 0: return None unsigned_exponent = abs(exponent) result = unsigned_power(base, unsigned_exponent) if exponent < 0: return 1.0 / result return result def unsigned_power(base, unsigned_exponent): """ 二分法计算a的n次方 """ ...
3a2195c4dad2f22bae1c5301bd19a7bbce290538
giovannyortegon/holbertonschool-machine_learning
/supervised_learning/0x05-regularization/7-early_stopping.py
804
3.71875
4
#!/usr/bin/env python3 """ Early Stopping """ def early_stopping(cost, opt_cost, threshold, patience, count): """ early_stopping Args: cost is the current validation cost of the neural network opt_cost is the lowest recorded validation cost of the neural network thres...
a01774381c98678c225a167a30a7bed50d99864f
kandrey999/PingPong
/rocket.py
633
3.5
4
import turtle class Rocket: def __init__(self, x, y, width=10, height=50): self.__pen = turtle.Turtle() self.width = width self.height = height self.__pen.goto(x, y) self.__pen.speed(0) def init_rocket(self): pen = self.__pen pen.color('white') ...
48c6757d7e536ce099d2b1a8f129d7a6d27e1690
rafaelperazzo/programacao-web
/moodledata/vpl_data/27/usersdata/108/7687/submittedfiles/divisores.py
235
3.90625
4
# -*- coding: utf-8 -*- from __future__ import division import math n = int (input ('Digite a quantidade de múltiplos:')) a = int (input ('Digite a:')) b = int (input ('Digite b:')) i=1 while (i<=n): multA=a*i multB=b*i
67be97da8472d96aeccbc22ef20fa510e3099eec
Toad2186/cs164
/tests/correct/def_recursive.py
244
4.4375
4
# Writing recursive functions and seeing if they work # Simple summation recursion which sums all numbers up to and including x. def sum_up_to(x): if x == 1: return x else: return x + sum_up_to(x-1) print sum_up_to(5)
9e7696634c5a7ae0bf5236f2d234bdde3385aa53
Joelsondrigu/CursoPython
/python_teste/LAÇOS_DE_REPETIÇÃO.py
1,350
3.765625
4
'''for c in range(1,11): print(f'conte {c}') print('Acabou') n = int(input('Digite um numero: ')) for c in range(1,20): tab = n*c print(f'{n} x {c} = {tab}') print('Fim da tabuada') for c in range(1,50): print(f'{c}') print('fim da contagem') for c in range(1,10): print('Oi') print('Joelson')...
d0efdc6448cf4b3c6c12f94431354364be77a82d
totemw/algorithm
/linked list/#merge.py
3,648
4.15625
4
""" Merge two sorted (ascending) linked lists and return it as a new sorted list. The new sorted list should be made by splicing together the nodes of the two lists and sorted in ascending order. """ class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = ...
04e23acc8bde8b498fba0377541bbf452dba415b
rafaelsaidbc/Exercicios_python
/ex071.py
958
3.984375
4
'''Crie um programa que simule o funcionamento de um caixa eletrônico. No início, pergunte ao usuário qual será o valor a ser sacado (numero inteiro) e o programa vai informar quantas cédulas de cada valor serão entregues. Considere que o caixa possui cédulas de R$50, R$20, R$10 e R$1.''' valor = 1 cinquenta = 0 vinte ...
9165e7165154e6141677f5060f36cdf8e6039e6f
yywecanwin/PythonLearning
/day07/02.匿名函数的应用场景.py
294
3.53125
4
# -*- coding: utf-8 -*- # author:yaoyao time:2020/1/8 def my_funcation(func): a = 100 b = 200 # 把cucalate_rule当做函数来调用 result = func(a,b) print("result:",result) my_funcation(lambda a,b:a + b) my_funcation(lambda a,b:a - b) my_funcation(lambda a,b:a * b)
e190e8a68e5bd4265d36f75f37a3fdc757c2624a
RahulBantode/Pandas_python
/Dataframe/application-1.py
350
4.4375
4
#Write a program to create a Dataframe using two dimensional list import pandas as pd def main(): list = [[1,2,3],[4,5,6],[7,8,9]] dataframe = pd.DataFrame(list,index=['ln-1','ln-2','ln-3'],columns=['col-1','col-2','col-3']) print(dataframe) print("Shape of DataFrame : ",dataframe.shape) if __...
0f98df53b2ecf83d0f86b085bfee59d4e62a4a82
tdb-alcorn/q2
/q2/agents/agent.py
1,318
3.5
4
from abc import ABC, abstractmethod, abstractproperty import tensorflow as tf import numpy as np from gym import Space class Agent(ABC): ### Properties ### # message: str -- picked up by the training regimen and displayed after each step @abstractmethod def __init__(self, observation_space:Space, act...
e45945275fad5924a7cebf4166660dda5741d497
arthurnog/semestre1
/lab00.py
429
3.8125
4
#Arthur Lucas da Silva Nogueira 213293 print('Entre com dois inteiros') first = float(input()) second = float(input()) soma = first + second print('Soma = %d' %soma) diferenca = first - second print('Diferenca = %d' %diferenca) multiplicacao = first * second print('Multiplicacao = %d' %multiplicacao) divisaointeira =...
c54dd5b785bd1104643eb0ddfe9ed7da62450b9c
JesusSePe/Python
/recursivity/Extras/exponential.py
147
3.609375
4
def exponential(base, exp): if exp == 1: return base else: return base*exponential(base, exp-1) print(exponential(5, 4))
98234202043727f9a44e8f40455f3885fdbe8aa7
lucasamsilva/python
/confere loteria.py
349
3.53125
4
resultado = [] numeros = [] acertos = 0 for i in range(15): resultado.append(int(input())) while True: for i in range(15): numeros.append(int(input())) if numeros[i] == 0: break for i in resultado: for j in numeros: if i == j: acertos += 1 ...
b8649f84cbab3a00434321863bddc55b6e5558af
midnitesun002/sorting
/python/shell_sort.py
725
3.84375
4
#!/usr/bin/python from math import log # Reference: https://en.wikipedia.org/wiki/Shellsort def shell(array, gaps): final = len(array) for gap in gaps: for i in range(gap, final): temp = array[i] j = i while (j >= gap and array[j - gap] > temp): array[j] = array[j - gap] j -= gap array[j] = te...
d61fe5d4a59cf9401d910ef4167399037423cca7
ninjrok/leetcode
/LC32_longest_valid_parenthesis.py
917
3.53125
4
class Stack: def __init__(self): self.arr = [] def is_empty(self): return (True if not self.arr else False) def top(self): return (self.arr[-1] if not self.is_empty() else None) def push(self, x): self.arr.append(x) def pop(self): r...
9f9e53c1c43d5fd9715637444382209ca351d8d3
gabrielbrum7/BaseDeConhecimento
/Scripts Python Gabriel Brum/paymentSumCalc_v2.1.py
1,018
3.875
4
#coding: utf8 print '\n\n' print 'paymentSumCalc\n\n' print 'Para cada entrega você terá que registrar os dados que se seguirão para alterar o XML\n\n' loop = input ('Digite a quantidade de entregas: \n') for item in range (0, loop): print 'Registro da ' + str(item + 1) + 'ª entrega: \n' amountDue = input ('Dig...
b96055f87949de3133bde33a282189e1cd3d93a2
iblackcat/leetcode
/56_Merge_Intervals.py
735
3.65625
4
class Interval(object): def __init__(self,s=0,e=0): self.start = s self.end = e def cmp(a,b): if a.start>b.start: return 1 elif a.start==b.start: return 0 else: return -1 def merge(intervals): n = len(intervals) if n==0: return [] intervals=sorted(intervals,cmp) l=1 a...
54074323ee7345683cd93135965e7c86247cbbcc
JavaScriptBach/Project-Euler
/117.py
897
4.03125
4
""" Using a combination of black square tiles and oblong tiles chosen from: red tiles measuring two units, green tiles measuring three units, and blue tiles measuring four units, it is possible to tile a row measuring five units in length in exactly fifteen different ways. ...
3ec3b09625e139cb794a750245c192ea9498004c
itsrainingmani/brainfuck-py
/brainfuck_py/interpreter.py
5,899
3.734375
4
import argparse import sys # Globals MAX_VAL = 255 MIN_VAL = 0 commands = "+-><[].,#!" DEBUG = False instructions = """\ Symbol: > Instr: Increment the data pointer by one (to point to the next cell to the right). Symbol: < Instr: Decrement the data pointer by one (to point to the next cell...
10495e7df4f5101961e857ceeef40527202f8646
gabrielqueiroz1/exercicios_uri
/tipos_triangulo-uri.py
575
3.859375
4
a, b, c = [float(i) for i in input().split()] if a + b > c and a + c > b and c + b > a: if a == b and a == c and b == c: #poderíamos escrever assim: r1 == r2 == r3: print("TRIANGULO EQUILATERO" "TRIANGULO ACUTANGULO") elif a == b != c or a == c != b or b == c != a: print("Os segme...
6c5f64ff955fbc36331555f71d085f3ab3ae5960
jwill824/python-examples
/shortest_distance.py
2,843
3.640625
4
import unittest class Graph: def __init__(self, graph): node_connections = graph.split(",") self.init = [] for data in node_connections: self.init.append(data[0]) self.node_values = sorted(set(self.init)) self.nodes ...
59e90638ed18b0256bb29d9f3db12d6c923b6e5a
blubits/tr3s
/views/interface.py
1,528
3.578125
4
""" Abstract base class for all Interfaces. :Author: Maded Batara III :Version: v20181126 """ from engine import ViewEvents class Interface: """A view for the three-four-three game engine. """ def __init__(self): """ Initializes an Interface. When subclassing Interface, a...
aa50ff904d26fe2105c87c51d65aad6cda9617ca
Codewithml/coding-problems-solutions
/arrays/anagram/anagram.py
902
3.78125
4
class Anagram(object): def anagram(self, string1, string2): if string1 is None or string2 is None: return None string1 = string1.replace(" ", "").lower() string2 = string2.replace(" ", "").lower() count = {} for let in string1: if let in count: ...
70a2b4784a29b39cc08dc33f7870f8135ae40899
weiyuyan/LeetCode
/Advanced/676. 实现一个魔法字典.py
2,404
4.09375
4
#!usr/bin/env python # -*- coding:utf-8 -*- # author: ShidongDu time:2020/1/17 ''' 实现一个带有buildDict, 以及 search方法的魔法字典。 对于buildDict方法,你将被给定一串不重复的单词来构建一个字典。 对于search方法,你将被给定一个单词,并且判定能否只将这个单词中一个字母换成另一个字母,使得所形成的新单词存在于你构建的字典中。 示例 1: Input: buildDict(["hello", "leetcode"]), Output: Null Input: search("hello"), Output: Fal...
3a676c738cc3c124d24bdc494443ca8bcc4ebfe3
CaseyNord-inc/treehouse
/Python Collections/set_math.py
1,136
3.78125
4
COURSES = { "Python Basics": {"Python", "functions", "variables", "booleans", "integers", "floats", "arrays", "strings", "exceptions", "conditions", "input", "loops"}, "Java Basics": {"Java", "strings", "variables", "inp...
5924aecc58e6838011f0cc64c6193e8b89410ecd
WenHui-Zhou/weekly-code-STCA
/top100_frequency/first/912.py
3,383
3.734375
4
class Solution(object): def sortArray(self, nums): """ :type nums: List[int] :rtype: List[int] if nums == []: return [] def quick_sort(nums,left,right): if left > right: return low = left hight = right ...
7b3c841ca1a2970c9e5956ef7430f03fe765274c
whereistanya/aoc
/2020/24.py
1,810
3.703125
4
#!/usr/bin/env python # Advent of code day 24. def walk(moves): x = 0 y = 0 # north is positive for move in moves: if move == "ne": x += 0.5 y += 1 elif move == "e": x += 1 elif move == "se": x += 0.5 y -= 1 elif move == "sw": x -= 0.5 y -= 1 elif mov...
5caa96c7fcc537db2f392d62cea764739642052e
thanjiramint/MyInternalProject1
/Optimization.py
11,061
4.125
4
import math import numpy as np import matplotlib.pyplot as plt import types def plot(f,start,stop, space=100): ### Plot ## x = np.linspace(start,stop,space) y = f(x) # plot the function plt.plot(x,y) plt.grid() # show the plot plt.show() def swap (a,b): temp=a a=b b=temp ...
07437ddc5a080dd8a33e74239efc74b54402bc44
ajpiter/PythonProTips
/DataVisualization/Images/AdjustAspectRatio.py
787
3.5
4
#An uneven aspect ratio occurs when you take a sample of the pixels #The code below takes the 4th across and the 2nd high #Resulting in uneven sampling and a distored image because the aspect ratio is not equal variable = variableb[::4,::2] print(variable.shape) plt.imshow(variable) plt.axis('off') plt.show() #To...
7d0caf162d094b88792c2a5bb5c6b16ed7487331
yoana91/Programming0-Solutions
/Week 5/budget2.py
489
3.625
4
def on_budget(books, budget): b = budget result = { "books_on_budget": 0, "loan": 0 } books = sorted(books) sum_books = sum(books) for book in books: if budget > 0: if book > budget: break budget -= book result["b...
e160568665edc3e6a60227a0eaf5c35dc1807f98
rafaelperazzo/programacao-web
/moodledata/vpl_data/206/usersdata/269/87104/submittedfiles/av1_parte3.py
130
3.875
4
# -*- coding: utf-8 -*- #COMECE AQUI ABAIXO n=int(input('digite n: ')) sp=0 for i in range(0,n,1): if i%2==0: sp=sp+
d6cb245b9b12162a7c6d4da4fad66c20ddc4ed37
jeronimomora/word-search-cv-cnc
/generate_words.py
600
3.6875
4
def generate_words(filename): 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'] newline = '\n' the_file = open(filename) characters = the_file.read() characters = list(characters) the_file....
040954972a391afff850934b93a445bcacb89687
DaiWeiJie-1/Python-learning
/mapreduce/reduce.py
98
3.5
4
from functools import reduce def add(x,y): return x + y r = reduce(add,[1,2,3,4,5]) print(r)
0516d3965c156ec89ec1705b0c878e10683d0514
para-de-codar-alek/Respostas-Uri
/1259.py
961
3.953125
4
# Um programa que leia valores em um intervalo inputado e nos mostre em ordem crescente os pares # e depois o ímpares em decr # Jogar os elementos divisíveis por 2 em uma lista e os não em outra # logo após sort as listas e mostrar em um loop os elementos da par primeiro e da ímpar logo após counter = int(input()...
e578975cacfe0a49b2557fc548f3f4c3273fc9ba
raysmith619/Introduction-To-Programming
/exercises/classes/cards_card.py
1,870
3.59375
4
#cards_card.py 07Oct2021 crs, author # """ A cards_card "module" which can be used by other programs """ class CardsCard: """ Simple playing card class """ rank2str = {14:"A", 13:"K", 12:"Q", 11:"J", 10:"10", 9:"9", 8:"8", 7:"7", 6:"6", 5:"5", 4:"4", 3:"3", 2:"2...
2c1ba88d09922cac4123291f7887610cee44c094
Amrithnath/46-python-excercises
/ex13-maxin1st
393
3.828125
4
#!/usr/bin/python import sys import os import time def main(): os.system('clear') mydata=input("please enter the list of numbers\n") start=time.time() gr8=max_in_list(mydata) print("greatest number from list is :",gr8) print("time taken:",time.time()-start) def max_in_list(x): ans=x[0] for element in x: if(e...
ee02c3b40e1b5ac8e20d39eecf9e7ff7a427c6df
hyeonukjeong/Algorithm
/kr/hs/dgsw/nyup/part01/design12/grade.py
213
3.828125
4
score = 100 if score >= 90: grade = 'A' elif 90 > score >= 80: grade = 'B' elif 80 > score >= 70: grade = 'C' else: grade = 'F' print(grade) g = 'FFFFFFFCBA' grade = g[score//10] print(grade)
517a2a25507962e2338392cdc82d758e36fde299
jlgull/Demo1
/Main.py
260
3.71875
4
y = 3 def print_stuff(): print ("Calling print_stuff") print(y) z = 4 print(z) print("exiting print_stuff") print_stuff() # we call print_stuff and the program execution goes to (***) print(y) # works fine print(z) # NameError!!!
360862632e5d2e6bc7c8c03d47173e3d9c38b1fb
wppply/LeetCode-in-Python
/p59.py
493
3.546875
4
class Solution(object): def generateMatrix(self, n): result = [[0 for i in range(n)] for j in range(n)] coord = [[(i,j) for j in range(n)] for i in range(n)] count = 0 while coord: for (x, y) in coord.pop(0): result[x][y] = co...
8e9a32b5e68ad6ae240af243b040a8151bfd9ac8
soura49/Python
/hackerrank/minion.py
861
3.5
4
from collections import Counter def minion_game(Name): length =len(Name) vowel_count = 0 consent_count = 0 Name_list = [] for i in xrange(length): for j in xrange(length): if Name[i:j+1] != '': Name_list.append(Name[i:j+1]) count = Counter(Name_list) ite...
0abb2f7623aec2f85f10f3485ef3c8255be31c08
KoussayDhifi/pyArray
/pyArray/myfunctions.py
996
3.703125
4
import random import string def create_array(type,length): T=[] for i in range(length): if type == 'int': T.append(random.randint(0,999)) elif type == 'str': letters = list(string.ascii_letters) T.append(letters[random.randint(0,51)]) elif type == 'bool': boolea = [True,False] T.append(boolea[ra...
962df4bcd4b8558d29b93402922f50db3918697f
JosephLevinthal/Research-projects
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/225/users/4003/codes/1756_1577.py
210
3.5
4
from numpy import* a=array(eval(input("a aceleracao:"))) v=array(eval(input("v0:"))) n=array(eval(input("numeros int.:"))) t=arange(n) d=zeros(n) i=0 while(i<n): d[i]=((a*(t[i]**2)/2)+v*t[i]) i=i+1 print(d)
485d7ffec5343ec1f9de8e02f2de3b7fb1b1fd7c
ArnoldYSYeung/phonemic-confusion
/transformer.py
9,509
3.765625
4
""" Transformer in PyTorch Authors: Arnold Yeung Upload Date: April 18th, 2019 Revisions: THIS CODE IS UNFINISHED AND ABANDONED. Helpful Links: How to code the transformer in Pytorch : https://towardsdatascience.com/how-to-code-the-transformer-in-pytorch-24db27c8f9ec...
a14cb859c635ff6b3edad1dc44e191f5b716b169
Julian0912/Book_DSA
/Chapter_7/CircularQueue.py
1,260
3.703125
4
# -*- coding:utf8 -*- # Author: Julian Black # Function: # class EmptyError(Exception): pass class Node(object): __slots__ = 'element', 'next' def __init__(self, element, next): self.element = element self.next = next class CircularQueue(object): def __init__(self): self.t...
ac68210540047f7ced6621b49ce9c69c072ab1c6
Vonewman/python_app
/openclassroom/for_2.py
156
3.5
4
chaine = "Bonjour les Kagglers" for lettre in chaine: if lettre in "AEIOUYaeiouy": # lettre est une voyelle print(lettre) else: print("*")
06e8331cc8f1aad9e40def42b0299af897e52199
upasanapradhan/IW-PythonAssignmentIII
/IW-PythonAssignmentIII/linear-search.py
416
3.96875
4
def search(arr, x): for i in range(len(arr)): if arr[i] == x: return i return -1 arr = [10, 20, 30, 40] r = search(arr, 10) if r != -1: print("Element is present at index", str(r)) else: print("Element is not present in array") r = search(arr,0) if r != -1: p...
05a965653c94717f0d201cae24273eec996ff25e
RobertAlexCL/HDT11
/python/hdt11/hdt11/hdt11.py
2,991
3.53125
4
import networkx as nx graph = nx.Graph() FILE_NAME = "guategrafo.txt" # ********************************** METODOS ************************** # imprime menu para usuario def imprimir_menu(): print("Menu") print("1. Agregar ciudad") print("2. Agregar coneccion entre ciudades") print("3. Eliminar cone...
cb2b94f93c562eaa04757fe3f168a6bb23b062b9
quenton1225/4-Link-Game-in-Python-CN
/main1.5.8.py
41,767
3.6875
4
import pygame from pygame.locals import * import copy import numpy as np import random as r import time as t from sys import exit as systemExit import math import tkinter as tk class Board: def __init__(self, size=16): #self.board = np.zeros((16, 16), int) self.board = np.array([[0]+...
0acecd1c801cdc288bc327918c4bbdd5f0ff42b3
southpawgeek/perlweeklychallenge-club
/challenge-105/stuart-little/python/ch-1.py
346
3.640625
4
#!/usr/bin/env python # run <script> <exponent> <number> import itertools import math import sys def nthRoot(xp,nr): rootFloor = next((i for i in itertools.count() if (i+1) ** xp > nr)) if (rootFloor ** xp == nr): return rootFloor return math.exp(math.log(nr)/xp) print(nthRoot(*list(map(lambda x...
0ec2e2cd2fdf5030e24684cdc06476afaf594cbf
AndreisSirlene/Python-Exercises-Curso-em-Video-World-1-2-and-3
/World 2/Challenge043.py
446
4.1875
4
w = float(input('What is your weight? (Kg) ')) h = float(input('What is your height? (m) ')) bmi = w / (h**2) print('The BMI of this person is {:.1f}'.format(bmi)) if bmi < 18.5: print('Becareful you are under weight!') elif 18.5 <= bmi < 25: print('Congratulations, your weight is ideal!') elif 25 <= bmi <= 30:...