blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
5464a614b6b02186a9139bf6aab72f279ea78099 | lucioeduardo/cc-ufal | /APC/Listas/04 - Funções/q6.py | 609 | 4.25 | 4 | """
6. Percebendo que o método anterior de cálculo
de notas foi muito severo, o professor decidiu
mudar o formato do cálculo. A nova fórmula foi:
– Nota = (nota/max)*10
– Faça um programa para calcular as notas dos
alunos segundo essa nova regra, utilizando
funções
"""
def maior(lista):
res = lista[0]
for i in... | false |
a9a1e6045d4a0ba4ff26f662bfc670c4ae007693 | alvintangz/pi-python-curriculum | /adventuregame.py | 745 | 4.34375 | 4 | # Simple adventure game for day 3.
hero = input("Name your hero. ")
print("\n" + hero + " has to save their friend from the shark infested waters.")
print("What do they do?")
print("A. Throw a bag of salt and pepper in the water?")
print("B. Drink up the whole ocean?")
print("C. Do nothing.\n")
option = input("What do ... | true |
8ca0ed2176a8dac59fd50ae330c278b1cf649ac1 | jzaunegger/PSU-Courses | /Spring-2021/CSE-597/MarkovChains.py | 1,804 | 4.3125 | 4 | '''
This application is about using Markov Chains to generate text using
N grams. A markov chain is essentially, a series of states, where each state
relates to one another in a logical fashion. In the case of text generation,
a noun phrase is always followed by a verb phrase.
Lets say we ha... | true |
28bf44989f72a0a9c14d5a34bb1068437800c72a | mustail/Election_analysis | /practice/python_practice2.py | 1,711 | 4.46875 | 4 | # python practice continued
print("Hello world.")
print("Arapahoe and Denver are not in the list of counties.")
# printing with f string
my_votes = int(input("How many votes did you get in the election?"))
total_votes = int(input("What is the total number of votes in the election?"))
percentage_votes = (my_votes/t... | true |
60dc024310defe5fb2ea8d12ecd91965d9151681 | mayelespino/code | /LEARN/python/functional-programming-tools/functional-programming.py | 538 | 4.15625 | 4 | #!/usr/bin/python
#https://docs.python.org/2/tutorial/datastructures.html
#---- filter ----
print "---- filter ----"
def isEven(x): return x % 2 == 0
myList = (filter(isEven, range(1,20)))
for N in myList:
print N
#---- map ----
print "---- map ----"
seq1 = range(1,10)
seq2 = range(101,110)
def addThem... | false |
08693ca174d12eff737cc6a467d1159652787a31 | astralblack/Calculator | /calc.py | 1,262 | 4.5 | 4 | # Astral's Calcultor
# Date: 9.27.18
# Menu
print("Hello welcome to my calculator!\n")
print("1: Addition")
print("2: Subtraction")
print("3: Multiplication")
print("4: Division\n")
# Functions
def addition():
num1 = int(input ("What is the first number?"))
num2 = int(input ("What is the second ... | false |
6873b522169569c7e04a6e39c065fdab343f6405 | Sabdix/Python-Tutorials | /Dictionaries.py | 465 | 4.25 | 4 | # A dictionary is a collection which is unordered, changeable and indexed.
thisDict = {
"apple": "green",
"bannana": "yellow",
"cherry": "red"
}
print(thisDict)
#Changing elements
thisDict["apple"] = "red"
print(thisDict)
#Create dictionary with method
thisdict = dict(apple="green", bannana="yellow", che... | true |
abbc2b40c22b26f2c2305a5b69b91cb8ccb63b9a | Sabdix/Python-Tutorials | /Json.py | 1,302 | 4.4375 | 4 | # importing JSON
import json
# If you have a JSON string, you can parse it to convert it in to a dictionary
# some JSON:
x = '{ "name":"John", "age":30, "city":"New York"}'
# parse x:
y = json.loads(x)
# the result is a Python dictionary:
print(y["age"])
#If you have a Python object, you can convert it into a JSON... | true |
5e44a8c1f6fe05525aacd26f0f03e5d37114476c | JuanSch/ejemplo_python | /Ejercicio 7 PRACTICA 2.py | 244 | 4.125 | 4 | cadena = input('Ingrese un string ')
cadenaInvertida = cadena[::-1] #invertimos la cadena
if (cadena == cadenaInvertida):
print('la palabra ingresada es palindrome')
else:
print('La palabra ingrtesada no es palindrome') | false |
bbfa000ad67f734df09ed03e70d85119123cfef0 | sangeetjena/datascience-python | /Dtastructure&Algo/algo/water_supply.py | 826 | 4.1875 | 4 | """Given N cities that are connected using N-1 roads. Between Cities [i, i+1], there exists an edge for all i from 1 to N-1.
The task is to set up a connection for water supply. Set the water supply in one city and water gets transported from it to other cities using road transport. Certain cities are blocked which mea... | true |
6e363f232d0f0345d446bcfbf7a7b9a649ec6470 | COSJIE/meachine-learning | /04_函数/hm_09_函数嵌套调--打印分隔线.py | 426 | 4.25 | 4 | # 定义一个print_line函数打印 * 组成的一条分隔线
# def print_line():
# print("*" * 50)
# print_line()
# 定义一个print_line函数打印 任意字符 组成的一条分隔线
# def print_line(char):
# print(char * 50)
# print_line("-")
# 定义一个print_line函数打印 任意字符 任意次数的组成的一条分隔线
def print_line(char,times):
print(char * times)
print_line("-", 10) | false |
00503cb30615d01facc609ef894f0ee570717a96 | kajaltingare/Python | /Basics/verbing_op.py | 328 | 4.4375 | 4 | # Write a program to accept a string from user & perform verbing operation.
inp_stmt=input("Enter the statement: ")
if(len(inp_stmt)>=3):
if(inp_stmt.endswith("ing")):
print(inp_stmt[:-3]+'ly')
else:print(inp_stmt+'ing')
else:
print('Please enter verb atleast 3 or more number of characters in... | true |
58b6f4caa8b080662653399a75cff2afc9ff6691 | kajaltingare/Python | /Basics/Patterns/pattern6_LL.py | 334 | 4.125 | 4 | # Write a program to print LowerLeft side pattern of stars.
def Pattern6(n):
for i in range(1,n+1):
for _ in range(0,n-i+1):
print('*',end='')
print()
def main():
n = eval(input('Enter the no of rows want to print pattern: '))
Pattern6(n)
if __name__ == '__main__':... | true |
c0af2569858fa4b0d2e8d8c2246d7948a8d97841 | kajaltingare/Python | /Basics/UsingFunc/fibboSeriesWithUpperLimit.py | 433 | 4.21875 | 4 | # Write a program to print fibonacci series with given upper limit, starting from 1.
def fiboSeries(upperLmt):
a,b=1,1
print(a,b,end='')
#for i in range(1,upperLmt):
while((a+b)<=upperLmt):
c=a+b
print(' %d'%c,end='')
a=b
b=c
def main():
upperLmt = eval(i... | true |
9b4de2ccf3539b1f714c3855bff8989f19f433fa | kajaltingare/Python | /Basics/min_of_3.py | 260 | 4.21875 | 4 | # Write a program to accept three numbers from user & find minimum of them.
n1,n2,n3=eval(input("Enter the 3 no.s: "))
if(n1<n2 and n1<n3):print("{0} is minimum".format(n1))
elif(n2<n1 and n2<n3):print('%d is minimum.'%n2)
else:print('%d is minimum.'%n3)
| true |
831023701ff1b841124a34e1eebb20f05489cc6a | kajaltingare/Python | /Basics/UsingFunc/isDivisibleByEight.py | 481 | 4.34375 | 4 | # Write a program to accept a no from user & check if it is divisible by 8 without using arithmatic operators.
def isDivisibleByEight(num):
if(num&7==0):
return True
else:
return False
def main():
num = eval(input('Enter the number: '))
result = isDivisibleByEight(num)
i... | true |
a8c06bb0934f021d06a854bba1861b83d31bd4e1 | kajaltingare/Python | /Basics/basic_str_indexing.py | 676 | 4.65625 | 5 | #String-Immutable container=>some basics about string.
name="kajal tingre"
print("you entered name as: ",name)
#'kajal tingre'
print("Accessing 3rd char in the string(name[2]): ",name[2])
print("2nd including to 5th excluding sub-string(name[2:5]): ",name[2:5])
print("Printing alternate char from 1st position(nam... | true |
094559f9145b0d98920ed6960f275c0de68f0d48 | Ahed-bahri/Python | /squares.py | 250 | 4.25 | 4 | #print out the squares of the numbers 1-10.
numbers=[1,2,3,4,5,6,7,8,9,10]
for i in numbers:
print("the square of each number is : ", i**2)
#mattan strategy
for i in range(1,11):
print("the square of each number is : ", i**2)
| true |
da3e46522a54ff4971dda36cb3a0ad19de85e874 | donchanee/python_trick | /Chaining_Comparison.py | 502 | 4.25 | 4 | # Chaining comparison operators:
>>> x = 5
>>> 1 < x < 10
True
>>> 10 < x < 20
False
>>> x < 10 < x*10 < 100
True
>>> 10 > x <= 9
True
>>> 5 == x > 4
True
'''
In case you're thinking it's doing 1 < x, which comes out as True, and then comparing True < 10,
which is also True, then no, that's really not what happens... | true |
ed37d9243eda6d10b8f2cb0e8c3c55791ed99e38 | KlimDos/exercism_traning | /python/yacht/yacht.py | 2,457 | 4.1875 | 4 | """
This exercise stub and the test suite contain several enumerated constants.
Since Python 2 does not have the enum module, the idiomatic way to write
enumerated constants has traditionally been a NAME assigned to an arbitrary,
but unique value. An integer is traditionally used because it’s memory
efficient.
It is a... | true |
336152ac95245e4b7b59387b1ec96501cecd2940 | Shalima2209/Programming-Python | /rectangle.py | 882 | 4.125 | 4 | class rectangle:
def __init__(self,length,breadth):
self.length=length
self.breadth=breadth
def area(self):
return self.length*self.breadth
def perimeter(self):
return 2*(self.length + self.breadth)
a=int(input("length of rectangle1 : "))
b=int(input("breadth of rect... | false |
c2bccd3dc5edb3734482d4540c954292ae6bc85f | shun-lin/Shun-LeetCode-OJ-solutions | /Algorithm/ImplmentingQueueUsingStacks.py | 1,718 | 4.40625 | 4 | class MyQueue(object):
def __init__(self):
"""
Initialize your data structure here.
"""
# stack is first in last out so in python we can use append to add and
# pop front
# we want to implement a queue which is first in first out
self.stacks = [[], []]
... | true |
09a4bf54f13dee45f673fcb7b8770c88ab7dc584 | Vishnu8649/task3 | /2/defaultdic.py | 316 | 4.25 | 4 | import collections as c
def default():
'''
demonstrating working of default dict
'''
d={1:'a', 2:'a', 3:'b', 4:'c',5:'d', 6:'c'}
print 'Before reversal', d
new=c.defaultdict(list)
for k,v in d.items():
new[v].append(k)
print 'Reversed dictionary is', dict(new)
default()
| false |
e064c21b78829ef1a99ce2e205c7298cca798afc | gmaher/flask-react-be | /src/crypto/password.py | 938 | 4.3125 | 4 | import bcrypt
def hash_password(pw, rounds=10):
"""
Uses the bcrypt algorithm to generate a salt and hash a password
NOTE: ONLY PASSWORDS < 72 CHARACTERS LONG!!!!
:param pw: (required) password to hash
:param rounds: number of rounds the bcrypt algorithm will run for
"""
if not type(pw) ==... | true |
3207b1deeb5506e7d1346291901a759cc2549fca | TianfangLan/LetsGoProgram | /Python/week_notes/week2_QueueADT_v1.py | 1,718 | 4.34375 | 4 | class EmptyQueueException(Exception):
pass
class Queue():
''' this class defines a Queueu ADT and raises an exception in case the queue is empty and dequeue() or front() is requested'''
def __init__(self):
'''(Queue) -> Nonetype
creates an empty queue'''
# representation invariant
... | true |
f7068520fbd7e15129b46ca5995c0a305ec9e07c | ArthurHGSilva/Atividades-Python | /Exercícios_parte3/exercício8.py | 552 | 4.125 | 4 | num1 = float(input('Coloque o valor do primeiro número: '))
num2 = float(input('Coloque o valor do segundo número: '))
operacao = input('Coloque a operação desejada: ')
if operacao == '+':
resultado = num1 + num2
print('Adição\t', resultado)
elif operacao == '-':
resultado1 = num1 - num2
p... | false |
54492efbf4c23f590bef414dcfc611dc28dde4a0 | mrklyndndcst/100-Days-of-Code-The-Complete-Python-Pro-Bootcamp-for-2022 | /Beginner/D004_Randomisation_and_Python_Lists/ProjectD4_Rock_Paper_Scissors.py | 1,551 | 4.15625 | 4 | import random
rock = "👊"
paper = "✋"
scissors = "✌️"
choices = [rock, paper, scissors]
player = int(input(f"What do you choose? type 1 for {rock}, 2 for {paper} or 3 for {scissors}\n"))
print("You choose")
if player < 1 or player > 3:
print("Invalid")
ai = random.randint(1 , 3)
print("Artificial Intell... | true |
e999d005eff83eca21ec9e1f4acb28cc96ba4d0b | zhanglulu15/python-learning | /python学习基础及简单实列/basic learing 6.py | 246 | 4.25 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 26 10:41:55 2018
@author: lulu
"""
count = 3
while count <= 5:
print("the count less than 5",count)
count = count + 1
else:
print("the count greater than 5",count) | true |
52c689ac08f7020700ec0ede437162eb1c0e7f81 | Valuoch/pythonClass | /pythonoperators.py | 1,375 | 4.53125 | 5 | #OPERATORS
#special symbols in python to carry out arithmetic and logical computations
#They include;
#1.arithmetic- simple math operations eg addition, sustraction, multiplication(*), division(/), modulas(%), floor(//),exponent(**)etc
#x=10
#y=23
#print(x+y)
#print(x-y)
#print(x/y)
#print(x*y)
#print(x%y)
#print(x//y)... | true |
ccb56373dde67a27e4c4bfabd234b6d0a310cf86 | alexthomas2020/Banking | /test_Account.py | 2,028 | 4.3125 | 4 | # Banking Application
# Author: Alex Thomas
# Updated: 11/10/2020
import unittest
from Account import get_account, get_accounts, Account
"""
Banking Application - Unit tests for Account class.
Run this program to view results of the tests.
"""
class TestAccount(unittest.TestCase):
def test_get_account(self):
... | true |
6966ec8f669922fa1a78661630eb6732ba5b549a | matthew02/project-euler | /p005.py | 820 | 4.1875 | 4 | #!/usr/bin/env python3
"""Project Euler Problem 5: Smallest multiple
Find the smallest positive number that is evenly divisible by all of the
numbers from 1 to 20.
https://projecteuler.net/problem=5
Usage:
python3 p0005.py [number]
"""
import sys
from math import gcd
from typing import List
def smallest_multi... | true |
5e8d00838e9a82b03de35bf595a3b140bfe5baa1 | yaHaart/hometasks | /Module21/03_fibonacci/main.py | 275 | 4.125 | 4 | index_number = 7
# 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233
def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci(n-1) + fibonacci(n-2)
print(index_number, '-ый элемент ряда ', fibonacci(index_number))
# зачёт! 🚀
| false |
3d8813c43d8f57d133fb2f487cd15f65b9a59106 | gabrielbessler/ProgrammingCompetition | /AI18/AI18_1.py | 1,422 | 4.65625 | 5 | #!/bin/python3
import sys
'''
Problem Statement
You have been given an integer which represents
the length of one of cathetus of a right-angle triangle.
You need to find the lengths of the remaining sides.
There may be multiple possible answers; any one will be accepted.
'''
def pythagorean_triple(side... | true |
85f848d0e6e073ec282e96cb98481eda112c43e4 | dstamp1/FF-BoA-2020 | /day01/day01c-ForLoops.py | 2,787 | 4.6875 | 5 | ### For Loops ###
# Computers are really good at repeating the same task over and over again without making any mistakes/typos
# Let's imagine we were having a competition to see who could type out "print('hello')" as many times as we could without using copy and paste.
# We might type out
print('hello')
print('hello'... | true |
43e6b014cd9e53fd21794668a77fde252063dd5c | anajulianunes/aprendendo-python | /Curso-python-iniciante/Projetos do Curso em Vídeo/aula9/9c - separa digitos de um numero.py | 280 | 4.21875 | 4 | numero = int(input('Insert a number: '))
u = numero // 1 % 10 #pega um número divide por 1 e depois por 10 e pega o resto da divisao
d = numero // 10 % 10
c = numero // 100 % 10
m = numero // 1000 % 10
print('Unidade: {}\nDezena: {}\nCentena: {}\nMilhar: {}'.format(u,d, c, m))
| false |
8c997e49168c94f312993b43f08b26c857579ba6 | vijaysharma1996/Python-LIst-Basic-Programmes | /list find the sum of element in list.py | 232 | 4.25 | 4 | # Python program to find sum of elements in list
# creating a list
list1 = [11, 5, 17, 18, 23]
# using sum() function
total = sum(list1)
# printing total value
print("Sum of all elements in given list: ", total)
| true |
b489616b270128b30f5f06ad34c2e4f613cdf575 | imnikkiz/Conditionals-and-Variables | /guessinggame.py | 2,344 | 4.15625 | 4 | import random
def check_guess(guess, correct):
""" Compare guess to correct answer.
Return False once guess is correct.
"""
if guess == correct:
return False
elif guess < 1 or guess > 100:
print "Your guess is out of the range 1-100, try again."
elif guess > correct:
p... | true |
6166a4a86a3a486745dee02399b400820ba446d9 | raresrosca/CtCI | /Chapter 1 Arrays and Strings/9_stringRotation.py | 847 | 4.125 | 4 | import unittest
def is_rotation(s1, s2):
"""Return True if s2 is a rotation of s1, False otherwise"""
for i, c in enumerate(s2):
if c == s1[0]:
if s2[i:]+s2[:i] == s1:
return True
return False
def is_rotation_2(s1, s2):
"""Return True if s2 is a rotation of s1, Fals... | true |
55885f48b318943495a44ff4454b5c21ca1f3f45 | sirajmuneer123/anand_python_problems | /3_chapter/extcount.py | 533 | 4.125 | 4 | #Problem 2: Write a program extcount.py to count number of files for each extension in the given directory. The program should take a directory name as argument and print count and extension for each available file extension.
import os
import sys
cwd=os.getcwd()
def count(cwd):
list1=os.listdir(cwd)
newlist=[]
frequ... | true |
a360a18d93371e46214a28eb71275171a5a3a93c | sirajmuneer123/anand_python_problems | /3_chapter/regular_ex.py | 409 | 4.21875 | 4 | '''
Problem 9: Write a regular expression to validate a phone number.
'''
import re
def reg_exp(str1):
match=re.search(r'phone:\d\d\d\d\d\d\d|mobile:\d\d\d\d\d\d\d\d\d\d',str1)
if match:
print 'found'
s= re.findall(r'phone:\d\d\d\d\d\d\d|mobile:\d\d\d\d\d\d\d\d\d\d',str1)
for i in s:
print i
else:
print ... | false |
9fdf38d1a2c8bf2460625ff16b4ebc6692936cfc | sirajmuneer123/anand_python_problems | /2_chapter/factorial.py | 412 | 4.1875 | 4 | #Problem 5: Write a function factorial to compute factorial of a number. Can you use the product function defined in the previous example to compute factorial?
array=[]
def factorial(number):
while number!=0:
array.append(number)
number=number-1
return array
def product(num):
mul=1
a=len(num)
while a!=0:
m... | true |
38171858be0fc89461f6e38bb85d7585c18525c1 | LTTTDH/dataScienceHelpers | /NaNer.py | 477 | 4.125 | 4 | # This function was created to deal with numerical columns that contain some unexpected string values.
# NaNer converts all string values into np.nans
def NaNer(x):
"""Takes a value and converts it into a float.
If ValueError: returns np.nan
Originally designed to use with pandas DataFrames.
... | true |
051c485cf68844613d64f75d57de227f614be24e | SetOffAtDawn/python | /day1/var.py | 571 | 4.3125 | 4 | """"
变量
目的:用来存储数据
定义变量:
name = "huchao"
变量定义的规则:
字母、数字、下划线
第一个字符不能是数字
关键字不能作为变量名
不合适的变量名:
a1
a 不知道变量代表的意思
姓名 = 'huchao'
xingming = "huchao"
推荐写法:
girl_of_friend = "huchao"
"""""
print("hello world")
name = "huchao"
print("my name is ",name)
name = "huchao"
name2 = name
print("my name is ",name,name2)... | false |
ee9d018f5a7fd7e23e66f972c0ab3aa8f8d19e27 | PingryPython-2017/black_team_palindrome | /palindrome.py | 823 | 4.28125 | 4 | def is_palindrome(word):
''' Takes in an str, checks to see if palindrome, returns bool '''
# Makes sure that the word/phrase is only lowercase
word = word.lower()
# Terminating cases are if there is no characters or one character in the word
if len(word) == 0:
return True
if len(word) == 1:
return Tru... | true |
be832202e22425289126c594a6c5649cff49d533 | dan76296/stopwatch | /stopwatch.py | 1,495 | 4.25 | 4 | import time
class StopWatch:
def __init__(self):
''' Initialises a StopWatch object'''
self.start_time = None
self.end_time = None
def __repr__(self):
'''Represents the object in a readable format'''
return 'Time Elapsed: %r' % ':'.join((self.convertSeconds(self.resul... | true |
aa08a6475f125520389646b0551301a54dafcf89 | GitFiras/CodingNomads-Python | /03_more_datatypes/3_tuples/03_16_pairing_tuples.py | 992 | 4.4375 | 4 | '''
Write a script that takes in a list of numbers and:
- sorts the numbers
- stores the numbers in tuples of two in a list
- prints each tuple
Notes:
If the user enters an odd numbered list, add the last item
to a tuple with the number 0.
'''
# sort numbers
numbers_ = [ 1, 5, 4, 67, 88, 99, 3, 2, 12]
num... | true |
be616a73c1e05410a1461277824f37d45e8a3d24 | GitFiras/CodingNomads-Python | /13_aggregate_functions/13_03_my_enumerate.py | 693 | 4.3125 | 4 | '''
Reproduce the functionality of python's .enumerate()
Define a function my_enumerate() that takes an iterable as input
and yields the element and its index
'''
def my_enumerate():
index = 0
value_list = ['apple', 'banana', 'pineapple', 'orange', 'grape'] # list
for value in value_list: ... | true |
64c9d551092b05a7d1fc1b4919403731cb2aa07d | GitFiras/CodingNomads-Python | /04_conditionals_loops/04_01_divisible.py | 473 | 4.40625 | 4 | '''
Write a program that takes a number between 1 and 1,000,000,000
from the user and determines whether it is divisible by 3 using an if statement.
Print the result.
'''
num = int(input('Please provide a number between 1 and 1,000,000,000: '))
if num % 3 == 0: # if output is 0, the numb... | true |
48550e1cb00bf023ec1394a0d0c8116fa0c8c456 | GitFiras/CodingNomads-Python | /06_functions/06_01_tasks.py | 2,146 | 4.25 | 4 | '''
Write a script that completes the following tasks.
'''
# define a function that determines whether the number is divisible by 4 or 7 and returns a boolean
print("Assignment 1 - Method 1:")
def div_by_4_or_7(x):
if x % 4 == 0:
print(f"{x} is divisible by 4: ",True) # boolean True if func... | true |
3ad789eadbc061a3dafa8af235e28282e659ad63 | GitFiras/CodingNomads-Python | /09_exceptions/09_05_check_for_ints.py | 669 | 4.625 | 5 | '''
Create a script that asks a user to input an integer, checks for the
validity of the input type, and displays a message depending on whether
the input was an integer or not.
The script should keep prompting the user until they enter an integer.
'''
while True:
try:
user_input = input("Please provide ... | true |
c43746c218b0df727e187614f7859b0146575356 | GitFiras/CodingNomads-Python | /03_more_datatypes/4_dictionaries/03_20_dict_tuples.py | 506 | 4.3125 | 4 | '''
Write a script that sorts a dictionary into a list of tuples based on values. For example:
input_dict = {"item1": 5, "item2": 6, "item3": 1}
result_list = [("item3", 1), ("item1", 5), ("item2", 6)]
'''
input_dict = {"item1": 5, "item2": 6, "item3": 1}
list_ = []
# Iteration from dict to list with tuples
for i i... | true |
20acb5c9c5b63cfb04b70a82a815027e856fb517 | GitFiras/CodingNomads-Python | /Inheritance - Course Example Code.py | 1,361 | 4.46875 | 4 | class Ingredient:
"""Models an Ingredient."""
def __init__(self, name, amount):
self.name = name
self.amount = amount
def expire(self):
"""Expires the ingredient item."""
print(f"whoops, these {self.name} went bad...")
self.name = "expired " + self.name
def __str__(self):
return f"You h... | true |
f39fadba2f9d57dd9c9f59c827619f891d579fa4 | SnehaMercyS/python-30-days-internship-tasks | /Day 7 task.py | 1,734 | 4.125 | 4 | Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:43:08) [MSC v.1926 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> #1) create a python module with list and import the module in anoother .py file and change the value in list
>>> list=[1,2,3,4,5,6]
>>> import m... | true |
81af9ef448d9228b34e6c8017b034ccd6405d9ea | clopez5313/Python | /1. Become a Python Developer/4. Programming Foundations - Data Structures/Arrays/2dArrays.py | 1,025 | 4.125 | 4 | import os
# Create a 2D array and print some of their elements.
studentGrades = [[72, 85, 87, 90, 69], [80, 87, 65, 89, 85], [96, 91, 70, 78, 97], [90, 93, 91, 90, 94], [57, 89, 82, 69, 60]]
print(studentGrades[1])
print(studentGrades[0])
print(studentGrades[2])
print(studentGrades[3][4])
# Traverse the array.
for st... | true |
ba5b7564b61ea7d0bacdfcb2ac19024a39f163ae | clopez5313/Python | /1. Become a Python Developer/4. Programming Foundations - Data Structures/Stacks and Queues/sortingQueues.py | 730 | 4.15625 | 4 | import queue
# Create the object and add some elements to it.
myQueue = queue.Queue()
myQueue.put(14)
myQueue.put(27)
myQueue.put(11)
myQueue.put(4)
myQueue.put(1)
# Sort with Bubble Sort algorithm.
size = myQueue.qsize()
for i in range(size):
# Remove the element.
item = myQueue.get()
#Remove the next... | true |
ec94e882ff4f039bad9c0785c6d615c445cb706b | shyboynccu/checkio | /old_library/prime_palindrome.py | 1,877 | 4.28125 | 4 | #!/usr/local/bin/python3
# An integer is said to be a palindrome if it is equal to its reverse in a string form. For example, 79197 and 324423 are palindromes. In this task you will be given an integer N. You must find the smallest integer M >= N such that M is a prime number and M is a palindrome.
# Input: An integer... | true |
48798e1b51baefc7c23b92cf86b34eef35313cee | emilnorman/euler | /problem007.py | 493 | 4.15625 | 4 | # !/usr/bin/python
# -*- coding: utf-8 -*-
# By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13,
# we can see that the 6th prime is 13.
#
# What is the 10 001st prime number?
def next_prime(p):
temp = p + 2
for i in xrange(3, temp, 2):
if ((temp % i) == 0):
return next_prime(t... | true |
05bd5cba24b50221d83ae84bee8958dff9b2c7ae | rsoemardja/Python | /PythonAndPygameArcade/Chapter 3 Quiz Games and If Statements/3.2/PythonOrder/PythonOrder/test.py | 996 | 4.3125 | 4 | # we are going to be taking a look at logic with if Statements
# Their is actually a hidden error
# The error is that computer looks at each statement
# and is 120 > 90. It is indeed and the else would execute but the else DID not excute hence the logic error
temperature=input("What is the temperature in Fahrenheit? ")... | true |
313c45fa97a1c12eee440966216c3904f549cd07 | KDRGibby/learning | /nthprime.py | 781 | 4.46875 | 4 | def optimusPrime():
my_list = [1,2]
my_primes = []
prime_count = 0
# this is supposed to add numbers to my_list until the prime count reaches x numbers.
while prime_count < 10:
last_num = my_list[-1]
my_list.append(last_num + 1)
#here we check to see if a number in my_list is a prime
for i in my_list:
... | true |
6c0fcf97e0aa94637e2582269a0984bb41003c52 | LeiZhang0724/leetcode_practice | /python/practice/easy/reverse_int.py | 2,743 | 4.15625 | 4 | # Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside
# the signed 32-bit integer range [-231, 231 - 1], then return 0.
# Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
def reverse(x: int) -> int:
INT_MIN, INT_... | false |
e170befde825656d17d5b17b81cd51d3c0f09c55 | allenxzy/Data-and-Structures-and-Alogrithms | /python_data/Chapter 1/P/P-1.36.py | 294 | 4.125 | 4 | #-*-coding: utf-8 -*-
"""
Write a Python program that inputs a list of words, separated by whitespace,
and outputs how many times each word appears in the list. You
need not worry about efficiency at this point, however, as this topic is
something that will be addressed later in this book
""" | true |
fbef3fb244b0ecb1c97a293c1f9e029fe3273f6f | allenxzy/Data-and-Structures-and-Alogrithms | /python_data/Chapter 2/R/R-2.4.py | 426 | 4.3125 | 4 | #-*-coding: utf-8 -*-
"""
Write a Python class, Flower, that has three instance variables of type str,
int, and float, that respectively represent the name of the flower, its number
of petals, and its price. Your class must include a constructor method
that initializes each variable to an appropriate value, and your c... | true |
3d1efee5bd503d5503ecafc36e40b60ef833fb7c | allenxzy/Data-and-Structures-and-Alogrithms | /python_data/Chapter 1/R/R-1.1.py | 590 | 4.40625 | 4 | #-*-coding: utf-8 -*-
"""
Write a short Python function, is_multiple(n, m), that takes two integer
values and returns True if n is a multiple of m, that is, n = mi for some
integer i, and False otherwise
"""
def is_multiple(n, m):
n = int(n)
m = int(m)
if n % m == 0 and n != 0:
return True
els... | true |
092eca02e6e2d164b20444d05b2c328e0b548cb6 | allenxzy/Data-and-Structures-and-Alogrithms | /python_data/Chapter 1/P/P-1.32.py | 395 | 4.21875 | 4 | #-*-coding: utf-8 -*-
"""
Write a Python program that can simulate a simple calculator, using the
console as the exclusive input and output device. That is, each input to the
calculator, be it a number, like 12.34 or 1034, or an operator, like + or =,
can be done on a separate line. After each such input, you should o... | true |
2124b62809bc75f650e3ed62908a4fb2aaf74ac9 | avanti-bhandarkar/ML | /2.py | 1,812 | 4.125 | 4 | #1 - linear regression with sklearn
import numpy as np
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
#predictor variable
x = np.array([5, 15 , 25 , 35 , 45 ,55])
xm = x
x = x.reshape((-1,1))
x.shape
#response variable
y = np.array([4,7,23,5,39,23])
ym = y
#y = y.reshape((-1,1))
y.... | false |
d22cd7865db4233da780c7346c2df1a21d7ef71c | jeasonliang/Learning-notes | /Python/3-8-9-10address.py | 2,702 | 4.28125 | 4 | #想出至少 5 个你渴望去旅游的地方。将这些地方存储在一个列表中,并确保其中的元素不是按字母顺序排列的。
world_address = ['LosAngeles','Beijing','Xiamen','Amsterdam','Caribbean Sea']
print('按照原始排列顺序打印该列表:\n\t',world_address)#按原始排列顺序打印该列表。
print('按照临时排列字母的顺序打印该列表:\n\t',sorted(world_address))#使用 sorted()按字母顺序打印这个列表,同时不要修改它。临时排序
print('按照原始排列顺序打印该列表:\n\t',world_address)#再次... | false |
88f2f7683025b2fcbcc0006b279bce698743d10b | himanshu2801/leetcode_codes | /sort colors.py | 912 | 4.15625 | 4 | """
Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
Follow up:
Could you solve thi... | true |
96ffd6f2d96e810840f4e8aab3bd3d5968f600ba | bitomann/classes | /pizza_joint.py | 1,322 | 4.625 | 5 | # 1. Create a Pizza type for representing pizzas in Python. Think about some basic
# properties that would define a pizza's values; things like size, crust type, and
# toppings would help. Define those in the __init__ method so each instance can
# have its own specific values for those properties.
class Pizza:
d... | true |
c05f369e874662f1f383cd25148e99c980f37d49 | Vohsty/password-locker | /user.py | 1,472 | 4.21875 | 4 | class User:
"""
Class to generate new instances of users
"""
user_list= [] # Empty user list
def __init__(self, f_name, l_name, username, password):
'''
To take user input to create a new user
'''
self.f_name = f_name
self.l_name = l_name
self.usernam... | true |
72d89fa9093ed5d9629c86480309380b87d871a2 | DiegoDeJotaWeb/uninove | /5 - LÓGICA DE PROGRAMAÇÃO/aula_05-06-2020/exer8.py | 394 | 4.125 | 4 | '''Para doar sangue é necessário ter entre 18 e 67 anos.
Faça um programa que pergunte a idade de uma
pessoa e diga se ela pode doar sangue ou não.'''
idade=int(input("Digite sua idade"))
if(idade >= 18 and idade <=67):
print("Sua idade é {}. Você pode doar sangue!".format(idade))
else:
print("Sua idade é {}... | false |
3f6e66a5e45651ee7fe6dd0454f771b6343edc29 | davidjbrossard/python | /hello.py | 669 | 4.3125 | 4 | import math as m
"""
This method takes in a string and returns another string. It encrypts the content of the string by using the Caesar cipher.
"""
def encrypt(message, offset):
encryptedString = "";
for a in message:
encryptedString+=chr(ord(a)+offset);
return encryptedString;
"""
This method ta... | true |
9473f6456519749d1b687bc83cf290e9d31316cf | KoushikRaghav/commandLineArguments | /stringop.py | 1,399 | 4.125 | 4 | import argparse
def fileData(fileName,stringListReplace):
with open(fileName,'w') as f:
f.write(str(stringListReplace))
print stringListReplace
def replaceString(replace,stringList,fileName,word):
rep = replace.upper()
stringListReplace = ' '
for w in stringList:
stringListReplace = w.replace(word, re... | true |
5ce58dda0c9928a43e3463e7447ce63f404c5e51 | brickfaced/data-structures-and-algorithms | /challenges/multi-bracket-validation/multi_bracket_validation.py | 2,197 | 4.34375 | 4 | class Node:
"""
Create a Node to be inserted into our linked list
"""
def __init__(self, val, next=None):
"""
Initializes our node
"""
self.val = val
self.next = next
def __repr__(self, val):
"""
Displays the value of the node
"""
... | true |
d1f9324a011cbbe33a65a2005115e06ab86f74d1 | brickfaced/data-structures-and-algorithms | /data-structures/binary_search_tree/fizzbuzztree.py | 602 | 4.5625 | 5 | def fizzbuzztree(node):
"""
Goes through each node in a binary search tree and sets node values to
either Fizz, Buzz, FizzBuzz or skips through them depending if they're
divisible by 3, 5 or both. The best way to use this function is to
apply it to a traversal method. For example: BST.in_order(fizzb... | true |
0a748373a51802c7500f8b6bd72cbd44d3f467d9 | brickfaced/data-structures-and-algorithms | /data-structures/hash_table/repeated_word.py | 857 | 4.125 | 4 | """Whiteboard Challenge 31: Repeated Word"""
from hash_table import HashTable
def repeated_word(text):
"""
Function returns the first repeated word.
First thing it does is splits the inputted string
into a list and for each word in that list it checks
if that word is already in the hash table, if ... | true |
b26893e0db5a57db2eed7de038eedc67337aecbf | abhaysingh00/PYTHON | /even odd sum of 3 digit num.py | 307 | 4.21875 | 4 | n= int(input("enter a three digit number: "))
i=n
sm=0
count=0
while(i>0):
count=count+1
sm=i%10+sm
i=i//10
if(count==3):
print(sm)
if(sm%2==0):
print("the sum is even")
else:
print("the sum is odd")
else:
print("the number entered is not of 3 digits")
| true |
ee3f8590f6a7be22bdf100b98b772aa9c09cc024 | o0brunolopes0o/Curso-em-video-exercicios | /ex044.py | 898 | 4.15625 | 4 | """
Exercício Python 44: Elabore um programa que calcule o valor a ser pago por um produto, considerando o seu preço normal
e condição de pagamento:
– à vista dinheiro/cheque: 10% de desconto
– à vista no cartão: 5% de desconto
– em até 2x no cartão: preço formal
– 3x ou mais no cartão: 20% de juros (no valor t... | false |
7bd2f2e61e7a2728c265e2606e06fc8e95e6d7e3 | aman1698/Semester-5 | /SEE/1/1a.py | 728 | 4.125 | 4 | def insert():
l=[]
while(True):
print("1-insert an element\n2-exit")
n=int(input())
if(n==1):
print("Enter the element")
n1=int(input())
l.append(n1)
else:
return l
l1=insert()
#l1=input().split()
print("Original List: ",l1)
l1.sort()
l2=len(l1)
print("Maximum Element ",l1[l2-1])
print("Minimum ... | true |
352066b731853c536a0c3d88bdb837092cdfc657 | aman1698/Semester-5 | /assignment4.py | 530 | 4.125 | 4 | dict={'O':'OXYGEN', 'N':'NITROGEN', 'C':'CARBON'}
print("Original Dictionary :", dict)
sym=input("Enter Unique Symbol : ").upper()
dict[sym]=input("Enter Name : ").upper()
print(dict,"\n")
print("Number of terms in Dictionary :",len(dict))
print("\n")
sym=input("Enter Symbol for element retrieval : ")
if sym in dict... | false |
a7f8be5252fe91554221a80ee00489284ddc87ab | wbsartori/ExerciciosPython | /2 - estrutura-de-decisao/1-Exercicio.py | 663 | 4.5 | 4 | """
Faça um Programa que peça dois números e imprima o maior deles.
"""
print('##############################################################')
print('####################### QUAL É MAIOR #########################')
print('##############################################################')
print('')
numero_um = int(i... | false |
e52e23f51a52d5c8fb1a242c19846028d0723126 | wbsartori/ExerciciosPython | /3 - estrutura-de-repeticao/6-Exercicio.py | 336 | 4.1875 | 4 | """
Faça um programa que imprima na tela os números de 1 a 20, um abaixo do outro.
Depois modifique o programa para que ele mostre os números um ao lado do outro.
"""
numero = 20
i = 0
while(i < numero):
i+= 1
print( '{}'.format(i))
j = 0
for j in range(numero):
j += 1
print( '{}'.format(j), en... | false |
ae9f409b6b7823bbc285a4f7e15812165c1de721 | PeriCode/PythWinter2018 | /py_kids2018/l06/quest.py | 1,884 | 4.34375 | 4 | print("""Вы - бабушка А. Очнулись вы в темном помещении.
Ваши действия:
1. Выглянуть в окно
2. Позвать на помощь
3. Попытаться позвонить""")
action = int(input("Выбор: "))
if action == 1:
print("""Вы выглянули в окно и узнали, что находитесь
на Пустошах. Перед домом пробегает двухметровый Радскорпион.
Просто так... | false |
3c089a72e04559e257a8972d563a5d6c0a21acb7 | PeriCode/PythWinter2018 | /py_kids2018/l02/digits.py | 567 | 4.21875 | 4 | number = 22
#print(number)
number = number + 10
#print(number)
number = number - 30
#print(number)
number = number * 10
#print(number)
number = number / 5
#print(number)
number += 5 # тоже самое, что и number = number + 5
number -= 5 # тоже самое, что и number = number - 5
number *= 5 # тоже самое, что и number =... | false |
9d20d1a57f32db564e29e662cefa6b2304d103c4 | PeriCode/PythWinter2018 | /PyNoFantasy2k18/l01/first.py | 738 | 4.34375 | 4 | print("Здравствуй, Амин" + ". Как твои дела?")
print(5) # целый тип - int
print(5.6) # дробный тип - float
print(int(7.6)) # преобразование float к int
print("I am a string") # строковый тип - str
print("5") # также строковый тип - str
print('3') # также строковый тип - str
print(True) # логический(булевый) тип ... | false |
8b83fbcfd31ba3cc1676ee16906a6bbd2935af98 | sanketsoni/6.00.1x | /longest_substring.py | 796 | 4.375 | 4 | """
Assume s is a string of lower case characters.
Write a program that prints the longest substring of s in which the letters occur in alphabetical order.
For example, if s = 'azcbobobegghakl', then your program should print
Longest substring in alphabetical order is: beggh
In the case of ties, print the first subst... | true |
72f2fa7a7980edb279f23269173545890ebd360b | mohor23/code_everyday | /binary_search(recursive).py | 701 | 4.125 | 4 | //binary search using recursion in python
def binary_search(arr,l,h,number):
if l<=h:
mid=(l+h)//2
if(arr[mid]==number):
return mid
elif(number<arr[mid]):
binary_search(arr,l,mid-1,number)
else:
binary_search(arr,mid+1,h,number)
else:
r... | true |
8b6df693a8931d87148817973e68ef401f524d73 | xuefengCrown/Learning-Python | /Beginning Python/database.py | 2,953 | 4.15625 | 4 | # Listing 10-8. A Simple Database Application
# database.py
import sys, shelve
def store_person(db):
"""
Query user for data and store it in the shelf object
"""
pid = raw_input('Enter unique ID number: ')
person = {}
person['name'] = raw_input('Enter name: ')
person['age'] = raw_input('Enter age: ')
pe... | true |
fafaffc7c97297e40be44fb5b0bd2b77b6bfb4e2 | InfinityTeq/Introduction-to-Python3 | /module05/m5-practice/data-comparison.py | 902 | 4.15625 | 4 | # for this module's practice:
# we will use sets to compare data
# created by : C0SM0
# sets of animals that can live on land and sea [respectively]
can_live_on_land = {"Wolves", "Alligator", "Deer"}
can_live_in_sea = {"Fish", "Dolphin", "Alligator"}
# create terrestial specific sets for the creature types
land_crea... | true |
534f12658f7dffa0efca11c00226adb79df46c76 | InfinityTeq/Introduction-to-Python3 | /module03/m3-practice/multiplication-tables.py | 682 | 4.4375 | 4 | # for this module's practice:
# we will make a program that will generate multiplication tables
# created by : C0SM0
# variables
range_limit = range(1, 13)
# iterate through each table
for table_number in range_limit:
# banner
print(f"\nMultiplication Table for {table_number}:")
# iterate through each ... | true |
8219a19e2e78f610f4acdff4d3139c5b65d36642 | mhamzawey/DataStructuresAlgorithms | /InsertionSort.py | 665 | 4.28125 | 4 | from BinarySearch import binarySearch
def insertionSort(arr):
"""
Insertion sort is a simple sorting algorithm
that works the way we sort playing cards in our hands.
:param arr:
:return: arr
Complexity O(n^2
"""
for i in range(len(arr)):
current = arr[i]
j ... | true |
af531dfc2e22c0b2ef6500bb74b484331f2c6ac7 | chokkalingamk/python | /Bitwise_operators.py | 588 | 4.28125 | 4 | #This is the Bitwise program to check
print ("Welcome to Addition Calculator")
print ("Enter the value A")
a = int(input())
print ("Enter the value B")
b = int(input())
and_val = (a & b)
or_val = (a | b)
xor_val = (a ^ b)
#not_val = (a ~ b)
left_val = (a << b)
right_val = (a >> b)
print ("The value of A is ", a )
print... | true |
955ba7fa1d1b396827c775318180d15ccf0b0ffe | ambateman/TechAcademy | /Python/PyDrill_Datetime_27_idle.py | 732 | 4.125 | 4 | #Python 2.7
#Branches open test
#Drill for Item 62 of Python Course
#
#The only quantity that should matter here is the hour. If the hour is between 9 and 21
#for that office, then that office is open.
import datetime
portlandTime = datetime.datetime.now().hour
nyTime = (portlandTime + 3)%24 #NYC is three hou... | true |
dc46be41cfc4becb94a1eeaec36fc098942b9fd7 | devyanshi-t/Contibution | /Codes/case.py | 493 | 4.34375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 13 10:25:35 2020
@author: devyanshitiwari
You are given a string and your task is to swap cases.
In other words, convert all lowercase letters to uppercase letters and vice versa.
"""
def swap_case(s):
x=""
for i in s:
if i.islower... | true |
37a1e9841cff3ceca38a39f3351a294f0efb1e0f | devyanshi-t/Contibution | /Codes/leapyear.py | 363 | 4.28125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 23 17:52:40 2020
@author: devyanshitiwari
"""
def is_leap(year):
leap = False
# Write your logic here
if(year%4==0 and year%100 !=0):
leap=True
elif(year%100==0 and year%400==0):
leap=True
ret... | false |
71e368e81fee53211cfecaed497d06a3b385f703 | eventuallyrises/CS61A | /hw1_q4.py | 624 | 4.125 | 4 | """Hailstone Sequence problem"""
def hailstone(n):
"""Print the hailstone sequence starting at n and return its length.
>>> a = hailstone(10) # Seven elements are 10, 5, 16, 8, 4, 2, 1
10
5
16
8
4
2
1
>>> a
7
"""
assert n > 0, 'Seed number %d is not greater than 0'... | true |
b457618da678f79c59ceb9b6e191e5c6a18df933 | Vivekyadv/InterviewBit | /Tree Data Structure/2 trees/1. merge two binary tree.py | 2,064 | 4.15625 | 4 | # Given two binary tree A and B. merge them in single binary tree
# The merge rule is that if two nodes overlap, then sum of node values is the new value
# of the merged node. Otherwise, the non-null node will be used as the node of new tree.
# Tree 1 Tree 2 Merged Tree
# 2 3 ... | true |
a79248bc4e2ee6c8146f7a292f336ccf6462b721 | Vivekyadv/InterviewBit | /Array/Arrangement/2. rotate matrix.py | 303 | 4.15625 | 4 | # rotate matrix by 90 ° clockwise
def rotate(A):
for i in range(len(A)):
for j in range(i,len(A)):
A[i][j], A[j][i] = A[j][i], A[i][j]
for i in range(len(A)):
A[i].reverse()
return A
arr = [
[1,2,3],
[4,5,6],
[7,8,9]
]
print(rotate(arr)) | false |
edcd7c026b3fd1a6122be4e78f13a77516a9c9e2 | Vivekyadv/InterviewBit | /String/String math/4. power of 2.py | 1,531 | 4.25 | 4 | # Find if Given number is power of 2 or not.
# More specifically, find if given num can be expressed as 2^k where k >= 1.
# Method 1: using log func
# 2 ^ k = num
# k*log(2) = log(num)
# k = log(num,2)
# if ceil value of k is equal to k then it can be expressed
num1 = "1024"
num2 = "1023"
from math import log, ceil
... | true |
cb1225395f4f4787d998a299bfa40e077da4421c | hualili/opencv | /deep-learning-2020S/20-2021S-0-2slicing-2021-2-24.py | 2,631 | 4.21875 | 4 | """
Program: 2slicing.py
Coded by: HL
Date: Feb. 2019
Status: Debug
Version: 1.0
Note: NP slicing
Slicing arrays, e.g., taking elements from one given index to another given index.
(1) pass slice instead of index as: [start:end].
(2) define the step like: [start:end:step].
(3) if we don't pass start its considered 0, ... | true |
894e677b208321a842d980a623f9a00bdee2ecea | gan3i/CTCI-Python | /Revision/LinkedList/remove_duplicates_2.1_.py | 2,738 | 4.15625 | 4 |
#ask questions
# 1. is it a doubly linked list or singly linked list
# 2. what type of data are we storing, integer? float? string? can there be negatives,
class Node():
def __init__(self,data):
self.data = data
self.next = None
# in interview do not write the linked list class assume that it's g... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.