blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
ceff26dafa21c28c83de4b79f60fe60ac6cd70de | jamesbarone/ebay_app | /get_UPC.py | 482 | 3.71875 | 4 | '''The get UPC module contains the get_UPC function, which gets input from the user in the form of a
UPC. '''
def get_UPC():
'''Gets a UPC from the user, which will be used to guide the product search.
'''
user_UPC = input(
'Please enter the keyword of the product you would like to se... |
574895622999fa9470edeaab188cd25061e3806b | Brian-Mascitello/Advent-of-Code | /Advent of Code 2021/Day 3 2021/Day3Q2 2021.py | 1,473 | 3.578125 | 4 | """
Author: Brian Mascitello
Date: 12/5/2021
Websites: https://adventofcode.com/2021/day/3
Info: --- Day 3: Binary Diagnostic ---
--- Part Two ---
"""
import pandas as pd
def df_to_int(df):
df = df.astype(str)
df['String'] = df.apply(''.join, axis=1)
return_str = df['String'... |
f8b449a31b31dda38c68fd4cc426fd53ece2eb97 | yugwas/python-functions-worksheet | /lessons/03_say_hello/say_hello.py | 257 | 3.71875 | 4 | #Line 2 DEFINES the function say_hello()
def say_hello(name):
print("Hello " + name)
#Line 6 CALLS the function and PASSES in the ARGUMENT "AL" to a LOCAL VARIABLE name. VARIABLES that have ARGUMENTS assigned to them are called PARAMETERS
say_hello("Al") |
253cce6a2840008dd615ede3408ddd16df616030 | vaibhav5219/Tic-Tac-Toe | /Tic Tack Toe.py | 2,269 | 3.828125 | 4 | from introduction import intro
import os
intro()
print("Enter 1st player name :- ")
p1=input()
print("Enter 2nd player name :- ")
p2=input()
cross="X"
circle="O"
a=[""," "," "," "," "," "," "," "," "," "]
def print_table(n):
os.system("cls")
print("\t WELCOME TO ... TIC TAC TOE ...\n")
print(" | ... |
ba293a3960ba5ea08e2f661ba42d96845fc1f5e4 | nicefuu/leetCode-python3 | /int0804.py | 1,057 | 3.546875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/4/26 1:16
# @Author : Fhh
# @File : int0804.py
# Good good study,day day up!
"""
幂集。编写一种方法,返回某集合的所有子集。集合中不包含重复的元素。
说明:解集不能包含重复的子集。
示例:
输入: nums = [1,2,3]
输出:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]"""
from typing import... |
60c83d0b6259823577e11c545825211e26fc9e29 | pauloMateos95/python_basico | /conversor_avanzado.py | 791 | 3.78125 | 4 | menu = """
Bienvenido al conversor de monedas
1- Pesos colombianos
2- Pesos argentinos
3- Pesos mexicanos
Elige una opción """
opcion = input(menu)
def conversor(tipo_peso):
if tipo_peso == 'colombianos':
valor_dolar = 3875
elif tipo_peso == 'argentinos':
valor_dolar = 65
elif tipo_peso ... |
0d0510d5c0b474ca793ce8f9010a65f405dad5cb | 10mincode/10mincode | /dicerollingsimultar.py | 483 | 4.0625 | 4 | import random
print("Welcome to dice rolling simultar")
input("Press Enter to continue")
p1name=input("Enter Player 1 Name: ")
p2name=input("Enter Player 2 Name: ")
print(f"Rolling rice for {p1name}...")
p1=random.randint(1,6)
print(p1)
input(f"Press Enter to roll dice for {p2name}")
print(f"Rolling rice for... |
94dd8286e5050f4c25ed4f3f8662fc25b0061888 | mblaszkiewicz/clouds-url-shortener | /url-shortener/db_urls.py | 1,419 | 3.515625 | 4 | class Database:
def __init__(self):
self.url_mappings = {}
self.id = 0
def delete_mappings(self):
"""Deletes all mappings stored in the memory"""
self.url_mappings.clear()
self.id = 0
def delete_mapping(self, idx):
"""Deletes single mapping identified by the... |
83793434f353641a72ffd21b3b14168d3fa4343a | dewmanpower/Dewman | /ex7.py | 162 | 3.59375 | 4 | "https://www.practicepython.org/exercise/2014/03/19/07-list-comprehensions.html"
a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
print([ i for i in a if i%2 == 0])
|
a322a6c261c2b80b9c0e161d3b104e252d1c3014 | dikaa7/kripto4 | /rsa.py | 792 | 3.65625 | 4 | import random
from util import is_prime, gcd, modinv
def generate_keypair(p, q):
if not (is_prime(p) and is_prime(q)):
raise ValueError('Both numbers must be prime.')
elif p == q:
raise ValueError('p and q cannot be equal')
n = p * q
phi = (p-1) * (q-1)
e = random.randrange(1, phi... |
d7898393dd7aa1bf25e7771fdc30c1632cd5f2e5 | Hello-Raviraj/Python-Programs | /Palidrome.py | 236 | 3.9375 | 4 | x="hello"
x.casefold()
y=reversed(x) #reversed function return reverse object
if list(x)==list(y): #so for comparision we convert them into list and then compare
print("its palindrome")
else:
print("no palindrome")
|
51cb575335bad84500d858cde3afb2e769792c6c | MahirRatanpara/pythonLearn | /14_mathFunctions.py | 358 | 3.921875 | 4 | import math
# there are various mathematical function present in the math module
# which helps us perform various complex math operation
x = 2.9
# round off the above number
y = round(x)
print(y)
x = -13
# abs return the mod value of our variable
y = abs(x)
print(y)
# trying few methods from math module
x = 3.6
prin... |
95630267a55a46d7774e5103f337f229df517829 | MaPing01/Python100 | /34.py | 588 | 3.921875 | 4 | #!usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Ma Ping
class A():
def __init__(self):
self.name = 'Aname'
def go(self):
print('a go a')
class B():
def go(self):
#super(B, self).go()
print('b go b')
class C(A):
def go(self):
super(C, self).go() #python2... |
0025e3166ed1629381c1f4b44b80f341ad4fa8c3 | jarvis-1805/DSAwithPYTHON | /Stacks and Queues/Queues/Reverse_Queue.py | 2,129 | 4.125 | 4 | '''
Reverse Queue
You have been given a queue that can store integers as the data. You are required to write a function that reverses the populated queue itself without using any other data structures.
Input Format:
The first list of input contains an integer 't' denoting the number of test cases/queries to be run.
T... |
b3a0b8cc2bd342ae79efaf11985c62de6e664aa1 | pramnora/python | /language/data/complex/list/array02.py | 823 | 4.625 | 5 | # python arrays can store mixed data types, including: number/string/numeric expression/
# and, even, include other sub-arrays, as well
num = [1,"111+111",111+111,"one",[1,2,3]]
for eachArrayItemNo in num:
print eachArrayItemNo
# python arrays can be searched using a specific array 'index number';
# the number coun... |
eaf677cc3a1e027c96f5ec68af817bdde7e0bf0f | Prins-Butt/uni-pro-troubles | /task4.py | 278 | 4.125 | 4 | def displayLargest(num1, num2):
if num1 > num2:
print("The first number is larger")
elif num2 > num1:
print("The second number is larger")
else:
print("Both numbers are equal")
displayLargest(7, 5)
displayLargest(1, 3)
displayLargest(4, 4)
|
785f7dfc15f43c438f645f638f4907dfc0936d3f | masoom-A/Python-codes-for-Beginners | /product odd even.py | 188 | 4.09375 | 4 | ## a=int(input('enter a number'))
for x in range (1,5,1):
p=x**2
if p%2==0:
print (x)
else:
print ('' "is a odd number",x)
|
484f48e2d0250c014a1f7d10229042c84d46e818 | fentonmartin/sample-python | /v-class 1 Post-test.py | 616 | 3.78125 | 4 |
x = (1,2,3)
print len(x)
for y in x:
print y,
'''a=10
b=5
d=0
if a and b or c or not d:
print abs(b-a)
'''
'''
x=3
if x == 0:
print x-3
elif x == 1 or x == 2:
print x
else:
print x-3*2
'''
'''
x = (1,2,3)
print len(x)
for y in x:
print y,
x[2]=4,
'''
'''n=5
while n<9:
print... |
f0c614d588b64c749ce9fecbb845f1912042cc1f | RajibDasBhagat/Basic-programs-python | /convertToBin.py | 658 | 3.609375 | 4 | class stack:
def __init__(self):
self.items=[]
def push(self,item):
return self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items)-1]
def isEmpty(self):
return self.items == []
d... |
9262ec198c6a986f9cb87bf86202d71f92d7e244 | teethzp/temp | /code1/totalinfo.py | 493 | 3.6875 | 4 | import sys,socket
def getipaddrs(hostname):
"""Given a host name,perform a standard (forward) lookup and return a list of IP addresses for
that host."""
result=socket.getaddrinfo(hostname,None,0,socket.SOCK_STREAM)
return [x[4][0] for x in result]
hostname=socket.gethostname()
print "Host name:",hostname
print ... |
65c991247455a58ea6ceb899109e5d5a19d71b92 | Komal97/DS-Algortihms | /13. Binary Search Tree/Python/No_of_unique_bst.py | 1,585 | 4 | 4 | '''
https://practice.geeksforgeeks.org/problems/unique-bsts/0
Find number of unique BST's with N nodes and nodes are numbered from 1 to N
This can be find out using catalan's number
'''
# using recursion
def find_catalan(num):
if num == 0:
return 1
ans = 0
for i in range(1, num+1):
ans ... |
764a8150c8e4811c1c14ccfff0a1a14b5bdb81ee | CueOminousMusic/LaunchCode | /Project_Requirements.py | 4,798 | 3.5625 | 4 | Project Overview
The capstone project is one of the most important pieces of landing the perfect LaunchCode apprenticeship. This project will be one of the biggest ways that the LaunchCode evaluation team will verify that you're job-ready, and it should be something that you're proud to show off to a potential employe... |
35fca92096e19c8ab4adc30f8c17c235e7500615 | stuf/pyles | /pyles/_argparse.py | 828 | 3.59375 | 4 | """Provide argument parsing."""
import sys
from argparse import ArgumentParser, FileType
parser = ArgumentParser(prog='pyles', description='Collect pyles of data!')
parser.add_argument('inpath',
type=str,
help='Path to directory to search through')
parser.add_argument('-e', '-... |
16074783ba5ecabe7dbc9092ba9ff3b35517183e | vugutsa/Password-locker | /user.py | 1,609 | 3.84375 | 4 | class User:
"""
Class that generates new instances of contacts
"""
user_list = [] # Empty user list
def __init__(self,user_name,password):
# docstring removed for simplicity
self.user_name = user_name
self.password = password
def save_user(self):
'... |
ee9460306b755e0a3e6d1ad9fce997dd30b99ee3 | IronE-G-G/algorithm | /leetcode/101-200题/151reverseWordsInAString.py | 826 | 4.28125 | 4 | """
151 翻转字符串里的单词
给定一个字符串,逐个翻转字符串中的每个单词。
示例 1:
输入: "the sky is blue"
输出: "blue is sky the"
说明:
无空格字符构成一个单词。
输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。
如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-words-in-a-string
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
class Solution:
... |
b60119b2eff862ee06dfa94fad9fb622f0433f9a | Gohos322/HW4 | /Required by Assignment/ms.py | 486 | 3.546875 | 4 | '''
Created on 12 gen 2019
@author: Lorenzo Guenci (Student ID 1532651)
'''
def read_file ():
f = open("<path_to_file>", "r")
i=0
n=""
m=""
for x in f:
if i==0:
n=x.replace("\n", "")
if i==1:
m=x.replace("\n", "")
i+=1
return n,m
... |
b510c067bdd922d49141362f43555112cd554e21 | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_148/198.py | 749 | 3.734375 | 4 | import sys
from bisect import bisect_right
def find_le(a, x):
'Find rightmost value less than or equal to x'
#print x
#print a
i = bisect_right(a, x)
if i:
#print "Found"
del a[i-1]
return True
return False
numCases = input()
for case in range( 1, numCases + 1 ):
N, S = [ int(x) for x in ra... |
80f0ee2ba2ba77730ff1153576e451db527b3165 | cerebrovoice/cv-monorepo | /cerebrovoice/capture/prompts.py | 6,655 | 3.515625 | 4 | import argparse
import json
import os
from collections import deque
from datetime import datetime
from random import choice, sample
from time import time
import pygame
# PYGAME SETUP
pygame.init()
screen = pygame.display.set_mode((640, 480))
clock = pygame.time.Clock()
done = False
# ARG PARSING
parser = argparse.Ar... |
4e61f61d091bcd26efd5cb8e80ecbe21411ceae0 | j1fig/euler | /3/main.py | 946 | 3.90625 | 4 | import sys
import cProfile
arg = int(sys.argv[1])
def _generate_next_prime(last_prime):
nextPrime = last_prime + 1
while True:
testNumber = 2
while nextPrime % testNumber != 0:
testNumber += 1
if testNumber == nextPrime:
yield nextPrime
nextPrime += 1
... |
c08680de268ca310aea325d4861e353c72661c77 | Jonathas-coder/Python | /EX 60 COM FOR.py | 119 | 3.75 | 4 | n=int(input('Qual o fatorial: '))
fator=n
for c in range (n-1,0,-1):
fator*=c
print(f'Fatorial de {n} é {fator}')
|
c3a98056d8267129bbd34889953aded0fe191d9d | diogogarbin/curso_python | /if_formatacao.py | 1,355 | 4.3125 | 4 | #!/usr/bin/python3
#ola = '''
#Sejam Bem Vindos
#'''
#print(ola)
#nome = input ('Digite seu nome: ')# A função imput pausa o script e esper interação do usuário
#print(nome.lower()) #lower() deixa tudo em minúsculo tittle() deixa em formato de títuli e upper() tudo minúsculi
#Exercício Atribuir dois número em var... |
9e76eaf601ba2dd9d57fdb82074b2ebc68cb1924 | kyungha47/python | /36. class_inheritance/method_overriding.py | 400 | 3.671875 | 4 | #method overriding : subclass에서 base class의 메서드를 새로정의
class Person:
def greeting(self):
print('hi')
class Student(Person):
def greeting(self):
super().greeting()
# base class의 메서드 호출하여 중복줄임
print('nice to meet you')
# 기능은 유지하면서 새 기능을 추가
kyungha = Student()
kyungha.gree... |
fba8cef6ba16f7c40024dee0bdc262e9273e7542 | LubosKolouch/adventofcode_2019 | /08/t8.py | 1,016 | 3.5625 | 4 | #! python3
# I could not come with anything better than np solution in Reddit, so took it as
# a learning material...
from pprint import pprint
import numpy as np
# remember - best to read, strip and reshape in one line
with open('input', 'r') as data:
data = np.array(list(data.read().strip())).reshape((-1, 6, 2... |
b6fe044dfdc91efcc2c2075ef103f2cfcb9e95b1 | ahnjongin/BOJ | /1934.py | 214 | 3.59375 | 4 | def gcd(A, B):
if (A%B) == 0:
return B
if B == 0:
return A
else:
return gcd(B, A%B)
T=int(input())
for i in range(T):
A,B= map(int, input().split())
print(int(A*B/gcd(A,B))) |
de01ddb5fa3e9d63a73cfa7f04ddfa65bcb8580f | ZimingGuo/MyNotes01 | /MyNotes_01/Step02/6-MySQL/day02_15/exercise01_register_login_edited.py | 1,561 | 3.625 | 4 | # author: Ziming Guo
# time: 2020/4/19
'''
模拟注册登录
'''
import pymysql
# 连接数据库
db = pymysql.connect(host='localhost',
port=3306,
user='root',
password='19971023gzm',
database='stu',
charset='utf8'
... |
5a448b8a57d1003b1898e02aeb1751764d0180d3 | Vlek/Project-Euler | /48.py | 223 | 3.703125 | 4 | #Problem 48
def selfpower(to):
'''adds all of the self powers together up to to'''
return sum([ num**num for num in range(1, to + 1) ])
if __name__ == '__main__':
print(str(selfpower(1000))[-10:])
|
85e7c0f23a71e7e76892ea61f1c99f77f03a73cd | TiagoTitericz/chapter2-py4e | /Chapter9/exercise3.py | 702 | 3.96875 | 4 | '''Exercise 3: Write a program to read through a mail log, build a histogram using a dictionary to count how many messages have come from
each email address, and print the dictionary.
Enter file name: mbox-short.txt
{'gopal.ramasammycook@gmail.com': 1, 'louis@media.berkeley.edu': 3,
'cwen@iupui.edu': 5, 'antranig@care... |
fd9235cd1884516449e0f5842da8d93e7c427587 | mrgentle1/koss_algorithm | /과제/2주차/boj_1918.py | 1,025 | 3.546875 | 4 | import sys
input = sys.stdin.readline
class Stack:
def __init__(self):
self.st = []
def push(self, e):
self.st.append(e)
def pop(self):
rt = self.st[-1]
self.st = self.st[:-1]
return rt
def top(self):
return self.st[-1]
def empty(... |
d6a6c4db9b7aa991ecc0c7458b47681a92d984f1 | Thereodorex/skillsmart_algo | /Part1/Task5/Queue_stack.py | 1,590 | 4.125 | 4 | class Node:
def __init__(self,value):
self.value = value
self.next = None
class Stack:
'''
Реализация стека на списке
'''
def __init__(self):
self.head = None
self._size = 0
def size(self):
return self._size
def pop(self):
'''
Слож... |
ada4239debbb5030bce6ea00d7182c638ccda05b | zhangmeilu/VIP8study | /推导式.py | 3,862 | 3.953125 | 4 | # 作用:用一个表达式创建一个有规律的列表或控制一个有规律的列表
# 列表推导式又叫列表生成式
# 需求:创建一个0-10的列表
# while循环实现
from homework import num
list1 = []
i = 0
while i < 10:
list1.append(i)
i += 1
print(list1)
# for循环实现
list1 = []
for i in range(10):
list1.append(i)
print(list1)
# 带if的列表推导式
# 需求:创建0-10的偶数列表
# 方法一:range()步长实现
list1 = [i for i in... |
0be5717ef766e8011878820b1fe3aa18590efb1a | shiyushui5/python_py | /y01083.py | 432 | 3.96875 | 4 | from y01083f import Answer_survey
question = "what language did you first to learn?"
my_survey = Answer_survey(question)
my_survey.show_question() #显示问题并存储答案
print("Enter 'a' at any time to quit.\t")
while True:
response = input("language: ")
if response == 'a':
break
my_survey.store_response(respo... |
e4492ad5cdd01de60b20e0786269ccc5350e0efb | yxserious/python_learning | /string.py | 608 | 3.6875 | 4 | name = 'steven'
result ='eve' in name
print(result)
#not in
result = 'tv' not in name
print(result)
#r 保留原格式 有r就不转义,没有r则转义
name = 'jason'
print(r'%s: \'hahaha!\''%name)
filename = 'picture.png'
print(filename[5]) #通共【】结合位置获取字母,只能一个
#包前不包后
print(filename[0:7])#0123456
print(filename[3:])#省略后面就一直到结尾
print(filename[... |
946d5e5bb9f91c240ba202dbaa26e0e8d31bb5fe | AdamZhouSE/pythonHomework | /Code/CodeRecords/2989/58575/252564.py | 264 | 4.03125 | 4 | str1=input()
str2=input()
str3=input()
if str1>str2:
temp=str1
str1=str2
str2=temp
if str3<str1:
print(str3,"\n",str1,"\n",str2,sep="")
elif str3<str2:
print(str1,"\n",str3,"\n",str2,sep="")
else:
print(str1,"\n",str2,"\n",str3,sep="")
|
6c630d9124b309ea802ca0288a6b3fbba18fcdc2 | feelthecoder/python_practice | /dict_sets_comprehension.py | 524 | 4.28125 | 4 | # Dictionary comprehension used to create dictionary in one line
square = {num:num**2 for num in range(1,11)} # Dictionary of key square
print(square)
#create a dictionary of character count of a string
String = "Vikas is a good programmer"
dict_count = {i:String.count(i) for i in String}
print(dict_count)
#dict ... |
35a71f8822d4ea2036c2a6f4122c5298c2fb5ba5 | glambertation/ToGraduate | /Leetcode/python/coins/500/567.py | 1,387 | 3.734375 | 4 | '''
Given two strings s1 and s2, write a function to return true if s2 contains the permutation of s1. In other words, one of the first string's permutations is the substring of the second string.
Example 1:
Input:s1 = "ab" s2 = "eidbaooo"
Output:True
Explanation: s2 contains one permutation of s1 ("ba").
Example 2:
I... |
64be083c8d5355b43b631efb0d4fe59caca265cc | Zhenye-Na/leetcode | /python/293.flip-game.py | 1,064 | 3.78125 | 4 | # [293] Flip Game
# Description
# You are playing the following Flip Game with your friend:
# Given a string that contains only two characters: `+` and `-`,
# you can flip two consecutive `"++"` into `"--"`, you can only flip one time.
# Please find all strings that can be obtained after one flip.
# Write a program... |
943b197ff725026ba3c77de689df186f475d8bc0 | rkks/refer | /script-prog/python/Python-Prog-on-Win32/ch06_doubletalk/doubletalk/dictlist.py | 1,721 | 3.515625 | 4 | # dictionary queries
"""dictlist.py
Assume we have a list of dictionaries. This extracts tabular data
from them, and provides common operations useful on such a list
"""
import doubletalk.datastruct
def GetKeys(dictlist):
"lists all the keys in all the dictionaries"
s = doubletalk.datastruct.Set()
fo... |
924c97c4403a8f8fe3d63e5c55e4fd9ece15e682 | uterdijon/evan_python_core | /_class_code/02_mammals.py | 1,903 | 4.1875 | 4 | class Animal(object):
"""docstring for Animal"""
body = True
def __init__(self):
self.substance = "carbon"
class Mammal(Animal):
"""
A clade of endothermic amniotes distinguished from reptiles
(including birds) by the possession of a neocortex (a region of the
brain), ha... |
b15e2d2e4505c23ab001cb5e6ef2b61c3d24e1ab | Roshni-jha/ifelse | /nested if else-pyt/strong num.py | 105 | 3.75 | 4 | num=int(input("enter the number"))
i=0
while i<=100:
if i%1!=0 and i%2!=0:
print(i)
i=i+1 |
e4dadc4361c77eda4bde15a4828d37bc14712e3e | SaurabhPal25081995/Full-Python-Course | /Ex 5- Pattern Printing.py | 410 | 3.796875 | 4 | # Pattern is n = no. of rows
"""
*****
****
***
**
*
"""
row = int(input("Enter no. of rows "))
bol = input("Type 1 for True, 0 for False")
var = bool(bol)
print(bol)
if bol==True:
for i in range(0,row):
for j in range(0,i+1):
print("*",end=" ")
print("\r")
else:
for i in range(0, ... |
ea182e879f2e582b3cc0397ecc9425c0408d5b25 | zengm71/Dojo | /Python/Assignments/UserWithBankAccount/userWithBankAccount.py | 1,766 | 4.15625 | 4 | class BankAccount:
def __init__(self, int_rate, balance):# now our method has 2 parameters!
self.account_balance = balance # the account balance is set to $0, so no need for a third parameter
self.int_rate = int_rate
def deposit(self, amount):
self.account_balance += amount
ret... |
cf84a06ed83c2aeada502e575156154f34d523c3 | trygvels/AST1100 | /Trygveoblig1.py | 2,400 | 4.125 | 4 | #Problem 7.2
#-------------------------Comments------------------------
"""
In this task we assume that since Beagles mass is so small
ralative to Mars, that Mars' velocity and position after
the initial values are negligible.
We are only looking at Beagles position and velocity,
using the velocity to calculate the po... |
864b491f8e35abce206d69f229e2c0dbadc50f35 | Biddy79/eclipse_python | /OOP/Classes/__init__.py | 1,901 | 4.59375 | 5 | #first we must understand that in python underscores are used before the nameing of
#methods. They act just the same as methods/functions below is and example of this
a = 12
b = 4
print(a + b)
# __add__ is a function which works the same as the + operator take note of the dot
# notation before calling and () at the e... |
8ccce9acb0afec392646c43ea685540a344d373b | tahsinozden/MyDevelopmentEnv | /CodeSnippets/Python/tests.py | 531 | 3.703125 | 4 | from unittest import TestCase
from main import Animal
class TestAnimal(TestCase):
def test_myName(self):
animal = Animal('tiger', 'predator')
self.assertEqual(animal.myType, 'My type is tiger')
def test_str_overloading(self):
animal = Animal('lion', 'king')
self.asser... |
49ddfefada05cdef9adf903730d629679e6d193a | trvsed/100-exercicios | /ex004.py | 394 | 3.8125 | 4 | var1 = input ('Digite algo: ')
print('O tipo primitivo desse valor é',(type(var1)))
print('Só tem espaços?',var1.isspace())
print('É um número?',var1.isnumeric())
print('É alfabético?',var1.isalpha())
print('É alfanumérico?',var1.isalnum())
print('Está em maiúsculas?',var1.isupper())
print('Está em minúsculas?',... |
d6f6c0c92a4350525cefab213576391d4c05e9c4 | Anjali-Poornima666/Passbook | /a.py | 603 | 3.53125 | 4 | import sys
import msvcrt
def win_getpass(prompt='Password: ', stream=None):
"""Prompt for password with echo off, using Windows getch()."""
import msvcrt
for c in prompt:
msvcrt.putch(c)
pw = ""
while 1:
c = msvcrt.getch()
if c == '\r' or c == '\n':
break
... |
dc363a4634b61435e6a2d4cfed354b08b999a8c6 | varunchandan2/python | /vacationCost.py | 536 | 3.890625 | 4 | try:
user = int(input('Please enter a range of numbers in 4 to 16 weeks: '))
except:
print("ERROR! Please enter number")
else:
for num in range(1,17):
while user < 17:
if user >= 4 and user <= 6:
print("Rent cost: $3080")
elif user >= 7 and user <= 10:
... |
3417c82809c064f521ca7b598607746d036b03ad | LXZbackend/Base_python | /0815/NameLegal.py | 621 | 3.640625 | 4 | #coding=utf-8
#写一个程序,判断用户输入的标识符是否合法,根据数字,字母下划线等去判断!
#利用正则表达式.
import re
myList = []
#循环的的将输入的字符串添加到列表中
while True:
inputName = raw_put("请输入标识符")
if inputName == '':
break
else
myList.append(inputName)
#遍历这个列表,和正则想匹配
for x in myList:
if re.match('[A-Za-z]',s):#判断是否是由大小写字母组成 通过进入下面一个
if re.search('[_]|\w',s):#... |
5f61584f31fcab67e8d13d321d2ffc462ed2b3c8 | anuraghakeem/da | /7.py | 830 | 3.75 | 4 | import random
import time
def partion(a,first,last):
pivot=a[first]
left=first+1
right=last
while True:
while (left<=right and a[left]<=pivot):
left=left+1
while (right>=left and a[right]>=pivot):
right=right-1
if right<left:
break
... |
da4e953bd96311b6bd5ad2d1ff30f1baf6ad0012 | JulyKikuAkita/PythonPrac | /cs15211/LongestSubstringWithAtLeastKRepeatingCharacters.py | 8,272 | 3.8125 | 4 | __source__ = 'https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/'
# https://github.com/kamyu104/LeetCode/blob/master/Python/longest-substring-with-at-least-k-repeating-characters.py
# Time: O(26 * n) = O(n)
# Space: O(26) = O(1)
#
# Description: Leetcode # 395. Longest Substring with... |
35892074dbfa13e334042edef7eeb736df23b25e | mnihatyavas/Python-uygulamalar | /Brian Heinold (243) ile Python/p32405.py | 1,481 | 3.796875 | 4 | # coding:iso-8859-9 Trke
from collections import *
dizge = "Bu fonksiyon verili dizge ierik karakterlerinin tekrar saysn karakter-tekrar ifti olarak ilk-rastlanan srada ierir."
sayar = Counter (dizge)
print ("sayar=Counter(dizge):", sayar)
print ("\nlist(sayar.items()):", list (sayar.items()) )
print ("\n... |
e84b116626c4bc88c4b54b95dfd8dd32f262b9b3 | Aasthaengg/IBMdataset | /Python_codes/p02819/s147614898.py | 332 | 3.703125 | 4 | X = int(input())
n = 10**6
is_prime = [True] * (n + 1)
is_prime[0] = False
is_prime[1] = False
for i in range(2, int(n**0.5) + 1):
if not is_prime[i]:
continue
for j in range(i * 2, n + 1, i):
is_prime[j] = False
for i, p in enumerate(is_prime):
if i >= X and p is True:
print(i)
... |
0a08c03796ba7e25c3d86c1e39d1263991435de6 | seany-web/Number-Guessing-Game | /guessing_game.py | 2,618 | 4.3125 | 4 | import random
def start_game():
# print welcome message when a player starts the application
print('?????????????????????????????????????????????????????\n\n')
print(' WELCOME TO THE NUMBER GUESSING GAME\n\n')
print('?????????????????????????????????????????????????????\n\n')
#set variabl... |
91e404df098e37cc0b3d13b8ba9c862ee3db08d5 | ashraf-a-khan/Leetcode-Python | /BalancedString.py | 393 | 3.71875 | 4 | """
1221. Split a String in Balanced Strings
"""
class Solution:
def balancedStringSplit(self, s: str) -> int:
count = 0
stack = 0
for i in s:
if i == 'L':
stack -= 1
elif i == 'R':
stack += 1
if sta... |
470637a7ccf2812a2d3c9472167eea3ffc7634b7 | lightmanca/InterviewPrep | /DataStructures/LinkedStack.py | 1,436 | 4 | 4 | from DataStructures.LinkedListNode import LinkedListNode
class LinkedStack:
head = None
num_items = 0
def __init__(self, initial_stack=None):
# if you specify an initial stack items will be pushed from left to right.
if initial_stack:
for item in initial_stack:
... |
86daf6868b04b5ef1ad8371e72ce2e2aa36c8267 | PeterBeattie19/Daily-Coding-Problem | /Problem_118.py | 128 | 3.59375 | 4 | arr = list(map(int, input().split()))
def sort_square(x):
return sorted(map(lambda y: y**2, x))
print(sort_square(arr))
|
3bcd4069c342c636df752509799d1d90df3d6542 | goodDev-junhyuk/Pandas_Excercise | /P_Exam05.py | 372 | 3.671875 | 4 | import pandas as pd
# 리스트를 이용하여 한 행씩 추가해서 데이터프레임을 생성.
columns = ['KOSPI', 'KOSDAQ']
index = [2014, 2015, 2016, 2017, 2018]
rows = []
rows.append([1915, 542])
rows.append([1961, 682])
rows.append([2026, 631])
rows.append([2467, 798])
rows.append([2041, 675])
df = pd.DataFrame(rows, columns=columns, index=index)
print... |
2cf311dd94660f96acd73a214bc19d1b884c8679 | sanekvery/Python_Algos | /Урок 2. Практическое задание/task_9/task_9_1.py | 1,242 | 4.03125 | 4 | """
9. Среди натуральных чисел, которые были введены, найти
наибольшее по сумме цифр. Вывести на экран это число и сумму его цифр.
Пример:
Введите количество чисел: 2
Введите очередное число: 23
Введите очередное число: 2
Наибольшее число по сумме цифр: 23, сумма его цифр: 5
ЗДЕСЬ ДОЛЖНА БЫТЬ РЕАЛИЗАЦИЯ ЧЕРЕЗ ЦИКЛ
""... |
26f7291e450f8910d98dd88a9078aa755d658177 | AbdullahElian1/data-structures-and-algorithms | /python/code_challenges/insert_sort/insert_sort/insert.py | 238 | 4.09375 | 4 | def insertionSort(arr):
for i in range(1,len(arr)):
j=i-1
temp=arr[i]
while j >=0 and temp < arr[j]:
arr[j+1]=arr[j]
j=j-1
arr[j + 1] =temp
return arr
arr=[1,6,9,33,55,77]
print(insertionSort(arr))
|
eabb98437ce3c17d8c8b0968f2a582b9f201bb2e | rangijayant15/Numerical_Analysis | /gauss_jacobi.py | 852 | 3.75 | 4 | import numpy as np
size=int(input("enter the size of matrix -->"))
A=np.zeros((size,size))
b=np.zeros((size,1))
X=np.zeros((size,1))
print("Enter the A matrix for Ax=b\n")
for i in range (0,size):
for j in range (0,size):
print ('entry in row: ',i+1,' column: ',j+1)
A[i][j] = int(input())
print("Enter the b vect... |
2d2974ceb597cd81fdbbbb6c8352e72a732dcb49 | beigerice/LeetCode | /284.py | 771 | 4.125 | 4 | class PeekingIterator(object):
def __init__(self, iterator):
"""
Initialize your data structure here.
:type iterator: Iterator
"""
self.i = iterator
self.n = None
def peek(self):
"""
Returns the next element in the iteration without advancing the ... |
86403347075e832f4d63b7d57f61431d9e8dbae4 | ii6uu99/ipynb | /python-note/python-programs-set-1-master/exercise_16.py | 950 | 4.53125 | 5 | print(
'-----------------------------------------\n'\
'Practical python education || Exercise-16:\n'\
'-----------------------------------------\n'
)
print(
'Task:\n'\
'-----------------------------------------\n'\
'Write a Python program to get the difference between a given number and 17, if the number... |
2889e220daa638c5055b5388ad553366dd79eb6b | SATHANASELLAMUTHU/MYPROJECT | /B43.py | 91 | 3.6875 | 4 | s1=raw_input("Enter the s1 string:")
s2=raw_input("Enter the s2 string:")
s=s1+s2
print(s)
|
a66b50e1d38eb7981b9baf416fa301ab04c69d88 | ivanmilevtues/python101 | /lesson_4/tasks.py | 854 | 3.90625 | 4 | def simplify_fraction(fraction):
frac_list = list(fraction)
a = min(frac_list)
for i in range(a + 1, 1, -1):
if frac_list[0] % i == 0 and frac_list[1] % i == 0:
frac_list[0] //= i
frac_list[1] //= i
return tuple(frac_list)
print(simplify_fraction((3, 9)))
print(simplify_... |
eb3cbcb200931746be2ce09382c166ffd2dcb52b | GeertenRijsdijk/Theorie | /code/algorithms/simann.py | 3,103 | 4.21875 | 4 | '''
simann.py
Authors:
- Wisse Bemelman
- Michael de Jong
- Geerten Rijsdijk
This file implements the simulated annealing algorithm.
Parameters:
- grid: the grid object
- T: initial temperature
- cooling_rate: amount the temperature decreases each iteration
- stopT: the temperature at which the algor... |
d689ca495f846c971d86a00ef8448d92493ed2bf | funnydog/AoC2018 | /day17/day17.py | 3,370 | 3.546875 | 4 | #!/usr/bin/env python
import sys
import re
UP = (0, -1)
RIGHT = (1, 0)
DOWN = (0, 1)
LEFT = (-1, 0)
def add(a, b):
return (a[0]+b[0], a[1]+b[1])
class Map(object):
def __init__(self, txt):
vertical = re.compile(r"x=(\d+), y=(\d+)..(\d+)")
horizontal = re.compile(r"y=(\d+), x=(\d+)..(\... |
3cef18816c58994adefeddc9ed63ad72f5aa4330 | VarshaRadder/APS-2020 | /Code library/137.K-diff Pairs in an Array.py | 732 | 3.84375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Apr 28 18:07:24 2020
@author: Varsha
"""
'''
A k-diff pair is defined as an integer pair (i, j), where i and j are both numbers in the array and their absolute difference is k
'''
def find_pairs(L,k):
L.sort()
N = len(L)
i = pairs = 0
j = ... |
1a3bf952bc6fad62e1466fa02f5e98e108a1eb86 | ueg1990/aids | /aids/stack/queue_two_stacks.py | 784 | 4.28125 | 4 | '''
Implement Queue data structure using two stacks
'''
from stack import Stack
class QueueUsingTwoStacks(object):
def __init__(self):
'''
Initialize Queue
'''
self.stack1 = Stack()
self.stack2 = Stack()
def is_empty(self):
'''
Return True if queue if empty else False
'''
return self.stack1.... |
4c4b35a4f1cab4eb148a59a6eb77064da189df26 | IsaacLeh1/Novel | /text.py | 77,789 | 4.03125 | 4 | #Pages
def stop():
input("press exit to end program")
quit()
def pg1a():
print("""Do not read this book straight through from beginning to end! These pages contain many different
adventures you can go on as you journey under
the sea. From time to time as you read along, you
will be asked to make a ch... |
2341dbe3fba41f18b1941a1f75a1a936ab7f4256 | wanglouxiaozi/python | /Dictionary/demo.py | 422 | 3.84375 | 4 | #!/usr/bin/env python2
# -*- coding: UTF-8 -*-
def test(dict1, list1):
dict1.pop('name')
list1.pop()
print dict1, list1
def test2(str1):
str1 = 's'
print str1
def __main():
dict1 = {'name': 'allen', 'age': 24, 'sex': 'm'}
list1 = ['nihao', 'shanghai']
print dict1, list1
test(dict1, list1)
print dict1, list... |
a1ea0303fe594fde08ca41c94050dbf9f5d2d3ad | abhinay-b/Leetcode-Submissions | /accepted_codes/Merge_Intervals/Merge Intervals_285451343.py | 727 | 3.53125 | 4 | class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
if not intervals:
return intervals
# sort based on the start of the interval
intervals.sort(key=lambda x: x[0])
res = []
idx = 1
temp = intervals[0]
while idx < len(int... |
611c1b9266d7acc8b646ade3a58378f3d08dec93 | yif042/leetcode | /Python3/no350. Intersection of Two Arrays II.py | 494 | 3.625 | 4 | class Solution(object):
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
if nums1 is None or nums2 is None:
return None
long, short = (nums1, nums2) if len(nums1) >= len(nums2) else (nums2, ... |
3e45fd58649d4ec9c16bcf24b426c8a04d0825d0 | Sylphy0052/TownDiceGameForPython | /src/landmark.py | 1,006 | 3.515625 | 4 | from enum import Enum
class LandmarkType(Enum):
TrainStation = 1
ShoppingMall = 2
AmusementPark = 3
RadioTower = 4
class Landmark:
def __init__(self, name, cost, player):
self.name = name
self.cost = cost
self.player = player
def play(self):
pass
def get_n... |
407493608416dc370b48d585dd1a6699e8e73a71 | 0n1udra/Learning | /Python/Python_Modules/Matplotlib.py | 13,000 | 4.03125 | 4 | # imports all functions of pyplot from matplotlib
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.ticker as mticker
from mpl_toolkits.mplot3d import axes3d
import matplotlib.style as mstyle
import matplotlib.animation as manime
import random as rd
import numpy as np
# creates plot da... |
838316fe1982df74260026165555da37548bb9c5 | hyperlolo/Leetcode | /Easy/twoSumEasy/twosum.py | 1,208 | 3.953125 | 4 | # Difficulty: Easy
# Given an array of integers numbers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.
# Return the indices of the two numbers (1-indexed) as an integer array answer of size 2, where 1 <= answer[0] < answer[1] <= numbers.length.
# You ma... |
67df4df9c107678587d85c29904eecde9e0e3455 | shonihei/road-to-mastery | /algorithms/linked-list-algorithms/get_Nth.py | 626 | 3.84375 | 4 | class Node:
def __init__(self, v=None, n=None):
self.key = v
self.next = n
# iteratively get the nth element
def get_Nth(node, n):
while n != 0:
if not node.next:
raise IndexError("n is larger than the length of the list")
node = node.next
n -= 1
return n... |
206a95b02a6d6ebff98aebb4dc20b4cc6588a359 | vdesire2641/python-for-programming | /pyc13.py | 164 | 3.765625 | 4 | # use of ifelse selection statements
a = 5
b = 3
if a>b:
c = 10
else:
c = 20
print(c)
# use of simple if selection statement
if b>a:
c = 25
print(c)
|
4adfa8889f2ff487e4187952106c99415cd9ca25 | Boissineau/challenge-problems | /leetcode/Easy/ReverseLinkedList/reverse.py | 789 | 3.75 | 4 | class Solution:
def reverseList(self, head):
curr = head
previous = None
while True:
if curr is None:
break
tmp_curr = curr.next
curr.next = previous
previous = curr
if tmp_curr is None:
break
... |
f9f0dfc40b556069c3a6f18dc569b08c4c4b8b57 | MishRanu/udemy-python-masterclass | /hello.py | 254 | 3.875 | 4 | print("Hello world!")
hello="hello"
# anurag=input("Please enter your name")
print(hello+ " " )
print('The pet shop owner said "No, no, \'e\'s eh.... he\s resting\"')
print("h" in "hello")
test="He's probably pining"
print(test[0::3])
print(test[1:9:2])
|
1e7af9b8b42474af1e5d79adb12cab6c7d17dd70 | johanaluna/Sorting | /src/iterative_sorting/iterative_sorting.py | 2,628 | 3.953125 | 4 | # TO-DO: Complete the selection_sort() function below
def selection_sort( arr ):
# loop through n-1 elements
for i in range(0, len(arr) - 1):
cur_index = i
smallest_index = cur_index
# TO-DO: find next smallest element
# (hint, can do in 3 loc)
for n in range(smallest_in... |
e6edf4cfab3566d73c470968b21a6a87ba724fe8 | Phlosioneer/zork-rs | /tools/verb_parser.py | 397 | 3.890625 | 4 |
def parse_number(num):
low_bits = num & 0xFF
high_bits = num >> 8
print("low bits: " + str(low_bits))
for bit in range(0, 8):
mask = 1 << bit
value = mask & high_bits
if value:
print("Bit " + str(bit + 8) + " is true.")
print("All other bits are false.")
... |
9126a5391d090b58187173c147286d367445910c | daniel-reich/ubiquitous-fiesta | /MhtcQNMbkP82ZKJpm_17.py | 275 | 3.5 | 4 |
from collections import Counter
def get_notes_distribution(students):
print(students)
students_list_of_lists = [s['notes'] for s in students]
res = dict(Counter([item for sublist in students_list_of_lists\
for item in sublist if item in [1,2,3,4,5]]))
return res
|
f969d62d5e0e8e9255c3b44895e8174afae53f42 | gabriellaec/desoft-analise-exercicios | /backup/user_212/ch150_2020_04_13_20_03_38_368317.py | 151 | 3.703125 | 4 | def calcula_pi (n):
p=0
total=0
for i in range (n):
p+=(6/n**2)
total=(p)**(1/2)
return total
|
6d49a4fd133303c1585d2cd11e3464d0545ab889 | MuberraKocak/data-structure-python | /TwoPointer/remove_duplicates.py | 380 | 3.78125 | 4 | def remove_duplicates(arr):
next_non_duplicate = 1
i = 1
while(i< len(arr)):
if arr[next_non_duplicate - 1] != arr[i]:
arr[next_non_duplicate] = arr[i]
next_non_duplicate += 1
i += 1
return next_non_duplicate
arr = [2, 3, 3, 3, 6, 9, 9]
print(remove_duplicates(... |
c4651cd8e54a6a86fa64144ee5594b97769ceaf5 | mba-mba/HacktoberFest2020-1 | /Python/heterogram.py | 225 | 3.875 | 4 | string=input()
lst=[]
for i in string.lower():
if ord(i)>=ord('a') and ord(i)<=ord('z'):
lst.append(i)
s1=set(lst)
if len(s1)==len(lst):
print("Heterogram string")
else:
print("its not heterogram string")
|
299cb41058a74756f6508bec62953c203532fdf4 | KIMJOOYEON97/pythonStudy | /20.05 studyData/아직도 못푼 문제 잇음.py | 5,551 | 3.78125 | 4 | '''
i=0
while i<5:
print("{}번 종속문장 실행".format(i))
i +=1
else:
print("조건식이 거짓인 경우에 실행 문장") #반복구문 다 실행한다음에 한번실행. 만약 거짓인 경우 이것만 실행)
print("메인 프로그램 실행 코드")
'''
'''
# 문제6] 다음과 같은 모형으로 출력되게 하세요. (단, 파이썬 서식을 사용안함. ) 서식문자사용X
6-1 6-2 6-3 6-4
* ***** * *****
** ... |
f1ebe6f60c2e2d3e6ef7dd0ab8492b6023d852eb | dedekinds/pyleetcode | /680_Valid Palindrome II_easy.py | 592 | 3.53125 | 4 |
'''
680. Valid Palindrome II
2017.12.23
'''
如果发现不少回文,那么给一次机会把那个字符剔除
class Solution:
def validPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
ispalindrome=lambda s:s==s[::-1]
conbination=lambda x,s: s[:x]+s[x+1:]
left=0
right=len(... |
1b786b004eb3df0ac77b0afa4f35bdc38dd2a343 | sergiodealencar/courses | /material/curso_em_video/ex071.py | 1,393 | 3.75 | 4 | # print('=='*15)
# print('{:^30}'.format('BANCO PATINHAS'))
# print('=='*15)
# nota50 = nota20 = nota10 = nota1 = 0
# valor = int(input('Que valor você quer sacar? R$'))
# while valor != 0:
# while valor >= 50:
# valor -= 50
# nota50 += 1
# while valor >= 20:
# valor -= 20
# nota... |
8bd72b0fb013d9fcaf699fea168251e32562a851 | hanskiebach/metrobus | /[hanskiebach]/[metrobus]/week2/homework.py | 240 | 3.5 | 4 | import logging
logging.basicConfig(level=logging.DEBUG)
def squared_threes():
return_value = [value ** 2 for value in range(3,100, 3)]
return return_value
if __name__ == "__main__":
for x in squared_threes():
print(x) |
6ec33929bdce0f29f2d7e61918e8828f7c648ee9 | leoren6631/Learning-Python | /quadratic_solve.py | 295 | 3.75 | 4 | import math
def quadratic(a, b, c):
if a != 0:
x1 = (-b + math.sqrt(b*b - 4*a*c)) / (2*a)
x2 = (-b - math.sqrt(b*b - 4*a*c)) / (2*a)
return (x1, x2)
else:
return('wrong input')
print(quadratic(2, 3, 1))
print(quadratic(1, 3, -4))
print(quadratic(0,2,3)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.