blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
85421053a1959d94b42c124a94ef17cc22205758 | mikeyPower/image-steganography | /steganography.py | 4,811 | 3.890625 | 4 | import cv2
import numpy as np
# Public Variables
delimeter = "####"
def message_to_binary(message):
if type(message) == str:
return ''.join([ format(ord(i), "08b") for i in message ])
elif type(message) == bytes or type(message) == np.ndarray:
return [format(i, "08b") for i in message ]
elif type(message) == ... |
f3cbd01fce25184510b4a6db926dbf09b05dfce0 | fengjijiao/python-code | /条件语句.py | 421 | 4.125 | 4 | #! /usr/bin/env python
#coding:utf-8
print("请输入任意一个整数:")
number = int(input())
if number==10:
print("您输入的数字是:{}".format(number))
print("You are Smart.")
elif number>10:
print("您输入的数字是:{}".format(number))
print("This number is more than 10.")
else:
print("您输入的数字是:{}".format(number))
... |
688c98a0340572e91c03af0c301f0adb835cf5a2 | JackInTaiwan/2017-ntu-course-alg | /b04901081_hw2/p1.py | 487 | 3.546875 | 4 | def smallestDigits(num) :
output = ''
for i in range(9,1,-1) :
while num % i == 0 :
output = str(i) + output
num /= i
if len(output) == 0 : return '11'
elif len(output) == 1 : return '1' + output
else : return output
if __name__ == '__main__' :
caseNum = int(in... |
e666797f0d83d7e7e61337fb54947cf636b24131 | ddarkclay/programming-cookbook | /Harry_Python/file_operations/Abstract_method.py | 356 | 3.90625 | 4 | from abc import ABC,abstractmethod
class Shape(ABC):
@abstractmethod
def printarea(self):
return 0
class Rectangle(Shape):
type = "Rectangle"
def __init__(self):
self.length = 6
self.breadth = 7
def printarea(self):
return self.length * self.breadth
rect =... |
afe08738c2b84d61d52cadd927632a5669d1d2b7 | xothkug/learning-python | /01_datatypes/lists.py | 640 | 3.71875 | 4 | games = ['Minecraft', 'Age Of Empires', 'Terraria', 'Agario']
colors = ['red', 'green', 'blue', 'yellow']
numbers = [10, 20, 50]
print(games[0])
print(games[-1])
print(games[0:3])
print(games + colors)
print(games[1:2] + colors[2:3]) # list + list
print(games[1] + colors[2]) # string + string
colors.append('black')... |
c12cc1a8b32093653cac52a262a8993a563dad66 | ChihYunPai/Data-Structure-and-Algorithms | /Leetcode_Algorithm/Python3/287_Find_the_Duplicate_Number.py | 1,340 | 3.921875 | 4 | """
Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.
Note:
You must not modify the array (assume the array is read only).
You must use only consta... |
349d25e17e2c51c52c324213f0791bfe22b7a7ce | ManuBedoya/holbertonschool-higher_level_programming | /0x01-python-if_else_loops_functions/1-last_digit.py | 540 | 3.90625 | 4 | #!/usr/bin/python3
import random
number = random.randint(-10000, 10000)
if (number < 0):
lDigit = (number * -1) % 10
lDigit *= -1
else:
lDigit = number % 10
if (lDigit > 5):
print("Last digit of {:d} is {:d} and is greater than 5".format(number,
... |
36ccce735c46e3d2ffe3b04692cfe142c81437b5 | akhandsingh17/assignments | /topics/Graphs/NumberIslands.py | 1,754 | 3.890625 | 4 | """
Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands.
An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically.
You may assume all four edges of the grid are all surrounded by water.
Example 1:
Input:... |
61987b613094b1c51f698c92ad13b8d913a9a376 | codxse/mitx6001 | /2016/PSET_1/ps1-2.py | 116 | 3.75 | 4 | c = 0
for i in range(len(s)):
if(s[i:i+3] == 'bob'):
c += 1
print('Number of times bob occurs is:', c)
|
fcbb4d738d62c7e376322ae42d255088d4c712aa | radavis47/automate_python | /Programs/collatzSequence.py | 594 | 4.3125 | 4 | def collatz(number):
if number % 2 == 0:
print(number//2)
return number // 2
elif number % 2 == 1:
print(3*+number+1)
return 3 * number + 1
r=''
print('Enter the number')
while r != int:
try:
r=input()
while r != 1:
r=collatz(int(r))
break ... |
28b07eaf550b43d37209562a599cc4ea8894ad01 | alu-rwa-dsa/week-3---dynamic-array-bello_brenda_abideen_catherine_cohort2 | /DSA_Wk3_Q4.py | 985 | 3.84375 | 4 | #Author : Brenda
a_list = dict()
class asso_list:
def __init__(self):
print("Welcome")
def add(self, name, age, major, country):
a_list["name"] = name
a_list["age"] = age
a_list["major"] = major
a_list["country"] = country
return a_list
def a_remove(self,... |
4f88de6c65e7ad5ea89f30fac0ed1606d652f72f | ywzhang188/spark-learn | /spark_dataframe/create_dataframe.py | 2,359 | 3.5 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# __author__='yzhang'
from getting_started.spark_session import *
# By using parallelize( ) function
ds = spark.sparkContext.parallelize([(1, 2, 3, 'a b c'),
(4, 5, 6, 'd e f'),
(7, 8, 9, 'g h i')])... |
2d133c96cf22e35dca21b40fb3217059eeb24d1f | kobechenhao/1807 | /07day/08-老王.py | 232 | 3.859375 | 4 | name = input("请输入一个名字")
money = float(input("请输入金钱"))
if name == "老王" and money > 1000:
print("砖石王老五")
elif name == "老王" and money < 500:
print("穷逼")
else:
print("小康")
|
64506a522a812b220d9d9a6a4693a3e7880b83bb | RafayAK/Softmax_Neural_Network | /source.py | 1,840 | 3.65625 | 4 | import numpy as np
import matplotlib.pyplot as plt
from utilities import *
import SoftmaxLayer
import LinearLayer
np.set_printoptions(precision=3, suppress=True)
X, y, colormap = loadData() # X->(20,2) ; y->(20,)
plt.figure(1)
plot_scatter(X, y, colormap)
# one hot encoded matrix
Y = one_hot_encode(y, num_classes... |
d41f55badbd597c87784833ba690fbe4555b1c66 | spiderjako/Python-101 | /week4_5/oop/music.py | 2,044 | 3.59375 | 4 | class Song:
def __init__(self, title, artist, album, length):
self.title = title
self.artist = artist
self.album = album
self.length= length
def __str__(self):
return '{0} - {1} from {2} - {3}'.format(self.title, self.artist, self.album, self.length)
def __repr__(self... |
2e64792594e933bbdc29a76eb7bbe5ccd5451995 | meyertovar/TraductorPython | /TraductorAudio.py | 1,682 | 3.546875 | 4 | import speech_recognition as sr
import webbrowser as wb
# creamos una instancia de la clase Recognizer
r = sr.Recognizer()
r1 = sr.Recognizer()
r2 = sr.Recognizer()
# usamos la clase Microphone para capturar el audio
with sr.Microphone() as source:
print('Por favor di algo : ')
# el audio sera capturado con e... |
3307bbefffe0bd7a29a4cb093033994495256838 | ash/amazing_python3 | /045-while-else.py | 124 | 3.984375 | 4 | # The "else" clause can be
# used together with "while"
x = 0
while x < 5:
print(x)
x += 1
else:
print('done')
|
9de29abcf63a46fa6de5aa2adc3e0d6d2e1ee8ea | CarolineXiao/AlgorithmPractice | /RainbowSort.py | 1,027 | 3.5 | 4 | class Solution:
"""
@param colors: A list of integer
@param k: An integer
@return: nothing
"""
def sortColors2(self, colors, k):
if colors == []:
return []
return self.rainbowSort(colors, 0, len(colors) - 1, 1, k)
def rainbowSort(self, colors, left, ... |
a83329f57e9f73f08cfe82aae2e09fcb12d080b0 | qizongjun/Algorithms-1 | /Leetcode/Bit Manipulation/#137-Single Number II/main.py | 1,452 | 3.75 | 4 | # coding=utf-8
'''
Given an array of integers, every element appears three times
except for one, which appears exactly once. Find that single one.
Note:
Your algorithm should have a linear runtime complexity.
Could you implement it without using extra memory?
'''
'''
此种方法极易理解,而且有很强的普适性,只要题干要求是一个数组所有数
都出现K次除了一个数只出现一... |
42758414411043ffc62e50ade773ddad10370df2 | staskur/infa_2020 | /lektors/lab1-6.py | 193 | 4.03125 | 4 | import turtle
turtle.shape('turtle')
# звезда
n=12
r=100
for i in range(0,n,1):
turtle.forward(r)
turtle.stamp()
turtle.backward(r)
turtle.left((360/n)*1)
a=int(input()) |
90b833207725fcbfe277c50be9add6f8a9290c21 | rafaelperazzo/programacao-web | /moodledata/vpl_data/131/usersdata/232/37584/submittedfiles/al10.py | 235 | 3.984375 | 4 | # -*- coding: utf-8 -*-
#NÃO APAGUE A LINHA ACIMA. COMECE ABAIXO DESTA LINHA
n=int(input('Digite o número de termos a ser calculado: '))
i=2
pi=1
for i in range (1,n+1,1):
pi=pi*(i/(i-1))*(i/(i+1))
pi=pi*2
print(pi)
|
c57abad271fee36884c96691f04a989634a05f99 | hccarlos/codeWarsAlgorithms | /valid_parens.py | 1,129 | 4.375 | 4 | # Write a function called validParentheses that takes a string of parentheses,
# and determines if the order of the parentheses is valid.
# validParentheses should return true if the string is valid, and false if it's invalid.
#
# Examples:
# validParentheses( "()" ) => returns true
# validParentheses( ")(()))" ) => re... |
66b8a74ef2781682dc9fcd6af3fadb08da9c3ed3 | Alexno1no2/algorithm-python | /第二章/2-5.py | 811 | 4.3125 | 4 | ListValue = [1, 5, 6, 2, 7, 3] #第一种模拟双链表的方法
ListRight = [3, 2, 4, 5, -1, 1] #分别使用三个数组来存储数值、
ListLeft = [-1, 5, 1, 0, 2, 3] #指向上一个元素和下一个元素的指针
head = ListLeft.index(-1) #头指针的值为-1在ListLeft中的位置
print(ListValue[head])
Next = ListRight[head]
while Next > -1:
print(ListValue[Next])
Next = ListRight[Next]
print() ... |
88e21c8e171edd2f012204b30fa4391de3753220 | Mekenwaka1/reinforcement_exercises_datatypes_variables_conditionals | /exercise2.py | 1,074 | 4.03125 | 4 | documentary = "Apollo 11"
drama = "Gulliver's Travels"
comedy = "Diary of a Wimpy Kid"
dramedy = "Boston Legal"
book = "The Pillars of the Earth"
print("rate your appreciation for documentaries on a scale from 1 to 5")
rating1 = int(input())
if rating1 >= 4 and rating1 <= 5:
print(documentary + " is recommended"... |
a554e660e1f753b54f81d5e76c170feb9b937ce2 | vshyshkin/pwr | /semester-5/scripting-langs/lab6/task1.py | 589 | 3.90625 | 4 | # Levenshtein distance
def calc_lev_dist(a, b):
def lev_dist(i, j):
if min(i, j) == 0:
return max(i, j)
return min(
lev_dist(i - 1, j) + 1,
lev_dist(i, j - 1) + 1,
lev_dist(i - 1, j - 1) + (0 if a[i - 1] == b[j - 1] else 1)
)
return lev_... |
bb0d42f25677e39c766685d88037797341f98497 | Lazizkhan1/Foundation | /N/N14.py | 119 | 3.59375 | 4 | sentence = input("Sentence kiriting: ")
for i in range(len(sentence)):
if i % 2 == 1:
print(sentence[i])
|
3356b9ee3c531d751dd772c18bcc234d2e5bc721 | Wes90/Python-Challenge | /Pypoll/main.py | 2,006 | 3.609375 | 4 | import os
import csv
#open csv path
with open('Resources/election_data.csv', newline= '') as file:
csv_reader=csv.reader(file, delimiter=',')
header=next(csv_reader)
#create variables
candidate_list = []
total_votes = 0
#create for loop and count votes
for row in csv_reader:
... |
f6edf045bf6d9b6585e740c4104eb6b65d74daed | ashokkalbhor/PythonTelusko | /Python_Selection_Sort.py | 335 | 3.625 | 4 | def sort(list):
for i in range(len(list)-1):
minpos=i
for j in range(i,len(list)):
if list[j]<list[minpos]:
minpos=j
temp=list[i]
list[i]=list[minpos]
list[minpos]=temp
print(list)
list = [999,101, 9920, 303, 40, 50,.05, 556, 6000, 70, 802, 99,... |
82008509a91f633c44caaa7ff02f1cda9093e0a3 | shi0524/algorithmbasic2020_python | /Python2/class17/Code02_Hanoi.py | 2,860 | 4.28125 | 4 | # -*- coding: utf-8 –*-
def hanoi1(n):
left_to_right(n)
def left_to_right(n):
""" 把1~N层圆盘 从左 -> 右
"""
if n == 1:
print('Move 1 from left to right')
return
else:
left_to_mid(n - 1)
print("Move {} from left to right".format(n))
mid_to_right(n - 1)
def left_... |
f3eea89111341b749f0ff2ad7d8d6f5ea32874d9 | todayido/ipython | /test000/__test__if__else.py | 179 | 3.8125 | 4 | sex = raw_input("input ur gender")
if sex == "girl":
print ("I want to have a birth to u")
elif sex == "boy":
print ("Going to homesexual...")
else:
print ("Pervert")
|
189aa70b64a70ddf5dc78f931cbfcac925b0112f | MarkGhebrial/Encrypt-o-matic-5000 | /encryptomatic.py | 2,098 | 4.125 | 4 | from alphabet import alphabet, tebahpla
class EncryptOMatic:
def __init__ (self, key: str):
self.key = key.lower()
# Create a sequence of three characters to use instead of spaces
if self.key != "space":
self.spaceSequence = EncryptOMatic("space").encryptString(key)[:3]
else:
self.spaceS... |
cd84f92c7f84ea090b2b8c1975d5c3b5e861aaef | MadhubanKhatri/Age-Calculator-App | /AgeCalculatorApp.py | 807 | 3.875 | 4 | from tkinter import *
from datetime import date
root = Tk()
root.geometry("400x400")
root.title("Age Calculator")
def cal():
try:
year = date.today().year
year_val = int(year_entry.get())
if year_val>year:
lbl1["text"] = "Your year is not valid"
else:
... |
4cf422bccc65aac537f1797cd61c31c60eb71b54 | hide-hub/PythonTest | /fer/utils_fer.py | 3,788 | 3.875 | 4 | # python functions for the project, Facial Expression Recognition.
# following functions are aimed to use that project (especially read_dataset).
import csv
import numpy as np
import pandas as pd
import cupy as cp
from matplotlib import pyplot as plt
from numpy import matlib as mlib
#########################... |
84914559e792679cdd91162c92b415141b543230 | k-kushal07/Algo-Daily | /Day 15 - Dollar Deletion.py | 473 | 3.890625 | 4 | def dollarDelete(string):
st = []
for i in string:
if i=='$' :
st.pop()
continue
st.append(i)
return ''.join(st)
def compare(str1, str2):
if(dollarDelete(str1) == dollarDelete(str2)):
print('The strings are same after deletion of Dollar sign')
el... |
71c062ef41e12981da45be8053b472bebe598d79 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/hamming/58cb4438ece2457f85b13bd51a426b82.py | 504 | 3.90625 | 4 | """This module implements a simple Hamming distance calculator
for measuring the number of point mutations between two DNA base
strings."""
def distance(s1, s2):
"""Returns the Hamming distance between two strings.
Will return -1 if strings are not of the same length."""
if len(s1) != len(s2):
... |
87879c7c63fa1b1218feed3b611d9ef68630b29b | BorisovDm/SBT_Autumn_2017 | /Python/lectures/6_scripts/lesson1/example2_good_step1.py | 889 | 3.53125 | 4 | #coding=utf-8
# импортируем специальную библиотеку
import pandas
# теперь мы можем считать файл одной строчкой
df = pandas.read_csv('sells2.csv')
# Вопрос на засыпку. Чем такой способ хуже предыдущего?
# Ответ: тем, что теперь мы весь файл считываем в память, а раньше по одной строчке читали
# Но распарсить каждое ... |
27bb36a3c008adfc376a355944ccaca2f6cdd65f | VladGavra98/SVV_SA_sim | /integration.py | 3,055 | 3.640625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Feb 17 14:32:04 2020
Integration function
@author: Luis, dannywhuang
@version: 21-02
"""
import numpy as np
import scipy.integrate
import matplotlib.pyplot as plt
def f(x):
return x*x
def integration(function,a,b,n):
"""Input: f,a,b, n
Output: wights"""
... |
3f623070b3bf97c0a11bc599107a565158d113e0 | soyal/python-cookbook-note | /chapter1/1-6.py | 195 | 4.0625 | 4 | # 字典中的键映射多个值
from collections import defaultdict
# defaultdict可以给dict每个key指定默认值
arr = defaultdict(list)
arr['a'].append(1)
arr['b'].append(2)
print(arr) |
bb93e99e1330d2d6406c1962616b6a20e05e79d9 | daniel-reich/turbo-robot | /CzrTZKEdfHTvhRphg_15.py | 1,945 | 4.65625 | 5 | """
Create a function that takes a string representing a fraction, and return a
string representing that input as a mixed number.
* Mixed numbers are of the form `1 2/3` — note the space between the whole number portion and the fraction portion.
* Resulting fractions should be fully reduced (see example #2).
... |
a2dc5050a4dcf78926a57b17d6cac71eaafc543e | RobertoAffonso/Python-Course | /IntroToLists/lists2.py | 355 | 4.21875 | 4 | list_1 = []
list_2 = list()
even = [2, 4, 6, 8]
odd = [1, 3, 5, 7, 9]
numbers = [even, odd] # This creates a list containing two other lists
print(numbers) # This prints out the numbers variable which contains a list of the two lists `even` and `odd`
for number_set in numbers:
print(number_set)
for value i... |
de7e69ce877151cb5545632d32dc0820b87e3680 | sukhwanipawan/Factorial-Sum-of-first-n-naturals | /Sum_&_Fact.py | 626 | 3.953125 | 4 | from time import *
def sum(A):
add = 0
if A == 1:
return 1
else:
add = A + sum(A-1)
return add
def factorial(A):
fact = 0
if A == 1:
return 1
else:
fact = A * factorial(A-1)
return fact
inp = int(input('Enter a positive number to find sum and fac... |
d296399955b77f43a8cc564d9b13f57cd1e6622f | joedeller/pymine | /drawmessageV2.py | 5,133 | 3.984375 | 4 | #! /usr/bin/python
# Joe Deller 2014
# Draw messages in minecraft blocks version 2
# Level : Intermediate
# Uses : Libraries, variables, dictionary, operators, loops, logic
# This is is exactly the same idea as version 1, except that
# the message is drawn flat on the floor, rather than vertically
import mcpi.mine... |
f7265af9d36c0f35fa30512c6b2f381f7b56be53 | HuipengXu/leetcode | /generateParenthesis.py | 1,051 | 3.609375 | 4 | # @Time : 2019/5/26 8:27
# @Author : Xu Huipeng
# @Blog : https://brycexxx.github.io/
from typing import List
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
res = {''}
for i in range(n):
tmp = set()
for p in res:
for j in range(0... |
3c51d6914decf7d861ca0ee6ee366912ebdf9b7d | bogdan-stv/2PEP21 | /C03_collections/app_2.py | 1,433 | 4.25 | 4 | """We need a class for an object that will keep track of products in a virtual supermarket for a game that has a
limited number of separated shelves. Processing needs to be done quickly.
- new product s will be listed first
- once a product has been sold out wit will not longer be displayed
- when there is n... |
54f5aac900cc843fdf1112aa6b14737b2f28e434 | JoeyBaileyK/myFirstRepo | /cheat.py | 1,532 | 3.96875 | 4 | #addition+
num1 = 1
num2 = 2
sum = (num1) + (num2)
#subtraction-
#multiplication*
#division/
#rounding division//
def some_Function():
print("this that")
print("and something")
some_Function()
name="jim"
def returnGreeting(name):
greeting = "hello, " + name
return greeting
print(returnGreeting("bo... |
0921aa2eb08d2c191c1577baa78bdab7257a4849 | egorniy/Egor_Malinin_Homework | /Homework/Lessons/14.09.2021/15.09.2021/16.09.2021/18.09.21/2.py | 996 | 3.921875 | 4 |
a= str((input())) #ВВОДИМ переменную а, это строка
try: #Пытаемся сделать действие
b=a+3 # Действие не выполнится из-за типа данных стр, к строкам нельзя прибавлять числа, только строки
except TypeError as err: #Здесь мы объявляем типовую ошибку, что если она приклоючиться, то делать надо следующее
print('Ты ... |
fddc4826e434ca435881744969e1267eaffa7968 | heshengbang/pylearn | /day2/8.py | 587 | 4.0625 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
print "______________________________________________"
print "传不可变对象实例"
#传不可变对象实例
def ChangeInt( a ):
a = 10
b = 2
ChangeInt(b)
print b # 结果是 2
print "______________________________________________"
print "传可变对象实例"
#传可变对象实例
# 可写函数说明
def changeme( mylist ):
"修改传入的列表"
... |
09e7305603d5c71a622930ee5296c520cce5aea6 | larson3/GL | /201/Homeworks/hw8/hw8.py | 8,314 | 4.21875 | 4 | #File: hw8.py
#Author: John Larson
#Date: 3/31/14
#Section: 2
#Email: larson3@umbc.edu
#Description: This file contains code which will import a text file, and then play a two player text based game with the user.
#whichFile() will ask for the user to enter the name of a file, it will then attempt to open the file, re... |
c24ee6d54b802a9561a7b1ae0fbc8de12b502dd9 | avastjohn/Interview_Practice | /print_nums_wo_duplicate_digits.py | 520 | 3.921875 | 4 | """
Given a range x to y, print any number that doesn't contain duplicate digits
Ex: 2415 will print but 2414 will not (bc it has two 4s)
"""
def print_unique_digits(x, y):
for num in range(x, y):
num_str = str(num)
d = {}
repeats = False
for digit in num_str:
if d.get(d... |
ad62e019582a019fe4f96ce90a9c66b4e1d099a4 | aldld/Project-Euler-solutions | /32/32.py | 697 | 3.609375 | 4 | #!/usr/bin/env python3
# Project Euler problem 32
from math import sqrt, ceil
from mergesort import mergeSort
def getDivisors(n):
s = 0
i = 1
divisors = []
limit = ceil(sqrt(n))
while i <= limit:
if n % i == 0:
if (int(n/i)) not in divisors:
divisors.append(i)
... |
4fe6ee520555729c2fb3a0bbacce281e13c79514 | cugis2019dc/cugis2019dc-Stacey-31 | /Day1staceys.py | 602 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
import plotly
print("My name is Stacey Acheampong")
print(5*2)
print(5/2)
print(5-2)
print(5**2)
print((8/9)*(3))
print("5*2")
def multiply(a,b):
multiply = a*b
print(multiply)
multiply(4,5)
... |
0fe42e240d6efe5b00f978dd9a8fe1272c7699b2 | jayhebe/Exercises | /Automate_Exercises/Chapter7/exercise7181.py | 371 | 3.828125 | 4 | import re
def pwd_detection(password):
if len(password) < 8:
return False
pwd_pattern = r"[A-Z]+[a-z]+[0-9]+"
result = re.search(pwd_pattern, password)
if result != None:
return True
else:
return False
password = "Start1234"
if pwd_detection(passwor... |
a3447e10f0776b8bc42f2a419de7a85eabae42b3 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2463/60737/251472.py | 354 | 3.609375 | 4 | numbers = [int(n) for n in input().split(',')]
target = int(input())
left, right = 0, len(numbers) - 1
while left<right:
tmp = numbers[left] + numbers[right]
if tmp == target:
print( [left + 1, right + 1])
break
elif tmp < target:
left += 1
elif tmp > target:
right -= 1
i... |
14b42ea46c919ac5b0bee728ab58ea7e9b33b0aa | rmotr-students-code/004_PYP_G3 | /class_2/lambdas.py | 181 | 3.890625 | 4 | def add1(x, y):
return x + y
add2 = lambda x, y: x + y
result = add1(2, 3)
print(result)
result = add2(2, 3)
print(result)
result = (lambda x, y: x + y)(2, 3)
print(result) |
16b0e8b74c9db0c475c133f8efb596891dae03f0 | Xenovoyance/adventofcode2019 | /day4/day4-1.py | 860 | 3.765625 | 4 | #!/usr/local/bin/python3
input_min = 130254
input_max = 678275
correct_passwords = []
def correct_length(input):
if len(str(input)) == 6:
return True
def correct_range(input):
global input_max
global input_min
if (input >= input_min) and (input <= input_max):
return True
def corr... |
7f601bfb0682174dc80b8d6a621bea33d591b8c9 | EviBoelen15/Schooloedeningen | /Hogeschool/Bachelor/Semester 1/IT Essentials/Oefeningen/6_strings/oefening6.1..py | 294 | 3.8125 | 4 | def main():
tekst = input("Geef hier uw tekst: ")
plaatsT = tekst.find('t')
uitvoer = ""
for letter in tekst:
if letter == "T" or letter == "t":
uitvoer = tekst[:plaatsT + 1] + tekst[plaatsT:].upper()
print(uitvoer)
if __name__ == "__main__":
main() |
1773e7553cea0f4a5897914327356c2af1f92a4d | xf97/myLeetCodeSolutions | /src/jianzhi10.py | 875 | 3.53125 | 4 | class Solution:
def fib(self, n: int) -> int:
#用递归做一下
#超时,递归,20/51
'''
if n == 0:
return 0
elif n == 1:
return 1
else:
return self.fib(n - 1) + self.fib(n - 2)
'''
#从f(0)和f(1)开始计算
#边界情况
'''
ti... |
b2d13b20742f68fc08aa8bce6f8a5d7642dd82e7 | metantonio/Loginwithpy | /Data/login.py | 2,018 | 3.765625 | 4 | '''
Autor: PaoloRamirez
Tema: Simple login con python a travez de metodo POST
Link: https://www.facebook.com/PaoloProgrammer/
'''
import requests
from bs4 import BeautifulSoup
'''
Datos generales
'''
#Proxies
proxies = {
#"http": "",
#"http": "",
}
#Direccion url a hacer el login
url = "http://miurl.com/login... |
de318a8ef871acd008a45a0064e06f663421b528 | ramsandhya/Python | /ex8.py | 540 | 3.578125 | 4 | formatter = "%r %r %r %r"
print formatter % (1, 2, 3, 4)
# don't forget the comma
print formatter % ("one", "two", "three", "four")
print formatter % (True, False, False, True)
print formatter % ( formatter, formatter, formatter, formatter)
# don't forget the comma
print formatter % (
"I had this thing",
"Th... |
551ed8db87d573668f57cec9515100982ccc2a98 | shraddha36/CodilityAnswers | /Palindrome.py | 113 | 3.9375 | 4 | def palindrome(fd):
a=fd[::-1]
if a==fd:
return True
return False
print(palindrome("MADAM"))
|
b48e69a038c4c6fe007c1914e78a53c6b792c0cd | atg-abhijay/Advent-of-Code-2020 | /Day-03/advent-03.py | 1,094 | 4.0625 | 4 | """
URL for challenge: https://adventofcode.com/2020/day/3
"""
from functools import reduce
from operator import mul
def process_input():
f = open("advent-03-input.txt")
return [list(row.strip()) for row in f.readlines()]
def part1(grid, right_mvmt, down_mvmt):
num_rows, num_cols = len(grid), len(grid... |
b846d926dfff9604da809323aac34c104256be06 | jpeterseni35/LearnPython | /example.py | 411 | 3.578125 | 4 | def hello():
print('Howdy!')
print('Howdy!!')
print('Hello there.')
hello()
hello()
hello()
def hello(name):
print('Hello ' + name)
hello('Alice')
hello('Bob')
print('Hello has ' + str(len('hello')) + ' letters in it')
def plusOne(number):
return number + 1
newNumber = plusOne(5)
print(n... |
6d2e4af831bff175ab9b5287166f826850292028 | yjthay/Project-Euler | /ProjectEuler Q062v3 inefficient.py | 1,169 | 3.578125 | 4 | #The cube, 41063625 (345**3), can be permuted to produce two other cubes:
#56623104 (384**3) and 66430125 (405**3). In fact, 41063625 is the smallest
#cube which has exactly three permutations of its digits which are also cube.
#Find the smallest cube for which exactly five permutations of its digits are cube.
def ... |
4a4c8d79ae9f3ed0495bed04369afba61dafe658 | doctorhoseinpour/compiler-project | /Modules/camelToSnake.py | 505 | 3.84375 | 4 | def camelCase(x):
y = ''
skipNext = False
for i in range(0, len(x)):
if skipNext:
skipNext = False
continue
if x[i] == '-' and x[i-1].isalpha() and i+1<len(x) and x[i+1].isalpha():
y = y + x[i+1].upper()
skipNext = True
else:
... |
954b2ec078eb2c24c7e1b02bda19cd54319babd6 | JQWu023/VisionTracker | /tracker.py | 8,074 | 3.546875 | 4 | import cv2
import dlib
from eye import Eye
from calibration import Calibration
import numpy as np
from scipy.spatial import distance as dist
import time
class EyeTracking(object):
"""
This class tracks the user's gaze.
It provides useful information like the position of the eyes
and pupils and allows ... |
03ccd8f3421b01e65eb834edf652d2758de2fea3 | Abijithhebbar/abijith.hebbar | /cspp1/m12/p1/p1/create_social_network.py | 2,504 | 4.25 | 4 | '''
Assignment-1 Create Social Network
'''
def create_social_network(data):
'''
The data argument passed to the function is a string
It represents simple social network data
In this social network data there are people following other people
Here is an example social network da... |
89e0b9823136f7fc7523e04e630d5a1b8ce94b1d | Jahnavi-Jonnalagadda/100DaysOfCode | /Contests/Coding_Club-15th_Aug/Harsh's_Happiness.py | 428 | 3.625 | 4 | # Contest Link - https://www.hackerrank.com/contests/all-india-contest-by-mission-helix-15-august/challenges
def harsh_happy(arr, k):
for j in range(len(arr)):
if(arr[j]>k):
return True
return False
t = int(input())
for i in range(t):
n,k = map(int,input().split())
arr = list(map(i... |
4939cfdd4f22b1be22f7382c36cb641fbf43bbd9 | jgam/leetcode | /baekjoon/hotter.py | 485 | 3.6875 | 4 | # hotter.py\
# using heap
def solution(scoville, K):
answer = 0
# here binary search algorithm
import heapq
heap = []
for i in scoville:
heapq.heappush(heap, i)
# always compare the first two from list
while K > heap[0]:
try:
heapq.heappush(heap, heapq.heapp... |
358cf305af7b0a7f96bb9726723dde68e5d4cc87 | faliona6/PythonWork | /OOP/students.py | 1,853 | 3.609375 | 4 | class Student:
def __init__(self, name, ID):
self.name = name
self.ID = ID
self.testScore = []
def __str__(self):
nameInfo = "Name: " + self.name
IDInfo = "ID: " + str(self.ID)
return nameInfo + " " + IDInfo + "\n"
def addScore(self, score):
self.testS... |
136227341425b1dd04e0ea0588dc1d2bd632b319 | ranji2612/Algorithms | /graphs/graph.py | 1,074 | 3.71875 | 4 | def BFS(a,startNode):
#a is the adjacency List
#-----------------BFS-------------------
q = []
d = [-1 for x in range(len(a))]
#Starting with the first node
q.append(startNode)
d[startNode] = 0
while (len(q) > 0):
node = q.pop(0)
for x in a[node]:
if d[x]... |
f613b46f1ee5539653c2ba4743f1a22ceee419c6 | Rohit967/Athlete-Events-with-Python | /Athlete_Events.py | 5,269 | 4.1875 | 4 |
# There are ten questions about 120 years of Olympic history:
# athletes and results dataset in this task.
#Download the file athlete_events.csv from the following Kaggle page:
#https://www.kaggle.com/heesoo37/120-years-of-olympic-history-athletes-and-results
#1. Import pandas
import pandas as pd
#2. read the dat... |
008cb07f32e7436038129502c12fc4068697843d | fsociety123/flask-stores-rest-api | /create_table.py | 608 | 4.0625 | 4 | import sqlite3
#Creating a connection
connection= sqlite3.connect("data.db")
#Creating a cursor
cursor= connection.cursor()
#Create table query
query= "CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, username text, password text)"
#Executing the query
cursor.execute(query)
query= "CREATE TABLE IF NOT EXI... |
8b8ab89bbc45818d578efdb8a2598d20e4c248fb | JarodPierreMurton/Functions | /Development Functions 3.py | 1,980 | 4.21875 | 4 | #Jarod Pierre Murton
#Development Excercise Currency Converter
#4/12/14
#pounds to euros
def pounds_euros():
amount = int(input("Please enter the amount you would like to convert: "))
total = amount * 1.229
print("€{0}".format(total))
#pounds to dollars
def pounds_dollars():
amount = int(i... |
a681017ac1b828a0400c2f66713c693695f30c23 | maiconcarlosp/python | /Extras/Python - Aluno/aulapython/exercicio-repeticao-2-1.py | 101 | 3.578125 | 4 |
while 1:
usu = input("Usuário: ")
sen = input("Senha: ")
if usu != sen:
break |
a379b6539712a4ac4f5ae2025731333ad694142f | Ammatar/Python_lessons_basic | /lesson03/home_work/hw03_normal.py | 1,693 | 3.625 | 4 | # Задание-1:
# Напишите функцию, возвращающую ряд Фибоначчи с n-элемента до m-элемента.
# Первыми элементами ряда считать цифры 1 1
def fibonacci(n, m):
a = 0
fibo = [1, 1]
while a< m:
fibo.append(fibo[0+a]+fibo[1+a])
a+=1
return fibo[n:m]
# Задача-2:
# Напишите функцию, сортирующую пр... |
6b5036071f74e43bc29aee80be2c83a5da605724 | poohcid/class | /e-Judge/Motion.py | 413 | 3.609375 | 4 | """Motion"""
def main():
"""function"""
import math
speed = float(input())
angle = float(input())
rad = (angle*math.pi)/180
radf = rad*2
time = (2*speed*math.sin(rad))/9.8
high = (math.pow(speed, 2)*math.pow(math.sin(rad), 2))/(9.8*2)
radar = (math.pow(speed, 2)*math.sin(radf))/9.8
... |
3cc3302e58a1ed0b308cd14429b5630fdc82c01f | altoid/misc_puzzles | /py/interview1/lego2.py | 1,584 | 3.734375 | 4 | #!/usr/bin/env python
import sys
import math
import fractions
choose_cache = {}
def choose(n, r):
if (n, r) not in choose_cache:
result = int( reduce(lambda x, y: x*y, (fractions.Fraction(n-i, i+1) for i in range(r)), 1) )
# print "choose(%s %s) = %s" % (n, r, result)
choose_cache[(n, r)] = res... |
720070a5b0070af45c0b206b74ee25281609e683 | bambrow/courseworks | /fundamental-algorithms/hanoi/HanoiWithD.py | 411 | 4.1875 | 4 | def hanoiWithD(n, A, B, C, D):
if (n == 1):
move(1, A, B)
elif (n == 2):
move(1, A, C)
move(2, A, B)
move(1, C, B)
else:
hanoiWithD(n-2, A, C, B, D)
move(n-1, A, D)
move(n, A, B)
move(n-1, D, B)
hanoiWithD(n-2, C, B, A, D)
def... |
c61820d34dc934f947726691c7bbef58264b8e26 | bonndomi/adventofcode2020 | /adventofcode/advent4.py | 2,996 | 3.53125 | 4 | import typing
def load_input(user_data_file):
with open(user_data_file, "r") as fd:
for line in fd:
yield line.strip()
def read_passports(lines: typing.Iterable[str]) -> list:
result = {}
for line in lines:
if line == "":
yield result
result = {}
... |
595bbaedbad1ef7ef6007406a5cf60460aec121c | dairadriana/LeetCode_MySubmissions | /palindrome-linked-list/palindrome-linked-list.py | 527 | 3.703125 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
lista = [head.val]
curr = head
while curr.next != None:
curr = cu... |
b9c8c61aa713d5e10b630bc0cc5977a44c46fbb1 | badandworse/leetcodeAns | /answers/102.py | 727 | 3.765625 | 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 levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
... |
a4174ed70eb5bc55f069d97f917b6f178d47f224 | gabriel-vitor/blastoff | /Blastoff/ex07.py | 137 | 3.53125 | 4 | lista1 = [1, 2, 3, 4 , 5, 6, 7 ,8 ,9, 10]
i = 0
for i in lista1:
if i % 2 != 0:
lista1.remove(i)
print(lista1)
|
f7d7a5e44ede451699488db61fb008cc7ab3b92d | Thiago-Gonzalez/Blackjack-Game | /main.py | 3,755 | 3.921875 | 4 | #Blackjack Game in Python
#Author: Thiago González
#Git: github.com/Thiago-Gonzalez
from ASCII import cards_ascii
from game_rules import rules
from art import logo
from cards_values import cv
import random
import os
def deal_card():
'''Returns a random card from the deck.'''
deck = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10... |
e3e44381208bfdad90326d7f120eb8a312364e0a | SnowSuno/SortingAlgorithmVisualizer | /algorithms/shell.py | 508 | 3.796875 | 4 | NAME = 'Shell Sort'
INFO = 'Time complexity\n' \
' Ω(n log(n))\n Θ(n log(n)²)\n O(n log(n)²)\n\n' \
'Space complexity\n' \
' O(1)'
def sort(s):
skip_index = (5, 3, 1)
for k in skip_index:
for _ in skip_insertion_sort(s, k):
yield
def skip_insertion_sort(s, k):
... |
090a53e43283180eb06d61a41a41c19503f5efd7 | Malak-Ghanom/Python | /Class_Assignment/CA03/q6.py | 425 | 4.1875 | 4 | #Swap then print following two tuples.
#first_tuple = (11, 22)
#second_tuple = (99, 88)
first_tuple = (11, 22)
second_tuple = (99, 88)
print(f"\nThe tuples befor swapping is:\n first tuple: {first_tuple}\t second tuple: {second_tuple} ")
swapped_tuple= first_tuple
first_tuple= second_tuple
second_tuple= swapped_tuple... |
68e7b78d53aa7d0f785145d1b69217afadd6a5e7 | JiangYuzhu/LearnPython | /python-qiyue/nine-class/c4.py | 481 | 3.796875 | 4 | #构造函数
class Student():
name = ''
age = 0
def __init__(self): #实例化的时候,python自动调用构造函数,不需要显示调用
print('student')
def do_homework(self):
print('homework')
student = Student()
a = student.__init__() #可以显示调用构造函数,但是实际编程没有必要
print(a) #默认返回值为None,构造函数不能指定返回其他值
print(type(a))... |
5e78f42e6704f36a0ca61e5910fa7e5a4e88f56c | tharunj30/t-bag | /tbagProject.py | 2,766 | 4.1875 | 4 | import time
digits_list = [] #first number in room 3(7)
def congrats():
print("Congratulations you made it to the next room! Do you have what it takes to go to the next room?")
def restart():
answer_restart = input("Would you like to start again?(Y/N)")
if answer_restart == 'Y' or 'y':
room_thre... |
c35a86d30617a0afa3b7a97b1be999b9f64f2f03 | sourabhossain/dimikoj | /39.py | 175 | 3.984375 | 4 | T = int(input())
for i in range(T):
n = input()
if n == n[::-1]:
print("Yes! It is Palindrome!")
else:
print("Sorry! It is not Palindrome!")
|
31812cbc68a41ec6855a5db22610dd41ca462b97 | gdc3000/bradfield-ds-algorithms | /binary_search.py | 5,565 | 4.1875 | 4 | """
Hashing and binary search both address the same problem: finding an item in a collection.
What are some trade-offs between the two strategies?
-Hashing has a higher insertion cost, if there are collisions.
-Hashing also has potential to consume more memory or use memory less efficiently
(since values aren't st... |
4700fc581c13c5ac9febade9a42bb44173d19d7a | cyy0127/Leet-Code-Solutions-Python | /Base7.py | 575 | 4 | 4 | """Given an integer, return its base 7 string representation.
Example 1:
Input: 100
Output: "202"
Example 2:
Input: -7
Output: "-10"
Note: The input will be in range of [-1e7, 1e7]."""
class Solution(object):
def convertToBase7(self, num):
if num == 0:
return "0"
digits =... |
f55cb0fc0db15a045c44c4df09dd8300e36fd67a | 20113261/p_m | /Test/test_func_code.py | 1,932 | 3.53125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2017/12/5 下午8:19
# @Author : Hou Rong
# @Site :
# @File : test_func_code.py
# @Software: PyCharm
import dis
def my_func():
a = [1] * (2 * 10 ** 7)
b = [2] * (2 * 10 ** 7)
return None
def my_func_2():
a = [1] * (2 * 10 ** 7)
b = ... |
869330b6fca0413f7abcbd8a07941dade70d7edf | jonegarm2/inventory | /inventory_app.py | 1,436 | 4.09375 | 4 | stock ={'apples': 6, 'oranges': 3, 'pears': 0}
alreadyAte = []
def menu():
print("Press 1: To add stock. ")
print("Press 2: To check stock. ")
print("Press 3: To enter purchase. ")
print("Press q: To add. ")
return input("What would you like to do? ")
run = menu()
while True:
if run == '1':
... |
75a3e57bbfc7fa8b1bad7fe889822df8eeb30ad2 | ram-ku/Weekly-Problems | /2012–2013/Week 14/Advanced/ryanscott.py | 730 | 3.5 | 4 | import itertools
import sys
cache = {}
def parts(min_part, num):
if min_part > num:
return 0
elif min_part == num:
return 1
elif (min_part, num) in cache:
return cache[(min_part, num)]
else:
num_parts = parts(min_part + 1, num) + parts(min_part, num - min_part)
cache[(min_part, num)] = num_parts
retur... |
2ebdf37778fb7b151bc411c4284f2403908a57d1 | efrigo88/Python-Course-Udemy | /08. Modules and Functions/_15_circle_scale.py | 2,018 | 3.859375 | 4 | import math
# with plotting
try:
import tkinter
except ImportError: # in case we're dealing with python 2
import Tkinter as tkinter
# def circle(page, radious, v, h):
# # changed the scale by multiplying and dividing the functions' parameters
# scaling = 100
# for_from = v * scaling
# for_... |
56faea58d1bde533ef5a0aeae1157cd9d5abe57e | flask-django-independent-study/week-4-varsity | /the_bank/models.py | 656 | 3.59375 | 4 | """Import libraries."""
from the_bank import db
# By now you should know how to set up a SQLAlchemy Model class. To make
# sure you know what's going on with this app, take a look below to see
# what properties an account has along with what data types it expects.
class Account(db.Model):
"""Account database mod... |
9afca13efc857396d3cfe1273e458354b04848eb | giuliana-marquesi/estudo-python | /coursera/co_pi_ah.py | 6,835 | 3.953125 | 4 | import re
def le_assinatura():
print("Bem-vindo ao detector automático de COH-PIAH.")
wal = float(input("Entre o tamanho medio de palavra:"))
ttr = float(input("Entre a relação Type-Token:"))
hlr = float(input("Entre a Razão Hapax Legomana:"))
sal = float(input("Entre o tamanho médio de sentença:... |
cac5596e340300ce7b31b68acf26e4e933c76140 | HenriTammo/OMIS | /tund1/soojendus.py | 164 | 3.546875 | 4 | külg_A = float(input("sisestada külg A"))
kõrgus = float(input("sisestada kõrgus"))
pindala = (külg_A*kõrgus)/2
print ("Kolmnurga pindala on", pindala, "cm")
|
48887a261211df1a152b720e5875f247bf2c79a4 | etsvetanov/Algorithms | /leetcode/word_break.py | 1,569 | 3.5 | 4 | from typing import List
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
word_set = set(wordDict)
memo_checked = [False] * len(s)
def recurse(start) -> bool:
for end in range(start + 1, len(s)+1):
if s[start:end] in word_set:
... |
fe1fa9d43d0d7e8cc6ff61b036bf0e9aa72c9da8 | night1008/py_snippet | /daterange/main.py | 1,663 | 3.578125 | 4 | from datetime import datetime, timedelta
def daterange(start_date, end_date, interval='day'):
"""
start_date: str or datetime, such as datetime(2019, 5, 12) or '2019-05-12'
end_date: str or datetime, such as datetime(2019, 5, 18) or '2019-05-18'
interval: str, such as minute, hour, day, week, month
... |
797b46548a35eff80402449231370889eb234c51 | joycetruong/15112-TermProject-MemoRe | /code/entry.py | 8,541 | 3.5625 | 4 | #################################################
# entry.py
# this is the entry object that will allow me to get user input in the GUI
#
# Your name: Joyce Truong
# Your andrew id: btruong
# Section: C1
#################################################
# From CMU 112 Animation Part 1 Notes:
# https://www.cs.cmu.edu/... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.