blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
965f6ee7983db7fa1b5d10b9f220ad5d56894edc | JoseCordobaEAN/ProgramacionG320182 | /Semana_11/ejercicios_while.py | 2,143 | 4.21875 | 4 | def de_la_z_a_la_a():
"""
() -> list of str
>>> de_la_z_a_la_a()
['z', 'y', 'x', 'w', 'v', 'u', 't', 's', 'r', 'q', 'p', 'o', 'n', 'm', 'l', 'k', 'j', 'i', 'h', 'g', 'f', 'e', 'd', 'c', 'b', 'a']
:return: list con las letras de la z a la a
"""
resultado = []
contador = 122
while co... | false |
94330ced7a14e30c9471635029b5aab87a0053dc | juliopovedacs/datascience | /1. Python/Intro to Python course/bmi_program.py | 221 | 4.1875 | 4 | #Body Mass Index Python Program
print("BMI PYTHON PROGRAM")
height = input("What is your height? \n")
weight = input("What is your weight? \n")
bmi = height / weight ** 2
print("Your Body Mass Index is " + str(bmi))
| false |
9f7ab2ec4f7747b7c72e3815310403bcaf53bac8 | ShushantLakhyani/200-Python-Exercises | /exercise_7.py | 570 | 4.28125 | 4 | # Q7) Write a Python program to construct the following pattern, using a nested for loop.
# *
# * *
# * * *
# * * * *
# * * * * *
# * * * *
# * * *
# * *
# *
#step 1: let a variable have the value 5, because of the final number of asterisks is 5
x = 5
# step 2: first 'for loop' to output the asterisks for the ... | true |
f4753e41101f6702cad27b5c62848e3afc1662a3 | ShushantLakhyani/200-Python-Exercises | /exercise_5.py | 538 | 4.4375 | 4 | #Write a python program to check if a triangle is valid or not
def triangle_validity_check(a,b,c):
if (a>b+c) or (b>a+c) or (c>a+b):
print("This is not a valid triangle.")
elif (a==b+c) or (b==c+a) or (c==a+b):
print("This can form a degenerated triangle.")
else:
print("These values ... | true |
2de6e4f4e6b61f97dc19627994d5d7fe04c0bcfd | ShushantLakhyani/200-Python-Exercises | /square_root__positive_number.py | 247 | 4.21875 | 4 | # Q3) Find the square root of a positive number
#Declare a number in a variable
a = 8
#to find thhe square root we raise the number to the power of 0.5, so raise a to the power of 0.5
a = a ** 0.5
# Now, print a to get the square root
print(a)
| true |
c4ed80db929a1218c2bee51a9f6691b5a3677bcb | AtnuamInar/python_assignment_dec15 | /q3.py | 287 | 4.34375 | 4 | #!/usr/bin/python3
num_list = [1, 2, 3, 4, 6, 7, 8, 9]
def power(num_list):
cube = list();
for num in num_list:
cubed = num ** 3
cube += [cubed]
return cube
cube = power(num_list)
print('Original list\t = {}\nCubed list\t = {}'.format(num_list, cube))
| false |
61133e6fa91e503cd0aa8370debc3140534d03a5 | voygha/RedGraySearchservice | /ejer3_instrucciones_con_texto.py | 968 | 4.28125 | 4 | mi_cadena= "Hola mundo!"
mi_cadena2= 'Hola mundo!'
print(mi_cadena)
#Si se va a mostrar comillas en una cadena, se debe poner una comilla contraria a las que se va a utilizar
cadena_con_comillas= 'Javier dijo: "Hola Mundo"'
print(cadena_con_comillas)
comillas_simples= "Hello it's me!"
print(comillas_simples)
#EL ... | false |
ba5ab5edaf9b9f85d5b95bc454e418d7cfc0cc6c | Paulvitalis200/Data-Structures | /Sorting/sort_list.py | 1,641 | 4.125 | 4 | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution(object):
def sortList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head or not head.nex... | true |
2db5ebe52b4e8512b8ae76e6f89165aa6a9cd095 | alineat/python-exercicios | /desafio085.py | 563 | 4.21875 | 4 | # Crie um programa onde o usuário possa digitar sete valores numéricos e cadastre-os em uma lista única que mantenha
# separados os valores pares e ímpares. No final, mostree os valores pares e ímapres em ordem crescente.
num = [[], []]
#valor = 0
for c in range(1, 8):
valor = int(input(f"Digite o {c}º valor: "))
... | false |
20cb8f53226940b8b42a70cc1d524d2a37e1d1e8 | Ornella-KK/password-locker | /user_test.py | 1,841 | 4.125 | 4 | import unittest
from user import User
class TestUser(unittest.TestCase):
def setUp(self):
self.new_user = User("Ornella")#create user object
def test_init(self):
'''
test_init test case to test if the object is initialized properly
'''
self.assertEqual(self.new_user.us... | true |
564db3e5e03d18e980107ed59fa9dab7bfe0bfca | RizwanAliQau/Python_Practice | /try_excep_example.py | 274 | 4.125 | 4 | try:
num = int(input(" enter a number"))
sq_num = num * num
print(sq_num)
num1= int(input("enter second number of division"))
b = num / num1
except ValueError:
print('invalid number')
except ZeroDivisionError:
print("num2 can't be zero") | false |
ba7389bd2476a80e1bd31936abce463963884f4d | DerrickChanCS/Leetcode | /426.py | 1,837 | 4.34375 | 4 | """
Let's take the following BST as an example, it may help you understand the problem better:
We want to transform this BST into a circular doubly linked list. Each node in a doubly linked list has a predecessor and successor. For a circular doubly linked list, the predecessor of the first element is the last e... | true |
164ab46dfc6364b49b06b0bd442fe5e85bd6ca37 | sushmeetha31/BESTENLIST-Internship | /Day 3 task.py | 1,042 | 4.40625 | 4 | #DAY 3 TASK
#1)Write a Python script to merge two Python dictionaries
a1 = {'a':100,'b':200}
a2 = {'x':300,'y':400}
a = a1.copy()
a.update(a2)
print(a)
#2)Write a Python program to remove a key from a dictionary
myDict = {'a':1,'b':2,'c':3,'d':4}
print(myDict)
if 'a' in myDict:
del myDict['a']
print(myD... | true |
125eaf98db6359cb6d899c8e6aea55556c6c99f3 | DKumar0001/Data_Structures_Algorithms | /Bit_Manipulation/Check_Power2.py | 366 | 4.4375 | 4 | # Check wheather a given number is a power of 2 or 0
def Check_pow_2(num):
if num ==0:
return 0
if(num & num-1) == 0:
return 1
return 2
switch ={
0 : "Number is 0",
1 : "Number is power of two",
2 : "Number is neither power of 2 nor 0"
}
number = int(input("Enter a Number"))
... | true |
ff61137fb930d6a2b211d8eeb1577ca67ec64924 | YammerStudio/Automate | /CollatzSequence.py | 490 | 4.28125 | 4 |
import sys
'''
Rules:
if number is even, divide it by two
if number is odd, triiple it and add one
'''
def collatz(num):
if(num % 2 == 0):
print(int(num/2))
return int(num/2)
else:
print(int(num * 3 + 1))
return int(num*3 + 1)
print('Please enter a number and the Collatz seque... | true |
5ec608e2a356eb31b0095da2153cedb1e74152d3 | oreo0701/openbigdata | /Review/integer_float.py | 801 | 4.1875 | 4 | num = 3
num1 = 3.14
print(type(num))
print(type(num1))
print(3 / 2) # 1.5
print(3 // 2) # floor division = 1
print(3**2) #exponnet
print(3%2) #modulus - distinguish even and odd
print(2 % 2) #even
print(3 % 2) #odd
print(4 % 2)
print(5 % 2)
print(3 * (2 + 1))
#incrementing values
num = 1
num = num + 1
num1 *= 10 ... | true |
f870ea6fa7baca5bb9c428128313c3a56ac80f4e | oreo0701/openbigdata | /Review/list_tuple_set.py | 1,463 | 4.25 | 4 | #list : sequential data
courses = ['History', 'Math', 'Physic','CompSci']
print(len(courses)) #4 values in list
print(courses[0])
print(courses[3])
print(courses[-1])
print(courses[-4])
print(courses[0:2])
print(courses[:2])
print(courses[2:])
#add values
courses.append('Art')
print(courses)
#choose location to ... | true |
6b6cbd67e07c2dee71b95c03526a06d991102d48 | SazonovPavel/A_byte_of_Python | /11_func_param.py | 465 | 4.1875 | 4 | def printMax(a, b):
if a > b:
print(a, 'максимально')
elif a == b:
print(a, 'равно', b)
else:
print(b, 'максимально')
printMax(3, 4) # Прямая передача значений
x = 5
y = 7
printMax(x, y) # передача переменных в качестве аргументов
x = 5
y = 5
printMax(x, y) # передача переменных... | false |
af63ce394403b2e94f3d944c41b3669687dff4a2 | GarryG6/PyProject | /String3_1.py | 727 | 4.28125 | 4 | # Задача 1. Определить, сколько раз в заданной строке встречается некоторый символ.
st = input('Введите строку: ')
sim = input('Введите символ: ')
k = 0 # Переменная-счетчик
for i in st: # Рассматриваем все номера символов строки в памяти компьютера
if i == sim: # Сравниваем соответствующий символ с заданным
... | false |
63712a1d093a8d1def5e5e3edb697a6ef831d622 | GarryG6/PyProject | /31.py | 794 | 4.1875 | 4 | # Дана последовательность чисел. Определить наибольшую длину монотонно возрастающего фрагмента
# последовательности (то есть такого фрагмента, где все элементы больше предыдущего).
n = int(input('Введите количество элементов '))
count = 1
max_ = 0
second = int(input('Введите элемент '))
for i in range(n - 1):
f... | false |
1bef673894fdda8f4671ec036532721bc30831d4 | GarryG6/PyProject | /String13_1.py | 1,072 | 4.25 | 4 | # Задача 11. Дано предложение, в котором слова разделены одним пробелом (начальных и конечных пробелов нет).
# Получить и вывести на экран два его первых слова.
st = input('Введите предложение: ')
# Получаем первое слово
# Определяем позицию первого пробела
pos = st.find(' ') # начиная с начала предложения
# Определя... | false |
852a1cbe7932d9065b29b6d11f81c3bdc8db6227 | nadiabahrami/c_war_practice | /level_8/evenorodd.py | 272 | 4.4375 | 4 | """Create a function that takes an integer as an argument and returns "Even" for even numbers or "Odd" for odd numbers."""
def even_or_odd(number):
return "Even" if number % 2 == 0 else "Odd"
def even_or_odd_bp(num):
return 'Odd' if num % 2 else 'Even'
| true |
58793a445e200a27bac54c49e397696d1ef94c3e | suiup/pythonProject | /python_learning/循环/while_learning.py | 360 | 4.1875 | 4 | print("while 循环演练")
"""
语法:
while 条件(判断 计数器 是否达到 目标次数):
条件满足 xxx
条件满足 xxx
... ...
处理条件(计数器 + 1)
"""
i = 0
while i <= 5:
print("Hello world")
if i == 3:
i = i + 1
continue
i= i + 1 | false |
4464f45eaf50f90ef887757f56d9ecd02ed7330c | imvera/CityUCOM5507_2018A | /test.py | 500 | 4.21875 | 4 | #0917test
#print("i will now count my chickens")
#print ("hens", 25+30/6)
#print("roosters",100-25*3%4)
#print("now count the eggs")
#print(3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6)
#print("is it true that 3+2<5-7?")
#print(3+2<5-7)
#print("what is 3+2?",3+2)
#print("what is 5-7?",5-7)
#print("is it greater?",5 > -2)
#print("... | true |
1a6195375e49cdcf2c06f3fd89f38134bc0ab80e | yukan97/python_essential_mini_tasks | /005_Collections/Task1_3_and_additional.py | 508 | 4.25 | 4 | def avg_multiple(*args):
return sum(args)/len(args)
print(avg_multiple(1, 2, 4, 6))
print(avg_multiple(2, 2))
def sort_str():
s = input("Eneter your text ")
print(' '.join(sorted(s.split(' '))))
sort_str()
def sort_nums():
num_seq_str = input("Please, enter your sequence ").split()
try:
... | true |
67dfa55500af7f9c1e0e57bcd96cb01b30d2353c | murchie85/hackerrank_myway | /findaString.py | 1,407 | 4.1875 | 4 | """
https://www.hackerrank.com/challenges/find-a-string/problem?h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen
Sample Input
ABCDCDC
CDC
Sample Output
2
Concept
Some string processing examples, such as these, might be useful.
There are a couple of new concepts:
In Python, the lengt... | true |
a949ff5542b269ac60a8e8c6de555b9354c529c8 | nadiavdleer/connectholland | /code/sortnum.py | 1,020 | 4.125 | 4 | """
Assessment problem 5
Nadia van der Leer for Connect Holland
10 June 2021
"""
from word2number import w2n
from num2words import num2words
def sort_numerically():
# initialise word list
word_list = [
"seventy five",
"two hundred forty one",
"three thousand",
"one million thir... | false |
87e87abc6bcedda29a349fb945fd45541e8a681a | AirborneRON/Python- | /chatbot/chatBot.py | 1,980 | 4.1875 | 4 | file = open("stop_words")
stopList = file.read().split("\n")
file.close()
# how to open up my plain text file, then create a variable to stuff the read file into
#seperating each element of the list by the return key
#then close
# all responses should start with a space before typing
print(" Hello ")
response =... | true |
c451f37b2016ec1ad6b073a5bae922a98c72e270 | RiverEngineer2018/CSEE5590PythonSPring2018 | /Source Code/Lab3 Q3.py | 2,249 | 4.34375 | 4 | #Don Baker
#Comp-Sci 5590
#Lab 3, Question 3
#Take an Input file. Use the simple approach below to summarize a text file:
#- Read the file
#- Using Lemmatization, apply lemmatization on the words
#- Apply the bigram on the text
#- Calculate the word frequency (bi-gram frequency) of the words (bi-grams)
#- Cho... | true |
49007104a978b21ad305c9ae13413da0dccd7e77 | noy20-meet/meet2018y1lab4 | /sorter.py | 228 | 4.375 | 4 | bin1="apples"
bin2="oranges"
bin3="olives"
new_fruit = input('What fruit am I sorting?')
if new_fruit== bin1:
print('bin 1')
elif new_fruit== bin2:
print('bin 2')
else:
print('Error! I do not recognise this fruit!')
| true |
ed6f6da350b48cde11a0e7952aad238c590cca74 | mkoryor/Python | /coding patterns/dynamic programming/palindromic_subsequence/palindromic_partitioning_brute.py | 1,329 | 4.15625 | 4 |
"""
Given a string, we want to cut it into pieces such that each piece is a palindrome. Write a function to return the minimum number of cuts needed.
Example 1:
Input: "abdbca"
Output: 3
Explanation: Palindrome pieces are "a", "bdb", "c", "a".
Example 2:
Input: = "cddpd"
Output: 2
Explanation: Palindrome pieces ar... | true |
d7830b9e24ae1feeff3e2e7fce5b3db531adab73 | mkoryor/Python | /coding patterns/dynamic programming/palindromic_subsequence/longest_palin_substring_topDownMemo.py | 1,591 | 4.15625 | 4 |
"""
Given a string, find the length of its Longest Palindromic Substring (LPS).
In a palindromic string, elements read the same backward and forward.
Example 1:
Input: "abdbca"
Output: 3
Explanation: LPS is "bdb".
Example 2:
Input: = "cddpd"
Output: 3
Explanation: LPS is "dpd".
Example 3:
Input: = "pqr"
Out... | true |
027f1de2e737fdc5556c86a83f0e7248c2812934 | mkoryor/Python | /coding patterns/subsets/string_permutation.py | 1,143 | 4.1875 | 4 |
"""
[M] Given a string, find all of its permutations preserving the character
sequence but changing case.
Example 1:
Input: "ad52"
Output: "ad52", "Ad52", "aD52", "AD52"
Example 2:
Input: "ab7c"
Output: "ab7c", "Ab7c", "aB7c", "AB7c", "ab7C", "Ab7C", "aB7C", "AB7C"
"""
# Time: O(N * 2^n) Space: O(N * 2^n)
de... | true |
2c713bda8945104526d6784acdced81ae0681ad4 | mkoryor/Python | /coding patterns/modified binary search/bitonic_array_maximum.py | 957 | 4.1875 | 4 |
"""
[E] Find the maximum value in a given Bitonic array. An array is
considered bitonic if it is monotonically increasing and then
monotonically decreasing. Monotonically increasing or decreasing means
that for any index i in the array arr[i] != arr[i+1].
Example 1:
Input: [1, 3, 8, 12, 4, 2]
Output: 12
Explan... | true |
83407eac0a8aaa8a71aa1631bbd17f5818dc877c | mkoryor/Python | /coding patterns/dynamic programming/longest_common_substring/subsequence_pattern_match_bottomUpTabu.py | 1,261 | 4.15625 | 4 |
"""
Given a string and a pattern, write a method to count the number of
times the pattern appears in the string as a subsequence.
Example 1: Input: string: “baxmx”, pattern: “ax”
Output: 2
Explanation: {baxmx, baxmx}.
Example 2:
Input: string: “tomorrow”, pattern: “tor”
Output: 4
Explanation: Following are the fo... | true |
b2ae19549528e82aaec418c4bb32868ac9272b73 | mkoryor/Python | /binary trees/diameterBT.py | 1,697 | 4.3125 | 4 |
# A binary tree Node
class Node:
# Constructor to create a new Node
def __init__(self, data):
self.data = data
self.left = self.right = None
# utility class to pass height object
class Height:
def __init(self):
self.h = 0
# Optimised recursive function to find di... | true |
b6c8c4750c8feca766f8d199428d11f6d5410ec6 | mkoryor/Python | /binary trees/inorder_traversal_iterative.py | 657 | 4.15625 | 4 |
# Iterative function to perform in-order traversal of the tree
def inorderIterative(root):
# create an empty stack
stack = deque()
# start from root node (set current node to root node)
curr = root
# if current node is None and stack is also empty, we're done
while stack or curr:
# if current node is not... | true |
68db251c87295d02c092b7e521524f134b55d0a8 | mkoryor/Python | /coding patterns/dynamic programming/palindromic_subsequence/palindromic_partitioning_bottomUpTabu.py | 1,836 | 4.15625 | 4 |
"""
Given a string, we want to cut it into pieces such that each piece is a palindrome. Write a function to return the minimum number of cuts needed.
Example 1:
Input: "abdbca"
Output: 3
Explanation: Palindrome pieces are "a", "bdb", "c", "a".
Example 2:
Input: = "cddpd"
Output: 2
Explanation: Palindrome pieces ar... | true |
db3da546c26b6d3c430ca62e18a2fc2127d76e60 | mkoryor/Python | /coding patterns/dynamic programming/knapsack_and_fib/count_subset_sum_bruteforce.py | 1,325 | 4.15625 | 4 |
"""
Given a set of positive numbers, find the total number of subsets whose sum
is equal to a given number ‘S’.
Example 1: #
Input: {1, 1, 2, 3}, S=4
Output: 3
The given set has '3' subsets whose sum is '4': {1, 1, 2}, {1, 3}, {1, 3}
Note that we have two similar sets {1, 3}, because we have two '1' in our input.... | true |
1f567c01031206e9cd45c02f0590a36a0affde12 | mkoryor/Python | /coding patterns/dynamic programming/longest_common_substring/longest_common_substring_topDownMemo.py | 1,204 | 4.125 | 4 |
"""
Given two strings ‘s1’ and ‘s2’, find the length of the longest substring which
is common in both the strings.
Example 1:
Input: s1 = "abdca"
s2 = "cbda"
Output: 2
Explanation: The longest common substring is "bd".
Example 2:
Input: s1 = "passport"
s2 = "ppsspt"
Output: 3
Explanation: The lon... | true |
6dbb44e147405710f942350d732c2ec4c0d12a4f | kukiracle/curso_python | /python1-22/seccion5-7/50DiccionariosPARTE2.py | 900 | 4.15625 | 4 | # UN DICCIONARIO TIENE (KEY, VALUE)como un diccionario
#es como un jason :V
#para entrar a los elementos con la key'IDE'
diccionario={
'IDE':'integrated develoment eviroment',
'OOP':'Object Oriented Programming',
'DBMS':'Database Management System'
}
#RECCORER LOS ELEMENTOS
for termino,valor in dic... | false |
adf515163aad1d273839c8c6ed2ca2d8503dfb9b | adamomfg/lpthw | /ex15ec1.py | 1,187 | 4.59375 | 5 | #!/usr/bin/python
# from the sys module, import the argv module
from sys import argv
# Assign the script and filename variables to argv. argv is a list of
# command lne parameters passed to a python script, with argv[0] being the
# script name.
script, filename = argv
# assign the txt variable to the instance of o... | true |
92be2d072d41e740329b967749d113fb96a40882 | amZotti/Python-challenges | /Python/12.2.py | 993 | 4.15625 | 4 |
class Location:
def __init__(self,row,column,maxValue):
self.row = row
self.column = column
self.maxValue = float(maxValue)
print("The location of the largest element is %d at (%d, %d)"%(self.maxValue,self.row,self.column))
def getValues():
row,column = [int(i) for i in input... | true |
6c311c48591efb25f6ab17bb06a906660800ac58 | dchen098/bmi_calc | /bmi_calculator.py | 424 | 4.15625 | 4 | print("\n\t\t\tBMI Calculator\n\t\t\tMade by Daniel Chen\n\n")
bmi=(int(input("What is your weight in pounds? "))*703)/(int(input("What is your height in inches? "))**2)
t="underweight"if bmi<18.5 else"normal"if bmi<25 else"overweight"if bmi<30 else"obese"
print("Your BMI is "+str(bmi)+"\nYou are "+t)
print("Try losi... | false |
b3fbd14eb0439bbb1249fd30112f81f1c72f2d51 | lglang/BIFX502-Python | /PA8.py | 2,065 | 4.21875 | 4 | # Write a program that prompts the user for a DNA sequence and translates the DNA into protein.
def main():
seq = get_valid_sequence("Enter a DNA sequence: ")
codons = get_codons(seq.upper())
new_codons = get_sets_three(codons)
protein = get_protein_sequence(new_codons)
print(protein)
def get_va... | true |
1efa65530ee7adfb87f28b485aa621d7bab157ca | nat-sharpe/Python-Exercises | /Day_1/loop2.py | 264 | 4.125 | 4 | start = input("Start from: ")
end = input("End on: ") + 1
if end < start:
print "Sorry, 2nd number must be greater than 1st."
start
end
for i in range(start,end):
if end < start:
print "End must be greater than start"
print i
| true |
fb971ad16bda2bb5b3b8bff76105a45510bcc24c | fyupanquia/idat001 | /a.py | 469 | 4.125 | 4 | name = input("Enter your name: ")
worked_hours = float(input("How many hours did you work?: "))
price_x_hour = float(input("Enter your price per hour (S./): "))
discount_perc = 0.15;
gross_salary = worked_hours*price_x_hour
discount = gross_salary*discount_perc
salary=gross_salary-discount
print("")
print("*"*10)
print... | true |
a267eff041e8e97141b82ad952deee9cf83c8b5e | Saswati08/Data-Structures-and-Algorithms | /Heap/finding_median_in_a_stream.py | 1,612 | 4.125 | 4 | def balanceHeaps():
'''
use globals min_heap and max_heap, as per declared in driver code
use heapify modules , already imported by driver code
Balance the two heaps size , such that difference is not more than one.
'''
# code here
global min_heap
global max_heap
if len(max_heap) - l... | false |
fd66e0908166c686971c2164cb81331045a54f49 | AniyaPayton/GWC-SIP | /gsw.py | 1,714 | 4.375 | 4 | import random
# A list of words that
word_bank = ["daisy", "rose", "lily", "sunflower", "lilac"]
word = random.choice(word_bank)
correct = word
# Use to test your code:
#print(word){key: value for key, value in variable}
# Converts the word to lowercase
word = word.lower()
# Make it a list of letters for someone ... | true |
a50ec0bb69075d06886309d4c8f95aa7e6b38ee2 | awesometime/learn-git | /Data Structure and Algorithm/Data Structure/ListNode/TreeNode.py | 1,644 | 4.34375 | 4 | ###
二叉树的产生及递归遍历
class TreeNode:
def __init__(self, value=None, left=None, right=None):
self.value = value
self.left = left # 左子树
self.right = right # 右子树
root = TreeNode('D', TreeNode('B', TreeNode('A'), TreeNode('C')), TreeNode('E', right=TreeNode('G', TreeNode('F'))))
print(root.value... | false |
f873c177b269ff834f3cb930f14b17d6295c4c1c | kronicle114/codewars | /python/emoji_translator.py | 837 | 4.4375 | 4 | # create a function that takes in a sentence with ASCII emoticons and converts them into emojis
# input => output
# :) => 😁
# :( => 🙁
# <3 => ❤
ascii_to_emoji = {
':)': '😁',
':(': '🙁',
'<3': '❤️',
':mad:': '😡',
':fire:': '🔥',
':shrug:': '¯\_(ツ)_/¯'
}
def emoji_translator(input, mapper):
... | true |
8cfc878be48ddbf6fc5a6a977075b1691b4c44c6 | IcefoxCross/python-40-challenges | /CH2/ex6.py | 778 | 4.28125 | 4 | print("Welcome to the Grade Sorter App")
grades = []
# Data Input
grades.append(int(input("\nWhat is your first grade? (0-100): ")))
grades.append(int(input("What is your second grade? (0-100): ")))
grades.append(int(input("What is your third grade? (0-100): ")))
grades.append(int(input("What is your fourth g... | true |
b0be90fabd5a0ba727f3e8c36d79aead438e20b5 | TheOneTAR/PDXDevCampKyle | /caish_money.py | 2,961 | 4.375 | 4 | """An account file ofr our Simple bank."""
class Account:
"""An Account class that store account info"""
def __init__(self, balance, person, account_type):
self.balance = balance
self.account_type = account_type
self.owner = person
def deposit(self, money):
self.balance +=... | true |
6e7622b6cc1de5399b05d7c52fe480f832c495ba | jacobkutcka/Python-Class | /Week03/hash_pattern.py | 636 | 4.25 | 4 | ################################################################################
# Date: 02/17/2021
# Author: Jacob Kutcka
# This program takes a number from the user
# and produces a slant of '#' characters
################################################################################
# Ask user for Input
INPUT = i... | true |
4c5a6f6d8e2d5a076872f06d0484d9d5f6f85943 | jacobkutcka/Python-Class | /Week03/rainfall.py | 1,668 | 4.25 | 4 | ################################################################################
# Date: 03/01/2021
# Author: Jacob Kutcka
# This program takes a year count and monthly rainfall
# and calculates the total and monthly average rainfall during that period
###################################################################... | true |
fe40e8644f98b8c2ebf6fedd95938c4dc95175d1 | lukeyzan/CodeHS-Python | /LoopandaHalf.py | 474 | 4.21875 | 4 | """
This program continually asks a user to guess a number until they have guessed
the magic number.
"""
magic_number = 10
# Ask use to enter a number until they guess correctly
# When they guess the right answer, break out of loop
while True:
guess = int(input("Guess my number: "))
if guess == magic_number:
... | true |
312a6d67c228c81a4365681d8b116c5502ce5df8 | LiamHooks/hw2p | /main.py | 1,338 | 4.34375 | 4 | # Author: Liam Hooks lrh5428@psu.edu
# Collaborator: Seulki Kim svk6271@psu.edu
# Collaborator: Angela Bao ymb5072@psu.edu
# Collaborator:
# Section: 2
# Breakout: 2
def getGradePoint(letter):
if letter == "A":
return 4.0
elif letter == "A-":
return 3.67
elif letter == "B+":
return 3.33
... | false |
2e4d716798afd6e737492f33e56165a5de790aaf | rsaravia/PythonBairesDevBootcamp | /Level3/ejercicio4.py | 418 | 4.4375 | 4 | # Write a Python function using list comprehension that receives a list of words and
# returns a list that contains:
# a. The number of characters in each word if the word has 3 or more characters
# b. The string “x” if the word has fewer than 3 characters
low = ['a','este','eso','aquello','tambien']
lor = [len(x) if... | true |
6e438a337feb8ef59ca8c8deae05ea6bfcbe1c13 | rsaravia/PythonBairesDevBootcamp | /Level1/ejercicio10.py | 543 | 4.28125 | 4 | # Write a Python program that iterates through integers from 1 to 100 and prints them.
# For integers that are multiples of three, print "Fizz" instead of the number.
# For integers that are multiples of five, print "Buzz".
# For integers which are multiples of both three and five print, "FizzBuzz".
l = [x+1 for x in ... | true |
5df3fa2d2ab2671f2302a582e95716d6a57dc09e | mariebotic/reference_code | /While Loops, For Loops, If Else Statements, & Boolean Operators.py | 2,947 | 4.53125 | 5 | # WHILE LOOPS, FOR LOOPS, IF ELSE STATEMENTS, & BOOLEAN OPERATORS
#______________________________________________________________________________________________________________________________________________________________________________#
import random
while True:
user_input = input("Please enter a number be... | true |
5b0b217cb0b2b4ef16066e9f2eb722347a7445ba | emjwalter/cfg_python | /102_lists.py | 1,058 | 4.625 | 5 | # Lists!
# Define a list with cool things inside!
# Examples: Christmas list, things you would buy with the lottery
# It must have 5 items
# Complete the sentence:
# Lists are organized using: ___variables____?????
# Print the lists and check its type
dreams = ['mansion', 'horses', 'Mercedes', 'flowe... | true |
4cd98053e49db7a5422d7ec0c410325f228dd5d2 | emjwalter/cfg_python | /104_list_iterations.py | 707 | 4.34375 | 4 | # Define a list with 10 names!
register = ['Bob', 'Billy', 'Brenda', 'Betty', 'Brian', 'Barry', 'Belle', 'Bertie', 'Becky', 'Belinda']
# use a for loop to print out all the names in the following format:
# 1 - Welcome Angelo
# 2 - Welcome Monica
# (....)
register = ['Bob', 'Billy', 'Brenda', 'Betty', 'Brian', 'Bar... | true |
ee9422e8c3398f0fae73489f6079517f2d3396b5 | scress78/Module7 | /basic_list.py | 718 | 4.125 | 4 | """
Program: basic_list.py
Author: Spencer Cress
Date: 06/20/2020
This program contains two functions that build a list for Basic List Assignment
"""
def get_input():
"""
:returns: returns a string
"""
x = input("Please input a number: ")
return x
def make_list():
"""
... | true |
0ae7ca84c21ffaa630af8f0080f2653615758866 | VertikaD/Algorithms | /Easy/highest_frequency_char.py | 974 | 4.4375 | 4 | def highest_frequency_char(string):
char_frequency = {}
for char in string:
if char in char_frequency:
char_frequency[char] += 1
else:
char_frequency[char] = 1
sorted_string = sorted(char_frequency.items(),
key=lambda keyvalue: key... | true |
e3581004a1dffa98a99e8c08cfe52c78395e5331 | RoaRobinson97/python | /binarySearch/main.py | 1,079 | 4.125 | 4 | #RECURSIVE
def binary_search_recursive(arr, low, high, x):
if high >= low:
mid = (high + low)
if arr[mid] == x:
return mid
elif arr[mid] > x:
return binary_search_recursive(arr, low, mid - 1, x)
else:
return binary_search_recursive(arr, mid + 1... | false |
30c2f43d22e30ade58e703b3ac64176db33a3cbf | juancarlosqr/datascience | /python/udemy_machine_learning/02_simple_linear_regression/01_simple_linear_regression.py | 2,083 | 4.21875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 19 13:49:10 2018
@author: jc
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# data preprocessing
# import dataset
dataset = pd.read_csv('salary_data.csv')
x = dataset.iloc[:, :-1].values
dependant_column_index = 1
y = ... | true |
22ebee6a673d7af7cc1a34744d4efeaa07e5c92b | lukasz-lesiuk/algo-workshop | /algo-workshop.py | 729 | 4.40625 | 4 | def get_even_numbers(x, stop, z):
"""
Returns a list containing first 'x' even elements lower than 'stop'.
Those elements must be divisible by 'z'.
"""
raw_list = []
for i in range(1,(stop//2)):
raw_list.append(2*i)
# print(raw_list)
list_sorted = []
for element in raw_list... | true |
71c4b61ee65ceb5042908accca49af509fc43210 | cyr1z/python_education | /python_lessons/02_python_homework_exercises/ex_03_lists.py | 1,208 | 4.34375 | 4 | """
Exercise: https://www.learnpython.org/en/Lists
In this exercise, you will need to add numbers and strings
to the correct lists using the "append" list method. You must add
the numbers 1,2, and 3 to the "numbers" list, and the words 'hello'
and 'world' to the strings variable.
You will also ha... | true |
8b9d35551a9f5b123a30c3e63ddf7f637eec279a | collins73/python-practice-code | /app.py | 823 | 4.21875 | 4 | # A simple program that uses loops, list objects, function , and conditional statements
# Pass in key word arguments into the function definition my_name
def my_name(first_name='Albert', last_name='Einstein', age=46):
return 'Hello World, my name is: {} {}, and I am {} years old'.format(first_name,last_name, a... | true |
9ef773c250dab6e409f956fb10844b1e3a22015f | Zakaria9494/python | /learn/tuple.py | 804 | 4.25 | 4 | #A tuple is a collection which is ordered and unchangeable.
# In Python tuples are written with round brackets.
thistuple = ("apple", "banana",
"cherry", "orange", "kiwi", "melon",
"mango")
print(thistuple[1])
# negative Indexing
#Print the last item of the tuple:
print(thistuple[-1])
#ran... | true |
978ed5bafbf3c3d796963d6152818fa68c230c52 | Zakaria9494/python | /learn/inputuser.py | 1,838 | 4.28125 | 4 |
# pyhon 3.6 input()
# python 2.7 raw_input()
# to get the functions of python in console
# first step python eingeben
#second step dir()
#third step dir("")
name =input("Was ist deine Name ? :")
if len(name)< 2:
print ("zu kurz")
elif name.isalpha():
age = input("bitte geben Sie Alter ein: ")
if age.isal... | false |
e29a66a3557e2eabca2ebe273f0454222479c015 | ericocsrodrigues/Python_Exercicios | /Mundo 03/ex074.py | 552 | 4.125 | 4 | """
Exercício Python 074: Crie um programa que vai gerar cinco números aleatórios e colocar em uma tupla. Depois disso, mostre a listagem de números gerados e também indique o menor e o maior valor que estão na tupla.
"""
from random import randint
n = (randint(1, 10), randint(1, 10), randint(1, 10), randint(1, 10), ra... | false |
39461100d0a24ca1afecb91bbe628f319c6c56c0 | ericocsrodrigues/Python_Exercicios | /Mundo 03/ex081.py | 869 | 4.1875 | 4 | """
Exercício Python 081: Crie um programa que vai ler vários números e colocar em uma lista. Depois disso, mostre:
A) Quantos números foram digitados.
B) A lista de valores, ordenada de forma decrescente.
C) Se o valor 5 foi digitado e está ou não na lista.
"""
lista = list()
cont = 0
while True:
lista.append(int... | false |
2572f07a5e1b2320bd3f19825b35eea43d963348 | ericocsrodrigues/Python_Exercicios | /Mundo 02/ex062.py | 764 | 4.21875 | 4 | """
Exercício Python 62: Melhore o DESAFIO 61, perguntando para o usuário se ele quer mostrar mais alguns termos. O programa encerrará quando ele disser que quer mostrar 0 termos.
"""
barra = '\033[36m=\033[m' * 22
print(barra)
print('\033[35m10 TERMOS DE UMA P.A\033[m')
print(barra)
n = int(input('Primeiro termo: '))... | false |
87c22b1d1b3f88e3737e20ac246dcf0cc300c793 | ericocsrodrigues/Python_Exercicios | /Mundo 03/ex078.py | 643 | 4.125 | 4 | '''
Exercício Python 078: Faça um programa que leia 5 valores numéricos e guarde-os em uma lista. No final, mostre qual foi o maior e o menor valor digitado e as suas respectivas posições na lista.
'''
lista = list()
for x in range(5):
lista.append(int(input(f'Digite um valor para a posição {x}: ')))
print(f'O mai... | false |
89d56e31f80950b8003903c7d20044b62d56a72a | eventuallyrises/Python | /CW_find_the_next_perfect_square.py | 821 | 4.15625 | 4 | #we need sqrt() so we import the build in math module
import math
#we start the function off taking in the square passed to it
def find_next_square(sq):
#for later we set up the number one higher than the passed square
wsk=sq+1
# Return the next square if sq is a square, -1 otherwise
#here we look to see... | true |
d0e40a83f302dc6a0117634b7224494dd69ab992 | KuroKousuii/Algorithms | /Prime numbers and prime factorization/Segmented Sieve/Simple sieve.py | 832 | 4.15625 | 4 | # This functions finds all primes smaller than 'limit'
# using simple sieve of eratosthenes.
def simpleSieve(limit):
# Create a boolean array "mark[0..limit-1]" and
# initialize all entries of it as true. A value
# in mark[p] will finally be false if 'p' is Not
# a prime, else true.
mark = [True for... | true |
862b61d7ff0c079159910d20570041da0d4747a3 | jasimrashid/cs-module-project-hash-tables | /applications/word_count/word_count_one_pass.py | 2,043 | 4.21875 | 4 | def word_count(s):
wc = {}
# without splitting string
beg = 0
c = ''
word = ''
word_count = {}
for i,c in enumerate(s):
# if character is end of line, then add the word to the dictionary
if i == len(s)-1: #edge case what if there is a space at the end of line or special... | true |
f5812e58373f52e38f8efa72d8e4a6627526f194 | prateek951/AI-Workshop-DTU-2K18 | /Session1/demo.py | 1,816 | 4.75 | 5 | # @desc Working with Numpy
import numpy as np
# Creating the array using numpy
myarray = np.array([12,2,2,2,2,2])
print(myarray)
# The type of the array is np.ndarray whereas in python it would be list class
print(type(myarray))
# To print the order of the matrix
print(myarray.ndim)
# To print the shape of the a... | true |
58558f014aa28b29b9e2ad662cd783ff524bd220 | prateek951/AI-Workshop-DTU-2K18 | /Session-5 Working on Various Python Library/numpyops.py | 2,447 | 4.375 | 4 | my_list = [1,2,3]
# Importing the numpy library
import numpy as np
arr = np.array(my_list)
arr
# Working with matrices
my_matrix = [[1,2,3],[4,5,6],[7,8,9]]
np.array(my_matrix)
# Create an array
np.arange(0,10)
# Create an array keeping the step size as 2
np.arange(0,10,2)
# Arrays of zeros
np.zeros(3)
# Array ... | true |
e4db9a855ebaf188c4190ec4c564a0c46a3c573f | abhiis/python-learning | /basics/carGame.py | 889 | 4.15625 | 4 | command = ""
is_started = False
is_stopped = False
help = '''
start: To start the car
stop: To stop the car
quit: To exit game
'''
print("Welcome to Car Game")
print("Type help to read instructions\n")
while True: #command != "quit": if we write this condition, last else block always gets executed
command = inpu... | true |
c69077d4872fa21cddbf88b09cab2faf4c7010be | ryanZiegenfus/algorithms_practice | /codewars/challenges.py | 2,239 | 4.125 | 4 | #####################################################################################################
# 1
# Create fibonacci sequence with n elements and ouptut it in a list. If n == 0 return empty list.
# 0 1 1 2 3 5 8 11 19 ...etc
# [0, 1, 1, 2, 3, 5,]
def fib_sequence(n):
base = [0, 1]
if n == 0:
r... | false |
37ec44a4c625be4aff3bcb25f88822f9a13d5d87 | l200183203/praktikum-algopro | /ainayah syifa prac 11 act 2.py | 1,371 | 4.21875 | 4 | #Practic 11. Activity 2. Make Simple Calculator. by@Ainayah Syifa Hendri
from Tkinter import Tk, Label, Entry, Button, StringVar
my_app = Tk(className= "Simple calculator")
L1 = Label(my_app, text= "Number 1")
L1.grid(row=0, column=0)
str1 = StringVar()
E1 = Entry(my_app, textvariable= str1)
E1.grid(row=0, c... | false |
409e94361c99c3833dcc7990a2593b3ee5b10f10 | amolgadge663/LetsUpgradePythonBasics | /Day7/D7Q1.py | 393 | 4.1875 | 4 | #
#Question 1 :
#Use the dictionary,
#port1 = {21: "FTP", 22:"SSH", 23: "telnet", 80: "http"},
#and make a new dictionary in which keys become values and values become keys,
# as shown: Port2 = {“FTP":21, "SSH":22, “telnet":23,"http": 80}
#
port1 = {21: "FTP", 22:"SSH", 23: "telnet", 80: "http"}
print(port1)... | true |
517f5396a3e74f8f4c1f727a3224f21dc22be127 | amolgadge663/LetsUpgradePythonBasics | /Day4/D4Q2.py | 212 | 4.40625 | 4 | #
#Question 2 :
#Explain using
#islower()
#isupper()
#with different kinds of strings.
#
st1 = "I am Amol."
print(st1)
print("String isLower? ", st1.islower())
print("String isUpper? ", st1.isupper()) | false |
59125fe5d98160896e811a9be0cf6421a73e711c | DRCurado/Solids_properties | /Circle.py | 744 | 4.21875 | 4 | #Circle shape
#Calculate the CG of a circle.
import math
#insert the inuts of your shape:
unit = "mm"
#insert the dimensions of your shape:
diameter = 100;
#Software do the calculations
Area = math.pi*(diameter/2)**2;
Cgx = diameter/2;
Cgy = diameter/2;
Ix= (math.pi*diameter**4)/64;
Iy= (math.pi... | true |
45e20efd919cb4ab2fc2b6b03449a8066b8f4f2a | alphaolomi/cryptography-algorithms | /transposition_encryption.py | 1,122 | 4.1875 | 4 | # Transposition Cipher Encryption
def main():
my_message = 'Common sense is not so common.'
my_key = 8
cipher_text = encrypt_message(my_key, my_message)
# Print the encrypted string in cipher_text to the screen, with
# a | (called "pipe" character) after it in case there are spaces at
# the en... | true |
ca827f71d84324d576adac8192f0391af29a457c | rragundez/utility-functions | /ufuncs/random.py | 699 | 4.1875 | 4 |
def generate_random_string(length, *, start_with=None,
chars=string.ascii_lowercase + string.digits):
"""Generate random string of numbers and lowercase letters.
Args:
length (int): Number of characters to be generated randomly.
start_with (str): Optional string to s... | true |
c10cb232f6c7b665dbf7fe0b672a8034dd97b6af | lukeitty/problemset0 | /ps0.py | 2,630 | 4.25 | 4 | #Author: Luke Ittycheria
#Date: 3/28/16
#Program: Problem Set 0 Functions
#Function 0
def is_even(number):
'''Returns a value if the number is even or odd'''
if number == 0:
return True
if number % 2 == 0:
return True
else:
return False
return evenOrOdd
#############################################... | true |
39b91946afdb07d27c8314405268e89e842c8840 | benichka/PythonWork | /favorite_languages.py | 707 | 4.40625 | 4 | favorite_languages = {
'Sara' : 'C',
'Jen' : 'Python',
'Ben' : 'C#',
'Jean-Claude' : 'Ruby',
'Jean-Louis' : 'C#',
}
for name, language in favorite_languages.items():
print(name + "'s favorite language is " + language + ".")
# Only for the keys:
print()
for k in favo... | true |
618e1fdc6d658d3fc80cff91737e74f6f8fc30a6 | benichka/PythonWork | /chapter_10/common_words.py | 553 | 4.25 | 4 | # Take a file and count occurences of a specific text in it.
text_file = input("Choose a text file from which to count occurences of a text: ")
occurence = input("What text do you want to count in the file?: ")
try:
with open(text_file, 'r', encoding="utf-8") as tf:
contents = tf.read()
except:
print("... | true |
d8947556c73c79505c31eb54718aecb20f1b1c2b | benichka/PythonWork | /chapter_10/addition.py | 787 | 4.28125 | 4 | # Simple program to add two numbers, with exception handling.
print("Input 2 numbers and I'll add them.")
while (True):
print("\nInput 'q' to exit.")
number_1 = input("\nNumber 1: ")
if (number_1 == 'q'):
break
try:
number_1 = int(number_1)
except ValueError:
print("\nOnly n... | true |
c77c04ac341a2eb7e0f99ab4fb30b2f134c790d6 | vit050587/Python-homework-GB | /lesson5.5.py | 1,475 | 4.125 | 4 | # 5. Создать (программно) текстовый файл,
# записать в него программно набор чисел, разделенных пробелами.
# Программа должна подсчитывать сумму чисел в файле и выводить ее на экран.
def sum_func():
try:
with open('file_5.txt', 'w+') as file_num:
str_num = input('Введите цифры через пробел \n')... | false |
8e0f68898778383bcc958dcade2b9f06910d1b61 | ndpark/PythonScripts | /dogs.py | 949 | 4.21875 | 4 | #range(len(list)) can be used to iterate through lists
dogs = []
while True:
name = input('Dog name for dog # ' + str(len(dogs)+1) + '\nType in empty space to exit\n>>')
dogs = dogs + [name] #Making a new list called name, and then adding it to dogs list
if name == ' ':
break
print ('The dog names are:')
for name ... | true |
8ade98a9e878e8ba1790be5e225372d9482b6cbb | ndpark/PythonScripts | /backupToZip.py | 859 | 4.21875 | 4 | #! python3
# backupToZip.py - Copies entire folder and its content into a zip file, increments filename
import zipfile, os
def backupToZip(folder):
folder = os.path.abspath(folder) #Folder must be absolute
#Figures out what the filename should be
number = 1
while True:
zipFilename = os.path.basename(folder) ... | true |
632a672805914b130a2de77eff69cc66af77c25c | rhitik26/python1 | /python assignments/day4b.py | 471 | 4.125 | 4 | def outer(a):
def inner():
print("this is inner!")
print(type(a))
a()
print("Inner finished execution!")
return inner
@outer #By adding this annotation the function will automatically become wrapper function(the concept is Decorator)
def hello():
print("hello World!")
@outer... | true |
f0de78586e06ab3b4a740b1e0ca181d1e3fcb819 | drkthakur/learn-python | /python-poc/python-self-poc/Calculator.py | 437 | 4.15625 | 4 | print(17/3)
print(17//3)
print(17%3)
height=10
breadth=20
print(height*breadth)
print (-3**2)
print ((-3)**2)
x=1 + 2*3 - 8/4
print(x)
if 2.0 < 2:
print("A")
elif 2.0 >= 2:
print("B")
else:
print("C")
score = input("Enter Score: ")
s = float(score)
if s >= 0.9:
print("A")
elif s >= 0.8:
print(... | false |
13d7ab468faf1f3342bf8f221ca36e51437b131d | bloomsarah/Practicals | /prac_04/lottery_ticket_generator.py | 778 | 4.1875 | 4 | """
Generate program that asks for number of quick picks
print that number of lines, with 6 numbers per line
numbers must be sorted and between 1 and 45
"""
import random
NUMBERS_PER_LINE = 6
MIN = 1
MAX = 45
def main():
number_of_picks = int(input("Enter number of picks: "))
while number_of_picks < 0:
... | true |
a4fe0d90b2772844969b34ce6ffa103c294ddfa1 | timeeeee/project-euler | /4-largest-palindrome-product/main.py | 358 | 4.15625 | 4 | # Find the largest palindrome that is the product of 2 3-digit numbers.
def isPalindrome(x):
string = str(x)
return "".join(reversed(string)) == string
maximum = 0;
for a in range(111, 1000):
for b in range(111, 1000):
product = a * b
if isPalindrome(product) and product > maximum:
... | true |
206deca44b6fa1c1147d3c6d698d92ea2aee44ed | timeeeee/project-euler | /62-cubic-permutations/slow.py | 1,720 | 4.15625 | 4 | """
The cube, 41063625 (345^3), can be permuted to produce two other cubes: 56623104 (384^3) and 66430125 (405^3). In fact, 41063625 is the smallest cube which has exactly three permutations of its digits which are also cube.
Find the smallest cube for which exactly five permutations of its digits are cube.
"""
from ... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.