blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
a661836d6a717301fc81f6704de27873d9e9f419 | hasanthex/fun-with-python | /python_basic/python_iterators.py | 2,515 | 4.46875 | 4 | # ******************************************************
# ITERATOR IN PYTHON
# ******************************************************
# Iterators are everywhere in Python.
# They are elegantly implemented within for loops, comprehensions, generators etc. but hidden in plain sight.
# Iterator in Python is simply ... | true |
c2e331eb3c5e3650cd17e4213123bf13f644dbf0 | Shockn/FC_2019-02 | /lista2_ex014.py | 401 | 4.21875 | 4 | '''Faça um programa que calcule o valor de PI pela soma dos n primeiros
termos da série abaixo:
raíz ( 12 * (1 - 1/4 +1/9 - 1/16 + 1/25 - 1/16 ... )'''
import math
def pi(n):
pi=0
for i in range(1, n+1):
if i%2==0:
pi-=1/(i**2)
else:
pi+=1/(i**2)
pi=pi*12
pi=mat... | false |
e1b1bb12f984925d4a015d04637bac7caab33cf4 | YS-Avinash/Python-programming | /functionUsingString.py | 387 | 4.59375 | 5 | #Python function to add 'ing' at the end of a given string and return the new string.
#If the given string already ends with 'ing' then add 'ly'.
#If the length of the given string is less than 3, leave it unchanged.
def add_string(str1):
return str1 if len(str1)<3 else str1+"ly" if str1.endswith("ing") else str1+... | true |
973522d56fd1a6083522a66ec6f8873683ef2840 | shariqueking/pyscripts | /battleship.py | 1,770 | 4.1875 | 4 | from random import randint
board = []
for x in range(5):
board.append(["O"] * 5) # creats 5x5 matrics
def print_board(board):
for row in board:
print(" ".join(row)) #use to replace , with " "
print("Let's play Battleship!")
print_board(board)
def random_row(board):
retu... | true |
813d3c89c6140ae700ba169f3357e048feee465e | Satyam-Bhalla/Python-Scripts | /Python Course/MultiThreading/multiThreading.py | 793 | 4.1875 | 4 | # Python program to illustrate the concept
# of threading
# importing the threading module
import threading
def print_cube(num):
"""
function to print cube of given num
"""
print("Cube: {}".format(num * num * num))
def print_square(num):
"""
function to print square of given num
"""
... | true |
392b8537797cdc5e23af55f4a31169c9c6081c75 | Athenian-ComputerScience-Fall2020/greatest-common-factor-ryanabar | /my_code.py | 1,102 | 4.25 | 4 | # Collaborators (including web sites where you got help: (enter none if you didn't need help)
# https://www.w3schools.com/python/python_operators.asp
# I used the one above to learn what the % operator does (This assingment became a lot easier after I learned that this exists :)
# https://www.mathsisfun.com/definitions... | true |
bba53f762bd066a9afcb9aaf0ef848a9158b8480 | programelu/python-demo | /fundamentals/tuples/simple-tuples.py | 1,354 | 4.5 | 4 | """tuples may have paranthesys or not"""
#tuple with paranthesys, recommanded for redability reasons
plane1 = ("Airbus", "319", 200)
print(plane1)
#tuple without paranthesys - recognized as tuples because comma has been encountered
plane2 = "Airbus", "A380", 500
print(plane2)
print(plane2[0])
#Tuples with only o... | true |
291453f748f7401fb94920034ee6353af2dbf675 | JoseAdrianRodriguezGonzalez/JoseAdrianRodriguezGonzalez | /python/octavo.py | 303 | 4.3125 | 4 | letra = input("Escriba una letra: ")
if letra == "a" or letra == "A" or letra == "e" or letra == "E" or letra == "i" or letra == "I" or letra == "o" or letra == "O" or letra == "u" or letra == "U":
print(f"La letra {letra} es una vocal")
else:
print(f"La letra {letra} es una consonante") | false |
4ef1f456cf46e7106d53f8ee80f0cac364482a6b | marnovo/lpthw | /exercises/ex07_sd.py | 1,470 | 4.53125 | 5 | # Learn Python the Hard Way
# https://learnpythonthehardway.org/python3/ex7.html
# Study Drills
# 1. Go back through and write a comment on what each line does.
# 2. Read each one backward or out loud to find your errors.
# 3. From now on, when you make mistakes, write down on a piece of paper what
# kind of mista... | true |
853d68f2b53695d4e623e66000b7a93f226d5d32 | luyihsien/leetcodepy | /Lincode/青銅/846多關鍵排序.py | 846 | 4.40625 | 4 | '''
846. 多关键字排序
中文English
给定 n 个学生的学号(从 1 到 n 编号)以及他们的考试成绩,表示为(学号,考试成绩),请将这些学生按考试成绩降序排序,若考试成绩相同,则按学号升序排序。
样例
样例1
输入: array = [[2,50],[1,50],[3,100]]
输出: [[3,100],[1,50],[2,50]]
样例2
输入: array = [[2,50],[1,50],[3,50]]
输出: [[1,50],[2,50],[3,50]]
'''
a=[[3,4,5],[1,2,3],[1,3,2],[3,5,5],[1,10,3]]
a.sort(key=lambda x:(x[0]... | false |
f9dd60343255a8a25925e5d3633d39c1ad8e24b0 | JorgeTranin/Cursos_Coursera | /Curso de Python USP Part1/Exercicios/Func_FizzBuzz.py | 740 | 4.3125 | 4 | '''
Escreva a função fizzbuzz que recebe como parâmetro um número inteiro e devolve
'Fizz' se o número for divisível por 3 e não for divisível por 5;
'Buzz' se o número for divisível por 5 e não for divisível por 3;
'FizzBuzz' se o número for divisível por 3 e por 5;
Caso o número não seja divisível 3 e também não ... | false |
06eb2e35ccbdffa5cdfe571ecb8d2e6eaa10c037 | vhngroup/Backend_with_Python_and_Django | /Python_Basico/sring_manage.py | 883 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""Como asignar o cambiar el contenido de una variable string"""
r='hola'
m= 'l' + r[1:]
print("El contenido de M es {} y cambio de R que es {}".format(m, r))
"""Como recorrer un string y conocer su longitud."""
my_string = 'platzi'
my_string [len(my_string)-1] # Se debe restar un valor, para... | false |
5a73e4c50f77dcdda03dc5765f96e9a8173ed643 | AlbertMukarsel/Pico-y-Placa | /restrictions.py | 1,566 | 4.1875 | 4 | from datetime import datetime
import utilities
def restrictionDays(date, licensePlate):
"""
Each day is represented by a number, Monday=0...Sunday-6
during weekdays, according to each day, if a license plate has
one of those digits as its last one, is subject to the Pico y Placa restrictions
I.E: o... | true |
d7267185a20504fb7f42e68f71753c8d8b274208 | pekasus/randomMusicPlayer | /file_renamer.py | 724 | 4.15625 | 4 | // File Renamer
// By: pekasus
// CC by 3.0
// This program will rename all files that end in .mp3 within a folder.
import os
songlist = "songlist.txt"
i = 1
with open(songlist, 'w') as fout:
fout.write("Legend of Songs\n\n");
fout.close()
for filename in os.listdir('/Volumes/musbox'):
if filename.lowe... | true |
32cf9ccecb1f2027e2bb47903a27831b1ebbf653 | I7RANK/holbertonschool-low_level_programming | /0x1C-makefiles/5-island_perimeter.py | 1,468 | 4.21875 | 4 | #!/usr/bin/python3
"""contains the island_perimeter function
"""
def island_perimeter(grid):
"""returns the perimeter of the island described in grid:
♪ 0 represents a water zone
♪ 1 represents a land zone
Args:
grid (list of lists): the grid
Returns:
int: the perimeter o... | true |
dad3c543d9682d90203cf189bdfad552d1b46a4a | idcrypt3/camp_2019_07_28 | /Caelan/Loops.py | 736 | 4.1875 | 4 | number_of_leaves = 14
for x in range(0, number_of_leaves):
print("A leaf fell to the ground " + str(x) + " leaves have fallen.")
print("All the leaves fell. For loop complete.")
on_roller_coaster = True
while on_roller_coaster:
print("Ahhh!")
on_roller_coaster = False
times_to_repeat = 5
for x in ... | true |
aef1d5641801ee27aadbd8b4bf3dd97a4357eb50 | code-in-the-schools/NestedCompoundConditionals_KidirTorain | /main.py | 414 | 4.28125 | 4 | #part1
for i in range(0,5):
print(i)
print("outer for loop | i :")
for j in range(0,5):
print("outer for loop | i : inner for loop | j :)
#part2
for b in range(0,9):
i = ("2,4,6,8")
j = ("2,4,6,8")
print(i,j)
print("these are both even")
#part3
for b in range(0,9):
i = ("1,3,5,7,9")
j = ("1,3,5,7,9")
print... | false |
4ff05fbda02740f66a714f0382a47381e237c42e | natterra/python3 | /Modulo1/exercicio028_2.py | 570 | 4.28125 | 4 | # Exercício Python 28: Escreva um programa que faça o computador “pensar” em um número inteiro entre 0 e 5 e peça para o usuário tentar descobrir qual foi o número escolhido pelo computador. O programa deverá escrever na tela se o usuário venceu ou perdeu.
from random import randint
numpc = randint (0, 5)
print("-=-"*... | false |
92f997ab011fe388d96fa2cfc88eb804ec32ea5b | natterra/python3 | /Modulo1/exercicio009_2.py | 276 | 4.125 | 4 | #Exercício Python 9: Faça um programa que leia um número Inteiro qualquer e mostre na tela a sua tabuada.
n = int(input("Digite um número: "))
i = 0
print("--------------")
while i < 10:
i += 1
print("{:2} x {:2} = {:2}".format(n, i, n*i))
print("--------------") | false |
c722a50ea46cfcf03b2011373f7371361528d632 | skhatri/pylearn | /week1/2_temp_conv.py | 830 | 4.1875 | 4 | """
Convert the given temparature in Celcius to Farenheit
"""
#your friend came from America. you find temperature for him
#37.5 Celcius is 99.5% Farenheit
C = 37.5
#F = ?
#we know F = 9/5 * C + 32
F = 9 / 5 * C + 32
print F
#89.6
F = 9 * 1.0 / 5 * C + 32
print F
#types of names/variables
print type(5)
print ty... | true |
4dd1d72ede3982aea33d067324950c8345cdee6e | wenqitoh/Recipe-Moderniser | /03_find_scale_factor_v2.py | 915 | 4.34375 | 4 | """Ask user for number of servings in recipe and
number of servings desired and then calculate the
scale factor
Version 2 - uses number checking function to ensure input is a number
Created by Wen-Qi Toh
28/6/21"""
# number checking function
# gets the sale factor - which must be a number
def num_check(question):
... | true |
297445e1a3b6886fcb21b73431e723aff27d7efc | unshah/amazon_sales | /sales.py | 1,608 | 4.125 | 4 | # Script to calculate Demand
#sold => total products sold (approx.)
#rev => total reviews of the product
# taking corelation as 1 review per 100 products (ex. rev = 5 || sold = 500)
# This is the feature branch !!
#----------------------------------------------------------------------------------------------------... | true |
35813bb247e0ee95679723b7cd07a8fe3a1e518b | zhangshv123/superjump | /interview/facebook/mid/LC494_Target Sum.py | 1,269 | 4.1875 | 4 | #!/usr/bin/python
"""
You are given a list of non-negative integers, a1, a2, ..., an, and a target, S. Now you have 2 symbols + and -. For each integer, you should choose one from + and - as its new symbol.
Find out how many ways to assign symbols to make sum of integers equal to target S.
Example 1:
Input: nums is [... | true |
0e9fb15850ffdefc0b94074e8694a2888a85cc0c | zhangshv123/superjump | /interview/google/mid/LC417. Pacific Atlantic Water Flow.py | 2,026 | 4.15625 | 4 | """
Given an m x n matrix of non-negative integers representing the height of each unit cell in a continent, the "Pacific ocean" touches the left and top edges of the matrix and the "Atlantic ocean" touches the right and bottom edges.
Water can only flow in four directions (up, down, left, or right) from a cell to ano... | true |
ceb685395799009e79f74f6bd2d7f6977d5a3395 | zhangshv123/superjump | /interview/others/easy/LintCode Insert Node in a Binary Search Tree.py | 1,056 | 4.15625 | 4 | """
Given binary search tree as follow, after Insert node 6, the tree should be:
2 2
/ \ / \
1 4 --> 1 4
/ / \
3 3 6
"""
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None... | true |
22784fc51726e32b5c14739dda4195063824e0d5 | zhangshv123/superjump | /interview/facebook/easy/LC461_477_Hamming Distance.py | 2,199 | 4.53125 | 5 | #!/usr/bin/python
"""
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Given two integers x and y, calculate the Hamming distance.
Note:
0 ≤ x, y < 231.
Example:
Input: x = 1, y = 4
Output: 2
Explanation:
1 (0 0 0 1)
4 (0 1 0 0)
↑ ↑
... | true |
9f08f217111cb664d37b42416a496c61a09b85b4 | itsHuShihang/PythonBeginner | /data_type/tuple.py | 307 | 4.40625 | 4 | t=(1,2,3,4,5,6)
'''
the methods of tuple are the same as the methods of list, but the elements in a tuple cannot be changed
you cannot delete the elements of a tuple but you can use del to delete the whole tuple
'''
# convert list to tuple
l = [1, 2, 3, 4, 5]
print(type(l))
l2t = tuple(l)
print(type(l2t)) | true |
282cc5a7d9243d2fd1a1a429ec296f0b224d1c89 | JamesWJohnson/TruckCapeProjects | /02_Better_Hello_World/better_hello_world.py | 731 | 4.375 | 4 | #!/usr/bin/env python3
# OK, now we're going to do a slightly more complicated Hello World
# First, declare two variables.
# Here, declare one called print1 with the value "Hello, world!"
# Now here, declare another one called print2 with the value "Nice to see you!"
# This bit here is called a loop. It executes... | true |
9f9150ce977b08fed005a19539ab2862699879c2 | nickfuentes/Python-Practice | /python/car_dealer.py | 605 | 4.125 | 4 | cars = []
# creating the Car class
class Car:
# constructor or initializer
def __init__(self, make, model, color):
self.make = make # set property make to the arguement make
self.model = model
self.color = color
# Passing self makes the the drive function availble to thte Car Objects... | true |
56835ed8a04a33fb8fc2f08b4937244cbc34b99c | sandroormeno/taller-de-python | /bloque 6/funcion_factorial.py | 265 | 4.125 | 4 | def factorial(n):
j = 1
for i in range(1, int(n)+1): # más uno para contar con le número
j = j * i
print("Factorial: " + str(j))
print("Programa para calcular el factorial de un número.")
numero = input("Ingrese un número: ")
factorial(numero)
| false |
06b03068025264b0598e9b5b4dd7ad081fd2b983 | akashrajput25/Python | /tkintler_gui/positioning_app.py | 262 | 4.15625 | 4 | #using GRID System , positioning
from tkinter import *
root =Tk()
myLabel1 = Label(root , text="Hello World").grid(row=0 ,column = 0) # positioning on screen and creating a label widget
myLabel2 = Label(root , text="Its Akash").grid(row=2 ,column = 1)
root.mainloop() | true |
13efaaf294755f28b21cb1592e8299127eb7d34d | ishantk/GW2019B | /venv/Session3B.py | 367 | 4.25 | 4 | # Read Data from User and store it in a container
data = input("Enter some data: ")
print("You Entered:",data)
print("Type of data is:",type(data))
num1 = int(input("Enter Number 1: "))
num2 = int(input("Enter Number 2: "))
num3 = num1 + num2
# print("num3 is: ",num3)
print("sum of",num1,"and",num2,"is:",num3)
print("... | true |
47d67710dd4a6ca5587fae426aaeda209bebbd79 | Bakley/effective-journey | /Chapter 7/Exercise7_3.py | 556 | 4.21875 | 4 | """
Write a function named test_square_root that prints a table.
The first column is a number, a; the second column is the square root of a computed with the function
from Exercise 7.2; the third column is the square root computed by math.sqrt; the fourth column
is the absolute value of the difference between the two e... | true |
641e4ba23f7c96415d09e39280320fd20b700544 | Konstantine616/1_lesson | /practice_5.py | 2,037 | 4.21875 | 4 | # Запросите у пользователя значения выручки и издержек фирмы. Определите, с каким финансовым результатом работает фирма
# (прибыль — выручка больше издержек, или убыток — издержки больше выручки).
# Выведите соответствующее сообщение.
# Если фирма отработала с прибылью, вычислите рентабельность выручки (соотношение ... | false |
d6051b1eb58bf7a4699a30b1be035b828ea2d5d4 | nanakiksc/algorithms | /merge_sort.py | 1,204 | 4.15625 | 4 | #!/usr/bin/env python
#-*- coding:utf-8 -*-
# Sort and count the number of inversions in an array.
def sort_count(array):
# Return the inversion count and the sorted subarray.
n = len(array)
if n <= 1:
return array, 0
else:
mid = n / 2
l_array, left = sort_count(array[:mid])
... | true |
069541fdcda77eeeda8c09d251dd63d49fe39948 | DeathGodBXX/python-programs-code | /4_flexsible_and_not/字符串.py | 286 | 4.15625 | 4 | str1 = "hello,武汉加油,湖北加油,hello"
# 查询字符串的字符个数
# print("len查询到的数量:",len(str1))
# 根据索引值去取数据
# print("index索引得到的对应数据:",str1[3])
print("去查询该数据第一次出现的索引值:", str1.index("武汉"))
| false |
c7aed50707ef05ea820dba0c56625af458fae4c6 | DeathGodBXX/python-programs-code | /16_coroutine/iterable_method.py | 2,244 | 4.34375 | 4 | """迭代器"""
"""只要具备iter()方法,就是可迭代对象;只要含有iter()和next()方法,就是迭代器。可以使用next方法取值"""
from collections import Iterable
from collections import Iterator
class Diy:
def __init__(self):
self.names = []
def add_name(self, name):
self.names.append(name)
# 变成可迭代对象,魔术方法
def __iter__(self):
p... | false |
e7b03ec619dcf6d805ac05a51eb9825d33afc2a5 | DeathGodBXX/python-programs-code | /13_multithreading/multiple threading in class.py | 1,131 | 4.28125 | 4 | """
利用类实现多线程任务
"""
# import threading
# import time
#
#
# class Demo(threading.Thread):
# # 必须要有实例方法run,run()固定名称,不可更改 代表线程的启动。
# # 大概是通过main()函数中,t1.start,启动这个run函数,线程启动
# # run方法于线程启动相关
# def run(self):
# for i in range(3):
# time.sleep(0.8)
# print(threading.enumerate... | false |
8cd1442a3b9767de97724463ca2272a706061da8 | arvakagdi/GrokkingTheCodingInterviews | /GTCI_2Pointers_1/DutchFlag.py | 1,203 | 4.3125 | 4 | '''
Problem Statement #
Given an array containing 0s, 1s and 2s, sort the array in-place. You should treat numbers of the array as objects, hence, we can’t count 0s, 1s, and 2s to recreate the array.
The flag of the Netherlands consists of three colors: red, white and blue; and since our input array also consists ... | true |
4866640c3c406ca213973d4d38bbc62f9e6255d5 | arvakagdi/GrokkingTheCodingInterviews | /GTCI_BitwiseXOR/1/SingleNumber.py | 927 | 4.15625 | 4 | '''
Problem Statement #
In a non-empty array of integers, every number appears twice except for one, find that single number.
Example 1:
Input: 1, 4, 2, 1, 3, 2, 3
Output: 4
Example 2:
Input: 7, 9, 7
Output: 9
Solution with XOR #
following are the two properties of XOR:
It returns zero if we take X... | true |
e4f28e42bdcc8911c83dce45f55f203553772a00 | arvakagdi/GrokkingTheCodingInterviews | /SlidingWindow/NoRepeatSubstring.py | 1,490 | 4.4375 | 4 | '''
Given a string, find the length of the longest substring which has no repeating characters.
Example 1:
Input: String="aabccbb"
Output: 3
Explanation: The longest substring without any repeating characters is "abc".
Example 2:
Input: String="abbbb"
Output: 2
Explanation: The longest substring without ... | true |
8de4537d4df3a92ecd86ab32f1584d0af5b165f2 | arvakagdi/GrokkingTheCodingInterviews | /GTCI_2Pointers_1/3SumCloseToTarget.py | 1,583 | 4.21875 | 4 | '''
Problem Statement #
Given an array of unsorted numbers and a target number, find a triplet in the array whose sum is as close to the target number as possible, return the sum of the triplet. If there are more than one such triplet, return the sum of the triplet with the smallest sum.
Example 1:
Input: [-2, ... | true |
724e0b4c178b08a32c7cfe2a1c3fb332062048b2 | rsamhollyer/Week-1-Algo-Challenge | /earlierPyAlgos/indicesums.py | 1,328 | 4.125 | 4 | #3. Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
# You may assume that each input would have exactly one solution, and you may not use the same element twice.
# You can return the answer in any order.
# Examples and clarification here: https:/... | true |
0ac0b0cc92209e998a6d1ba8210ffbcf4cb2700a | soumikchaki/coursera-py4e | /p2-python-data-structure/week4/a1-string-order.py | 632 | 4.34375 | 4 | # Open the file romeo.txt and read it line by line. For each line,
# split the line into a list of words using the split() method.
# The program should build a list of words. For each word on each line check to see if the word is already in the list
# and if not append it to the list. When the program completes, sort a... | true |
97d1d59e3fb09d918d6d9dc5510fb876d3fc0822 | abhishekjee2411/python_repos_novice | /2_odd_even_div.py | 1,165 | 4.25 | 4 | #-------------------------------------------------------------#
print ("------------------------------------------------------------")
#-------------------------------------------------------------#
nbr = int(input("Enter a number: "))
if (nbr%2 == 0):
print ("The number is even!")
if (nbr%4 == 0):
print ("It is a... | true |
a607c7b2ea1f032032c96e8e4e17067a3741bd72 | isrdoc/snit-hr-wd1-python-basics | /08_Introduction_to_Python_and_variables.py | 309 | 4.1875 | 4 | message = "Hello"
user_name = input("Please enter your name: ")
user_age = int(input("Please enter your age: "))
is_user_logged_in = False
if message == "Hello":
print(message + " " + user_name)
print("Your age is: " + str(user_age - 10))
print("User is logged in.")
print("After conditional")
| true |
b688a5a651d9c9e26a5bdeec19b4827759d1b919 | Youbornforme/Python9.HW | /hw9.py | 1,954 | 4.15625 | 4 | #Задача 1. Курьер
#Вам известен номер квартиры, этажность дома и количество квартир на этаже.
#Задача: написать функцию, которая по заданным параметрам напишет вам,
#в какой подъезд и на какой этаж подняться, чтобы найти искомую квартиру.
room = int(input('Введите номер квартиры ')) # кол-во квартир
floor = int(5) #... | false |
ae8b14f07eff5b367d74c440e58b64bce4fc4899 | ManassaVarshni/ProjectEuler | /Problem9.py | 747 | 4.375 | 4 | """
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a2 + b2 = c2
For example, 32 + 42 = 9 + 16 = 25 = 52.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
"""
def pythagoreanTriplet(n):
# If the triplets are in sorted order.
# The ... | true |
09248cd9bc40e1cfcb6ddad885b28c8ca41c9f9f | lingler412/UDEMY_PYTHON | /factorial_for_loop.py | 516 | 4.53125 | 5 | my_num1 = int(input("Give me a number so I can give you it's factorial! ")) # give me a whole integer
def calc_factorial(my_num): # here is a function to caluate the factorial of the provided integer
for num in range(my_num - 1, 1, -1):
my_num *= num
return my_num
my_factorial = calc_factorial(my_nu... | true |
66ced30141bf401a6446557ad4f066d0fb69d2ec | James-Ashley/python-challenge | /PyBank/main.py | 2,812 | 4.375 | 4 | # * In this challenge, you are tasked with creating a Python script for analyzing the financial records of your company. You will give a set of financial data called [budget_data.csv](PyBank/Resources/budget_data.csv). The dataset is composed of two columns: `Date` and `Profit/Losses`. (Thankfully, your company has rat... | true |
28f51d47018af7c2690031e68529309897cb22ca | pradhanmanva/PracticalList | /pr4.py | 298 | 4.28125 | 4 | # WAP to calculate the area of the triangle
side1 = 10
side2 = 6
side3 = 8
semi = (side1 + side2 + side3) / 2
area = (semi * (semi - side1) * (semi - side2) * (semi - side1)) ** (1 / 2)
print("Area of the triangle with sides "+str(side1)+", "+str(side2)+" and "+str(side3)+" : "+str(area)+". ")
| false |
db5211eb8eefe9534af15e817d427204aa2b75e6 | Azurick05/Ejercicios_Nate_Academy | /Tabla_de_multiplicar/Tabla_de_multiplicar_for.py | 408 | 4.125 | 4 |
numero_multiplicar = int(input("Introduzca el numero a multiplicar: "))
primer_numero = int(input("Introduzca el primer numero del rango: "))
segundo_numero = int(input("Introduzca el segundo numero del rango: "))
for multiplo in range(primer_numero,segundo_numero + 1):
print("{} x {} = {}".format(numero_multipli... | false |
03ec30cab8a1c75770778442464c785ea5359562 | Ahm36/pythonprograms | /CO1/program17.py | 261 | 4.40625 | 4 | dict={
"ABC":101,
"BCS":999,
"JKL":888,
"IHG":897,
"XYZ":345,
"MKF":998
}
print("Ascending order")
for i in sorted(dict.keys()):
print(i,dict[i])
print("Descending order")
for i in sorted(dict.keys(),reverse=-1):
print(i,dict[i]) | false |
282454d642780f4441398a592aed122eaff363a2 | ronmarian7/TAU-HW-Python | /EX7/ex7_316593839.py | 2,876 | 4.4375 | 4 | """ Exercise #7. Python for Engineers."""
#########################################
# Question 1 - do not delete this comment
#########################################
class Beverage:
def __init__(self, name, price, is_diet):
self.name = name
self.price = price
self.is_diet = is_diet
... | true |
15f3739d21506bd03f1edb911a7ebf3ddf921f03 | kangli-bionic/coding-challenges-and-review | /random/random_odd.py | 2,048 | 4.5625 | 5 | """
Input: interval a, b
Output: a random odd integer in the range of a to b with equal probability
Range is inclusive.
Given a random function random(a, b) that returns a random integer in the range of a to b, implement a randomOdd(a, b)
function that returns a random odd integer in the range of a to b
ran... | true |
40455235cf6903ce53d012a8236cde45a90d447e | s2097382/Testing | /Assessment2.py | 2,661 | 4.25 | 4 | #Q1
def student_pass(score1, score2, score3):
# Insert your code here
passed = False
avg = (score1 + score2 + score3)/3
if score1 >= 40 and score2>= 40 and score3 >= 40:
passed = True
elif avg > 50:
if score1>=40 and score2>=40:
passed = True
elif score1>=40 and... | true |
8e8a31015a12aa32887939003918bebf7863a9f6 | Leandromaro/python | /Basic/dictionary.py | 451 | 4.125 | 4 | def dictionary_comprehension(letter):
planets = {'one': 'Mercury',
'two': 'Venus',
'three': 'Earth',
'four': 'Mars',
'five': 'Jupiter',
'six': 'Saturn',
'seven': 'Uranus',
'eighth': 'Neptune'}
planetsFiltere... | false |
596fa4fbbe7968c0423d042994723b1f7ea104c0 | gazelleazadi/INF200-2019-Exersices | /src/ghazal_azadi_ex/ex01/letter_counts.py | 418 | 4.125 | 4 | def letter_freq(txt):
txt = txt.lower()
letter_new = {}
for i in txt:
letter_new[i] = txt.count(i)
return letter_new
# Using Dictionary that holds unique "Key Values" pair.
if __name__ == '__main__':
text = input('Please enter text to analyse: ')
frequencies = letter_freq(text)
f... | true |
9fc95f21fc44b7c73361c27af2a63d5d92504b9c | ricardo-vallejo/cursopython | /tiposNumericos.py | 1,473 | 4.15625 | 4 | #Enteros
"""
Sin decimales
Positivos y negativos o 0
No hay tamaño limite
"""
numeroEntero = 33
type(numeroEntero)
#Booleanos
"""
True o False
Subclase del tipo entero (1, 0)
"""
verdadero = True
falso = False
print(verdadero)
print(falso)
verdNum = int(verdadero) #Se puede convertir el valor booleano a entero
falNu... | false |
4ec2e53de37a6ab733d7695fbb7952623e655972 | Madara701/Python_OO | /Python_OO/built-in.py | 403 | 4.15625 | 4 | '''
SobreEscrevendo a maneira de somar em python
'''
class MeuInt(int):
def __add__(self,num):
return 0
a = MeuInt(1)
r = a + 2
print(r)
'''
SobreEscrevendo o metodo append de lista pra que ele funcione da maneira que eu quiser ou achar
necessaria!
'''
class MinhaLista(list):
def append(self, *args):
... | false |
659d64a63c101f2fe07e79dd81410bbdc56206a7 | lanchunyuan/Python | /PythonCrashCourse/chapter-4/4-10.py | 297 | 4.3125 | 4 | favorite_pizzas = ['pepperoni', 'hawaiian', 'veggie','sausage']
print(r'The first three items in the list are:')
print(favorite_pizzas[:3])
print(r'Three items from the middle of the list are:')
print(favorite_pizzas[1:4])
print('The last three items in the list are:')
print(favorite_pizzas[-3:]) | true |
1d9c06fd8df38fdba89467496a77666f71fef83a | Sohaib76/Python-Certified-Cisco | /Assignments/Assignment # 1.py | 1,914 | 4.5625 | 5 | '''1. Write a Python program to print the following string in a specific format
(see the output).
Twinkle, twinkle, little star,
How I wonder what you are!
Up above the world so high,
Like a diamond in the sky.
Twinkle, twinkle, little star,
How I wonder what you are'''
print('''Twinkle, twinkle, little star, \n\tHow... | true |
77263cee411732ef87a4357e9e6e8f6b14e88fa1 | TimTheFiend/Python-Tricks | /pyFiles/2.1_assert.py | 1,082 | 4.375 | 4 | def apply_discount(product, discount):
price = int(product['price'] * (1.0 - discount))
"""Assert:
If this isn't true, throw an exception
Assertions are meant to be internal self-checks for you program.
They work by declaring some conditions as impossible in your code.
I... | true |
59b11140614aee7f6deece88357000b4118ba2e0 | TimTheFiend/Python-Tricks | /pyFiles/5.4_sets_and_multisets.py | 2,084 | 4.40625 | 4 | """A set is an unordered collection of objects that does not allow duplicate elements.
"""
# set - your go-to set
vowels = {'a', 'e', 'i', 'o', 'u',}
print('e' in vowels) # True
letters = set('alice')
print(letters.intersection(vowels)) # {'i', 'e', 'a'}
vowels.add('x')
print(vowels) # {'i', 'x', 'u', 'e', 'o', 'a'}... | true |
208171031745565970746e7c7c9ae56bb07d826e | mjmandelah07/assignment1 | /assignment_2/question_3.py | 458 | 4.25 | 4 | # Given a list slice it into 3 equal chunks and reverse each chunk
sampleList = [11, 45, 8, 23, 14, 12, 78, 45, 89]
chunk_1 = sampleList[:3]
chunk_2 = sampleList[3:6]
chunk_3 = sampleList[6:9]
print("Original list:", sampleList)
print("Chunk 1:", chunk_1)
print("After reversing chunk 1:", chunk_1[::-1])
print("chunk ... | true |
462be16865837a4a3d365fe1b524f86a6d706c78 | mjmandelah07/assignment1 | /question2.py | 472 | 4.15625 | 4 | # Given a range of first 10 numbers, Iterate from start number to the end number and
# print the sum of the current number and previous number:
# HINT : Python range() function
def number(num):
previous_num = 0
for a in range(num):
sum_num = previous_num + a
print("Current Number", a, "Previous ... | true |
e351e024fefa1cd4c15d8495eef7beaecdf2be58 | zaiyangliu/theo-code-of-python | /sum_of_even_factorial_numbers_less_than_inputed.py | 694 | 4.125 | 4 | #python 3.6
def fib(num):
sum = 0
p1 = 1
p2 = 1
i = 1
result = 0
while result < num:
if i >= 1:
if result % 2 == 0:
sum += result
result = p1 + p2
p1,p2 = p2, p1 + p2
print(sum)
num = int(input("please input an positive integer\n"))... | true |
b4711eeca831fa811438a36dc1f1cd1dbb1c4c6e | Vaishanavi13/Customer-Segregation-ML | /CustomerSegregation.py | 2,272 | 4.15625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[2]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt #Data Visualization
import seaborn as sns #Python library for Visualization
# In[3]:
#importing dataset
dataset = pd.read_csv(r'C:\Users\HP\Downloads\customer-segmentation-dataset\customer-se... | true |
4ec9dda57eda5aa185f90a34df487fea45812d8c | aliakseisysa/Intro-into-Python | /Practice_3/Task_3_3.py | 532 | 4.21875 | 4 | #3. Реализовать функцию my_func(), которая принимает три позиционных аргумента,
# и возвращает сумму наибольших двух аргументов.
def max_func():
var_1 = int(input("Enter the first number: "))
var_2 = int(input("Enter the first number: "))
var_3 = int(input("Enter the first number: "))
my_list = [var_1, ... | false |
e8d5b7de3cdf9667a2f0daf87acffb1fea0dfb65 | sadofnik/basics_python | /Урок 3. Функции/1.py | 700 | 4.25 | 4 | # 1. Реализовать функцию, принимающую два числа (позиционные аргументы) и выполняющую их деление.
# Числа запрашивать у пользователя, предусмотреть обработку ситуации деления на ноль.
def calc(a,b):
try:
return a / b
except ZeroDivisionError:
return f'На ноль делить нельзя'
print(f"{'*'*10} Ф... | false |
21753658f0d6f829974d6b7bd3f7684061e8effb | MaxwellMensah/Data-Structures-and-Algorithms | /Arrays/11. Slice and Delete from a List.py | 1,961 | 4.46875 | 4 |
myList = ['a', 'b', 'c', 'd', 'e', 'f']
print(myList[0:2]) # same as:
myList = ['a', 'b', 'c', 'd', 'e', 'f']
print(myList[:2])
# omitting the second elements
myList = ['a', 'b', 'c', 'd', 'e', 'f']
print(myList[1:])
# omitting both elements
myList = ['a', 'b', 'c', 'd', 'e', 'f']
print(myList[:])
# updating first... | true |
867a8f1048850aea8c88748e8b783a0a680b4373 | MaxwellMensah/Data-Structures-and-Algorithms | /Dictionary/2. Inserting into a dictionary.py | 299 | 4.34375 | 4 |
# Update or Add an element to the dictionary
myDict = {'name': 'Edy', 'age': 26}
myDict['age'] = 27 # overwrite/changed from 26 to 27. Time Complexity : O(1)
print(myDict)
# Adding new pairs
myDict['address'] = 'London' # Time Complexity : O(1)
print(myDict)
| true |
b6928db4afcdcdb5b2fe405d5033122635a51973 | loide/hackerrank | /python/staircase.py | 1,055 | 4.6875 | 5 | """
Consider a staircase of size n = 4:
#
##
###
####
Observe that its base and height are both equal to n, and the image is drawn
using # symbols and spaces. The last line is not preceded by any spaces.
Write a program that prints a staircase of size n.
Input Format
A single integer,n, denoting the size of t... | true |
d8181599f70a0eb546c9073177bfdbd67c042763 | EvanJamesMG/Leetcode | /python/Array/268. Missing Number.py | 759 | 4.125 | 4 | # coding=utf-8
__author__ = 'EvanJames'
'''
Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.
For example,
Given nums = [0, 1, 3] return 2.
Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra... | true |
e98bb4522cd61870e4027eb01c8033388c9ecb3d | SUREYAPRAGAASH09/Unsorted-Array-Exercises | /32.shiftrightleft/shiftrightleft.py | 750 | 4.3125 | 4 | Question :
==========
Shift Right Left the element of the array
Input :
=======
Unsorted Integer Array
Output :
========
Unsorted Integer Array but, after shifting right left the element of the array
Code :
======
def swapRight(array,shiftValue):
temp = 0
iterator = 0
while (iterator2!=shiftValu... | true |
e00985f648f9c2e443c89141dd5cf4d1e41eee64 | SUREYAPRAGAASH09/Unsorted-Array-Exercises | /39.getIndexafterrotationright/getindexRight.py | 491 | 4.40625 | 4 | #37. Given an unsorted integer array A,
# find the value that will be in 3rd position or index after 2 rotations to the right.
import Rotateright
def getIndexAfterrotationRight(array,index,rotation_value):
afterRotation = Rotateright.swapRight(array,rotation_value)
return afterRotation[index]
#array = [5,7,6... | true |
91b2938a08664a245836b94af2410b8a84725f21 | SUREYAPRAGAASH09/Unsorted-Array-Exercises | /25.2ndLargestNumber/2ndLagestNumbers.py | 397 | 4.21875 | 4 | Question :
==========
Get Second largest number form the list
Input :
=======
Unsorted Integer Array
Output :
========
Integer - Get second largest integer
Code :
======
import Max
def secondLargestNumber(array):
Maximum = Max.Max(array)
for iterator in array:
if Maximum == iterator:
... | true |
ebf880df76a00a981c9d0430a0da732cae36fc05 | mserevko/sorting-algorithms | /algorithms/bubble_sort.py | 757 | 4.3125 | 4 | """
Bubble sort
1. Looping through list
2. Compares elements of list (list[n] > list[n+1]), swaps them if they are in the wrong order.
3. The pass through the list is repeated until the list is sorted.
"""
import random
import copy
randomlist = [random.randint(0,100) for i in range(0, 7)]
def bubble_sort(some_lis... | true |
6455740e9b80d0ad3327998842788cd6284ea8c3 | EOppenrieder/HW070172 | /Homework5/Exercise7_5.py | 520 | 4.25 | 4 | # A program to tell you whether your weight is appropriate
def main():
weight = float(input("Please enter your weight in pounds: "))
height = float(input("Please enter your height in inches: "))
BMI = (weight * 720) / (height**2)
if BMI > 25:
print("You're above the healthy range")
elif 19 ... | true |
08690352d335dee2c78fb17f9e4be53434a1177f | EOppenrieder/HW070172 | /Homework4/Exercise3_17.py | 359 | 4.21875 | 4 | # A program to guess the square root of numbers
def main():
x = float(input("Enter the number of which you want to know the square root: "))
n = int(input("Enter the number of times to improve the guess: "))
g = x / 2
for i in range (n):
g = (g + x / g) / 2
print(g)
import math
prin... | true |
6f06c24cc9eecc85ed6ef6c386520cfcab0eed49 | EOppenrieder/HW070172 | /Homework3/Exercise11.py | 272 | 4.1875 | 4 |
def main():
print("This program converts meter per second (ms)")
print ("into kilometers per hour (kmh).")
ms = eval(input("Enter your velocity in meter per second: "))
kmh = 3.6 * ms
print("Your velocity is",kmh,"kilometers per hour.")
main ()
| false |
6fa21435c58ab7dd564676c274660f01c7236b5f | EOppenrieder/HW070172 | /Homework4/Exercise3_3.py | 489 | 4.25 | 4 | # A program to calculate the molecular weight
# of a carbohydrate (in grams per mole)
def main():
H = int(input("Enter the number of hydrogen atoms: "))
C = int(input("Enter the number of carbon atoms: "))
O = int(input("Enter the number of oxygen atoms: "))
Hweight = 1.00794
Cweight = 12.0107
... | true |
7db330f7c85ba02facdaa1c36786e7cdcffde435 | EOppenrieder/HW070172 | /Homework4/Exercise3_13.py | 282 | 4.125 | 4 | # A program to sum a series of numbers
def main():
n = int(input("Enter the amount of numbers that are to be summed: "))
x = float(input("Enter a number: "))
for factor in range(2, n+1):
y = float(input("Enter a number: "))
x = x + y
print(x)
main() | true |
6ccc66d54d210e84dfa88b25df787a2035eb6d42 | Lakssh/PythonLearning | /basic_learning/exception_handling.py | 1,128 | 4.1875 | 4 | """
Exception Handling
Exceptions are errors and should be handled in the code
link to python built in exceptions https://docs.python.org/3/library/exceptions.html
try: <Function to be written here>
except: <Exception block, same as catch in java>
else: <executed when there is no exception>
finally: <always executed de... | true |
c996e11bbea73af2ee242abe4ee4fb70f5bee606 | PnFTech/CodingInterview | /ch10/python/sorted_merge.py | 1,212 | 4.21875 | 4 | #!/usr/bin/env python
'''
Author: Ping Guo
Email: pingg104@gmail.com
Problem Statement:
You are given two sorted arrays, A and B, where A has a large enough buffer
at the end to hold B. Write a method to merge B into A in sorted order.
Example: A = [1, 5, 9]
B = [2, 4, 7]
C = [6, 9, 22, 34, 87, 98,101]... | true |
fe407ecfd67c5ca3131c83f28114b644b17ddd11 | gakkistyle/comp9021 | /Practice_1 solution/span.py | 1,566 | 4.125 | 4 | """
prompts the user for a seed for the random number generator,
and for a strictly positive number, nb_of_elements,
generates a list of nb_of_elements random integers between 0 and 99,
prints out the list, computes the difference between the largest
and smallest values in the list without using the builtins min() ... | true |
be88c101b67e060cff923ae719e0f178d9733e64 | EmmanuelSR10/Curso-Python | /Curso/Condicionales.py | 228 | 4.15625 | 4 | """CONDICIONALES"""
numero = int (input("Numero:"))
if numero > 0:
print("El numero es positivo") #siempre poner " : " para identacion
elif numero== 0:
print("El número es cero")
else:
print("El numero es negativo") | false |
db4c1238f2d9177d3ca1abc7cdb3764c3b937028 | EmmanuelSR10/Curso-Python | /Ejercicios_Lista/Ejercicio_2.py | 552 | 4.5 | 4 | """ Escribir un programa que almacene las asignaturas de un curso
(por ejemplo Matemáticas, Física, Química, Historia y Lengua) en una
lista y la muestre por pantalla el mensaje Yo estudio <asignatura>, donde <asignatura>
es cada una de las asignaturas de la lista."""
materias = []
num_materias = int(input("Numero d... | false |
daaa3f43ca4efe6d84bf7ff374be168f791d5c7c | EmmanuelSR10/Curso-Python | /POO/MetodosEspeciales.py | 1,138 | 4.15625 | 4 | """Métodos especiales y objetos embebidos"""
class Fabrica:
def __init__(self, tiempo, nombre, ruedas): #def __init__ nos ayuda como método constructor
self.tiempo = tiempo
self.nombre = nombre
self.ruedas = ruedas
print("Se creó el auto", self.nombre)
def __del__(self): # __d... | false |
3872ae39b4f089816c8110aad6ab6a188bd765a7 | yoonju-baek/Learn-Python-Programming | /1.basics/dictionaries.py | 1,953 | 4.5 | 4 | # Dictionaries - a collection of key-value pairs {key:value}
fruit_0 = {'color': 'red', 'shape': 'circle'}
print(fruit_0)
print(fruit_0['color'])
print(fruit_0['shape'])
# Adding new key-value
fruit_0['price'] = 3
print(fruit_0)
# Modifying values
fruit_0['color'] = 'yellow'
fruit_0['shape'] = 'rectangle'
print(fruit... | true |
2cb8c1f3f5fee45e1e7dbde9b44e5a3e9795df8a | yoonju-baek/Learn-Python-Programming | /1.basics/ending_while_loops.py | 487 | 4.4375 | 4 | # User enter 'quit' to end the program
prompt = "Tell me something. If you want to end the program, enter 'quit': "
message = ""
while message != 'quit':
message = input(prompt)
if message != 'quit':
print(message)
# Using a flag to end the program
prompt = "(Using a flag)Tell me something. If you wa... | true |
c393006cc9139f859d46d62873d29e3532f51de7 | yoonju-baek/Learn-Python-Programming | /1.basics/conditional operations.py | 926 | 4.3125 | 4 | # Checking the condition of case is case sensitive
# Equality: ==
# Inequality: !=
# Mathematical comparisons: <, > <=, >=
# Multiple conditions: and, or
# Strings Comparisons
coffees = ['moca', 'espresso', 'americano', 'latte']
for coffee in coffees:
if coffee == 'americano':
print(coffee.title())
el... | true |
ed7b1ca37da1bfbbbfdf09f56d3fc8bb860a439d | rahulshukla29081999/python-professional-programming-dsa | /bubble sort.py | 664 | 4.15625 | 4 | # Bubble Sort in Python...
#time complexity of bubble sort is O(n^2)
#it is a simple comparision based algorithm ...
#in this compare two adjacent element of list ..if 1st elemnt is bigger than 2nd then swap them ...
#largest element of the list will be in last position .
#second largest element of the list will come i... | true |
f08cf2d80f0af8a80254ac68c18a7b1977bfdd40 | clettieri/Algorithm_Implementations | /breadth_first_search.py | 2,685 | 4.375 | 4 | """
Breadth-First Search
This searching algorithm will search through a tree going through each
node at one level before continuing to the next level of nodes.
BFS will search through the tree assigning each vertex(node) a DISTANCE
value, which is the distance from the source vertex, and a PREDECESSOR value
which is ... | true |
0f24ce9b604ccda5bd7d222b9908dfbf57208982 | clettieri/Algorithm_Implementations | /MergeSort.py | 2,577 | 4.3125 | 4 | """
MergeSort
Given an array, merge_sort will recursively divide that array
until a subarray is length 0 or 1. In this base case (length 0 or 1),
the subarray is said to be sorted. Once the array is split up to the base case,
the merge function is called on each pairing of subarrays. The merge
function looks at the... | true |
2306352364be797d3e51b2b1380e821e8f68c065 | fabiofigueredo/python | /ex/ex009.py | 2,910 | 4.1875 | 4 | frase='Curso em Video Python'
print(frase) #Quando se insere uma string no Python, cada letra vira um espaço numerado na memária, iniciando de zero.
print(frase[9]) #Mostra a letra que está na posição 9.
print(frase[9:13]) #Mostra as letras no intervalo em 9 e 13, excluindo a ultima (13).
print(frase[9:21:2]) #Mostra a... | false |
49c2cbcf5686416914004eb4f071f84d669feb5b | zalthehuman/Python | /eulerPro.py | 2,352 | 4.25 | 4 | import sys
import math
from collections import OrderedDict
#1 Multiples of 3 and 5
"""
If we list all the natural numbers below 10 that are multiples of 3 or 5,
we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
"""
def multThreeOrFive():
sum = 0
for i in ... | true |
a7387c1ecff82382aa75b75b113e62f318c73d32 | MiguelCF06/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/4-print_square.py | 556 | 4.25 | 4 | #!/usr/bin/python3
"""
Prints a square with "#"
"""
def print_square(size):
"""
An argument size type integer
representing the size of the square
"""
if isinstance(size, bool):
raise TypeError("size must be an integer")
elif not isinstance(size, int):
raise TypeError("size mus... | true |
e4e2598fbf394b7a2e1c2b660bb21732333a9005 | MiguelCF06/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/tests/6-max_integer_test.py | 1,226 | 4.375 | 4 | #!/usr/bin/python3
"""Unit test for the function max_integer
"""
import unittest
max_integer = __import__('6-max_integer').max_integer
class TestingMaxInteger(unittest.TestCase):
"""
Class Test for the max integer cases
"""
def no_arguments_test(self):
""" Test when no arguments is passed """
... | true |
cc926e711459e9bcb61c56041f6092a967b13cc8 | colinbazzano/learning-python | /src/classes/cats.py | 489 | 4.28125 | 4 | class Cat:
species = 'mammal'
def __init__(self, name, age):
self.name = name
self.age = age
# Instantiate the Cat object with 3 cats
cat1 = Cat("Tiff", 1)
cat2 = Cat("Gregory", 3)
cat3 = Cat("Harold", 12)
# Create a function that finds the oldest cat
def oldest_cat(*args):
return max... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.