blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
2d7eb20c2f6eb18f3a8e7524df6decdceafb3cd7 | 1505069266/python- | /面向对象/公有,私有成员.py | 1,202 | 4.125 | 4 | class Student:
name = ''
age = 0
# 一个班级里所有学生的总数
sum1 = 0
__score = 0
# 实例方法
def __init__(self, name, age):
# 构造函数 实例化的时候会运行这里的代码
self.name = name
self.age = age
self.__class__.sum1 += 1
print("当前班级人数:" + str(self.__class__.sum1))
# print('我是:'... | false |
7ac0ace8b17c80af072aa80be36b1831684c91da | 1505069266/python- | /面向对象/静态方法.py | 1,015 | 4.125 | 4 | class Student:
name = ''
age = 0
# 一个班级里所有学生的总数
sum1 = 0
# 实例方法
def __init__(self, name, age):
# 构造函数 实例化的时候会运行这里的代码
self.name = name
self.age = age
self.__class__.sum1 += 1
print("当前班级人数:" + str(self.__class__.sum1))
# print('我是:' + name)
... | false |
5ff753d7ac3265f5e88dfa88ee11742f85499e8d | ArtZubkov/pyDev | /lab1.py | 2,463 | 4.28125 | 4 | '''
Программа, вычисляющая уравнение прямой, которая пересекает
заданную окружность и расстояние между точками пересечения
которой минимальны.
'''
#Ввод данных и инициализация
print('Уравнение окружности: (x-x0)^2+(y-y0)^2=r^2 ')
x0=float(input('Введите x0 для уравнения окружности: '))
y0=flo... | false |
4c28efd8124035ef404c5cdabf8279a25ffdead2 | nasingfaund/Yeppp-Mirror | /codegen/common/Argument.py | 1,926 | 4.4375 | 4 | class Argument:
"""
Represents an argument to a function.
Used to generate declarations and default implementations
"""
def __init__(self, arg_type, name, is_pointer, is_const):
self.arg_type = arg_type
self.name = name
self.is_pointer = is_pointer
self.is_const = is... | true |
7432e574d515aadac24d93b6aa1568d3add65fc6 | johnpospisil/LearningPython | /try_except.py | 873 | 4.21875 | 4 | # A Try-Except block can help prevent crashes by
# catching errors/exceptions
# types of exceptions: https://docs.python.org/3/library/exceptions.html
try:
num = int(input("Enter an integer: "))
print(num)
except ValueError as err:
print("Error: " + str(err))
else: # runs if there are no errors
print('... | true |
d78585044147f77090dc54494e1a3c24b36c5b37 | johnpospisil/LearningPython | /while_loops.py | 592 | 4.21875 | 4 | # Use While Loops when you want to repeat an action until a certain condition is met
i = 1
while i <= 10:
print(i, end=' ')
i += 1
print("\nDone with loop")
# Guessing Game
secret_word = "forge"
guess = ""
guess_count = 0
guess_limit = 3
out_of_guesses = False
print("\nGUESSING GAME")
while guess != secret_... | true |
7a1bae5b1b9bedf34e6b2f2623024b98a6c25348 | johnpospisil/LearningPython | /variables.py | 420 | 4.3125 | 4 | char_name = "John"
char_age = 50
is_male = True
print("There once was a man named " + char_name + ".")
print("He was " + str(char_age) + " years old.")
print("He liked the name " + char_name + ".")
print("But he did not like being " + str(char_age) + " years old.")
print("Is " + char_name + " male? " + str(is_male))
p... | false |
c0520b4031b569268c84a81d38616af2b39b8d26 | hansrajdas/random | /practice/loop_starting_in_linked_list.py | 2,003 | 4.15625 | 4 | class Node:
def __init__(self, k):
self.k = k
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def insert_begin(self, k):
if self.head is None:
self.head = Node(k)
return
n = Node(k)
n.next = self.head
s... | false |
a9286b6aa0e4185915bebea4888bc79d7c27bc3b | yeasellllllllll/bioinfo-lecture-2021-07 | /basic_python/210701_70_.py | 763 | 4.25 | 4 | #! /usr/bin/env python
print(list(range(5)))
# [0, 1, 2, 3, 4]
print('hello'[::-1])
# olleh
print('0123456789'[0:5:1])
#위의 숫자 위치 찾는 것은 원하는 위치를 설정할수없다.
print(list(range(2, 5, 1)))
# [2, 3, 4] 2~5사이의 1차이나게끔 올려서 리스트 보여줘
totalSum = 0
for i in range(3):
totalSum += i
print(i)
print('totalSum:', totalSum)
'''
... | false |
9fc9df1a3b6028dffaae5efdfacc2b5577929ce2 | lihaoyang411/My-projects | /Encryption-Bros-master/Main.py | 1,947 | 4.15625 | 4 |
import sys
typeChosen = 0
def choose(choice):
while True:
if choice.find(".") >= 0 or choice.find("-") >= 0:
choice = input("You didn't type in a positive integer. Please try again: ")
else:
try:
choice = int(choice)
dummyNum = 2/choice
... | true |
23334bd9745a107a337460c8cd4a2b8dcfa6a52d | Shiliangwu/python_work | /hello_world.py | 1,037 | 4.21875 | 4 | # this is comment text
# string operation examples
message="hello python world"
print(message)
message="hello python crash course world!"
print(message)
message='this is a string'
message2="this is also a string"
print(message)
print(message2)
longString='I told my friend, "Python is my favorite language!"'
pri... | true |
bde6d52ed8e8578510e2e3ed47ca03fd13172c33 | anindo78/Udacity_Python | /Lesson 3 Q2.py | 698 | 4.15625 | 4 | # Define a procedure, greatest,
# that takes as input a list
# of positive numbers, and
# returns the greatest number
# in that list. If the input
# list is empty, the output
# should be 0.
def greatest(list_of_numbers):
if len(list_of_numbers) == 0:
return 0
else:
maximum = list_of_numbers[0]... | true |
0fc6e1ae13fecbc47013ddecc2b29ef71f13b8c6 | hamsemare/sqlpractice | /291projectReview.py | 2,985 | 4.28125 | 4 | import sqlite3
connection = None
cursor = None
name= None
# Connect to the database
def connect(path):
global connection, cursor
connection=sqlite3.connect(path)
cursor=connection.cursor()
def quit():
exit(0)
def findName():
global name
studentName= input("Enter Student Name: ")
if(studentName=="q" or stud... | true |
3f30bad898e7fbaa90495f3f609f6f6c3d43ba78 | HunterOreair/Portflio | /RollDie.py | 942 | 4.1875 | 4 | #A simple python program that rolls die and returns the number that has been rolled. Made by Hunter Oreair.
from random import randint # imports randint. duh.
min = 1 #sets the minimum value on the dice that you can roll
max = 6 #sets the maximum value
def die(): # Creates a method called die
rollDie = r... | true |
464d00436d9c90def53af9f7b1717e16f1031b23 | JerryCodes-dev/hacktoberfest | /1st Assignment.py | 884 | 4.15625 | 4 | # NAME : YUSUF JERRY MUSAGA
# MATRIC NUMBER : BHU/19/04/05/0056
# program to find the sum of numbers between 1-100 in step 2
for a in range(1,100,2):
print(a)
num = 1
while num < 100:
print(num)
num += 2
# program to find all even numbers between 1-100
for b in range(2,100,2):
print (b)
numb = 2... | true |
5cc890b202f98bb88b5d614c43745cf2b427b0e4 | CoffeePlatypus/Python | /Class/class09/exercise1.py | 893 | 4.6875 | 5 |
#
# Code example demonstrating list comprehensions
#
# author: David Mathias
#
from os import listdir
from random import randint
from math import sqrt
print
# create a list of temps in deg F from list of temps in deg C
# first we create a list of temps in deg C
print('Create a list of deg F from a list of deg C tem... | true |
7185ccd8e4a6913a24efb58ee17692112564b4d7 | CoffeePlatypus/Python | /Class/class03/variables.py | 804 | 4.125 | 4 |
#
# Various examples related to the use of variables.
#
# author: David Mathias
#
x = 20
print type(x)
print
y = 20.0
print type(y)
print
s = "a"
print type(s)
print
c = 'a'
print type(c)
print
b = True
print type(b)
print
print('8/11 = {}'.format(8/11))
print
print('8.0/11 = {}'.format(8.0/11))
print
print('... | true |
884f3d8864db1f221e5ff8b3f06fc87a20fc6882 | shabazaktar/Excellence-Test | /Question2.py | 304 | 4.21875 | 4 | # 2 Question
def maxValue(d2):
key = max(d2, key=d2.get)
d3={key : d2[key]}
return d3
d1= {
"1" : "Shahbaz",
"2" : "Kamran",
"3" : "Tayyab"
}
d2= {
"1" : 50,
"2" : 60,
"3" :70
}
print(maxValue(d2))
| false |
3e8ea3989cf216ab53e9a493b07ea974dbe17091 | rp927/Portfolio | /Python Scripts/string_finder.py | 585 | 4.125 | 4 | '''
In this challenge, the user enters a string and a substring. You have to print the number of times that the substring occurs in the given string. String traversal will take place from left to right, not from right to left.
'''
def count_substring(string, sub_string):
ls = []
o = 0
count = 0
l = le... | true |
0fa7471aa14fec407c4b491a338ffaf70f530183 | lherrada/LeetCode | /stacks/problem1.py | 741 | 4.28125 | 4 | # Check for balanced parentheses in Python
# Given an expression string, write a python program to find whether a given string has balanced parentheses or not.
#
# Examples:
#
# Input : {[]{()}}
# Output : Balanced
#
# Input : [{}{}(]
# Output : Unbalanced
from stack import Stack
H = {'{': '}', '[': ']', '(': ')'... | true |
4c4cbbf75cd598226f55a08b967597dde477e7a3 | odemeniuk/twitch-challenges | /interview/test_palindrome.py | 336 | 4.40625 | 4 |
# write a function that tells us if a string is a palindrome
def is_palindrome(string):
""" Compare original string with its reverse."""
# [::-1] reverses a string
reverse = string[::-1]
return string == reverse
def test_is_palindrome():
assert is_palindrome('banana') is False
assert is_pal... | true |
d8f9c69874ca0ab5da4dac704f88fedb77b1b30d | dragonRath/PythonBasics | /stringformatting.py | 2,162 | 4.53125 | 5 | #The following will illustrate the basic string formatting techniques used in python
age = 24
#print("My age is " + str(age) + " years\n")
print("My age is {0} years".format(age)) #{} Replacement brackets
print("There are {0} days in {1}, {2}, {3}, {4}, {5}, {6} and {7}".format(31, "January", "March", "May", "July", ... | true |
c603d6ab0955cfc0100daa3a9c4c37cceb58876c | loweryk/CTI110 | /p3Lab2a_lowerykasey.py | 1,026 | 4.46875 | 4 | #Using Turtle in Python
#CTI-110 P3LAB2a_LoweryKasey
import turtle #Allows us to use turtles
wn = turtle.Screen() #Creates a playground for turtles
alex = turtle.Turtle() #Creatles a turtle, assign to alex
#commands from here to the last line can be replaced
alex.hideturtle() #Hides the turtle i... | true |
676b4eb2f036c5379c5367528429cd124facc5b0 | CBGO2/Mision-04 | /Triangulos.py | 1,086 | 4.25 | 4 | # Carlos Badillo García
# Programa que lee el valor de cada uno de los lados de un triangulo e indica el tipo de triángulo que es
def indicarTipoTriangulo(lado1, lado2, lado3): #Indicar que tipo de triángulo es dependiendo el valor de sus lados
if lado1 == lado2 == lado3:
return "El triángulo es equ... | false |
2ea9f7ee2ecaf30a0678c566a6492d3c2f75a290 | DrOuissem/useful_programs | /code_python2/chapter1_oop/4_video_abstract_class/video4_AbstractClass.py | 1,054 | 4.15625 | 4 | from abc import ABC, abstractmethod
class Person(ABC):
def __init__(self,name,age):
self.name = name
self.age = age
def print_name(self):
print("name: ",self.name)
def print_age(self):
print("age: ",self.age)
@abstractmethod
def print_info(self):
pass
class St... | false |
f643f39546ae35916bf1147df22e1bdfddfd4972 | sheriaravind/Python-ICP4 | /Source/Code/Num-Py -CP4.py | 359 | 4.28125 | 4 | import numpy as np
no=np.random.randint(0,1000,(10,10)) # Creating the array of 10*10 size with random number using random.randint method
print(no)
min,max = no.min(axis=1),no.max(axis=1) # Finding the minimum and maximum in each row using min and max methods
print("Minimum elements of 10 size Array is",min)
print("Max... | true |
3fb3edce524850dfdc618bc407b47c3f57d89978 | TENorbert/Python_Learning | /learn_python.py | 637 | 4.125 | 4 | #!/usr/bin/python
"""
python
"""
'''
first_name = input("Enter a ur first name: ")
last_name = input("Enter your last name: ")
initial = input("Enter your initial: ")
person = initial + " " + first_name + " " + last_name
print("Ur name is %s" %person)
print("Ur name is %s%s%s" %initial %first_name %last_name)
... | true |
2c23e549b3f04c9d776a698348039ef1e8eba4a3 | diegoasanch/Fundamentos-de-Progra-2019 | /TP3 Estructura alternativa/TP3.10 Clasificador de triangulos.py | 1,441 | 4.28125 | 4 | #Desarrollar un programa para leer las longitudes de los tres lados de un triángulo
# L1, L2, L3 y determinar qué tipo de triángulo es según la siguiente clasificación:
# · Si A >= B + C no se trata de un triángulo.
# · Si A² = B² + C² se trata de un triángulo rectángulo.
# · Si A² > B² + C² se trata de un triángulo ob... | false |
2bc83bf2c084a7baba788f047d97427d57d7eb3c | diegoasanch/Fundamentos-de-Progra-2019 | /TP5 Funciones/TP5.12 Extraer un digito de un entero.py | 1,705 | 4.15625 | 4 | # Extraer un dígito de un número entero. La función recibe como parámetros dos
# números enteros, uno será del que se extraiga el dígito y el otro indica qué cifra
# se desea obtener. La cifra de la derecha se considera la número 0. Retornar el
# valor -1 si no existe el dígito solicitado. Ejemplo: extraerdigito(12345,... | false |
4d2e57dbc334cb1ba9f22efbdbac4fd5f38d95a8 | diegoasanch/Fundamentos-de-Progra-2019 | /TP4 Estructura iterativa/TP4.2 Imprimir primer y ultimo valor.py | 504 | 4.15625 | 4 | #Realizar un programa para ingresar desde el teclado un conjunto de números. Al
#finalizar mostrar por pantalla el primer y último elemento ingresado. Finalizar la
#lectura con el valor -1.
print('Ingrese numeros, para finalizar ingrese -1')
print()
n=int(input('Ingrese un valor: '))
if n!=-1:
primero=n
while n... | false |
25b1a46a621054c7d04da0e02ce0acc6181c46eb | keithrpotempa/python-book1 | /sets/cars.py | 1,539 | 4.21875 | 4 | # Create an empty set named showroom.
showroom = set()
# Add four of your favorite car model names to the set.
showroom.update(["Car1", "Car2", "Car3", "Car4"])
# Print the length of your set.
print("Showroom length", len(showroom))
# Pick one of the items in your show room and add it to the set again.
showroom.upda... | true |
d4a524ea19b19afd811e32a9f0c58916b4cabb8f | BrutalCoding/INFDEV01-1_0912652 | /DEV_01_1___Assignment_4___Exercise_1.b/DEV_01_1___Assignment_4___Exercise_1.b/DEV_01_1___Assignment_4___Exercise_1.b.py | 227 | 4.25 | 4 | celcius = -273.15 #This is the default value to trigger the while loop here below
while celcius <= -273.15:
celcius = input("Enter Celcius to convert it to Kelvin:\n")
print "Celcius:", celcius, "Kelvin = ", celcius+273.15 | true |
b0985c06edbb8bc0ff8d86e3f7b5772d204954a3 | olivepeace/ASSIGNMENT-TO-DETERMINE-DAYOF-BIRTH | /ASSIGNMENT TO DETERMINE DAY OF BIRTH.py | 1,960 | 4.375 | 4 |
"""
NAME: NABUUMA OLIVIA PEACE
COURSE:BSC BIOMEDICAL ENGINEERING
REG NO: 16/U/8238/PS
"""
import calendar
print("This Program is intended to determine the exact day of the week you were born")
print(".....................................................")
day = month = year = None
#Next code ensures that o... | true |
c08a6b31684f0d20fd1c7ef9b64e8db0168e7ff5 | NDjust/python_data_structure | /sort_search/search.py | 1,413 | 4.21875 | 4 | from random import randint
import time
def linear_search(L, x):
'''
using linear search algorithms
time complexity
-> O(n)
parmas:
L: list
x: target num
'''
for i in range(len(L)):
if x == L[i]:
return i
return -1
def binary_search(L, x):
'''
usin... | false |
afad2695aa4dff1ce100cfaf65cbdcca9b6c37d4 | RaazeshP96/Python_assignment1 | /function12.py | 305 | 4.3125 | 4 | '''
Write a Python program to create a function that takes one argument, and
that argument will be multiplied with an unknown given number.
'''
def multi(n):
a = int(input("Enter the number:"))
return f"The required result is { n * a }"
n = int(input("Enter the integer:"))
print(multi(n))
| true |
8c225b5b0ac4648cfa8e555b9aaf74312d89484f | RaazeshP96/Python_assignment1 | /function16.py | 237 | 4.25 | 4 | '''
Write a Python program to square and cube every number in a given list of
integers using Lambda.
'''
sq=lambda x:x*x
cub=lambda x:x*x*x
n=int(input("Enter the integer:"))
print(f"Square -> {sq(n)}")
print(f"Cube -> {cub(n)}") | true |
0ac4c15f04bf3e49e1ca36ac3bb67e81ed9a0200 | Rogersamacedo/calc | /calc.py | 1,279 | 4.28125 | 4 | def calculadora():
print("Qual operação deseja efetuar? : ")
print( "Para soma digite 1")
print( "Para subtração digite 2")
print( "Para divisão digite 3")
print( "Para mutiplicação digite 4")
print( "Para potencia digite 5")
print( "Para porcentagem digite 6")
print( "Para raiz quadrada... | false |
d7a0eaf524bd36baf8ef17e6aab4147e32e61e9b | DeepuDevadas97/-t2021-2-1 | /Problem-1.py | 1,046 | 4.21875 | 4 | class Calculator():
def __init__(self,a,b):
self.a=a
self.b=b
def addition(self):
return self.a+self.b
def subtraction(self):
return self.a-self.b
def multiplication(self):
return self.a*self.b
def division(self):
... | true |
22b5e71d891a902473213c464125bea0ca1526c6 | kelpasa/Code_Wars_Python | /5 кю/RGB To Hex Conversion.py | 971 | 4.21875 | 4 | '''
The rgb function is incomplete. Complete it so that passing in RGB decimal values will result in a hexadecimal representation being returned. Valid decimal values for RGB are 0 - 255. Any values that fall out of that range must be rounded to the closest valid value.
Note: Your answer should always be 6 characters ... | true |
efe2f3dd96140dfb7ca59d5a5571e6c031491273 | kelpasa/Code_Wars_Python | /5 кю/Scramblies.py | 430 | 4.15625 | 4 | '''
Complete the function scramble(str1, str2) that returns true if a portion of str1 characters can be rearranged to match str2, otherwise returns false.
Notes:
Only lower case letters will be used (a-z). No punctuation or digits will be included.
Performance needs to be considered
'''
def scramble(s1,s2):
fo... | true |
4d26fc6d60a59ad20aec5456cf32bc6588018139 | kelpasa/Code_Wars_Python | /6 кю/String transformer.py | 489 | 4.40625 | 4 | '''
Given a string, return a new string that has transformed based on the input:
Change case of every character, ie. lower case to upper case, upper case to lower case.
Reverse the order of words from the input.
Note: You will have to handle multiple spaces, and leading/trailing spaces.
For example:
"Example Input" ... | true |
a62713c957216d00edf4dbb925e5f561f94c4cf2 | kelpasa/Code_Wars_Python | /6 кю/Sort sentence pseudo-alphabetically.py | 1,238 | 4.3125 | 4 | '''
Given a standard english sentence passed in as a string, write a method that will return a sentence made up of the same words, but sorted by their first letter. However, the method of sorting has a twist to it:
All words that begin with a lower case letter should be at the beginning of the sorted sentence, and sor... | true |
4804ed7aa18e361bf99084a6d1f2390b18d8bb8a | kelpasa/Code_Wars_Python | /5 кю/Emirps.py | 1,045 | 4.3125 | 4 | '''
If you reverse the word "emirp" you will have the word "prime". That idea is related with the purpose of this kata: we should select all the primes that when reversed are a different prime (so palindromic primes should be discarded).
For example: 13, 17 are prime numbers and the reversed respectively are 31, 71 wh... | true |
3f821ad7f3538a1066e56a6c8737932fcbda94b0 | kelpasa/Code_Wars_Python | /6 кю/Parity bit - Error detecting code.py | 1,118 | 4.21875 | 4 | '''
In telecomunications we use information coding to detect and prevent errors while sending data.
A parity bit is a bit added to a string of binary code that indicates whether the number of 1-bits in the string is even or odd. Parity bits are used as the simplest form of error detecting code, and can detect a 1 bit ... | true |
ab10772302efd8e44c5b0d5a157587cbeea7ce62 | kelpasa/Code_Wars_Python | /6 кю/Multiplication table.py | 424 | 4.15625 | 4 | '''
our task, is to create NxN multiplication table, of size provided in parameter.
for example, when given size is 3:
1 2 3
2 4 6
3 6 9
for given example, the return value should be: [[1,2,3],[2,4,6],[3,6,9]]
'''
def multiplicationTable(n):
table = []
for num in range(1, n+ 1):
row = []
for c... | true |
9180bd22fb2a47c8276454dda65caa58fd5116ce | kelpasa/Code_Wars_Python | /6 кю/Matrix Trace.py | 1,236 | 4.34375 | 4 | '''
Calculate the trace of a square matrix. A square matrix has n rows and n columns, where n is any integer > 0. The entries of the matrix can contain any number of integers. The function should return the calculated trace of the matrix, or nil/None if the array is empty or not square; you can otherwise assume the inp... | true |
deb7b21d9a08444b3681c1fce4ce1f82e38a6192 | kelpasa/Code_Wars_Python | /6 кю/Selective Array Reversing.py | 893 | 4.46875 | 4 | '''
Given an array, return the reversed version of the array (a different kind of reverse though), you reverse portions of the array, you'll be given a length argument which represents the length of each portion you are to reverse.
E.g
selReverse([1,2,3,4,5,6], 2)
//=> [2,1, 4,3, 6,5]
if after reversing some portion... | true |
2b6315a9c117156389761fb6d25ec1d375ed9d1b | kelpasa/Code_Wars_Python | /5 кю/Human Readable Time.py | 690 | 4.15625 | 4 | '''
Write a function, which takes a non-negative integer (seconds) as input and returns the time in a human-readable format (HH:MM:SS)
HH = hours, padded to 2 digits, range: 00 - 99
MM = minutes, padded to 2 digits, range: 00 - 59
SS = seconds, padded to 2 digits, range: 00 - 59
The maximum time never exceeds 359999 (... | true |
f67afbb5da9f57dd033101e6b219a495e466b392 | kelpasa/Code_Wars_Python | /6 кю/Duplicate Arguments.py | 584 | 4.25 | 4 | '''
Complete the solution so that it returns true if it contains any duplicate argument values. Any number of arguments may be passed into the function.
The array values passed in will only be strings or numbers. The only valid return values are true and false.
Examples:
solution(1, 2, 3) --> false
solu... | true |
2d40bf4dba925bf5a846e7fd859f390fe5046b07 | eligiuz/Curso_Python | /practica_for.py | 1,217 | 4.1875 | 4 | # for i in ["primavera","verano","otoño","invierno"]:
# print(i)
#-- imprime en una linea con un espacio por pase de for
# for i in ["Pildoras", "Informativas", 3]:
# print("Hola",end=" ")
#-- Revisa si se encuentra la @ en el email --
# contador=0
# miEmail=input("Introduce tu dirección de email: ")
# for... | false |
421b1232a36a6718cce0560efee1260a906f84fb | miguel-nascimento/coding-challenges-stuffs | /project-euler/004 - Largest palindrome product.py | 375 | 4.1875 | 4 | # Find the largest palindrome made from the product of two 3-digit numbers.
# A palindromic number reads the same both ways
def three_digits_palindome():
answer = max(i * j
for i in range(100, 1000)
for j in range(100, 1000)
if str(i * j) == str(i * j)[:: -1])
... | true |
4aef3e9c439bc78c0de034650e260cf98b6b5ee3 | evelyn-pardo/actividad-de-clases | /condicion.py | 1,372 | 4.1875 | 4 | class Condicion:
def _init_(self,num1,num2):
self.numero1=num1
self.numero2=num2
numero = self.numero1+self.numero2
self.numero3=numero
def __init__(self,num1,num2):
self.numero1=num1
self.numero2=num2
numer... | false |
50e6dc86d6a2dcec1df9cac643815c3e9c3a7f06 | ArnoBali/python-onsite | /week_01/03_basics_variables/08_trip_cost.py | 402 | 4.46875 | 4 | '''
Receive the following arguments from the user:
- miles to drive
- MPG of the car
- Price per gallon of fuel
Display the cost of the trip in the console.
'''
miles = int(input("please input miles to drive:" ))
mpg = int(input("please input MPG of the car:" ))
p_gallon = int(input("please input Price ... | true |
1bdcfa5db635cbba8f5f54f3d651187ee1865810 | ArnoBali/python-onsite | /week_02/07_conditionals_loops/Exercise_05.py | 532 | 4.375 | 4 | '''
Take two numbers from the user, an upper and lower bound. Using a loop, calculate the sum
of numbers from the lower bound to the upper bound. Also, calculate the average of numbers.
Print the results to the console.
For example, if a user enters 1 and 100, the output should be:
The sum is: 5050
The average ... | true |
d2dd93a12035f03644a19898b5e8356a16320a02 | ArnoBali/python-onsite | /week_02/07_conditionals_loops/Exercise_01.py | 382 | 4.5625 | 5 | '''
Write a program that gets a number between 1 and 1,000,000,000
from the user and determines whether it is odd or even using an if statement.
Print the result.
NOTE: We will be using the input() function. This is demonstrated below.
'''
input_ = int(input("Please input a number between 1 - 1,000,000,000: "))
if ... | true |
930aa1338bd9bcab9c005cb62111e8d6b7820016 | udichibarsagadey/pychemistry | /ML/panda_ML.py | 409 | 4.15625 | 4 | """
how to write csv file in panda
1) Pandas head()
2) Pandas tail()
3) Pandas write csv ‘dtype’
4) Pandas write csv ‘true_values‘
5) Pandas write csv ‘false_values’
# pandas fillna
"""
import pandas as pd
ab = pd.read_csv('Fortune_10.csv')
print(ab)
print(ab.head())
print(ab.tail(7))
ab = pd.read_csv('student_resu... | false |
c3eafe4b5b245cf0ad6e77460780af570a92560c | chandrakant100/Assignments_Python | /Practical/assignment4/factorial.py | 246 | 4.28125 | 4 | # To find factorial of a number using recursion
def rec_fact(num):
if num <= 1:
return 1
return num * rec_fact(num - 1)
num = int(input("Enter a number: "))
print("Factorial of {0} is {1}".format(num, rec_fact(num)))
| true |
349d17c98133a3970fe6f20f369a802ab59d8c3b | govindarajanv/python | /programming-practice-solutions/exercises-set-1/exercise-01-solution.py | 968 | 4.21875 | 4 | #1 printing "Hello World"
print ("Hello World")
#Displaying Python's list of keywords
import keyword
print ("List of key words are ..")
print (keyword.kwlist)
#2 Single and multi line comments
# This is the single line comment
''' This is multiline
comment, can be
used for a paragraph '''
#3 Multi line state... | true |
4f5ad33e6485de134980f5523cb21c41b51bfb99 | govindarajanv/python | /gui-applications/if-else.py | 338 | 4.15625 | 4 | #
number = 23
# input() is used to get input from the user
guess = int(input('Enter an integer : '))
if guess == number:
print('Congratulations, you guessed it.') # New block starts here
elif guess < number:
print('No, it is a little higher than that') # Another block
else:
print('No, it is a little l... | true |
6658ab77e9521efd122e1348c1860401d6b7abda | govindarajanv/python | /regex/regex-special-sequences.py | 1,679 | 4.34375 | 4 | import re
pattern = r"(.+) \1"
print ("pattern is",pattern)
match = re.match(pattern, "word word")
if match:
print ("Match 1")
match = re.match(pattern, "?! ?!")
if match:
print ("Match 2")
match = re.match(pattern, "abc cde")
if match:
print ("Match 3")
match = re.match(pattern, "abc ab")
if match:
... | true |
170ffd1a881e4043e7e9be7d70841c5652443d9d | govindarajanv/python | /regex/regex.py | 1,061 | 4.125 | 4 | import re
# Methods like match, search, finall and sub
pattern = r"spam"
print ("\nFinding \'spam\' in \'eggspamsausagespam\'\n")
print ("Usage of match - exact match as it looks at the beginning of the string")
if re.match(pattern, "eggspamsausagespam"):
print("Match")
else:
print("No match")
print ("\nUsag... | true |
8638bd18648d6ed7aceaffd6c842e42a0cad680b | govindarajanv/python | /functional-programming/loops/fibonacci.py | 539 | 4.1875 | 4 | """
0,1,1,2,3,5,8,13...n
"""
def factorial(n):
first_value = 0
second_value = 1
for i in range(1,n,1):
if i == 1:
print ("{} ".format(first_value))
elif i==2:
print ("{} ".format(second_value))
else:
sum = first_value + second_value
pri... | true |
04db43932905662ea741f34a135cd9097941e469 | govindarajanv/python | /regex/regex-character-classes.py | 1,794 | 4.6875 | 5 | import re
#Character classes provide a way to match only one of a specific set of characters.
#A character class is created by putting the characters it matches inside square brackets
pattern = r"[aeiou]"
if re.search(pattern, "grey"):
print("Match 1")
if re.search(pattern, "qwertyuiop"):
print("Match 2")
if... | true |
10e85d68d0c5c121457de9a464b8cc8a22bf62db | Achraf19-okh/python-problems | /ex7.py | 469 | 4.15625 | 4 | print("please typpe correct informations")
user_height = float(input("please enter your height in meters"))
user_weight = float(input("please enter your weight in kg"))
BMI = user_weight/(user_height*user_height)
print("your body mass index is" , round(BMI,2))
if(BMI <= 18.5):
print("you are under weight")
elif(BMI... | true |
e5e26adc9ce9c5c85bd2b8afdb2bc556746f8d20 | azhar-azad/Python-Practice | /07. list_comprehension.py | 770 | 4.125 | 4 | # Author: Azad
# Date: 4/2/18
# Desc: Let’s say I give you a list saved in a variable:
# a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100].
# Write one line of Python that takes this list a and makes a new list
# that has only the even elements of this list in it.
# ------------------------------------... | true |
bcd76925689d3e401ce55f7efe88aa323b02c0d0 | azhar-azad/Python-Practice | /10. list_overlap_comprehensions.py | 995 | 4.3125 | 4 | # Author: Azad
# Date: 4/5/18
# Desc: Take two lists, say for example these two:
# a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
# b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
# and write a program that returns a list that
# contains only the elements that are common between the li... | true |
900685d187fce72a3edb34daef753d90395b2a8b | ARBUCHELI/100-DAYS-OF-CODE-THE-COMPLETE-PYTHON-PRO-BOOTCAMP-FOR-2021 | /Guess the Number/guess_the_number.py | 1,951 | 4.4375 | 4 | #Number Guessing Game Objectives:
# Include an ASCII art logo.
# Allow the player to submit a guess for a number between 1 and 100.
# Check user's guess against actual answer. Print "Too high." or "Too low." depending on the user's answer.
# If they got the answer correct, show the actual answer to the player.
# Trac... | true |
2a29710b1ce51119772ee86b796193f1eec0658a | tzyl/ctci-python | /chapter9/9.1.py | 726 | 4.28125 | 4 | def stair_permutations(n):
"""Returns the number of different ways a child can hop up a staircase
with n steps by hopping 1,2 or 3 steps at a time."""
if n == 0 or n == 1:
return 1
elif n == 2:
return 2
return (stair_permutations(n - 1) +
stair_permutations(n - 2)... | false |
4e51ccfe4bbdf4401dd6c2741d3f2d8ca63ef3c2 | tzyl/ctci-python | /chapter9/9.2.py | 1,672 | 4.125 | 4 | def number_of_paths(X, Y):
"""Returns the number of paths to move from (0, 0) to (X, Y) in an X by Y
grid if can only move right or down."""
if X == 0 or Y == 0:
return 1
return number_of_paths(X - 1, Y) + number_of_paths(X, Y - 1)
def number_of_paths2(X, Y):
"""Solution using mat... | true |
9f8201a7a55fd59dc02cdd24fbd64ee8cd10ebfc | tzyl/ctci-python | /chapter5/5.5.py | 736 | 4.28125 | 4 | def to_convert(A, B):
"""Clears the least significant bit rather than continuously shifting."""
different = 0
C = A ^ B
while C:
different += 1
C = C & C - 1
return different
def to_convert2(A, B):
"""Using XOR."""
different = 0
C = A ^ B
while C:
... | true |
e46c3484f1214958d5f7c4574cb5be85b7336c0c | CharlesA750/practicals_cp1404 | /P5_Email.py | 579 | 4.28125 | 4 | email_dict = {}
def main():
email = input("What is your email address?\n>>> ")
while email != "":
nameget = get_name(email)
name_check = input("Is your name " + nameget + "? (y/n) ").lower()
if name_check == "y":
email_dict[email] = nameget
else:
real_name... | false |
2e925cbed4eaeb10f9f822f1b7600823bf8f0603 | carlosmertens/Python-Introduction | /default_argument.py | 2,221 | 4.59375 | 5 | """ DEFAULT ARGUMENTS """
print("\n==================== Example 1 ====================\n")
def box(width, height, symbol="*"):
"""print a box made up of asterisks, or some other character.
symbol="*" is a default in case there is not input
width: width of box in characters, must be at least 2
height... | true |
e4232c807b730f7419e3b750122c765543747fc8 | pawansingh10/PracticeDemo | /CodeVita/Fibonacci.py | 1,724 | 4.125 | 4 | import math
"""USING RECURSION TIME COMPLEXITY EXPONENTIAL COMPLEXITY SPACE O(N)"""
def fib(n):
if n==0 :
return 0
elif n==1:
return 1
else:
return fib(n-1)+fib(n-2)
"""USING DYNAMIC PROGRAMMING AVOID REPAETED WORK"""
def fibo(n):
fib_list=[0,1]
while len(fib_list)<n+1 :
... | false |
62ce698cea9b770dd6f641a27aec07034898d2e8 | usmanwardag/Python-Tutorial | /strings.py | 1,619 | 4.28125 | 4 | import sys
'''
Demonstrates string functions
'''
def stringMethods():
s = 'Hello, how are you doing?'
print s.strip() #Removes whitespaces
print s.lower()
print s.upper() #Changes case
print s.isalpha()
print s.isdigit()
print s.isspace() #If all characters belong to a class
print s.startswith('H'... | true |
d9c4bbd50b8473f6dc1ad17b3e0fa4ec8ce5c424 | Micky143/LPU_Python | /Functions2.py | 725 | 4.3125 | 4 |
greeting ="hello World.!"
print(greeting)
print(greeting.find('lo')) #output :- 3
print(greeting.replace('llo', 'y')) #output :- hey World.!
print(greeting.startswith('hell')) #output :- True
print(greeting.isalpha()) #output :- False
greeting = "Micky Mehra..!"
print(greeting.lower(... | false |
16d8dd34584e0b7bddc27bd9bddddbea2be24baf | fibeep/calculator | /hwk1.py | 1,058 | 4.21875 | 4 | #This code will find out how much money you make and evaluate whether you
#are using your finances apropriately
salary = int(input("How much money do you make? "))
spending = int (input("How much do you spend per month? "))
saving = salary - spending
#This line will tell you if you are saving enough money to eventual... | true |
7d090650fc7fc908e6a8914310b12878ce38dd80 | SpencerBeloin/Python-files | /factorial.py | 228 | 4.21875 | 4 | #factorial.py
#computes a factorial using reassignment of a variable
def main():
n= eval(input("Please enter a whole number: "))
fact = 1
for factor in range(n,1,-1):
fact = fact*factor
print fact
main()
| true |
02cf43e0fbc8f701a5c57a8f87ee32c6475469d0 | mayad19-meet/meet2017y1lab4 | /fruit_sorter.py | 244 | 4.21875 | 4 | new_fruit=input('what fruit am i storing?')
if new_fruit=='apples':
print('bin 1!')
elif new_fruit=='oranges':
print('bin 2!')
elif new_fruit=='olives':
print('bin 3!')
else:
print('error!! i do not recognize this fruit!')
| false |
0e4b133eba2337b2e30e389d1fe95606bf439233 | annettemathew/rockpaperscissors | /rock_paper_scissors.py | 2,038 | 4.1875 | 4 | #Question 2
# Write a class called Rock_paper_scissors that implements the logic of
# the game Rock-paper-scissors. For this game the user plays against the computer
# for a certain number of rounds. Your class should have fields for how many rounds
# there will be, the current round number, and the number of wins ... | true |
50888ff04c2d2ad05058c3ff77a6a94a2cd93fcf | atulmkamble/100DaysOfCode | /Day 19 - Turtle Race/turtle_race.py | 1,896 | 4.46875 | 4 | """
This program implements a Turtle Race. Place your bet on a turtle and tune on to see who wins.
"""
# Import required modules
from turtle import Turtle, Screen
from random import randint
from turtle_race_art import logo
def main():
"""
Creates turtles and puts them up for the race
:return: nothing
... | true |
d70fb4d40081bda2356d7f9909c5873a7ab3a126 | atulmkamble/100DaysOfCode | /Day 21 - Snake Game (Part 2)/main.py | 1,529 | 4.125 | 4 | """
This program implements the complete snake game
"""
from turtle import Screen
from time import sleep
from snake import Snake
from food import Food
from scoreboard import Scoreboard
def main():
# Setup the screen
screen = Screen()
screen.setup(width=600, height=600)
screen.bgcolor('black')
scr... | true |
cec29c33017cd1b9398ea08710e6ff219a43933c | atulmkamble/100DaysOfCode | /Day 10 - Calculator/calculator.py | 1,736 | 4.21875 | 4 | """
This program implements the classic calculator functionality (Addition, Subtraction, Multiplication & Division)
"""
from calculator_art import logo
def add(n1, n2):
return n1 + n2
def subtract(n1, n2):
return n1 - n2
def multiply(n1, n2):
return n1 * n2
def divide(n1, n2):
return n1 / n2
... | true |
02089de9852f240b5ff07e1ca47e8e41e19537c2 | atulmkamble/100DaysOfCode | /Day 4 - Rock Paper Scissors/rock_paper_scissors.py | 2,029 | 4.3125 | 4 | """
This program is a game of rock, paper and scissors. You and the program compete in this game to emerge as a
winner. The program is not aware of your choice and it's a fair game. Please follow the directions in the program.
"""
from random import randint
from time import perf_counter
from time import process_time
... | true |
f97594ad3514fa073068bc4f54194ab13abeaec3 | duochen/Python-Kids | /Lecture06_Functions/Homework/rock-paper-scissors-game.py | 891 | 4.15625 | 4 | print("Welcome to the Rock Paper Scissors Game!")
player_1 = "Duo"
player_2 = "Mario"
def compare(item_1, item_2):
if item_1 == item_2:
return("It's a tie!")
elif item_1 == 'rock':
if item_2 == 'scissors':
return("Rock wins!")
else:
return("Paper wins!")
elif... | true |
c2abe9e5d0fce7f2cfbb6657e98349b4cfcbd591 | JohannesHamann/freeCodeCamp | /Python for everybody/time_calculator/time_calculator.py | 2,997 | 4.4375 | 4 | def add_time(start, duration, day= None):
"""
Write a function named add_time that takes in two required parameters and one optional parameter:
- a start time in the 12-hour clock format (ending in AM or PM)
- a duration time that indicates the number of hours and minutes
- (optional) a starting day... | true |
e4fc4b53e49fb44be9d4f1a0879948264fbf635d | prasannarajaram/python_programs | /palindrome.py | 340 | 4.6875 | 5 | # Get an input string and verify if it is a palindrome or not
# To make this a little more challenging:
# - Take a text input file and search for palindrome words
# - Print if any word is found.
text = raw_input("Enter the string: ")
reverse = text[::-1]
if (text == reverse):
print ("Palindrome")
else:
print... | true |
f993283ec857e4843cc6ea403a19b95669c2d437 | paulacaicedo/TallerAlgoritmos | /ejercicio35.py | 800 | 4.125 | 4 |
#EJERCICIO 35
numero_1=int(input("Introduzca un primer valor: "))
numero_2=int(input("Introduzca un segundo valor: "))
numero_3=int(input("Introduzca un tercer valor: "))
#NUMERO MAYOR
if numero_1>numero_2 and numero_1>numero_3:
print("El numero mayor es: ",numero_1)
if numero_2>numero_1 and numero_2>numero_... | false |
9fbf936bdf5c6f4798aa4ce97146394de3dadc40 | evanmiracle/python | /ex5.py | 1,230 | 4.15625 | 4 | my_name = 'Evan Miracle'
my_age = 40 #comment
my_height = 72 #inches
my_weight = 160 # lbs
my_eyes = 'brown'
my_teeth = 'white'
my_hair = 'brown'
# this works in python 3.51
print("Test %s" % my_name)
# the code below only works in 3.6 or later
print(f'Lets talk about {my_name}.')
print(f"He's {my_heigh... | true |
5204daaef67721495cd2bf137d21ff70c374b393 | adeshshukla/python_tutorial | /loop_for.py | 719 | 4.15625 | 4 | print()
print('--------- Nested for loops---------')
for i in range(1,6):
for j in range(1,i+1):
print(j, end=' ') # to print on the same line with space. Default it prints on next line.
#print('\t')
print()
print('\n') # to print two lines.
print('-------- For loop In a tuple with break ----------------')
# f... | true |
ca0e358ea678b2c375709e2efb286194b58cc697 | Annie677/me | /week3/exercise3.py | 2,483 | 4.40625 | 4 | """Week 3, Exercise 3.
Steps on the way to making your own guessing game.
"""
import random
def not_number_rejector(message):
while True:
try:
your_input = int(input(message))
print("Thank you, {} is a number.".format(your_input))
return your_input
except:
... | true |
10054b21be49bc24ea3b3772c97c116bf425533b | L51332/Project-Euler | /2 - Even Fibonacci numbers.py | 854 | 4.125 | 4 | '''
Problem 2
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued... | true |
ed2527878b79f75db82f16c90f223922834bd933 | Joyojyoti/intro__to_python | /using_class.py | 618 | 4.21875 | 4 | #Defining a class of name 'Student'
class Student:
#defining the properties that the class will contain
def __init__(self, name, roll):
self.name = name
self.roll = roll
#defining the methods or functions of the class.
def get_details(self):
print("The Roll number of {} is {}.".format(self.name, self.ro... | true |
864a01eb4152e25e30a64bbbaafa2385f0e9fea4 | zbs881314/Deeplearning | /regression4LP.py | 848 | 4.28125 | 4 | # Linear regression example: linear prediction
# for Lecture 7, Exercise 7.2
import numpy as np
import matplotlib.pyplot as plt
## generated training data set with model x(i)=a x(i-1)+ e(i)
N=5000 # total number of training data
a=0.99
ei=np.random.randn(N)*np.sqrt(0.02) # generate e(n)
xi=np.zeros((N),dtype=np.floa... | false |
0df7f56ad62d036dee1dc972a5d35984cfebcbec | snpushpi/P_solving | /preorder.py | 1,020 | 4.1875 | 4 | '''
Return the root node of a binary search tree that matches the given preorder traversal.
(Recall that a binary search tree is a binary tree where for every node, any descendant of node.left has a value < node.val, and any descendant of node.right has a value > node.val. Also recall that a preorder traversal display... | true |
c4cd3e7b687b65968f2863e2e19fb4fa303d4612 | snpushpi/P_solving | /1007.py | 1,356 | 4.125 | 4 | '''
In a row of dominoes, A[i] and B[i] represent the top and bottom halves of the i-th domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.)
We may rotate the i-th domino, so that A[i] and B[i] swap values.
Return the minimum number of rotations so that all the values in A are the ... | true |
602dd4b4552f050d3e799cc9bc76fc3816f40358 | snpushpi/P_solving | /next_permut.py | 1,499 | 4.1875 | 4 | '''
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
The replacement must be in-place and use only constant extra memory.
Here a... | true |
82d7b5ebca2d850aea48cc1a4719ef53f7bd09de | snpushpi/P_solving | /1041.py | 1,536 | 4.25 | 4 | '''
On an infinite plane, a robot initially stands at (0, 0) and faces north. The robot can receive one of three instructions:
"G": go straight 1 unit;
"L": turn 90 degrees to the left;
"R": turn 90 degress to the right.
The robot performs the instructions given in order, and repeats them forever.
Return true if and o... | true |
9b6d023f110699aee047ab231e17a18989abd40d | snpushpi/P_solving | /search.py | 906 | 4.15625 | 4 | '''
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,0,1,2,2,5,6] might become [2,5,6,0,0,1,2]).
You are given a target value to search. If found in the array return true, otherwise return false.
Example 1:
Input: nums = [2,5,6,0,0,1,2], target = 0
Output: t... | true |
b6f17ceaebb3d8e846272eff1313a09e13cefe84 | Zahidsqldba07/codesignal-20 | /FamilyGroup.py | 2,338 | 4.375 | 4 | # -*- coding: utf-8 -*-
"""
We’re working on assembling a Game of Thrones family tree.
Example:
Mad King Rickard
/ \ / \
Daenerys Rhaegar Lyanna Ned Catelyn
\ / \ /
Jon Arya
Write a function that returns three collections:
-Peo... | false |
b9401748ab04808e5587cec3d3280ae95a10752b | Guimbo/Pesquisa_Ordenacao | /Heap Sort.py | 1,213 | 4.21875 | 4 | #Heap Sort
#Princípio: Utiliza uma estrutura de dados chamada heap, para ordenar os elementos
#à medida que os insere na estrutura. O heap pode ser representado como uma árvore
#ou como um vetor.
#Complexidade no melhor e no pior caso: O(n log2n) é o mesmo que O(n lgn)
from RandomHelper import random_list
def heapSo... | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.