blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
b073e30fb0c7b43e61845de6a0cb50ea6fe1d4f0 | Benature/Computational-Physics-Course-Code | /chp9/随机数/布朗运动1d.py | 1,082 | 4.25 | 4 | # 参考答案
# random walk,随机行走
import matplotlib.pyplot as plt
import random as rd
# %matplotlib inline
nsteps = 100 # input('number of steps in walk -> ')
nwalks = 100 # input('number of random walks -> ') 粒子数
seed = 10 # input('random number seed -> ')
rd.seed(seed)
steps = range(nsteps)
xrms = [0.0] * nsteps # mean ... | true |
0bb48e09dcbde0d8d604075bf650e9f2c42e9570 | jezzicrux/Python-Alumni-Course | /Excercises/inclass9_16.py | 508 | 4.28125 | 4 | #Making a function the adds three number and divdes by 3. (Pretty much average)
#This the function to get the average of the three numbers
avg = 0
def average(x,y,z):
avg=(x+y+z)/3
print(f"The average the three numbers is {avg}.")
def getting_numbs():
print ("Please enter your first number")
x = int(in... | true |
ef1b85d6df36bc6b251b94edd51c27c019bc63ec | jezzicrux/Python-Alumni-Course | /Excercises/triangle.py | 992 | 4.25 | 4 | def main():
print(f"Welcome to the triangle finder program")
print(f"Please enter 3 values for each side.")
print(f"Enter in value for side 1")
side1 = int(input(">> "))
print(f"Enter in value for side 2")
side2 = int(input(">> "))
print(f"Enter in value for side 3")
side3 = int(input(">... | true |
17a546db017b9abc0b1853b1df5137167e6fb795 | jezzicrux/Python-Alumni-Course | /Excercises/HW1.py | 837 | 4.34375 | 4 | #a message stating it going to count the number on chickens
print("I will now count my chickens:")
#number of hens
print("Hens", 25 + 30 / 6)
#number of roosters
print("Roosters", 100 - 25 * 3 % 4)
#a message counting the number of eggs
print("Now I will count the eggs:")
#The math for calculating the number of eggs
pr... | true |
fb8125f73e2825f92d99ac10951cf857e8be7239 | jaredmckay17/DataStructuresAlgorithmsPractice | /binary_search.py | 1,120 | 4.125 | 4 | # Non-recrusive implementation
def binary_search(input_array, value):
first = 0
last = len(input_array) - 1
while first <= last:
midpoint = (first + last) // 2
if input_array[midpoint] == value:
return midpoint
else:
if value < input_array[midpoint]:
last ... | true |
622fcca8ab5f8c6c280f6ec1c75df9ff52f81e07 | sumforest/first_python | /test_repr_str_format.py | 563 | 4.15625 | 4 | # 输入一个立方表
for x in range(1,11):
print(repr(x).rjust(2),repr(x*x).rjust(3),end=' ')
print(repr(x*x*x).rjust(4))
for x in range(1,11):
print('{0:2d} {1:3d} {2:4d}'.format(x,x*x,x*x*x))
# 在:后面跟数字可以保证宽度
table = {'Google':1,'Runoob':2,'Alibaba':3}
for k,v in table.items():
print('{0:10}===>{1:10}'.format(... | false |
f3f08d4b739c4993a6597060d8e8b66340b4d514 | sumforest/first_python | /列表-列表推导式.py | 587 | 4.15625 | 4 | # 将列表中每个数值乘三,获得一个新的列表:
vec = [3,6,9]
print([x*3 for x in vec])
# 得到一个嵌套列表
print([[x,x*2] for x in vec])
# 对序列里每一个元素逐个调用某方法:
freshfruit = [' banana', ' loganberry ', 'passion fruit ']
print([fruit.strip() for fruit in freshfruit])
# 使用if做过滤条件
print([x for x in vec if x > 3])
# 循环和其它技巧的演示:
vec1 = [1,2,3]
vec2 = [2... | false |
f791702e716e22da1327780cbc9e272648b5c2b8 | justinmyersdata/ProjectEuler | /7_Project_Euler.py | 607 | 4.25 | 4 |
def isprime(x):
'''Returns True if x is prime and false if x is composite'''
if x == 1:
return False
elif x == 2:
return True
elif x % 2 == 0:
return False
else:
for y in range(3,int(x**(1/2))+1,2):
if x % y == 0: ... | true |
ab65d41474186820587e216e5c91617621b599c2 | amitshipra/PyExercism | /recursion/examples.py | 743 | 4.28125 | 4 | __author__ = 'agupt15'
# Source: http://www.python-course.eu/python3_recursive_functions.php
#
#
#
#
# ## Example 1
#
# Write a recursive Python function that returns the sum of the first n integers.
###
def rec_add(num):
if num == 1:
return 1
return num + rec_add(num - 1)
print(rec_add(10))
### ... | true |
4350d764af0961abc44c2adb1c54d4d8173dd403 | srikanthpragada/pythondemo_21_june_2019 | /oop/gen_demo.py | 269 | 4.125 | 4 | # Generator to yield even number from start to end
def even_numbers(start, end):
if start % 2 != 0:
start = start + 1
for n in range(start, end + 1, 2):
yield n
print(type(even_numbers(10, 20)))
for n in even_numbers(11, 21):
print(n)
| false |
5bea9d32a0f174543c3d734002f8e856d6ac6279 | gurkiratsandhu/Assignment_Daily | /assignment7 (1).py | 1,521 | 4.15625 | 4 | #(Q.1)- Create a function to calculate the area of a circle by taking radius from user.
def area():
pi = 3.14
radius = float(input("enter radius: "))
area = pi*radius**2
print("Area of a circle = ",area)
area()
#(Q.2)- Write a function “perfect()” that determines if parameter number is a perfect number.
#Us... | true |
8263b10b5c958eb40ebc8c67a4aafecf5b18a6f8 | rhysJD/CC1404_Practicals | /Prac 2/exceptions_demo.py | 785 | 4.21875 | 4 | """
CP1404 - Practical 2
Rhys Donaldson
"""
try:
numerator = int(input("Enter the numerator: "))
denominator = int(input("Enter the denominator: "))
while denominator == 0:
denominator = int(input("Denominator cannot be zero. PLease enter a new number: "))
fraction = numerator / denominator
... | true |
685f5b4ead65493c2689d479df91bbc9af93aa0c | kiwi-33/Programming_1_practicals | /p12-13/p12p3(+pseudo).py | 639 | 4.28125 | 4 | '''define function for getting approx square root
prompt for input and convert to float
check if greater than 0
call function with (input, self selected tolerance)
else print message'''
def sq(number, epsilon):
root = 0.0
step = epsilon**2
while abs(number-root**2) >= epsilon and root <= number:
ro... | true |
ddb2f13ed4d056934a51cdc65a58aa3c7eabe411 | kiwi-33/Programming_1_practicals | /p14-15/p15p3.py | 568 | 4.1875 | 4 | '''define the function
prompt for input
enter while loop:
enter for loop, limit = input:
print statement that shows progression towards the base case and calls function
prompt for input'''
def series(x):
if x == 0:
return 13
elif x == 1:
return 8
else:
return((series... | true |
68390cc2272a00e24b578960ba52c76c1a3265e4 | Kadus90/CS50 | /pset6/mario/less/mario.py | 899 | 4.21875 | 4 | from cs50 import get_int
def main():
# Get an integer between 1 - 8
height = get_positive_int("Height: ")
# Print bricks
print_bricks(height)
def get_positive_int(prompt):
# Use get_int to get an integer from the user
n = get_int(prompt)
# While not in the proper range
while n < 1 or... | true |
ccb9824ec5d7ffeeb123b86914383d174eb63e03 | alcoccoque/Homeworks | /hw5/ylwrbxsn-python_online_task_5_exercise_2/task_5_ex_2.py | 692 | 4.5625 | 5 | """
Task05_2
Create function arithm_progression_product, which outputs the product of multiplying elements of arithmetic progression sequence.
The function requires 3 parameters:
1. initial element of progression - a1
2. progression step - t
3. number of elements in arithmetic progression sequence - n
Example,
... | true |
a0716844aecf22b76731ae339ea52037ba170bb9 | alcoccoque/Homeworks | /hw10/ylwrbxsn-python_online_task_10_exercise_3/task_10_ex_3.py | 2,102 | 4.375 | 4 | """
File `data/students.csv` stores information about students in CSV format.
This file contains the student’s names, age and average mark.
1. Implement a function get_top_performers which receives file path and
returns names of top performer students.
Example:
def get_top_performers(file_path, number_of_top_st... | true |
28c998e30f41f350345d22934294b93fda8f3dc2 | alcoccoque/Homeworks | /hw9/ylwrbxsn-python_online_task_9_exercise_4/task_9_ex_4.py | 2,094 | 4.28125 | 4 | """
Implement a bunch of functions which receive a changeable number of strings and return next
parameters:
1) characters that appear in all strings
2) characters that appear in at least one string
3) characters that appear at least in two strings
Note: raise ValueError if there are less than two strings
4) ch... | true |
d5b3eb35448994bbe027230cf715f633e3bbef90 | alcoccoque/Homeworks | /hw4/ylwrbxsn-python_online_task_4_exercise_8/task_4_ex_8.py | 638 | 4.1875 | 4 | """
Task 04-Task 1.8
Implement a function which takes a list of elements and returns a list of tuples containing pairs of this elements.
Pairs should be formed as in the example. If there is only one element in the list return `None`
instead.
Using zip() is prohibited.
Examples:
>>> get_pairs([1, 2, 3, 8, 9])
... | true |
0039bfc1dae3f74a8116973fade7541d37435561 | mandypepe/py_data | /spark_querin_dataset.py | 1,071 | 4.1875 | 4 | # First we need to import the following Row class
from pyspark.sql import SQLContext, Row
# Create a RDD peopleAge,
# when this is done the RDD will
# be partitioned into three partitions
peopleAge = sc.textFile("examples/src/main/resources/people.txt")
# Since name and age are separated by a comma let's split them
par... | true |
2a51577b5291d2667e285d799a1cb47d0dec5c88 | lunawarrior/python_book | /Exercises/6/1_turn_clockwise.py | 721 | 4.28125 | 4 |
'''
This is the first exercise in chapter 6:
The four compass points can be abbreviated by single-letter strings as “N”, “E”, “S”, and “W”.
Write a function turn_clockwise that takes one of these four compass points as its parameter,
and returns the next compass point in the clockwise direction. Here are some tests... | true |
9f682db0dcc89ab6381271f077388845f204f8ed | Kvazar78/Skillbox | /8_algoritm_for/task_83_3.py | 1,004 | 4.1875 | 4 | # Саша просыпается когда угодно, но в 23 часа уже точно идёт спать.
# Питается Саша следующим образом: каждые 3 часа он выпивает литр воды и
# съедает N калорий. Пить и есть он, кстати, начинает сразу как только
# проснётся. Напишите программу, которая считает сколько он выпьет литров
# воды и сколько калорий он съест ... | false |
b391144829bc43326c3a7be3eef5c7b6ad9e4166 | Kvazar78/Skillbox | /float2/dz/task_9.py | 1,087 | 4.4375 | 4 | # Степень числа
#
# Дано вещественное положительное число a и целоe число n.
#
# Вычислите a в степени n, не используя циклы, возведение в степень через ** и функцию math.pow()
# (да, такая тоже есть). Решение оформите в виде функции power(a, n).
def power(a, n):
if n < (-1):
a *= a
n +=1
po... | false |
d77058dc12856ad93390c6485de970a21e76160c | Kvazar78/Skillbox | /15_list1/task_153_2.py | 1,497 | 4.1875 | 4 | # Соседи
#
# Дана строка S и номер позиции символа в строке. Напишите программу, которая выводит соседей этого символа и сообщение
# о количестве таких же символов среди этих соседей: их нет, есть ровно один или есть два таких же.
#
# Пример 1:
#
# Введите строку: abbc
# Номер символа: 3
#
# Символ слева: b
# Символ сп... | false |
bc799c08a481763510aaa17ef54168892738ff1c | Kvazar78/Skillbox | /18_format_f-strings/task_182_1.py | 963 | 4.21875 | 4 | # Заказ
#
# После того, как человек сделал заказ в интернет-магазине, ему на почту приходит оповещение
# с его именем и номером заказа.
#
# Напишите программу, которая получает на вход имя и код заказа, а затем выводит на экран
# соответствующее сообщение. Для решения используйте строковый метод format.
#
# Пример:
#
#... | false |
8972ce6fcf663435611ff17ecf65bbd40c79a6c3 | Kvazar78/Skillbox | /24_classes/dz/task_3.py | 2,501 | 4.125 | 4 | # Окружность
#
# На координатной плоскости рисуются окружности, у каждой окружности следующие параметры: координаты X и Y центра окружности и значение R ― это радиус окружности. По умолчанию центр находится в (0, 0), а радиус равен 1.
#
# Реализуйте класс «Окружность», который инициализируется по этим параметрам. Круг ... | false |
5cd6b42215512fd27cc989d662e58057a02ee112 | Kvazar78/Skillbox | /float2/dz/task_2.py | 1,419 | 4.125 | 4 | # Генеалогическое древо
#
# Сэм создаёт генеалогические деревья разных семей. Ему постоянно приходится рассчитывать количество
# места, занимаемое именами родителей на экране.
#
# Пользователь вводит имена и фамилии двух родителей. Создайте функцию get_parent_names_total_length
# для Сэма, которая возвращает количество... | false |
daf822d911b62894b775b26a322be393f83163f8 | Kvazar78/Skillbox | /9_for_strings/task_93_2.py | 870 | 4.4375 | 4 | # Ваня экспериментирует с различного рода компьютерными вирусами,
# которые портят жизнь людям. На просторах Интернета он нашёл код довольно
# необычного вируса, который “поворачивает” весь текст в документе и
# повторяет каждый символ 3 раза.
#
# Пользователь вводит текст. Напишите программу, которая выводит каждый
# ... | false |
2ade3194e71fa9dc2ae37377c7aba4f69c98e050 | Kvazar78/Skillbox | /6.3_while_break/dz/task_1.py | 720 | 4.21875 | 4 | # Любителю математики Паше снова стало мало распечатанных табличек,
# включая последнюю со степенями двойки. Теперь он хочет взять третью
# степень чисел от 1 до абсолютно любого!
# Напишите программу, которая возводит в третью степень каждое число
# от 1 до N и выводит результат на экран.
num = int(input('По какое чис... | false |
8ca442198d42b54b5aa4ee8538f72201d50fc491 | anasazi/Swarm-AI---Zombies | /vector.py | 2,572 | 4.25 | 4 | #Alice Forehand
#Robert Pienta
#Eric Reed
from math import acos, sqrt, pi, atan2
class Vector:
"""A simple 2d vector
>>> v1 = Vector(1,0)
>>> v2 = Vector(0,1)
>>> print(v1.add(v2))
(1, 1)
>>> print(v1 + v2)
(1, 1)
>>> print(v1.subtract(v2))
(1, -1)
>>> print(v1 - v2)
(1, -... | false |
b735e871863e7f2fe735293b21f01ea0158bb9d5 | quydau35/quydau35.github.io | /ds/chunk_6/python_modules.py | 2,618 | 4.53125 | 5 | """
# Python Modules\n
What is a Module?\n
Consider a module to be the same as a code library.\n
A file containing a set of functions you want to include in your application.\n
# Create a Module\n
To create a module just save the code you want in a file with the file extension ```.py```:\n
```
# Save this code in a ... | true |
fa096dffbef3c9578b693c3b2c07014a53b94ec6 | sandycamilo/SPD1.4 | /Complexity_Analysis/merge_lists.py | 1,027 | 4.125 | 4 | # Merge two sorted linked lists and return it as a new list.
# The new list should be made by splicing together the nodes of the first two lists.
# Input: 1->2->4, 1->3->4
#Create a new linked list:
# Output: 1->1->2->3->4->4
# O(1)
class Solution(object):
def mergeTwoLists(self, l1, l2):
head = ListN... | true |
62cf7ad9407f66a4a189ae9d8232c10ca64a0043 | capkum/python-calculator | /example/step01.py | 850 | 4.34375 | 4 | '''
example 변수안의 식만을 계산
'''
def calculator(str):
number = []
operation = []
for x in str.replace(' ', ''):
if x.isdigit():
number.append(x)
else:
operation.append(x)
nmbr_len = len(number)
x = int(number[nmbr_len - 2])
y = int(number[nmbr_len - 1])
... | false |
2acf6153ffee5b46504954ea22204254ff1c5ca9 | matamkiran/python2020 | /functions/function_multiplication.py | 298 | 4.25 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jan 31 11:26:26 2021
@author: Divya
"""
def func1(n,l):
for i in l:
print(n ," * ", i,"=",n*i)
number=int(input("Enter the number you wish to display multiplication of table :"))
b=[1,2,3,4,5,6,7,8,9,10]
func1(number,b)
| false |
e85c5ae1101d7e3e25ccd570231e3e04e5e32d74 | JLtheking/cpy5python | /practical03/q1_display_reverse.py | 899 | 4.3125 | 4 | # Filename: q1_display_reverse.py
# Author: Justin Leow
# Created: 19/2/2013
# Modified: 22/2/2013
# Description: Displays an integer in reverse order
##Input a positive integer: 5627631
##1367265
##Input a positive integer: nope
##Input is not an integer. Utilizing default value of 6593
##3956
##Input a positive inte... | true |
bf920db934db1952d9c741ce8e8335a47dae2d0f | JLtheking/cpy5python | /08_OOP/bankaccount.py | 2,339 | 4.3125 | 4 | #bankaccount.py
class Account():
'''Bank account class'''
def __init__(self,account_no,balance):
'''constructor method'''
#double underscore makes it a hidden private attribute
self.__account_no = account_no
self.__balance = balance
def get_account_no(self):
'''accessor method to retrieve account no'... | true |
73b2fa58628caf0682ba2fbcca4d44c25662c460 | JLtheking/cpy5python | /practical01/q1_fahrenheit_to_celsius.py | 634 | 4.25 | 4 | # Filename: q1_fahrenheit_to_celsius.py
# Author: Justin Leow
# Created: 22/1/2013
# Modified: 22/1/2013
# Description: Program which converts an input of temperature in farenheit to an
# output in celcius
# main
while(True):
#get user input farenheit
fInput = input(["Input temperature in farenh... | true |
1e53c2e3e7052d86c164fa4b58c85b266338f01f | KathMoreno/prog-101 | /Python/clases/arrays.py | 845 | 4.1875 | 4 | # Declare array
my_array = ["Luna de miel en familia", "Escuadrón suicida", "Maléfica"]
# Print a value from the array
# print(my_array[1])
# Print all the array
# print(my_array)
# Add item
# my_array.append("Nuestro video prohibido")
# print(my_array)
# Remove item
# my_array.remove("Nuestro video prohibido")
# prin... | false |
bbcd58c87ea0fbc8479ac182e434715e079b37de | NaguBianchi/Workspace | /Integrando_conocimientos/Integracion.py | 1,834 | 4.3125 | 4 | """
Una librería de la ciudad de Carlos Paz requiere de un programa que permita
cargar los montos de todas las ventas realizadas en el mes. Para ello el programa
debe permitir guardar ese valor en una lista.
Se debe generar un menú que permita realizar las siguientes operaciones:
Agregar el monto de una venta.
Mostrar... | false |
cd4121bd09406dad559630f0d16a91eba83fd4fe | NaguBianchi/Workspace | /Estructuras/Clase2_Funciones.py | 1,303 | 4.25 | 4 | """
Parametros o Argumentos
Los Parametros son posicionales y requeridos
Para que los parametros no sean obligatorios se define un parametro por default
Ej:def user_info(nombre, edad, ciudad = "Cordoba"):
En pocas palabras, son valores que se reciben en una funcion a traves de los parentesis
"""
# def user_info(nombre... | false |
af47a62770895f3239b6a0505b1cce9509a903ad | mmutiso/digital-factory | /darts.py | 773 | 4.28125 | 4 | import math
def square(val):
return math.pow(val,2)
def score(x, y):
'''
Give a score given X and Y co-ordinates
Rules
X range -10,10
Y range -10, 10
The problem is finding the radius of the circle created by a given point x,y
then compare if the point is inside the circle using pythag... | true |
d239595956f2ebdd76d628be8aae6892ba43e352 | Andeleisha/dicts-restaurant-ratings | /ratings.py | 1,534 | 4.15625 | 4 | """Restaurant rating lister."""
# put your code here
def build_dict_restaurants(filename, dictionary):
"""Takes a file and creates a dictionary of restaurants as keys and ratings as values"""
with open(filename) as restaurant_ratings:
for line in restaurant_ratings:
line = line.strip()
line = line.split(... | true |
f12370d769339351a1e01eb6189c6e45914fbd67 | sukritishah15/DS-Algo-Point | /Python/armstrong_number.py | 585 | 4.1875 | 4 | n = int(input())
l = len(str(n))
s = 0
temp = n
while temp > 0:
s += (temp%10) ** l
temp //= 10
if n == s:
print("Armstrong number")
else:
print("Not an armstrong number")
'''
Check whether a number entered by the user is Armstrong or not.
A positive integer of n digits is called an Armstrong Number ... | true |
ec34d801bf68c970a600d37ae6cc5a6e04fee1f6 | sukritishah15/DS-Algo-Point | /Python/majority_element.py | 733 | 4.375 | 4 | # Python problem to find majority element in an array.
def majorityElement(nums, n):
nums.sort()
for i in range(0, n):
if(i+int(n/2)) < n and nums[i] == nums[i+int(n/2)]:
return nums[i]
return None
n = int(input("Enter the total number of elements\n"))
print('Enter a list of '+str(n)... | true |
c1d8ba9a81d785d6a77de20d075150f371825ba7 | sukritishah15/DS-Algo-Point | /Python/automorphic.py | 423 | 4.125 | 4 | # Automorphic Number: The last digits of thr square of the number is equal to the digit itself
n=int(input("Enter the number: "))
sq= n**2
l=len(str(n))
ld=sq%pow(10,l)
if (ld==n):
print("Automorphic Number")
else:
print("Not a automorphic number")
"""
I/O
Enter the number: 25
Automorphic Numbe... | true |
ccfe5912c428bbaf377448c3b4961ce2d3c4e838 | sukritishah15/DS-Algo-Point | /Python/inordder.py | 608 | 4.28125 | 4 | class Node:
def __init__(self,key):
self.left = None
self.right = None
self.val = key
def printInorder(root):
if root:
printInorder(root.left)
print(root.val),
printInorder(root.right)
root = Node(1)
root.left = Node(2)
root.right = N... | true |
00d927ab9488e3d8954720d71ee8272394f99739 | sukritishah15/DS-Algo-Point | /Python/harmonic.py | 372 | 4.3125 | 4 | # Sum of harmonic series
def sumHarmonic(n):
i = 1
sum = 0.0
for i in range(1, n+1):
sum = sum + 1/i;
return sum;
n = int(input("First term :"))
print("Sum of the Harmonic Series :", sumHarmonic(n))
""""
Example:
First term :
6
Sum of the Harmonic Series : 2.4499999999999997
.........
Time... | true |
aabf2577bd44425c702d6a670ba21dcef79c4aa0 | dboldt7/PRG105 | /Banana revised.py | 1,207 | 4.21875 | 4 | """"
Banana Bread Recipe:
2 cups of flour
1 teaspoon of baking soda
0.25 teaspoons of salt
0.5 cups of butter
0.75 cups of brown sugar
2 eggs
2.33 bananas
Recipe produces 12 servings of bread
Write a program that asks the user how many servings they want
Program displays the ingredients needed to make the ... | true |
4d58fd2658087cccd782b2b14f05ed2e5cd138fc | dboldt7/PRG105 | /lesson 5.2 logic.py | 988 | 4.25 | 4 | number = int(input("Enter a whole number between 20 and 100 "))
def divide_two(num):
if num % 2 == 0:
print(num, "is divisible by 2")
else:
print(num, "is not divisible by 2")
def divide_three(num):
if num % 3 == 0:
print(num, "is divisible by 3")
else:
... | false |
c3920afa242227c20a26747c5903249ca2fb2687 | AliMazhar110/Python-Projects | /Guess-a-number/main.py | 1,575 | 4.1875 | 4 | #Number Guessing Game Objectives:
from art import logo
import random
from os import system
# 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 answ... | true |
29e98b11111eb495b5c71f6e308abcb03881273c | dilciabarrios/Curso-Python | /5_Tipos_datos_avanzados/al_turron1.py | 1,478 | 4.125 | 4 | #Tenemos una lista con nombres de ciudades
ciudadesDeEspaña = ['Granada','Cordoba','Santiago de Compostela','Paris','Malagá', 'Barcelona']
otrasCiudades = ['Toledo','Sevilla','Cadiz','Berlin','Alicante']
#Tareas
# 1- Quitar de la listas las ciudades que no pertezcan a España (Berlin y Paris)
# 2- Unir ambas listas e... | false |
f3dccd370b40a781ab0854040305fa7415609131 | dilciabarrios/Curso-Python | /9_Funciones/al_turron.py | 1,698 | 4.34375 | 4 | #Objetivo: dividir las diferentes operaciones en funciones:
#Ademas, añadir:
#Una comprobacion que nos diga si el numero par o impar
#Una comprobacion que nos diga si el numero es primo o no
def ComprobarSiEsPar (numero):
if (numero % 2 == 0):
return True
else:
return False
def ComprobarMultip... | false |
1147112c2a786e7e1c20436914cbe043db9b97dc | dilciabarrios/Curso-Python | /12_Debug/al_turron.py | 986 | 4.40625 | 4 | print('Bienvenido al sistema de almacenamiento de usuarios.')
usuarios = ['Juan','Marta','Miguel','Elisa','Claudia','Jorge','Ana','Pedro']
while(True):
print('''---
¿Qué operación deseas realizar?
1 - Ver una lista de usuarios
2 - Añadir un usuario
3 - Eliminar un usuario
X - Salir del programa... | false |
357c290a2c2ab8f2ce0e8da3552084d3f4218518 | leofoch/PY | /ManejoDeCadenas.py | 494 | 4.15625 | 4 | #documentacion en: http://pyspanishdoc.sourceforge.net/lib/module-string.html
#nombreUsuario=input("intro nombre: ")
#print("El nombre es: ", nombreUsuario.upper())
#print("El nombre es: ", nombreUsuario.capitalize())
edad=input("intro Edad: ")
while(edad.isdigit()==False):
print("No es numerico")
edad=input... | false |
db509bc5c514d48ea0dfcfd2b0445bd8879e87a3 | PacktPublishing/-Python-By-Example | /Section 1/Section1/Video2_Nesting_Python_dicts_2_vehicles.py | 784 | 4.15625 | 4 | '''
Created on Mar 30, 2018
@author: Burkhard A. Meier
'''
from pprint import pprint
cars = {}
car_1 = {'make': 'BMW', 'speed': 'fast'}
car_2 = {'make': 'Mercedes', 'speed': 'good'}
car_3 = {'make': 'Porsche', 'speed': 'very fast'}
cars['car 1'] = car_1
cars['car 2'] = ca... | false |
233d0067b828c7d7a12c6fd0d7c8e5f2f3d5476a | Elyseum/python-crash-course | /ch9/car.py | 1,512 | 4.25 | 4 | """ Modifying class state """
class Car():
""" Simple car """
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
""" Formatting a descriptive name """
long_na... | true |
92eaf41e7093c52216487e96553cb00fb0b17cc5 | Elyseum/python-crash-course | /ch8/formatted_name.py | 788 | 4.25 | 4 | """
Return values
"""
def get_formatted_name(first_name, last_name):
""" Returns a full name, neatly formatted"""
full_name = first_name + ' ' + last_name
return full_name.title()
MUSICIAN = get_formatted_name('jimi', 'hendrix')
print(MUSICIAN)
def get_formatted_name_2(first_name, last_name, middle_n... | false |
f21caae41042f33a4a60ea9ebcc8211b85d62bd2 | jormao/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/3-say_my_name.py | 939 | 4.4375 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
This module have a function that prints My name is <first name> <last name>
prototype: def say_my_name(first_name, last_name=""):
"""
def say_my_name(first_name, last_name=""):
""" function that prints My name is <first name> <last name>
first_name and last_nam... | true |
48af3a3a7920e8b0fc67cca325cc3d1305db77d1 | PureWater100/DATA-690-WANG | /ass_2/ass2.py | 1,413 | 4.21875 | 4 | # python file for assignment 2
# code from the jupyter notebook
user_inputs = []
MAX_TRY = 11
for i in range(1, MAX_TRY):
while True:
try:
user_input = input("Please enter an integer:")
in_input = int(user_input)
break
except:
print("Please retry (... | true |
5c3e03c9ec8a0c41e68d542f959098169adf612f | selvendiranj-zz/python-tutorial | /hello-world/exceptions.py | 2,018 | 4.3125 | 4 | """
Python provides two very important features to handle any unexpected error in your Python programs
and to add debugging capabilities in them
Exception Handling
Assertions
"""
def KelvinToFahrenheit(Temperature):
assert (Temperature >= 0), "Colder than absolute zero!"
return ((Temperature - 273) * 1.8) +... | true |
b1cff2e2be5fc5b3c99833102c7382dbe6efe8af | Loser-001/p_008 | /chap6/demo14.py | 564 | 4.15625 | 4 | #位 置:南京邮电大学
#程 序 员:邱礼翔
#开发时间:2020/10/29 19:20
a=20
b=100 #两个整数类对象的相加操作
c=a+b
d=a.__add__(b)
print(c)
print(d)
class Student:
def __init__(self,name):
self.name=name
def __add__(self, other):
return self.name+other.name
def __len__(self):
return len(self.name)
stu1=Student('张三')
s... | false |
fc2a1870e98be5abae3b215fc719125eae7ccedf | Loser-001/p_008 | /chap4/demo5.py | 624 | 4.1875 | 4 | #位 置:南京邮电大学
#程 序 员:邱礼翔
#开发时间:2020/10/25 16:09
'''
for item in 'python':
print(item)
for i in range(10):
pass
print(i)
for _ in range(5):
print('人生苦短,我用python')
sum=0
for j in range(1,101):
if j%2==0:
sum=sum+j
print(sum)
'''
a=135
print(int(a/100))
print(int(a/10%10))
print(a%10)
'''输出a100... | false |
c16a4d2cb51863a144f5a9e33c46467620b8abd9 | LogSigma/unipy | /docstring.py | 916 | 4.5 | 4 | def func(*args, **kwargs):
"""
Summary
This function splits an Iterable into the given size of multiple chunks.
The items of An iterable should be the same type.
Parameters
----------
iterable: Iterable
An Iterable to split.
how: {'equal', 'remaining'}
The method to sp... | true |
9d07ce046e2c46a928da07c2d6578f7e91d1df9b | kristinamb15/cracking-the-coding-interview | /1_ArraysStrings/1.4.py | 1,286 | 4.15625 | 4 | # 1.4 Palindrome Permutation: Given a string, write a function to check if it is a permutation of a palindrome.
# The palindrome does not need to be limited to just dictionary words.
# You can ignore casing and non-letter characters.
import unittest
# Solution 1
# O(N)
def palindrome_perm(mystring):
mystring = my... | true |
eaac82b9fe0a9bb5eff99d38a3d75cfa23e3cdc6 | jorgepdsML/Threads_Projects_Python | /threading_sub_class_example2/threading_sub_class_python.py | 1,093 | 4.21875 | 4 | """
uso del modulo threading mediante la definición de una sub_clase
la herencia viene de la clase base Thread
"""
import threading
import time
class BThread(threading.Thread):
#atributo de clase
Nthread=0
#overriding el método __init__()
def __init__(self,name="braintels"):
#invocar ... | false |
616067b46918e0940fcf1805d8e3ae12ab0bbf2f | ShehabAhmedSayem/Rosalind-Chapterwise | /Chapter 1/ba1a.py | 691 | 4.15625 | 4 | # Problem Name: Compute the Number of Times a Pattern Appears in a Text
def read_input_from_file(file_name):
with open(file_name, 'r') as file:
string = file.readline().strip()
pattern = file.readline().strip()
return string, pattern
def occurrence(string, pattern):
"""
string... | true |
f8b875595f336a2d7ad29db2b2f6051f5340f82d | Cmartis/pythonsrc | /examples/automate/ch05_01.py | 555 | 4.28125 | 4 | birthdays = {'rachel':'26th Sept 2006', 'ryan':'9th Jan 2003', 'chris':'28th Jan 1973', 'medha':'8th Sep 1973', 'rita':'14th July 1940'}
while True:
print('enter a name: (blank to quit]')
name = input()
if name == '':
break
if name in birthdays:
print(birthdays[name] + ' is the birthda... | false |
864401be5d0d0ba69503da811f67cebe37edbaa4 | Mustafa-Filiz/HackerRank--Edabit--CodeWars | /Codewars_12_ROT13.py | 1,234 | 4.65625 | 5 | # ROT13
"""
ROT13 is a simple letter substitution cipher that replaces a letter with the letter 13 letters after it in the alphabet. ROT13 is an example of the Caesar cipher.
Create a function that takes a string and returns the string ciphered with Rot13. If there are numbers or special characters included in the str... | true |
d8ad0945acb41da09f474325b940b6b289bd91ad | newemailjdm/intro_python | /121515/conditional.py | 337 | 4.21875 | 4 |
first_name = input("What's your first name")
name_length = len(first_name)
if name_length > 10:
print("That's a long name!")
elif name_length > 3:
print("Nice, that's a name of medium length.")
elif name_length == 3:
print("That's a short name.")
else:
print("Are you sure those aren't ... | true |
83a1611d3673951ca106228ea3b28e55c97a85b1 | AnkurPokhrel8/LinkedList | /LinkedList.py | 2,012 | 4.28125 | 4 | # -*- coding: utf-8 -*-
"""
@author: Ankur Pokhrel
"""
class Node: # Node class
def __init__(self, data):
self.data = data
self.next = None
class LinkedList: # Linkedlist class
def __init__(self):
self.head = None
def addNode(... | true |
6243bfacd386b76e0bf1fb38183e40bba96c48d9 | jmason86/python_convenience_functions | /lat_lon_to_position_angle.py | 982 | 4.1875 | 4 | import numpy as np
def lat_lon_to_position_angle(latitude, longitude):
"""Function to translate heliocentric coordinates (latitude, longitude) into position angle
Written by Alysha Reinard and James Paul Mason.
Inputs:
longitude [float]: The east/west coordinate
latitude [float]: The nort... | true |
7a9c22cdc58108bf175cc08bcd9a63b069caec0c | hadesLiu/python100d | /day08-面向对象编程基础/circle.py | 1,412 | 4.3125 | 4 | # -*- coding: utf-8 -*-
# @Author : hiro,
# @Mail : hiroliu@yeah.net
# @FileName: circle.py
# @Time : 2019/6/3 7:27 PM
"""
练习
修一个游泳池 半径(以米为单位)在程序运行时输入 游泳池外修一条3米宽的过道
过道的外侧修一圈围墙 已知过道的造价为25元每平米 围墙的造价为32.5元每米
输出围墙和过道的总造价分别是多少钱(精确到小数点后2位)
Version: 0.1
Author: 骆昊
Date: 2018-03-08
"""
from math import pi
class Circ... | false |
94418a9660befad407049a9b6b6c3e3708c3e394 | LogicPenguins/BeginnerPython | /Udemy Course/HW Funcs & Methods/exer3.py | 444 | 4.375 | 4 | # Write a Python function that accepts a string and calculates the number of upper case
# and lowercase letters.
def case_info(string):
num_upper = 0
num_lower = 0
for char in string:
if char.islower():
num_lower += 1
elif char.isupper():
num_upper += 1
print(f'U... | true |
d79574835a4f1924c0d5fc4160cb3e31788aba42 | madhuri-bh/DSC-assignmentsML-AI | /Python1.py | 572 | 4.25 | 4 | movieEntered = input("Enter a movie")
thriller=["Dark","Mindhunter","Parasite","Inception","Insidious","Interstellar","Prison Break","MoneyHeist","War","Jack Ryan"]
comedy=["Friends","3 Idiots","Brooklyn 99","How I Met Your Mother","Rick And Morty","The Big Bang Theory","TheOffice","Space Force"]
movieEntered = movi... | true |
2e045de83fd7aa18e3e13758215025950768c1d8 | sushtend/100-days-of-ml-code | /code/basic python in depth/11 logical operator.py | 202 | 4.15625 | 4 | name = "Abdul Kalam"
if not name:
print("1st name is empty")
name = ""
if not name:
print("2nd name is empty")
# Chaining comparison operator
age = 25
if 18 <= age <= 25:
print("Eligible")
| false |
6c8326308e4df9e5a607376b8ccf1c68a1ba6478 | sushtend/100-days-of-ml-code | /code/basic python/13.5 guessing game.py | 361 | 4.1875 | 4 | Guess_count=1
guess=9
print("+++++ This program lets you guess the secret number +++++")
while Guess_count<=3:
num = int(input("Gues the number: "))
if guess==num:
print("Correct")
#exit()
break
Guess_count+=1
# Else for while loop evaluates after completion of all loops without brt... | true |
a957102ba9b196c13b102ecdf02e81ed94796a8b | sushtend/100-days-of-ml-code | /code/basic python in depth/21 sets.py | 1,367 | 4.5 | 4 | # https://realpython.com/python-sets/
#
numbers = [1, 2, 3, 4]
first = set(numbers)
second = {1, 5}
print(first | second) # Uniion
print(first & second) # Intersection
print(first - second) # Differece
print(first ^ second) # semantic difference. Items in either a or b but not both
# ----------------------------... | true |
635a67a18e9542866a68fc362ecc2941069da6e1 | jinm808/Python_Crash_Course | /chapter_4_working_w_lists/pracs.py | 1,661 | 4.5625 | 5 | '''
4-1: Pizzas
Think of at least three kinds of your favorite pizza.
Store these pizza names in a list, and then use a for loop to print the name of each pizza.
Modify your for loop to print a sentence using the name of the pizza instead of printing just the name of the pizza.
For each pizza you should have one lin... | true |
cab02298ed5b609d152d734f11416bf9442792f8 | jinm808/Python_Crash_Course | /chapter_8_functions/user_album.py | 712 | 4.21875 | 4 | def make_album(artist_name, album_title, tracks = 0):
"""Build a dictionary describing a music album."""
album_dict = {
'artist' : artist_name.title(),
'album' : album_title.title()
}
if tracks:
album_dict['tracks'] = tracks
return album_dict
print("Enter 'q' at any time to stop.")
while True:... | true |
2fc1a9a57b5e8713e1fd8b231289656d1838e32c | wandingz/daily-coding-problem | /daily_coding_problem61.py | 1,695 | 4.28125 | 4 | '''
This problem was asked by Google.
Implement integer exponentiation. That is, implement the pow(x, y) function, where x and y are integers and returns x^y.
Do this faster than the naive method of repeated multiplication.
For example, pow(2, 10) should return 1024.
'''
class Solution:
def powNaive(self, a, b)... | true |
5503d10bbcf8a15a7e6e4d4e1becb769f87839d1 | glemvik/Knowit_julekalender2017 | /Luke11.py | 2,087 | 4.375 | 4 | # -*- coding: utf-8 -*-
from time import time
from math import sqrt
def mirptall(primes):
"""
Returns all positive 'mirptall' smaller than 'number', where 'mirptall' are
primes which are also primes when the digits are reversed without being
palindromes.
"""
# INITIALIZE
... | true |
db545519dc14cf85b7b0a0b7c146974958756205 | pipa0979/barbell-squats | /Singly Linked List/Insertion/LL-Insertion-end.py | 1,746 | 4.28125 | 4 | # Purpose - to add node to the end of the list.
class Node(object):
def __init__(self, val):
self.data = val
self.next = None
class LinkedList(object):
# Head, Tail in a new LL will point to None
def __init__(self):
self.head = None
self.tail = None
... | true |
8d90eb725e1b93cafb1f814f531052d52f7db673 | emcguirk/atbs | /Chapter 7/strongPass.py | 573 | 4.1875 | 4 | import re
import pyperclip
# Regexes for each requirement:
hasLower = re.compile(r'[a-z]')
hasUpper = re.compile(r'[A-Z]')
hasNumber = re.compile(r'[0-9]')
def isStrong(pwd):
assert type(pwd) == str
lower = hasLower.findall(pwd)
upper = hasUpper.findall(pwd)
number = hasNumber.findall(pwd)
if len(lower) < 1 or l... | true |
159c7cf258c708281d9f1cc17d48e9f871f0ece8 | jakubwosko/Algorithms | /number_of_bits.py | 792 | 4.1875 | 4 | ##########################################################
# Several ways to count bits in Python 3.6
# JW 2018
##########################################################
# classic bit shift
def number_of_bits1(n):
x = 0
while n > 0:
x += n & 1
n >>= 1
return x
# bin.count method
def numbe... | false |
f242ca44b241f49b69bd857d106747af2bcf5e2c | mattdrake/pdxcodeguild | /python/fizz_buzz.py | 757 | 4.1875 | 4 | __author__ = 'drake'
#reques input from user for any number
question = input("Enter a number. ")
#created variable for incrementing input from user
num = -1
#create loop to count from zero to user input number
while question > num:
#incrementing by one
num += 1
#test if number is a multiple of both 3 and 4 not in... | true |
742e5d7916310d6be17299e6d47c40c901498635 | kebron88/essential_libraries_assignment | /question11.py | 941 | 4.21875 | 4 | import numpy as np
import pandas as pd
#Do not import any other libraries
"""
Suppose you have created a regression model to predict some quantity. Write a function that takes 2 numpy arrays that both have the same length, y and y_pred.
The function should return the loss between the predicted and the actual values wh... | true |
45b12f398d04c8e709bc201c172a499eeae9c852 | ttund21/LearningPython | /PythonBrasilExercicios/EstruturaSequencial/Respostas/11_Questao.py | 474 | 4.21875 | 4 | # 11. Faça um Programa que peça 2 números inteiros e um número real. Calcule e mostre:
# A. o produto do dobro do primeiro com metade do segundo .
# B. a soma do triplo do primeiro com o terceiro.
# C. o terceiro elevado ao cubo.
num = []
for i in range(3):
inpNum = int(input(f'Escreva o {i + 1}º número: '))
... | false |
c5e14dd3bb3bd198c4d732330af9032436e6e1e8 | ttund21/LearningPython | /PythonBrasilExercicios/EstruturaDeDecisao/Respostas/2_Questao.py | 203 | 4.15625 | 4 | # 2. Faça um Programa que peça um valor e mostre na tela se o valor é positivo ou negativo.
valor = int(input('Escreva uma valor: '))
if valor < 0:
print('Negativo')
else:
print('Positivo')
| false |
a89b7beb4621c92bb11042bc38315ec76cf2f519 | ttund21/LearningPython | /PythonBrasilExercicios/EstruturaDeRepeticao/Respostas/11_Questao.py | 248 | 4.125 | 4 | # 11. Altere o programa anterior para mostrar no final a soma dos números.
num1 = int(input('Número 1: '))
num2 = int(input('Número 2: '))
soma = 0
for i in range(num1 + 1, num2):
soma += i
print(i, end=' ')
print(f'\nSoma: {soma}')
| false |
bf80df161b39f16e53a395e5ac177afca976a262 | Mujju-palaan/Python | /loopswithlist39.py | 201 | 4.15625 | 4 | numbers = [1,2,3,4,5,6,7,8,9,10]
for i in range(0,len (numbers)):
print(numbers[i])
for i in range(0,len (numbers),2):
print(numbers[i])
for i in range(0,len (numbers),3):
print(numbers[i]) | false |
69ba98a8c14e62037d3016662fc7d6e571187c67 | LukeG-dev/CIS-2348 | /homework1/3.18.py | 888 | 4.21875 | 4 | # Luke Gilin
import math
wall_H = float(input("Enter wall height (feet):\n"))
wall_W = float(input("Enter wall width (feet):\n"))
wall_A = wall_H * wall_W # Calculate wall area
print("Wall area:", '{:.0f}'.format(wall_A), "square feet")
paintNeeded = wall_A / 350 # Calculate Paint needed for wall
pri... | true |
5226c99becd7721dcced90cd85b26526fa8880c8 | ashish-dalal-bitspilani/python_recipes | /python_cookbook/edition_one/Chapter_One/recipe_two.py | 597 | 4.625 | 5 | # Chapter 1
# Section 1.2
# Swapping values without using a temporary variable
# Python's automatic tuple packing (happens on the right side)
# and unpacking are used to achieve swap readily
a,b,c = 1,2,3
print("pre swap values")
print('a : {}, b : {}, c : {}'.format(a,b,c))
a,b,c = b,c,a
print("post swap values")
p... | true |
43ab394f43b06ace4fffb0b09c18d01c04c0b962 | CruzAmbrocio/python-factorial | /application.py | 1,161 | 4.28125 | 4 | """This program calculates a Fibonacci number"""
import os
def fib(number):
"""Generates a Fibonacci number."""
if number == 0:
return 0
if number == 1:
return 1
total = fib(number-1) + fib(number-2)
return total
def typenum():
"""Function that allows the user to enter a numbe... | true |
95c11512136c758f51ae686b4ac904be82f361ee | Lcarera/Trabajo-Practico-1 | /ej4y5.py | 1,202 | 4.3125 | 4 | """El programa da 3 opciones.
Dependiendo de la opcion elegida pide la temperatura y la devuelva convertida,
o devuelve una tabla de conversion."""
def conversorC(f):
"""Convierte grados Celsius a Fahrenheit."""
Celsius= (f-32)*5/9
return "{0:.2f}".format(Celsius)
def conversorF(c):
"""Convierte grados... | false |
29322f2c5a750b532c5faccb5549d29841bd5b14 | miku/khwarizmi | /sorting/median.py | 645 | 4.21875 | 4 | #!/usr/bin/env python
# coding: utf-8
"""
Swap the median element with the middle element. Create two smaller
problems, solve these.
Subproblems: Find the median of an unsorted list efficiently.
"""
def sort(A):
medianSort(A, 0, len(A))
def medianSort(A, left, right):
if left > right:
# find median ... | true |
1771618b573a48c8f0c19fbce9d50bf705fd481e | joedo29/Self-Taught-Python | /NestedStatementsAndScope.py | 1,367 | 4.46875 | 4 | # Author Joe Do
# Nested Statement and Scope in Python
'''
It is important to understand how Python deals with the variable names you assign.
When you create a variable name in Python the name is stored in a *name-space*.
Variable names also have a *scope*, the scope determines the visibility of that variable name to ... | true |
072ad3929e779ef840bc40875ff1eccaf7e55c1a | joedo29/Self-Taught-Python | /Files.py | 1,452 | 4.65625 | 5 | # Joe Do
# Python uses file objects to interact with external files on your computer.
# These file objects can be any sort of file you have on your computer,
# whether it be an audio file, a text file, emails, Excel documents, etc.
# Note: You will probably need to install certain libraries or modules to interact with ... | true |
516defd5b62da3eb06cacfaddbd7e33b48c267f8 | shilpa5g/Python-Program- | /python_coding_practice/leap_year.py | 290 | 4.3125 | 4 | # program to check a year is leap year or not
year = int(input("enter a year: "))
if(year % 400 == 0):
print(year,"is a leap year.")
elif(year % 100 == 0):
print(year,"is not a leap year.")
elif(year % 4 == 0):
print(year,"is a leap year.")
else:
print(year,"is not a leap year.")
| false |
0230151c53ea3f13baa6b353e2c9108452b1edff | shilpa5g/Python-Program- | /python_coding_practice/sum_of_series.py | 276 | 4.25 | 4 | # program to find Sum of natural numbers up to given range
terms = int(input("Enter the last term of the series: "))
if terms < 0:
print("please enter a positive number.")
else:
sum = 0
for i in range(1, terms+1):
sum +=i
print('sum of series = ',sum) | true |
55084a7529445303cf7dc531022ee39ab52613d2 | shilpa5g/Python-Program- | /python_coding_practice/palindrome.py | 246 | 4.5625 | 5 | # Program to check if a string is palindrome or not
string = str(input("enter a string: "))
rev_str = reversed(string)
if list(string) == list(rev_str):
print("The string is a palindrome.")
else:
print("The string is not a palindrome.") | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.