blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
a0c345ef1bff86d36895d35a6291383a06ef8def | MayankVerma105/Python_Programs | /multiplication.py | 305 | 4.125 | 4 | def printTable(num, nMultiples = 10):
for multiple in range(1, nMultiples + 1):
product = num * multiple
print(num,'*','%2d'% multiple, '=' , '%5d'% product)
def main():
num = int(input('Enter the Number : '))
printTable(num)
if __name__ == '__main__':
main()
| false |
4d9a439a7e2c3eea5d6413139db67b685fb38e7a | Burrisravan/python-fundamentals. | /LIST/lists.py | 1,013 | 4.1875 | 4 | lst1=[1, 'sravan', 10.9]
lst2 =[90,20,50,100,8,0]
lst3 =[5,89,3,99,23,7]
print(lst1)
print(lst1[2])
print(lst1+lst2)
print(lst1*5)
print(max(lst2))
print(min(lst2))
print(len(lst2))
print(lst2[:]) # prints all in the list
print(lst2[1:3])
print(lst2[-1]) # pri... | true |
4ad7d619d47c08500341a4e860b95a11301f233f | enthusiasticgeek/common_coding_ideas | /python/exception.py | 553 | 4.21875 | 4 | #!/usr/bin/env python3
def divide_numbers(a, b):
try:
result = a / b
print("Result:", result)
except ZeroDivisionError:
print("Error: Division by zero!")
except TypeError:
print("Error: Invalid operand type!")
except Exception as e:
print("An unexpected error occu... | true |
3982d495e405bef4db0ae8a3787540f03ad38f01 | mohanakrishnavh/Data-Structures-and-Algorithms-in-Python | /Searching/count_element.py | 1,682 | 4.15625 | 4 | from typing import List
def find_min_index(A: List[int], x: int) -> int:
"""
Finds the max index of the element being searched
:param A: Input Array
:param x: Element to search in the array
:return: Min Index of the element being searched
"""
min_index = -1
start = 0
end = len(A)-1... | true |
e81faee5b80e46b9efa87794c8293d22638a20b1 | mohanakrishnavh/Data-Structures-and-Algorithms-in-Python | /Sorting/insertion_sort.py | 427 | 4.125 | 4 | '''
Insertion Sort
Time Complexity : O(n^2)
Best Case : O(n)
Average Case : O(n^2)
Worst Case : O(n^2)
Space Complexity : O(1)
'''
def insertion_sort(A):
n = len(A)
for i in range(1, n):
value = A[i]
hole = i
while hole > 0 and A[hole - 1] > value:
A[hole] = A[hole - 1]
... | false |
bbe4ea6780e4b3aa8bb98bd82fb38a9ea0bc678a | mohanakrishnavh/Data-Structures-and-Algorithms-in-Python | /datastructures/stack/Stack.py | 1,282 | 4.15625 | 4 | class Stack:
def __init__(self):
self.stack = []
self.top = -1
def push(self, x):
'''
Push an element x into the stack
:param x: input element
'''
self.top += 1
self.stack.append(x)
def pop(self):
'''
Removes the topmost eleme... | true |
e8bac117e889770c1bae6fc994a73ea401096af0 | Stephan-kashkarov/Number-classifier-NN | /neuron.py | 1,393 | 4.28125 | 4 | import numpy as np
class Neuron:
"""
Neuron Initializer
This method initalises an instance of a neuron
Each neuron has the following internal varaibles
Attributes:
-> Shape | This keeps track of the size of the inputs and weights
-> Activ | This is the function used to cap the ra... | true |
2be6c1dff2a08f4b38119d1094ab5b8b589ad699 | Nimrod-Galor/selfpy | /823.py | 615 | 4.4375 | 4 | def mult_tuple(tuple1, tuple2):
"""
return all possible pair combination from two tuples
:tuple1 tuple of int
:type tuple
:tuple2 tuple of int
:type tuple
:return a tuple contain all possible pair combination from two tuples
:rtype tuple
"""
comb = []
for ia in tuple1:
... | true |
0d3683efd8fc9dd8578928cda52114cc18204895 | Dev-352/prg105 | /chapter 10/practiec 10.1.py | 1,760 | 4.6875 | 5 | # Design a class that holds the following personal data: name, address, age, and phone number.
# Write appropriate accessor and mutator methods (get and set). Write a program that creates three
# instances of the class. One instance should hold your information and the other two should hold your friends'
# or family... | true |
570f38c28c680b599d34897d1988f74196f61225 | Dev-352/prg105 | /chapter 9/practice 9.2.py | 1,161 | 4.15625 | 4 | # Create a dictionary based on the language of your choice with the numbers from 1-10 paired with the numbers
# from 1-10 in English. Create a quiz based on this dictionary. Display the number in a foreign language and
# ask for the number in English. Score the test and give the user a letter grade.
def main():
... | true |
da5322901540169f5a33d233ab94b973430be4a7 | Dev-352/prg105 | /sales.py | 787 | 4.5 | 4 | # You need to create a program that will have the user enter in the total sales amount for the day at a coffee shop.
# The program should ask the user for the total amount of sales and include the day in the request.
# At the end of data entry, tell the user the total sales for the week, and the average sales per day... | true |
aac34c61da8a66e9539c44318db89fa1ddf1a5fd | fatima-cyber/madlibs | /madlibs.py | 939 | 4.46875 | 4 |
# MadLibs - String Concatenation
#suppose we want to create a string that says "subscribe to ____"
youtuber = "Fatima" #some string variable
# a few ways to do this
# print("subscribe to " + youtuber)
# print("subscribe to {}".format(youtuber))
# print(f"subscribe to {youtuber}") # using this
adj = input("Adje... | true |
c39bd54af1b2b184392b69d7712f7f06d77ed3df | Sampatankar/Udemy-Python | /280521.py | 708 | 4.3125 | 4 | # Odd or Even number checker:
number = int(input("Which number do you want to check? "))
if number % 2 != 0:
print("This is an odd number.")
else:
print("This is an even number.")
# Enhanced BMI Calculator
height = float(input("enter your height in m: "))
weight = float(input("enter your weight in... | true |
d5df4247029297677c33b8f8172b4e62d7369093 | BillMaZengou/raytracing-in-python | /01_point_in_3d_space/mathTools.py | 769 | 4.1875 | 4 | def sqrt(x):
"""
Sqrt from the Babylonian method for finding square roots.
1. Guess any positive number x0. [Here I used S/2]
2. Apply the formula x1 = (x0 + S / x0) / 2. The number x1 is a better approximation to sqrt(S).
3. Apply the formula until the process converges. [Here I used 1x10^(-8)]
... | true |
3309ec514d0ae1ad9f84aab3f7f455836b91f5aa | ivaben/Intro-Python-I | /src/13_file_io.py | 998 | 4.28125 | 4 | """
Python makes performing file I/O simple. Take a look
at how to read and write to files here:
https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files
"""
# Open up the "foo.txt" file (which already exists) for reading
# Print all the contents of the file, then close the file
# Note: pay close... | true |
5cd8bf7993bd2c5c4e297489e12ff22170f21297 | WillLuong97/Back-Tracking | /countSortedVowelString.py | 2,449 | 4.125 | 4 | #Leetcode 1641. Count Sorted Vowel Strings
'''
Problem statement:
Given an integer n, return the number of strings of length n that consist only of vowels (a, e, i, o, u) and are lexicographically sorted.
A string s is lexicographically sorted if for all valid i, s[i] is the same as or comes before s[i+1] in the alp... | true |
911c4f8d06289dcbc836627b624afeba3ee01d59 | nasimulhasan/3D-Tank-Implementation-with-Pygame | /frange.py | 831 | 4.28125 | 4 | def frange(x, y, jump=1.0):
'''
Range for floats.
Parameters:
x: range starting value, will be included.
y: range ending value, will be excluded
jump: the step value. Only positive steps are supported.
Return:
a generator that yields floats
Usage:
>>> list(... | true |
ef113f468766d0b48cb18482b59871dbbba7f210 | nguyenhuuthinhvnpl/met-cs-521-python | /instructor_code_hw_5/hw_5_5_1.py | 670 | 4.125 | 4 | def vc_cntr(sentence):
"""
Return count of vowels and consonants from input sentence
:param sentence:
:return:
"""
vowels = "AEIOU"
sentence = sentence.upper()
v_total = len([v for v in sentence if v in vowels])
c_total = len([c for c in sentence if c.isalpha() and c not in vowels... | false |
6c5155cd03a0219f37566a46e68b629720962910 | RenanBertolotti/Python | /Curso Udemy/Modulo 02 - Pyhton Basico/Aula 04 - Dados Primitivos/aula04.py | 636 | 4.15625 | 4 | """
Tipos de dados
String - str == Texto 'assim' ou "assim"
Inteiro - int == 1, 2, 3, 4, 5
Float - real/flutuante = 1.12313, 2.465456, 3.465465
Bool - Booleane/logico = true or false
"""
print("Luiz", type("Luiz"))
print(10, type(10))
print(10.5, type(10.5))
print(True, type(True))
print("Renan"=="Renan", type("Renan... | false |
e1a422898de6efb51dd0081bb6b0c1fc798cd957 | RenanBertolotti/Python | /Curso Udemy/Modulo 03 - Python Intermediário (Programação Procedural)/Aula 27 - Try, Except - Tratando Exceçoes em Python/Aula27.py | 1,226 | 4.125 | 4 | """
Try / Except em python
#Try/Except basico
try:
a = 1/0
except NameError as erro:
print("erro", erro)
except (IndexError, KeyError) as erro:
print("erro de indice", erro)
except Exception as erro:
print("ocorreu um erro inesperado")
else:
print("Seu codigo foi afetuado com sucesso")
finally:
... | false |
e3b1316f30318aefc72598f57ecaeaac86ca2409 | NeniscaMaria/AI | /1.RandomVariables/lab1TaskC/main.py | 2,428 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Feb 29 15:54:46 2020
@author: nenis
"""
from sudoku import Sudoku
from geometricForms import GeometricForms
from cryptoarithmeticGame import CryptoarithmeticGame
def showMenu():
print("\nPlease choose one from below:")
print("0.Exit")
print("1.Sudoku")
print(... | true |
cfd40b3aac0c66750c048a7c85dc3cfcdbd79e31 | TsabarM/MIT_CS_Python | /analyze_song_lyrics.py | 2,085 | 4.6875 | 5 | # Analyze song lyrics - example for use python dictionaries
'''
In this example you can see how to create a frequency dictionary mapping str:int.
Find a word that occures the most and how many times.
Find the words that occur at least X times.
'''
def lyrics_frequencies(lyrics):
'''
Creates a Dictionary with... | true |
0e61d1baa0e9ae984dd83cf27ac96d4c7e6c509f | JCode1986/python-data-structures-and-algorithms | /sorts/insertion_sort/insertion.py | 430 | 4.21875 | 4 | def insertion_sort(lst):
"""
Sorts list from lowest to highest using insertion sort method
In - takes in a list of integers
Out - returns a list of sorted integers
"""
for i in range(1, len(lst)):
j = i - 1
temp = int((lst[i]))
while j >= 0 and temp < lst[j]:
lst[j + 1] = lst[j]
... | true |
a3154200beab4765d7c8177e01cc426ef4ec63b0 | kfcole20/python_practice | /math_practice.py | 1,021 | 4.625 | 5 | # Assignment: Multiples, Sum, Average
# This assignment has several parts. All of your code should be in one file that is well commented to indicate what each block of code is doing and which problem you are solving. Don't forget to test your code as you go!
# Multiples
# Part I - Write code that prints all the odd nu... | true |
404c5cd7f34836b70d2eb951764f4381d65f8eb8 | Edre2/StarkeVerben | /main.py | 2,763 | 4.15625 | 4 | import csv
import random as rando
# The prompt the user gets when he has to answer
PROMPT = "> "
# The numbers of forms of the verbs in franch and german
NUMBER_OF_FORMS_DE = 5
NUMBER_OF_FORMS_FR = 1
# Gets the verbs from verbs.csv
def get_defs():
verbs = []
with open('verbs.csv', 'r') as verbs_file:
read... | true |
584c5f4001acaf49483381af86083d9453c755db | eSuminski/Python_Primer | /Primer/examples/key_word_examples/key_word_examples.py | 987 | 4.125 | 4 | from to_import import MyClass as z
# from indicates where the code is coming from
# import tells you what code is actually being brought into the module
# as sets a reference to the code you are importing
my_list = ["eric", "suminski"]
for name in my_list:
print(name)
# for is used to create a loop, and in is use... | true |
f294b5d241e782c77cf243666f82a043f7ae2c8b | Jitender214/Python_basic_examples | /02-Python Statements/03-while Loops, break,continue,pass.py | 808 | 4.1875 | 4 | # while loops will continue to execute a block of code while some condition remains true
#syntax
#while some_boolean_condition:
#do something
#else
#some different
x = 0
while x < 4:
print(f'x value is {x}')
x = x+1
else:
print('x is not less than 5')
x = [1,2,3]
for num in x:
#if we put comment afte... | true |
96f4c4be86ed6e56acf3864c6131dfda9f33e5c1 | Jitender214/Python_basic_examples | /02-Python Statements/02-for Loops.py | 956 | 4.375 | 4 | # we use for loop to iterate the elements from the object
#syntax:
#my_iterate = [1,2,3]
#for itr_name in my_iterate:
#print(itr_name)
mylist = [2,4,5,7,9,10]
for num_list in mylist:
print(num_list)
for num in mylist:
if num % 2 == 0:
print(f'number is even: {num}')
else:
print(f'number i... | false |
c9ffaee4d2e9fc627f2586c709ab3ee3e007f8c0 | Jitender214/Python_basic_examples | /00-Python Object and Data Structure Basics/04-Lists.py | 1,098 | 4.125 | 4 | my_list = [1,2,3,4,5]
print(my_list)
my_list = ['string',100,13.5]
print(my_list)
print(type(my_list))
print(len(my_list))#length of list
my_list = ['one','two','three','four']
print(my_list[0])
print(my_list[1:]) #slicing using index
print(my_list[-2:])#reverse slicing
another_list = ['five','six']
new_list = my_li... | true |
8d6570ca6f135bcf1fa8caf94c374e4f2efbd4d7 | longmen2019/Challenges- | /Euler_Project_Problem_4.py | 736 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 8 21:22:28 2021
@author: men_l"""
"""A palindromic number reads the same both ways. The largest plindrome made from the product of two 2-digit numbers is
9009 = 91 x 99.
Find the largest palindrome made from the product of two 3-digit numbers"""
def is_pal... | true |
8eff7d0e679b2c30ac2f704e9480ff346dd0883f | Lomilpda/Lab_Python | /first_lab/1-21.py | 783 | 4.21875 | 4 | """
21. Напишіть програму, яка створить стрічку в якій будуть записані
другі символи всіх слів з стрічки silly.
"""
silly = "newly formed bland ideas are inexpressible in an infuriating way"
silly = silly.split() # создаем из строки список, разделяя по пробелу
new_str = ''
for word in silly: # перебор всех слов в спи... | false |
608a20a4d01b96b04db2f8cdccea6f9a73e078ad | rockchar/OOP_PYTHON | /PythonRegularExpressions.py | 2,146 | 4.5625 | 5 | #here we will discuss the regular expresssions in python
#import the regular expression module
import re
pattern = "phone"
text = "the agents phone number is 400-500-600"
print(pattern in text)
#now lets search the pattern using regular expressions
print(re.search(pattern,text))
#lets assign a match object
match =... | true |
01c3d559c8a51349938c70400e6b996d417861d6 | rockchar/OOP_PYTHON | /ClassInheritance.py | 637 | 4.40625 | 4 | ''' here we will discuss class inheritance '''
class Animal():
def __init__(self,type,name):
print("animal created")
self.type=type
self.name=name
def who_am_i(self):
print("I am an animal")
def eat(self):
print("I am an animal eating")
class Dog(Animal):
def ... | false |
df1dad41db36bfa1940c8a43d6a278b8e4a30b7f | kwmoy/py-portfolio | /pre_2022/sort_array.py | 748 | 4.40625 | 4 | def sort_array(arr):
"""This function manually sorts an input array from ascending to descending order."""
sorted_arr = []
# Start off our list
sorted_arr.append(arr.pop())
print(sorted_arr)
for number in arr:
# With input arr, we compare it to each number currently in the list.
for i in ra... | true |
d1933edbf3ef92526b5c2ba35c36e6bbf8e012b7 | madsaken/forritunh19 | /move.py | 1,595 | 4.34375 | 4 | Left = 1
Right = 10
def moverFunction(x):
#This function makes a new board.
newLocation = x
newX_left = newLocation-Left
newX_right = Right-newLocation
newBoard = "x"*newX_left + "o" + "x"*newX_right
print(newBoard)
ans = 'l'
placement = int(input("Input a position between 1 and 10:... | true |
04b90cc05f322dd3ef3527877f24d64d196ebced | madsaken/forritunh19 | /int_seq.py | 910 | 4.4375 | 4 | #Variables that will store data from the user.
count = 0
summary = 0
even = 0
odd = 0
largest = 0
current = 1 #Note that 'current' must start with the value 1 otherwise the loop will never start.
#A loop that will end when the user types in either 0 or less than zero.
while current > 0:
current = int(input('Enter ... | true |
0564c1eda7c4e05af33f529322b5f51dec67cb0f | rembold-cs151-master/Lab_SetSieve | /Lab20.py | 1,415 | 4.1875 | 4 | """
Investigating the number of words in the english language that can
be typed using only a subset of modern keyboard layouts.
"""
from english import ENGLISH_WORDS
import time
QWERTY_TOP = "qwertyuiop"
QWERTY_HOME = "asdfghjkl"
QWERTY_BOT = "zxcvbmn"
DVORAK_TOP = "pyfgcrl"
DVORAK_HOME = "aoeuidhtns"
DVORAK_BOT = "... | true |
cb47d28fd0ef6dcedf87dd10543bb4906cd6acad | PascalUlor/code-challenges | /python/insertion-sort.py | 930 | 4.21875 | 4 | """
mark first element as sorted
loop through unsorted array from index 1 to len(array)
'extract' the element X at index i as currentValue
set j = i - 1 (which is the last Sorted Index)
while index of sorted array j >= 0 and element of sorted array arr[j] > currentValue
move sorted element to the ri... | true |
072a24baab732c2ad8cf526ad0432f958ab221ad | joshua9889/ENR120 | /09.11.17/tempConv.py | 209 | 4.21875 | 4 | # A Celsius to Fahrenheit. conver
print "Convert Celsius to Fahrenheit."
degreeC = input("Please input celsius: ")
degreeF = degreeC*9./5. +32 # Calculate Fahrenheit.
print 'Fahrenheit value: ' + str(degreeF)
| true |
331390dde109a4b9779b31522e4adcb520b908a2 | ticotheps/practice_problems | /code_signal/arcade/smooth_sailing/common_character_count/common_character_count.py | 950 | 4.21875 | 4 | """
****** UNDERSTAND Phase ******
Given two strings, find the number of common characters between them.
- Example:
- Inputs: "aabcc", "adcaa" (2; string data type; "s1" & "s2")
- Outputs: 3 (1; integer data type; "num_common_chars")
"""
def commonCharacterCount(s1, s2):
s1_dict = {}
s1_list = [x for ... | false |
cde036f6381893e9cd8cb5dde13155aa92194870 | ticotheps/practice_problems | /edabit/medium/shared_letters/shared_letters.py | 2,306 | 4.34375 | 4 | """
LETTERS SHARED BETWEEN TWO WORDS
Create a function that returns the number of characters shared between two
words.
Examples:
- get_shared_letters('apple', 'meaty') -> 2
- get_shared_letters('fan', 'forsook') -> 1
- get_shared_letters('spout', 'shout') -> 4
"""
"""
PHASE I - UNDERSTAND THE PROBLEM
Ob... | true |
19dedc6f1b9082fda0afe546aa7dbd1cab0ba384 | ticotheps/practice_problems | /edabit/medium/a_circle_two_squares/a_circle_two_squares.py | 1,732 | 4.375 | 4 | """
A CIRCLE AND TWO SQUARES
Imagine a circle and two squares: a smaller and a bigger one. For the smaller
one, the circle is a circumcircle and for the bigger one, an incircle.
Objective:
- Create a function that takes in an integer (radius of the circle) and returns
the square area of the square inside the... | true |
d0dff41d253ddeeecd09a2dc68948c5754c080c7 | ticotheps/practice_problems | /edabit/hard/alphanumeric_restriction/alphanumeric_restriction.py | 2,706 | 4.375 | 4 | """
ALPHANUMERIC RESTRICTION
Create a function that returns True if the given string has any of the
following:
- Only letters and no numbers.
- Only numbers and no letters.
If a string has both numbers and letters, or contains characters which don't fit
into any category, return False.
Examples:
- a... | true |
46d77997d86c15ac35859e8639710997dc6b1d63 | ticotheps/practice_problems | /edabit/easy/time_for_milk_and_cookies/time_for_milk_and_cookies.py | 2,939 | 4.6875 | 5 | """
Is it Time for Milk and Cookies?
Christmas Eve is almost upon us, so naturally we need to prepare some milk and
cookies for Santa! Create a function that accepts a Date object and returns True
if it's Christmas Eve (December 24th) and False otherwise.
Objective:
- Write an algorithm that takes in a single in... | true |
aeeafce1e20575ffba77b35953aec7f1c4482267 | ticotheps/practice_problems | /algo_expert/hard/reverse_linked_list/reverse_linked_list.py | 1,639 | 4.28125 | 4 | """
REVERSE LINKED LIST
Write a function that takes in the 'head' of a singly linked list, reverses the
list in place (i.e. - doesn't create a brand new list), and returns its new
'head'.
Each 'LinkedList' node has an integer, 'value', as well as a 'next' node
pointing to the next node in the list or to 'None'/'null'... | true |
8af1196d576fdc5bac1efa1bf73520f4ebdd60c6 | ramnathpatro/OOPs | /Regular_Expression.py | 2,153 | 4.21875 | 4 |
"""
******************************************************************************
* Purpose: Regular Expression
*
* @author: Ramnath Patro
* @version: 1.0
* @since: 26-3-2019
*
******************************************************************************
"""
import re
def regex(string):
constant1 = 0
wh... | false |
f433fda6480fe3cac5afcb580f10457da4a1d65f | Nchia-Emmanuela/Average_Height | /Average height.py | 587 | 4.15625 | 4 | Student_Height = input("Enter a list of students heights :\n").split()
print(Student_Height)
# calculating the sum of the heights
total_of_height = 0
for height in Student_Height:
total_of_height += int(height)
print(f"total heights = {total_of_height}")
# calculating the number students
number_of_students = 0
fo... | true |
a8d3aab468d7495659c15bfe709d93d9a437a1f3 | thisisvarma/python3 | /blog_learning/operators/membershipOperator.py | 475 | 4.1875 | 4 | print("\n ****** membership Operator examples **** ")
print('''
in --> True if value or variable presents in list, string,tuple or dict
not in --> True if value or variable not presents in list, string, tuple or dict
''')
x=input("enter string what ever you like : ")
y="aeiou"
print("'H' in x is : ",'H' in x)
... | true |
321d8e8034504d725070df509734088103708b85 | Platypudding/Rando-stuff | /Gram-Ounce Calculator.py | 940 | 4.1875 | 4 | #Converts grams into ounces or vice versa
def convert_gram(gram):
ounce = gram / 28.35
print("Grams:", gram, "\n" + "Ounces:", ounce)
def convert_ounce(ounce):
gram = ounce * 28.35
print("Ounces:", ounce, "\n" + "Grams:", gram)
gramounce = input("Input g to convert from grams, o to convert from ounce... | false |
d53eff888bd61bdf36303c232a8300f871de7654 | NicciSheets/python_battleship_attempt | /ship.py | 1,690 | 4.25 | 4 |
SHIP_INFO = {
"Battleship": 2,
"Cruiser" : 3,
"Submarine" : 4,
"Destroyer" : 5
}
SHIP_DAMAGE = {
"Battleship": 0,
"Cruiser" : 0,
"Submarine" : 0,
"Destroyer" : 0
}
# returns a list of all the keys in the dictionary, which you can then use to return a certain ship name from the SHIP_INFO dictionary ... | true |
6d700b6b5f6ca80d260cbff864459cf49ca69cb1 | keen-s/alx-higher_level_programming | /0x06-python-classes/101-square.py | 2,387 | 4.5625 | 5 | #!/usr/bin/python3
"""Write a class Square that defines a square by:
(based on 5-square.py)
"""
class Square:
"""Square class with a private attribute -
size.
"""
def __init__(self, size=0, position=(0, 0)):
"""Initializes the size variable as a private
instance artribute
"""
... | true |
84059ceca8bf9da2d3a7b82f62501c53c99e215d | laurennpollock/comp110-21f-workspace | /exercises/ex01/numeric_operators.py | 940 | 4.1875 | 4 | """Practicing numberic operators."""
__author__ = "730392344"
left_hand_side: str = input("Left-hand side: ")
right_hand_side: str = input("Right-hand side: ")
int(str(left_hand_side))
int(str(left_hand_side))
exponentiation = int(left_hand_side) ** int(right_hand_side)
division = int(left_hand_side) / int(right_hand_... | false |
9835ccfe8458dbffd844eedc273984aed6025e9c | Knorra416/daily_coding_challenge | /July_2019/20190722.py | 856 | 4.375 | 4 | # There exists a staircase with N steps,
# and you can climb up either 1 or 2 steps at a time.
# Given N, write a function that returns the number of unique ways you can climb the staircase.
# The order of the steps matters.
# For example, if N is 4, then there are 5 unique ways:
# 1, 1, 1, 1
# 2, 1, 1
# 1, 2, 1
# 1,... | true |
6718a6008d1870df1b20f67a1dd3b948375c6885 | king-Daniyal/assignment-1-py | /do.py | 550 | 4.15625 | 4 | #(print) this is the feature which prints the word given ahead of it
print("hi, i am a text") # this is the function the word inside of the "" will come as output
# lets try numbers
print(2020, "was bad") # this works with numbers and text but the "" shall not be included with the number because it is of no use
pr... | true |
73db52476f91e787f5441b81ac790ea4fe0916d0 | NickCorneau/PythonAlgorithms | /deep_reverse.py | 693 | 4.375 | 4 | # Procedure, deep_reverse, that takes as input a list,
# and returns a new list that is the deep reverse of the input list.
# This means it reverses all the elements in the list, and if any
# of those elements are lists themselves, reverses all the elements
# in the inner list, all the way down.
# Note: The proc... | true |
7cf8abf975c0d5317999a2daec0bb0fa4e6cbb8d | AhsanVirani/python_basics | /Basic/Classes/classes_instances_1.py | 1,042 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri May 8 06:57:49 2020
@author: asan
"""
# Creating and instanciating classes
# Tut 1
class Employee:
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '@company.... | true |
70d8e31b35c73a792f4c6c8160db16f8019bdb7f | kirtanlab/pure_mess | /MODULE15/15.3/main.py | 1,754 | 4.125 | 4 | #Program 1
print("\n**\n ** \nProgram No: 0 : Program to find sum of square of first n natural numbers\n **\n**")
def squaresum(n) :
sm = 0
for i in range(1, n+1) :
sm = sm + (i * i)
return sm
n = int(input("\nEnter the Input: "))
print(squaresum(n))
#Program 2
print("\n**\n ** \nProgram No: 1 : program to sp... | true |
5abae9ce6ec3065280f6799fd1cab57c79a2d629 | nickruta/DataStructuresAlgorithmsPython | /selection_sort.py | 1,638 | 4.21875 | 4 | """ Using the PEP 8 Style Guide for Python Code:
https://www.python.org/dev/peps/pep-0008/ and python linters """
def selection_sort(a_list):
"""The selection sort improves on the bubble sort by making only one
exchange for every pass through the list. In order to do this, a selection
sort looks for the l... | true |
8d715b5244502b202be141f5190a8b8032aef202 | Leonardo-Alejandro-Juarez-Montes/CLUB_PRO_2020 | /EjercicioPOO_21_03_20.py | 658 | 4.15625 | 4 | print("EJERCICIO NUMERO 1")
n= 1 + int(input("Introduce el numero de filas weon: "))
for y in range(n):
print("* "*y)
print(" ")
print ("EJERCICIO NUMERO 2")
l=int(input("Introduce el numero de filas pd:te quiero :3: "))
for y in range (l,0,-1):
print("* "*y)
print(" ")
print("EJERCICIO NUMERO 3")
m= 1 + int... | false |
a3620b4b22b61a4e05386afedb3e42ebab83fc65 | TimTomApplesauce/CIS1415 | /PigLatin.py | 389 | 4.1875 | 4 | def to_pig_latin(usr_str):
split_str = usr_str.split(' ')
for word in split_str:
first_letter = word[0]
word = word[1:]
print(word + first_letter + 'ay', end =' ')
print()
return
user_string = input("Please enter a sentance to convert to Pig Latin:\n")
pr... | false |
abe3713a43c57d6564c638ceacbab2c2ce308a0a | meermm/test | /композиция.py | 908 | 4.1875 | 4 | '''
По композиции один из классов состоит из одного или нескольких экземпляров других классов.
Другими словами, один класс является контейнером, а другой класс - содержимым, и если вы удалите объект-контейнер, все его объекты содержимого также будут удалены.
'''
class Salary:
def __init__(self, pay):
self... | false |
3ac1299605142a62c6c7c9e4df09020fccb95c75 | nidhi2802/18IT033_IT374_PythonProgramming_Practical_Tasks | /Week_4/Assignment2/4.py | 731 | 4.15625 | 4 | from collections import Counter
list1 = [1, 2, 3, 2, 2, 2, 5, 6]
counter = 0
num = list1[0]
for i in list1:
current = list1.count(i)
if(current>counter):
counter=current
num=i
print("Most common element in list: ",num)
print("Count of element in list: ", counter)
tuples = ("apple", 2, 3,"apple","apple", "a... | false |
59e4a6bab2feb777b3bec0b1ece5c6bccf1c2433 | nidhi2802/18IT033_IT374_PythonProgramming_Practical_Tasks | /Week_1/Practical7.py | 501 | 4.21875 | 4 | choice = int(input("To covert rupees to dollar- enter 1 and to convert dollar to rupees - enter 2 "))
if(choice==1):
amt_rupees = float(input("Enter amount in rupees: "))
cnv_dollar = amt_rupees/70
print(amt_rupees, "rupees is equal to ", cnv_dollar, "dollar/s")
elif(choice==2):
amt_dollar = float(input... | true |
1ca2340361d2623294f76a41dc5181d62b5d17c9 | melandres8/holbertonschool-higher_level_programming | /0x06-python-classes/3-square.py | 733 | 4.375 | 4 | #!/usr/bin/python3
"""Square class"""
class Square():
"""Validating if size is an instance
and if is greater and equal to 0
Attributes:
attr1 (int): size is a main attr of a square
"""
def __init__(self, size=0):
"""isinstance function checks if
the object is an instance or... | true |
9a956a51c89fe66441040b2db5ab0b5dd3bf53fe | melandres8/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/5-text_indentation.py | 758 | 4.1875 | 4 | #!/usr/bin/python3
"""
Handling new lines, some special characters
and tabs function.
"""
def text_indentation(text):
"""
Print a text with two new line at the end
after each of these characters '.'':''?'
Args:
text: (string) Given text
Raises:
Type... | true |
9923d3414c6e87199ffca081c646b80967cac9d8 | melandres8/holbertonschool-higher_level_programming | /0x0A-python-inheritance/10-square.py | 445 | 4.1875 | 4 | #!/usr/bin/python3
""" Applying inheritance and super() method
"""
Rectangle = __import__('9-rectangle').Rectangle
class Square(Rectangle):
""" Defining constructor
"""
def __init__(self, size):
"""Constructor method
Args:
size: square size
"""
self.int... | true |
e89d2a1bb8619dd97424585534da78618f6c4bf7 | ml-nic/Algorithms | /src/typical_string_processing_functions.py | 1,007 | 4.125 | 4 | def is_palindrome(string: str) -> bool:
"""
Is the string a palindrome?
:param string:
:return:
"""
length = len(string)
for i in range(int(length / 2)):
if string[i] != string[-i - 1]:
return False
return True
assert is_palindrome("HelloolleH") is True
assert is_pa... | true |
422c8cd0e2bcc3bce513c2a4b412d775b328e138 | massivetarget/mtar_a | /capping.py | 201 | 4.1875 | 4 | # this is python file for capitalisation of give string
nm = str(input("please Enter word to capitilise it: "))
print(nm.capitalize())
# this will do the real work
print("adding 23 to 34", 23 + 34)
| true |
776570db6172e6379b4dc91afd491c5b05871515 | jsourabh1/Striver-s_sheet_Solution | /Day-13_Stack/question3_queue_using_stack.py | 562 | 4.125 | 4 | def Push(x,stack1,stack2):
'''
x: value to push
stack1: list
stack2: list
'''
#code here
stack1.append(x)
#Function to pop an element from queue by using 2 stacks.
def Pop(stack1,stack2):
'''
stack1: list
stack2: list
'''
#code here
if stack1:
s... | true |
1ba233bf6d91df731ef3347bfe864e6b353f2be8 | elinaavintisa/Python_2variants | /2uzdevums.py | 900 | 4.1875 | 4 | """
Funkcija akrs akceptē trīs argumentus - skaiļus viens, divi un trīs,
aprēķina to kvadrātu starpību un atgriež to.
Pārbaudiet funkcijas darbību ar dažādiem argumentiem,
parādot skaitli ar četriem simboliem aiz komata.
Argumenti:
viens {int vai float} -- pirmais skaitlis
... | false |
f5d59978eb41fa768c32f83a8270359687f00c85 | green-fox-academy/ZaitzeV16 | /python_solutions/week-02/day-2/data_structures/telephone_book.py | 1,155 | 4.53125 | 5 | """
# Telephone book
We are going to represent our contacts in a map where the keys are going to be
strings and the values are going to be strings as well.
- Create a map with the following key-value pairs.
| Name (key) | Phone number (value) |
| :------------------ | :------------------- |
| William ... | false |
394529d04bd7be33bf77db2a9c9eb43d0152dea3 | green-fox-academy/ZaitzeV16 | /python_solutions/week-01/day-4/average_of_input.py | 340 | 4.15625 | 4 | # Write a program that asks for 5 integers in a row,
# then it should print the sum and the average of these numbers like:
#
# Sum: 22, Average: 4.4
_sum = 0
number_of_inputs = 5
for i in range(number_of_inputs):
_sum += int(input("number {}: ".format(i + 1)))
print("sum: {}, average: {:.1f}".format(_sum, _sum /... | true |
6cef60c67ed6680f4649a9aa9223ad38793d6f72 | green-fox-academy/ZaitzeV16 | /python_solutions/week-02/day-1/functions/greet.py | 356 | 4.28125 | 4 | # - Create a string variable named `al` and assign the value `Green Fox` to it
# - Create a function called `greet` that greets it's input parameter
# - Greeting is printing e.g. `Greetings dear, Green Fox`
# - Greet `al`
al = "Green Fox"
def greet(name: str):
print("Greetings dear, {}".format(name))
if __... | true |
d591cbf39e6a63369d5c674941a8994c8d87ffd3 | vincentt117/coding_challenge | /lc_merge_sorted_array.py | 1,577 | 4.125 | 4 | # Merge Sorted Array
# https://leetcode.com/explore/interview/card/microsoft/47/sorting-and-searching/258/
# Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
# Note:
# The number of elements initialized in nums1 and nums2 are m and n respectively.
# You may assume that ... | true |
2d8988baedd00b46718268d1b13aaa05a908dd44 | vincentt117/coding_challenge | /lc_power_of_three.py | 659 | 4.1875 | 4 | # 326. Power of Three
# https://leetcode.com/problems/power-of-three/description/
# 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: ... | true |
e4216a7f86a3d561a1d68240942799919fcb3e5b | MarketaR0/up_ii_calculator | /src/Calculator.py | 2,774 | 4.15625 | 4 | from src.FunctionManager import FunctionManager
from src.BasicFunctions import add, subtract, multiply, divide
# Runs the calculator.
def calculate():
func_manager = FunctionManager()
# Allows user to choose operation.
func_manager.show_functions()
user_choice = int_input(len(func_manager.functions))... | true |
000f23ea08180197ae4e666159a3100d689b1e9e | NicolaBenigni/PythonExam | /Simulation.py | 2,517 | 4.125 | 4 | # Import necessary libraries
from matplotlib import pyplot as plt
from random import randint
# Import the file "Roulette" where roulette and craps games are defined
import Roulette
### This file tests whether roulette and craps game works. Moreover, it simulates awards and profit distribution
### for 1000 crap games
... | true |
325628121e6010bcf26bb007217b2d9d953b4b4f | jonathadd27/AritmatikaSederhanaPert1 | /AritmatikaSederhana.py | 963 | 4.1875 | 4 | #Program Hello World !!
print("Hello World")
print("Saya sedang belajar bahasa pemrograman Python")
print("")
print("")
print("Berikut program latihan Aritmatika sederhana dengan inline variable Python")
print("")
print("")
#Program Aritmatika Dasar
bil1 = 25
bil2 = 50
penjumlahan = bil1 + bil2
pengurangan ... | false |
a3258932dc63aba4e3991745592c933e53fd444e | sc1f/algos | /sorting.py | 615 | 4.1875 | 4 | def mergesort(nums):
if len(nums) <= 1:
# already sorted
return
# split into 2
mid = len(nums) // 2
left = nums[:mid]
right = nums[mid:]
# recursively split
mergesort(left)
mergesort(right)
# start merging
merge(left, right, nums)
return nums
def merge(left, right, nums):
index = 0
while left and ... | true |
d388be010509b5f4afb69817d29edc9cb94f62ad | csulva/Rock_Paper_Scissors_Game | /rock_paper_scissors_game.py | 2,174 | 4.25 | 4 | import random
# take in a number 0-2 from the user that represents their hand
user_hand = input('\nRock = 0\nPaper = 1\nScissors = 2\nChoose a number from 0-2: \n')
def get_hand(number):
if number == 0:
return 'rock'
elif number == 1:
return 'paper'
elif number == 2:
return 'scisso... | true |
a0d5e506fda1eb6516c6427d0a246bf8256c75d9 | Skelmis/Traffic-Management-Simulator | /cars.py | 1,094 | 4.3125 | 4 | # A class which stores information about a specific car
class Car:
name = None
# Which road did the car enter from
enter = None
# Which direction would the car like to go in
direction = None
def __init__(self, name, enter, direction):
self.name = name
self.enter = enter
... | true |
92439e7c1286c56a4a7335f42c496b5e97a49653 | efuen0077/Election_Analysis | /Python_prac.py | 2,450 | 4.21875 | 4 | #counties = ["Arapahoe","Denver","Jefferson"]
#if counties[1] == 'Denver':
#print(counties[1])
#temperature = int(input("What is the temperature outside? "))
#if temperature > 80:
# print("Turn on the AC.")
#else:
# print("Open the windows.")
#What is the score?
#score = int(input("What is your test score?... | true |
54e250c7c93908773fd293b84468594d9706eb5d | incesubaris/Numerical | /secant.py | 1,330 | 4.1875 | 4 | import matplotlib.pyplot as plt
import numpy as np
## Defining Function
def f(x):
return x**3 - 5*x - 8
##Secant Method Algorithm
def secant(x0, x1, error, xson, yson):
x2 = x0 - (x0-x1) * f(x0) / (f(x0)-f(x1))
print('\n--- SECANT METHOD ---\n')
iteration = 1
while abs(f(x2)) > error:
if ... | true |
4cfefb42c88250aa58e56356cd9489a9eca915f6 | ppicavez/PythonMLBootcampD00 | /ex09/plot.py | 1,399 | 4.15625 | 4 | import matplotlib.pyplot as plt
import numpy as np
def cost_(y, y_hat):
"""Computes the mean squared error of two non-empty numpy.ndarray,
without any for loop. The
two arrays must have the same dimensions.
Args:
y: has to be an numpy.ndarray, a vector.
y_hat: has to be an numpy.ndarray, a vec... | true |
7a278079bd6b7ebd4dbb79011fc0f3bb1a77dfe5 | vinagrace-sadia/python-mini-projects | /Hangman/hangman.py | 1,330 | 4.125 | 4 | import time
import random
def main():
player = input('What\'s your name? ')
print('Hello,', player + '.', 'Time to play Hangman!')
time.sleep(1)
print('Start guessing . . .')
time.sleep(0.5)
# Lists of possible words to guess
words = [
'bacon',
'grass',
'flowers... | true |
2c602e7c8e6f9862eda00e14c9959c2cb9d59336 | FelipeDreissig/Prog-em-Py---CursoEmVideo | /Mundo 1/Ex006 - operacoes.py | 216 | 4.125 | 4 | num = int(input('Digite um número inteiro: '))
dobro = num*2
triplo = num*3
raiz = num**(1/2)
print('O dobro do número é {}, o triplo do número é {} e a raiz do número é {:.2f};'.format(dobro, triplo, raiz))
| false |
fe74281880b4219344591d6f7e8b1dc974969565 | mattthewong/cs_5_green | /hw10/Ant.py | 2,671 | 4.6875 | 5 | from Vector import *
import random
import turtle
class Ant:
def __init__(self, position):
'''This is the "constructor" for the class. The user specifies a position of the ant
which is a Vector. The ant keeps that vector as its position. In addition, the
ant chooses a random color for its fo... | true |
0f6ba572e53dc34067241b53aa7d65c72f4e1462 | Mauricio1xtra/python | /basic_revisions2.py | 2,903 | 4.125 | 4 | """
Formatando valores com modificadores - AUlA 5
:s - Texto (strings)
:d - Inteiro (int)
:f - Números de ponto flutuante (float)
:.(NÚMERO)f - Quantidade de casas decimais (float)
:CARACTERE) (> ou < ou ^) (QUANTIDADE) (TIPO - s, d ou f)
> - Esquerda
< - Direita
^ - Centro
"""
"""
num_1 = 1
print(f"{num_1:0>10}")
... | false |
f74423128c8fcacbf42426d5a6d8061ad747d706 | lyubomirShoylev/pythonBook | /Chapter04/ex08_herosInventory2.py | 1,292 | 4.1875 | 4 | # Hero's Inventory 2.0
# Demonstrates tuples
# create a tuple with some items and display with a for loop
inventory = ("sword",
"armor",
"shield",
"healing potion")
print("\nYour items:")
for item in inventory:
print(item)
input("\nPress the enter key to exit.")
# get the l... | true |
9eaf4fbd375f2f10554b93b64cddd7f6f0e8d334 | lyubomirShoylev/pythonBook | /Chapter06/ch02_guessMyNumberModified.py | 1,848 | 4.21875 | 4 | # Guess My Number
# **MODIFIED**
#
# The computer picks a random number between 1 and 100
# The player tries to guess it and the computer lets
# the player know if the guess is too high, too low
# or right on the money. In this version of the game
# the player has limited amount of turns.
#
# MODIFICATION:
# Reusing t... | true |
e550fd073b917dafc66ff71ee3455053617cd920 | lyubomirShoylev/pythonBook | /Chapter04/ex05_noVowels.py | 445 | 4.53125 | 5 | # No Vowels
# Demonstrates creating new strings with a for loop
message = input("Enter a message: ")
newMessage = ""
VOWELS = "aeiou"
print()
for letter in message:
# letter.lower() assures it could be from VOWELS
if letter.lower() not in VOWELS:
newMessage += letter
print("A new string has be... | true |
bcb1b9acfea3e0eb1714788eee2c42d9ddb9d694 | LeeroyC710/pj | /Desktop/py/YuyoITGradingSystem2.py | 2,203 | 4.1875 | 4 | def grading(num): #Grades the grades
if num >=99:
return "U. No way you could have gotten that without cheating. (A****)"
elif num >=94:
return "S-Class Hero ranking. All might would be proud."
elif num >= 87:
return "A**. Either a prodigy or a cheater."
elif num >= 79:
r... | true |
124cee9a7367047f0fed2037b3997df4cfaf9399 | Kamil-Ru/Functions_and_Methods_Homework | /Homework_7.py | 1,384 | 4.46875 | 4 | # Hard:
# Write a Python function to check whether a string is pangram or not. (Assume the string passed in does not have any punctuation)
# Note : Pangrams are words or sentences containing every letter of the alphabet at least once.
# For example : "The quick brown fox jumps over the lazy dog"
# Hint: You may want t... | true |
95b5d44432371958fb85efcb606729590797041d | anuradhaschougale18/PythonFiles | /21st day-BinarySearchTreee.py | 1,346 | 4.28125 | 4 | '''
Task
The height of a binary search tree is the number of edges between the
tree's root and its furthest leaf. You are given a pointer, root,
pointing to the root of a binary search tree.
Complete the getHeight function provided in your editor so that it returns the height of the binary search tree.
'''
cla... | true |
7ce0712c715ebc1a5eadac7d45520f3bd87bd947 | jalani2727/HackerRank | /Counting_Valleys.py | 770 | 4.1875 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the countingValleys function below.
# reverse engineer
# Every time you return to sea level (n) after n has decreased, one valley has been travelled through
def countingValleys(n, s):
valley_counter=0
compare_to = n
for l... | true |
4abdbbab21357a288a4cd7f92d09393e9b15f08e | zdravkob98/Python-Advanced-September-2020 | /Functions Advanced - Exercise/04. Negative vs Positive.py | 421 | 4.21875 | 4 | def find_biggest(numbers):
positive = sum(filter(lambda x: x >= 0, numbers))
negative = sum(filter(lambda x: x <= 0, numbers))
print(negative)
print(positive)
if abs(positive) > abs(negative):
print("The positives are stronger than the negatives")
else:
print("The negatives ar... | true |
01165803a5ece1682e91f49d604a47f39bdba27a | jerryeml/Python_Class | /Class_List01.py | 769 | 4.125 | 4 | a_tuple = (12,3,5,15,6)
b_tuple = 2,4,6,7,8
a_list =[12,3,67,7,82]
a_list.append(0) #添加
a_list.insert(2,11) #添加在指定位置
a_list.remove(12) #只會刪除碰到第一個12
for i in range(len(a_list)): #依照list長度分別輸出第幾個元素的value
print(i,a_list[i])
print('Last element:',a_list[-1])#從最後一個開始數
#print(a_list)
print('first to three element:',a_list... | false |
56ed53478852a695eaab1d6b41d5c867fa48909e | LoyalSkm/Home_work_2_base | /hw2_task_3.py | 1,866 | 4.25 | 4 | print(''' 3. "Нарисовать" в консоли прямоугольный треугольник из символов "*",
пользователь задаёт высоту и ширину(в количестве элементов).
''')
print('''Задавай какую хочешь высоту, но триугольник будит пропорциональным только если высота<ширины в 2 раза
''')
import numpy #позволит мне сделать список из е целых чис... | false |
4e070270f812ddd28e7a7d7453cd10397b16631c | Janarbek11/ifElse | /ifelse.py | 832 | 4.34375 | 4 | # Написать программу которая проверит число на несколько критериев:
# Чётное ли число?
# Делится ли число на 3 без остатка?
# Если возвести его в квадрат, больше ли оно 1000?
с = int(input("Введите число: "))
if с % 2 == 0:
print ("Четное число!")
else:
print("Нечетное число!")
o = int(input("Введите число: ... | false |
9e47611cfa3d80554715e98da0f9f1c08b8331ff | tboydv1/project_python | /Python_book_exercises/chapter6/exercise_11/online_purchase.py | 1,288 | 4.25 | 4 | """Suppose you are purchasing something online on the Internet. At the website, you get
a 10% discount if you are a member. Additionally, you are also getting a discount of
5% on the item because its Father’s Day.
Write a function that takes as input the cost of the item that you are purchasing and
a Boolean variable i... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.