blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
d2f53b00cae8731e03e804a43fbe06db53f340c6 | cidexpertsystem/python-snippets | /isLucky.py | 1,161 | 4.1875 | 4 | # Ticket numbers usually consist of an even number of digits.
# A ticket number is considered lucky if the sum of the first half
# of the digits is equal to the sum of the second half.
# Given a ticket number n, determine if it's lucky or not.
import math
def isLucky(n):
# if sum of first half of digits equals s... | true |
1856263def6d2dee52316831dd29e8a92b4408fa | brunoczim/op-desafios | /desafio-03/JonathanLopes403/python/main.py | 1,281 | 4.25 | 4 | """
Esse progama mostrar todos os números palindrômicos entre um número e outro
"""
import sys
def num_palindromicos(inicio, fim):
""" Essa função é responsavel por gerar os números palindrômicos """
#Conjunto dos números que são palindrômicos
palindromicos = set()
# Verifica se fim é menor que inicio ... | false |
1811759e340d506fa6574deb9ae9d4bb43912d10 | theblacksigma/Py9ft | /5. Python progra to calculate Area of Right Angled Triangle.py | 346 | 4.34375 | 4 | #Python progra to calculate area of Right Angled Triangle
b=int(input("Enter base of the right angled triangle:"))
p=int(input("Enter perpendicular height of the right angled triangle:"))
h=(b**2+p**2)**(1/2)
x=b+p+h
a=(1/2)*b*p
print("Perimeter of Right Angled Triangle:",x,"units")
print("Area of Right Angled ... | true |
645b76d43eb988a42ce1daf1d5832eeb65a651b7 | matthewzar/CodeWarsKatas | /Python/Kyu8/PositiveNegativeCount/PositiveNegativeCount.py | 923 | 4.21875 | 4 | '''
https://www.codewars.com/kata/count-of-positives-slash-sum-of-negatives/train/python
Count positive numbers, and sum negatives.
'''
def count_positives_sum_negatives(arr):
if(arr == []):
return []
return [sum([1 if x > 0 else 0 for x in arr]),
sum([x if x < 0 else 0 for x in arr])]
impo... | false |
192eccf887cad1887c94db578a1d7d02904f3530 | kinjal2110/PythonTutorial | /39_comprehension.py | 1,254 | 4.21875 | 4 | # ls = []
# for i in range(50):
# if i%3==0:
# ls.append(i) #i module 3 ==0 value print
# above things we can also done by list comprehensions
# -----------------------------------------------list comprehension-----------------------------------
ls = [i for i in range(50) if i %3==0] #it i... | true |
61ed971df85f240a7c33ea84425ada21cec640f2 | kinjal2110/PythonTutorial | /38_generator.py | 953 | 4.28125 | 4 | '''
Itersble- __iter__() or __getitem__
Iterator __next__()
Iteration
'''
def gen(n):
for i in range(n):
# return i
yield i #it is return value
g =gen(3)
for i in g:
print(i)
for i in range(6):
print(i)
# using generator factorial
print("Factorial is: ")
def fact(n):
sum = 1
... | false |
fc8a0e66310d9b4b30dff5addcdf4f01e026b489 | kinjal2110/PythonTutorial | /8.py | 867 | 4.25 | 4 | #Exercise:- Take user input, and we need to say user to those number or less then or greater then number
# which already has an over program.(it likes binary search).
# if n=18
# number of guesses is 9
# we need to print number of guesses left
# number of guesses he took to finish.
# if all guesses left the... | true |
d32ee087bf3d78c6a64b676ba841df8023e4edde | alexandru-dinu/competitive-programming | /leetcode/implement_trie_prefix_tree.py | 923 | 4.1875 | 4 | # https://leetcode.com/problems/implement-trie-prefix-tree
class Trie:
def __init__(self):
self.kids = {} # char -> Trie
self.is_end = False
def walk(self, word: str) -> Optional["Trie"]:
t = self
for c in word:
if c not in t.kids:
return None
... | false |
aa49e54950f552058444b70b8c3385321018ae7f | Astrolopithecus/PalindromeChecker | /palindromeChecker.py | 1,088 | 4.21875 | 4 | # Miles Philips
# prog 260
# 7-10-19
# Palindrome Detection program
from stack import Stack
#Implement this function that checks whether the input string is a palindrome:
# (a string where the characters of the string read the same when read backward
# as forward. E.g. racecar, mom)
def palindromeCheck(mystr)... | true |
d796fa0e2daf167745ac995e14b6f6ea65a30425 | wernicka/learn_python | /example_prgms/ex6.py | 1,071 | 4.5625 | 5 | # set variable types_of_people to an integer: 10
types_of_people = 10
# set variable x to a string: sentence about types_of_people.
x = f"There are {types_of_people} types of people"
# unnecessarily set values of binary and do_not to strings
binary = "binary"
do_not = "don't"
# set variable y to another string which h... | true |
191362f0e7bd2ab6bbe104b1d65304e373dafc3f | wernicka/learn_python | /original_code/Algorithms/2_integer_array.py | 1,233 | 4.375 | 4 | # You are given an array (which will have a length of at least 3, but could be very large) containing integers.
# The array is either entirely comprised of odd integers or entirely comprised of even integers except for a single
# integer N. Write a method that takes the array as an argument and returns N.
# For example... | true |
e2b029a70231d60abb74d730e81372904909f7eb | mutemibiochemistry/Biopython | /exercise11functions/question4.py | 394 | 4.21875 | 4 | #Write a function that accepts a single integer parameter, and returns True if the number is prime, otherwise False.
a=int(raw_input("Enter number: "))
def isprime(a):
#return True if the number is prime, false otherwise
if (a == 1) or (a == 2):
return "is True"
else :
for i in range(2, a ):
if a%i == 0:
... | true |
0c7faa1a84483918796097fa8b70c3d5fb60f208 | mutemibiochemistry/Biopython | /exercise5/question9.py | 242 | 4.28125 | 4 | #enters sequence of nos ending with a blank line then prints the smallest
nos = raw_input("Enter numbers: ")
smallest = nos
while nos != '':
if int(nos) < int(smallest):
smallest = nos
nos = raw_input("Enter numbers: ")
print smallest
| true |
d981b1f0bf529307d8053f8d324d87d5132a8977 | MCNANA12/pycharmdupdated | /Hello World.py | 732 | 4.4375 | 4 | # Basic string Operation
str = 'Hello World, this is a string!'
print(len(str)) # Get the length
print(str * 3) # Repeat
print(str.replace('Hello', 'Hola')) # Replace
print(str.split(',')) # Split
print(str.startswith('H')) # starts with
print(str.endswith('!'))
print(str.lower())
print(str.upper())
# slicing - o... | true |
f9765623e0b33467cd76e4f439b29f077985b1a2 | FstRms/basic-python | /BMI.py | 610 | 4.34375 | 4 | """ Script to calculate Body Mass Index"""
print("Hi there!!!\nWelcome to the Body Mass Index Calculator tool!!!\n")
height = float(input("Please enter your height in m:\n"))
weight = float(input("Please enter your weight in kg:\n"))
bmi = int(weight / (height ** 2))
if bmi < 18.5:
print (f"Your BMI is {bmi}. You... | false |
761dee0913c11def9e5eb5574602917184325c1d | Riceps/cp1404_practicals | /prac_02/exceptions_demo.py | 754 | 4.25 | 4 | """
CP1404/CP5632 - Practical
Answer the following questions:
1. When will a ValueError occur?
2. When will a ZeroDivisionError occur?
3. Could you change the code to avoid the possibility of a ZeroDivisionError?
"""
try:
numerator = int(input("Enter the numerator: "))
denominator = int(input("Enter the denomi... | true |
7a1d6919281d2a8ef58faa4ab2ad5ef27cf8b831 | Riceps/cp1404_practicals | /prac_01/loops.py | 526 | 4.21875 | 4 | "Prints all numbers between 1 and 20 inclusive, with a step of 2 (i.e. all odd numbers)"
for i in range(1, 21, 2):
"prints number i and a space TODO:(question what (end) does)"
print(i, end=' ')
print()
for i in range(0, 101, 10):
print(i, end=' ')
print()
for i in range(20, 0, -1):
print(i, end=' ')
... | true |
0630dd5fb3b671748d9a3051b55c26238580351a | reedcwilson/programming-fundamentals | /lessons/2/homework/fibonacci.py | 804 | 4.25 | 4 |
# import some modules so that we get some extra functionality
# ask for the option they would prefer (nth number or number <= n)
# if you recognize their choice then continue
# ask for the n
# keep track of the current first and second numbers
# if we are option number 1 do the nth number algorithm
... | true |
370707f5da6c457ed71bbf830892dd9b6a3cc48f | Kosyka/Learning-python | /inventary2.py | 2,214 | 4.21875 | 4 | #Продолжение изучения кортежа
inventary = (
"Меч",
"Щит",
"Кольчуга",
"зелье лечения"
)
print("В вашем распоряжении: ")
for item in inventary:
print(item)
input("Для того, чтобы узнать размер вашего инвентаря нажмите Enter...")
print("Размер инвентаря: {0} предмета/ов".format(len(inventary)))
#про... | false |
24b22a11d42fe928633529bdc3f9c7fdc7cf7003 | nickaroot/pdsm04 | /ex00/benchmark.py | 1,187 | 4.21875 | 4 | #!/usr/bin/env python3
import timeit
def loop(emails):
gmails_loop = []
for email in emails:
if "@gmail.com" in email:
gmails_loop.append(email)
def comprehension(emails):
[email for email in emails]
def main():
emails = ['john@gmail.com', 'james@gmail.com', 'alice@yahoo.com', '... | false |
0d6a271fc3ee12c49765632be2e35ca706029e8b | premkrish/Python | /Lists/lists.py | 792 | 4.28125 | 4 | """ This script contains lessons for list """
#Instantitate a list
list1 = [1, 2, 3, 4, 5]
print(list1)
list2 = [6, 7, 8, 9, 10]
print(list2)
#concatenation - maintains order
print(f"List 1 + List 2: {list1 + list2}")
print(f"List 2 + List 1: {list2 + list1}")
#Add item to list
list1.append(6)
print(type(list1))
pr... | true |
2138d7d5205c8623fea526c66a778527935381ff | premkrish/Python | /Tuples/tuples.py | 1,478 | 4.65625 | 5 | """ This script contains lessons for tuples """
# List and Tuple have similar features
list1 = [1, 2, 3, 4, 5, 6]
tuple1 = (1, 2, 3, 4, 5, 6)
print(f"Length of list : {len(list1)}")
print(f"Length of tuple : {len(tuple1)}")
#Iterate and print the elements
for n in list1:
print(f"List element: {n}")
print(80*"-"... | true |
13825f7e72fc4ad98b21b7179eda599a15922ee1 | ayush0477/pythonexperimt- | /squireelplay.py | 275 | 4.125 | 4 | temp = int(input("enter the temparure value\n"))
summer = str(input("enter the summer value true or false\n"))
if(temp>=60 and temp<=90 and summer=="false"):
print("true")
elif (temp>=60 and temp<=100 and summer=="true"):
print("true")
else:
print("false") | true |
98c4df06481581947e415593a11f16e435cdfbd5 | realDashDash/SC1003 | /Week4/Discussion2.py | 1,182 | 4.125 | 4 | # requirements:
# - more than 8 characters
# - at least one upper letter and lower letter
# - at least one number
# - at least one special character
# todo regular expression operations
def check_pw(password):
length = 0
upper = False
lower = False
number = False
special = False
n... | true |
d29015ed62d062d408f27fed846ec277be23c029 | ivanromanv/manuales | /Python/Edx_Course/Introduction to Programming Using Python/Excercises/w3_If_elif_Divisibilidad.py | 902 | 4.53125 | 5 | #Write a program which asks the user to enter a positive integer 'n' (Assume that the user always enters a positive integer) and based on the following conditions, prints the appropriate results exactly as shown in the following format (as highlighted in yellow).
#when 'n' is divisible by both 2 and 3 (for example 12)... | true |
012b37666aeb11b42bbf9deeae22a432b62760fa | ivanromanv/manuales | /Python/Edx_Course/Introduction to Programming Using Python/Excercises/W7_Dictionary_Assignment3_find_word_crossword_vertical.py | 1,700 | 4.1875 | 4 | # Part 2: Find a word in a crossword (Horizontal)
# 0.0/30.0 puntos (calificados)
# Write a function named find_word_vertical that accepts a 2-dimensional list of characters (like a crossword puzzle) and a string (word) as input arguments. This function searches the columns of the 2d list to find a match for the word. ... | true |
59035219f7287bd7c84007bdc04021f5a2a2b253 | ivanromanv/manuales | /Python/Edx_Course/Introduction to Programming Using Python/Excercises/W6_Strings_lider_espacio_blanco.py | 614 | 4.3125 | 4 | # Write a function that accepts an input string consisting of alphabetic characters and removes all the leading whitespace of the string and returns it without using .strip(). For example if:
#
# input_string = " Hello "
# then your function should return a string such as:
# output_string = "Hello "
#
def funcion_... | true |
874b4d47c1487bdae79ec5aa4fe35402a0eff88d | ivanromanv/manuales | /Python/Edx_Course/Introduction to Programming Using Python/Excercises/w3_Condicional_If_elif_numero.py | 467 | 4.3125 | 4 | #Write a program which asks the user to type an integer.
#If the number is 2 then the program should print "two",
#If the number is 3 then the program should print "three",
#If the number is 5 then the program should print "five",
#Otherwise it should print "other".
numero = input("Insert the number: ")
numero = in... | true |
6f94acdd9baac844cb8633d85502c84bed331182 | ivanromanv/manuales | /Python/Edx_Course/Introduction to Programming Using Python/Excercises/W6_Strings_suma_codigo_caracteres.py | 574 | 4.46875 | 4 | #Write a function that accepts an alphabetic string and returns an integer which is the sum of all the UTF-8 codes of the character in that string. For example if the input string is "hello" then your function should return 532
#
def funcion_suma_codigo_caracteres(caracteres):
suma=0
for x in caracteres:
... | true |
5b6e4eca927532afdf680a6d524f5b7002940e15 | ivanromanv/manuales | /Python/Edx_Course/Introduction to Programming Using Python/Excercises/w3_Condicional_If_elif.py | 496 | 4.34375 | 4 | #Ask the user to type a string
#Print "Dog" if the word "dog" exist in the input string
#Print "Cat" if the word "cat" exist in the input string.
#(if bothj "dog" and "cat" exist in the input string, then you should only print "Dog")
#Otherwise print "None". (pay attention to capitalization)
cadena = input("Insert the ... | true |
b3f54800bd3faaee42ceb1cdf76c8d029f18bbbe | ivanromanv/manuales | /Python/Edx_Course/Introduction to Programming Using Python/Excercises/W4_While_Calculo_Serie_3_n.py | 269 | 4.15625 | 4 | #Write a program using while loop, which prints the sum of every third numbers from 1 to 1001 ( both 1 and 1001 are included)
#(1 + 4 + 7 + 10 + ....)
numero = int(1)
suma = int(0)
while numero <= 1001:
suma = suma + numero
numero = numero + 3
print(int(suma))
| true |
f34ceee60cc001952bec5a15b56089be0ff2eb5f | ivanromanv/manuales | /Python/Edx_Course/Introduction to Programming Using Python/Excercises/W6_Strings_E7_conteo_caracter_comun.py | 1,055 | 4.125 | 4 | # Write a function that takes a string consisting of alphabetic characters as input argument and returns the lower case of the most common character. Ignore white spaces i.e. Do not count any white space as a character. Note that capitalization does not matter here i.e. that a lower case character is equal to a upper c... | true |
f121606b3c62d6bbf0a5bc792bcf28ce2f9744a1 | ivanromanv/manuales | /Python/Edx_Course/Introduction to Programming Using Python/Excercises/W6_Strings_entero_a_caracter.py | 358 | 4.15625 | 4 | # Write a function that accepts a positive integer n and returns the ascii character associated with it.
#
def funcion_entero_a_caracter(number):
return (chr(number))
# OJO SOLO FUNCION!!!
# Main Program #
number = int(input("Enter number: "))
evalua_funcion_entero_a_caracter = funcion_entero_a_caracter(number)
pr... | true |
97269d02b35e0cefd0fb906d9d58207356c07d71 | ivanromanv/manuales | /Python/Edx_Course/Introduction to Programming Using Python/Excercises/W7_Multidimensional_E9_Function_lista_2d_to_1d.py | 560 | 4.25 | 4 | # Write a function that accepts a 2-dimensional list of integers, and returns a sorted (ascending order) 1-Dimensional list containing all the integers from the original 2-dimensional list.
#
def list_covert_2d_to_1d_list(lista):
new_list = []
for data in lista:
new_list=new_list+data
new_list.... | true |
d779832ff8ae87018cebf243c57b5a6b3a9e0e20 | ivanromanv/manuales | /Python/Edx_Course/Introduction to Programming Using Python/Excercises/W7_Multidimensional_E1_Function_suma_lista_2d.py | 562 | 4.15625 | 4 | # Write a function which accepts a 2D list of numbers and returns the sum of all the number in the list You can assume that the number of columns in each row is the same. (Do not use python's built-in sum() function).
#
def sum_of_2d_list(lista):
total_sum=0
for data in lista:
for list_index in range(0... | true |
29f5308510497013c9adb03646a89d47ff5578cf | ivanromanv/manuales | /Python/Edx_Course/Introduction to Programming Using Python/Excercises/W7_Multidimensional_E11_Function_verifica_multiplicacion_2_matrices.py | 1,075 | 4.4375 | 4 | # Write a function that accepts two (matrices) 2 dimensional lists a and b of unknown lengths and returns True if they can be multiplied together False otherwise. Hint: Two matrices a and b can be multiplied together only if the number of columns of the first matrix(a) is the same as the number of rows of the second ma... | true |
201e75cd77d36941fe1f29ffbfda2e1933a3741c | ivanromanv/manuales | /Python/Edx_Course/Introduction to Programming Using Python/Excercises/W8_Q6_E5_Function_calculo_gastos.py | 2,146 | 4.125 | 4 | # Quiz 6, Part 5
# 0.0/20.0 puntos (calificados)
# Write a function named calculate_expenses that receives a filename as argument. The file contains the information about a person's expenses on items. Your function should return a list of tuples sorted based on the name of the items. Each tuple consists of the name of ... | true |
23d2e251b59414149095c587cf28b660fedaf6c8 | ivanromanv/manuales | /Python/Edx_Course/Introduction to Programming Using Python/Excercises/W7_Dictionary_E5_Function_diccionario_conteo_letras.py | 937 | 4.375 | 4 | # Write a function that takes a string as input argument and returns a dictionary of letter counts i.e. the keys of this dictionary should be individual letters and the values should be the total count of those letters. You should ignore white spaces and they should not be counted as a character. Also note that a small... | true |
f148a68aacfd6a6803837740053704716887b4f3 | ivanromanv/manuales | /Python/DataCamp/Intermediate Python for Data Science/Excercises/E3_Line plot (3).py | 906 | 4.34375 | 4 | # Now that you've built your first line plot, let's start working on the data that professor Hans Rosling used to build his beautiful bubble chart. It was collected in 2007. Two lists are available for you:
# * life_exp which contains the life expectancy for each country and
# * gdp_cap, which contains the GDP per capi... | true |
89cf8a303d3b91925367105dab6cf8b7736be519 | ivanromanv/manuales | /Python/Edx_Course/Introduction to Programming Using Python/Excercises/W7_Dictionary_E2_Function_valores_ordenados.py | 528 | 4.3125 | 4 | # Write a function that accepts a dictionary as input and returns a sorted list of all the values in the dictionary. Assume that the values of this dictionary are just integers.
#
def dictionary_sorted_values(dictionary):
valores = dictionary.values()
valores = list(valores)
valores.sort()
return valore... | true |
7a7b17926e7c5bd5c88899374ae5deb1938d0c73 | YuKaoriGenji/AlgorithmExp | /AlgorithmCourse/Exp1/quicktest.py | 2,901 | 4.21875 | 4 | import quicksort
import random
import numpy as np
import time
def random_int_list(start,stop,length):
start,stop=(int(start),int(stop)) if start<= stop else (int(stop),int(start))
length=int(abs(length)) if length else 0
random_list=[]
for i in range(length):
random_list.append(random.randint(... | false |
ec15200763c8c79bbfc9727c1585ef8dd6292dee | dsementsov/python.cousrse.mitx | /week2_GuessMyNumber.py | 828 | 4.15625 | 4 | # guess my number
def guess_my_number ():
guess_low = 0
guess_high = 100
print ("Please think of a number between " + str(guess_low) + " and " + str(guess_high) + "!")
while True:
guess = int((guess_high + guess_low)/2)
print("Is your secret number " + str(guess) + "?")
guess... | true |
aed3fe6169903e52cd3dbe967eb88ca6690df98a | rpyne97/Code_Academy_worth_saving | /hammingsdistance.py | 1,201 | 4.21875 | 4 | # Input: Strings Pattern and Text along with an integer d
# Output: A list containing all starting positions where Pattern appears as a substring of Text with at most d mismatches
# This function matches a Pattern sequence to a Test sequence if there are less than or equal to d mismatches
def ApproximatePatternMatchin... | true |
66707f02425519ff3d9c877c0e9099da17f7a393 | tgaborit/surlyllabe | /python/syllabation_encoder.py | 886 | 4.3125 | 4 | # -*-coding:Utf-8 -*
"""
Programme réalisant la syllabisation d'un mot passé en paramètre, puis
encode le résultat pour donner un nombre dont les chiffres correspondent à la
taille des syllabes du mot.
"""
import argparse
from syllabes import *
# Gestion des arguments
parser = argparse.ArgumentParser(description="Pr... | false |
0d24c54ddad66895ed31c0f3da5639350d25fe92 | jhammelman/HSSP_Python | /lesson2/text_adventure_game.py | 1,283 | 4.15625 | 4 | #!/usr/bin/env python
print("You are standing in front of a black iron gate with rusty hinges and a large gold lock. Behind the gate stands an ominous castle, shrouded with clouds and with large gargoyles that cast creepy shadows onto the ground.")
go_in = raw_input("Do you try to open the gate? (y or n) ")
if go_in =... | true |
a0b9298f53a17f612aabfaab15c89b1f72ee58d8 | jupiterorbita/python_stack | /python_OOP/bike.py | 1,939 | 4.75 | 5 | #http://learn.codingdojo.com/m/72/5471/35330
#Assignment: Bike
# Create a new class called Bike with the following properties/attributes:
# price
# max_speed
# miles
# Create 3 instances of the Bike class.
# Use the __init__() method to specify the price and max_speed of each instance (e.g. bike1 = Bike(200, "25mph")... | true |
ce7d0ffa978ce9565290d9b901958bad5b5b3e8c | jupiterorbita/python_stack | /python_fundamentals/functions_interm_II_dict.py | 890 | 4.125 | 4 | # Assignment: Functions Intermediate II
# Write the following function.
# Part I (essential)
# Given the following list:
# students = [
# {'first_name': 'Michael', 'last_name' : 'Jordan'},
# {'first_name' : 'John', 'last_name' : 'Rosales'},
# {'first_name' : 'Mark', 'last_name' : 'Guillen'},
# {'... | false |
db273d324cceae6725e9b753373f78d5d9ea007d | BrodyJorgensen/practicles | /prac_1/loops.py | 480 | 4.28125 | 4 | #for the odd numbers
#for i in range(1, 21, 2):
# print(i)
#count to 100 in lots of 10
#for i in range(0, 101, 10):
# print(i)
#to ocunt down from 20
#for i in range(20, 0, -1):
# print(i)
#printing different numbers of stars
#number_of_stars = int(input("Number of stars: "))
#for i in range (number_of_star... | true |
19da8c81fbbbde3d9e08038825566210a88ff341 | AlexFue/Interview-Practice-Problems | /math/fizz_buzz.py | 1,102 | 4.4375 | 4 | # Problem:
# Given an input, print all numbers up to and including that input, unless they are divisible by 3, then print "fizz" instead, or if they are divisible by 5, print "buzz". If the number is divisible by both, print "fizzbuzz".
# For example, given 5:
# 1
# 2
# fizz
# 4
# buzz
# Given 10:
# 1
# ... | true |
c0bbf25f0855f258bc7bec174de3e3fb607eee64 | AlexFue/Interview-Practice-Problems | /math/palindrome_number.py | 2,054 | 4.3125 | 4 | Problem:
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
Follow up: Could you solve it without converting the integer to a string?
Example 1:
Input: x = 121
Output: true
Example 2:
Input: x = -121
Output: false
Explanation: From left to right, ... | true |
256a03dcbc7e21268fcac16009241ae548e22f5a | AlexFue/Interview-Practice-Problems | /string/group_anagrams.py | 1,935 | 4.4375 | 4 | Problem:
Given an array of strings strs, group the anagrams together. You can return the answer in any order.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Example 1:
Input: strs = ["eat","tea","tan","ate","na... | true |
4bb9c049136e21b22c9ed3047e55559d766d8051 | AlexFue/Interview-Practice-Problems | /math/power_of_three.py | 688 | 4.6875 | 5 | Problem:
Given an integer, write a function to determine if it is a power of three.
Example 1:
Input: 27
Output: true
Example 2:
Input: 0
Output: false
Example 3:
Input: 9
Output: true
Example 4:
Input: 45
Output: false
Solution:
import math
def power_of_three(n):
power = 0
while 3**power <= n:
if 3*... | true |
f396cb3f64cc487ad75d3c5d2cceb84ccd7b1b00 | AlexFue/Interview-Practice-Problems | /sorting_algorithm/median_two_sorted_arrays.py | 2,137 | 4.15625 | 4 | Problem:
Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.
Follow up: The overall run time complexity should be O(log (m+n)).
Example 1:
Input: nums1 = [1,3], nums2 = [2]
Output: 2.00000
Explanation: merged array = [1,2,3] and median is 2.
Example 2:... | true |
69bce08cc02472e4ec62a8dfb78e586692574dfa | flashypepo/myMicropython-Examples | /displays/DisplaysDrawingText/drawtextnpmatrix.py | 813 | 4.125 | 4 | # 2016-1219 draw text on neopixel matrix
# https://learn.adafruit.com/micropython-displays-drawing-text/software
import neopixel
import machine
matrix = neopixel.NeoPixel(machine.Pin(13, machine.Pin.OUT), 64)
# define the pixel function, which has to convert a 2-dimensional
# X, Y location into a 1-dimensional loca... | true |
64291a7cb59c8e4de148a075ab0c0f59faf84b84 | BlueBookBar/SchoolProjects | /Projects/PythonProjects/Project4.py | 1,825 | 4.125 | 4 |
#used the factorial number system
def Permutation(thisList):
NumberofpossibleFactorial = [1]#Used to contain the number of factorial possiblities of the permutation
for iterator in range(1,len(thisList)+1):#Populate the factorial list
NumberofpossibleFactorial.append(NumberofpossibleFactorial[iterato... | true |
469d35e7c3c3d7dbd7ef63c65af009e1e6b764ea | qsyed/python-programs | /leetcode/reverse_integer.py | 1,282 | 4.15625 | 4 | """
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: [−231, 231 − 1]. For the pu... | true |
6e9126df734b950627a21661d32c6e99ce738395 | qsyed/python-programs | /sqlite3-python/sql_injection.py | 1,313 | 4.375 | 4 | import sqlite3
conn = sqlite3.connect("sqlite3-python/users.db")
"""
this execrise wa meant to show how sql injection can work if the query strings are not set up properly
first we have to set up a data base and enter in seed data.
the data base was created by using
query = "CREATE TABLE user (username TEX... | true |
74d2268b7683c0da087c8c2f6e4f7549e2788998 | JulieRoder/Practicals | /Activities/prac_06/car.py | 1,162 | 4.25 | 4 | """
CP1404/CP5632 Practical - Car class example.
Student name: Julie-Anne Roder
"""
class Car:
"""Represent a Car object."""
def __init__(self, name="Car", fuel=0):
"""Initialise a Car instance.
fuel: float, one unit of fuel drives one kilometre
"""
self.name = name
s... | true |
dc37ecb1e5a2fd133bbae234ff4f9351ba608c97 | JulieRoder/Practicals | /Activities/prac_06/guitar_class.py | 823 | 4.125 | 4 | """
Guitar Class
Student name: Julie-Anne Roder
"""
class Guitar:
"""Represents a Guitar Object."""
CURRENT_YEAR = 2020
VINTAGE_THRESHOLD = 50
def __init__(self, name="", year=0, cost=0.0):
"""Initialises a guitar instance
name: make & model
year: year guitar was made
... | true |
4fb8c17e5922581379dd0bc65e9c29e46c364a47 | Jian-jobs/Jian-leetcode_python3 | /algorithm/BubbleSort.py | 747 | 4.15625 | 4 |
# coding:utf-8
# 冒泡排序
# 1. 外层循环负责帮忙递减内存循环的次数【1, len-1】
# 2. 内层循环负责前后两两比较, index 的取值范围【0, len-2】 len-1-i 次,求最大值放到最后
def bubble_sort(nums):
# [1, len-1]
for i in range(1, len(nums)-1):
print(i)
# [0, len(nums)-i] j is index
for j in range(len(nums)-i):
if nums[j] > nums[j+1... | false |
2feff85ac758dcafa3d9f7dfdc3fac2acea55acc | pastaTree/Data-Structures-and-Algorithms | /453_flatten_binary_tree_to_linked_list.py | 2,020 | 4.1875 | 4 | """453 Flatten Binary Tree to Linked List
Algorithm:
1. 显然我们很难直接在数上操作达到in-place的flatten
2. 使用递归
3. 把right subtree挂到left subtree的最右边节点上,left subtree再挂到root的right上去。
这样不停操作,就可以达到把树向右边flatten的目的。
Note:
分治:(返回最后一个节点)
情况 操作 返回值
左有右有 swap right_last
左有右无 swap left_last
左无右有 N/A right_last
左无右无 N/A node
前序遍... | false |
0ba48b9de780c8ce1add0dfdadddce69e4ce4e36 | santosh235/com_phy | /HW1/santosh_HW1/3/3.py | 382 | 4.1875 | 4 | # Q3:TO PRINT POLAR COORDINATES
import math
import numpy as np
x=input("Enter the X-cordinate:")
y=input("\n Enter the Y-cordinate:")
x=float(x)
y=float(y)
r=x*x+y*y
r=math.sqrt(r)
rad=np.arctan(abs(y)/abs(x))
theta=(360*rad)/(2*3.14)
if x<0 and y>0 :
theta=theta+90
if x<0 and y<0 :
theta=theta+180
if x>0 and y<0 ... | false |
751627ebef789a911d50b90d2f398c6b49dbdf3d | ctostado/Python-Projects | /Ejemplos/Listas.py | 618 | 4.21875 | 4 | datos = [4, "Caracteres", -13, 3.1416, "otra cadena"]
print (datos[0])
print (datos[3])
print (datos[0:2])
print (datos[2:])
#Añadiendo contendio a las listas
pares = [0,2,4,5,8]
pares[3] = 6
print(pares)
pares.append(10)
print(pares)
pares.append(6*2)
print(pares)
#Modificando el contenido con Slicing
le... | false |
9bdb46cb7f8263c67a7f8d76643ebaf4e048883b | wfhsiao/datastructures | /python/classes/LinkedQueue.py | 1,510 | 4.375 | 4 | # Python3 program to demonstrate linked list
# based implementation of queue
# A linked list (LL) node
# to store a queue entry
class Node:
def __init__(self, data):
self.data = data
self.next = None
# A class to represent a queue
# The queue, front stores the front node... | true |
0ba44ef8e4017d9152f874ef190d2b09c4c58764 | jfcjlu/APER | /Python/Ch. 07. Python - Normal Distribution - Probability of x between x1 and x2.py | 585 | 4.125 | 4 | # Python - NORMAL DISTRIBUTION - PROBABILITY OF x BETWEEN x1 AND x2
# http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.norm.html
from scipy.stats import norm
# Enter the following values
mean = 4 # the mean
stdev = 1 # and standard deviation of the distribution
# Enter the values of the limit... | true |
09bae4b4fd74433d59a19694a3a7a9a0a672dbc1 | shahed-swe/python_practise | /recursion.py | 1,522 | 4.15625 | 4 | # here we will discuss about recursion
# factorial problem
def factorial(n):
'''this function return the factorial number'''
if n == 1:
return 1
return n * factorial(n-1)
# out put will be the factorial of the number is given
# reverse order problem
def print_rev(i,n, a):
'''this function basi... | true |
6e16b3b82f4942ed14679fa2b22e22ae527eb67e | shahed-swe/python_practise | /flexible_functions.py | 2,624 | 4.40625 | 4 | # intro to arguments means (args*)
# make flexible function
# *operator
# *args
def all_elem(*args):
print(args)
print(type(args))
def all_sum(*args):
total = 0
for i in args:
total += i
return total
if __name__ == '__main__':
all_elem(2,3,4,5)
print(all_sum(2,5,6,7,8,9))
#we can't write parame... | false |
62960d349418a139f2dbe16a607dbdbc2f012716 | caiolucasw/pythonsolutions | /exercicio53.py | 1,063 | 4.59375 | 5 | '''Assuming that we have some email addresses in the "username@companyname.com" format,
please write program to print the user name of a given email address. Both user names and company names
are composed of letters only.
Example: If the following email address is given as input to the program:
john@google.com
Then, ... | true |
65f418215ce8198f87b4bb9e15b1839663360cbf | caiolucasw/pythonsolutions | /exercicio31.py | 268 | 4.1875 | 4 | '''Define a function which can print a dictionary where the keys are numbers between 1 and 20
(both included) and the values are square of keys.'''
dicionario = {i: i**2 for i in range(1,21)}
print(dicionario)
#exercicio32
for i in dicionario.keys():
print(i) | true |
d020d4a32b7a6b4d62b80a73c0f3687874c79feb | Strangedip/Rock-Paper-Scissor-game | /main2.py | 830 | 4.1875 | 4 | #create rock paper scissor game using functions
import random
def gamewin(comp, player):
if comp == player:
return None
elif comp == "r":
if player=="p":
return True
else :
return False
elif comp == "p":
if player=="s":
ret... | false |
d7726b01bddf327561c0914c1c7db68433f840b1 | spacecowboy2049/clouds | /Linux/python/1/Activities/05-Variable-Dissection/UNSOLVED-Variables-Dissect.py | 1,714 | 4.3125 | 4 | # Part 1
# =====================================
# Prints: [FILL IN]
variable_one = 10
print(variable_one)
print(type(variable_one))
# Prints: [FILL IN]
variable_two = 5
print(variable_two)
# Prints: [FILL IN]
sum_of_variables = variable_one + variable_two
print(sum_of_variables)
# Prints: [FILL ... | true |
09172aacd60e7d7b00b39fffe191ccb571fe0665 | brdyer/DAEN_500_Fall_2020_Final_Exam | /DAEN_500_final_prob_1.py | 892 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 8 08:21:51 2020
@author: braddyer
"""
# get user input of range for analysis
usr_range_start = int(input('Enter the low end of the range you want to try: '))
usr_range_end = int(input('Enter the high end of the range you want to try: '))
# determ... | true |
651d4ded3f2b151553b44c300998d6352c69a76e | mturpin1/CodingProjects | /Python/encrypt.py | 385 | 4.21875 | 4 | import os
plainText = input('Please enter a word you would like encrypted - ').lower().strip()
key = int(input('Please enter an encryption key (it can be any whole number) - '))
alphabet = 'abcdefghijklmnopqrstuvwxyz'
encryptedText = ''
for letter in plainText:
index = alphabet.find(letter)
encryptedText += (al... | true |
b3116b23c454985cdc1c5a6c00d8e6b4123d596a | mturpin1/CodingProjects | /Python/curfew_checker.py | 911 | 4.3125 | 4 | age = input('How old are you?: ')
age = int(age)
time = input('What hour is it?: ')
time = int(time)
def curfew_check():
if age >= 0 and age <= 12:
print('\"Get off the computer, please.\"')
elif (age > 12 and age <= 16) and (time >= 0 and time <= 8):
print('\"You should be asleep!\"')
elif ... | false |
dfcc64126ae03f7328660a14a3f87cf4056416d6 | mturpin1/CodingProjects | /Python/debugging3.py | 340 | 4.28125 | 4 | color = input('Pick a color. ')
def color_choice(color):
if color == 'red' or color == 'Red':
print('You chose red.')
elif color == 'blue' or color == 'Blue':
print('You chose blue.')
elif color == 'orange' or color == 'Orange':
print('You chose orange.')
else:
print('You screwed something up.')... | true |
7b62c3824d332f64cba621ce991237cafcc09118 | SHPStudio/LearnPython | /basic/iteration.py | 978 | 4.125 | 4 | # 迭代器
# Iterator 可以使用next()不断获取值的对象 并且可以使用isinstance()判断对象是否是迭代器
# Iterable 是可以使用for迭代去获取值的对象 叫可迭代对象但并不一定是Iterator
# 比如generater生成器一定是迭代器对象 list tuple set等等可能就不是迭代器对象
# 但是他们可以使用iter()变为迭代器对象
from collections import Iterable,Iterator
print(isinstance('adfa',Iterable))
print(isinstance([1,1,2,3],Iterable))
print(isinstan... | false |
a9042e33d9a85d4a4329f85024ffde27f0503528 | haidarknightfury/PythonBeginnings | /Programs/SearchEngine/OtherPrograms/Symmetric.py | 626 | 4.34375 | 4 | # A list is symmetric if the first row is the same as the first column,
# the second row is the same as the second column and so on. Write a
# procedure, symmetric, which takes a list as input, and returns the
# boolean True if the list is symmetric and False if it is not.
def symmetric(lists):
if lists == []:
... | true |
1e951346e8e76304a79f761ab81cbf7a5f3334b4 | haidarknightfury/PythonBeginnings | /Programs/SearchEngine/OtherPrograms/IdentityMatrix.py | 696 | 4.1875 | 4 | # Given a list of lists representing a n * n matrix as input,
# define a procedure that returns True if the input is an identity matrix
# and False otherwise.
# An IDENTITY matrix is a square matrix in which all the elements
# on the principal/main diagonal are 1 and all the elements outside
# the principal diagonal ... | true |
946833b6f8f89ed914ccdf9fe14b3dea226d5121 | beknazar1/code-platoon-self-paced | /week-1-challenges/armstrong_numbers.py | 612 | 4.1875 | 4 | import math
def find_armstrong_numbers(numbers):
OUTPUT = []
for number in numbers:
# Leverage python libraries to easily split a number into a list of digits
DIGITS = [int(digit) for digit in str(number)]
# Length of DIGITS list will be the exponent per defintion of Armstrong numbers
... | true |
d42e67147a1222caeaa547d013741f55c7894669 | griffithcwood/Image-Processing | /imageOpen.py | 828 | 4.15625 | 4 | #!/usr/bin/env
from tkinter import filedialog
from tkinter import *
import tkinter as tk # neede for window
def prompt_and_get_file_name():
"""prompt the user to open a file and return the file path of the file"""
# TO DO: add other file types!!!!!!!!!!!!!!!!!!
try:
img_file_name = filedialog... | true |
72b840a1618a274cd2e076fd0a796fe2dcae79f3 | Skumbatee/bc-9-oop | /student.py | 2,003 | 4.1875 | 4 | import datetime
map_ = {
'UG': 'Uganda',
'KE': 'Kenya',
'NG': 'Nigeria',
'TZ': 'Tanzania'
}
class Student(object):
#declaring a variable Id with a value zero which is an instance variable
Id = 0
#Create an empty dictionary attendace that stores the attendance of the students ... | false |
25f4d99f9dd32a9ac8d5d2ddab5959822c0c932f | Dhan-shri/If-else | /schedule.py | 669 | 4.34375 | 4 | time=float(input("enter a time"))
# time is given in 24 format
if time>6 and time<=7:
print("morning exercise")
elif time>7 and time<=8.30:
print("breakfast")
elif time>8.30 and time<=9.30:
print("english activity")
elif time>9.30 and time<=13:
print("coding time")
elif time>13 and time<=14.30:
pri... | true |
710aebc04b24921c716e0c3ff0b30574773c9c68 | kalu661/desafio | /desafio_1.py | 1,241 | 4.1875 | 4 | print('>-----------------------------------------<')
#Definicion de Variables
palabra = input('Ingrese una palabra ');
palabra1 = int(len(palabra));
palabra2 = int;
palabra3 = int;
es_multiplo = int;
result = int;
a_string = palabra
# Conversion de string a ASCII
ASCII_values = []
for character in a_string:
ASCII_... | false |
fd8fbbc10b3cf4a4f960a7234229be4d2bd6aa17 | MrBlackred/python | /section3.py | 481 | 4.28125 | 4 | # list
'''
name = ['ame', 'nts', 'fb', 'XQ', 'y']
print(name)
print(name[0].title())
print(name[-1]) # end element
## 3-2 append change del insert
name[0] = 'kaka' #change
name.append('hel')
name.insert(0, 'lx')
name2 = name.pop()
name3 = name.pop(2)
name.remove('kaka')
del name[1]
print(name)
print(name2)
print(... | false |
889fe072686f7c2376300452cea08d619d326540 | adomiter/CAAP-CS | /assignment_2/practice10.py | 548 | 4.1875 | 4 | #modify the above program
def Easter(year):
a = year%19
b = year%4
c = year%7
d = (19a + 24)%30
e = (2b+4c+6d+5)%7
exceptions = {"1954",
"1981",
"2049",
"2079"}
if year == exceptions;
print("The date for Easter in", year,"is April",... | false |
2111d6fda9adc76a528dd5782c92931b486fba42 | adomiter/CAAP-CS | /Practices_Ch8/quiz_2.py | 327 | 4.15625 | 4 | def word_length(sentence):
sentence_array=sentence.split(" ")
num_words=len(sentence_array)
sum=0
for i in sentence_array:
length_word=len(i)
sum += length_word
return(sum/num_words)
def main():
user_sentence=input("What is the sentence?")
print(word_length(user_sentence))
m... | true |
c8a092a5ef6048a1b7de4b5b8bba925e807da787 | A-fish-in-Lake-Baikal/python-exercise | /110Questions/58.py | 237 | 4.125 | 4 | # -*- coding: utf-8 -*-
#使用pop和del删除字典中的”name”字段,dic={“name”:”zs”,”age”:18}
dic1 = {"name":"zs","age":18}
dic2 = {"name":"zs","age":18}
dic1.pop("name")
print(dic1)
del dic2["name"]
print(dic2)
| false |
074b5c41d84ebf7a30362101ae6a0c404840b70f | spoorthyvv/Python_workshop | /day2/p5.py | 204 | 4.1875 | 4 | import numpy as np
List=[]
num=int(input("Enter the number of elements"))
print('Enter the elements: ')
for i in range(num):
List.append(int(input()))
print('Average Of The Numbers Is: ',np.mean(List))
| true |
57bcf5cd33907e850f05e7f5f10c45c5020960ba | spoorthyvv/Python_workshop | /day1/offline_exercises_session1_day1/program5.py | 480 | 4.1875 | 4 | num1=int(input("Enter the first number: "))
num2=int(input("Enter the second number: "))
num3=int(input("Enter the Third number: "))
num4=int(input("Enter the fourth number"))
def find_Biggest():
if(num1>=num2) and (num1>=num2):
greatest=num1
elif(num2>=num1) and (num2>=num3):
greatest=... | true |
057f90b504c71f45eb2e766b9d663f5d767f20b8 | santosh6171/pyScripts | /reverseSentence.py | 246 | 4.375 | 4 |
def get_reverse_string(str):
liststr = str.split()
return " ".join(liststr[::-1])
string = input("Enter a sentence to be reversed\n")
reverseString = get_reverse_string(string)
print ("Reversed string is: {0}" .format(reverseString))
| true |
4295e7f056474a6453ef15da6d17a18ff890e5f1 | surya1singh/Python-general-purpose-code | /multithreading/simple_use.py | 2,024 | 4.1875 | 4 | from threading import Thread, Lock, active_count, current_thread, Timer, enumerate
import time
def first_threads():
first = Thread(target=print, args=("This is print statement is with input :",1))
second = Thread(target=print, args=("This is print statement is with input :",2))
third = Thread(target=print,... | true |
a9a263f4b3a58c22a57d5f06ba4b17d98707e0c4 | Aperocky/leetcode_python | /007-ReverseInteger.py | 945 | 4.21875 | 4 | """
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: [−231, 231 − 1]. For th... | true |
f481a25733269c39d82eb807e0c549550b19dfdf | nitzjain/practice | /array/create_own_dynamic_array.py | 1,843 | 4.3125 | 4 | '''
the aim is to create your own dynamic array.
If the array gets filled up, then double the size of the array.
So we create a new array with double the size and rename it to the first array.
We use ctypes library to create an array object.
'''
import ctypes
class DynamicArray(object):
#init method. Has 3 compon... | true |
4482f2a0cf59f804ae3a604d2a7ad2c7a1663347 | ben-whitten/ICS3U-Unit-4-03-Python | /square_to_be_fair.py | 2,257 | 4.21875 | 4 | #!/usr/bin/env python3
# Created by: Ben Whitten
# Created on: October 2019
# This is a program which tells you the total value of a number.
# This allows me to do things with the text.
class color:
PURPLE = '\033[95m'
CYAN = '\033[96m'
DARKCYAN = '\033[36m'
BLUE = '\033[94m'
GREEN = '\033[92m'
... | true |
ea76bb800fb75050700f066e2e4c7b0b68e879a4 | Ramshiv7/Python-Codes | /Timer.py | 302 | 4.28125 | 4 | # Write a Python function which display timer(in Seconds)
import time
def timer(i):
while i>0:
print(i)
time.sleep(1)
i-= 1
try:
i = int(input('Set the Timer for (Seconds): '))
int(i)
timer(i)
except ValueError:
print('Input is not an INTEGER !')
| true |
d9d45ba89127f5703db72deae8b44add3ed03919 | 7minus2/Python | /Excercises/highest_even.py | 404 | 4.46875 | 4 | #!/usr/local/bin/python3
def highest_even(my_list):
'''
Info: Get the highest even number from a list of numbers \n
Example: highest_even([10,2,3,4,8,11]) # returns 10
'''
even_list = [num for num in my_list if num % 2 == 0]
highest_number = sorted(even_list, reverse=True)
return highest_n... | true |
93fdf41bfe452b6a82d8683df202919f24bf802c | Lemito66/Python | /SobreCargaOperadores.py | 1,029 | 4.21875 | 4 | class Vector(object):
def __init__ (self, x, y,z):
self.x = x
self.y = y
self.z=z
def __repr__ (self):
return '(%f, %f,%f)' % (self.x, self.y,self.z)
def __mul__ (self, v): #sobrecarga de multiplicacion
return Vector (self.x *v.x, self.y *v.y,... | false |
9787c525e089d6aac97d7279a37b84ee7428ba88 | Philstrae/001-projet | /san_antonio.py | 1,431 | 4.15625 | 4 | import random
import json
# -*- coding: utf8 -*-
quotes= [
"Ecoutez-moi, Monsieur Shakespeare, nous avons beau être ou ne pas être, nous sommes !",
"On doit pouvoir choisir entre s'écouter parler et se faire entendre."
]
#characters = [
# "alvin et les Chipmunks",
# "Babar",
# "betty boop",
# "cal... | false |
02bde541cb9fac492db28cc4d9cdec72918afeaf | pranali04/practice | /inheritance.py | 1,112 | 4.25 | 4 | # Online Python compiler (interpreter) to run Python online.
# Write Python 3 code in this online editor and run it.
#print("Hello world")
class math:
def __init__(self,a,b):
print("math class")
class divide(math):
def __init__(self,a,b):
self.a = a
self.c = b
print("divide initi... | false |
d2bfc5e779a9a7f493f990ab092856dd6bbee7c8 | danieljobvaladezelguera/CYPDANIELJVE | /for3.py | 208 | 4.15625 | 4 | for v in range(3,31,3):
print("Hola",v)
for v in range(20,-1,-1):
print("Hola",v)
print('------------------------')
n = int(input("Dame un numero: "))
for x in range(0,n,1):
print("+",end="")
| false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.