blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
b87cafe0bec26f966a8c027f0aa4e3311be3a18f | chris4540/algorithm_exercise | /basic/arr_search/rotated_arr/simple_approach.py | 1,736 | 4.3125 | 4 | """
https://www.geeksforgeeks.org/search-an-element-in-a-sorted-and-pivoted-array/
1) Find out pivot point and divide the array in two
sub-arrays. (pivot = 2) /*Index of 5*/
2) Now call binary search for one of the two sub-arrays.
(a) If element is greater than 0th element then
search in l... | true |
4a3368612d71c0d50ea714669551caf6922696ba | Sakshipandey891/sakpan | /vote.py | 285 | 4.3125 | 4 | #to take age as input & print whether you are eligible or not to vote?
age = int(input("enter the age:"))
if age==18:
print("you are eligible for voting")
elif age>=18:
print("you are eligible for voting")
else:
print("you are not eligible for voting")
| true |
d4fc59edb7222118899818e3a6bfb3e84d57797e | MikhaelMIEM/NC_Devops_school | /seminar1/1.py | 574 | 4.21875 | 4 | def reverse_int(value):
reversed_int = 0
while value:
reversed_int = reversed_int*10 + value%10
value = value // 10
return reversed_int
def is_palindrome(value):
if value == reverse_int(value) and value%10 != 0:
return 'Yes'
else:
return 'No'
if __name__ == '__main_... | true |
b4b5b23dff3ef54135b31a52c397ab7bb347c298 | ashwani99/ds-algo-python | /sorting/merge_sort.py | 1,092 | 4.34375 | 4 | def merge_sort(arr):
l = len(arr)
return _merge_sort(arr, 0, l-1)
def _merge_sort(arr, start, end):
if start < end:
mid = (start+end)//2
_merge_sort(arr, start, mid)
_merge_sort(arr, mid+1, end)
merge(arr, start, mid, end)
return arr
def merge(arr, start, mid, end):
... | true |
8839d7b99405de758cab6ca4c4bd04718891c34c | ashwani99/ds-algo-python | /sorting/mergesort_inplace.py | 872 | 4.125 | 4 | def merge_sort(arr):
n = len(arr)
return _merge_sort(arr, 0, n-1)
def _merge_sort(arr, start, end):
if start < end:
mid = (start+end)//2
_merge_sort(arr, start, mid)
_merge_sort(arr, mid+1, end)
_merge(arr, start, mid, end)
return arr
def _merge(arr, start, mid, end):... | false |
7024125f920382245e33eae4f71d857d6b3f24b7 | shensleymit/HapticGlove | /Haptic Feedback Code/RunMe2.py | 1,725 | 4.375 | 4 | #################################################
# This asks the user which function they would #
# like to see, and loads that one. Ideally, #
# this won't be needed, and instead the choice #
# of function and the function will all be part #
# of one file. #
####################... | true |
9d272a9c8c1733568d01335040bc94a3bec2eb1c | aaronbushell1984/Python | /Day 1/Inputs.py | 1,596 | 4.3125 | 4 | # Python has Input, Output and Error Streams
# Python executes code sequentially - Line by Line
# Python style guide https://www.python.org/dev/peps/pep-0008/
# Add items to input stream with input - Print variable to output stream
name = input('enter your name: ')
print("Your name is", name)
# Input takes input and ... | true |
e24d82a2699dd90ef9551b67975fad2f77bd84a1 | bolducp/MIT-6.00SC-OpenCourseWare-Solutions | /Set 1/problem_2.py | 1,235 | 4.15625 | 4 | # Problem Set 1, Problem 2: Paying Off Debt in a Year
def get_outstanding_balance():
outstanding_balance = round(float(raw_input("Enter the outstanding balance on the credit card: ")), 2)
return outstanding_balance
def get_annual_interest_rate():
annual_interest_rate = round(float(raw_input("Enter the a... | true |
1564137dce26a1cb9dfdeab8552a7246d5ee491a | keerthiballa/PyPart5 | /palindrome.py | 447 | 4.34375 | 4 | def is_palindrome(value: str) -> bool:
"""
This function determines if a word or phrase is a palindrome
:param value: A string
:return: A boolean
"""
return value.replace(" ", "").lower() == value[::-1].replace(" ","").lower()
# ballakeerthi@zipcodes-MacBook-Pro-3 PyPart5 % python3 -m unittes... | false |
93fb4f4dab9e74fa1da1499eaa5f874cb2710e15 | danielblignaut/movie-trailer-application | /media.py | 1,185 | 4.15625 | 4 | class Movie() :
""" This class provides a way to store movie related data """
VALID_RESTRICTIONS = ["G", "PG", "PG-13", "R"]
def __init__(self, title, storyline, image_poster, youtube_trailer, rating, restriction) :
self.title = title
self.storyline = storyline
self.image_p... | true |
2134dde3da45d97bed30599df119beb184f15eaa | kwahome/python-escapade | /fun-with-problems/in_place_string_reverse.py | 1,685 | 4.3125 | 4 | # -*- coding: utf-8 -*-
#============================================================================================================================================
#
# Author: Kelvin Wahome
# Title: Reversing a string in-place
# Project: python-escapade
# Package: fun-with-problems
#
#
# Write a function to reverse ... | true |
9485759ef1b43b19642b35039ec0e5a0e5408f36 | raylyrainetwstd/MyRepo | /M07_Code_Fixed.py | 2,458 | 4.1875 | 4 | #this function takes an input from a user in response to a question
#if the user input is not a number, is_num doesn't accept the user input
def is_num(question):
while True:
try:
x = int(input(question))
break
except ValueError:
print("That is not a number")
... | true |
91cd8ab16e42d87249023a65929e46bc756e857a | raylyrainetwstd/MyRepo | /SDEV120_M02_Simple_Math.py | 452 | 4.1875 | 4 | #get two numbers from user
#add, subtract, multiply, and divide the two numbers together and save the values to variables
#print the results on one line
num1 = int(input("Please type a number: "))
num2 = int(input("Please type another number: "))
addition = str((num1 + num2))
subtraction = str((num1 - num2))
multiplic... | true |
3042a58e9d3deadaad9caa2291f2a672798b482d | cuichacha/MIT-6.00.1x | /Week 2: Simple Programs/4. Functions/Recursion on non-numerics-1.py | 621 | 4.25 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 15 20:54:15 2019
@author: Will
"""
def isIn(char, aStr):
'''
char: a single character
aStr: an alphabetized string
returns: True if char is in aStr; False otherwise
'''
if aStr=="":
return False
if char==aS... | true |
f1f4ca1185dda31236ba9bd5ceded47043312d59 | enireves/converter | /andbis.py | 462 | 4.25 | 4 | weather = input("What's the weather like? ")
temperature = input("What temperature is it? ")
if weather == "rainy" and temperature == "cold" :
print("Take an umbrella and a warm jacket.")
elif temperature == "warm":
print("Take an umbrella and a shirt.")
elif weather == "sunny" and temperature == "cold":
pr... | true |
083a2d404922c25ca29310ead58938ebcf613db7 | quangvinh86/python-projecteuler | /PE-010/summation_of_primes.py | 949 | 4.125 | 4 | """
Solution to Project Euler problem 10
@author: vinh.nguyenquang
@email: quangvinh19862003@gmail.com
"""
import math
UPPER_LIMIT = 2000000
def is_prime(number):
if number <= 1:
return False
elif number <= 3:
return True
elif not number % 2:
return False
max_range = int(ma... | true |
cc7bf998dc1b446c9bbe4b5f1455c5e62b7c8276 | FrankCardillo/practice | /2016/codewars/python_practice/digital_root.py | 577 | 4.21875 | 4 | # A digital root is the recursive sum of all the digits in a number.
# Given n, take the sum of the digits of n.
# If that value has two digits, continue reducing in this way until a single-digit number is produced.
# This is only applicable to the natural numbers.
def digital_root(n):
total = 0
stringified = ... | true |
b7fab26d44f16a123f15142f6aac5cd697abcf58 | fearlessfreap24/codingbatsolutions | /Logic-2/make_chocolate.py | 572 | 4.125 | 4 | def make_chocolate(small, big, goal):
# not enough bricks
if big * 5 + small < goal:
return -1
# not enough small bricks
goalmod = goal % 5
if goalmod > small:
return -1
# enough small bricks
if big < goal // 5:
return goal - (big * 5)
if big >= goal // 5:
... | true |
58724808401d4280a852997f06a00f4480d75aeb | Maidou0922/Maidou | /阶乘.py | 421 | 4.15625 | 4 | b=int(input("pls input number:"))
def fact(a):
result=1
if a < 0:
return("Error") # should be Error
elif a == 0 or a==1:
return(str(a))
while a > 1:
tmp=a*(a-1)
result=result*tmp
a -=2
return result #return after loop
print(fact(b))... | true |
73f05af982732d91004c84a6686e2116e2e1b705 | rinkeshsante/ExperimentsBackup | /Python learning-mosh/Python Files/learn_02.py | 1,123 | 4.15625 | 4 | # from the python mega course
# to run the entire code remove first ''' pair from code
# create text file named test.txt containg multiple lines
# file handling opening t& reading the file
'''
file = open("test.txt", "r")
content = file.readlines()
# file.read() for all content reading
# file.seek(0) to readjustng th... | true |
e4c11407f315d7ee14c92362ce290ac3665076cc | shanshanya123/test | /string.py | 588 | 4.15625 | 4 | str1="hello world "
str2="python hello world "
print("str1[0]:",str1[0])
print("str2[0:5]:",str2[0:5])
l=str1.__len__()
print("更新字符串:",str1+str2)
str3=str1+str2
print(str3)
print(str3.find(str2))
print(str3.count('h'))
print(str1.capitalize())
print(str1.center(50,'+'))
str = "字符串函数";
str_utf8 = str.enco... | false |
f09c699d0bf7d7486a1f0f881eee9f61686d6403 | axentom/tea458-coe332 | /homework02/generate_animals.py | 1,713 | 4.34375 | 4 | #!/usr/bin/env python3
import json
import random
import petname
import sys
"""
This Function picks a random head for Dr. Moreau's beast
"""
def make_head():
animals = ["snake", "bull", "lion", "raven", "bunny"]
head = animals[random.randint(0,4)]
return head
"""
This Function pulls two random animals fr... | true |
84db20f7bfcaa6dd31784c4b6b23739fdc1a249d | Arjun-Pinpoint/InfyTQ | /Programming Fundamentals using Python/Day 3/Assignment 22.py | 557 | 4.125 | 4 | '''
Write a Python program to generate the next 15 leap years starting from a given year. Populate the leap years into a list and display the list.
Also write the pytest test cases to test the program.
'''
#PF-Assgn-22
def find_leap_years(given_year):
list_of_leap_years=[]
count=0
while(count<15):
i... | true |
030f3b5229cd74842dd83ad861f3463d5e1681e6 | Arjun-Pinpoint/InfyTQ | /Programming Fundamentals using Python/Day 7/Assignment 47.py | 1,317 | 4.3125 | 4 | '''
Write a python function, encrypt_sentence() which accepts a message and encrypts it based on rules given below and returns the encrypted message.
Words at odd position -> Reverse It
Words at even position -> Rearrange the characters so that all consonants appear before the vowels and their order should not change
... | true |
8853b70819c16150e377d6c4a3654c1f36810c61 | Jit26k/HacktoberFestContribute | /Algorithms/Array/ReverseArray.py | 464 | 4.28125 | 4 | import Arrays
def reversingAnArray(start, end, myArray):
while(start < end):
myArray[start], myArray[end - 1] = myArray[end - 1], myArray[start]
start += 1
end -= 1
if __name__ == '__main__':
myArray = Arrays.Array(10)
myArray.insert(2, 2)
myArray.insert(1, 3)
myArray.inse... | false |
92f91f8292a0b48d2cb75c94955a0187327cb563 | jandirafviana/python-exercises | /my-python-files/aula06_desafio004.py | 2,986 | 4.1875 | 4 | n1 = int(input ('Digite um número: '))
n2 = int(input('Digite outro número: '))
s = n1 + n2
print('A soma entre {} e {} é {}'.format(n1, n2, s))
a = input('Digite algo: ')
print('O tipo primitivo desse valor é ', type(a))
n = input('Digite algo: ')
# Esse 'n' que estamos analisando é um objeto. Em n.isnumeric por exe... | false |
e4d361c009cd1a4cd312d9ebd6cf5cdd5019c954 | JRobinson28/CS50-PSets | /pset7/houses/import.py | 933 | 4.125 | 4 | from cs50 import SQL
from sys import argv, exit
from csv import reader, DictReader
db = SQL("sqlite:///students.db")
def main():
# Check command line args
if len(argv) != 2:
print("Exactly one commmand line argument must be entered")
exit(1)
# Open CSV file given by command line arg
... | true |
7157f20e3565c8ec175b673725fd2073ad8ae33e | fennieliang/week3 | /lesson_0212_regex.py | 1,082 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 25 14:40:57 2021
@author: fennieliang
"""
#useful links for regular expression
#http://python-learnnotebook.blogspot.com/2018/10/python-regular-expression.html
#https://www.tutorialspoint.com/python/python_reg_expressions.htm
#regular expression
i... | true |
d32aa6fa40b6dd5c0201e74f53d5bd581d6a3fe9 | josephcardillo/lpthw | /ex19.py | 1,825 | 4.375 | 4 | # creating a function called cheese_and_crackers that takes two arguments.
def cheese_and_crackers(cheese_count, boxes_of_crackers):
print(f"You have {cheese_count} cheeses.")
print(f"You have {boxes_of_crackers} boxes of crackers.")
print("Get a blanket.\n")
print("We can just give the function numbers di... | true |
7f97672e9989079ecf723aad9f71c57952440e35 | josephcardillo/lpthw | /ex15.py | 795 | 4.375 | 4 | # imports argv module from sys
from sys import argv
# the two argv arguments
script, filename = argv
# Using only input instead of argv
# filename = input("Enter the filename: ")
# Opens the filename you gave when executing the script
txt = open(filename)
# prints a line
print(f"Here's your file {filename}:")
# Th... | true |
09f1000e2058e584e8261d7dc437af52c3709674 | IslamOrtobaev/This_is_my_own_private_repository_and_I_will_not_be_harassed | /Алгоритмы и структуры данных на Python. Базовый курс/Урок 1. Практическое задание/task_6.py | 760 | 4.34375 | 4 | """
Задание 6. Пользователь вводит номер буквы в алфавите.
Определить, какая это буква.
Пример:
Введите номер буквы: 4
Введёному номеру соответствует буква: d
Подсказка: используйте ф-ции chr() и ord()
"""
user_input_symbol = int(input('Введите номер буквы: '))
if 0 < user_input_symbol < 27:
user_in... | false |
6c7beee44a89b6b3f5c99e9164ebfe51db81e734 | IslamOrtobaev/This_is_my_own_private_repository_and_I_will_not_be_harassed | /Алгоритмы и структуры данных на Python. Базовый курс/Урок 2. Практическое задание/task_2_1.py | 1,043 | 4.15625 | 4 | """
2. Посчитать четные и нечетные цифры введенного натурального числа.
Например, если введено число 34560, то у него 3 четные цифры
(4, 6 и 0) и 2 нечетные (3 и 5).
Подсказка:
Для извлечения цифр числа используйте арифм. операции
Пример:
Введите натуральное число: 44
В числе 44 всего 2 цифр, из которых 2 чётных и 0 ... | false |
6fb99f7f646c260eb763fc5804868a9bcf529971 | Shubham1744/HackerRank | /30_Days_of_code/Day_1_Data_Types/Solution.py | 777 | 4.25 | 4 |
int_2 = int(input())
double_2 = float(input())
string_2 = input()
# Read and save an integer, double, and String to your variables.
sum_int = i + int_2
sum_double = d + double_2
sum_string = s + string_2
# Print the sum of both integer variables on a new line.
# Print the sum of the double variables on a new line.
... | true |
cff97b2c99af7fe57a02233fb49e0e09db361242 | bagreve/Nivelacion | /26082019/000000.py | 771 | 4.15625 | 4 | # En la nivelacion numero 6,se ensana como usar y crear diccionarios
d = {} # Se crea un diccionario vacio
d["George"] = 24 # se crean nuevos valores ligados a llaves , siendo George la llave y su edad el valor
d["Tom"] = 32
d["Jenny"] = 20
d[10] = 100 # no solo se pueden crear listas con llave... | false |
250bbfc0aac5bf851b2cdb6ca2ca7fc5a2d658af | josealbm/PracticasPython | /Práctica 3/P3E2.py | 684 | 4.25 | 4 | #Práctica 3 - Ejercicio 2 - José Alberto Martín
#Pida al usuario 5 números y diga si estos estaban en
#orden decreciente, creciente o desordenados.
print ("Escribe cinco números y te diré que orden has utilizado")
a=int(input("Escribe el primer número "))
b=int(input("Escribe el segundo número "))
c=int(input... | false |
670efb0e6c1807247434ea2b21f83dbccddb5e28 | josealbm/PracticasPython | /Práctica 7/P7E4.py | 428 | 4.25 | 4 | #Práctica 7 -Ej 4 - José Alberto Martín Marí
#Escribe un programa que pida una frase, y le pase como parámetro
#a una función dicha frase. La función debe sustituir todos
#los espacios en blanco de una frase por un asterisco,
#y devolver el resultado para que el programa principal la imprima
#por pantalla... | false |
6dad818288d32ed0797f59fc4af3700c49a6e6b8 | josealbm/PracticasPython | /Práctica 5/P5E12.py | 1,901 | 4.125 | 4 | #Práctica 5 - Ejercicio 12 - José Alberto Martín Marí
#Escriu un programa per a jugar a endevinar un nombre (l'usuari pensa un nombre i el programa
#l'ha d'endevinar). El programa comença demanant entre què nombres està el nombre
#a endevinar i després intenta endevinar de què nombre es tracta. L'usuari va
#dient s... | false |
ad07b60b0c4d663663a286ca854833a903e3ee6a | Philiplam4516/TRM | /Python Workshop/Advnaced Python/Codes/Functions/Functions/F05.py | 431 | 4.125 | 4 | '''
Write a program to get a circle radius from terminal,
and then compute the area of the circle by a function
'''
PI = 3.14
def compute_circle_area(radius):
return radius*radius*PI
def main():
print("Enter a circle radius (m)")
radius=input()
radius = float(radius) # type cast from string to float
area... | true |
307cabfc949ee7f6af494726552b2228f09249d5 | jahanzebhaider/Python | /if\else/else.py | 1,841 | 4.15625 | 4 | #THIS CODE WILL PRINT THR HONDA CAR WITH UPPER CASE AND REST WITH LOWER CASE ALPHABETS
cars=['audi','bmw','honda','toyota','suzuki']
for car in cars:
if car =='Honda':
print(car.upper())
else:
print(car.lower())
# checking nother of checking in list
if 'ponks' in cars:
print("it'... | true |
5db7c26589e626757b3bd3c34f6470a4667b4508 | TheCoderIsBibhu/Spectrum_Internship | /Task1(PythonDev)/prgm2.py | 232 | 4.25 | 4 | #2 Given a number find the number of zeros in the factorial of the number.
num=int(input("Enter a Number: "))
i=0
while num!=0:
i+=int(num/5)
num=num/5
print("The Number of zeros in factorial of the number is ",i) | true |
dd2203fe3867099c933500e09d4b8e8e70933cb8 | fran-byte/python_exercises | /tests/excepciones/ValueError.py | 921 | 4.21875 | 4 |
# (_ _ _ _ __ |_ |_ _
# | | (_|| ) |_)\/|_(-
# /
# Realiza una función llamada agregar_una_vez() que reciba una lista y un elemento, uno a uno.
# La función debe añadir el elemento al final de la lista con la condición de no repetir ningún elemento.
lista=[]
def agregar_una_vez(lista... | false |
c33def97afff545464952faa066c663e1d472491 | RyanMolyneux/Learning_Python | /tutorialPointWork/lab5/test2.py | 1,186 | 4.5625 | 5 | #In this session we will be working with strings and how to access values from them.
print("\nTEST-1\n----------------------------\n");
"""Today we will test out how to create substrings, which will involve slicing
of an existing string."""
#Variables
variable_string = "Pycon"
variable_substring = variable_string[2... | true |
20d19ed63a0dd22c377a915facdb707c2b069732 | RyanMolyneux/Learning_Python | /pythonCrashCourseWork/Chapter 8/8-8-UserAlbums.py | 844 | 4.1875 | 4 | #Chapter 8 ex 8 date : 21/06/17.
#Variables
albums = []
#Functions
def make_album(artistName,albumTitle,num_tracks = ""):
"Creates a dictionary made up of music artist albums."
album = {"artist" : artistName,"album title": albumTitle}
if num_tracks:
album["number of tracks"] = num_tracks
retu... | true |
01cb8a39730aca55603be93355359da08d0a453e | RyanMolyneux/Learning_Python | /pythonCrashCourseWork/Chapter 10/ex10/main.py | 526 | 4.25 | 4 | """This will be a basic program which just consists of code counting the number of times 'the' appears in a text file."""
#Chapter 10 ex 10 DATE:17/07/18.
#Import - EMPTY
#Variables
file_name = ""
text = ""
#Objects - EMPTY
#Functions - EMPTY
#Body
file_name = input("\n\nPlease enter name of the fil... | true |
8d1bb14e3ea2315a1011b0abf715739c4e9b710a | darkleave/python-test | /Test/venv/Example/2/5.py | 267 | 4.28125 | 4 | #序列相加,只有相同类型的序列才能进行链接操作
addList = [1,2,3] + [4,5,6]
print(addList)
addString = 'Hello, ' + 'world!'
print(addString)
#字符串和列表类型不同,无法进行链接
addListString = [1,2,3] + 'world!'
print(addListString) | false |
182c3617675992814e9548d390db913b2f08fb7e | darkleave/python-test | /Test/venv/Example/2/4.py | 525 | 4.15625 | 4 | #步长示例
#步长通常都是隐式设置的,默认步长为1,分片操作就是按照这个步长逐个遍历序列的元素,然后返回开始和
#结束点之间的所有元素
numbers = [1,2,3,4,5,6,7,8,9,10]
num1 = numbers[0:10:2]
print(num1)
num2 = numbers[3:6:3]
print(num2)
num3 = numbers[::4]
print(num3)
num4 = numbers[8:3:-1]
print(num4)
num5 = numbers[10:0:-2]
print(num5)
num6 = numbers[0:10:-2]
print(num6)
num7 = numb... | false |
7694fe65590f429966a4315ed28b3dfaf1be8b6b | darkleave/python-test | /Test/venv/Example/4/5.py | 791 | 4.125 | 4 | #使用get()的简单数据库
people = {
'Alice':{
'phone':'2341',
'addr':'Foo drive 23'
},
'Beth':{
'phone':'9102',
'addr':'Bar street 42'
},
'Cecil':{
'phone':'3158',
'addr':'Baz avenue 90'
}
}
#针对电话号码和地址使用的描述性标签,会在打印输出的时候用到
labels = {
'phone':'phone num... | false |
4bc87ec0732a1bbae109667d396bc02610ecb6c7 | Gustacro/learning_python | /become_python_developer/3_Ex_Files_Learning_Python/Exercise Files/Ch3/calendars_start.py | 1,776 | 4.25 | 4 | #
# Example file for working with Calendars
#
# import the calendar module
import calendar
# create a plain text calendar
c = calendar.TextCalendar(calendar.SUNDAY)
# st = c.formatmonth(2019, 12, 0, 0) # "formatmonth" method allow format a particular month into a text string
# print(st)
# create an HTML formatted ca... | true |
a212f533bf41ef324030787837c59924207f7b9d | bansal-ashish/hackerR | /Python/Introduction/division.py | 1,753 | 4.34375 | 4 | #!/usr/bin/env python
"""
In Python, there are two kinds of division: integer division and float
division.
During the time of Python 2, when you divided one integer by another integer,
no matter what, the result would always be an integer.
For example:
>>> 4/3
1
In order to make this a float division, you would need... | true |
35815caac7564a6be04e75a3af3b12139b97eced | jaredcooke/CP1404Practicals | /prac1/fromscratch.py | 442 | 4.15625 | 4 | number_of_items = int(input("Number of items: "))
total_cost = 0
while number_of_items <= 0:
print("Invalid number of items!")
number_of_items = int(input("Number of items: "))
for i in range(number_of_items, 0, -1):
price_of_item = float(input("Price of item: "))
total_cost += price_of_item
if total_co... | true |
a90ca0253478d5f3ed76ae32ed0b59607ba40d9c | jathinraju/module-3 | /python module 3/prgm9.py | 257 | 4.3125 | 4 | #prgm on to check is palindrome are not
n = int(input("enter a number:"))
rev = 0
while(n != 0):
remi = n%10
rev = rev*10+remi
n = n//10
print("reverse of the number:",rev)
if n==rev :
print(n,"is a palindrome ")
else :
print("it is not a palindrome")
| false |
8b348d1a210524f7884e2602f3fe820adb0398e0 | KoretsValentyn/py_zoo | /zoo.py | 1,035 | 4.15625 | 4 | """There are three kinds of animals in a zoo. """
class Zoo:
"""implementation zoo object"""
def __init__(self):
self.animals = []
def get_animals(self):
"""return all animals in zoo"""
return self.animals
def add(self, animal):
"""add new animal in zoo"""
sel... | false |
a3af7a2a970e81045dfc09b7efcd54e8107f203c | melrjcr/GIT_DailyChall | /Caesar_Cipher.py | 521 | 4.25 | 4 | text = input('insert text to encrypt: ')
pattern = int(input('choose a shift pattern: '))
alphabet = abcdefghijklmnopqrstuvwxyz
def encrypt(text, pattern):
result = ""
for i in range(len(text)):
char = text[i]
if char.isupper():
result += chr((ord(char) + pattern - (ord('A'))) % le... | false |
8369dabbbe5680471488c495cf5a9b8599e11ea8 | orbache/pythonExercises | /exercise1.py | 541 | 4.40625 | 4 | #!/usr/bin/python
__author__ = "Evyatar Orbach"
__email__ = "evyataro@gmail.com"
'''Exercise 1
Create a program that asks the user to enter their name and their age. Print out a message addressed to them that tells them the year that they will turn 100 years old.
'''
from datetime import datetime
year = datetime.now()... | true |
3bd707a6c0b5a2ffb1657ae2ac8465452aa30d6d | orbache/pythonExercises | /exercise14.py | 747 | 4.5625 | 5 | #!/usr/bin/python
__author__ = "Evyatar Orbach"
__email__ = "evyataro@gmail.com"
'''Exercise 14
Write a program (using functions!) that asks the user for a long string containing multiple words.
Print back to the user the same string, except with the words in backwards order.
For example, say I type the string:
My n... | true |
c8cf7a7c6b5a999bcad80cc8a3ab48492a2aabf4 | brunoleej/study_git | /Basic/Algorithm/Basic/OOP/Public_private_protected_ex.py | 1,311 | 4.15625 | 4 | # 원 클래스 생성하기
# attribute : 원 반지름, 원 이름
# method
# 1. 원 이름 리턴 메소드
# 2. 원 넓이 리턴 메소드
# 참고(원 넓이 식) : 3.14 X 원 반지름 **2(원 반지름의 제곱)
# 3. 원 길이 리턴 메소드
# 참고(원 길이 식) : 2 X 3.14 X 원 반지름
# 생성자에서만 attribute 값 설정 가능
# attribute는 private으로 설정
... | false |
1d70db077c874f75b3911d94f58428037734fa66 | saurabhchris1/Algorithm-and-Data-Structure-Python | /Bubble_Sort/Bubble_Sort_Iterative_Optimized.py | 644 | 4.3125 | 4 | # Bubble Sort Iterative Optimized
# Print i,j will help you figure out calculations
def bubble_sort_iterative(num_arr):
len_arr = len(num_arr)
flag = True
for i in range(len_arr):
if not flag:
break
flag = False
for j in range(len_arr - i - 1):
print(i, j)
... | false |
5270f1e5b8d4285e401d440476bc077ee89b0315 | Themis404/completed_tasks | /task_twelve/task_twelve.py | 1,092 | 4.5625 | 5 | '''
2. В одном файле в каждой строке записаны координаты пар точек.
Каждая координата отделена от другой пробелом.
Например, строка вида 3 6 -2 4 означает, что координаты первой точки (3;6), второй - (-2;4).
Во второй файл требуется построчно записать наибольшее и наименьшее расстояние между точками
'''
import math
d... | false |
b71c8353038c7cac83a834e5b047cc735648b371 | abelar96/PythonPrograms | /HW2.py | 425 | 4.21875 | 4 | ##Diego Abelar Morales
def distance(s, h):
return s * h
speed = int(input("What is the speed of the vehicle in mph?: "))
hours = int(input("How many hours has it traveled: "))
print("Hours Distanced Traveled")
print("------------------------------")
for time in range(1, 1 + hours):
distance(... | true |
0d58826718124173c580fddc80ab18717d8db13e | Vaishnav95/bridgelabz | /testing_programs/vending_notes.py | 758 | 4.40625 | 4 | '''
Find the Fewest Notes to be returned for Vending Machine
a. Desc -> There is 1, 2, 5, 10, 50, 100, 500 and 1000 Rs Notes which can be
returned by Vending Machine. Write a Program to calculate the minimum number
of Notes as well as the Notes to be returned by the Vending Machine as a
Change
b. I/P -> read the Change... | true |
de3f20a97b1f6ad9a4f09553914f7a0b4b55ee54 | Vaishnav95/bridgelabz | /algorithm_programs/sort_merge.py | 700 | 4.15625 | 4 | '''
Merge Sort - Write a program to do Merge Sort of list of Strings.
a. Logic -> To Merge Sort an array, we divide it into two halves, sort the two halves
independently, and then merge the results to sort the full array. To sort a[lo, hi),
we use the following recursive strategy:
b. Base case: If the subarray le... | true |
6c802e64c761ee9de46c355b25dad866c867ded1 | Vaishnav95/bridgelabz | /logical_programs/tic_tac_toe.py | 630 | 4.25 | 4 | '''
Cross Game or Tic-Tac-Toe Game
a. Desc -> Write a Program to play a Cross Game or Tic-Tac-Toe Game. Player 1
is the Computer and the Player 2 is the user. Player 1 take Random Cell that is
the Column and Row.
b. I/P -> Take User Input for the Cell i.e. Col and Row to Mark the ‘X’
c. Logic -> The User or the Compute... | true |
b3a26c56d18f363bfb1cba242bff0d33a3363414 | cod3baze/initial-python-struture | /solo_learn/handle_files/readin.py | 293 | 4.1875 | 4 | #Para recuperar cada linha em um arquivo, você pode usar o método
# readlines para retornar uma lista na qual cada elemento é uma linha no arquivo.
file = open("textos.txt", "r")
#print(file.readline())
#file.close()
# ou usando um loop FOR
for line in file:
print(line)
file.close() | false |
f2784c8cc19167c649f41b9f077b127c8eb04cbe | svshriyansh/python-starter | /ex2fiborecur.py | 244 | 4.15625 | 4 | def fib(n):
if n == 1:
return 0
elif n == 2:
return 1
else:
return fib(n-1) + fib(n-2)
m = int(input("Enter the number to find its fibonacci: "))
for Num in range(1, m+1):
print(fib(Num),end=' ')
| true |
a2380c2f8ea772778259ae69c8851a5ebffffb8e | itodotimothy6/CTCI | /Arrays-&-Strings/1.4/solution.py | 1,566 | 4.25 | 4 | # Given a string, write a function to check if it is a permutation of a
# palindrome. A palindrom is a word or phraze that is the same forwards and
# backwards. A permutation is a rearrangement of letters. A palindrome does not
# need to be linited to just dictionary words.
# Note: a maximum of one character should ha... | true |
f2ce02fe4a649be8b2646c34427984151f68b8be | 23devanshi/pandas-practice | /Automobile Dataset/Exercises.py | 2,191 | 4.34375 | 4 | # Exercises taken from : https://pynative.com/python-pandas-exercise/
import pandas as pd
import numpy as np
#pd.display
df = pd.read_csv('D:/Python tutorial/Pandas Exercises/1 Automobile Dataset/Automobile_data.csv')
df.shape
#: From given data set print first and last five rows
print(df.head())
print(df.t... | true |
25b050106a89f63ea2133a42edc2fb2359379ee2 | victorparra96/Dictionaries-in-Python- | /exercise9.py | 2,093 | 4.25 | 4 | """
Escribir un programa que gestione las facturas pendientes de cobro de una empresa. Las facturas se almacenarán en
un diccionario donde la clave de cada factura será el número de factura y el valor el coste de la factura. El programa
debe preguntar al usuario si quiere añadir una nueva factura, pagar una existent... | false |
5a909adc2afee84b66d5b2b234ba71e55da4e5a3 | A-creater/turtle_exemple | /event_button.py | 2,384 | 4.28125 | 4 | import turtle
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
class Button(turtle.Turtle):
point1: Point
point2: Point
title: str
def __init__(self, point1: Point, point2: Point, title: str):
super(Button, self).__init__()
self.point1 = point1
... | false |
554e1ac6391e6f8582fcf1e48f3d724e4d992c42 | Romeo2393/First-Code | /Comparison Operator.py | 220 | 4.21875 | 4 | temperature = 30
temperature = int(input("What's the temperature outside? "))
if temperature > 30:
print("It's a hot day")
elif temperature < 10:
print("Its a cold day")
else:
print("Enjoy your day") | true |
3eebb69e178befbda33ea9fe8289474751af63b8 | Reyloso/Test_Ingenieria_datos | /fibonacci.py | 2,958 | 4.1875 | 4 |
from math import log10, sqrt
"""
Serie Fibonacci
La secuencia de Fibonacci es una secuencia de números con la relación:
𝐹𝑛=𝐹𝑛-1𝐹𝑛-2, donde 𝐹1=1 y 𝐹2=1
Resulta que 𝐹541 contiene 113 dígitos y es el primer número de Fibonacci donde los
últimos 9 dígitos son una secuencia pan-digital (que contiene todos los núm... | false |
84e23d7bb5df3549b754b9785c6c4a906f504a97 | zacniewski/Decorators_intro | /05_decorators_demystified.py | 1,460 | 4.1875 | 4 | """The previous example, using the decorator syntax:
@my_shiny_new_decorator
def another_stand_alone_function():
print "Leave me alone"
another_stand_alone_function()
#outputs:
#Before the function runs
#Leave me alone
#After the function runs
Yes, that's all, it's that simple. @decorator is just a shortcut to:
... | true |
f170a6023f6c27d8c4e1b77ff865275fa33dd551 | david-ryan-alviola/winter-break-practice | /hackerRankPython.py | 1,977 | 4.40625 | 4 | # 26-DEC-2020
# Print Hello, World! to stdout.
print("Hello, World!")
# Given an integer, , perform the following conditional actions:
# If is odd, print Weird
# If is even and in the inclusive range of 2 to 5, print Not Weird
# If is even and in the inclusive range of 6 to 20, print Weird
# If is even and grea... | true |
10eadac8c43d0dab3039732e0fa8b497a875c3b7 | arturfil/data-structures-and-algorithms | /sort/insertion_sort.py | 453 | 4.21875 | 4 | def insertion_sort(arr):
# traverse through index 0 to len(arr)
for i in range(1, len(arr)):
current_value = arr[i]
position = i
while position > 0 and arr[position - 1]>current_value:
arr[position] = arr[position-1]
position = position - 1
arr[position] = current_value
# testing al... | false |
701c8ac9df8e1544c22b63d94e2894fbf20ab04c | PaulGG-Code/Security_Python | /Simple_File_Character_Calculator.py | 242 | 4.1875 | 4 | #open file in read mode
file = open("D:\data.txt", "r")
#read the content of file
data = file.read()
#get the length of the data
number_of_characters = len(data)
print('Number of characters in text file :', number_of_characters)
| true |
835f358f71f3a8e6361c2c5fa0a8ed765e58386b | jakupierblina/learning-python | /tutorial/set.py | 1,059 | 4.1875 | 4 |
x = set('abcde')
y = set('bdxyz')
print('e' in x) # membership
print(x-y) #difference
print(x | y) #union
print(x & y) #intersection
print(x ^ y) #symmetric difference
print(x > y, x < y) #superset, subset
z = x.intersection(y) #find the same elements
z.add('SPAM')
print(z)
z.update(set(['X', 'Y'])) #update the se... | true |
0a4cf1075711c3b98b5d6dfd88b0065aec99c044 | stephenchenxj/myLeetCode | /findDiagonalOrder.py | 1,512 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
498. Diagonal Traverse
Medium
Given a matrix of M x N elements (M rows, N columns), return all elements of the matrix in diagonal order as shown in the below image.
Example:
Input:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
Output: [1... | true |
f8ff8c47fe3b6f6532182ec3474a1405f8293638 | stephenchenxj/myLeetCode | /reverseInteger.py | 1,146 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Oct 5 00:44:11 2019
@author: stephen.chen
"""
'''
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 r... | true |
da0019078824aa244442fbf23e20fb33814c05af | stephenchenxj/myLeetCode | /shuffle.py | 1,386 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Oct 11 20:26:42 2019
@author: stephen.chen
Shuffle an Array
Shuffle a set of numbers without duplicates.
Example:
// Init an array with set 1, 2, and 3.
int[] nums = {1,2,3};
Solution solution = new Solution(nums);
// Shuffle the array [1,2,3] and return its result. Any... | true |
89da494a7cae93de6c64d9220ff8a598c14499e0 | stephenchenxj/myLeetCode | /python_search_dict_by_value.py | 220 | 4.28125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 13 15:06:15 2020
@author: chen
"""
mydict = {1:'a', 2:'b', 3:'a'}
value = 'a'
keys = [ key for key,val in mydict.items() if val==value ]
print(keys) | false |
b0ba8f4f5411931d0d106a1e4ff75c15deb4a32c | christian-alexis/edd_1310_2021 | /colas.py | 2,818 | 4.15625 | 4 | #PRUEBAS DE LAS COLAS
class Queue:
def __init__(self):
self.__data = list()
def is_empty (self):
return len(self.__data)==0
def length(self):
return len(self.__data)
def enqueue(self,elem):
self.__data.append(elem)
def dequeue (self):
i... | true |
0ffe4afc95e64efe667b76c42dbae97687b2160d | mendozatori/python_beginner_proj | /rainfall_report/rainfall_report.py | 1,305 | 4.3125 | 4 | # Average Rainfall Application
# CONSTANTS
NUM_MONTHS = 12
# initialize
total_inches = 0.0
# input
years = int(input("How many years are we calculating for? "))
while years < 0:
print("Please enter a valid number of years!")
years = int(input("How many years are we calculating for? "))
... | true |
3b811ee60b5aee105510e413af107661e2127836 | tenzin1308/PythonBasic | /Class/TypesOfMethods.py | 711 | 4.125 | 4 | """
We have 3 types of Methods:
a) Instances/Object Methods
b) Class Methods
c) Static Methods
"""
class Student:
# Class/Static Variable
school = "ABC School"
def __init__(self, m1, m2, m3):
self.m1 = m1
self.m2 = m2
self.m3 = m3
# Instances/Object M... | true |
23f386c4f97055645a6724a76dc49f3b7a93c93b | pc2459/learnpy | /csv_parse.py | 2,455 | 4.15625 | 4 | """
Write a script that will take three required command line arguments - input_file,
output_file, and the row_limit. From those arguments, split the input CSV into
multiple files based on the row_limit argument.
Arguments:
1. -i: input file name
2. -o: output file name
3. -r: row limit to split
Default settings:
1. ... | true |
da75fe91a98fc2861ee2fbf266e5223eeac0c9b4 | austincunningham/python_exercises | /5_Miles_to_Feet.py | 275 | 4.21875 | 4 | #!/usr/bin/python3
def Miles_to_Feet(Miles):
feet = (Miles * 5280)
print ("%1.0f feet in %1.0f miles" %(feet,Miles))
def main():
print("Enter number of miles to convert to feet")
mile = input(">")
Miles_to_Feet(mile)
if __name__=='__main__':
main()
| false |
2791583af83b9ff15ac5fe9d30acd2313e6cfd2a | kirteekishorpatil/dictionary | /studant_data_8.py | 375 | 4.34375 | 4 | # i=0
# dict1={}
# if i<3:
# num=input("enter the student name")
# num2=int(input("enter the students marks"))
# i=i+1
# new_type={num:num2}
# dict1.update(new_type)
# print(dict1)
num=input("enter the student name")
num2=int(input("enter the students marks"))
# i=0
dict1={}
# while i<8:
new_type={... | true |
7af8b77a791d567ac85b2749936633f166f719f7 | Ratashou/Tic-Tac-Toe | /tictactoe.py | 2,675 | 4.25 | 4 | #! python3
#A program to make a simple tic tac toe/noughts and crosses game
theBoard = {'top-L': ' ', 'top-M': ' ', 'top-R': ' ',
'mid-L': ' ', 'mid-M': ' ', 'mid-R': ' ',
'bot-L': ' ', 'bot-M': ' ', 'bot-R': ' '} #the different positions on the board
def printBoard(ticSpace):
print(ticSpace['top-L'] + '|... | false |
2bbf90d8645ba21f97c0e4fc635cd50be9bffe2c | milnorms/pearson_revel | /ch7/ch7p5.py | 841 | 4.15625 | 4 | '''
(Sorted?)
Write the following function that returns True if the list is already sorted in increasing order:
def isSorted(lst):
Write a test program that prompts the user to enter a list of numbers separated by a space in one line and displays whether the list is sorted or not. Here is a sample run:
Sample Run 1... | true |
97d6ffbe6671998c18f37757459a61aea61de6f0 | milnorms/pearson_revel | /ch8/ch8p4.py | 1,626 | 4.46875 | 4 | '''
(Markov matrix)
An n by n matrix is called a positive Markov matrix if each element is positive and the sum of the elements in each column is 1. Write the following function to check whether a matrix is a Markov matrix:
def isMarkovMatrix(m):
Write a test program that prompts the user to enter a 3 by 3 matrix of... | true |
d5ae42360d6c5b28032c26f94bf5570608378ae7 | milnorms/pearson_revel | /ch4/ch4p2.py | 888 | 4.3125 | 4 | '''
(Convert letter grade to number)
Write a program that prompts the user to enter a letter grade A/a, B/b, C/c, D/d, or F/f and displays its corresponding numeric value 4, 3, 2, 1, or 0.
Sample Run 1
Enter a letter grade: B
The numeric value for grade B is 3
Sample Run 2
Enter a letter grade: b
The numeric val... | true |
c54e78731fa62bc05f222e87bb91d0961b89766a | milnorms/pearson_revel | /ch2/ch2p5.py | 1,009 | 4.21875 | 4 | '''
(Financial application: calculate future investment value)
Write a program that reads in an investment amount, the annual interest rate, and the number of years, and then displays the future investment value using the following formula:
futureInvestmentAmount = investmentAmount * (1 + monthlyInterestRate) ^ numbe... | true |
f96567cd7769179e1192ddda76022832c3454a8f | Saksykov/Stepik_Python_Courses | /introduction_to_python_practicum/lesson2.2_step5.py | 533 | 4.125 | 4 | """
Простое число делится без остатка только на 1 и на само себя.
Напишите программу, которая прочитает число и выведет "prime" если число простое и
"composite" в противном случае (без кавычек).
"""
x = int(input())
j = x - 1
f = True
while j > 1:
if x % j != 0:
j -= 1
continue
else:
f ... | false |
94e1e2f107723e9ea3d4ea648cbd16487b69af16 | pectoraux/python_programs | /question5.py | 2,323 | 4.125 | 4 | '''
Efficiency:
----------------------------------------------
member function get_length() of class Linked_List runs in O(1)
member function get_at_position() of class Linked_List runs in O(n)
make_ll() runs in O(n)
So question5() runs in O(n)
'''
class Node(object):
def __init__(self, da... | true |
41ad1238055f8657136aebbfdddd50e81ac0e66b | ebrahim-j/FindMissingLab | /MissingNumber.py | 662 | 4.125 | 4 | def find_missing(list1, list2):
inputList = [] #list with extra number
checkList = [] #template list
if len(list1) > len(list2): #determines the variable (input and check)lists will be assigned to
inputList = list1
checkList = list2
else:
inputList = list2
checkList = li... | true |
4cd52636027021227a8195e5a0a8ed31cb7753b3 | 7Aishwarya/HakerRank-Solutions | /30_Days_of_Code/day5_loops.py | 343 | 4.125 | 4 | '''Given an integer, n, print its first 10 multiples. Each multiple n x i (where 1<=i<=10) should be printed on a new line
in the form: n x i = result.'''
#!/bin/python3
import math
import os
import random
import re
import sys
if __name__ == '__main__':
n = int(input())
for i in range(10):
print(... | true |
8bb2e6edbb2d703ad41e899b57cb32b228676557 | 7Aishwarya/HakerRank-Solutions | /Algorithms/beautiful_days_at_the_movies.py | 1,685 | 4.46875 | 4 | '''Lily likes to play games with integers. She has created a new game where she determines the difference between a number and
its reverse. For instance, given the number 12, its reverse is 21. Their difference is 9. The number 120 reversed is 21, and their
difference is 99.
She decides to apply her game to decision ... | true |
6ce7779a588924aab0caea37a70bbe7be5d93ff2 | 7Aishwarya/HakerRank-Solutions | /30_Days_of_Code/day25_running_time_and_complexity.py | 745 | 4.15625 | 4 | '''Given a number, n find if it is prime or not.
Input Format
The first line contains an integer, T, the number of test cases.
Each of the T subsequent lines contains an integer, n, to be tested for primality.
Constraints
1<=T<=30
1<=n<=2*10^9
Output Format
For each test case, print whether n is Prime or Not Prime on a... | true |
c0afc50c0c7194f15656f6b58464908626e4c230 | VITA-mlr/cbs_lessons | /Python/es_4-2_iterator_generator.py | 1,409 | 4.25 | 4 | """
task1:
Напишите итератор, который возвращает элементы заданного списка в обратном порядке (аналог reversed).
task2:
Перепишите решение первого задания с помощью генератора.
"""
class ListIterator:
def __init__(self, collection):
self.collection = collection
self.cursor = len(self.... | false |
abb691603f4655d3c1a116d94b76f83655d182c3 | Jinx-Heniux/Python-2 | /maths/odd_check.py | 980 | 4.4375 | 4 | def is_odd(number: int) -> bool:
"""
Test if a number is a odd number.
:param number: the number to be checked.
:return: True if the number is odd, otherwise False.
>>> is_odd(-1)
True
>>> is_odd(-2)
False
>>> is_odd(0)
False
>>> is_odd(3)
True
>>> is_odd(4)
Fals... | true |
8bd8af36d1693829ebbf3e958a11b8a15fe44e0c | Jinx-Heniux/Python-2 | /sorts/quick_sort.py | 1,336 | 4.125 | 4 | """
https://en.wikipedia.org/wiki/Quicksort
"""
def quick_sort(array, left: int = 0, right: int = None):
"""
Quick sort algorithm.
:param array: the array to be sorted.
:param left: the left index of sub array.
:param right: the right index of sub array.
:return: sorted array
>>> import r... | true |
82c56958204986ce03caf2d8e913b06ccf433ac5 | Jinx-Heniux/Python-2 | /searches/binary_search_recursion.py | 871 | 4.15625 | 4 | """
https://en.wikipedia.org/wiki/Binary_search_algorithm
"""
def binary_search(array, key) -> int:
"""
Binary search algorithm.
:param array: the sorted array to be searched.
:param key: the key value to be searched.
:return: index of key value if found, otherwise -1.
>>> array = list(range(... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.