blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
706f7af5c7a3c732df5923577dd0321e87630f87 | maherme/python-deep-dive | /Numeric_Types/FloatCoercingToIntegers.py | 751 | 4.34375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 25 12:01:19 2021
@author: maherme
"""
#%%
# Let's see trunc function:
from math import trunc
print(trunc(10.3), trunc(10.5), trunc(10.9))
# Trunc is used by default for the int constructor:
print(int(10.4), int(10.5), int(10.9))
#%%
# Let's see ... | true |
9a89d50b6d86604378507e92964ab812c49e8fcf | maherme/python-deep-dive | /Numeric_Types/FloatInternalRepresentation.py | 782 | 4.25 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 25 11:18:51 2021
@author: maherme
"""
#%%
# Let's see the float constructor:
print(float(10))
print(float(10.4))
print(float('12.5'))
print(float('22/7')) # This will fail, you need to create a fraction first
#%%
from fractions import Fraction
a ... | true |
6311e80dfa4995203437be22f5bc1c0343fac53b | Kseniya159/home_work | /задание 1.py | 467 | 4.1875 | 4 | #Поработайте с переменными, создайте несколько,
# выведите на экран, запросите у пользователя несколько чисел и строк и сохраните в переменные,
# выведите на экран..
number = int ( input ("Введите число"))
print( number)
age = 28
print ( age)
name = input( "Введите имя")
from1 = input( (" Я из "))
| false |
793453499738c02f538f5a5e7585426e3c89de37 | AlvaroSanchezBC/-lvaro-S-nchez-Beato | /practica24.py | 548 | 4.15625 | 4 | # -º- coding: utf-8 -º-
'''
Pr�ctica 28
FechaL�mite:2/11/2020
FechaCorreci�n:5/11/2020
author@: alvaro.sanchez
'''
#Escribir un programa que solicite del usuario una lista de edades y muestre en pantalla la lista de edades de menor a mayor y de menor a mayor.
#Primero voy a crear una lista de edades.
#Ahor... | false |
9e222085ac82d074594e896dd8f9ecec93b071f2 | MatsK/python-for-grade-8 | /example01_print_and_variables.py | 255 | 4.34375 | 4 | # My first program
print "Hello, world!"
name = "Your name"
#name = "Someone elses name"
print "Hello %s" % name
# x is a integer variable name
x = 5
print "x=%s" % x
# We can change the value of x with a mathematical operation
x = x + 2
print "x=%s" % x
| true |
c135c6a9d36b791f5c3222d012acfc0911e81b63 | ColdMacaroni/sort-by-ord | /no_sort_by_ord.py | 1,976 | 4.28125 | 4 | ##
# no_sort_by_ord.py
# Sorts input string by the value given by ord(char)
# 2021-03-31
def str_to_ord(string):
"""
Returns a list with the ord of each character.
"""
return [ord(x) for x in string]
def corresp_ord(string):
"""
Returns a dictionary of the equivalent ascii ord... | true |
b110b7e2469298143333a46a0bb226873852dd57 | magedu-pythons/python-19 | /6-kwei/week13/homework.py | 2,036 | 4.21875 | 4 | # 1、实现数据结构stack(栈),并实现它的append,pop方法【动手查询相关资料理解stack特点以及与queue区别】
# 用数组实现
class Stack:
def __init__(self, length: int):
self.length = length
self.stack = [None] * length
self.index = -1
def append(self, item):
if self.index + 1 >= self.length:
print('overflow!')
... | false |
5eae836273a74302642730313923d3bf8732c0b9 | magedu-pythons/python-19 | /0-Answers/week11/2-parenthesis.py | 591 | 4.125 | 4 | # 2、打印出N对合理的括号组合。
# 例如: 当N=3,输出:()()(),()(()),(())(),((())),(()())
def print_parenthesis(output, opend, close, pairs):
"""
左右括号数量匹配
:param output:
:param opend:
:param close:
:param pairs:
:return:
"""
if opend == pairs and close == pairs:
print(output)
else:
if... | false |
dd7a85fa55680805cf4fe5f83993dce00ba8420b | magedu-pythons/python-19 | /P19035-艾合麦提/week2/1.py | 442 | 4.15625 | 4 | def fibonacci_generator():
"""
:return:the generator produces number
"""
i = 0
j = 1
yield 1
while True:
yield j+i
n = i
i = j
j = n + i
def main(n):
for k in fibonacci_generator():
if k < n:
print(f"the number is {k}")
#test
if __n... | false |
b8322e0df48c549087167b2a887be03f659e587a | jeffwright13/codewars | /is_prime.py | 946 | 4.1875 | 4 | def main():
print is_prime.__doc__
def is_prime(n):
"""
Checks for primality via trial division on (1, sqrt(n)]
"""
from math import sqrt
if type(n) != int or n <= 1:
return False
#print 'checking for n =', n
for i in range(2, int(round(sqrt(n)))+1):
if n % i == 0:
... | false |
00194cd3682ef8a32845aa3b52ac7b9f03c582ba | jeffwright13/codewars | /mixed_fraction.py | 2,189 | 4.5625 | 5 | def main():
print mixed_fraction.__doc__
def mixed_fraction(s):
"""
https://www.codewars.com/kata/simple-fraction-to-mixed-number-converter
Task:
Given a string representing a simple fraction x/y, your function must return a string representing the corresponding mixed fraction in the following fo... | true |
341d3ca705d51e831f9bd0aed54b27dc4931da42 | jeffwright13/codewars | /permutation_average.py | 1,623 | 4.25 | 4 | def main():
print permutation_average.__doc__
def permutation_average(n):
"""
A number is simply made up of digits.
The number 1256 is made up of the digits 1, 2, 5, and 6.
For 1256 there are 24 distinct permuations of the digits:
1256, 1265, 1625, 1652, 1562, 1526, 2156, 2165, 2615, 2651, 2561... | true |
d59f595e547df9dff7ecef38724b1729dabc2b23 | jeffwright13/codewars | /sumDig_nthTerm.py | 2,345 | 4.4375 | 4 | def main():
print sumDig_nthTerm.__doc__
def sumDig_nthTerm(initVal, patternL, nthTerm):
"""
We have the first value of a certain sequence, we will name it initVal. We define pattern list, patternL, an array that has the differences between contiguous terms of the sequence. E.g: patternL = [k1, k2, k3, k4]... | true |
a626678ccefac238fdc86942ad04c0f5c6ebfd91 | jeffwright13/codewars | /find_next_square.py | 1,524 | 4.34375 | 4 | def main():
print find_next_square(None)
def find_next_square(sq):
"""
You might know some pretty large perfect squares. But what about the NEXT one?
Complete the findNextSquare method that finds the next integer perfect square after the one passed as a parameter. Recall that an integral perfect squar... | true |
a7d20941cdeb717e3e519c286c059ccdd5cb6e4e | jeffwright13/codewars | /remainder.py | 1,106 | 4.4375 | 4 | def main():
print remainder(None)
def remainder(dividend, divisor):
"""
Task
----
Write a method 'remainder' which takes two integer arguments, dividend and divisor, and returns the remainder when dividend is divided by divisor. Do NOT use the modulus operator (%) to calculate the remainder!
A... | true |
55abc4c575a0c0f15f21f69ca6b7e4ecc8ff64bc | JuanAngel1/PrimerRepo | /prog3.py | 960 | 4.15625 | 4 | #Menu
#Operaciones
#S. Suma
#R. Resta
#M. Multiplicacion
#D. Division
#A. Salir
#Que opcion elige? :
#Ingrese numero uno
#Ingrese numero dos
print("Programa para resolver operaciones aritmeticas")
while True:
print('''Operaciones: 1.- S. Suma 2.- R. Resta 3.- M. Multiplicacion 4.- D. Division 5.- A. Salir
¿Q... | false |
a4af751a08ba85b2009e042f0c31d6eaac5cb57c | wfSeg/py3dahardway | /py16.py | 1,103 | 4.4375 | 4 | # what can you do with files?
# close: close the file
# read: reads the file
# readline: reads just one line of text
# truncate: Empties the file.. so it's not truncate, it's like Erase
# write('stuff'): Writes into the file
# seek(0): Moves the r/w location to beginning of file.. this is like for HDDs
from sys import... | true |
00fcc169bc667b5d259b76bb31e7a6ed1f0d04e0 | wfSeg/py3dahardway | /py31.py | 2,074 | 4.125 | 4 | # I go out for boba everyday, sometimes even twice. :|
print("""You enter a dark room with two doors.
Do you go through the door on the LEFT or the door on the RIGHT?""")
choice = input("> ")
#if choice == "L" or "Left": #hmm capitalization matters. Need a better way to sanitize the input
# doesn't work.
if choice ... | true |
e3829c37aeb3c9cf05a090ed36625b6da355a9f5 | komerela/dataStructAlgosPython | /mergelinkedlists.py | 1,528 | 4.3125 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
"""
1 -> 2 -> 4 1 -> 3 -> 4 -> 5 ->6
l1 l2
new_List 0 -> 1 ->
(start new merged list)
1. set variables
"""
cla... | true |
d6c336ad50bb88fc70f86641b8cbbe40b89a0d63 | airakesh/interviewbits | /arrays/anti_diagonals.py | 722 | 4.375 | 4 | '''
Give a N*N square matrix, return an array of its anti-diagonals. Look at the example for more details.
Example:
Input:
1 2 3
4 5 6
7 8 9
Return the following :
[
[1],
[2, 4],
[3, 5, 7],
[6, 8],
[9]
]
Input :
1 2
3 4
Return the following :
[
[1],
[2, 3],
[4]
]
'''
class Solution:
... | true |
51c636d72134537e16a284191ddb828a637dd6d4 | HardyBubbles/TikTakToe | /player_input.py | 857 | 4.28125 | 4 | '''
Функция спрашивает у 1го игрока, каким маркером он хочет отмечать свои квадратики на доске
The function asks the 1st player with which marker he wants to mark his squares on the board
'''
def player_input():
p1_m = "" # стартовое знач-е для запуска цикла while
while not (p1_m == "X" or p1_m == "O"):
... | false |
c715c821737e4f25dc84d73ed29f9840d1cb7674 | olgaBovyka/BasicLanguagePython | /Урок 3/Task3_3.py | 1,172 | 4.5625 | 5 | """
3. Реализовать функцию my_func(),
которая принимает три позиционных аргумента, и возвращает сумму наибольших двух аргументов.
"""
def my_func(argument1, argument2, argument3):
argument_list = [argument1, argument2, argument3]
argument_list.sort()
return argument_list[1] + argument_list[2]
input_var ... | false |
27c3871b192c088d6c2a2bcf1af6471a05f9ed78 | ScienceStacks/common_python | /common_python/util/dataframe.py | 1,508 | 4.15625 | 4 | """Utilities for DataFrames"""
import pandas as pd
import numpy as np
def isLessEqual(df1, df2):
"""
Tests if each value in df1 is less than or equal the
corresponding value in df2.
"""
indices = list(set(df1.index).intersection(df2.index))
dff1 = df1.loc[indices, :]
dff2 = df2.loc[indices, :]
df = d... | true |
d31914ca5bf9ec1e3b03e53b5b957216fcde80fd | erikayoon/Automate-The-Boring-Stuff-With-Python | /Chapter 4/commaCode.py | 868 | 4.1875 | 4 | # TASK:
# Take a list value as an argument
# Return a string with all the items separated by a comma and space
# With 'and' inserted before the last item
# Ex: apples, bananas, tofu, and cats
# PERSONAL TWIST:
# If the first value of the list is a string
# Capitalize it
### MY CODE BELOW: ###
# Define functi... | true |
69e69ff253c15e514a62aed56a5792ac6ce175c9 | Elvandro/Password-locker | /user.py | 748 | 4.15625 | 4 | class User:
"""
Class that generates new instances of users
"""
user_list = []
def __init__(self, user_name, password):
"""
__init__ method helps us define our object
Args:
user_name: New user name.
password: New user password.
"""
se... | true |
e33f993b6a2a63db6c94b998a3d7aed4d48804b4 | yanyanxumian/Stats507_F21 | /nb/string_df.py | 1,659 | 4.5 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Create a small pandas DataFrame for examples.
@author: James Henderson
@date: August 31, 2021
"""
# 79: ------------------------------------------------------------------------
# libraries: -----------------------------------------------------------------
import pand... | true |
4b8fca052411efb9514b2b31e434126cf326d376 | fangyeqing/hello-python | /_7_oop/_5_class_attribute.py | 699 | 4.125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__title__ = '实例属性和类属性'
__author__ = 'fangyeqing'
__time__ = '2016/11/3'
"""
# 学生
class Student(object):
# 用于记录已经注册学生数
student_number = 0
def __init__(self, name):
self.name = name
# 注册一个学生:注册必填项名字,选填项利用关键字参数传递。注册完成,学生数+1
def register(name, **kw)... | false |
40a2e739e6752b978deb83b7c04dd653aa541cbe | Maddallena/python | /day_2.py | 1,366 | 4.21875 | 4 | # DZIEŃ DRUGI____________________________________________________________________________________________________________________________________
# Data types
# print("Hello" [3]) SUBSCRIPTING A CHARACTER
# num_char = len(input("what is your name?: "))
# new_num_char = str(num_char)
# print("your name has " ... | false |
fd70bcf214fe1afaa31eb8f1c70639d3cfdf18c7 | annecode21/Projects | /Random password generator.py | 446 | 4.1875 | 4 | import random
print ("Welcome to my random password generator!")
chars = "abcdefghijklmnopqrstuvwxyzABCEDFGHIJKLMNOPQRSTUVWXYZ123456789!@#$%&"
number = int(input("Number of password(s) to generate: "))
length = int(input("Enter length of password required: "))
print ("\nHere is/are your password(s): ")
for pwd in ra... | false |
8585491202fd2e83a07204c2bdccd91762a0f9a4 | jaumecosta/python | /tortuga.py | 787 | 4.15625 | 4 | import turtle
#funcion que se encarga de la activacion de la ventaan de dibujo y de llamar a la funcion haz rectangulo
def oceano():
window = turtle.Screen()
tortuguita = turtle.Turtle()
haz_rectangulo(tortuguita)
turtle.mainloop()
#funcion que nos hace las preguntas de largo y alto
def haz_rectang... | false |
51d4e110fa914f72d9acbf1a0f2e45c8c726650f | mystor/ugrad-thesis | /figs/canasta.py | 750 | 4.125 | 4 | def value(num, suit):
if num <= 2:
return 20
elif 3 == num and suit in ['H', 'D']:
return 100 # red 3s are worth 100
elif 3 <= num < 8:
return 5
elif 8 <= num:
return 10
def main():
# Read in the type of card.
numbers := ['A', '2', '3', '4', '5', '6', '7', '8', '... | true |
2dce48e58b3a4682acb9787e9bf06f6b82a9f2ad | rosajong/population | /Population.py | 1,606 | 4.34375 | 4 | """
Define class Human which has the following : gender hair eyes AGE
For every baby a Human gets Population must be += 1
Only women can have babies
Human grows from baby > child > adolescent > adult
The attributes gender hair eyes are randomly given to Human
Give population a starting number and make that amount of h... | true |
a4d8597b95e2597a4ba85080248dc67819d515a6 | mhiloca/PythonBootcamp | /challenges/valid_parentheses.py | 539 | 4.125 | 4 | def valid_parentheses(string):
# check = []
# for p in string:
# if p == '(':
# check.append('(')
# if p == ')':
# check.remove('(') if check else check.append('(')
# return not check
count = item = 0
while item < len(string):
if string[item] == '(':
... | true |
56bdf527e4d9e212d136ed7ee92df0b3d5f21928 | Kiran-24/python-assignment | /python_partA_171041001/centroid.py | 640 | 4.1875 | 4 | ''' Implement a python code to find the centroid of a triangle'''
def centroid(p1,p2,p3):
''' To calculate the centroid of triangle'''
centroid = [(p1[0]+p2[0]+p3[0])/3 , (p1[1]+p2[1]+p3[1])/3]
return centroid
def main():
print('enter x y co-ordinates of first vertex :')
p1 = [float(d) for d in input().split()]
... | false |
b8115f4ebdea6c62c79d545587ff159b893f046d | melipefelgaco/project_madLibs | /project_madLibs.py | 1,397 | 4.3125 | 4 | # Reads text files and lets user add their own text anywhere the words ADJECTIVE, NOUN, VERB or NOUN appears in the text.
# Read the file panda.txt stored on this same folder.
# Path = yourpath
# The results should be printed to the screen and saved to a new text file. (newpanda.txt)
from pathlib import Path
import os... | true |
2b8d6283a183aa16f1d5d2a9ce113c0ba55b3d59 | xgabrielrf/igti-python | /modulo1/class.py | 1,189 | 4.28125 | 4 | print(''''Erro' ao absorver informação de uma variável que foi obtida por classe.
Nesse caso abaixo nós fazemos o carro_2 = carro_1, porém, ao modificar o carro_2,
o carro_1 é alterado indevidamente.
Isso ocorre por conta de quando colocamos carro_2 = carro_1, fazemos o apontamento
para o mesmo objeto na memória. Assi... | false |
bd43128053f6a3e8e88e860cd103f09f8288d8e7 | marioabz/python-cheat-sheet | /data_types/collections/dictionaries.py | 1,423 | 4.375 | 4 |
# Dictionary is a collection that stores values in a key-value fashion
# Dictionaries are changeable and don't allow duplicates
person = {
"age": 67,
"name": "Jinpig",
"last_name": "Xi",
"ocupation": "President",
"country_of_origin": "China",
}
# Accesing the 'age' key of dict 'person'
print(pers... | true |
83144e045f2852d5219c6d7c4b73b67d8fe53b29 | lee000000/leetcodePractice | /434.py | 1,015 | 4.125 | 4 | '''
434. Number of Segments in a String
Count the number of segments in a string, where a segment
is defined to be a contiguous sequence of non-space characters.
Please note that the string does not contain any non-#printable characters.
Example:
Input: "Hello, my name is John"
Output: 5
'''
class Solution(object)... | true |
b2cea68ccf191849f470f7263f73758199e7bc47 | Elephantxx/gs | /05_高级数据类型/x_15_字符串统计操作.py | 254 | 4.28125 | 4 | hello_str = "hello hello"
# 1. 统计字符串长度
print(len(hello_str))
# 2. 统计某一个小字符出现的次数
print(hello_str.count("llo"))
print(hello_str.count("abc"))
# 3. 某一个子字符串出现的位置
print(hello_str.index("llo")) | false |
d97c062c45e9e754a6f04f7ba683d2a1d0e73c92 | Elephantxx/gs | /05_高级数据类型/x_01_列表基本使用.py | 1,036 | 4.28125 | 4 | name_list = ["zhangsan", "lisi", "wangwu"]
# 1. 取值和取索引
# list index out of range - 列表索引超出范围
print(name_list[2])
# 已知数据内容,查找该数据在列表中的位置
print(name_list.index("lisi"))
# 2. 修改
name_list[1] = "李四"
# list assignment index out of range - 列表指定的索引超出范围
# name_list[3] = "小明"
# 3. 增加
# append 方法可以向列表末尾追加数据
name_list.append("小... | false |
3d5ace7db875341ae5e0f442f4752402b1fd7725 | NineMan/Project_Euler | /Euler_2.py | 732 | 4.125 | 4 | """
Задача 2 Четные числа Фибоначчи
Каждый следующий элемент ряда Фибоначчи получается при сложении двух предыдущих.
Начиная с 1 и 2, первые 10 элементов будут:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
Найдите сумму всех четных элементов ряда Фибоначчи, которые не превышают четыре миллиона.
"""
lst = [1... | false |
3c46650b3604ff754235564bf09e508320169a51 | strayberry/data_struct | /Chain.py | 2,359 | 4.21875 | 4 | # -*- coding: UTF-8
class Node(object):
def __init__(self, data):
self.data = data
self.next = None
class LinkedList(object):#链表
def __init__(self):
self.head = None
self.tail = None
def is_empty(self):
if self.head is None:
print('The linkedlist is empty')
else:
print('The linkedlist is not emp... | false |
25f8cf1be395e35ac62c3334e9b6264512a9abc6 | pramo31/LeetCode | /Completed/group_anagrams.py | 662 | 4.125 | 4 | from typing import List
"""
Given an array of strings, group anagrams together.
"""
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
anagram_dict = {}
for word in strs:
sorted_word = "".join(sorted(list(word)))
if (sorted_word in anagram_dict.ke... | true |
9817dccf295e2f42f3548a9e1282e5ba71557f66 | IndranilRay/PythonRecipes | /GeeksForGeeks/Int2Bin.py | 247 | 4.1875 | 4 | """
Program displays binary equivalent of an integer > 0
"""
def display_bin(n):
if n == 0:
return
display_bin(n//2)
print(n % 2)
if __name__ == "__main__":
number = input("Enter a number")
display_bin(int(number))
| true |
bb3455c61e127d8462c979b13ac4c61104cafcca | IndranilRay/PythonRecipes | /GeeksForGeeks/stringIsPalindromeRecursive.py | 526 | 4.34375 | 4 | """
WAP to check if input string is palindrome recursive version
"""
def isPalindrome(input_string, start=0, end=0):
if start >= end:
return True
return (input_string[start] == input_string[end]) and isPalindrome(input_string, start+1, end-1)
if __name__ == '__main__':
string = input("Enter the... | true |
f812c8ea740c64c629b3c325152c12d249b31412 | Supermac30/CTF-Stuff | /Mystery Twister/Autokey_Cipher/Autokey Encoder.py | 327 | 4.1875 | 4 | """
This script encodes words with the AutoKey Cipher
"""
plaintext = input("input plaintext ")
key = input("input key ")
ciphertext = ""
for i in range(len(plaintext)):
ciphertext += chr((ord(plaintext[i]) + ord(key[i]))%26 + ord("A"))
key += plaintext[i]
print("Your encoded String is:",cipher... | true |
5a98e54f9762d2fab78ea8134bb80bb385dce851 | vaibhavs33/RockPaperScissors | /loops.py | 1,110 | 4.1875 | 4 | keepPlaying = True
player1 = input("What is player 1's choice? ")
while(player1 != "rock" and player1 !="paper" and player1 != "scissors"):
player1 = input("Please choose a valid choice (rock,paper, or scissors): ")
# print(player1,"is the right choice")
player2 = input("What is player 2's choice? ")
while(pla... | true |
ccfc5b68b5272b0ed16c06f5c44793e8dea81923 | king-tomi/python-learning | /family.py | 2,621 | 4.5625 | 5 | class Family:
"""This is a program representation of a nuclear family.
parent_name: name of the mother or father of the family.
children_name: a list of the children in the family.
child_gender: a list of the corresponding genders of each child."""
def __init__(self,parent_name,children... | true |
e6e4a103b43fd3dae304d8b953ac6f3532e1851e | dexter2206/redis-classes | /examples/sets.py | 980 | 4.15625 | 4 | """Basic examples of using sets."""
from redis import Redis
import settings
if __name__ == '__main__':
client = Redis(
host=settings.HOST,
port=settings.PORT,
password=settings.PASSWORD,
decode_responses=True
)
name = 'kj:set'
# Create some set by adding elements to it... | true |
87ec263519dcd85bc7b003549ff02d2421dd1aa4 | LauraBrogan/pands-problem-set-2019 | /solution-1.py | 1,024 | 4.4375 | 4 | # Solution to Problem 1
# Ask the user to Input any positive integer and output the sum of all numbers between one and that number.
# n is asking the user to input a postive integer.
n = int(input("Input a Positive Integer: "))
# If the user inputs a negative number or a zero the programe displays "this is not a pos... | true |
c32e91fef72a2d2a87d0f63dca588965d3f83cd9 | ericel/python101 | /hypotenuse.py | 1,882 | 4.25 | 4 |
import math
# Calculates length of the hypotenuse of a
# right trianle given lengths of other 2 legs
def hypotenuse(a, b):
# should return a float
print(0.0)
return 0.0
# return 0.0
hypotenuse(3, 4)
# Calculates length of the hypotenuse of a
# right trianle given lengths of other 2 legs
def hypotenuse(... | true |
d124c6551c0f8d07c3737d412b690cac1af08876 | ericel/python101 | /volume_of_sphere.py | 982 | 4.34375 | 4 | import math
# Calculate the volume of a sphere
def volume_of_sphere(r):
print('returns a float 0.0')
return 0.0
# Call to check function initial works
volume_of_sphere(2)
# Calculate the volume of a sphere
def volume_of_sphere(r):
# calculate cubed of radius r
r3 = r ** 3
print('Sphere Radius cub... | true |
66ff09519b7f56fb7c8639106c08d1fcddef5d97 | mariskalucia/Py | /Ditctionaries.py | 393 | 4.375 | 4 | # Ditctionaries
print("Ditctionaries")
capitals = {"Japan":"Tokyo", "South Korea":"Seoul"}
print(capitals)
print(len(capitals))
capital = capitals["Japan"]
print(capital)
capitals["China"] = "Beijing"
capitals["Australia"] = "canberra"
print(capitals)
for country in capitals:
capital = capitals... | false |
8bba4750eceea388549be9f89eaee45227ca4942 | akaybanez/hacktoberfest2k | /scripts/aballe-melchi-3.py | 500 | 4.21875 | 4 | def incrementWhileLoop (a):
print ("While Loop increment values")
print ("Condition while a != b = (a + 5)")
b = a + 5
while (a != b):
print (a)
a += 1
def decrementWhileLoop (a):
print ("While Loop decrement values")
print ("Condition while a != b = (a - 5)")
b = a - 5
while (a != b):
print(a)
a -= 1
... | false |
f5ed880f569a31a33a77d7968835351baf81e70e | Fortune-Adekogbe/ECX_30_days_of_code_Python | /Python files/Fortune_Adekogbe_day_25.py | 751 | 4.25 | 4 | def desc_triangle(a,b,c):
'''
This function takes in 3 integers a,b,c representing the length of the sides
of a triangle and Returns a tuple of 2 elements whose first element is a
string describing the triangle and second element is the area of the
triangle...
'''
s= (a+b+c)/2
area = ((s... | true |
c5e1ebe304d4912e18203c00702e6d3f2967be21 | Fortune-Adekogbe/ECX_30_days_of_code_Python | /Python files/Fortune_Adekogbe_day_23.py | 736 | 4.40625 | 4 | def find_Armstrong(x,y):
'''
find_Armstrong is based on a definition for armstrong numbers that involves
summing the cubes of the digits in the number.
Parameters:
x: an integer representing the start of the interval
y:an integer representing the last number in the interval
Returns:
A list of all the armstro... | true |
fbc42a844313b04a8c38ea4f5b7c08f4fb08a276 | Fortune-Adekogbe/ECX_30_days_of_code_Python | /Python files/Fortune_Adekogbe_day_6.py | 463 | 4.15625 | 4 | def power_list(List):
"""
This function takes a list as parameter and returns its power list
(a list containing all the sub lists of a particular super list including null
list and list itself).
"""
if List==[]:
return [[]]
a=List[0]
b=power_list(List[1:])
c=[]
for d in ... | true |
f34b7153bc2df4a97fcbbe8a41ebfcf7e5ffc0b2 | DemetrioCN/random_walk | /1D_random_walk.py | 1,028 | 4.25 | 4 | # Random Walk in One Dimension
# DemetrioCN
import random
# Choose the next step and add it to the previous one
def walk_1D(steps):
count = 0
for i in range(steps):
walk = random.choice([(1),(-1)])
count += walk
return count
# Compute the distance from 0
def random_walk_1D(steps, atte... | true |
5abb7140a4733fbbed83230dcea680826002f5f6 | ian-gallmeister/sorting_algorithms | /pep8/radixsort.py | 1,259 | 4.21875 | 4 | #!/usr/bin/env python3
""" An implementation of radixsort """
import random
SHOW_LISTS = True
def radixsort(seq):
""" The radix sort algorithm """
max_val = max(seq)
oom = 0 #order of magnitude
while max_val // 10**oom > 0:
countingsort(seq, oom)
oom += 1
#adapt to take arg for which... | true |
535a90af8ae6c271edaa538259579ee69cc24c0f | ES2Spring2019-ComputinginEngineering/hw3-sofialevy | /ES2BubbleLevel.py | 2,893 | 4.25 | 4 | # HOMEWORK 3 --- ES2
# Bubble Level
# FILL THESE COMMENTS IN
#*****************************************
# YOUR NAME: Sofia Levy
# NUMBER OF HOURS TO COMPLETE: 6
# YOUR COLLABORATION STATEMENT(s):
# I worked with Rene Jameson on this assignment.
# I received assistance from Dr. Cross on this assignment.
#*************... | true |
1ff4255feadcfcd2d20c8de6c5622fefd2354f45 | kmoreti/python-masterclass | /CreateDB/checkdb.py | 321 | 4.15625 | 4 | import sqlite3
conn = sqlite3.connect("contacts.sqlite")
name = input("Please enter a name to search for: ")
select_sql = "SELECT * FROM contacts WHERE name = ? "
result = conn.execute(select_sql, (name,))
print(result.fetchone())
# for row in conn.execute("SELECT * FROM contacts"):
# print(row)
conn.close()
... | true |
0ef62d90642adc8a915ce64ae750fd0ee554c2d8 | mef21/GirlsWhoCode | /Lesson 1 - Variables/examples/example1.py | 1,041 | 4.59375 | 5 | """
WELCOME TO VARIABLES EXAMPLE 1
BEFORE YOU DO ANY CODING COPY THE BELOW TEXT INTO THE .replit FILE
language = "python3"
run = "cd 'Lesson 1 - Variables'; cd examples; clear; python3 example1.py"
Below are a series of examples using different types of variables and how to manipulate them:
"""
""" STRING EXAMPL... | true |
0d0f05a92e4d6662322708f86ccf50a94699938b | mef21/GirlsWhoCode | /Lesson 2 - Conditionals/examples/examples.py | 888 | 4.46875 | 4 | """
WELCOME TO CONDITIONAL EXAMPLES
BEFORE YOU DO ANY CODING COPY THE BELOW TEXT INTO THE .replit FILE
language = "python3"
run = "cd 'Lesson 2 - Conditionals'; clear; cd examples; python3 examples.py"
"""
""" EXAMPLE 1 """
if(1 < 2):
print("1 is less than 2")
else:
print("1 is not less than 2")
""" EXAMPLE 2... | true |
a28e74d2bc450034db3c043b4722d89f92b6827d | 712Danila712/edu_projects | /python/Stepic_1.12_3.py | 380 | 4.15625 | 4 | a = float(input())
b = float(input())
o = input()
if b == 0 and (o == "/" or o == "mod" or o == "div"):
print("Деление на 0!")
elif o == "+":
print(a + b)
elif o == "-":
print(a - b)
elif o == "/":
print(a / b)
elif o == "*":
print(a * b)
elif o == "mod":
print(a % b)
elif o == "div":
print(... | false |
fb2abdde6842295463e0aa0aba32a99999663fa1 | cyhe/Python-Note | /Base/1.4_List.py | 2,154 | 4.3125 | 4 | # -*- coding: utf-8 -*-
# # list是一种有序的集合,可以随时添加和删除其中的元素。
workmates = ['jack', 'steve', 'boers']
print(workmates)
# 取元素
print('取出下标为1的元素', workmates[1])
# 取出最后一个元素还可以直接取-1 负号表示倒数 ,倒数第一(-1),倒数第二个(-2)
print('取出最后一个的元素', workmates[-1])
# 数组越界
"""
print('取出下标为-1的元素', workmates[3])
Traceback (most recent call last):
... | false |
9a08902a1af1388c059b11369ec44726a9f09944 | IgnacioZentenoSmith/notable_challenges | /All or Any.py | 1,475 | 4.21875 | 4 | '''
CREDITS TO HACKERRANK FOR THIS CHALLENGE
TASK
You are given a space separated list of integers. If all the integers are positive, then you need to check if any integer is a palindromic integer.
Input Format
The first line contains an integer . is the total number of integers in the list.
The second lin... | true |
a21cc3d5bc986b700af3d5c863c0ef80b1d41b51 | Samarkina/PythonTasks | /6.py | 907 | 4.125 | 4 | # Monthly interest rate = (Annual interest rate) / 12.0
# Monthly payment lower bound = Balance / 12
# Monthly payment upper bound = (Balance x (1 + Monthly interest rate)^12) / 12.0
balance = float(input("balance - the outstanding balance on the credit card: "))
AnnualInterestRate = float(input("annualInterestRate - ... | true |
8b5fe8de96e8e778ec30d5cf23371ae2c4cfc6e1 | IhebChatti/holbertonschool-higher_level_programming | /0x10-python-network_0/6-peak.py | 904 | 4.1875 | 4 | #!/usr/bin/python3
"""[python script to find peak of list]
"""
def peakfinder(list_of_integers, bot, top):
"""[recursively search for peak in list]
Args:
list_of_integers ([list]): [list of ints]
bot ([int]): [first item of list]
top ([int]): [last item of list]
Returns:
... | false |
ea6a053af6727ae9a3c09ac44e21ad29230235a4 | dfilter/udemy-flask-restapi | /section-2/29-lambda-functions.py | 719 | 4.34375 | 4 | def add(x, y):
return x + y
# Same as above function
add = lambda x, y: x + y
print(add(1, 2))
# lambda function can be executed without being named like this:
sum_ = (lambda x, y: x + y)(5, 7)
print(sum_)
def double(x):
return x * 2
sequence = [1, 3, 5, 9]
doubled = [double(x) for x in sequence]
# sam... | true |
f04e411b6921aff654df609b8ac717beedd27b7c | Ellis-Anderson/Pluralsight_Python | /Getting_Started/hs_students.py | 703 | 4.15625 | 4 | class HighSchoolStudent(Student):
"""
Adds a High School Student to the list.
:param name: string - student name
:param student_id: integer - optional student ID
"""
# Derived/child class. Attributes, like school_name, can be overridden
school_name = "Springfield High School"... | true |
e8e49bbf5245a46172cd6e1b36124e3337c9de65 | Ran05/cwd-marketing-bot | /bot.py | 1,930 | 4.15625 | 4 | def greetings(bot_name):
outputLine = f"""==========================================================================="""
print(outputLine)
print("Hello! My name is {0}.".format(bot_name))
print("We'd like to help you with your digital marketing needs! \nWe'll help you build your brand online by creati... | true |
39ee7a169e9a69700650de41712c7629b6d90926 | wdampier2000/pyton-curso | /10-sets-diccionarios/diccionarios.py | 732 | 4.125 | 4 |
"""
Como una lista pero son datos que almacena indices alfanumerico
formato clave > valos
"""
persona= {
"nombre": "Victor", #nompre es el indice, Victor es el valor
"apellido": "Rigacci",
"email": "riga@rmi.com.ar",
}
print(type(persona))
print(persona)
print(persona["apellido"])
print("\n")
... | false |
249ffde4bd50f3d91ba7e4cf03bb0d76197a32d1 | sheleh/homeworks | /lesson_25/task_25_3.py | 1,176 | 4.375 | 4 | # Implement a queue using a singly linked list.
from lesson_25.task_25_1 import Node
class Queue:
def __init__(self):
self._head = self._tail = None
def is_empty(self):
if self._head is None:
return True
else:
return False
def enqueue(self, item):
... | true |
6d1bdf281cb4c1a2ece1b5944ece0aa444acfc4b | sheleh/homeworks | /lesson11/task_11_1.py | 1,798 | 4.15625 | 4 | #School
#Make a class structure in python representing people at school. Make a base class called Person, a class called Student,
# and another one called Teacher. Try to find as many methods and attributes as you can which belong to different classes,
# and keep in mind which are common and which are not. For example,... | true |
0340793c8ad45699b466d2a4d25e4f6ad630e7e1 | sheleh/homeworks | /lesson3/task_3.py | 807 | 4.1875 | 4 | #Write a program that has a variable with your name stored (in lowercase)
# and then asks for your name as input. The program should check if your input is equal to the stored name
# even if the given name has another case, e.g., if your input is “Anton” and the stored name is “anton”,
# it should return True.
name = '... | true |
0bde00df76938a0e0dbf9938b2ce4ccfce89b8a2 | leecmoses/intro-to-cs | /18-how-programs-run/notes.py | 2,624 | 4.1875 | 4 | #############
# Notes #
# Lesson 18 #
#############
'''
Algorithm - is a procedure that always finishes and produces the correct result
Procedure - is a well defined sequence of steps that can be executed mechanically
Equivalent Expressions
* A property 'ord' and 'chr' is that they are inverses.
* This means ... | true |
e5952bd822051b4e4a0a5fb7f0f6a8c9d08ecbc3 | Pav0l/Sorting | /src/searching/searching.py | 2,544 | 4.21875 | 4 | # STRETCH: implement Linear Search
def linear_search(arr, target):
res = False
for i in arr:
if arr[i] == target:
res = i
if not res:
print('Linear Search: Target not found!')
else:
print(f'Linear Search: Found the target value at index {res}')
# linear_search([0, ... | true |
9d001981862c261062a6ae6b0507c5e24c9b2cc8 | zackguerra/git_practice | /PycharmProjects/IntroToAlgorithmsPython/6_Conditionals/conditional_statements.py | 373 | 4.25 | 4 | # Conditional Statements
# (if-else statements)
# Getting user input
# input(prompt) - atkes user input and returns as string
# Later (Error handling and validation)
age = int(input("Enter your age:"))
# or use age = int(age)
if age >= 21:
print("You can start drinking!")
elif 13 < age < 21:
print("Study... | true |
21949834637a1b26e3264dbe55536f0b35d23ec6 | zackguerra/git_practice | /PycharmProjects/IntroToAlgorithmsPython/Labs/Lab_Binary_Linear_Search.py | 1,607 | 4.375 | 4 | # In this lab, you will be using two searching algorithms we covered in class to
# search for a word in dictionary. Compare the performance for each algorithm.
# You will have to output the number of steps for both algorithms when used for searching
# for the same word. (case-insensitive)
# Your output should look like... | true |
8d0e859942bbf5c1c23304140465496ee8fb4f54 | zackguerra/git_practice | /PycharmProjects/IntroToAlgorithmsPython/12_SortingAlgorithm/bubble_sort.py | 887 | 4.21875 | 4 | # Bubble Sort
# - Time Complexity: O(n^2)
#
# For each scan,
# For each comparison (two adjacent items),
# if left item > right item:
# "swap" two items
items = [5, 2, 1, 4, 3]
# Naive Bubble Sort -> can be improved!
def naive_bubble_sort(items):
steps = 0
for scan in range(len(items)):... | true |
5d83e64d0b90935ff1f01fb4565dd914c3060628 | HasibeZaferr/PythonBasicExamples | /tuples.py | 745 | 4.34375 | 4 | # -*- coding: utf-8 -*-
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')
print (tuple) # tuple içindeki tüm elemanları yazar.
print (tuple[0]) # tuple içindeki ilk elemanı yazar.
print (tuple[1:3]) # 2. elemandan 3. elemana kadar olanları yazar.
print (tuple[2:]) # 3... | false |
6c253aa9c69ea1a582068e67507a27c1143a1fbb | Akshaykumara62/Assignment-1 | /Factorial Assignment.py | 391 | 4.28125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
#5! = 1*2*3*4*5 =120
# In[13]:
factorial = 1
num = 5
if num<0:
print("factorial does not exist for negative numbers")
elif num==0:
print("the factorial of 0 is 1")
else:
for i in range(1,num+1):
factorial=factorial * i
print("the factorial o... | false |
87054dbe6be6523dbe9af5a6eb9c4e636d74a338 | Himstar8/Algorithm-Enthusiasts | /algorithms/sorting/shell_sort/shell_sort.py | 565 | 4.15625 | 4 | def shell_sort(arr):
length = len(arr)
h = 1
# find the starting h value
while h < length / 3:
h = 3 * h + 1
while h >= 1:
for i in range(h, length):
tmp = arr[i]
pos = i
while pos >= h and arr[pos - h] > tmp:
arr[pos] = arr[pos - ... | false |
1c0c8fc7666041fba47bcec27315971b5d13c746 | Himstar8/Algorithm-Enthusiasts | /algorithms/arrays/search_in_rotated_sorted_array/search_in_rotated_sorted_array.py | 824 | 4.21875 | 4 | def search_in_rotated_sorted_array(nums, target):
def binary_search(start, end):
while start <= end:
mid = (end + start) // 2
if target == nums[mid]:
return mid
elif target > nums[mid]:
start = mid + 1
else:
end ... | false |
2f265398b7026b9291f91c99981fbc0024a12e96 | np-n/Python-Basics-GCA | /Session 1/Variable.py | 1,499 | 4.4375 | 4 |
"""-------------------------------------------------"""
##print("Hello World") # First program
msg = "Hello World"
##print(msg)
"""-------------------------------------------------"""
# Knowing the type of the variable
##print("Msg is of type: ", type(msg))
##print("1 is of type: ", type(1))
##print("-1 is of type:... | true |
925f6c07306067409e400ce657ac9a00932c61e5 | np-n/Python-Basics-GCA | /Session 3/reverse_string.py | 431 | 4.25 | 4 |
"""
Module to reverse a string either a word or sentence
using loops and inbuilt methods
"""
sentence = "Python is beautiful"
_reverse = []
# print(len(sentence))
# Using loops
##for c in range(len(sentence)-1, -1, -1):
## # print(sentence[c])
## _reverse.append(sentence[c])
##
### print(_reverse)
##
... | true |
e1fb187e9da12e64a048cc922a2ef8c753f02200 | 8chill3s/py4e | /ex_5_2.py | 546 | 4.1875 | 4 | largest = None
smallest = None
while True:
num = input('Enter a number: ')
if num == 'done': break
#validate input
try:
num = int(num)
except:
print('Invalid input')
continue
#compare integers
if largest is None:
largest = num
elif nu... | true |
ef5950d0d2be143fd223df9f191fa60f7be0b9d4 | AtheeshRathnaweera/Cryptography_with_python | /hash.py | 1,073 | 4.1875 | 4 | from Crypto.Hash import SHA256
print ("\n\t\t____________ PASSWORD MANAGEMENT DEMO USING HASH VALUES ____________\n")
createdHash = 0
#Check the created password and validate
def passwordCreation():
userPw = input("\tCreate a new password : ")
print ("\tPassword: "+userPw)
global createdHash
created... | false |
b95f5e7efa0c5dfc3ac527dac1f8a33a1443843b | netxeye/Python-programming-exercises | /answers/q65.py | 1,039 | 4.21875 | 4 | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
def question65_fibonacci(n):
if not isinstance(n, int):
raise ValueError('Exception: Function only accepts integer value')
if n == 1:
return 1
elif n == 0:
return 0
else:
return question65_fibonacci(n - 1) + question65_fib... | false |
641a2855da5e639eaa2b6f2bd0219fe29bbd39f1 | techsoftw/General-Coding | /Python/lab8.2.py | 1,644 | 4.21875 | 4 | #!/usr/bin/python
# NAME: Dylan Tu
# FILE: lab8.2.py
# DESC: Connect to sqlite3 database, insert and prints data
import sqlite3
# sqlite3.connect creates a file named 'databasefile.db' on the system.
connection = sqlite3.connect('week16.db')
# The cursor is the control structure that traverses records in the database.... | true |
d9d91e1f2191bd6722dac905a5008ecb75773af9 | viver2003/school | /odd>even.py | 656 | 4.28125 | 4 | x = float(input('input a number: '))
y = float(input('input another number: '))
n = float(input('input yet another number: '))
if x % 2 == 0 and y % 2 == 0:
print 'There are more even numbers than odd numbers!'
if x % 2 == 0 and n % 2 == 0:
print 'There are more even numbers than odd numbers!'
if y % 2 == 0 an... | false |
661be2d62d9259abc244533ccccc8ccfdb408b3b | ttop5/ChallengePython | /page_02/19.py | 367 | 4.21875 | 4 | # 思路一:转换成同字符以后用in:
UPPER = a.upper()
if 'LOVE' in UPPER:
print 'LOVE'
else:
print 'SINGLE'
# 或者使用find
UPPER = a.upper()
if UPPER.find('LOVE') >= 0:
print 'LOVE'
else:
print 'SINGLE'
# 思路二:使用正则
import re
flag = re.findall("[lL][oO][vV][eE]",a)
if flag:
print 'LOVE'
else:
print 'SINGLE'
| false |
d3ac5b7e14663381177c3d0a2ca40d63cecfe139 | Wambita/pythonprework | /looping/forloop/for_loop.py | 327 | 4.375 | 4 | #A for loop is used when one wants to repeat something a number of times. Just like the if statements, blocks of code in a for loop are indented, otherwise they will not run.
numbers = [1,2,3,4,5]
for number in numbers:
print(number)
letters = ['a','b','c','d','e','f','g','h']
for letter in letters:
print(... | true |
0b46922e480d9e580a6b613afc9da7260cd11c10 | Vitalii-Tolkachov/Test_05092020 | /home_work_3/6.py | 552 | 4.3125 | 4 | # Пишем программу, которая попросит пользователя ввести слово
# (строка без пробелов в середине, а вначале и в конце пробелы могут быть),
# состоящее только из символов букв.
# Пока он не введёт правильно, просите его ввести.
while True:
mess = input("enter no space word: ")
mess = mess.strip()
if ' ' not ... | false |
496b1b48419b12ca3a808e5ddf2c527e889a4983 | Eternally1/web | /python/基础/one16.py | 615 | 4.1875 | 4 | """
一个摄氏度 华氏度转换的例子
"""
class Celsius:
def __init__(self,value=26.0):
self.value = value
def __get__(self,instance,owner):
return self.value
def __set__(self,instance,value):
self.value = value
class Fahrenheit:
def __get__(self,instance,owner):
return instance.cel * 1.... | false |
16108ab9efad2788494da28d46bb1074c77d9458 | AJV1416/test2 | /Story.py | 981 | 4.21875 | 4 | start = '''
You are now playing as Alice from Wonderland, Try and get through all the Disney characters!
'''
keepplaying = "yes"
print(start)
while keepplaying == "yes" or keepplaying =="Yes":
print("Mickey is your first character, make sure you answer his question to get through")
userchoice = input("What i... | true |
733b4f77c9f50f7d09226b4f44363bca86e1b25d | tmiklu/hra | /game.py | 1,850 | 4.15625 | 4 | import os
import random
print("Zahraj si hru kamen, papier a noznice")
print("Vzdy napise len jedno slovo: kamen, papier alebo noznice")
# score
your_score = 0
# game cycle
while True:
if your_score == -1:
print("Koniec hry, prehral si! ---> Tvoje score: " + str(your_score))
break
print("#########"... | false |
62d58174a8ded907a52059b474528397a55d694d | dlx24x7/Automate_boring_stuff_w_Python | /vampire.py | 348 | 4.21875 | 4 | # this code teaches you how to program
# Its a great way to learn coding
name = 'sam'
age = 2001
print(age)
if name == 'Alice':
print('Hi, Alice.')
elif age < 12:
print('You are not Alice, kiddo.')
elif age > 2000:
print('Unlike you, Alice is not an undead, immortal vampire.')
elif age > 100:
print('Yo... | true |
8518c2915a015826ba851b3f509e9b323d6d7bd5 | bgoldstone/Computer_Science_I | /Labs/5_factorial.py | 444 | 4.3125 | 4 | # 5_factorial.py
# A program that asks the user for input and tells user what that numbers factorial is
# Date: 9/22/2020
# Name: Ben Goldstone
num = 0
while num >= 0:
num = int(input("Enter an integer (negative to quit): "))
factorial = 1
# if negative print a goodbye message
if num < 0:
print(... | true |
d53451899b3bc1a4dc06537a2be24b93bf2a1ec4 | syth3/Teaching-Tech-Topics | /Python/Loops/break_keyword.py | 335 | 4.21875 | 4 | print("Break Keyword with a while loop")
counter = 0
while counter < 10:
counter += 1
if counter == 3:
print("Exit the loop entirely")
break
print(counter)
print()
print("Break Keyword with a for loop")
for i in range(10):
if i == 5:
print("Exit the loop entirely")
brea... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.