blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
37f0162910ed4541fbad07ba16b71d71b406449f | BeniyamL/alx-higher_level_programming | /0x03-python-data_structures/2-replace_in_list.py | 384 | 4.3125 | 4 | #!/usr/bin/python3
def replace_in_list(my_list, idx, element):
"""
replace_in_list - replace an element of a list
@my_list: the given list
@idx: the given index
@element: element to be replaced
@Return : the replaced element
"""
if idx < 0 or idx >= len(my_list):
return my_list
... | true |
a7ce1f8eca0bed05c35f6cbaa0671ec1febea9df | BeniyamL/alx-higher_level_programming | /0x04-python-more_data_structures/6-print_sorted_dictionary.py | 311 | 4.40625 | 4 | #!/usr/bin/python3
def print_sorted_dictionary(a_dictionary):
"""function to sort a dictionary
Arguments:
a_dictionary: the given dictionary
Returns:
nothing
"""
sorted_dict = sorted(a_dictionary.items())
for k, v in sorted_dict:
print("{0}: {1}".format(k, v))
| true |
0497d2f931697ad17a338967d629b2c430ece31b | BeniyamL/alx-higher_level_programming | /0x0B-python-input_output/100-append_after.py | 660 | 4.28125 | 4 | #!/usr/bin/python3
""" function defintion for append_after
"""
def append_after(filename="", search_string="", new_string=""):
""" function to write a text after search string
Arguments:
filename: the name of the file
search_string: the text to be searched
new_string: the string to be... | true |
ee769eb6ad867b1e9b7cb2462c2b48ac2abaf5b8 | BeniyamL/alx-higher_level_programming | /0x07-python-test_driven_development/4-print_square.py | 485 | 4.46875 | 4 | #!/usr/bin/python3
""" print_square function """
def print_square(size):
""" function to print a square of a given size
Arguments:
size: the size of the square
Returns:
nothing
"""
if type(size) is not int:
raise TypeError("size must be an integer")
if type(size) is in... | true |
2d55b3451ad2d1d344cb614b0b8ab8eb085fb125 | JanhaviMhatre01/pythonprojects | /flipcoin.py | 618 | 4.375 | 4 | '''
/**********************************************************************************
* Purpose: Flip Coin and print percentage of Heads and Tails
* logic : take user input for how many times user want to flip coin and generate head or
* tail randomly and then calculate percentage for head and tail
*
* @author : Janh... | true |
65d88e7d92ca1e0ddde0bef59759663520c591fe | TAndrievskiy/Test_python | /hw4/longest_word.py | 1,233 | 4.21875 | 4 | """
1. Вводится строка
2. Программа считает количество слов в введенной строке и выводит на экран.
2. Программа определяет самое длинное слово и его длину и выводит на экран.
___________________________________________________________________________
Например:
###
Hello,world! I am learning py... | false |
38003895f46c8d64b626005812e6a18b649d233b | TAndrievskiy/Test_python | /hw5/practice_1.py | 1,704 | 4.25 | 4 | """
Программу принимает на ввод строку string и число n.
Выводит на экран строку с смещенными символами на число n.
Весь код можно написать в одной функции main,
но рекомендуется разбить код на несколько функций, например:
- main
- функция для получения не пустой строки.
- функция для получ... | false |
fc8f5cda197bf5b0209f2c18b3089d3dc7d08be9 | elenabarreto/includeTec | /Situacion-S3.py | 474 | 4.125 | 4 | # -*- coding: utf-8 -*-
print "___________________"
print "-*- EJERCICIO 3 -*-"
print "___________________"
print " "
print " "
print " "
print "_______________________________________________________________________________"
print " "
presion = input("Ingrese valor de presión: ")
volumen = input("Ingrese valor de vo... | false |
825238465b41ec4ac2979816c1ef236cc759048a | AvinashMishra1997/projects-for-all | /Dictionary.py | 841 | 4.15625 | 4 | from PyDictionary import PyDictionary
dictionary = PyDictionary()
print ('choose if u want the antonym or synonym or meaning or translations of a word')
d=raw_input ("Enter 'a' for antonym 's' for synonym 'm' for meanings and 't' for translations : ")
if d=='m':
word=raw_input('Enter the word you want the meaning... | false |
a4eddae42b365b5884a465424f2a6ca1203f358f | iliankostadinov/hackerrank-python | /write-a-function.py | 537 | 4.15625 | 4 | #!/usr/bin/python
def is_leap(year):
leap = False
if year % 400 == 0:
leap = True
elif year % 100 == 0:
leap = False
elif year % 4 == 0:
leap = True
return leap
if __name__ == '__main__':
year = int(raw_input())
if year < 1900:
print "You should enter y... | false |
8cb108ab7d77ee8f7d7e44b68b2d0b0fdd77849b | rodrigo-meyer/python_exercises | /odd_numbers_selection.py | 340 | 4.3125 | 4 | # A program that calculates the sum between all the odd numbers
# that are multiples of 3 and that are in the range of 1 to 500.
# Variables.
adding = 0
counter = 0
for c in range(1, 501, 2):
if c % 3 == 0:
counter = counter + 1
adding = adding + c
print('The total sum of {} values is {}'.forma... | true |
b04b13fffc01f746d2e6795682fe9d993702b865 | sunilkum84/golang-practice-2 | /revisiting_ctci/chapter3/MultiStack_3_1.py | 1,314 | 4.25 | 4 | """
use one array to implement three stacks.
i.e.
array := []Stack{3}
have functions to call the array position
and perform the stacks command on the given position
"""
from stack import Stack
class MultiStack():
def __init__(self):
self.__stack_list = [Stack(), Stack(), Stack()]
self.__pos_err = 'MultiSta... | false |
34c3bec34c7d4c18596381f3ac1c7164a183091f | gulnarap1/Python_Task | /Task3_allincluded.py | 2,822 | 4.1875 | 4 | #Question 1
# Create a list of the 10 elements of four different types of Data Types like int, string,
#complex, and float.
c=[2, 6, 2+4j, 3.67, "Dear Client", 9, 7.9, "Hey!", 4-3j, 10]
print(c)
#Question 2
#Create a list of size 5 and execute the slicing structure
my_list=[10, 20, ["It is me!"], 40, 50]
#Slicing
S... | true |
46f0f7ed004db78260c547f99a3371bb64ce6b08 | MemeMasterJeff/CP1-programs | /9-8-payroll-21.py | 2,572 | 4.125 | 4 | #William Wang & Sophia Hayes
#9-8-21
#calculates payroll for each employee after a week
#defins the employee class
try:
class employee:
def __init__(self, name, pay):
self.name = name
self.pay = pay
#inputted/calculated values
self.rate = float(inp... | true |
b7c53f9f71b18e7b850c9d6327507cd6590a43e3 | gomezquinteroD/GWC2019 | /Python/survey.py | 557 | 4.1875 | 4 | #create a dictionary
answers = {}
# Create a list of survey questions and a list of related keys that will be used when storing survey results.
survey = [
"What is your name?",
"How old are you?",
"What is your hometown?",
"What is your date of birth? (DD/MM/YYYY)"]
keys = ["name", "age", "hometown", "... | true |
4e808368dcb9f4e791aca828f31a17b47c6947dc | macrespo42/Bootcamp_42AI | /day00/ex03/count.py | 1,009 | 4.375 | 4 | import sys
import string
def text_analyzer(text=None):
"""
This functions count numbers of upper/lower letters, punctuation spaces
and letters in a string
"""
upper_letters = 0
lower_letters = 0
punctuation = 0
spaces = 0
text_len = 0
if (text == None):
print("Wh... | true |
26d14c6b1786baf307400f126ca9c81f183d0aa3 | AndrewBatty/Selections | /Selection_development_exercise_2.py | 368 | 4.125 | 4 | # Andrew Batty
# Selection exercise:
# Development Exercise 2:
# 06/102014
temperature = int(input("Please enter the temperature of water in a container in degrees centigrade: "))
if temperature <= 0:
print("The water is frozen.")
elif temperature >=100:
print("The water is boiling.")
else:
pr... | true |
c224d08507b99b58f1deee67a61a110567c28169 | whp5924/Python | /fig09_03.py | 860 | 4.21875 | 4 | #
# 基类 派生类
import math
class Point:
def __init__(self,xValue=0,yValue=0):
self.x=xValue
self.y=yValue
class Circle(Point):
def __init__(self,x=0,y=0,radiusValue=0):
Point.__init__(self,x,y)
self.radius=float(radiusValue)
def area(self):
return math.pi * self.radius **... | false |
3b4608f02475a5cb37397511b3fa5bad4c4007e2 | earth25559/Swift-Dynamic-Test | /Number_3.py | 530 | 4.1875 | 4 | test_array = [-2, -3, 4, -6, 1, 2, 1, 10, 3, 5, 6, 4]
def get_index(max_val):
for index, value in enumerate(test_array):
if(value == max_val):
return index
def find_index_in_array(arr):
max_value = arr[0]
for value in arr:
if value > max_value:
max_value = value
... | true |
e4ad61b609bed028b402265b224db05ceef7e2de | itaditya/Python | /Maths/toPostfixConv.py | 937 | 4.125 | 4 | from stack import Stack
def prec(operator):
if(operator == '^'):
return 3
elif(operator == '*' or operator == '/'):
return 2
elif(operator == '+' or operator == '-'):
return 1
else:
return -1
# print("Not a valid operator")
def postfixConv():
s = Stack()
e... | true |
56e9ead65e1b1eea967b3f3a2f54634db55a61b0 | Yu-python/python3-algorithms | /5. LeetCode/104.maximum-depth-of-binary-tree/3.py | 1,764 | 4.1875 | 4 | """
方法三: 广度优先搜索(BFS)
https://leetcode-cn.com/leetbook/read/data-structure-binary-tree/xefb4e/
解题思路:
首先我们引入一个队列,这是把递归程序改写成迭代程序的常用方法。
1. 队列中只存放「某一层的所有节点」
2. 先记录这一层的节点数 size (队列中元素个数)
3. 迭代 size 次,每次出队一个元素,获取它的左右子节点再入队
4. 迭代完 size 次后,队列中就是下一层的所有节点。将最终结果 ans 值加 1
5. 重复步骤 1 - 4。二叉树的最大深度即为 ans
时间复杂度:O(n),其中 n 为二叉树节点的个数。每个... | false |
275fe7b79c7c091237ce170cb043b4983a1fc1b2 | SweLinHtun15/GitFinalTest | /Sets&Dictionaries.py | 1,520 | 4.1875 | 4 | #Sets
#include a data type for sets
#Curly braces on the set() function can be used create sets.
basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
print(basket)
#Demonstrates set operations on unique letters from two words
a = set('abracadabra')
b = set('alacazm')
a # unique letter in a
a - b ... | true |
38f1a362e3adc4f816c57980606498d5ab1b56b3 | tylors1/Leetcode | /Problems/longestSubarray.py | 681 | 4.125 | 4 | # subarray sum - find the longest subarray sequence
# that adds up to a target
# FOLLOW UPS:
# 1. How would we modify this if we're looking for min subarray sequence?
# 2. How would we modify this if we're looking for min subarray sequence equal to OR greater than target?
def longestSubarray... | false |
885d43c1619d5ddd8166a60492eb74f026778c5f | Candy-Robot/python | /python编程从入门到实践课后习题/第七章、用户输入与循环/while.py | 1,683 | 4.15625 | 4 | """
prompt = "\nwhat Pizza ingredients do you want: "
prompt += "\n(Enter 'quit' when you are finished) "
while True:
order = input(prompt)
if order == 'quit':
break
print("we will add this "+order+" for you")
prompt = "\nwhat Pizza ingredients do you want: "
prompt += "\n(Enter 'quit' when you ... | true |
07df07e0d977f286a3cb28c187f5a4adbbd2fd12 | samyhkim/algorithms | /56 - merge intervals.py | 977 | 4.25 | 4 | '''
sort by start times first
if one interval's end is less than other interval's start --> no overlap
[1, 3]: ___
[6, 9]: _____
if one interval's end is greater than other interval's started --> overlap
[1, 3]: ___
[2, 6]: _____
'''
def merge(intervals):
merged = []
intervals.sort(key=lambda i: i[0]) ... | true |
79ca667df5a747c3926ca8806022df645789d6d5 | abisha22/S1-A-Abisha-Accamma-vinod | /Programming Lab/27-01-21/prgm4.py | 437 | 4.25 | 4 | Python 3.9.1 (tags/v3.9.1:1e5d33e, Dec 7 2020, 17:08:21) [MSC v.1927 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> def word_count(str):
counts=dict()
words=str.split()
for word in words:
if word in counts:
counts[word]+=1
else:
counts[word]=... | true |
a00231b5aaa06630c3237083ca1650384ce7d71b | FJLRivera86/Python | /Dictionary.py | 1,118 | 4.53125 | 5 | #DICTIONARY {}: Data structure Like Tuple or List
#It's possible save elements,list or tuples in a dictionary
firstDictionary = {"Germany":"Berlin", "France":"Paris", "England":"London", "Spain":"Madrid"}
#To print a value, It's necessary say its KEY
print(firstDictionary)
print(firstDictionary["England"])
#ADD eleme... | true |
2d042a110b5642719a60a1d5aedc4528bb40cb86 | momentum-cohort-2019-05/w2d1-house-hunting-redkatyusha | /house_hunting.py | 754 | 4.1875 | 4 | portion_down_payment = .25
current_savings = 0
r = .04
months = 0
annual_salary_as_str = input("Enter your annual salary: ")
portion_saved_as_str = input(
"Enter the percent of your salary to save, as a decimal: ")
total_cost_as_str = input("Enter the cost of your dream home: ")
annual_salary = int(annual_salary_a... | true |
f2ce62028c31efdc396f3209e1c30681daa87c17 | pmxad8/cla_python_2020-21 | /test_files/test_1.py | 769 | 4.21875 | 4 | ################### code to plot some Gaussians ####################################
#### import libraries ####
import math
import numpy as np #import numerical library
import matplotlib.pyplot as plt #allow plotting
n = 101 # number of points
xx = np.linspace(-10,10,n) #vector of linearly spaced points
s = 0.5,1,1.5... | true |
b708990ef5d70f151ca468a13784f9b6c49745db | san33eryang/learnpy | /sorted.py | 896 | 4.21875 | 4 |
# -*- coding: utf-8 -*
# 排序数字,或按照绝对值排序
print(sorted([-2,-6,-99,9,8]))
print(sorted([-2,-6,-99,9,8],key = abs))
#排序字母,按照大小写或忽略大小写排序
print(sorted(['bob','about','Zoo','Credit','credit']))
print(sorted(['bob','about','Zoo','Credit','credit'],key=str.lower))
print(sorted(['bob','about','Zoo','Credit','credit'],key=str.l... | false |
7deff2841c1b9164ff335a4b1cb11c3266482a00 | SuryaDhole/tsf_grip21 | /main.py | 2,683 | 4.125 | 4 | # Author: Surya Dhole
# Technical TASK 1: Prediction using Supervised ML (Level - Beginner)
# Task Description: in this task, we will predict the percentage of marks that a student
# is expected to score based upon the number of hours
# they studied. This is a simple linear regression task as it involves just two var... | true |
eeb9ffe5b8ebe9beb9eda161b15b61ccea90ba9a | RezaZandi/Bank-App-Python | /old_code/switch_satements.py | 758 | 4.15625 | 4 |
"""
def main():
print("hi")
main_console = ("\nSelect an option to begin:")
main_console += ("\nEnter 0 to Create a new account")
main_console += ('\nEnter 1 to Deposit')
main_console += ('\nEnter 2 to Withdraw')
main_console += ('\n What would you like to do?: ')
while True:
user_option = int(i... | true |
382fbdd4d1b95633025b9f2951ddaa904a1727f1 | AdaniKamal/PythonDay | /Day2/Tuple.py | 2,762 | 4.53125 | 5 | #Tuple
#1
#Create a Tuple
# Set the tuples
weekdays = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday")
weekend = "Saturday", "Sunday"
# Print the tuples
print('-------------------------EX1---------------------------------')
print(weekdays)
print(weekend)
#2
#Single Item Tuples
a = ("Cat")
b = ("Cat",)
print('... | true |
8d96260c69e129db0e133a1d23042af4eea88c40 | gongnanxiong235/fullstack | /day10/lesson_set.py | 990 | 4.15625 | 4 | # author:gongnanxiong
# date:2018/11/22
'''
set的两大用途:
1.去重,把列表转换成set之后自动去重
2.关系式
set的key都是可哈希的,也就是key不能是列表和字典
set是可变的,非可哈希的,所以set也不能作为dict的key
set是无顺序的,所以不能像list一样通过下标找到元素,只能通过遍历和iter的方式
set是无顺序的,所以set.pop()是随机删除一个值
'''
set_a=set([1,2,3])
set_b=set([1,2,3])
print(set_a==set_b)
set_b.add(4)
print(set_a<set_b)
set_a.u... | false |
9ab16b835f79e48d35d6ceed5b216e73cc9a090b | RobsonDaniel/Treinamento-python3 | /aula6_atividade.py | 1,235 | 4.21875 | 4 | '''
Exercício: Escreva uma função que recebe um objeto de coleção e retorna o valor do maior número
dentro dessa coleção. Faça outra função que retorna o menor número dessa coleção.
'''
# def maior_numero(lista_numero):
# return max(lista_numero)
#
# def menor_numero(lista_numero):
# return min(lista_... | false |
9ffe03358e681158af1452776150deb8057eaa29 | violetscribbles/Learn-Python-3-the-Hard-Way-Personal-Exercises | /Exercises 1 - 10/ex9.py | 791 | 4.28125 | 4 | # Here's some new strange stuff, remember type it exactly.
# Defines 'days' variable as a string
days = "Mon Tue Wed Thu Fri Sat Sun"
# Defines 'months' variable as a string. Each month is preceded by \n, which
# is an escape character that tells python to create a new line before the
# text.
months = "\nJan\nF... | true |
361d9db0d848b177a18fb734d04451616ef06a2a | Rolodophone/various-python-programs | /Completed/String manipulation programming challenges 2.py | 689 | 4.15625 | 4 | while True:
string = input("\n\nEnter a string")
option = input("Would you like to:\nFind the [N]umber of characters in "
"the string\n[R]everse the string\nConvert the string "
"to [U]ppercase\nConvert the string to [L]owercase\n")
if option == "n":
pri... | false |
974f629117846daae4de8b0e22b1d68407763078 | study-material-stuff/Study | /Study/Python/Assignments/Assignment 8/Assignment8_5.py | 570 | 4.28125 | 4 | #5.Design python application which contains two threads named as thread1 and thread2.
#Thread1 display 1 to 50 on screen and thread2 display 50 to 1 in reverse order on
#screen. After execution of thread1 gets completed then schedule thread2.
import threading;
def DispNumbers():
for no in range(1,51):
prin... | true |
2fb056ddefd2368f9947f213e92627b9e09071e1 | study-material-stuff/Study | /Study/Python/Assignments/Assignment 4/Assignment4_1.py | 238 | 4.28125 | 4 | #1.Write a program which contains one lambda function which accepts one parameter and return
#power of two.
powerof2 = lambda num : num * num;
num = int(input("Enter the number :"));
print("power of the number is ",powerof2(num)); | true |
d023f2fe5bfb44a3ca32176ad557542eeaf0883b | Devil-Rick/Advance-Task-6 | /Inner and Outer.py | 506 | 4.1875 | 4 | """
Task
You are given two arrays: A and B .
Your task is to compute their inner and outer product.
Input Format
The first line contains the space separated elements of array A .
The second line contains the space separated elements of array B .
Output Format
First, print the inner product.
Second, p... | true |
c1108c9ae69f08de277b80fbba0d450c245fe081 | mygoal-javadeveloper/Dataquest.io | /Machine Learning Introduction/Calculus For Machine Learning/Finding Extreme Points-159.py | 565 | 4.15625 | 4 | ## 3. Differentiation ##
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-5,6,110)
y = -2 * x + 3
plt.plot(x,y)
plt.show()
## 6. Power Rule ##
slope_one = 5 * (2 ** 4)
print(slope_one)
slope_two = 9 * (0 ** 8)
print(slope_two)
## 7. Linearity Of Differentiation ##
slope_three = 5 * (1 ** 4) - ... | false |
e9ff6b17552a2cc278d5817ce0ced6ef730cc144 | ilakya-selvarajan/Python-programming | /mystuff/4prog2.py | 353 | 4.21875 | 4 | #a program that queries the user for number, and proceeds to output whether the number is an even or an odd number.
number=1
while number!=0:
number = input("Enter a number or a zero to quit:")
if number%2==0 and number!=0:
print "That's an even number"
continue
if number%2==1:
print "That's an odd number"
... | true |
876eb77d4a81863b5d478f37827c0298a4270cf2 | ilakya-selvarajan/Python-programming | /mystuff/7prog6.py | 440 | 4.125 | 4 | #A function which gets as an argument a list of number tuples, and sorts the list into increasing order.
def sortList(tupleList):
for i in range( 0,len(tupleList) ):
for j in range(i+1, len(tupleList) ):
if tupleList[j][0]*tupleList[j][1]<tupleList[i][0]*tupleList[i][1]:
temp=tupleList[j]
tupleList[j]=t... | true |
eee40d974a515868c2db25c959e1cfa303002d00 | ilakya-selvarajan/Python-programming | /mystuff/8prog4.py | 433 | 4.21875 | 4 | # A function to find min, max and average value
from __future__ import division
def minMaxAvg(dict):
sum=0
myTuple=()
myValues= dict.values() #extracting the values
for values in myValues:
sum+=values
avg=sum/len(myValues) #Calculating the average
myTuple=(min(myValues),max(myValues),avg) #Return... | true |
2600172fbc0223edb28af3000ea79adc68a81210 | luisauribe/Python-languaje | /listas.py | 1,310 | 4.15625 | 4 | +---+---+---+---+---+---+
| P | y | t | h | o | n |
+---+---+---+---+---+---+
0 1 2 3 4 5 6
-6 -5 -4 -3 -2 -1
mi_lista = [17, 39, "Laura", True]
print(mi_lista)
# Asigna un valor nuevo al indive 1
mi_lista[1] = 7
print(mi_lista[:])
# Accede al indice 1 e imprime desde el 1 hasta el 3 omitiendo ... | false |
12a89096fd6ad6bab15da2f113bd6d6067292380 | luisauribe/Python-languaje | /ejercio_1.py | 335 | 4.15625 | 4 | num_1 = int(input("Introduce un numero: "))
num_2 = int(input("Introduce otro numero: "))
def devuelve_max(num_1, num_2):
if num_1 > num_2:
print("El número más alto es: ", num_1)
elif num_1 < num_2:
print("El número mas alto es: ", num_2)
else:
print("Son iguales")
devuelve_max(nu... | false |
68b01adeba8e433530175f0c39a80c5c336d1ce3 | thinboy92/HitmanFoo | /main.py | 2,562 | 4.21875 | 4 | ### Animal is-a object (yes, sort of confusing) look at the extra credit
class animal(object):
def __init__(self, type):
self.type = type
def fly(self):
print "This %s can fly" %(self.type)
## Dog is-a animal
class Dog(animal):
def __init__(self, name):
# class Doh has-a __init__ that accepts self an... | true |
03bc0cf52a337355dc9d829995465da3778f8531 | bulsaraharshil/MyPyPractice_W3 | /class.py | 1,071 | 4.40625 | 4 | class MyClass:
x = 5
print(MyClass)
#Create an object named p1, and print the value of x
class MyClass:
x=5
p1=MyClass()
print(p1.x)
#Create a class named Person, use the __init__() function to assign values for name and age
class Person:
def __init__(self,name,age):
self.name = name
self.age = ... | true |
1f468a2055ef8548a517fb5333f574737a2da217 | bulsaraharshil/MyPyPractice_W3 | /lambda.py | 768 | 4.5 | 4 | #lambda arguments : expression
#A lambda function that adds 10 to the number passed in as an argument, and print the result
x = lambda x:x+5
print(x(5))
#A lambda function that multiplies argument a with argument b and print the result
x = lambda a,b:a*b
print(x(5,6))
#A lambda function that sums argument a, b, and c... | true |
e42b70c7d1d2a3284808ef118eedfb1a1a90d63e | BI4HUU/WEB | /py.py | 2,703 | 4.28125 | 4 | print("Показать ето в консоль")
name = 8 # переменная
input("1") # Предлагает ввести даные
# Преобразовать тип даных
int(name) # В число
str(name) # В строку
float(name) # В число с точкой
del name # Удалить переменную
name += 80
# Условные операции
ten = 10
if ten == 1:
print("ok1")
elif t... | false |
8fdbe01a6176568addcfe99fa3eafbf386c740f0 | dindamazeda/intro-to-python | /lesson3/homework/3.third_task.py | 1,606 | 4.40625 | 4 | # TREĆI ZADATAK
# Dat je niz imenica u nasumičnom redosledu.
# Napisati program koji će da grupiše imenice u novu listu na osnovu početnog slova tj. da ih poređa po redosledu
# Međutim ima jedan uslov - prve imenice u novoj listi moraju da počinju sa slovom 'm', a nakon toga treba da ide po alfabetu
# Videti primer isp... | false |
06dc005308c02f4950075b21aa04fec50a073fc7 | dindamazeda/intro-to-python | /lesson3/homework/6.sixth_task.py | 1,038 | 4.15625 | 4 | # ŠESTI ZADATAK
# # Napisati program koji će da uzme dve liste i od njih napravi dictionary gde će elementi prve liste biti ključevi, a elementi druge liste vrednosti
# ### primer ###
# # voce = ['banane', 'kivi', 'limun', 'lubenica', 'grejpfrut', 'jabuke', 'ananas']
# # cene = [127.5, 119.8, 220.3, 84.4, 255.8, 65.3, ... | false |
0c1e3c615df5d832a4f875b51a8ec27a25dddfa8 | dindamazeda/intro-to-python | /lesson4/homework/5. frequency-in-paragraph.py | 2,916 | 4.25 | 4 | # PETI ZADATAK
# Napisaćemo program koji utvrđuje frekventnost slova u srpskom jeziku nad datim tekstom
# Potrebno je ispisati rečnik sa slovom i procenat (udeo) tog slova u odnosu na ukupan broj slova
# npr. ako je dat tekst -> patka je slatka, program treba da zna sledeće:
# u tekstu ima 13 slova (razmaci se ne račun... | false |
36b2d60352a9e55abb53d30f25e98319383dadc0 | dindamazeda/intro-to-python | /lesson3/exercise/7.element-non-grata.py | 542 | 4.28125 | 4 | # We have a list of sweets. Write a program that will ask the user which is his least favourite sweet and then remove that sweet from the list
### example ###
# sweets = ['jafa', 'bananica', 'rum-kasato', 'plazma', 'mars', 'bananica']
# program: Which one is your least favourite?
# korisnik: bananica
# program: ['jafa'... | true |
05cb1521168d0320f080cd8c25137ea9ef6e91b9 | dindamazeda/intro-to-python | /lesson2/exercises/3.number-guessing.py | 821 | 4.1875 | 4 | # Create list of numbers from 0 to 10 but with a random order (import random - see random module and usage)
# Go through the list and on every iteration as a user to guess a number between 0 and 10
# At end the program needs to print how many times the user had correct and incorrect guesses
# random_numbers = [5, 1, 3,... | true |
227d3c1780cca1ea0979d759c9a383fcdafb2314 | dindamazeda/intro-to-python | /lesson1/exercises/6.more-loops_dm.py | 612 | 4.3125 | 4 | # write a loop that will sum up all numbers from 1 to 100 and print out the result
### example ###
# expected result -> 5050
sum = 0
for numbers in range(1, 101):
sum = sum + numbers
print(sum)
# with the help of for loop triple each number from this list and print out the result
numbers = [5, 25, 66, 3, 100, 34]... | true |
bb941f4da9976abb554a43fe2d348ec956587cf1 | micalon1/small_tasks | /part5.py | 760 | 4.125 | 4 | shape = input("Enter a shape: ")
s = "square"
r = "rectangle"
c = "circle"
if shape == s:
l = int(input("What is the length of the square? "))
print("The area of the square is {}.". format(l**2))
elif shape == r:
h = int(input("What is the height of the rectangle? "))
w = int(input("What is the ... | true |
7bd385f1465918ac1c73311062647516a0d8ce74 | ritesh2k/python_basics | /fibonacci.py | 328 | 4.3125 | 4 | def fibonacci(num):
if num==0: return 0
elif num==1: return 1
else:
return fibonacci(num-1)+fibonacci(num-2) #using recursion to generate the fibonacci series
num=int(input('How many fibonacci numbers do you want? \n'))
print('Fibonacci numbers are :\n')
for i in range(num):
print(fibonacci(i) , end=' ')
p... | true |
7c3e9c6db39509af1c38818f60a5b9c9697697c4 | ritesh2k/python_basics | /sentence_capitalization.py | 429 | 4.3125 | 4 | def capitalization(str):
str=str.strip()
cap=''
for i in range(len(str)):
if i==0 or str[i-1]==' ':cap=cap+str[i].upper() #checking for the space and the first char of the sentence
else: cap=cap+str[i] #capitalizing the character after space
#cap =[words[0].upper()+words[1:]]
print ('The result i... | true |
7a6c27963f8e1adcba4b636cd29fdf598acdde0b | YeasirArafatRatul/Python | /reverse_string_stack.py | 492 | 4.125 | 4 | def reverse_stack(string):
stack = [] #empty
#make the stack fulled by pushing the characters of the string
for char in string:
stack.append(char)
reverse = ''
while len(stack) > 0:
last = stack.pop()
#here the pop function take the last character first thats why
... | true |
817a383769b024049a81ad3e76be36231099462d | YeasirArafatRatul/Python | /reverse_string_functions.py | 340 | 4.625 | 5 | def reverse_string(string):
reverse = "" #empty
for character in string:
"""
when we concate two strings the right string
just join in the left string's end.
"""
reverse = character + reverse
return reverse
string = input("Enter a string:")
result = reverse_string(st... | true |
2c5b1e85b26ea93a1f6636758db8889b28b7798a | tnotstar/tnotbox | /Python/Learn/LPTHW/ex06_dr01.py | 822 | 4.5 | 4 | # assign 10 to types_of_people
types_of_people = 10
# make a string substituting the value of types_of_people
x = f"There are {types_of_people} types of people."
# assign some text to some variables
binary = "binary"
do_not = "don't"
# make a string substituting last variable's values
y = f"Those who know {binary} and... | true |
d854d2f8e29e061f085af15ac1da61b4cf9a6283 | wendotdot/my-first-blog | /tutorial.py | 280 | 4.21875 | 4 | if 5 > 2 :
print("5 is greater than 2")
else :
print("5 is not greater than 2")
name = "Wendy"
def hi(name):
#print("Hi There")
#print("How are you?")
if name == "Ola":
print("Hi Ola!")
elif name == "Sonja":
print("Hi Sonja!")
else:
print("Hi Anonymous")
hi(name) | false |
833d91dfe8f65ce41b7dfa9b4ae15632a03e6170 | undefinedmaniac/AlexProjects | /Basic Python Concepts/if statements and loops.py | 1,580 | 4.40625 | 4 | # If statements are used to make decisions based on a conditional statement
# for example, the value in a variable could be used
variable1 = True
variable2 = False
if variable1:
print("True")
# else if statements can be added to check for additional conditions
if variable1:
print("Variable 1 is True")
elif ... | true |
971247c94cba717a85b4d900b0f93ae2bb6338a1 | radek-coder/simple_calculator | /run_it.py | 636 | 4.21875 | 4 | from addition import addition
from multiplication import multiplication
from division import division
from subtraction import subtraction
num_1 = int(input("Please insert your first number: "))
num_2 = int(input("Please insert your second number: "))
operation = input("Please insert your operation ")
if operation == ... | true |
f88b699c69329d90c31d9b9d18ca19bb7f671090 | Arl-cloud/Python-basics | /basics5.py | 2,327 | 4.28125 | 4 | #For loops: How and Why
monday_temperatures = [9.1, 8.8, 7.6]
print(round(monday_temperatures[0])) #print rounded number with index 0
#in 1st iteration, variable temp = 9.1, in the 2nd iteration 8.8
for temp in monday_temperatures:
print(round(temp)) #executed command for all items in an array
print("Done")
... | true |
ae35bfc0d8c5057a7d70cf79a272a353a0f15cf4 | pwgraham91/Python-Exercises | /shortest_word.py | 918 | 4.34375 | 4 | """
Given a string of words, return the length of the shortest word(s).
String will never be empty and you do not need to account for different data types.
"""
def find_short_first_attempt(string):
shortest_word_length = None
for word in string.split(' '):
len_word = len(word)
if shortest_wor... | true |
dc9a10c8f8f1cd1c46f78c475ed1ca57cc381ee1 | pwgraham91/Python-Exercises | /process_binary.py | 494 | 4.15625 | 4 | """
Given an array of one's and zero's convert the equivalent binary value to an integer.
Eg: [0, 0, 0, 1] is treated as 0001 which is the binary representation of 1
"""
def binary_array_to_number(array):
output = ''
for i in array:
output += str(i)
return int(output, 2)
assert binary_array_to_... | true |
9b8ee1df25e986a9ad3abd9134abda3f6d3970f5 | pwgraham91/Python-Exercises | /sock_merchant.py | 990 | 4.71875 | 5 | """
John works at a clothing store. He has a large pile of socks that he must pair by color for sale. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are.
For example, there are socks with colors . There is one pair of color and one of colo... | true |
7c9c234858d6903b255c291661ae61787f7c8a4f | victorcwyu/python-playground | /learn-python/functions.py | 1,273 | 4.375 | 4 | # divide code into useful blocks
# allows us to order code, make it more readable, reuse it and save time
# a key way to define interfaces to share code
# defined using the block keyword "def", followed by the function name as the block name
def my_function():
print("Yolo")
# may receive arguments (variables pass... | true |
f515c806b5240f92a077dd7ded268eaa19e8edd2 | victorcwyu/python-playground | /python-crash-course/string-replacement.py | 512 | 4.125 | 4 | # exercise: use Python's string replace method to fix this string up and print the new version out to the console
journey = """Just a small tone girl
Leaving in a lonely whirl
She took the midnight tray going anywhere
Just a seedy boy
Bored and raised in South Detroit or something
He took the midnight tray going anywhe... | true |
84bd0d4db2706319680706e1cd0621ed313fa034 | Utkarshkakadey/Assignment-solutions | /Assignment 1.py | 1,053 | 4.40625 | 4 | # solution 1
# Python program to find largest
# number in a list
# list of numbers
list1 = [10, 20, 4, 45, 99]
# sorting the list
list1.sort()
# printing the last element
print("Largest element is:", list1[-1])
#solution 2
a=[]
c=[]
n1=int(input("Enter number of elements:"))
for i in range(1,n1+1... | true |
36ca26358ff16d783d4b7bc0b24e2768879ef9b4 | NadezhdaBzhilyanskaya/PythonProjects | /Quadratic/src/Bzhilyanskaya_Nadja_Qudratic.py | 2,751 | 4.125 | 4 | import math
class Qudratic:
def __init__(self, a,b,c):
"""Creates a qudratic using the formula: ax^2+bx+c=0"""
self.a = a
self.b = b
self.c = c
self.d = (b**2)-(4*a*c)
def __str__(self):
a = str(self.a) + "x^2 + " + str(self.b) + "x + " + str(se... | true |
68202e160654a74f879656915b632679e51ccb89 | lmaywy/Examples | /Examples/Examples.PythonApplication/listDemo.py | 1,041 | 4.25 | 4 | lst=[1,2,3,4,5,6,7]
# 1.access element by index in order
print 'access element by index in order';
print lst[0];
print 'traverse element by index in order '
for x in lst:
print x;
# 2.access element by index in inverse order
print 'access element by index in inverse order'
print lst[-1];
length=len(lst... | true |
1f4619da7153fa21df1f9bb5b8b647bc566c41c5 | Piero942/calculadora | /t03alfaro/ejercicio3.py | 331 | 4.34375 | 4 | #Algoritmo para hallar la resta de 3 numeros
numero1,numero2,numero3,resta=0.0,0.0,0.0,0.0
#asignacion de valores
numero1,numero2,numero3=35.9,25.5,7.4
#calculo
resta=numero1-numero2-numero3
#mostrar valores
print("la numero1 es",numero1)
print("la numero2 es",numero2)
print("la numero3 es",numero3)
print("la resta ... | false |
62d8c229f14671d1ffacfcd65a667a1bce570b9b | aguynamedryan/challenge_solutions | /set1/prob4.py | 2,219 | 4.28125 | 4 | # -*- coding: utf-8 -*-
"""
Question:
Complete the function getEqualSumSubstring, which takes a single argument. The single argument is a string s, which contains only non-zero digits.
This function should print the length of longest contiguous substring of s, such that the length of the substring is2*N digits and the... | true |
3cf5096bbe84a7fc9fca40f3b076252d06e0d9bb | Kimuksung/bigdata | /python/carclass.py | 727 | 4.15625 | 4 | '''
동적 멤버 변수 생성
- 필요한 경우 특정 함수에서 멤버 변수 생성
self : class의 멤버를 호출 하는 역할 self.member / self.method()
'''
class Car:
door = cc = 0
name = None # null
#생성자 : 객체 + 초기화
def __init__(self , door , cc , name):
self.door = door
self.cc= cc
self.name = name
def info(self):
... | false |
26b44398c5ffb32c22b98bd8a145cca3e7540185 | usddddd/CompSci | /myfunc.py | 1,236 | 4.25 | 4 | def is_divisible_by_2_or_5(n):
"""
>>> is_divisible_by_2_or_5(8)
True
>>> is_divisible_by_2_or_5(7)
False
>>> is_divisible_by_2_or_5(5)
True
>>> is_divisible_by_2_or_5(9)
False
"""
return n % 2 == 0 or n % 5 == 0
def compare(a,b):
"""
>>> compare(5, 4)
1
>... | false |
3cb212414eb444e17899f469d89d8a2421f39517 | usddddd/CompSci | /numberlists.py | 2,385 | 4.125 | 4 | def only_evens(numbers):
"""
>>> only_evens([1, 3, 4, 5, 6, 7, 8])
[4, 6, 8]
>>> only_evens([2, 4, 6, 8, 10, 11, 0])
[2, 4, 6, 8, 10, 0]
>>> only_evens([1, 3, 5, 7, 9, 11])
[]
>>> only_evens([4, 0, -1, 2, 6, 7, -4])
[4, 0, 2, 6, -4]
>>> nums = [1, 2, 3, 4]
>>> only_evens(nums... | false |
e443a8469abd8dd648d3919ba5122505f9ae0ee7 | ozturkaslii/GuessNumber | /Py_GuessNumber/Py_GuessNumber/Py_GuessNumber.py | 1,214 | 4.25 | 4 | low = 0;
high =100;
isGuessed = False
print('Please think of a number between 0 and 100!');
#loop till guess is true.
while not isGuessed:
#Checking your answer with Bisection Search Algorithm. It allows you to divide the search space in half at each step.
ans = (low + high)/2;
print('Is your secret number '... | true |
6bb5fe7da5b77c12e4f6f37cd852a5b74478ab3d | wrenoud/aoc2020 | /lib/__init__.py | 628 | 4.125 | 4 | class Coord(object):
def __init__(self, x: int, y: int):
self.x = x
self.y = y
def __add__(self, other):
return Coord(self.x + other.x, self.y + other.y)
def __sub__(self, other):
return Coord(self.x - other.x, self.y - other.y)
def __len__(self) -> int:
"""ret... | false |
3b72cf3f9878c6a37ba0274f31df18f4f3a5ad69 | khusheimeda/Big-Data | /Assignment1 - Map Reduce/reducer.py | 789 | 4.125 | 4 | #!/usr/bin/python3
import sys
# current_word will be used to keep track of either recognized or unrecognized tuples
current_word = None
# current_count will contain the number of tuples of word = current_word seen till now
current_count = 0
word = None
for line in sys.stdin:
line = line.strip()
word,... | true |
9ce6d36ed817b6029a056e3dbd9e6581a00853e5 | KirthanaRamesh/MyPythonPrograms | /decimal_To_Binary.py | 1,577 | 4.53125 | 5 |
# Function for separating the integer and fraction part from the input decimal number.
def separation_of_integer_and_fraction():
global decimal_number, decimal_integer, decimal_fraction
decimal_integer = int(decimal_number)
decimal_fraction = decimal_integer - decimal_number
# Function to convert integer... | true |
409e2fc12f0a27a26d2b84e830e79694509c5063 | Sigtamx/EDD-HOFJ | /Practica2u1.py | 671 | 4.25 | 4 | """
Desplegar y calcular factorial de un numero dado por el usuario con recursividad
"""
m=1
def factorialRecursivo(n):
global m
if(n>1):
m*=n
n-=1
factorialRecursivo(n)
else:
print(m)
print("Fin")
print("Ingrese el numero para usar factorial:... | false |
6b8bf1fd5506f086a1367c35f416315b8cc8b8bb | jeffder/legends | /main/utils/misc.py | 621 | 4.3125 | 4 | # Miscellaneous utilities
from itertools import zip_longest
def chunks(values, size=2, fill=None):
"""
Split a list of values into chunks of equal size.
For example chunks([1, 2, 3, 4]) returns [(1, 2), (3, 4)].
The default size is 2.
:param values: the iterable to be split into chunks
:param... | true |
0649d4edfd70e8836a98437b1860c7f7709adaae | mihaivalentistoica/Algorithms_Data_Structures | /01-recursion/example-01.py | 319 | 4.34375 | 4 | def factorial(n):
"""Factorial of a number is the product of multiplication of
all integers from 1 to that number. Factorial of 0 equals 1.
e.g. 6! = 1 * 2 * 3 * 4 * 5 * 6
"""
print(f"Calculating {n}!")
if n == 0:
return 1
return n * factorial(n - 1)
print(f"6! = {factorial(6)}")
| true |
187269a9d58a66513d8bdda626b909f8c62ef928 | mosesokemwa/bank-code | /darts.py | 1,113 | 4.375 | 4 | OUTER_CIRCLE_RADIUS = 10
MIDDLE_CIRCLE_RADIUS = 5
INNER_CIRCLE_RADIUS = 1
CENTRE = (0, 0)
def score(x: float, y: float):
"""Returns the points earned given location (x, y) by
finding the distance to the centre defined at (0, 0).
Parameters
----------
x : float,
The cartesian x-coordinate ... | true |
e52d775f79831414f58c5ceeef965f1306b27293 | OsamaOracle/python | /Class/Players V1.0 .py | 1,294 | 4.3125 | 4 | '''
In the third exercise we make one final adjustment to the class by adding initialization data and a docstring. First add a docstring "Player-class: stores data on team colors and points.". After this, add an initializing method __init__ to the class, and make it prompt the user for a new player color with the messa... | true |
cb159d75464cd184798a3069e8779a0ec65b9472 | jbmarcos/Python-Curso-em-video-Mundo-1-2-3- | /ex037 # bin oct hex fatiamento str if elif else .py | 594 | 4.125 | 4 | # bin oct hex fatiamento str if elif else
num = int(input(' Digite um númeto inteiro: '))
print('''Escolha a base de conversção que deseja:
[ 1 ] para Binário
[ 2 ] para Octal
[ 3 ] para Hexadecimal''')
opção = int(input(' Sua opção: '))
if opção == 1:
print(' {} convertido para Binário é {} '.format(num, bin(n... | false |
87c6013053de3c1b0cdddff68e64ea6b76e5040f | lihaoranharry/INFO-W18 | /week 2/Unit 2/sq.py | 316 | 4.25 | 4 | x = int(input("Enter an integer: "))
ans = 0
while ans ** 2 <= x:
if ans **2 != x:
print(ans, "is not the square root of" ,x)
ans = ans + 1
else:
print("the square root is ", ans)
break
if ans **2 == x:
print("we found the answer")
else:
print("no answer discovered")
| true |
055abc0aa8a0fe307d3b1dda6ec697c908e61e44 | RelayAstro/Python | /ejercicio29.py | 962 | 4.5625 | 5 | #The is_palindrome function checks if a string is a palindrome. A palindrome is a string that can be equally read from left to right or right to left, omitting blank spaces, and ignoring capitalization. Examples of palindromes are words like kayak and radar, and phrases like "Never Odd or Even". Fill in the blanks in t... | true |
5c84f84a9e1816751630c17bb1acb9b3301459a3 | dbrooks83/PythonBasics | /Grades.py | 711 | 4.5 | 4 | #Write a program to prompt for a score between 0.0 and 1.0.
#If the score is out of range, print an error. If the score is between
#0.0 and 1.0, print a grade using the following table:
#Score Grade
#>= 0.9 A
#>= 0.8 B
#>= 0.7 C
#>= 0.6 D
#< 0.6 F
#If the user enters a value out of range, print a suitable error messa... | true |
91fa15b2c4ae7d49ff66f69e13a921aed349f63e | TranshumanSoft/Repeat-a-word | /repeataword.py | 205 | 4.1875 | 4 | word = str(input("What word do you want to repeat?"))
times = int(input(f"How many times do you want to repeat '{word}'?"))
counter = 0
while counter < times:
counter = counter + 1
print(word) | true |
8c855c41046f03888b12b957cfb66ac866144ca7 | fandres70/Python1 | /functiondefaults.py | 575 | 4.34375 | 4 | # Learning how Python deals with default values of
# function parameters
def f(a, L=[]):
'''This function appends new values to the list'''
L.append(a)
return L
# not specifying a list input
print(f(1))
print(f(2))
print(f(3))
# specifying a list input
print(f(1, []))
print(f(2, []))
prin... | true |
39b12a36d1c809b5b64250ac4543c95d26f5912b | fandres70/Python1 | /factorial.py | 426 | 4.34375 | 4 | #!/usr/bin/env python
# Returns the factorial of the argument "number"
def factorial(number):
if number <= 1: #base case
return 1
else:
return number*factorial(number-1)
# product = 1
# for i in range(number):
# product = product * (i+1)
# return product
user_input = int(raw_... | true |
a4034f4c5a30994a6b8568eb369a8a4df8610c46 | Saskia-vB/eng-57-pyodbc | /error_file.py | 1,338 | 4.5 | 4 | # Reading a text file
# f = open ('text_file.txt', 'r')
#
# print(f.name)
#
# f.close()
# to use a text within a block of code without worrying about closing it:
# read and print out contents of txt file
# with open('text_file.txt', 'r') as f:
# f_contents = f.read()
# print(f_contents)
# reading a txt file ... | true |
5f62cb78547b5a4152223c2a9c55789768d87b21 | bhumphris/Chapter-Practice-Tuples | /Chapter Practice Tuples.py | 2,234 | 4.46875 | 4 | # 12.1
# Create a tuple filled with 5 numbers assign it to the variable n
n = (3,5,15,6,12)
# the ( ) are optional
# Create a tuple named tup using the tuple function
tup = tuple()
# Create a tuple named first and pass it your first name
first = tuple("Ben")
# print the first letter of the first tup... | true |
03ef1ea5a2c991e7a597f40b06aac37890dde380 | knobay/jempython | /exercise08/h01.py | 593 | 4.1875 | 4 | """Uniit 8 H01, week2"""
# Gets an input from the user works
# out if it is an Armstrong number
def armstrong_check():
"Works out if the user has entered an Armstrong number"
userinput = input("Enter a 3 digit number")
evaluation = int(userinput[0])**3 + int(userinput[1])**3 + int(userinput[2])**3
i... | true |
688fa627915adf73bf41bc04d0636d41fb0d349d | knobay/jempython | /exercise08/e03.py | 581 | 4.125 | 4 |
"""Uniit 8 E03, week2"""
# Gets an input from the user works
# out if it contains a voul
PI = [3.14, 2]
def voul_or_not():
"Works out if the user has entered a voul or consonant"
userinput = input("Enter a letter")
if (userinput == 'a' or userinput == 'e'
or userinput == 'i' or userinput == ... | true |
2d766aea3921242f98860cc272bbfda43fb38efe | knobay/jempython | /exercise08/e02.py | 720 | 4.28125 | 4 | import math
#
print("\n--------------------------------------------------------------")
print("------------------------ E02 -------------------------")
x = True
while x:
numStr = input("Please enter a whole number:- ")
if numStr.isdigit():
num = int(numStr)
break
elif numStr.replace(... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.