blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
5def1bd799b63e16e9fe067bece1fa9b3d35141d | mikeodf/Python_Line_Shape_Color | /ch2_prog_9_rounded_rectangle_1.py | 2,454 | 4.28125 | 4 | """ ch2 No.9
Program name: rounded_rectangle_1.py
Objective: Draw a rounded rectangle using similar specifications to
a conventionl rectangle. The radius of the corners also needs to be stated.
Keywords: arc circle, rounded rectangle.
============================================================================... | true |
41da0cf9ef8c68bbdc2f84dfb3d24989f04dd417 | parhamafsharnia/AI_search_algorithms_Maze | /Cell.py | 663 | 4.3125 | 4 | class Cell:
"""A cell in the maze.
A maze "Cell" is a point in the grid which may be surrounded by walls to
the north, east, south or west.
"""
def __init__(self, point, n: bool = True, e: bool = True, s: bool = True, w: bool = True):
"""Initialize the cell at (x,y). At first it is surrou... | true |
28fbd5de71b5a0d4d483fb6ec95022a993f67b63 | vikanksha/Python-Book-Exercises | /condition_loops_program/median.py | 229 | 4.375 | 4 | # Write a Python program to find the median of three values.
val1 = int(input('Enter value 1:'))
val2 = int(input('Enter value 2:'))
val3 = int(input('Enter value 3:'))
if val1 < val2 and val2 < val3:
print('median is', val2) | true |
884e4a7f77c0482425607c3ce1d4fa1e627213d6 | vikanksha/Python-Book-Exercises | /devu_program/list_name.py | 249 | 4.28125 | 4 | # Write a program to return a list of all the names before a specified name.
list_of_names = eval(input(" "))
speci_name = input(" ")
list = []
for i in list_of_names:
if i == speci_name:
break
list_of_names.append(i)
print(list) | true |
e40638d4b9cec1d2f668f3a1a32870e0fd315e36 | vikanksha/Python-Book-Exercises | /chap3/ex1.py | 406 | 4.25 | 4 | # temp conversion
choice = eval(input("Enter selection"))
while choice !="F" and choice != "C":
temp = int(input("enter temp to convert"))
if choice == "F":
converted_temp = (temp-32)*5/9
print(temp , "degree fahrenheit is equal to" , converted_temp, "degree celcius")
else:
converted_temp = (9/5*temp)+3... | true |
2d087f0ac71902d13bcb45ec60dd6fb67108e7da | vikanksha/Python-Book-Exercises | /condition_loops_program/days_no.py | 510 | 4.46875 | 4 | # Write a Python program to convert month name to a number of days.
print("list of month : January, February, March, April, May, June, July, August, September, October, November, December")
Month = input("Enter month name :")
if Month == "Februrary":
print("no of days 28/29")
elif Month in ("January" , "March", "Ma... | true |
c12d509b78482c34fe24ffbecc37364adb0e7883 | vikanksha/Python-Book-Exercises | /devu_program/t4.py | 343 | 4.1875 | 4 | # 4. write a definition of a method COUNTDOWN(PLACES) to find and display those place names, in which there are more than 5 characters.
# ['DELHI', 'LONDON', 'PARIS', 'NEW YORK', 'DUBAI']
def countdown(places):
for p in places:
if len(p) > 5:
print(p)
print(countdown(['DELHI', 'LONDON', 'PARIS',... | false |
453ca9c00317b80931d41df787587320c5d616e4 | ZohanHo/PycharmProjectsZohan | /untitled3/Задача 10.py | 561 | 4.1875 | 4 | """В математике функция sign(x) (знак числа) определена так:
sign(x) = 1, если x > 0,
sign(x) = -1, если x < 0,
sign(x) = 0, если x = 0.
Для данного числа x выведите значение sign(x).
Эту задачу желательно решить с использованием каскадных инструкций if... elif... else."""
x = int(input("введите x: "))
if ... | false |
6b59d6be3f0e4ba1be591d40f7bd5c4a645064c3 | ZohanHo/PycharmProjectsZohan | /untitled3/Задача 5.py | 329 | 4.125 | 4 | """Условие «Hello, Harry!»
Напишите программу, которая приветствует пользователя, выводя слово Hello, введенное имя и знаки препинания по образцу:"""
z = str(input("Введите имя: "))
print("Hello " + z + "!") | false |
5e1c459f721bfc9c0084f9102d265333113f6f5e | GeekBM/python_hometask | /lesson_3/4.py | 427 | 4.1875 | 4 | x = abs(float(input('Введите действительное положительное число х ')))
y = int(input("Введите целое отрицательное число у "))
while y >= 0:
y = int(input('Вы ввели не отрицательное число. Введите целое отрицательное число у '))
def my_func (x, y):
return x ** y
print(my_func (x, y))
| false |
2793480aa76bb6f501a940ab321ce9c18d182579 | af0262/week9 | /bubble_sort2.py | 627 | 4.375 | 4 | import random
def sort(items):
# 1. TO DO: Implement a "bubble sort" routine here
for outer in range(len(items)):
for inner in range(len(items)-1-outer):
if items[inner] > items[inner+1]:
items[inner], items[inner+1] = items[inner+1], items[inner] # Swap!
return items
... | true |
9d6fe91d37141db9f013eb58c4b971eebc4714c3 | IghnatenkoMatvey/ip-Ignatenko-Matvey-1 | /lesson2/PythonClass 2.py | 1,281 | 4.125 | 4 | # >
# <
# ==
# !=
# <=
# >=
# x = 5 > 10
# type(x)
# print(x)
# x = 1
# print(x)
# x = True
# if x == 1 or x:
# print('yes')
# elif x:
# print('Noway')
# else:
# print('No')
#
# original_password = 'x777'
# password = input('Введите пароль: ')
# access = 0
# if password == original_password:
# print('Па... | false |
7551611f9a88fd54b427b21bb02f02cbb7e12f6a | payal8797/Algo | /bubble.py | 472 | 4.28125 | 4 | def bubble(array):
array=[]
n=int(input("Enter number of elements:"))
for s in range(n):
m=int(input())
array.append(m)
print("Elements are:",array)
for i in range(n):
for j in range(n-i-1):
if(array[j]>array[j+1]):
array[j],array[j+1]=array[j+1],a... | false |
50741e2a960c9bc0158f8c32819083126e4928bc | nikiknak/fundamentos_de_informatica | /ejercicios guia 1/ej5 G1.py | 276 | 4.1875 | 4 | #5: Realizar un programa que lea tres números por teclado y calcule el promedio de ellos.
num1 = int(input("ingrese un número:"))
num2 = int(input("ingrese otro numero:"))
num3 = int(input("ingrese otro numero:"))
promedio = (num1 + num2 + num3) / 3
print(int(promedio))
| false |
796cb0250390e87782d2422d475f2914fd093804 | nikiknak/fundamentos_de_informatica | /Segunda parte /guia Pandas 2/ej5.py | 348 | 4.125 | 4 | #Ejercicio 5
#Realizá un programa que verifique si una columna dada se encuentra presente en un DataFrame.
import pandas as pd
datos = {"A": [1,2,3,4], "B": [5,6,7,8], "C": [9,10,11,12]}
df=pd.DataFrame(data=datos, index=["w","x","y","z"])
print(df)
verifique = "A" in df.columns
print(verifique)
verifique2 = "a" in df... | false |
87d299f0568c4c3e0b949af5a542e9d8d6a2ffd9 | juandaangarita/CursoBasicoPython | /multiplication_tables.py | 300 | 4.125 | 4 | def multiplication_table(number):
for i in range (10):
print(str(number) + ' x ' + str(i) + ' = ' + str(number*i))
def run():
number = int(input('Enter the number you want to know the multiplication table: '))
multiplication_table(number)
if __name__ == '__main__':
run() | false |
8cb06562dd43a5863811bf471e0ecf94baa7d1f1 | juandaangarita/CursoBasicoPython | /Fibonacci.py | 795 | 4.59375 | 5 | def fibonacci(nth):
fibonacci_sequence = [0, 1]
for i in range(2, nth + 1):
fibonacci_sequence.append(fibonacci_sequence[i-1] + fibonacci_sequence[i-2])
print(fibonacci_sequence)
def fibonacci_recursion(nth):
"""
Calculate fibonacci sequence of a number in a recursive way
:param nth: ... | false |
9a0fc1b30c2cbdc5926cf542bfab58d841f7f90d | juliaguida/learning_python | /week8/leap_year.py | 891 | 4.46875 | 4 | # def year_leap(year):
# #If a year is multiple of 400 it is a leap year.
# if year %400 == 0:
# #print('This is a year leap ')
# if year %4 == 0:
# #print('This is a year leap')
# if year %100 == 0:
# #print('This is not a year leap')
# return True
# else:
# ... | false |
705ab198790777f50fbf874d7beff92f974c7c43 | juliaguida/learning_python | /week5/function_add.py | 289 | 4.125 | 4 | # Write a program that takes 2 numbers as arguments to a function and returns the sum of those 2 numbers
def add_func(number1,number2):
return number1 + number2
numb1 = int(input('Enter a number: '))
numb2 = int(input('Enter another: '))
result = add_func(numb1,numb2)
print(result) | true |
b9691374f143af16f1cdc6065a7d727f09b16964 | juliaguida/learning_python | /week4/choose_a_side.py | 385 | 4.28125 | 4 | import turtle
def shape(number_of_sides,side_length):
angle = 360/number_of_sides
for i in range(number_of_sides):
turtle.forward(side_length)
turtle.right(angle)
turtle.done()
number_of_sides = int(input('Please input the numbers of side: '))
side_length = int(input('Please ... | true |
eec05c50c073b60c0bf7d04b046c3501e33580ff | juliaguida/learning_python | /homework.py/week8/check_numb.py | 235 | 4.6875 | 5 | # This code checks if a number is positive or negative
number = float(input('Please enter a number to check if it is negative or positive.'))
if number > 0:
print('The input is positive')
else:
print( 'This input is negative')
| true |
4c79e7f0179e3220a55ec56c15845cb283abf844 | wafarifki/Hacktoberfest2021 | /Python/linked_list_reverse.py | 853 | 4.1875 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None # Head of list
def reverse(self, head):
if head is None or head.next is None:
return head
rest = self.reverse(head.next)
head.next.next = head
head.next = None
return... | true |
f5e60e6364aa94698b52f6bf9faf42cda94f19e7 | franktank/py-practice | /fb/hard/145-binary-tree-postorder-traversal.py | 1,324 | 4.125 | 4 | """
Given a binary tree, return the postorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3},
1
\
2
/
3
return [3,2,1].
Note: Recursive solution is trivial, could you do it iteratively?
"""
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(s... | true |
6fb49004c5a722c118e6ac007c4b58945f169f01 | Selva0810/python-learn | /string_to_integer.py | 2,814 | 4.25 | 4 |
'''
String to Integer (atoi)
Solution
Implement atoi which converts a string to an integer.
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character takes an optional initial plus or minus sign followed by as many nu... | true |
5b399f2b01afcc2f26ad07af5108e38e22eb2315 | hoppang0817/Python | /If-else.py | 1,146 | 4.125 | 4 | if True:
print('if문 실행1')
print('if문 실행2')
print('if문 실행3')
print('if문아님')
name = 'Alice'
if name == 'Alice':
print('Hi,Alice')
print('종료')
print('\n')
# if else
# name = '밥'
# if name == '앨리스':
# print('당신이 앨리스군요')
# else:
# print('누구인가')
# if elif else
name = '밥'
if name == '앨리스':
p... | false |
3e818dbefab6bd432a04a9fa1332ef0aaa44ad70 | asadiqbalkhan/shinanigan | /Games/guess.py | 1,404 | 4.34375 | 4 | # This is a guess the random number game
# import random function
# Author: Asad Iqbal
# Language: python 3
# Date: 18 - June - 2017
import random
# variable to store the total guesses done by the player
guesses_taken = 0
# Display welcome message to the player
# Input required by the player at this stage to proceed
... | true |
7d770f3d71e16201a74e82b07fe793ca00679139 | JunboChen94/Leetcode | /junbo/LC_173.py | 1,378 | 4.125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class BSTIterator:
'''
Based on inorder
'''
def __init__(self, root: TreeNode):
self.stack = []
... | true |
672a9eeac7871138036f566ae12e4ca6b9137e15 | Collinslenjo/pythondata | /hello-world/datatypes.py | 1,960 | 4.15625 | 4 | # Datatypes and Ints using operators
#Addition
age1 = 20
age2 = 42
age3 = age1 + age2
print(age3)
#subtraction
age1 = 20
age2 = 42
age3 = age1 - age2
print(age3)
#multiplication
age1 = 20
age2 = 42
age3 = age1 * age2
print(age3)
#division
age1 = 20
age2 = 42
age3 = age1 / age2
print(age3)
#modulus
age1 = 20
age2 = 42
a... | false |
b1fac02cb617d774d738774769c6a836fc15607c | smkrishnan22/python-basics-to-ml | /language/Product.py | 753 | 4.375 | 4 | '''
class Product:
# Default Constructor.
def __init__(self):
self.productid = 10
self.productname = "Ashok"
_instance = Product()
print(_instance.productid)
'''
class Product:
# This is Constructor.
# We can have only one constructor in Python.
def __init__(self, ids, name... | true |
d9f51fbaf3cf11226bf18110aa04a79c3be58883 | jyotsanaaa/Python_Programs | /find_lcm.py | 341 | 4.21875 | 4 | #Find LCM
#LCM Formula = (x*y)//gcd(x,y)
num1 = int(input("Enter lower num : "))
num2 = int(input("Enter greater num : "))
#To find GCD
def gcd(x,y):
while(y):
x,y = y, x%y
return x
#To find LCM
def lcm(a,b):
lcm = (a*b)//gcd(a,b)
return lcm
print(f"LCM of {num1} and {num2} ... | true |
3460833f74721665e81bd89924e6fcd2e33691df | jyotsanaaa/Python_Programs | /conversion.py | 237 | 4.34375 | 4 | #Convert decimal to binary, octal and hexadecimal
num = int(input("Enter number in decimal : "))
print(f"\nConversion of {num} Decimal to :- ")
print("Binary :",bin(num))
print("Octal :",oct(num))
print("Hexadecimal :",hex(num)) | true |
39a1712a4f8f9e2e3ed646a1e45fe209f34d3457 | jyotsanaaa/Python_Programs | /armstrong_num.py | 588 | 4.21875 | 4 | #Armstrong Number
"""An Armstrong number is an n-digit base b number such that the sum of its (base b) digits raised to the power n is the number itself.
Eg: 407 is sum of cube of three num i.e.4,0,7 && 1634 is sum of ^4 of 4 num i.e.1,6,3,4"""
#import math
n = int(input("Enter number : "))
order = len(str(n))
#order ... | true |
b659bb7fa3f753e538e21d80c5708e24a877df7d | Anvitha-N/My-Python-Codes | /assign list.py | 402 | 4.4375 | 4 | #Assigning elements to different lists:
animals = ["dog","monkey","elephant","giraffee"]
print(animals)
#replace
animals[1] = "chrocodile"
print(animals)
#insert
animals.insert(2,"squirrel")
print(animals)
#sort
animals.sort()
print(animals)
#delete
del animals[0]
print(animals)
#append
animal... | true |
1aba9eba32f19c6c6cf27ad8bd7ad508a36623cc | aniqmakhani/PythonTraining | /Assignment3.py | 1,716 | 4.1875 | 4 | # Question No: 01 Write a Solution to reverse every alternate k characters from a
# string. Ex. k = 2 , Input_str ="abcdefg", Output_str = bacdfeg"
print("Question 1: ")
Input_str = input("Enter a string: ")
k = int(input("Enter a value for k: "))
inp = list(Input_str)
for i in range(0,len(inp),k+2):
if i+1 < len(... | true |
9e9d2b081559d045b18042e00fa8f2cb93ec737d | venkat79/java-python | /python/src/main/python/testscripts-master/inner/couple.py | 1,016 | 4.5 | 4 | '''
Consider the following sequence of string manipulations -
abccba
abccba - "cc" is a couple as both appear together. Remove the couple from the string and count as "1 couple"
abba - Resulting string after removing the couple
abba - Now "bb" is a couple. Remove the couple from the string and increment the count to 2... | true |
b4396c661758a357af1ce8df15fffe7cc527e0a4 | JiteshCR7/Python_Lab | /lab2.py | 2,537 | 4.125 | 4 | Python 3.7.3 (default, Apr 3 2019, 05:39:12)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license()" for more information.
>>> 2**5
32
>>> a=20
>>> b=30
>>> c=a+b
>>> c
50
>>> a=input("enter value of a;")
enter value of a;20
>>> b=input("enter value of b;")
enter value of b;30
>>> c=a+b
>>> c
'2030'
>... | true |
5c0984cc0b0a40f72149458f3ac64e11e1f7080b | LEXW3B/PYTHON | /python/exercicios mundo 1/ex005/ex007.py | 516 | 4.25 | 4 | #faça um programa que leia uma frase pelo teclado e mostre.(quantas vezes aparece a letra 'a'),(em que posição aparece a primeira vez),(em que posição ela aparece a ultima vez).
frase = str(input('digite uma frase: ')).upper().strip()
print('a letra A aparece {} vezes na frase'.format(frase.count('A')))
print('a primei... | false |
a89692d005e1004b5aa9ea7ebe98f5678f2e7ea2 | LEXW3B/PYTHON | /python/exercicios mundo 2/ex56_65.py/ex009.py | 823 | 4.28125 | 4 | '''65-CRIE UM PROGRAMA QUE LEIA VARIOS NUMEROS INTEIROS PELO TECLADO. NO FINAL DA EXECUÇÃO , MOSTRE A MEDIA ENTRE TODOS OS VALORES E QUAL FOI O MAIOR E O MENOR VALOR LIDO. O PROGRAMA DEVE PERGUNTAR AO USUARIO SE ELE QUER OU NÃO CONTINUAR A DIGITAR VALORES. '''
resposta='S'
soma=quantidade=media=maior=menor=0
while re... | false |
857a992f5c12f1730f642e0f3682746df4dabb19 | abhiramvenugopal/vscode | /Spoj_test/String_Rotation.py | 493 | 4.15625 | 4 | def isSubstring(s1, s2):
if s1.find(s2) != -1:
return True
if s2.find(s1) != -1:
return True
return False
## Do not change anything above
def isRotation(s1,s2):
s1s1=s1+s1
print(isSubstring(s2,s1s1))
## You can only call isSubstring function from this function once. Use this fu... | true |
b434bbb41e4676059a29526d553ffab35cb337aa | abhiramvenugopal/vscode | /5-26-2021/even_odd_seperator.py | 616 | 4.28125 | 4 | # Write a function with name even_odd_separator, you should exactly the same name
# This even_odd_separator functions should take a list of integers and return a list
# you can start from here
def even_odd_separator(numbers):
odd_list=[]
even_list=[]
for i in numbers:
if i%2==0:
even_li... | true |
4435d655b68aa16413b065fcfcb71e78fdebd920 | abhiramvenugopal/vscode | /5-16-2021/int_palindrome.py | 384 | 4.125 | 4 | # Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward
# Input
# 1 containing integer
# Output
# 1 line containing Boolean value
# Example
# Input: 121
# Output: True
# Input: 10
# Output: False
# ----------------------------------------------------... | true |
771febd6086b7ad67fa38173fb1be2b77c08fb47 | abhiramvenugopal/vscode | /special/odd_even_or_one_zero_subset.py | 1,094 | 4.28125 | 4 | # You are given an array A of N positive integer values. A subarray of this array is called Odd-Even subarray if the number of odd integers in this subarray is equal to the number of even integers in this subarray.
# Find the number of Odd-Even subarrays for the given array.
# Input
# The input consists of two lines.... | true |
7dc39930c14219cb9f4badd0dce651d25368af14 | vmsouza30/520 | /Aula2/media3.py | 841 | 4.125 | 4 | #!/usr/bin/python3
# está validando para entrada de nova até 10, se for maior avisa com erro, e faz a qtdade -1 para tirar da media
# caso queira que force sempre para entrar com um valor correto, utilizar WHILE e tirar qtdade -1
qtdadenotas = int(input('Digite a quantidade de notas: '))
total = 0
# ou total = float(... | false |
a30f89daa5285607b61fe43398259de765d1ba61 | nfredrik/pyjunk | /regexps/notmatch.py | 442 | 4.3125 | 4 | import re
#
#I'm looking for a regular expression that will match all strings EXCEPT those that contain
# a certain string within. Can someone help me construct it?
#For example, looking for all strings that do not have a, b, and c in them in that order.
#So
#abasfaf3 would match, whereas
#asasdfbasc would not
r = r... | true |
81a86c2aa78e6ed3f85d3d8a842548b99c0fe19a | CodaGott/introtopythonforcomputerscienceanddatascienceexercises | /Chapter_two_exercises/Exercise2.2.py | 495 | 4.15625 | 4 | """ (What’s wrong with this code?) The following code should read an integer into the
variable rating:
rating = input('Enter an integer rating between 1 and 10') """
rating = input('Enter an integer rating between 1 and 10')
""" The above code can be casted on declaration
or casted at calculation
to cas... | true |
2c64537f7f567b2dc9dda6f18049aad51798a4cc | CodaGott/introtopythonforcomputerscienceanddatascienceexercises | /Chapter_two_exercises/ChapterOneExercises.py | 460 | 4.53125 | 5 | """ (What does this code do?) Create the variables x = 2 and y = 3, then determine what
each of the following statements displays:
a) print('x =', x)
b) print('Value of', x, '+', x, 'is', (x + x))
c) print('x =')
d) print((x + y), '=', (y + x)) """
x = 2
y = 3
print('x=', x) #this will print 2
print('Value of', x, '+... | true |
20549ee8b2bd75ddb1542eac4b074b2e94bafdc4 | gordonmannen/The-Tech-Academy-Course-Work | /Python/Python 3 Essential Training - Py3.5.1/GettingStarted.py | 2,247 | 4.125 | 4 | print("Hello, World!")
a, b = 0, 1
if a < b:
print('a ({}) is less than b ({})'.format(a, b))
else:
print('a ({}) is not less than b ({})'.format(a, b))
a, b = 5, 1
if a < b:
print('a ({}) is less than b ({})'.format(a, b))
else:
print('a ({}) is not less than b ({})'.format(a, b))
# blocks are call... | true |
cb34d3c7a7399b0f513fb090182eef540f89adb8 | Menelisi-collab/Classes-exercise | /izibalo.py | 532 | 4.125 | 4 | def task(self):
a = int(input("Enter a Number: "))
b = int(input("Enter another Number: "))
total = (a + b) or (a - b) or (a * b) or (a / b)
if total == (a + b):
print(f"The added result is: {total}")
elif total == (a - b):
print(f"The subtracted result is: {total}")
elif total ... | true |
9ed540608eca140a8697e457b03b38d4095fe363 | lakshay451/Deep-Neural-Networks-with-PyTorch | /Week 1/2_D Tensors.py | 2,461 | 4.4375 | 4 | # -*- coding: utf-8 -*-
"""
2-D Tensors
"""
"""
A 2d tensor can be viewed as a container the holds numerical values of the same type.
In 2D tensors are essentially a matrix. Each row is a different sample and each column is a feature or attribute.
We can also represent gray-scale images as 2D tensors. ... | true |
afef11b98745fda79c08dfeada6308919b6f4e54 | yerimJu/crawling_examples | /src/using_DB/sqlite3_test.py | 604 | 4.46875 | 4 | import sqlite3 # standard library for Python
DB_PATH = 'test.sqlite'
conn = sqlite3.connect(DB_PATH)
cur = conn.cursor()
cur.executescript('''
DROP TABLE IF EXISTS items;
CREATE TABLE items(
item_id INTEGER PRIMARY KEY,
name TEXT UNIQUE,
price INTEGER
);
INSERT INTO items(name, price) VALUES ('Apple', 8... | true |
7bc6de20ac5d4841019ad7c2917ea9750367f668 | garciagenrique/template_project_escape | /template_project_escape/code_template_escape.py | 1,213 | 4.15625 | 4 | # -*- coding: utf-8 -*-
# Template module with an example for the ESCAPE project
import numpy as np
import argparse
def square_number(number):
"""
Function that returns the square of the input number.
Parameters:
-----------
number: int or float
Number to square.
Returns:
... | true |
b8a91f071c64be352a59299c737e21c6d8161ba5 | chuajunyu/scvu-git-tutorial | /HW1/HW01_YuHong.py | 2,553 | 4.1875 | 4 | from operator import add, sub
#Question 1
def a_plus_abs_b(a, b):
# """Return a+abs(b), but without calling abs.
# >>> a_plus_abs_b(2, 3)
# 5
# >>> a_plus_abs_b(2, -3)
# 5
# """
if b < 0:
f = sub
else:
f = add
return f(a, b)
# print(a_plus_abs_b(5,10))
# print(a_pl... | false |
0db16e37cd7b9e2d3842aba851cadf5b3902db99 | ColeMaddison/hillel_python | /python_3/hw_3_1.py | 590 | 4.25 | 4 | # Задача-1
#
# Дан произвольный текст. Соберите все заглавные буквы в одно слово в том порядке
# как они встречаются в тексте.
# Например: текст = "How are you? Eh, ok. Low or Lower? Ohhh.", если мы соберем все
# заглавные буквы, то получим сообщение "HELLO".
text = "How are you? Eh, ok. Low or Lower? Ohhh."
def u... | false |
469bf83faa1aab82227c840113430b0b92437367 | rebeccaAhirsch/frc-hw-submissions | /lesson5/hw_5.py | 262 | 4.21875 | 4 | words = ["red", "blue", "green", "purple", "magenta", "great", "wonderful", "yay!", "koala", "hi"]
anything = raw_input("what's your favorite word?")
if (anything in words) == True:
print "i like that word too"
else:
words.append(anything)
print words
| true |
56f8ba5742d98072231765d565a7a7d479c875b1 | Ivanlxw/Exercises | /Mega Project LIst/Numbers/MortgageCalculator.py | 2,426 | 4.34375 | 4 | def calculate_payment():
"""
Calculate the monthly payments of a fixed term mortgage over Nth terms at a given interest rate.
Extra: add an option for users to select the compounding interval (Monthly, Weekly, Daily, Continually).
"""
interval = int(input("Select compounding interval:\n1.Monthly\n2... | true |
89e882d4aae56b3c457f1398e4e775d1f5fc6220 | yudianzhiyu/Notebook | /mystuff/ex30.py | 446 | 4.15625 | 4 | #!/usr/bin/python
people = 30
cars = 40
buses = 15
if cars > people:
print "we should take the cars."
elif cars < people:
print " we shoule not take the cars."
else:
print " we can't decide."
if buses> cars:
print "that's too many buses."
elif buses<cars:
print "may be we could take buses."
else:
print "we stil... | true |
71ae734bbe1057377b22c9b5bf06ecfa649eee5d | silvesterriley/hello--world | /code.py | 736 | 4.1875 | 4 | message="hello python"
print(message)
#variables to hold my names
firstname="Silvester"
middlename="Muthiri"
lastname="Marubu"
Age=24
#i want to print my details
print("My first name is", firstname)
print("My middle name is" ,middlename)
print("My last name is" ,lastname)
print(Age,"years old")
#p... | true |
1081929f35684cb77485cbd588643048a6c142ae | sofide/ds_dices | /ds_dices.py | 1,463 | 4.28125 | 4 | black_dice = [0, 1, 1, 1, 2, 2]
blue_dice = [1, 1, 2, 2, 2, 3]
orange_dice = [1, 2, 2, 3, 3, 4]
def convert_string_to_dict_dices(string_input):
dices_str_list = string_input.split()
if not dices_str_list:
raise ValueError()
try:
dices_int_list = [int(n) for n in dices_str_list]
excep... | true |
730c640969690b391503c4446314d4a5148f787a | mxu007/daily_coding_problem_practice | /DCP_10_1.py | 2,195 | 4.15625 | 4 | # Determine if a cycle exists
# Given an UNDIRECTED graph, determine if it contains a cycle
# implement the solution using depth-first search. For each vertex in the graph, if it has not already been visited. we call our search function on it. This function will recursively traverse unvisited neighbors of the vertex a... | true |
ec4f6c3dc4159ec63b7535f4bd9cd8696d811a6b | mxu007/daily_coding_problem_practice | /DCP_7_2.py | 864 | 4.1875 | 4 | # Given a sorted array, convert it into a height-balanced binary search tree
# As asked for a height-balanced tree, we have to pick the middle value in the sorted array to be the root
class Node:
def __init__(self, data, left=None, right =None):
self.data = data
self.left = left
self.right... | true |
eaac00d6251b9da52cc54f0b2bde44f63b36a5db | mxu007/daily_coding_problem_practice | /DCP_1_2.py | 2,088 | 4.15625 | 4 | # Given an array of integers that are out of order, dtermine the bounds of the smallest window that must be sorted in order for the entire array to be sorted.
# Example Input: [3,7,5,6,9], Sorted Input: [3,5,6,7,9]
# Output: (1,3)
# Example Input: [1,5,2,3,8,6,7,9]
# Output: (1, 6)
# use python built-in sort functio... | true |
89267563c2bcfd9d0f5c97344074423be79cd57b | kunjabijukchhe/python | /kunja14.py | 1,087 | 4.28125 | 4 | '''a= float(input("enter a first number:"))
b= float(input("enter a second number:"))
op=input("enter a operator:")
if op=="+":
print(a+b)
elif op =="-":
print(a - b)
elif op =="*":
print(a * b)
elif op =="/":
print(a / b)
else:
print("invalid")'''
def deposite(x,y):
... | false |
a268bd67d22631549b68cf6d40c59bda9b5b62ec | PBNSan/Python-Code-Samples | /building_sets.py | 472 | 4.125 | 4 |
squares = set()
# todo: populate "squares" with the set of all of the integers less
# than 2000 that are square numbers
# Note: If you want to call the nearest_square function, you must define
# the function on a line before you call it. Feel free to move this code up!
def nearest_square(limit):
answ... | true |
fdc53ef4c37d355099124759f0c888fb077baeb6 | Bes0n/python2-codecademy | /projects/area_calculator.py | 920 | 4.375 | 4 | """
Area Calculator
Python is especially useful for doing math and can be used to automate many calculations. In this project, we'll create a calculator that can compute the area of the following shapes:
Circle
Triangle
The program should do the following:
Prompt the user to select a shape.
Calcula... | true |
32cdc29f0c982373cb97107bafb3d9f0d1a16923 | althafuddin/python | /Python_Teaching/introduction/addition.py | 424 | 4.25 | 4 | def calc_addition(int_a,int_b):
""" Add the given two numbers """
try:
print (int(int_a) + int(int_b))
except ValueError:
print('You have to enter integers only!')
while True:
number_1 = input("Enter your first number: ")
number_2 = input("Enter your second number: ")
if (numbe... | true |
e3c048c7444db6c50ada2f4ed8b4f2291e517443 | Divya-vemula/methodsresponse | /strings/dict.py | 699 | 4.59375 | 5 | # Creating, accessing and modifying a dictionary.
# create and print an empty dictionary
emptyDictionary = {}
print("The value of emptyDictionary is:", emptyDictionary)
# create and print a dictionary with initial values
grades = {"John": 87, "Steve": 76, "Laura": 92, "Edwin": 89}
print("\nAll grades:", grades)
# acces... | true |
170d56e759e95b32561c83cbe3478684604ad616 | RoanPaulS/List_Python | /list_operations.py | 722 | 4.3125 | 4 | square = [1,2,3,4];
print(square);
print(square[0]);
square.append(0);
print(square);
square.append(121**2);
print(square);
print();
print();
# removing list elements
letter = ["a","b","c","d","e","f","g","a"];
print(letter);
print("Length is ",len(letter));
letter[2:5] = [];
print(letter);
print("Le... | false |
4e52a490ec4ac9b4b8f07bda697464cd41a0476b | puthalalitha/calculator | /calculator.py | 1,990 | 4.3125 | 4 | """A prefix-notation calculator.
Using the arithmetic.py file from Calculator Part 1, create the
calculator program yourself in this file.
"""
from arithmetic import *
# Your code goes here
# No setup
# repeat forever:
# read input
# tokenize input
# if the first token is "q":
# quit
# else:... | true |
c13188089e7d5e6d3359d5f8642befcdfb2f1aed | Tarajit-Singh/python-lab-programs- | /5.1)experiment.py | 475 | 4.4375 | 4 | """
5.1) Implement a python script to count frequency of characters in a given string.
"""
s=input("enter the string")
result = {}
for letter in s:
if letter not in result:
result[letter.lower()] = 1
else:
result[letter.lower()] += 1
print("count frequency of characters in given string:",res... | true |
130500eda364a84fa4398a12cd625bf5a832c4a1 | chasebleyl/ctci | /data-structures/interview-questions/arrays_and_strings/1_6.py | 1,808 | 4.125 | 4 | # String Compression: Implement a method to perform basic string compression using the counts of repeated characters. For example, the string aabcccccaaa would become a2blc5a3. If the "compressed" string would not become smaller than the original string, your method should return the original string. You can assume the... | true |
eaa2834a381ad0a864cb9b5433d429ee183e0347 | osluocra/pachito_python | /code/s04/RosetteGoneWild.py | 457 | 4.15625 | 4 | # RosetteGoneWild.py
import turtle
t = turtle.Pen()
turtle.bgcolor('black')
t.speed(0)
t.width(3)
# Ask the user for the number of circles in their rosette, default to 6
number_of_circles = int(turtle.numinput("Number of circles",
"How many circles in your rosette?", 6))
color_of... | true |
0d764e769012d326598de8bdeb714a665cda1354 | sophiebuckley/cipher-project | /vigenerecipher.py | 2,035 | 4.625 | 5 | #A function which performs the Vigenere encryption algorithm on an input phrase.
key = raw_input("Please enter the keyword that you would like to use for your encryption: ")
message = raw_input("Please enter the message that you would like to encrypt: ")
def encrypt_vigenere(key, plaintext):
return vigenere_calc... | true |
d2ad9df2d675da2a918b47c296940014d44dfaaf | Keegan-Cruickshank/CP1404 | /prac_05/word_counter.py | 557 | 4.5625 | 5 | """
Simple application to display the frequency of all words from a users input.
"""
text_input = input("Text: ")
word_count_dict = {}
word_list = text_input.split(" ")
for word in word_list:
if word.lower() in word_count_dict:
word_count_dict[word.lower()] += 1
else:
word_count_dict[word.lowe... | true |
fde1d6e88a167908ec38df2789a956294f4a8c92 | CristinaHG/python-Django | /python-Django/ExampleCourse/HelloWord.py | 1,072 | 4.3125 | 4 | # -*- coding: utf-8 -*-
print ("Hello World")
#collections and comments
#List
fruits=['Banana','Strawberry','Apple','Grapes']
print(fruits[0])
print(fruits[-1])
print(fruits[-3])
#List slicing
numbers=[0,1,2,3,4,5,6,7,8,9,10]
from_2to7=numbers[2:7]
print from_2to7
geatherThan3=numbers[3:]
print geatherThan3
pairsNum... | true |
f637759e6ebeac0ecc1bbb261f036568edad91d5 | adebudev/holbertonschool-higher_level_programming | /0x0B-python-input_output/0-read_file.py | 275 | 4.21875 | 4 | #!/usr/bin/python3
"""
function that reads a text file
"""
def read_file(filename=""):
"""
read_file - Read a text file
filename - Name of a File
"""
with open(filename, mode="r", encoding="utf-8") as file_open:
print(file_open.read(), end='')
| true |
d5c8046b9e8fa70ac2a690981311d8f29c89315c | heyjohnnie/MVA-Introduction-to-Python | /ShortStory/ShortStory/ShortStory/ShortStory.py | 792 | 4.4375 | 4 | #This program creates a short story based on user's input
#Welcome message
print("Welcome to Story Teller v1.0")
print("Let's create a short story where you'll be the main character!")
print("First, we need some info about you")
#Getting data and making sure to correct the input
firstName = " "
firstName = input("Wha... | true |
7256cea75dbad959fe52a797fa503fa3640b3c1e | mjruttenberg/battleships | /battleships_py3.py | 1,416 | 4.15625 | 4 | from random import randint
# create and populate the board
board = []
for x in range(5):
board.append(["O"] * 5)
# convert the board to space delimited and print the board
def print_board(board):
for row in board:
print(" ".join(row))
print_board(board)
# create the battleship X and Y axis position... | true |
6ce4addde50d84d479b1d5e82cf6c5ea3c837013 | bmadren/MadrenMATH361B | /IntroToProgramming/I8_PrimeFunc_Madren.py | 494 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Feb 17 20:58:00 2019
@author: benma
"""
def prime_check(N):
is_prime = True
if (N >= 2):
for i in range(2, N):
if((N % i) == 0 and N != i):
is_prime = False
else:
return False
return is_prime
n = 6
plist = []
count... | false |
efc3b3713d3a98bac2f580bd7f55337485030f1f | deusdevok/pythonMergeSort | /mergeSort.py | 839 | 4.21875 | 4 | #######################
### MERGE ALGORITHM ###
#######################
import numpy as np
def mergesort (arr): # Sort array 'arr'
n = len(arr)
if (n == 1):
return arr
l1 = arr[0:int(n/2)]
l2 = arr[int(n/2):n]
l1 = mergesort(l1)
l2 = mergesort(l2)
return merge(l1,l2)
def merge (a,b): # Merg... | false |
492ad5738e83acdf1f4427af015eb9f95b3e597c | lion137/Functional---Python | /trees.py | 1,193 | 4.21875 | 4 | # define an abstract data - binary tree - pairs and functional abstraction
from functional_tools_python.immutable_lists import *
def construct_tree(val, left, right):
"""constructs a tree as a List, holds
as a first elem a value in a node, second and
third elements are left, right branches (also trees)"""... | true |
b520e97e73dd7cd2b9798ad22e3c6740286b913a | JustinDudley/Rubiks-Cube-One | /string_to_list.py | 1,239 | 4.4375 | 4 | # This module takes a Rubik's Cube algorithm, perhaps inputed by a user, and
# converts it to a list, so that it can be manipulated by other programs as a list
def convert_to_list(alg_stri):
# Takes a string and converts it to a list, for better functionality in manipulation by other programs.
# This function assum... | true |
dc7235719a4d37ae8dd3fff65023a67fa644d9a3 | Adam-Davey/cp1404_pracs | /prac_05/color_names.py | 497 | 4.21875 | 4 | COLOR_NAMES = {"turquoise": "#40e0d0", "yellowgreen": "#9acd32", "salmon": "#fa8072", "saddlebrown": "#8b4513"}
color_length = max([len(color) for color in COLOR_NAMES])
for color in COLOR_NAMES:
print("{:{}} is {}".format(color, (color_length), COLOR_NAMES[color]))
color = input("enter a color").lower()
while c... | true |
eb39963bd2f6cec6467103bc8be21bff19c1e762 | romannocry/python | /comparison.py | 535 | 4.4375 | 4 | # Python3 code to demonstrate
# set difference in dictionary list
# using list comprehension
# initializing list
test_list1 = ['ro','ma']
test_list2 = ['ro','man']
# printing original lists
print ("The original list 1 is : " + str(test_list1))
print ("The original list 2 is : " + str(test_li... | true |
d5fa47b98d799059ac50cd3cdd6a4df0ca6c4f41 | reyllama/leetcode | /Python/C240.py | 1,603 | 4.125 | 4 | """
240. Search a 2D Matrix II
Write an efficient algorithm that searches for a target value in an m x n integer matrix. The matrix has the following properties:
Integers in each row are sorted in ascending from left to right.
Integers in each column are sorted in ascending from top to bottom.
"""
class Solution(obj... | true |
0fa5eb00e017567a4be83ed88ffbc2b2bbdd2123 | reyllama/leetcode | /Python/#7.py | 847 | 4.15625 | 4 | '''
7. Reverse Integer
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−2^3... | true |
d7240926fd437fd21e86fe98c928e1946d38cce3 | reyllama/leetcode | /Python/#344.py | 1,855 | 4.21875 | 4 | """
344. Reverse String
Write a function that reverses a string. The input string is given as an array of characters char[].
Do not allocate extra space for another array, you must do this by modifying the input array in-place
with O(1) extra memory.
You may assume all the characters consist of printable ascii char... | true |
6996584587d1da1bea89feeac00a77acf8064f01 | reyllama/leetcode | /Python/C739.py | 1,665 | 4.1875 | 4 | """
739. Daily Temperatures
Given a list of daily temperatures temperatures, return a list such that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead.
For example, given the list of temperatures t... | true |
431b13b9f4000a3db036ff19a64714652560a1c6 | HaiyuLYU/UNSW | /COMP9021-Principles-of-Programming/Quizzes/Q6/quiz_6.py | 2,948 | 4.3125 | 4 | # Defines two classes, Point() and Triangle().
# An object for the second class is created by passing named arguments,
# point_1, point_2 and point_3, to its constructor.
# Such an object can be modified by changing one point, two or three points
# thanks to the method change_point_or_points().
# At any stage, the obje... | true |
cb3d396fef9475c46f6f01c3332647407ecacefb | Juli03b/coding | /python-ds-practice/fs_4_reverse_vowels/reverse_vowels.py | 819 | 4.25 | 4 | def reverse_vowels(s):
"""Reverse vowels in a string.
Characters which re not vowels do not change position in string, but all
vowels (y is not a vowel), should reverse their order.
>>> reverse_vowels("Hello!")
'Holle!'
>>> reverse_vowels("Tomatoes")
'Temotaos'
>>> reverse_vowels("Re... | false |
a252aaed19f3ab44a5366ab8022fbfe2787a6987 | MattB70/499-Individual-Git-Exercise | /DumbSort.py | 1,771 | 4.15625 | 4 | # Sorting Integers or Strings.
# Matthew Borle
# September 14, 2021
# Python 2.7.15
while True:
input_type = raw_input("Integers or Strings? (Ii/Ss): ")
if input_type == "I" or input_type == "i":
print "Integers selected"
array = raw_input("Input integers seperated by spaces:\n")
pri... | true |
3863f7eb7dd6770add7e38179e8cd7567db018fb | yangsg/linux_training_notes | /python3/basic02_syntax/datatype_list.py.demo/looping-techniques.py | 1,467 | 4.3125 | 4 | #// https://docs.python.org/3.6/tutorial/datastructures.html#looping-techniques
#// https://docs.python.org/3.6/library/functions.html
def iterate_dict():
knights = {'gallahad': 'the pure', 'robin': 'the brave'}
for k, v in knights.items(): #// 同时获取dict的key, value
print(k, v)
def iterate_list_with... | false |
7057b8a23fbfddadfae7d4e86db3428fae4c405d | yangsg/linux_training_notes | /python3/basic02_syntax/classes/02_a-first-look-at-classes.py | 2,324 | 4.625 | 5 |
#// https://docs.python.org/3.6/tutorial/classes.html#a-first-look-at-classes
#// 类定义需要先执行才能生效(可以将class 定义放在if 语句块或函数的内部)
if True:
class ClassInIfBlock():
pass
def function():
class ClassInFunction:
pass
#// 当进入 class definition 时,被当做 local scope的一个新的名字空间(namespace) 就被创建了
#// When a class d... | true |
0311b3f019f5296d2e4bf1e3084dd28d229dd452 | Pelinaslan/Cryptography | /Cryptology/Vigenere_cipher.py | 1,306 | 4.125 | 4 | import string
alphabet = string.ascii_uppercase
def Key_generation(text, key):
key = list(key)
if len(text) == len(key):
return (key)
else:
for i in range(len(text) - len(key)):
key.append(key[i % len(key)])
return key
def vigenere_Encryption(text, key):
encrypted_mess... | false |
31e193aaaeba31bf82941aa2da1dc1c1c17e58b8 | pxue/euler | /problem20.py | 2,910 | 4.1875 | 4 | # Problem20: Factorial digit sum
# find sum of factorial of 100!
# Python has builtin Math.Factorial function
# let's see how that's implemented
# From python src code
# Divide-and-conquer factorial algorithm
#
# Based on the formula and psuedo-code provided at:
# http://www.luschny.de/math/factorial/binarysplitf... | true |
f74dde0261038d46e3ada75c994c31d62ee9dba1 | rugbyprof/2143-ObjectOrientedProgramming | /ClassLectures/day01.py | 2,090 | 4.59375 | 5 | import random
# simple print!
print("hello world")
# create a list
a = []
# prints the entire list
print(a)
# adds to the end of the list
a.append(3)
print(a)
# adds to the end of the list
a.append(5)
print(a)
# adds to the end of the list, and python doesn't care
# what a list holds. It can a mixture of all ty... | true |
165acb2cc72d57f0d8943f97abb0c7ce17f33b42 | yangreal1991/my_leetcode_solutions | /0035.search-insert-position/search-insert-position.py | 847 | 4.28125 | 4 | import numpy as np
class Solution:
def __init__(self):
pass
def searchInsert(self, nums, target):
"""Given a sorted array and a target value, return the index if the target is found.
If not, return the index where it would be if it were inserted in order.
Args:
nu... | true |
0c3e6ac49b8bec6557523015348f8f6b3f04b09f | Kkkb/hello-world | /lpthw/ex6.py | 1,289 | 4.375 | 4 | # -- coding:utf-8 --
#Python通过双引号或单引号识别字符串
# 将变量x赋值给一个带有格式化字符串的字符串"There are %d types of people."
x = "There are %d types of people." % 10
# 将字符串"binary"赋值给变量binary
binary = "binary"
#变量do_not获得"don't"这个字符串
do_not = "don't"
# 1.变量y获得字符串"Those who know %s and those who %s.",带有两个格式化字符串,值为binary和do_not
y = "Those who... | false |
f35131e969c63c6f09d2f5dade49e883ecceb3b0 | Kkkb/hello-world | /liaoxuefeng_python/recur_move.py | 392 | 4.125 | 4 | # -*- coding: utf-8 -*-
#汉诺塔的移动可以用递归函数非常简单地实现。
#请编写move(n, a, b, c)函数,它接收参数n,
#表示3个柱子A、B、C中第1个柱子A的盘子数量,
#然后打印出把所有盘子从A借助B移动到C的方法
def move(n, a, b, c):
if n == 1:
print(a, '-->', c)
else:
move(n-1, a, c, b)
move(1, a, b, c)
move(n-1, b, a, c) | false |
802fc59c09de89d9abaeff6326ef02d5dadf5777 | hahntech/python-practice | /subclasses.py | 1,080 | 4.28125 | 4 | #!/usr/bin/python3
class Animal:
"""A Loose Representation of an Animal"""
def __init__(self, animalType, name, breed):
self.animalType = animalType
self.name = name
self.breed = breed
self.age = 0
def birthDay(self):
self.age +=1
def getAge(self):
re... | false |
d026133e160d8f0b83b5167fb1898c5334147cf4 | MattMackreth/BasicsDay1 | /02datatypes_strings.py | 1,689 | 4.59375 | 5 | # # Data types
# # Computers are stupid
# # they don't understand context so we need to be specific with data types
#
# # We can use type() to check datatypes
#
# # Strings
# # lists of characters bundled together in a specific order
# # using index
# print('hello')
# print(type('hello'))
#
# # Concatentation of string... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.