blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
62833ea200d07b5956dd27af2b99ebc37168153a | NarenSuri/Computer-Vision | /FaceExpressionRecognition-Test/DataGeneration.py | 5,239 | 3.65625 | 4 | import numpy as np
import pandas as pd
import random
## working on data set of kaggle for face expression recognition
# I have already built a deep neural network with the just python and TensorFlow
# now, I will use the CNN for the image analysis, which is definitely a better tool compared to the DNN
# I will use the... |
39f1ad715040b9e7baafeec246a6e874fb7c1a6a | vScourge/Advent_of_Code | /2021/03/2021_day_03_2.py | 6,897 | 3.921875 | 4 | """
--- Day 3: Binary Diagnostic ---
The submarine has been making some odd creaking noises, so you ask it to produce a diagnostic
report just in case.
The diagnostic report (your puzzle input) consists of a list of binary numbers which, when
decoded properly, can tell you many useful things about the conditions of ... |
dbf1f23643e58ad8a3a8d6545a384fbbb140d852 | project-documentanalysis/Exercises | /intro/main.py | 39,764 | 3.53125 | 4 | import numpy as np
import matplotlib.pyplot as plt
from collections import defaultdict
from operator import itemgetter
class RandomArrayGenerator(object):
def __init__(self, seed=None):
""" Initialisiert den Zufallsgenerator
Params:
seed: Zufallssaat
"""
if seed is not... |
519b998a28381c3c870587c4d47ecae5ef4da630 | Ashutosh5370/DailyCodingProblems | /Problem2.py | 1,138 | 4.0625 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the bonAppetit function below.
def bonAppetit(bill, k, b):
totalbill = sum(bill)
anna = int((totalbill - bill[k])/ 2)
if(anna == b):
print("Bon Appetit")
else:
print(b - anna)
if __name__ =... |
95cb90e236bedbd45d0d96f1edf794dbe99a9800 | Aspace-dev/Austin-Spacek---Homework-2 | /python-challenge/as_pypoll/austin_s_polling.py | 1,846 | 3.671875 | 4 | import csv
with open ("election_results.txt", "w+") as output:
with open("election_data.csv" , "r") as csvfile:
readCSV = csv.reader(csvfile)
data = list(readCSV)
row_count = len(data)
print("Election Results:")
print("-------------------------")
print("Tota... |
22d9a3ef9d5e0aa8c7546a239e8fcc2e5e02ad70 | zhutiankang/PyLearning | /advance/two/c1.py | 1,177 | 3.71875 | 4 | # 实现可迭代对象和迭代器对象
'''
某软件要求,从网络抓取各个城市气温信息,并依次显示:
北京:15-20
天津:17-22
长春:12-18
....
如果依次抓取所有城市天气再显示,显示第一个城市气温时,有很高的延时,并且浪费存储空间
解决方式: “用时访问”策略,并且把所有城市气温封装到一个对象里,可用for语句进行迭代
'''
from collections import Iterable,Iterator
# 迭代器对象
class WeatherIterator(Iterator):
def __init__(self,cities):
self.cities = cities
... |
5c23bbdf11d16eb81b48f92e48f470fb3bd226c4 | ShriBuzz/IW-PythonLogic | /Assignment I/Data Types/9.py | 183 | 4.125 | 4 | # Write a Python function that takes a list of words and returns the length of the
# longest one.
string = input()
new = string[-1:] + string[1:len(string)-1] + string[:1]
print(new)
|
546549d920c87e89525b8f1471dddbd2cc59eaa0 | juliotmorais/passwordGenerator | /passwordGenerator.py | 969 | 3.796875 | 4 | import random
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","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"]
numbers=["1","2","3","4","5","6","7","8","9","0"]
symbols=["!","#","$","%","&","("... |
46fd1182813d667414495e52ea54383beb244792 | Wqymai/Python_Spider | /BeautifulSoup_test.py | 891 | 3.671875 | 4 | from bs4 import BeautifulSoup
html ="""<html><head><title>The Dormouse's story</title></head><body><a class='myclass'/><p>hello
world
</p></body></html>"""
soup = BeautifulSoup(html,'html5lib')
print soup.a
print type(soup.a)
print soup.name
print soup.a.name
print soup.a.attrs
print soup.a['class']
print soup.t... |
fc36dce6f5ecbda1989b39c2f89a7a8eee0abba7 | mwharmon1/BasicWhileLoopAssignment | /input_loops/average_input_scores.py | 1,086 | 4.28125 | 4 | """ Author: Michael Harmon
Last Date Modified: 9/19/2019
Description: This program will use a basic while loop
to calculate the average from a list of scores.
"""
def average(score_list):
scores_total = 0
items = len(score_list)
for i in score_list:
scores_total += i
items - 1
... |
3f0fd8bfcfab8278c57ff546f86ceb4d4aa64246 | Hi-Im-darkness/snake | /test/1.5.2017/other.py | 845 | 3.75 | 4 | class Pos:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
print(self.x, self.y)
def __eq__(self, taget):
if self.x == taget.x and self.y == taget.y:
return True
return False
def distance(self, taget):
return (self.x - tag... |
7df6a1b3439c726a5ff06a2b0f36ea4bf5967e1d | angelmonge/1-evaluaci-n | /condicional_2.py | 259 | 3.65625 | 4 | def condicional_2():
edad=input("cual es tu edad? ")
if(edad >= 18 ):
print "Sala alcoholica "
else:
if(edad >= 15 ):
print "Sala adoescentes"
else:
print "Sala infantil"
condicional_2()
|
45f832e48e71a6644800a59b1e9b39c37d275391 | sumitalp/problems | /algorithms/HackerRank/binary_search_tree_insertion.py | 1,874 | 4.28125 | 4 | '''
You are given a pointer to the root of a binary search tree and values to be inserted into the tree. Insert the values into their appropriate position in the binary search tree and return the root of the updated binary tree. You just have to complete the function.
Input Format
You are given a function,
Node * in... |
52b4f7b3cb508b0f7d3ea641c0077ee51c8f141d | JamesExeter/tic-tac-toe-poetry | /tic_tac_toe/game.py | 10,125 | 4.03125 | 4 | # global dictionary to store which symbols are used for each player
from typing import List
from tic_tac_toe import constants as consts
from copy import deepcopy
"""
import Player
import Board
import Game_Controller
"""
def check_draw(elapsed_turns: int) -> bool:
"""
Checks if the game is a draw
Par... |
fa5985831fd78c8c964dbb4040cee4acdba79b67 | AyrtonDev/Curso-de-Python | /Exercicios/ex032.py | 292 | 3.828125 | 4 | from datetime import date
print('Descubra se seu ano é BISSEXTO')
ano = int(input('Digite o seu ano: '))
if ano == 0:
ano = date.today().year
res = ano % 4
if res == 0:
print('O ano de {} é BISSEXTO.'.format(ano))
else:
print('O ano de {} não é BISSEXTO'.format(ano)) |
22cd681b8e3e61ae220cbadecaa7d3f9a227d4e6 | zhouzhousc/data-structures | /1.13.py | 395 | 3.96875 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
# author: Carl time:2020/4/25
def s_list(list0):
list1 = []
for i in list0:
list1.insert(0, i)
return list1
list_test = [23, 432, 12, 53, 90]
print(s_list(list_test))
# list.reverse()
# 反向列表中元素
list_test.reverse()
print(list_test)
# list.sort( key=None,... |
e67aebff8cc3e96899bf92f76dc3749b6f0c6c50 | leafsummer/keeplearning | /python-gems/online_judge/problemset/problem_panlindrome.py | 511 | 3.65625 | 4 | from problem import Problem
class PalindromeProblem(Problem):
_id = 5
title = "Palindrome Or Not"
description = "A palindrome is a word, phrase, number,\
or other sequence of characters which reads the same backward or forward.\
return True if the supplied word is palindrome, else return False"
method... |
0e9a81319f95bd3d71e8154d7c8e1bfdce7da84c | EduardoScalise/PythonLab | /PyFuncao.py | 934 | 3.890625 | 4 | # Definindo uma função
def primeiraFunc():
print('Hello World!')
primeiraFunc()
# Definindo uma função com parâmetro
def primFunc(nome):
print('Welcome %s' %(nome))
# Chamando a função e passando parãmetro (Neste caso solicitando o nome - entrada
primFunc(input('What\'s your name: '))
def funcLeitura():... |
b516d84a6015665efe2bc8602f2f7d4a84118342 | RAM-droi/StructuredPrograming2A | /unit1/activity.01.py | 250 | 4.15625 | 4 | num1 = 0
num2 = 0
result_add = 0
result_m = 0
num1 = int( input( "Enter number1:" ) )
num2 = int( input( "Enter number2: "))
result_add = num1 + num2
result_m = num1 * num2
print("This is the add:",result_add)
print("This is the mult:",result_m)
|
43ba3a2285640924c0e7dd06a923d7033046d871 | porrametict/learningSpace | /PythonWithChulalondkorn/basic_concept.py | 218 | 3.921875 | 4 | # w = int(input("width = ")) #string ="5"
# h = int(input("height = "))
print(w*h)
# print(5*3)
#dynamic typing
w = input("width")
print(type(w))
a = 5 #int
print(type(a))
b = 5.0 #float
print(type(b))
c =1/3
print(c) |
20013479273937bf5a1fad5bd2e8cf598827bfe0 | mjcarter95/MSc-University-of-Liverpool | /Data Mining and Visualisation/Perceptron/binaryperceptron.py | 3,729 | 3.859375 | 4 | import numpy as np
import plotgraph
def train(train_data, test_data, num_elements, epoch, messages, shuffle):
'''
Train the perceptron algorithm
:param train_data
:param num_elements the number of features in the dataset
:param epoch
:param messages print weights and bias at eac... |
96c50b39f69eb74c2c882498bf1c7b516fa7b510 | JonnyCBB/BeamlineI02work | /beamImageConstructor.py | 5,578 | 4 | 4 | import numpy as np
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
def generateBeamFromPNG(pngImage, redWeightValue, greenWeightValue, blueWeightValue):
"""Function that generates a beam array from a PNG file.
INPUTS:
pngImage -The path to a png file that contains an image o... |
327c897f8eb62e14009f1b26a7b095e5112ed2b2 | sj43/Code-Storage | /DailyCodingProblem/1.py | 233 | 3.546875 | 4 | def two_sum(arr, k):
d = {}
for a in arr:
if a in d:
return True
d[k-a] = True
return False
ex1 = [10, 15, 3, 7]
print two_sum(ex1, 17)
ex2 = [1, 2, 3, 4, 5, 6, 7]
print two_sum(ex2, 12)
|
d85819e6099949bb137714322ce858c417712129 | geshem14/my_study | /Coursera_2019/Python/week9/week9task1_2_test.py | 1,551 | 4.09375 | 4 | from sys import stdin
from copy import deepcopy
# week 9 task 2
# https://www.coursera.org/learn/python-osnovy-programmirovaniya/programming/
# cTJex/dobavit-umnozhit
class Matrix:
def __init__(self, listOfLists):
self.matrix = deepcopy(listOfLists)
def __str__(self):
str1 = ''
for ... |
b15735efb6e5ccfd5144d91ad15bf2f3db39a8e3 | GeoffRiley/AdventOfCode | /2022/17/day17.py | 6,050 | 3.625 | 4 | """
Advent of code 2022
Day 17: Pyroclastic Flow
"""
from itertools import cycle
from math import floor
from textwrap import dedent
from typing import List
from aoc.loader import LoaderLib
from aoc.utility import lines_to_list
ROCK_CHUNKS = [
[0b00111100],
[0b00010000,
0b00111000,
0b00010000],
[... |
955e498bc530ee05d4830455f0dff6d2beb31668 | ssempax1/StatsCalculator | /Statistics/Median.py | 238 | 3.65625 | 4 |
def median(data):
n = len(data)
data.sort()
if n % 2 == 0:
median1 = data[n // 2]
median2 = data[n // 2 - 1]
median = (median1 + median2) / 2
else:
median = data[n // 2]
return median
|
7c0053676b8e3af976088328d1e1369726adb943 | AleksaArsic/ProjektovanjeAlgoritama | /pripremaT1/pripremaPrviTest.py/pripremaPrviTest.py/pythonMania.py | 1,349 | 3.640625 | 4 | import sys
def sumOfN(x):
retVal = 0
for i in range(x):
retVal += i
return retVal
def sumOfNsquares(x):
retVal = 0
for i in range(x):
retVal += x**2
return retVal
def stringManipulation(first, second):
return first[0:3]*2 + second[len(second) - 3: len(second)]
def l... |
f99faf48a4805a8903f53821d3e2b551cc1e51ba | eggzotic/Hackerrank | /FairRations/FairRations.py | 1,151 | 3.703125 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the fairRations function below.
def fairRations(B):
# identify all the indices of odd numbers
oddPosition = {}
oddCount = 0
for i in range(len(B)):
if B[i] % 2 == 1:
oddCount += 1
oddPosi... |
d781a5f547d47017d6b50113e9d7c2fac2e64105 | djiwandou-p/backend-assessment-evermos | /Treasure Hunt/treasure-hunt.py | 3,183 | 3.6875 | 4 | from turtle import *
from base import vector
import random
from math import sqrt
path = Turtle(visible = False)
writer = Turtle(visible = False)
aim = vector(20, 0)
pacman = vector(-170, 110)
grids = [
0, 0, 0, 0, 0, 0, 0, 0,
0, 1, 1, 1, 1, 1, 1, 0,
0, 1, 0, 0, 0, 1, 1, 0,
0, 1, 1, 1, 0, 1, 0, 0,
0... |
b2c97c48cdedb199a042ecdf07672a8bf39397ac | canyon15/PythonMod | /Example_3.py | 1,457 | 4.5 | 4 | """
CSE310 Python Workshop - Example 3
This example will explore classes and inheritance
in Python.
"""
class Job:
def __init__(self, title, work):
"""
Constructor for a Job object
"""
self.title = title
self.work = work
pass
def __str__(self):
"""
... |
eeb32b86f35a8343120dfeb28fb8f22e49f9ed83 | KowsalyaS18/task227 | /replace.py | 69 | 3.78125 | 4 | string=input("enter your string")
x=string.replace(",","|")
print(x)
|
c2194f226c1575a3bb9485867622a2c9ad92ece6 | jakesig/cs2020fall | /Week 11/Week 11 - Lab/sheepdog.py | 458 | 3.546875 | 4 | #!/usr/bin/python
class Dog:
color = "black"
def run(this):
print( "my " + this.color + " dog is running" )
def fetch( this, thing ):
return this.color+" dog's slobber-covered "+thing
class SheepDog( Dog ):
def herd(this,what):
print( "my " + this.color + " sheep-dog is herding " + what )
dog1 = ... |
abd905afa74123196b72cfb28a24a6a78372704a | Sowmiyau1/python-programming | /begin level/celcius to kelvin.py | 114 | 3.984375 | 4 | celsius=int(input("Enter the temperature in celcius:"))
f=(celsius + 273.15)
print("Temperature in kelvin is:",f)
|
c6982d04bc02f7f0e1662fdf606c22aadbcef702 | yalowe/Phyton | /polindrom_check.py | 379 | 4.28125 | 4 | print("")
print("the app check if what we get from the user is palindrom or not:")
print("")
print("please enter number or string to cheke if the input is palindrom or not:")
print("")
palindrom=input()
lenhgt = len(palindrom)
for x in range(0,lenhgt-1):
if palindrom[x] != palindrom[lenhgt-x-1]:
print("not ... |
f5db163ec6d94312f12c216cf4577f8c27c83147 | luisdomal/Python | /S1/tablas_multiplicar.py | 446 | 4.03125 | 4 | print("Ingresa el número: ")
n = input()
numN = int(n)
print("{} x 1 = {}".format(n, numN))
print("{} x 2 = {}".format(n, numN*2))
print("{} x 3 = {}".format(n, numN*3))
print("{} x 4 = {}".format(n, numN*4))
print("{} x 5 = {}".format(n, numN*5))
print("{} x 6 = {}".format(n, numN*6))
print("{} x 7 = {}".format(n, nu... |
da1d2c4a933f80b4b60ff6066faab1650b0532c1 | erp12/sklearn-symbolic-regression | /utils.py | 1,787 | 3.890625 | 4 | """
"""
import math, random
import numpy as np
MAX_NUM_MAGNITUDE = 1e8
MIN_NUM_MAGNITUDE = 1e-8
def get_arity(f):
"""Returns the artity of the function f.
Returns
-------
arity : int
Returns the number of argumetns f takes.
Examples
--------
::
>>> get_arity(lambda x: x*... |
4086e9c26446f8907f8cf014b3e7d51eedefb7f4 | jaros1024/emotion-predictor | /lib/postprocessing.py | 1,824 | 3.625 | 4 | from pandas import DataFrame
from sklearn.preprocessing import MinMaxScaler
from sklearn.preprocessing import StandardScaler
import lib.emotion as em
class Postprocessing:
"""
This class contains methods used to transform data to be ready to use in machine learning
"""
def __init__(self, freq):
... |
6590874e71f1fd3ce26fbd5f07bc5add5ed02e5a | FreeKev/MITCompSciNotes | /MITCompSci.py | 10,757 | 4 | 4 | # print(int(9/5), 9%5)
# x = 3
# x = x*x
# print (x)
# n = int(input('enter #: '))
# print(n)
# print n/n
# Can't use
# print (value or command?)
# 28 keywords can't use
# Branching pattern
# can change order of instructions
# based on a test (usually var value)
# x = int(input('x='))
# if (int(x/2))*2 == x:
# pri... |
562b1e66debe92315315bf9e9a77caa0fcb0b21c | sunnygirlzyq/KNN-with-pure-python | /KNN_M_407.py | 4,389 | 3.515625 | 4 | """
使用马式距离做KNN分类
输出正确率验证结果
61518407李浩瑞 2021.1.5
"""
from KNN_O_407 import *
def Grad(data,label,A):
y=len(data[0])
n=len(data)
Prow = []
"""计算概率矩阵"""
P=np.zeros((n, n))
for i in range(n):
sums=0
#print("sums:",sums)
for j in range(n):
if j ... |
61e249ac3e0d57922f2c85ce6d783bf4e2e3a4f7 | srinivasgirijala/python-projects | /calc.py | 1,445 | 4.21875 | 4 | # this fun add two numbers.
def add(x, y):
return x + y
# this fun sub two numbers.
def subtract(x, y):
return x - y
# this fun mul two numbers.
def multiply(x, y):
return x * y
# this fun div two numbers.
def divide(x, y):
return x / y
# it will print below options
print("Select operation."... |
9441041038b50800a66230de87547809ff233767 | debmalya/EmailClassification | /src/main/python/SimpleFileReaderNPrinter.py | 214 | 3.8125 | 4 | def readNPrintFile(fileName):
"""
Read the passed file name.
Print each word in a separte line.
"""
for line in open(fileName):
for word in line.split():
print word
readNPrintFile("./Gutso Gold.txt") |
f18cf5b282464a4117b064d67e05a54d1cd8cbcb | qmnguyenw/python_py4e | /geeksforgeeks/python/python_all/132_8.py | 3,391 | 3.875 | 4 | Why do people prefer Selenium with Python?
Selenium is a strong set of tools that firmly supports the quick development
of test automation of web applications. It offers a set of testing functions
that are specially designed to the requirements of testing of a web
application. These functions are reliable fac... |
73ccaa02f0385e19d21ba2039a04be4b337bd70a | shionit/til | /Python-handson/basic/if_else.py | 332 | 4.09375 | 4 | # coding: UTF-8
# 条件分岐 if
# <= >= > < == !=
score = 70
if score >= 80:
print("pass!")
else:
print("not pass!")
# 1 liner
print("pass!" if score >= 80 else "not pass!")
if score >= 80:
print("OK!")
elif score >= 60:
print("so so")
else:
print("oh....")
if 40 <= score < 60:
print("mmmmmm... |
ba59ed49cbea9e6470c3b67ea3e6a21693482b26 | MrHamdulay/csc3-capstone | /examples/data/Assignment_3/mrgsac001/question2.py | 133 | 3.84375 | 4 | m=eval(input("Enter the height of the triangle: \n"))
n=" "
o=1
while m>=1:
print(n*(m-1),o*"*", sep="")
o+=2
m=m-1 |
42f9fb5933480956b867f4762411fea10a7e7e3f | midigo0411/Password-locker | /user.py | 494 | 3.96875 | 4 | class User:
'''
Class to create user accounts and save their information
'''
# Class Variables
# global users_list
users_list = []
def __init__(self,first_name,last_name,password):
'''
Method to define the properties for each user object will hold.
'''
# instance variables
self.first_name = first_name... |
f084abd26828326c22ab343aa796e86789112b90 | binshengliu/leetcode | /25.reverse-nodes-in-k-group/solution.py | 1,166 | 3.875 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reverseKGroup(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
# print... |
ae50fbef9eb2885b1694b25c84a70527f2219558 | Jump3rX/speech-to-text-in-python | /SpeechToText.py | 2,852 | 3.734375 | 4 | import speech_recognition as sr #imports the SR module
import time,pygame
from PyDictionary import PyDictionary #imports dictionary module to check word meanings
from googletrans import Translator #imports function to translate words to any language
translator = Translator() #assigns Translator function to var na... |
f51d3518b076e27232b4257f5d4fbf66ed185304 | su222ya/Test_Python | /97_python_exercise.py | 1,878 | 4.15625 | 4 | # 각 사람에 대한 데이터를 읽어서 성적순으로 출력하면 되요! 출력양식은 다음과 같습니다.
#예시)
# 1등 아이유 95.6
# 2등 홍길동 89.3
# class Student(object):
# def __init__(self,name,grade1,grade2,grade3):
# self.name = name
# self.grade1 = grade1
# self.grade2 = grade2
# self.grade3 = grade3
#
# file1 = open("C:/python_data/stude... |
cf839bd311520eca23478fe1833e458d079f6ce9 | weiting0032/LeetCode | /code/python/PowerofFour.py | 851 | 3.671875 | 4 | '''
Title: 342. Power of Four (Easy) https://leetcode.com/problems/power-of-four/
Runtime: 24 ms, faster than 99.72% of Python online submissions for Power of Four.
Memory Usage: 11.9 MB, less than 6.41% of Python online submissions for Power of Four.
Description:
Given an integer (signed 32 bits), write a fu... |
99288d12161c1c71e021dd095caf21347bf8c6c7 | bertha-xuecheng/test001 | /第三次作业/人力系统.py | 3,692 | 3.5 | 4 | #!/usr/bin/env python
# -*-coding:utf-8 -*-
# @Author雪成
# 菜单: ("查看员⼯信息","添加员⼯信息", "修改员⼯信息", "删除员⼯信息", "退出")
import os
'''查看员⼯信息'''
def Viewemployeeinformation():
id = int(input('请输入你要查看的全部员工信息的id: '))
f = open('emp.db', mode='r', encoding='utf-8')
for line in f:
lst = line.strip().split(',')
... |
3374f2a5d0a4ae1a251634425ee0b3efd368d594 | BuildingBB8/RCcarOptocoupler | /rotatecar.py | 554 | 3.59375 | 4 | import RPi.GPIO as GPIO #bring in the library
import time #bring in the time library
GPIO.setmode(GPIO.BCM) #setup the pin naming convention
GPIO.setwarnings(False) #give me warnings
GPIO.setup(23,GPIO.OUT) #left button
GPIO.setup(24,GPIO.OUT) #right button
print "SPIN COUNTER CLOCKWISE"
GPIO.output(23,GPIO.HIGH) #powe... |
229daa79e852c762b94ac10a3ca8b9c1e4ba19c4 | bl-deepakchawla/ML-Followship-Program | /Python Datastructure/52. WAP to check whether an element exists within a tuple.py | 177 | 3.6875 | 4 | def check_value_exists_tuple():
tuple_value = (12, 13, 14, 15, 16)
if 12 in tuple_value:
print(True)
else:
print(False)
check_value_exists_tuple()
|
ae82e00cd13730942e594ec401b4468b0eec12d6 | Nayjer/Euler-Problems-Solutions-Python | /67.py | 1,828 | 3.734375 | 4 | #!/usr/bin/python3
"""
By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23.
3
7 4
2 4 6
8 5 9 3
That is, 3 + 7 + 4 + 9 = 23.
Find the maximum total from top to bottom in triangle.txt (right click and 'Save Link/Target As...'), a 15... |
d152f1d1a95683d654e8395afc35093dceeb2ae0 | vyahello/trump-bullet-game | /app/model/visual.py | 2,510 | 3.640625 | 4 | from abc import ABC, abstractmethod
from typing import Tuple
from pygame import display, Surface, time
from app.model.properties import Resolution
class Window(ABC):
"""The class represents abstract window."""
@abstractmethod
def parent(self) -> Surface:
"""Returns parent window."""
pass
... |
a14032433b48d0cd4931d49df293b8979481bddc | ck-unifr/leetcode | /design/460-lfu-cache.py | 2,993 | 4 | 4 | """
https://leetcode.com/problems/lfu-cache/
460. LFU Cache
Design and implement a data structure for Least Frequently Used (LFU) cache.
It should support the following operations: get and put.
get(key) - Get the value (will always be positive) of the key if the key exists in the cache,
otherwise return -1.
put(ke... |
0d4f3cd11edbcfbbc54119a07446c3f8cc99ce2e | CaJiFan/PF-coding-exercises | /U5) Arreglos n-dimensionales/Ejercicio 3 - L1.py | 909 | 3.796875 | 4 | #Terminado
#En una empresa le piden a usted crear un programa que nos ayude a determinar los nombres de los empleados que ganan mas de 300 dolares
#dentro de la empresa, para ello nos dan una lista de nombre de los empleados y los sueldos de cada uno de ellos
#Defina una funcion que con el uso de numpy nos ayude a sab... |
1283043bfe841affdf77e89e808d9ef005213ee0 | sarojthapa60/Codewars | /7kyu/two_to_one.py | 575 | 3.875 | 4 | """
7kyu: Two to One
https://www.codewars.com/kata/two-to-one/train/python
Take 2 strings s1 and s2 including only letters from ato z. Return a new sorted string, the longest possible, containing distinct letters,
each taken only once - coming from s1 or s2.
Examples:
a = "xyaabbbccccdefww"
b = "xxxxyyyyabklmopq"
lon... |
4f2556eee689b9672cc0ee02bedfc73462b81ce4 | NuclearAck/pythonLearning | /day25/反射.py | 825 | 4.25 | 4 | #反射(用字符串操作类中的属性)
#getattr(对象,属性)获取对象中属性(对象,方法等等)的值,属性是一个字符串,当属性是一个字符串或者用INPUT输入的值的时候
#hasattr(对象,属性)检测对象中是否含有某个属性,其中属性是一个字符串
#setattr(对象,属性,值),给对象设置属性和值
#delattr(对象,属性),删除对象中的某个属性,属性是一个字符串
class Foo:
def __init__(self,name,age):
self.name =name
self.age = age
def show(self):
return '%s... |
ade5cff6ed43551126f440f4b362a514330f93b0 | karthikrangasai/rekomendo | /src/collaborative_model.py | 1,653 | 3.640625 | 4 | import numpy as np
import scipy as sp
from sklearn.metrics import mean_squared_error
from scipy import stats
from sklearn.metrics import precision_score
''' The following functions are used to calculate metrics used to evaluate our recommender systems'''
def rmse(y, y_pred):
'''Root Mean Squared Error Calculation'''... |
1b72ea4cafbcc76d283422adc536c7c1042228f2 | TemistoclesZwang/Algoritmo_IFPI_2020 | /listaExercicios/Lista fabio 1 parte 2/F1_P2_Q3_DIAS.py | 187 | 3.578125 | 4 | # ENTRADA
dias = int(input('Insira o número de dias: '))
# PROCESSAMENTO
semana = int(dias / 7)
resto = dias % 7
# SAIDA
print(f'{dias} Dias são {semana} semana(s) e {resto} dia(s)')
|
961618f58436f4f3bb733691c07fbba60ab13d3d | stepik/SimplePyScripts | /HypotenuseOfTriangle/HypotenuseOfTriangle.py | 1,194 | 3.953125 | 4 | # coding=utf-8
import math
import argparse
__author__ = 'ipetrash'
def createParser():
parse = argparse.ArgumentParser(description=u"Программа высчитывает гипотенузу прямоугольного треугольника")
parse.add_argument("-a", type=int, help=u"Первый катет")
parse.add_argument("-b", type=int, help=u"второй кате... |
274216b3aa7abfa43c401a4bb0f40b69968e0322 | siberian122/kyoupuro | /ABC192/B.py | 202 | 3.71875 | 4 | s = input()
for i in range(len(s)):
# print(i)
if i % 2:
if s[i].islower():
exit(print("No"))
else:
if s[i].isupper():
exit(print("No"))
print("Yes")
|
f155fba6e07368fa23895ea5be3e86091ed6845e | Deanhz/normal_works | /算法题/Leetcode/easy/Plus_One.py | 1,834 | 3.578125 | 4 | '''
2017.9.23
66.
Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.
You may assume the integer do not contain any leading zero, except the number 0 itself.
The digits are stored such that the most significant digit is at the head of the list.
'''
class Solution(object... |
2d09812811dcb3fa8b827356207680522d6e22ba | abdulrafaykhan/Security-with-Python-Code | /threads2.py | 932 | 3.75 | 4 | import threading
import time
class aThread(threading.Thread):
def __init__(self, num, val, count):
threading.Thread.__init__(self)
self.numThread = num
self.valThread = val
self.loopcount = count
def run(self):
print("Starting to run...")
print("Thread No. ", se... |
58239cac2c1c0ab8864a5b6f3962bb365a68a52d | jcranch/Trainset | /base.py | 3,696 | 3.5 | 4 | from datetime import date, datetime, time, timedelta
from warnings import filterwarnings, resetwarnings, warn
class ConversionFailure(Exception):
"""
Unexplained failure.
"""
pass
class IncoherentData(Exception):
"""
Bad data, where good data was expected.
"""
pass
class TrainsetW... |
60e35206d9de9d6be8c15c8112e417f66d304673 | kevmct90/PythonProjects | /Python-Programming for Everybody/Week 11 Regex/Code/Lab 11.1 Regex Introduction.py | 1,863 | 4.53125 | 5 | __author__ = 'Kevin'
# 19/04/2015
# Regular Expression Quick Guide:
# ^ - Matches the beginning of a line
# $ - Matches the end of the line
# . - Matches any character
# \s - Matches whitespace
# \S - Matches any non-whitespace character
# * - Repeats a character zero or more times
# *? - Repeats a character zero or m... |
113d0c7624f021c6bef6373326b7588aa7d07c1f | sbj1811/ud_movie_website | /entertainment_center.py | 3,698 | 3.609375 | 4 | # This is the Main python module
# importing
# media module that is used to store movies info
# fresh_tomatoes will generate html sections for each movies
import media
import fresh_tomatoes
# multiple instances of that Python Class "Movie" from module Media to represent various movies
the_dark_knight= med... |
3f46ca7dd70e36bc3a27552ae939cac8fb7ee900 | behlerbg/AoC-Solutions | /2015/AOC2015_1.py | 641 | 3.875 | 4 | #! python3
## AOC2015_1.py
## Advent of Code 2015 puzzle #1 - "(" == up ")" == down
## Brett Behler 12.28.2018
def get_directions():
with open('2015ChallengeInput1.txt', 'r') as instruct:
return instruct.read()
def eval_directions(directions):
cur_floor = 0
enter_basement = 0
i = 0
for cha... |
60ab705a24dd9f21d7ab569ff4b9565692db769e | Namita123456789/Python_14_Sep-main | /Python_14_Sep-main/Python/SHASHWAT/chessboard.py | 389 | 3.890625 | 4 | for i in range(1,9):
if i%2==0:
for j in range(1,9):
if j%2==0:
print("BLACK", end=" ")
else:
print("WHITE", end=" ")
print()
else:
for j in range(1,9):
if j%2==0:
print("WHITE", end=" ")
e... |
367cef672bc77efd753037389fc90179fae95f58 | shafeeqjadoon/Data-Structures | /Python_notebooks/16-hashmaps.py | 2,379 | 3.875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[30]:
class HashMap:
def __init__(self):
self.size = 10
self.map = [ None ] * self.size
# In[31]:
def _get_hash(self, key):
if type(key) is str:
return len(key) % self.size
elif type(key) is int:
return key % self.size
else... |
9a6f8d889781017a638a1867b85be4ac3518fdb3 | tigeral/polygon | /python/Glasun_labs/lab9.py | 3,650 | 4.5625 | 5 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
""" This application demonstrates the encryption and decryption of texts via using Vigenere cipher. """
class Cipher:
""" Uses Vigenere cipher with specified alphabet to convert text data into encrypted string and vice versa. """
def __init__(self, alphabet, key)... |
6fd495c23ef9b18d5cb0780604594142b3bf7ac7 | RaghavJindal2000/Python | /basics/Python/while_sample.py | 64 | 3.53125 | 4 | i=1
while(i<=10):
print(i," Hello World")
i=i+2
input()
|
0b3184ad9ce87fdfcba2d81ea74d1df69ef39fa2 | HannaKulba/AdaptiveTraining_English | /tasks/part_2/remove_letters.py | 122 | 3.921875 | 4 | word = input()
new_word = ""
for i in range(len(word)):
if i % 2 == 0:
new_word += word[i]
print(new_word)
|
17e132541b20eebfd58e7aa7a9e2c561317da2a9 | JanLandstorfer/PY4E_Jan | /Coursera_P4E/Course_1/20200508_jan_find_max_personal.py | 633 | 3.78125 | 4 | import random
randomlist = []
numbers = input("Enter amount of random numbers: ")
for i in range(0,int(numbers)):
n = random.randint(0,99)
randomlist.append(n)
#print(randomlist)
maxv = 0
minv = 300
count = 0
maxcount = 0
mincount = 0
for i in randomlist:
if i < minv:
minv = i
count = count + ... |
72d88bf92275f6a2875506938eb7928dbac3fef2 | rkachi1/python-certification-course-assignment | /geekspractice/factorial.py | 151 | 4.09375 | 4 | def fact(num):
i = 1
fact = 1
while(i <= num):
fact = fact * i
i+=1
print('Factorial of the number is', fact)
fact(5) |
88916292d5ecf0fdf639672faa89fa366fd7d8fb | vivek-144/1BM17CS144-PYTHON | /1 a (even list).py | 209 | 4.0625 | 4 | a=int(input("ENter the number of array elements"))
arr=[]
even=[]
for x in range(a):
arr.append(int(input("Enter number\n")))
for x in arr:
if (x%2==0):
even.append(x)
print(arr)
print(even)
|
956e06c2c35c8b17539add1aa34c5b9960a16cba | dkoriadi/query-plans-visualiser | /MainFrame.py | 15,031 | 3.640625 | 4 | """
MainFrame.py
This script is called by app.py to display the landing page.
"""
# GUI modules
import tkinter
import db_connection_manager as db_connect
import qep_processor
import query_plan_visualizer as visualiser
import PlansFrame
class LandingPage(tkinter.Frame):
"""
This is the class that allows us... |
e48bbf9d2a36b2baf561b63d4c314249440f87d3 | sounakdey/DeepRosetta | /core/BaseExporter.py | 728 | 3.5625 | 4 | from abc import ABCMeta, abstractmethod, abstractproperty
import os
class BaseExporter:
""" Abstract class modeling a base importer
"""
__metaclass__ = ABCMeta
def __init__(self):
pass
@abstractmethod
def save(self, file_path):
""" Loads a given model file.
It wil... |
8211bc7c5544a7c27ca621e7056c9a249e9a5817 | PatrykLisik/iad | /Zadanie2/SOM/functions.py | 5,646 | 3.6875 | 4 | import numpy as np
from scipy.spatial import distance
def Euklides_dist(x1, x2):
"""
Euclidean distance:
Square root of sum of squared substraction of every dimension
"""
return distance.euclidean(x1, x2)
def RNF(R, distance):
"""
rectangular neighborhood function
R - neighborhood r... |
ad02480f575ef29b7922e26439fb2230f8f32c15 | mbaty001/experimental | /PythonExcercises/Objects/dict.py | 901 | 4.0625 | 4 | '''
Created on Jan 14, 2016
@author: test
'''
a = ['a', 'b', '1']
a.sort() # in place - returns None
sorted(a) # does not change a - returns sorted list
d = {'a':'1'}
d.iteritems() #<dictionary-itemiterator object at 0x7fb123706100>
d.items() # [('a', '1')]
''' dictionary sort '''
import operator
import collection... |
d0147b76c674f9e97ae3b10bebd7b784ceb989d6 | resvirsky/Python | /Item 37UPDATE COMMAND- connection with SQL.py | 207 | 3.53125 | 4 | import sqlite3
with sqlite3.connect("test_renato.db") as connection:
c = connection.cursor()
c.execute("SELECT Name, Species FROM Roster WHERE IQ>30")
for row in c.fetchall():
print row
|
afebcd03d1077fa7f110bde6126db3d0ebd91774 | darlcruz/python-challenge-solutions | /neoOkpara/Phase-1/Day3/calendarPrint.py | 209 | 3.90625 | 4 | import calendar
def calendarKnow(yearNo, monthNo):
print(calendar.month(yearNo, monthNo))
year = int(input("Input the yearNo : "))
month = int(input("Input the monthNo : "))
calendarKnow(year, month)
|
b94e4f604a2a7460f197ad2f188ed8d93b851164 | Mifour/Algorithms | /algoexpert/easy_binary_search.py | 541 | 3.90625 | 4 | """
a functionn that the index of a target in a array, else -1, using dichotmous technique
"""
def binarySearch(array, target):
# Write your code here.
if array[int(len(array)/2)] == target:
return int(len(array)/2)
if array[int(len(array)/2)] < target and int(len(array)/2) > 0:
res = binarySearch(array[int(l... |
cd74e1aef6b9c1b7704f39513e734a20c2c7f9ae | x95102003/leetcode | /invert_binary_tree.py | 329 | 3.5625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def invert_binary_tree(root):
"""TODO: Docstring for invert_binary_tree.
:root: TODO
:returns: TODO
"""
if not root:
return None
else:
tmp_node = self.invertTree(root.right)
root.right = self.invertTree(root.left)
root.left = tmp_node
retu... |
b92eba78cd82db68a9c1058baea50eeea3ad07f6 | miku3920/pythonStudyNotes | /myproject/2021-03/17-Day08/001-tk-messagebox.py | 607 | 3.859375 | 4 | import tkinter as tk
from tkinter import messagebox
win = tk.Tk()
win.wm_title("miku3920")
win.minsize(width=320, height=240)
win.resizable(width=False, height=False)
messagebox.showinfo("showinfo", "Information")
messagebox.showwarning("showwarning", "Warning")
messagebox.showerror("showerror", "Error")
x0 = message... |
ccfe63233b4d3d079e248d72066d24f817ad1b28 | sebaslherrera/holbertonschool-machine_learning | /math/0x02-calculus/17-integrate.py | 548 | 3.75 | 4 | #!/usr/bin/env python3
"""17 Integrate Module """
def poly_integral(poly, C=0):
"""Return an list of the integrated polynomial"""
if (not isinstance(poly, list) or
len(poly) == 0 or
not all(isinstance(x, (int, float)) for x in poly) or
not isinstance(C, (int, float))):
ret... |
900c5521835435eabba2b77e977fc646ec41754b | gekif/CompletePythonProgrammingCourseForBeginners | /Function/xargs.py | 291 | 3.8125 | 4 | # [2, 3, 4, 5]
# [] -> List: can add collection, mutable
# () -> Tuples: cannot modified collection, immutable
def multiply(*numbers):
total = 1
for number in numbers:
# Using augmented assignment
total *= number
return total
print(multiply(2, 3, 4, 5)) |
b4febb4fe6248c21fda71b7c7e938d7cbe035e24 | nguyenngochuy91/companyQuestions | /facebook/onsite/variationDutchFlag.py | 1,641 | 4.375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Nov 4 16:27:33 2019
@author: Huy Nguyen
"""
"""
Variation of Dutch National Flag problem
You have an unsorted array of integers and a function
string getCategory(integer), which deterministically returns 1 of three possible strings: "low", "medium", or "high",
depending on ... |
514749adcbd09faa242952d688c4c462d9ae55e4 | mariehposa/python-and-oop | /kangaroo.py | 268 | 3.828125 | 4 | # Complete the kangaroo function below.
def kangaroo(x1, v1, x2, v2):
if(x2 > x1 and v2 == v1):
return('NO')
elif(x2 - x1) % (v2 - v1) == 0 and (x2 - x1) * (v2 - v1) < 0:
return('YES')
else:
return('NO')
print(kangaroo(0, 2, 5, 3)) |
320b5d4a2bd40976323ad6d178a731ee8a637c10 | tonylixu/devops | /system/input-output/file/write-file-batch.py | 444 | 3.53125 | 4 | '''
How to write data into file as batches
'''
poem = '''There was a young lady named Bright,
Whose speed was far faster than light;
She started one day
In a relative way
And returned on the previous night.
'''
offset = 0
size = len(poem)
print size
chunk = 50
with open('poem.txt', 'xt') as f:
while True:
... |
7aeaaa8c975b65ee671373b0460f6c43035ec433 | Pelero016/Python_Libro | /Ejericio11.6.py | 437 | 3.59375 | 4 | #Ejercicio uno: escribe un programa simple que simule la operación del
#comando grep en Unix. Debe pedir al usuario que ingrese una expresión
#regular y cuente el número de líneas que coincidan con ésta:
import re
er = input("Ingresa una expresión regular: ")
txt = open("m-box.txt")
x=list()
count = 0
for linea in txt:... |
87a8311514083db8c565a1e341cae4df5adbb276 | fynnfreund/LPTHW | /EX03/ex3.py | 475 | 3.890625 | 4 | print "I will now count my apples:"
print "Green ones", 25 + 30 / 6
print "Red ones", 100 - 25 * 3 % 4
print "Now I will count the bananas:"
print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6
print "Is is true that 3 + 2 < 5 - 7?"
print 3 + 2 < 5 - 7
print "What is 3+2?", 3+2
print "What is 5-7?", 5-7
print "Oh, that's why... |
80420ceaef1b02cd6f7f9b6259a965aca0efb2c8 | TorleifHensvold/ITGK-TDT4110 | /Oving3/Torleif/Torleif_03_04_alternerende_sum.py | 1,581 | 3.859375 | 4 | #Hvis du ikke skjønner det, sorry. Var litt hodebry, så du får tenke litt selv også :D
def addisjon(number):
accumulator=0
for i in range(1,number+1):
if i%2:
accumulator = accumulator + i**2#adder med -(i^2)
else:
accumulator = accumulator - i**2#adder med i^2... |
bccd430337c48ec1febdae9e77e060e447f26b7a | dyhmzall/gu_python_1208 | /Popravko_Mikhail_dz_3/task_3_3.py | 1,307 | 3.53125 | 4 | """
3. Написать функцию thesaurus(), принимающую в качестве аргументов имена сотрудников и возвращающую словарь,
в котором ключи — первые буквы имён, а значения — списки, содержащие имена, начинающиеся с соответствующей буквы.
Например:
thesaurus("Иван", "Мария", "Петр", "Илья")
{
"И": ["Иван", "Илья"],
"М": ["... |
b567a0f154af12cb155d913a40ebf7eeaf264ec5 | larsenandtoubroinfotech/python | /test.py | 586 | 3.671875 | 4 | #!/usr/bin/python
path = '/home/test'
name='test'
head = path.split()
print head
#def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
# print("-- This parrot wouldn't", action)
# print("if you put", voltage, "volts through it.")
# print("-- Lovely plumage, the", type)
# print("-- I... |
5e217377bcf4c59f1793cd116a6fadd7f9abb49b | thelegendarysquare/statement-printer | /statement-printer.py | 193 | 4 | 4 | myit = 'y'
mystring = ''
while myit == 'y':
mystring = input('Please enter a statement to print.\n')
print(mystring)
myit = input('Would you like to do it again? y or n: ')
|
df08e0f946c39b0aaa35df04c497a2a7b2ed14d0 | kimdanny/Coding-Questions | /Algorithms/circularArrayRotation.py | 686 | 3.828125 | 4 | # https://www.hackerrank.com/challenges/circular-array-rotation/problem
def circularArrayRotation(arr, k, queries):
for _ in range(k):
arr.insert(0, arr.pop(len(arr)-1))
# print("arr: ", arr) arr: [5, 6, 7, 8, 1, 2, 3, 4]
for x in queries:
print(arr[x])
import collections
def circu... |
d2baa5dc761bf9f7eed117a00d62f45854f53a89 | A01376622/Registro-Dos | /Ej2.py | 749 | 3.890625 | 4 | #Autor: Michelle Sánchez
#Programa de adivina un número
import random
def main():
numeroAleatorio = random.randint(1,10)
print(numeroAleatorio)
adivina = int(input("¿Cuál es el número?"))
veces = 0
while adivina != numeroAleatorio and veces <= 2:
veces += 1
print(... |
8965be4232aebd820044da410f4cdcee0ebc7dec | Jaconhunt/Python-Advanced | /Python_100.py | 1,179 | 3.890625 | 4 | #https://www.runoob.com/python/python-100-examples.html
#https://blog.csdn.net/github_39655029/article/details/82932848
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019-9-8 13:37
# @Author : JaocnHunt
# @Site :
# @File : Python_100.py
# @Software: PyCharm
#1. 三位数
def main():
n = 0
for i... |
c9c91e0ecc3b95f4971ac469a923516085a0e005 | agreppi/Project-Euler | /isPalindrome.py | 193 | 3.71875 | 4 | def isPalindrome(num):
result = True
str_num = str(num)
for i in range(len(str_num) // 2):
if str_num[i] != str_num[-i-1]:
result = False
return result |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.