blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
87f7fea9e16f8aa7dbaa1fdd060b4bc9301663d8 | adelq/project-euler | /52.py | 485 | 3.6875 | 4 | def numhash(num):
num = str(num)
digithash = {0:0, 1:0, 2:0, 3:0, 4:0, 5:0, 6:0, 7:0, 8:0, 9:0}
for digit in num:
digithash[int(digit)] += 1
return digithash
i = 1
while True:
spechash = numhash(i)
if spechash == numhash(2*i):
if spechash == numhash(3*i):
if spechash == numhash(4*i):
if spechash == nu... |
46cbebecf360194534ad020c3ecd78eb83acdc3b | adit-sinha/Solutions-to-Practice-Python | /(15) Reverse Word Order.py | 95 | 3.625 | 4 | a = input("Please enter your sentence here.")
u = a.split()[::-1]
d = " ".join(u)
print(d)
|
b0677d17d22162a8db8819920fa99049d995f2d0 | pauloesampaio/simple_image_clf | /web/src/simple_image_clf.py | 2,641 | 3.59375 | 4 | import streamlit as st
import pandas as pd
import requests
from tensorflow.image import resize, decode_image
from tensorflow.keras.applications.resnet import (
ResNet50,
decode_predictions,
preprocess_input,
)
def download_image(url, target_size=(224, 224)):
"""Function to download images from url and... |
2f533bce3b3d7db218ff088861a919b87c577738 | tinkle1129/Leetcode_Solution | /String/8. String to Integer (atoi).py | 1,548 | 3.5 | 4 | ###########################################
# Author: Tinkle
# E-mail: shutingnupt@gmail.com
# Name: String to Integer.py
# Creation Time: 2017/6/22
###########################################
'''
Implement atoi to convert a string to an integer.
Hint: Carefully consider all possible input cases. If you want a challen... |
17220c1b5e3ffe659bb621dca41e1c0ef68cc926 | rafalacerda1530/Python | /Aulas Sec 8/Função com parametros.py | 2,005 | 4.6875 | 5 | """
Funções com parametros
-Funções que recebm dados
- FUnções Podem receber N parametros, podemos receber
quantos parametros quisermos e els são separados por
virgula
- o Return deve ser colocado no bloco da função
"""
"""
# ela recebe um parametro e é obrigatorio colocar por ex: print(quadrado(2))
# o 2 é o par... |
6858d1aebd9114c6db53ae8d039fa9a21d3c9b63 | micko45/python_code | /codeabby/4.py | 279 | 3.578125 | 4 | #!/usr/bin/env python
#min-of-two
count = raw_input("data:\n")
answer = []
for i in range(0, int(count)):
num1, num2 = raw_input().split()
if int(num1) < int(num2):
answer.append(num1)
else:
answer.append(num2)
for x in range(len(answer)):
print answer[x],
|
b842bc1848312fc881eaf9dab8e46730f783cd61 | BolajiOlajide/pythonbo | /sample_yield.py | 205 | 3.796875 | 4 | names = ["Bolaji", "Emmanuel", "Olajide"]
def read_names():
for name in names:
yield name
def get_names():
for name in read_names():
print('Reading ===> ' + name)
get_names()
|
c5aa96a71a88e9cf6e5ecea0c698b29642b802c4 | tsaomao/GenPiFromRandomThrows | /trial.py | 1,058 | 3.5625 | 4 | # Process per group of trials:
# Process per trial:
# Process per observation:
# Generate 2 numbers
# Test for coprimality
# Count number of coprimes in a field of some number of pairs
# Find observed probability of these coprimes
# Calculate pi from sqrt(6/observed probability)
# Compar... |
4de488b731af4a6ed62177b00c3560ef24f1aae3 | hc9599/git_start | /Git_Test/mul_table.py | 352 | 3.984375 | 4 | while True:
mul_no = int(input('Enter the number you want to have multiplication number: '))
range_no = int(input('Enter the number till you want multiplication: '))
for i in range(1, range_no+1):
print(mul_no, 'X', i, '=', mul_no*i)
choice_op = str(input('Want to continue(y/n): '))
if choi... |
700ddc5a6340308b21af309cc95d76e5d5fa5460 | Seonghoon-Yu/leetcode | /0167_Two_Sum_II_Input_array_is_sorted.py | 1,486 | 3.5 | 4 | # 1. 투 포인터 풀이
# numbers가 정렬되어 있으므로 투 포인터를 이용하여 풀 수 있습니다.
class Solution:
def twoSum(self, numbers, target):
left, right = 0, len(numbers) - 1
while left < right:
sum = numbers[left] + numbers[right]
if sum < target: # sum이 target보다 작으면 left += 1
lef... |
3cc7e58cdae8c3c29598a51131b8d4c6e1b1a9f4 | luodousha/Every_day | /DAY2/分支.py | 629 | 4.15625 | 4 | #单分支:
name = '赵志强'
if name=='赵志强':
print('老单身狗%s'%name)
#双分支:
girl_friend = ''
if girl_friend:
print('恭喜啊,居然有女朋友了')
else:
print('求求你快恋爱吧.%s.'%name)
#多分支:
'''
判断成绩档次小程序
90-100 A
80-89 B
60-79 C
40-59 D
0 -39 E
程序启动,用户输入成绩,根据成绩打印等级
'''
score = int(input('请输入你的成绩:'))
if 90<= score <= 100:
print('A')
elif 79<s... |
a7b9a7fc575bb72fb1ddc2337ad945c7bbd64825 | LokeshVadlamudi/DataStructuresLC | /Day46.py | 136 | 3.671875 | 4 | # 280. Wiggle Sort
# nums = [3,5,2,1,6,4]
#
# for i in range(len(nums)):
# nums[i:i+2]=sorted(nums[i:i+2],reverse=i%2)
# print(nums) |
b578754f3488f742b1b2d432bb0e19bdf5d55b00 | sumanthreddy24/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/0-square_matrix_simple.py | 188 | 3.71875 | 4 | #!/usr/bin/python3
def square_matrix_simple(matrix=[]):
sqr_mtx = []
for row in matrix:
row = list(map(lambda x: x**2, row))
sqr_mtx.append(row)
return sqr_mtx
|
dc7bfa438159c049096f4b4f9cb6810a4c87de1a | snowdj/cs_course | /Algorithms/challenges/lc500_keyboard_row.py | 819 | 4.03125 | 4 | """
Time: O(n)
Space: O(n)
Given a List of words, return the words that can be typed using
letters of alphabet on only one row's of American keyboard like the
image below.
Example 1:
Input: ["Hello", "Alaska", "Dad", "Peace"]
Output: ["Alaska", "Dad"]
Note:
You may use one character in the keyboard more than once.
Y... |
86ce3de1c4a7fb954c8d726b8a7c2216a198954a | ljia2/leetcode.py | /solutions/tree/654.Maximum.Binary.Tree.py | 4,476 | 3.921875 | 4 | # 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):
def constructMaximumBinaryTree(self, nums):
"""
Given an integer array with no duplicates. A maximum tree building ... |
7018fdecdd2714528038d38b77dbc265237fc29b | FDio/csit | /resources/libraries/python/PLRsearch/log_plus.py | 3,557 | 3.609375 | 4 | # Copyright (c) 2021 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... |
2cb6994012ba776828f3e3a09d3e95f05ccd7bd0 | sledziu32/python_nauka | /petlaif.py | 506 | 4.125 | 4 | """
zapraszam na https://github.com/sledziu32/python_nauka
"""
"""
porównanie liczb czy są takie same
"""
x = int(5)
#y = "5" nie można porównać ciągu z liczbą
y = float(5) #float może być równy intigerowi jeżeli nie ma części ułamkowych
if x == y:
print("super! ")
else:
print("niestety")
a = 5
b =... |
12cd95926d0ec0c32fc5e80edd2cb4e31b2be07e | amarantejoacil/estudo-python | /manipulacao_arquivo/io_desafio_csv.py | 762 | 3.890625 | 4 | #!/usr/local/bin/python3
# -*- coding: latin1 -*-
import csv
# import urllib.request
#from urllib import request
# funciona mas nao sei como kkk
import urllib2
def read(url):
req = urllib2.Request(url)
resposta = urllib2.urlopen(req)
for cidade in csv.reader(resposta):
print('Cidade: {}, Cidade:... |
6b5a1a8ce5a0465db30a9c0c2668bb7238c19d37 | tganesan70/epai3-session14-tganesan70 | /dataMerger.py | 14,155 | 3.875 | 4 | # Session-14 : Ganesan Thiagarajan
# 13-Aug-2021
import csv
from itertools import islice
from collections import namedtuple
#
# Create the namedtuple templates for parking various records and date format
#
date_of_record = namedtuple('date', 'day, month, year')
person_record = namedtuple('per_record', 'ssn,first_name... |
55503730665009447f72e8c61d2e65bbae299772 | Lucas130/leet | /376-wiggleMaxLength.py | 1,825 | 3.671875 | 4 | """
如果连续数字之间的差严格地在正数和负数之间交替,则数字序列称为摆动序列。第一个差(如果存在的话)可能是正数或负数。少于两个元素的序列也是摆动序列。
例如, [1,7,4,9,2,5] 是一个摆动序列,因为差值 (6,-3,5,-7,3) 是正负交替出现的。相反, [1,4,7,2,5] 和 [1,7,4,5,5] 不是摆动序列,第一个序列是因为它的前两个差值都是正数,第二个序列是因为它的最后一个差值为零。
给定一个整数序列,返回作为摆动序列的最长子序列的长度。 通过从原始序列中删除一些(也可以不删除)元素来获得子序列,剩下的元素保持其原始顺序。
示例 2:
输入: [1,17,5,10,13,15,10,5,16,8]
输出... |
dc033b4e86572d028345be99d3dc0a66861ac913 | SenthilKumar009/100DaysOfCode-DataScience | /Python/Programs/no_teen_sum.py | 226 | 3.625 | 4 | def no_teen_sum(a,b,c):
return fix_teen(a) + fix_teen(b) + fix_teen(c)
def fix_teen(num):
if (num >=13 and num <= 14) or (num>16 and num<20):
return 0
else:
return num
print(no_teen_sum(1,13,15)) |
30153befb1dd7f81d15e84eafc11c7f7f791a044 | EduardoArias/Tareas | /Generador de 10000 numeros aleatorios.py | 387 | 3.75 | 4 | '''Este programa busca un elemento en un arreglo de 10.000 numeros aleatorios'''
import random
def buscar(lista,numero):
for i in range(len(lista)):
if lista[i] == numero:
return i
return -1
lista = [random.randint(0,100) for _ in range(10000)]
print(buscar(lista,7))
print(busca... |
bd0122dedc428144c004106b5b2903772f4c9dbf | JuniorDugue/100daysofPython | /day001/basics.py | 938 | 4.40625 | 4 | # this will print the date and time
# import datetime
# print (datetime.datetime.now())
# this will print a string with the date & time on 2 different lines
# import datetime
# print("The date and time is")
# print (datetime.datetime.now())
# this will print everything on one line
# import datetime
# print("The dat... |
661e5418119605ca1142663874ab2c71eed98c37 | py2k5/PyGeneralPurposeFunctions | /voice_recognition_tool.py | 3,066 | 3.5 | 4 | import speech_recognition as sr
import re
import webbrowser
from smtplib import SMTP
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def main():
# enter the name of usb microphone that you found
# using lsusb
# the following name is only used as an example
#mic_name ... |
e12dbcc642f75d7f69c96b6d18259f477d0705e6 | Long0Amateur/Self-learnPython | /Chapter 6 Strings/Problem/6. A program where uppercase is converted to lowercase and punctuation are ignored.py | 283 | 4.46875 | 4 | # A program asks user to enter string s,
# converts s to lowercase, remove all punctuation
s = input('Enter a string:')
# This will remove the uppercase and convert to lowercase
s1 = s.casefold()
for c in ',.;:-?!()\'"!':
s_new = s1.replace(c,'')
print(s_new)
|
fdb23d46822c4b0ec347ffd967e4eefc8112ee2b | yohanswanepoel/rugbygame | /ball.py | 1,875 | 3.90625 | 4 | # Sprite classes for platform game
import pygame
from settings import *
from rules import *
vec = pygame.math.Vector2
class Ball(pygame.sprite.Sprite):
def __init__(self, x, y, width, height):
pygame.sprite.Sprite.__init__(self)
self.height = 0
self.vel_height = 0
self.acc_height ... |
b7734da68c503bc04c210b2a6b34529d3bc79520 | himeshnag/Ds-Algo-Hacktoberfest | /Python/tortois-hare_pointer.py | 1,037 | 4.125 | 4 | #cycle detection
#one pointer moving at twice the speed of other
#Floyd's cycle finding algorithm
#Given a constant array of n elements which contains elements from 1 to n-1,
#with any of these numbers appearing any number of times. Find any one of these repeating numbers in
#O(n) and using only constant memory space... |
bf17226dc329aff722cd21b027bb9ec82d48d938 | srikloud/PyProjects | /List/ret_elemt_indx_frmlist.py | 210 | 3.796875 | 4 | def reteleindfrmlist():
a = [1,2,3,4,5,6,7,8]
out=[]
for i in range(0,len(a)):
print(a[i])
print(i)
x = [y for y in range(1, 8) if y%2 == 0]
print(x)
reteleindfrmlist() |
785641ccd8ac9e93667d6d1b921d208f7e4a539b | DaHuO/Supergraph | /codes/CodeJamCrawler/16_0_2_neat/16_0_2_shivank77_yy.py | 740 | 3.890625 | 4 | def reverse(string):
#string = string[::-1]
string = string.replace('-','=')
string = string.replace('+','-')
string = string.replace('=','+')
return string
t = int(input())
for i in range(1,t+1):
string = input()
p = len(string)
s = ''
count = 0
c = 0
if strin... |
67544711035af51be140064ec343936e14cda304 | qizongjun/Algorithms-1 | /Leetcode/Math/#43-Multiply Strings/main.py | 916 | 4.125 | 4 | # coding=utf-8
'''
Given two non-negative integers num1 and num2 represented as strings,
return the product of num1 and num2.
Note:
The length of both num1 and num2 is < 110.
Both num1 and num2 contains only digits 0-9.
Both num1 and num2 does not contain any leading zero.
You must not use any built-in BigInteger li... |
eddf2715b7fcebc54884ca5e54dac463ffb4c8e0 | ThomasBriggs/python-examples | /Classes/Classes.py | 1,599 | 3.75 | 4 | class Employee:
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + "." + last + "@comapny.com"
self.raise_ammount = 4
def __add__(self, other):
return self.pay + other.pay
def __contains__(self, it... |
644997e6b52dd60a630381f1e8e77091a8dd69cf | chriscarter777/lunarLander | /P2_LunarLander.py | 3,528 | 4.03125 | 4 | #
# -------LUNAR LANDER-------
# (it's a oldie but a goodie)
#
def main():
def chooseDifficulty():
difficulty = raw_input("Select a difficulty level (1-5):")
try:
difficulty = int(difficulty)
except ValueError:
print "Difficulty level must be a number."
... |
3599bf4b4cc88af655e9b3a6b22a75e62933bce9 | Jonathan-E-Navarro/wallbreakers | /week1/surroundedRegions.py | 2,007 | 3.84375 | 4 | class Solution:
def solve(self, board: List[List[str]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
#dfs is going to modify every O that can be reached by another O
def dfs(row, col):
# if not within boundary or on boundary or not a zer... |
999266d9a8e342a03465da5657c8f37b72039193 | Cbkhare/Challenges | /repeated_substr.py | 1,887 | 3.796875 | 4 | #In case data is passed as a parameter
from sys import argv
import re
file_name = argv[1]
fp = open(file_name,'r+')
contents = [line.strip('\n') for line in fp]
#print (contents)
for item in contents:
junk = list(item)
i =2
j =0
stack = []
s = 0
while (i-j)*2 <= len(item) and j < len(it... |
5fced2357787705619f050793a42f4b18f0e8fb4 | ntexplorer/PythonPractice | /PythonForComputation/Week3_Prac/Lab1_4.py | 297 | 4.59375 | 5 | import math
def convert_degree_to_radians(x):
rad = x / 360 * 2 * math.pi
return rad
degree = int(input('Enter the degree you want to convert: '))
rad = convert_degree_to_radians(degree)
print(degree)
print(rad)
print("An angle of {} in degrees is {} in radians".format(degree, rad))
|
71c1763f4620469c143d510b9ddb71432f7d7e8d | DagdiHiman/EDX-Python-Course-6.00.1x- | /PRG2-bob.py | 400 | 3.53125 | 4 | s="Hibob Bobob bo b"
count=0
x=0; y=3
length = int(len(s))
while y < length:
z=s[x:y]
if (z=='bob'):
count+=1
else :
count+=0
y+=1
x+=1
print("No. of bob =" + str(count))
"""
#another method-
s="Hibob Bobob bo bob"
numBobs = 0
for i in range(1, len(s)):
if s[i... |
5b3e9a1ea6e3085f0c315a5729c1c755feb1ce4b | shazam2064/complete-python-developer | /part2/tupples.py | 1,369 | 4.15625 | 4 | # my_tuple = (1, 2, 3, "Stardust Crusaders", ["Star Platinum", "Hierophant Green", "Magician's Red", "Silver Chariot"])
#
# print(my_tuple[4])
# # The piece of code below won't work, because a tuple's values can't be modified.
# my_tuple = (1, 2, 3, "Stardust Crusaders", ["Star Platinum", "Hierophant Green", "Magician... |
41b450949ed7bd173fd32997c8fc25b512df24f2 | NotAKernel/python-tutorials | /rental_car.py | 120 | 3.5625 | 4 | ask_car = "What car would you like? "
car = input(ask_car)
print(f"Let me see if we have any {car.title()}'s in stock.") |
c77feebb78886fb914540a24ad062e245979fabd | smyang2018/ergatis | /src/python/lgtanalysis.py | 10,482 | 3.671875 | 4 | # This is a program to analyse SAM files for Lateral Genome Transfers.
# Ashwinkumar Ganesan.
# Date: 01/25/2010
# This module is access os functions, like check if a file exists or not.
import os
# Class to work with SAM Files.
from seqfileparse import SeqFileAnalyse
# Class for LGT.
# It contains the function to a... |
1008deb2160d2d6acefed49faae43f493f0fb762 | drolleigh/AdventCode | /Day3/day3.py | 1,443 | 3.90625 | 4 | # Author: Dylan Rolleigh
# Day: 3
import numpy as np
def map_reader():
with open('day3_input.txt', "r") as text_file:
policy = text_file.readlines()
return policy
map = map_reader()
# print(map)
# Build map in matrix form and pop off '/n'
matrix = []
for sub in map:
matrix.append(list(sub))
for ... |
eef2896a9381c7d063dddea9a2ce68eb2cbae7ce | Seremontis/Simple_Projects_in_Python | /python object 2.py | 1,826 | 3.59375 | 4 | class ElementZamowienia:
nazwa=''
cena=0
liczbaSztuk=0
def __init__(self,nazwa='',cena=0.00,liczbaSztuk=0):
self.nazwa=nazwa
self.cena=cena
self.liczbaSztuk=liczbaSztuk
def __str__(self):
return '{} {} zł, {} szt., łącznie {} zł'.format(self.nazwa,self.cena,s... |
70ad3d1fd9df1a88b3ed77a39ade0876b9b0bdb4 | Mantarus/Formal-languages | /Task1/Task1_(not valid).py | 2,102 | 3.578125 | 4 | ADV = "ADV"
WIN = "WIN"
LOSE = "LOSE"
FALSE = "FALSE"
A_WON = "A WON"
B_WON = "B WON"
def main():
string = input("Type input string: ")
result = run_det(string)
if result:
print("Det: Allowed")
else:
print("Det: Not allowed")
result = run_not_det(string)
if result:
pri... |
fc51102adca52b8e0d7f8720fedf8fe6cfde6711 | burbol/LineTensionPackage | /Analyze_trajectories/Results_Module.py | 12,056 | 3.609375 | 4 | #!/usr/bin/python
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from scipy import stats
from fractions import Fraction
import math
#from scipy.optimize import curve_fit
#import os
#from scipy.interpolate import interp1d
#from matplotlib.font_manager import FontProperties
# func is the function... |
51f09029423d648526adc825f507781f84095b5e | glock3/Learning- | /Alexey/Algorithms/OB_125/sorting/bubble_sort.py | 479 | 3.640625 | 4 | from Alexey.Algorithms.OB_125.sorting.time_decorator import timer
def main():
array = []
print(*array)
print(sort(array))
@timer
def sort(array):
try:
for i in range(len(array)-1, 0, -1):
for y in range(i):
if array[y] > array[y + 1]:
array[y],... |
6a22a98c793f49b38fbbd45a4c00f8e07c6d7d5d | adeak/AoC2015 | /day05.py | 946 | 3.578125 | 4 | from collections import Counter
def day05(inps, part2=False):
if part2:
is_nice_fun = is_nice_v2
else:
is_nice_fun = is_nice
return sum(map(is_nice_fun, inps.strip().split('\n')))
def is_nice(word):
counter = Counter(word)
if sum(counter[c] for c in 'aeiou') < 3:
return Fal... |
061a3ec0534e3b8bf24352f61201d927574987a3 | AnonymnyNikto/PythonProgramovanie | /Edupage/Mocnina.py | 159 | 3.734375 | 4 | cislo = input("Zadajte cislo: ")
cislo = int(cislo)
tri = cislo ** 3
sest = cislo ** 6
print("Tretia mocnina je ", tri, " a siesta mocnina je", sest)
|
fd90f1e4accd0f7289e2aef66cdc942cc7d1a439 | evandrofranco/curso_python | /8_desafio_5_fatorial.py | 121 | 3.890625 | 4 |
valor = int(input("Digite o valor de n: "))
aux = 1
while (valor > 1):
aux *= valor
valor -= 1
print(aux)
|
732672dc221400fad4e444cb77a22c64bd4e7636 | PacktPublishing/Mastering-Python-Scripting-for-System-Administrators- | /Chapter03/if_example.py | 150 | 4.15625 | 4 | def check_if():
a = int(input("Enter a number \n"))
if (a == 100):
print("a is equal to 100")
else:
print("a is not equal to 100")
return a
|
bf837a6be53dd91bfe837f5e45e3afa4371e42ae | fstahlberg/ucam-scripts | /gnmt/align2csv.py | 876 | 3.59375 | 4 | '''
This script converts a line from an alignment file to a
csv file
'''
import argparse
import operator
import sys
parser = argparse.ArgumentParser(description='Converts a single line of a alignment '
'text file to csv format.')
args = parser.parse_args()
weights = {}
max_src = 0
max_trg ... |
7e2b2e3b7464bfa2cec6b7844e06d6a8010d7f7f | Yiming-Gao/UIUC-Fall-2017 | /CS_446/Homework/HW3/hw3_p2_sol.py | 3,593 | 3.765625 | 4 | import numpy as np
import matplotlib.pyplot as plt
def rbf_kernel(x1, x2, gamma=100):
"""
RBF Kernel
:type x1: 1D numpy array of features
:type x2: 1D numpy array of features
:type gamma: float bandwidth
:rtype: float
"""
# Student implementation here
diff = x1 - x2
return np.e... |
c48949bf4bcf79b5d7fe97f83dd5e573696c60c9 | Zahidsqldba07/Python2020 | /covid_3.py | 550 | 3.671875 | 4 | #!/bin/python3
class Code():
x = [1, 2, 3, 4, 5]
def __init__(self, unicode, task=None):
self.unicode = unicode
self.task = task
def main(self):
try:
press = int(input("Enter the unicode value [1, 2, 3, 4, 5] :- "))
x = [1, 2, 3, 4, 5]
if press in x:
return "Your code is right."
elif press ... |
dedcebab66c1aae3f28007a1a5e5c8fd27da2a44 | JokerToMe/PythonProject | /shine/object/demo3.py | 645 | 4.15625 | 4 | # 析构函数:__del()__释放对象时自动调用
class Person(object):
def __init__(self,name,age):
self.name = name
self.age = age
def say(self):
print('My name is %s,%d years old' % (self.name,self.age))
print(self.__class__)
# 在内部创建对象
def createInstance(self):
p = self.__class__(... |
afb637fbeca1ec1726c3bfa6bdef6196b604895a | ManasaPola/Coding-Exercise | /Bigram.py | 574 | 3.671875 | 4 | '''Leetcode Contest'''
def main():
text = "alice is a good girl she is a good student"
first = "a"
second = "good"
text1 = "we will we will rock you"
first1 = "we"
second1 = "will"
ans = findOccurences(text1, first1, second1)
print(ans)
def findOccurences(text, first, second):
if l... |
194fff3d21a4e6a97da82301943a61303f699178 | cosmos-sajal/python_design_patterns | /behavioural/strategy_pattern.py | 1,470 | 4.15625 | 4 | ## refernces - https://www.youtube.com/watch?v=MOEsKHqLiBM
from abc import ABCMeta, abstractmethod
class Movement(metaclass=ABCMeta):
@abstractmethod
def move(self):
pass
class Fly(Movement):
def move(self):
print("I will fly")
class Walk(Movement):
def move(self):
print("... |
e9c6dcaf585d7bcc595d08efe42a31657f8e1afe | zyzmoz/python-course | /classes.py | 603 | 3.734375 | 4 | class Dog():
# Class Object Attribute
species = "Mammal"
def __init__(self, breed, name):
self.breed = breed
self.name = name
# pass
mydog = Dog("Pug", "No One")
print(mydog.breed)
print(mydog.name)
print(mydog.species)
# mydog.species = "Troll"
# print(mydog.species)
class Circle():
pi... |
0e9c9ebcc126f1d7c99a8d024ae53d0d78db44b9 | vladimir4919/nu8 | /bank_account.py | 4,601 | 3.8125 | 4 | """
Программа "Банковский счет"
Работа программы:
Запускаем программу.На счету -0
Программа предлагает:
1. пополнить счет
2. оплатить покупку
3. вывести историю покупок
4. выход
Добавлено сохранение суммы счета в файл.
При первом открытии программы на счету 0
После того как мы воспользовались программой и вы... |
43331eb9b79bdf95fd59a81d6b0df758198942b1 | ttafsir/100-days-of-code | /code/day21/event.py | 1,386 | 3.828125 | 4 | """
Bert is in charge of organizing an event and got the attendees names,
locations and confirmations in 3 lists. Assuming he got all data and being
Pythonic he used zip to stitch them together (see template code) but
then he sees the output:
('Tim', 'DE', False)
('Bob', 'ES', True)
('Julian', 'AUS', True)
('Carmen', ... |
e40bf8ee37fc3ba8e23642cf9aaf35bc18208846 | blanksblanks/Python-Fun | /46-Simple-Ex/ex15.py | 475 | 4.40625 | 4 | from ex13 import max_in_list
from ex14 import list_convert
def find_longest_word(alist):
''' (list) -> str -> int
Defines a function find_longest_word() that takes a list of words and returns
the length of the longest one.
'''
alist = list_convert(alist)
alist = max_in_list(alist)
return alist
ourzoo = ['cat',... |
92fe4ce79ae9bfb20802452bd33c8b1672ee9720 | googlelxhgithub/testgit | /pan7.py | 729 | 3.890625 | 4 | # 最小公倍数是小学五年级的数学课程内容,小学生完成最小公倍数的学习后就可以升学到初中了。
# 如何用程序求出任意两个数的最小公倍数?
a = int(input("first: "))
b = int(input("second: "))
# 方法一:先算出最大公约数,在算最小公倍数
# 取最小的那个数
# d = min(a, b)
# for i in range(1, d+1):
# if a % i == 0 and b % i == 0:
# c = i
# print(f"{a} and {b} number1 is {c}")
# print(f"{a} and {b} numbe... |
139f7a86d16c559b8ec5882594b47a71c33fd405 | martin-martin/python-crashcourse | /02_21_thu/string_methods.py | 348 | 4.03125 | 4 | my_string = " hELLo there "
#
# # lowercase
# print(my_string.lower())
#
# # uppercase
# print(my_string.upper())
#
#
# # title-case
# print(my_string.title())
# # capitalize
# print("cap")
# print(my_string.capitalize())
# split
print(my_string.strip(' h').lower())
# print(my_string.lstrip())
# print(my_string.r... |
61d68dfc290133a6ecc916ad3a9aa1044e07d5df | meteozcan06/python | /fonksiyon.py | 912 | 3.578125 | 4 | #dortgen_alan_hesapla_v1
def dikdortgenAlan(genislik, yukseklik):
alan = float(genislik) * float(yukseklik)
print("Alan :", alan)
return alan
gen = input("Genişlik : ")
yuk = input("Yükseklik : ")
dikdortgenAlan(gen, yuk)
#daire_alan_hesapla_v1
def daireAlan(yaricap):
alan = float(yari... |
279fb47627241a877bac389f22ebc4768846eac1 | 824zzy/Leetcode | /N_Queue/MonotonicQueue/L1_239_Sliding_Window_Maximum.py | 920 | 3.546875 | 4 | """ https://leetcode.com/problems/sliding-window-maximum/
define a monotonic queue state as (idx, val) and we want to ensure
1. current index is within the window size
2. val is in descending order
"""
from header import *
# heap implementation
class Solution:
def maxSlidingWindow(self, A: List[int], k: int) -> Li... |
d7671875f0293be608d20f559643718fb08cd90d | ovifrisch/Python-Data-Structures | /lists/stack.py | 863 | 3.875 | 4 |
class Stack:
class Node:
def __init__(self, val, next):
self.val = val
self.next = next
def __iadd__(self, i):
curr = self
while (i > 0):
i -= 1
curr = curr.next
return curr
def __init__(self):
self.size = 0
self.head = None
def push(self, val):
self.head = self.Node(val, self.... |
1f2b70fac927a8f1a86a47178e6d47f1c70af49b | YaraDeOliveira/CursoemVideo | /ex065.py | 466 | 3.890625 | 4 | n = 'S'
x = soma = maior = menor = z = 0
while n in 'Ss':
x = int(input('Digite um numero:'))
soma += x
z += 1
if z == 1:
menor = maior = x
if x > maior:
maior = x
if x < menor:
menor = x
n = str(input('Quer continuar [S/N]')).upper().strip()
print('Foram digitados {}... |
2825fd6c3ce67deee019741661c8c20013c87f99 | jeromehayesjr/University | /512/test.py | 184 | 3.796875 | 4 | def even_nums(lst):
# return [x for x in lst if x % 2 == 0]
evens = []
for x in lst:
if type(x) == int and x % 2 == 0:
evens.append(x)
return evens
|
ab5b4ba85b5db3bbbd9dbf1f1fd0faf98096bf4f | suomela/recoloring | /check-tiles.py | 2,283 | 3.578125 | 4 | #!/usr/bin/env python3
import itertools
colours = [1, 2, 3, 4]
def good_tile(x):
a,b,c,\
d,e,f,\
g,h,i = x
return a != b != c and \
d != e != f and \
g != h != i and \
a != d != g and \
b != e != h and \
c != f != i
def parts(x):
a,b,c,\
... |
e56a702080c5bd6c9c174dcd287517576252d7b9 | samims/nptel_python | /week_2/slice.py | 179 | 4.15625 | 4 | a = " hello"
print(a[:]) #will print whole string
print(a[:3]) #will print upto 3rd index
a = a[0:3] +"p!" #creating a new value not modifying it, strings are immutable
print(a)
|
07921bd311c8352637e31e346e5757f655a424f5 | mmann964/exercises | /Exercise18.py | 1,936 | 3.78125 | 4 | #!/usr/bin/python
import random
def generate_number():
#num_str = ""
c = range(0, 10)
n = random.sample(c, 4) # a list of 4 unique numbers between 0 and 9
return n
def get_user_number():
# get a four digit number from the user.
# check that it's 4 digits -- length + 0-9
# give them a cha... |
5fd940cb3e0df6c0d9424f6dde21a5ce41dcc0f3 | hguochen/code | /python/questions/ctci/linked_lists/return_kth_to_last.py | 2,735 | 3.984375 | 4 | """
CtCi
2.2 Implement an algorithm to find the kth to last element of a singly linked list.
0 to last -> last element
1 to last -> last second element
2 to last -> last third element
"""
def kth_to_last(head, k):
"""
Time: O(n)
Space: O(1)
where n is the size of the linked list.
Make a first pas... |
dd80aefccbd3840a45ebd62cefc90762106f5f6e | Ljfernando/MovieRecommendation | /MovieRecommendation.py | 14,147 | 4.46875 | 4 | __author__ = 'lancefernando'
"""This Movie Recommendation program utilizes collaborative filtering to recommend movies the user may enjoy.
Data used is original data from MovieLens. It will ask a user to rate 50 random movies on a scale
from 0 to 5 where the 0 value means that the user has not seen the movie. The r... |
c2a06c744c6fcbad972670100e8aebfb1837a78b | furkan-kanuga/Multithreaded_Chat_Python | /server_ipv6.py | 3,004 | 3.953125 | 4 | # Chat server where multiple clients can connect to the server.
#The server reads the message sent by each lient and broadcasts it to all other connected clients.
import socket
import select
#list of socket descriptors (readable client connections)
#Socket descriptors are like file descriptors, in this case used for... |
c3063f76ba5bf1f9b7370f063df13d8de996c1b2 | ansrivas/pyswitcheo | /pyswitcheo/datatypes/fixed8.py | 1,451 | 3.515625 | 4 | # !/usr/bin/env python
# -*- coding: utf-8 -*-
"""Implementation for custom datatypes to interact with the blockchain."""
from decimal import Decimal
from pyswitcheo.crypto_utils import reverse_hex
import logging
logger = logging.getLogger(__name__)
class Fixed8(object):
"""Fixed point representation of a given... |
6159179b88c97cce7471756aff9e939fc2697377 | dfridman1/coursera-data-structures-and-algorithms-specialization | /algorithmic-toolbox/assignments/week4/sorting/sorting.py | 1,207 | 3.703125 | 4 | # Uses python2
import numpy as np
DEBUG = False
def quicksort(xs):
def sort(p, r):
if p < r:
q1, q2 = partition(xs, p, r)
sort(p, q1-1)
sort(q2+1, r)
sort(0, len(xs)-1)
def partition(xs, p, r):
pivot_idx = np.random.randint(p, r+1)
pivot = xs[pivot_idx]... |
e6da329cede060ca836cd6529f3e649304060a4c | Kaitensatsuma/BAN690 | /pdf_export.py | 391 | 3.53125 | 4 | import PyPDF2
print("What PDF do you want to scrape text from?")
pdf_file = PyPDF2.PdfFileReader(open(str(input()), 'rb'))
print("And where do you want to write to?")
text_file = str(input())
container = ''
iterations = range(pdf_file.numPages)
with open(text_file,'w') as file:
for x in iterations:
contai... |
e0e1c8003a6a22bdfcc3be5880d309cff19ac492 | yuyeh1212/University | /python/16.py | 692 | 3.796875 | 4 | # 擲骰子6000次並記錄點數出現次數
import random
def main():
one = 0
two = 0
three = 0
four = 0
five = 0
six = 0
for i in range(6000):
number = random.randint(1, 6)
if number == 6:
one += 1
elif number == 5:
two += 1
elif number == 4:
t... |
a1b6aa392a2513b82faef555a5c24b837d4f7380 | nazhimkalam/Data-Science-Course | /Pandas/Series.py | 2,313 | 4 | 4 | # Series
# Series() is a function of pandas class or module
import numpy as np
import pandas as pd
label = ['a','b','c'] # list
my_data = [10, 20, 30] # list
arr = np.array(my_data) # NumPy array
d = {'a':10, 'b':20, 'c':30} # Dictionary
# Series will return the data with index
# Syntax Series... |
83281d0bd1b6fdf6e338c5412ff728ec17a80cd5 | andrefcordeiro/Aprendendo-Python | /Uri/strings/1234.py | 1,431 | 3.734375 | 4 | # Sentença dançante
while True:
try:
str = input()
strDancante = []
antIsUp = -1 #anterior está em maiusculo
for i in range(0, len(str)):
charCode = ord(str[i])
if charCode == 32: #espaco em branco
strDancante.append(str[i])
else... |
93a63b34264cc28e6f3d5a72bdcbc6106a4dc41c | frankieliu/problems | /leetcode/python/1121/1121.divide-array-into-increasing-sequences.py | 1,146 | 3.6875 | 4 | #
# @lc app=leetcode id=1121 lang=python
#
# [1121] Divide Array Into Increasing Sequences
#
# https://leetcode.com/problems/divide-array-into-increasing-sequences/description/
#
# algorithms
# Hard (52.57%)
# Total Accepted: 1.4K
# Total Submissions: 2.6K
# Testcase Example: '[1,2,2,3,3,4,4]\n3'
#
# Given a non-de... |
cb73aa75586f0d2a9f0c673152838603ec407c6e | Jordaness/DataStructures | /Stack.py | 975 | 4.15625 | 4 | # Class Representation of a Stack
class Stack:
def __init__(self):
self.collection = list()
self.count = 0
def push(self, element):
"""Adds a element to the top of the Stack"""
self.collection.append(element)
self.count += 1
return self
def pop(self):
... |
6fcc50d7964660ae6ee54f25908c19ce127c8dd4 | MountTan/aa | /字典,列表操作一.py | 377 | 3.734375 | 4 | a = {'a': 1, 'b': 2}
b = {'c': 3, 'd': 4}
c = {**a, **b}
print(c)
d = a.copy()
d.update(b)
print(d) # {'a': 1, 'b': 2, 'c': 3, 'd': 4}
f = [1, 2]
g = [3, 4]
h = f + g
print(h) # [1, 2, 3, 4]
i = ['a', 'b', 'c']
j = [1, 2]
k = [1, 2, 3]
l = [item * 2 for item in k]
print(l) # [2, 4, 6]
m = ['a', 'b', 'c']
n = [1,... |
50ae2f6e6febacea9aa58e89702de41dfb0f6b1d | CosmicTomato/ProjectEuler | /eul119.py | 1,174 | 4.09375 | 4 | #Digit power sum
#The number 512 is interesting because it is equal to the sum of its digits raised to some power: 5 + 1 + 2 = 8, and 8^3 = 512. Another example of a number with this property is 614656 = 28^4.
#We shall define an to be the nth term of this sequence and insist that a number must contain at least two d... |
0ddd032fba2bc09e2f749a4a4c8d1e116c654b05 | BiswasAngkan/BasicPython | /Conditional_Statement.py | 349 | 4.0625 | 4 | # Angkan Biswas
# 23.05.2020
# To use if_else statement
'''1st case'''
x = input('Insert a Number: ')
x = int(x)
if x < 5:
print('Welcome')
if x < 5:
print('Welcome')
else:
print('Please Go Back!!!')
'''2nd case'''
for i in range(20):
if i < 5:
print(0)
else:
print(5)
'''3rd case'''
x = range(20)
y = [0 i... |
6e2cf37b510e9b6bb1f60e831b55dd719f1fe828 | Abdul89-dev/Victor | /types.py | 1,124 | 3.984375 | 4 | #a = 2
#sum = 2.5
#b = sum - a
#print(a + b)
# name = input ("input your name" )
# print('Hello'+ name)
#v = int(input("Введите число от 1 до 10"))
#print(v)
#s = int(input("Введите число от 1 до 10"))
#print(s + 10)
#name = input("Enter your name")
#print(name)
#print (float ('1'))
#print(int("2.5"))
#print... |
c8d592100685b5acc60be43bc74499c9c8550f56 | gabrieleliasdev/python-mentoring | /ex20.py | 837 | 3.5625 | 4 | from sys import argv
script, input_file = argv
# Aguardo receber (02) parametros: script: python3 e input_file: Caminho do Arquivo
def imprime_tudo(f):
print(f.read())
def rebobinar(f):
f.seek(0)
# seek (0): vai mover o cursor para o inicio do arquivo.
def imprima_uma_linha(numero_linha, f):
print(numer... |
e4bd12dbb59d30d9141e65807e23f82863ff451c | fangpings/Leetcode | /143 Reorder List/untitled.py | 930 | 3.796875 | 4 | class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def reorderList(self, head):
if not head:
return
cur = head
storage = []
while cur:
storage.append(cur)
cur = cur.next
... |
826c3b13612f83d2fe0dbfaabcf030786f573ea5 | chrisx8/Ballzzz | /gameModules/ball.py | 4,398 | 3.765625 | 4 | import math
class Ball(object):
def __init__(self, color, startX, canvasHeight, canvasMargin):
# user-defined color in customization
self.color = color
# radius is always 5px
self.radius = 5
# balls start at where the last ball landed, at the bottom of canvas
self.c... |
1ae23ef969c5e2ef9896a295f4d05b87a5d33169 | HGNJIT/statsCalculator | /MathOperations/multiplication.py | 416 | 3.578125 | 4 | class Multiplication:
@staticmethod
def product(multiplier,multiplicand=None):
if (isinstance(multiplier,list)):
return Multiplication.productList(multiplier)
return multiplier * multiplicand
@staticmethod
def productList (valueList):
result = 1
for element ... |
134c3e138b63d260e7bc5b21e102c04e34552247 | LiuXPeng/leetcode | /59.py | 812 | 3.5 | 4 | class Solution:
def generateMatrix(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
number = 1
res = [[None for col in range(n)] for row in range(n)]
#每次写数,都把一行/列写满
for k in range(n):
#上
for i in range(k, n - k):
... |
ae5e53c534c73929158e88aa10d9ef6cf979c14e | 19goux/python-eval | /adv_partie-II.py | 496 | 3.5625 | 4 | from codec import TreeBuilder, Codec
text = "a dead dad ceded a bad babe a beaded abaca bed"
builder = TreeBuilder(text)
binary_tree = builder.tree()
# on passe l'arbre binaire à un encodeur/décodeur
codec = Codec(binary_tree)
# qui permet d'encoder
encoded = codec.encode(text)
# et de décoder
decoded = codec.decod... |
3a53af0caf0a603c5e733ea2c80337e35fa0da0f | Tperm-coder/python-codes | /series and parallel calculations.py | 1,600 | 3.734375 | 4 | import os
os.system('color b')
os.system('cls')
# TOC stands for type of connection
pap = True
while pap :
os.system('color a')
os.system('cls')
TOC = input('series or parallel ?')
if TOC == 'series' :
NOR = int(input('what are the number of resistors ?'))
# NOR stands for number of resisto... |
9feba435621932846974b4de7e8cea0a2a166c51 | CoderFemi/AlgorithmsDataStructures | /practice_challenges/python/quick_sort.py | 437 | 4.15625 | 4 | def quickSort(arr) -> list:
"""Implement quicksort"""
pivot = arr[0]
left = []
equal = [pivot]
right = []
for index in range(1, len(arr)):
num = arr[index]
if num < pivot:
left.append(num)
elif num == pivot:
equal.append(num)
else:
... |
dbca8c76f97ddfbe815d0a73ac15eecaf0fdef82 | niharikasaraswat/python | /pos_neg.py | 197 | 3.984375 | 4 | # enter series range
list1 = [20, -60, 80, 50, -10]
for num in list1:
if num > 1:
print('positive numbers in list', num)
else:
print('negative numbers in list', num)
|
656870d4ba887cfd702750093ddb916cbc97eb9c | AnumHassan/Class-Work | /Table.py | 95 | 3.5 | 4 | able = int(input("Enter a No:" ))
for i in range(1,11):
print(able, "x",i,"=",str(able*i)) |
0ae7f4d79704b12eb64f7643d1b730d231814204 | fernandorunte/SHSU_Assingnments | /Python/Chapter3/chap3_2.py | 530 | 4.0625 | 4 | ##areas of rectangles
length1=int(input('enter lenght of the first rectangle: '))
width1=int(input('enter the width of the first rectangle: '))
length2=int(input('enter lenght of the second rectangle: '))
width2=int(input('enter the width of the second rectangle: '))
area1= length1*width1
area2= length2*width... |
40047e93afa0f6cdd8fe2480d006dc0840706a70 | IKNL/vertigo | /scripts/auxiliaries.py | 2,048 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
auxiliaries.py
Auxiliary functions.
Created on Mon Mar 18 09:55:09 2019
@author: Arturo Moncada-Torres
arturomoncadatorres@gmail.com
"""
#%% Preliminaries
import pandas as pd
from sklearn.utils import resample
#%%
def downsample(X, y, random_state=None):
"""
Perform class balanc... |
bc733bd3e55880d3b50b8a93540ebf6fa13d886c | developr4u/learning-coding | /python_course/chp_threeEx4.py | 186 | 3.890625 | 4 | user_input = input("Enter a number: ")
i = 0
total = 0
length = len(user_input)
while length > 0:
total = int(user_input[i]) + total
length -= 1
i += 1
print(total)
|
fdb58606849c43e42a4cb9f5a7e8264794f7a761 | aakashdinkar/Hackerrank-Series | /CaeserCipher.py | 730 | 3.640625 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the caesarCipher function below.
def caesarCipher(s, k):
st = ""
for item in s:
if item.isalpha():
print(ord(item)+k)
if item.isupper():
a = 'A'
st += chr(ord(a) +... |
a75526c85c9ab5561dbcc1b63814fa5e22378915 | kshulgina/codetta | /helper_functions.py | 13,539 | 3.53125 | 4 | import os
import sys
from subprocess import call, Popen, PIPE
import re
import numpy as np
from ftplib import FTP
import datetime
def translate(sequence, gct):
"""
For a DNA sequence, translate it into a sequence of one symbol per codon, following
a specific translation table. For example, this could be t... |
10166a92e26316e1182a17528bfa73e88f4364e4 | eloghin/Python-courses | /LeetCode/contains_duplicate.py | 703 | 4.1875 | 4 | # Given an array of integers that is already sorted in ascending order, find two numbers such that
# they add up to a specific target number.
# Given an array of integers, find if the array contains any duplicates.
# Your function should return true if any value appears at least twice in
# the array, and it should ... |
d3dda9a06c0a019523e27239420bb5a5df18de03 | sourabbanka22/Competitive-Programming-Foundation | /HackerEarth/Math/Number Theory/Basic Number Theory-2/isPrime.py | 204 | 3.890625 | 4 | def isPrime(number):
if number<2:
return False
idx = 2
while idx*idx <= number:
if number%idx == 0:
return False
idx += 1
return True
print(isPrime(1)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.