blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
02350014103279d5c3d072b18cae6a3e0798de75 | teddyk251/alx-higher_level_programming-1 | /0x07-python-test_driven_development/2-matrix_divided.py | 1,289 | 4.28125 | 4 | #!/usr/bin/python3
""" divides all elements of a matrix """
def matrix_divided(matrix, div):
"""
divides all elements of a matrix
Args:
matrix: matrix to be divided
div: number used to divide
Return:
matrix with divided elements
"""
if not all(is... | true |
a4b17d50fcc0e1c5ff7bc85f4315217397529ea9 | nakashi120/PythonLectureKame | /basic/dictionary_func.py | 535 | 4.1875 | 4 | fruits_colors = {'apple': 'red', 'lemon': 'yellow', 'grapes': 'purple'}
if 'peach' in fruits_colors:
print(fruits_colors['peach'])
else:
print('the key is not found')
# .get(): dictionaryから値を取得する→なくてもエラーにならない
# fruits_colors.get('peach', 'nothing')
fruit = input("フルーツの名前を指定してください:")
print(fruits_colors.get(fr... | false |
c50d56c52c0a4b7c106abf365dccf609029e4792 | nakashi120/PythonLectureKame | /basic/if_non.py | 216 | 4.125 | 4 | # if文でのNoneの取り扱い
a = None # 「なにも値が入っていない」が入っている
# if a is None:
# print("a is None!")
# else:
# print("a has value!")
if not a:
print("a is None")
| false |
758b8709a3d0133fa00beb506b662cb00bd51129 | rkgitvinay/python-basic-tutorials | /3-control_flow.py | 714 | 4.21875 | 4 | """ Control Flow Statements """
"""
uses an expression to evaluate whether a statement is True or False.
If it is True, it executes what is inside the “if” statement.
"""
""" If Statement """
if True:
print("Hello This is if statement!")
""" Output: Hello This is if statement! """
if 5 > 2:
print("5 is greate... | true |
06e0b06b985e0ac48cfe3ecd6c1ca1de69334424 | ybettan/ElectricalLabs | /electrical_lab_3/aws_experiment/part2/preliminary/q4.py | 279 | 4.3125 | 4 |
grades = {"python": 99, "java": 90, "c": 90}
grades_list = [x for _, x in grades.items()]
max_grade = max(grades_list)
min_grade = min(grades_list)
print "My lowest grade this semester was {}".format(min_grade)
print "My highest grade this semester was {}".format(max_grade)
| true |
2d11b7b1d939f6be364dc2394728fe2a21b99e95 | Nduwal3/python-Basics | /function-Assignments/soln16.py | 377 | 4.125 | 4 | """
Write a Python program to square and cube every number in a given list of
integers using Lambda.
"""
def calc_square_and_cube(input_list):
square_list = map(lambda num: num * num, input_list)
cube_list = map(lambda num: num ** 3, input_list)
print(list(square_list))
print(list(cube_list))
sample... | true |
f4fd513b8f8706e0339d7da3284b5f22364b5d04 | Nduwal3/python-Basics | /soln43.py | 374 | 4.25 | 4 | """
Write a Python program to remove an item from a tuple.
"""
# since python tuples are immutable we cannot append or remove item from a tuple.
# but we can achive it by converting the tuple into a list and again converting the list back to a tuple
my_tuple = ('ram', 37, "ram@r.com")
my_list = list(my_tuple)
my_l... | true |
10047fa0561ecf373381ce8abed48587402952b3 | Nduwal3/python-Basics | /function-Assignments/soln7.py | 825 | 4.21875 | 4 | """
Write a Python function that accepts a string and calculate the number of
upper case letters and lower case letters.
Sample String : 'The quick Brow Fox'
Expected Output :
No. of Upper case characters : 3
No. of Lower case Characters : 12
"""
def count_string_lower_and_upper_case(input_string):
count_up... | true |
4af30bc0c5fa913415ad507c23232f86a20fad8a | Nduwal3/python-Basics | /function-Assignments/soln9.py | 591 | 4.15625 | 4 | """
Write a Python function that takes a number as a parameter and check the
number is prime or not.
Note : A prime number (or a prime) is a natural number greater than 1 and that
has no positive divisors other than 1 and itself.
"""
def check_prime(num):
is_prime = False
if num > 1:
for i in range... | true |
515a4847f1592a5d8329f075cf40506c63350f82 | Nduwal3/python-Basics | /soln25.py | 548 | 4.1875 | 4 | """
Write a Python program to check whether all dictionaries in a list are empty or
not.
Sample list : [{},{},{}]
Return value : True
Sample list : [{1,2},{},{}]
Return value : False
"""
def check_empty_dictionaries(sample_list):
is_empty = False
for item in sample_list:
if item:
is_... | true |
b15c7f66e5d574148dc9ac92344d92440ec0744f | arossouw/study | /python/math/factorial.py | 204 | 4.28125 | 4 | #!/usr/bin/python
# recursive function for factorial
# factorial example: 4! = 4 * 3 * 2 * 1 = 24
def factorial(n):
if n == 0:
return 1
return n * factorial(n-1)
print factorial(4)
| false |
fc5d4c5006f3c9217d58848447a4fd76382a4a72 | GravityJack/keyed-merge | /keyed_merge/merge.py | 880 | 4.1875 | 4 | import functools
import heapq
def merge(*iterables, key=None):
"""
Merge multiple sorted iterables into a single sorted iterable.
Requires each sequence in iterables be already sorted with key, or by value if key not present.
:param iterables: Iterable objects to merge
:param key: optional, callab... | true |
270e8bd8f98d915bb4c3eab7214254d168e6c5af | MarcosMaciel-MMRS/Desenvolvimento-python | /Python-desenvolvimento/ex100.py | 730 | 4.1875 | 4 | #Faça um programa que tenha uma lista chamada números e duas funções chamadas sorteia() e somaPar().
#A primeira função vai sortear 5 números e vai colocá-los dentro da lista e a segunda função vai mostrar
#a soma entre todos os valores pares sorteados pela função anterior.
from random import randint
numeros = list... | false |
f1a8f4d31bebc4ac16a5398074c3b239b157b57f | MarcosMaciel-MMRS/Desenvolvimento-python | /Python-desenvolvimento/ex043.py | 988 | 4.15625 | 4 | #ler a altura e o peso, e diga o IMC da pessoa
print('-=-'*15)
print(' Tabela IMC')
print('-=-'*15)
print('''Classifição de IMC:
-Abaixo de 18.5: Abaixo do Peso
-Entre 18.5 e 25: Peso ideal
-25 até 30: Sobrepeso
-30 até 40: Obsesidade
-Acima de 40: Obesidade Mórbida''')
altura = float(input('I... | false |
79bbbe4ccc0ed72472e0afb9ee68195e2987b4a7 | MarcosMaciel-MMRS/Desenvolvimento-python | /Python-desenvolvimento/ex072.py | 767 | 4.3125 | 4 | #ler um némero entre 0-20 e mostrar ele por extenso ex: 1 - um
tupla = ('Zero','um','dois','tres', 'quatro', 'cinco', 'seis', 'sete', 'oito','nove','dez',
'onze','dose','treze','quatorze','quinze','dezesseis', 'dezessete','dezoioto','dezenove','vinte')
from time import sleep
while True:
numero = ' '
whil... | false |
4215f51f733aee82705cb8c4eef62d371153ab4a | MarcosMaciel-MMRS/Desenvolvimento-python | /Python-desenvolvimento/ex016.py | 521 | 4.15625 | 4 | #receber um numero real e converter em inteiro
#from math import trunc
import math
n = float(input('Informe um Número Real: '))
#assim é sem importar nenhuma biblioteca
print('O número {} tem a aparte inteira {}.'.format(n, int(n)))
#print('O número {} tem a aparte inteira {}.'.format(n, math.tunc(n)))-- usando o... | false |
0ae9854fa9f101ff2544726d2b4a26b7798dfd2e | MarcosMaciel-MMRS/Desenvolvimento-python | /Python-desenvolvimento/ex103.py | 668 | 4.15625 | 4 | #Faça um programa que tenha uma função chamada ficha(), que receba dois parâmetros opcionais:
#o nome de um jogador e quantos gols ele marcou. O programa deverá ser capaz de mostrar a ficha do jogador,
#mesmo que algum dado não tenha sido informado corretamente.
#função
def ficha(nome = 'Desconhecido', gols = ... | false |
670e0cdf838b9b91613d24164ac5ec9882e3d96f | MarcosMaciel-MMRS/Desenvolvimento-python | /Python-desenvolvimento/ex075.py | 540 | 4.1875 | 4 | #gerar uma tupla aleatoria com 5 números.
#mostrar quem é o maior, e quem é o menor.
from random import randint
numeros = (randint(1,10), randint(1,10), randint(1,10),
randint(1,10), randint(1,10))
print('Os números Sorteados foram: ', end = ' ')
for n in numeros:
print(f'{n}', end = ' ')
prin... | false |
ce66653d7fff7ecf1b4546c0b1e1bcefe823c01c | MarcosMaciel-MMRS/Desenvolvimento-python | /Python-desenvolvimento/ex086.py | 624 | 4.28125 | 4 | #Crie um programa que declare uma matriz de dimensão 3x3 e preencha com valores lidos pelo teclado.
#No final, mostre a matriz na tela, com a formatação correta.
from random import randint
aleatorio = randint(0,10)
matriz = [[0,0,0], [0,0,0], [0,0,0]]
for l in range(0,3):#para ler o camando na linha
for c in ... | false |
c42d98a322b0062c2c2e66fc1f00645174de5d88 | igoradriano/curso_python_bemol | /Aula_22/aula_22-funcao-lambda.py | 742 | 4.25 | 4 | # Funcoes anonimas
soma = lambda a,b : a + b
mult = lambda a,b,c : (a+b)*c
print((lambda a,b: a - b)(3,44)) # Neste caso nem preciso declar nome, nem chamá-la, ele ja executa
# Usando a funcao criada
c = soma(1,2)
print(c)
print(soma(1,2))
print(mult(1,2,3))
# Usando funcoes como parâmetro da funcao lambda
r = la... | false |
7c918ccd80ec7fd3c45d8233a12a62bd423c7937 | msflyee/Learn_python | /code/Chapter4_operations on a list.py | 1,062 | 4.28125 | 4 | # Chapter4-operations on a list
magicians = ['Alice','David','Liuqian'];
for magician in magicians: #define 'magician'
print(magician + '\t');
for value in range(1,5): #define value
print(value);
numbers = list(range(1,6));
print(numbers);
even_numbers = list(range(2,11,2)); #打印偶数,函数range()的第三个参数为 步数
print(... | true |
733f3343ec96f97ef4af38c87accc5cda0324999 | AndrewNik/python_course | /less7/task2.py | 936 | 4.1875 | 4 | # 2. Отсортируйте по возрастанию методом слияния одномерный вещественный массив, заданный случайными числами на
# промежутке [0; 50). Выведите на экран исходный и отсортированный массивы.
import random
def merge_sort(arr):
def merge(left, right):
result = []
i = j = 0
while i < len(left) and j < len(right):
... | false |
30808f5fb665d31421e878ace60502afebf33836 | ShaneRandell/Midterm_001 | /midterm Part 4.py | 867 | 4.1875 | 4 | ## Midterm Exam Part 4
import csv # imports the csv library
file = open("book.csv", "a") # Opening a file called book.csv for appending
title = input("enter a title: ") # asking the user to enter a title
author = input("Enter author: ") # asking the user to enter a author
year = input("Enter the year it wa... | true |
065aff05e0876ed0cedeea555109f6147a9d3219 | Venkatesh147/60-Python-projects | /60 Python projects/BMI Calculator.py | 572 | 4.28125 | 4 | Height=float(input("Enter your height in centimeters: "))
Weight=float(input("Enter your weight in kg: "))
Height=Height/100
BMI=Weight/(Height*Height)
print("your Body Mass Index is: ", BMI)
if(BMI>0):
if (BMI<=16):
print("you are severly underweight")
elif (BMI<=18.5):
... | true |
2b654bfaf67cefdbdff9a1b4b61d4d80af3da5ff | CodecoolBP20172/pbwp-3rd-si-code-comprehension-frnczdvd | /comprehension.py | 1,948 | 4.34375 | 4 | # This program picks a random number between 1-20 and the user has to guess it under 6 times
import random # Import Python's built-in random function
guessesTaken = 0 # Assign a variable to 0
print('Hello! What is your name?') # Display a given output message
myName = input() # Ask for user input
number = random.ran... | true |
f97c7326e6be4786e1fda3a5c4a55c61aa6c6f3c | KLKln/Module11 | /employee1.py | 2,382 | 4.53125 | 5 | """
Program: employee.py
Author: Kelly Klein
Last date modified: 7/4/2020
This program will create a class called employee allowing the user to
access information about an employee
"""
import datetime
class Employee:
def __init__(self, lname, fname, address, phone, start_date, salary):
"""
use r... | true |
6ba6176c13121443a781646914751b1430766e51 | RaHuL342319/Integration-of-sqlite-with-python3 | /query.py | 813 | 4.375 | 4 | import sqlite3
# to connect to an existing database.
# If the database does not exist,
# then it will be created and finally a database object will be returned.
conn = sqlite3.connect('test.db')
print("Opened database successfully")
# SELECTING WHOLE TABLE
cursor = conn.execute(
"SELECT * from Movies")
... | true |
ae3dfe81639e3c295061a8b173dde8303632fd41 | holbertra/Python-fundamentals | /dictionary.py | 1,201 | 4.3125 | 4 | # Dictionaries
# dict
my_dictionary = {
"key" : "value",
"key2" : 78
}
product = {
"id" : 2345872425,
"description": "A yellow submarone",
"price" : 9.99,
"weight" : 9001,
"depart" : "grocery",
"aisle" : 3,
"shelf" : "B"
}
#print(product["price"... | true |
27c43829d72a2e43b5ca4f1d6d54031bfdd10138 | axayjha/algorithms | /diagonal_traverse.py | 886 | 4.21875 | 4 | """
https://leetcode.com/problems/diagonal-traverse/
Given a matrix of M x N elements (M rows, N columns), return all elements of the matrix in diagonal
order as shown in the below image.
Example:
Input:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
Output: [1,2,4,7,5,3,6,8,9]
Explanation:
Note:
The total... | true |
edff4979701065d3a63aa5b1c7312a8389989d0b | shaduk/MOOCs | /UdacityCS101/app/days.py | 1,144 | 4.34375 | 4 | def nextDay(year, month, day):
"""Simple version: assume every month has 30 days"""
if day < 30:
return year, month, day + 1
else:
if month == 12:
return year + 1, 1, 1
else:
return year, month + 1, 1
def daysBetweenDates(year1, month1, day1... | true |
2aa27e73539e9ef7766fcf5ee480679d7b4fe2e2 | shaduk/MOOCs | /edx-CS101/myLog.py | 1,063 | 4.375 | 4 | '''Write a simple procedure, myLog(x, b), that computes the logarithm of a number x relative to a base b. For example, if x = 16 and b = 2, then the result is 4 - because 24=16. If x = 15 and b = 3, then the result is 2 - because 32 is the largest power of 3 less than 15.
In other words, myLog should return the larges... | true |
e1b9ba8875c43b15ba0e68c7f9e1d4842af94de8 | sashokbg/python-exercises | /fibonacci/fibonacci.py | 516 | 4.125 | 4 | import argparse
def main():
args, number = parseArgs()
fibonacci(number)
def parseArgs():
parser = argparse.ArgumentParser()
parser.add_argument('number', help='Calculate the fibonacci sequence to the n-th element', type = int)
args = parser.parse_args()
return args, args.number
def fibonacci... | false |
69e0dd90a8cb90dab50b81eb9949364244187e45 | Luncode/Python-Learn | /dict.py | 489 | 4.40625 | 4 | print('学习:Python-dict')
#定义字典列表
d = {'Bob':95,'Lisa':96,'Luncode':100}
#修改key的值
d['Bob'] = 99
#检查key是否在列表中
print('Lisa' in d)
#输出对应key的value
print(d['Bob'])
#删除列表中的key和value
d.pop('Lisa')
#输出列表
print(d)
#小结
d = {'Michael': 95,'Bob': 75,'Tracy': 85}
print('d[\'Michael\'] =', d['Michael'])
print('d[\'Bob\'] =', d['Bob'... | false |
41411ad71ab27f75e0771dbadac75de58b9bb3dc | sol83/python-simple_programs_7 | /Lists/get_first.py | 467 | 4.34375 | 4 | """
Get first element
Fill out the function get_first_element(lst) which takes in a list lst as a parameter and prints the first element in the list. The list is guaranteed to be non-empty.
You can change the items in the SAMPLE_LIST list to test your code!
"""
SAMPLE_LIST = [1, 2, 3, 'a', 'b', 'c']
def get_first_e... | true |
0bed91b6da6b75ca360119fe10bd8c6507c16080 | patricia-faustino/AprofundandoEmPython | /manipulandoStrings02.py | 676 | 4.125 | 4 | #TUDO EM MAIÚSCULO
print("acarajé com camarão".upper())
#tudo em minúsculo
print("acarajé com camarão".lower())
#Inicial maiúscula
print("acarajé com camarão".capitalize())
#Quantas vezes o parametro aparece, count(parametro)
print("acarajé com camarão".count("é"))
#Troca um item por outro, replace(old, new)
p... | false |
5298e43d2497174ebf8477e9adede2f9c008fc67 | TSG405/SOLO_LEARN | /PYTHON-3 (CORE)/Fibonacci.py | 659 | 4.21875 | 4 | '''
@Coded by TSG, 2021
Problem:
The Fibonacci sequence is one of the most famous formulas in mathematics.
Each number in the sequence is the sum of the two numbers that precede it.
For example, here is the Fibonacci sequence for 10 numbers, starting from 0: 0,1,1,2,3,5,8,13,21,34.
Write a program to take N (variab... | true |
6dd541d14a70d5d0654da10db9074c0999507725 | kumarritik87/Python-Codes | /factorial.py | 217 | 4.21875 | 4 | #program to find factorial of given number using while loop:-
n = int(input("Enter the no to find factorial\n"))
temp = n
f = 1
while(temp>0):
f = f*temp
temp = temp-1
print('factorial of ',n,'is', f)
| true |
de6c458f37b0512d53d4f87baa84115af4cc235c | infinitumodu/CPU-temps | /tableMaker.py | 1,787 | 4.21875 | 4 | #! /usr/bin/env python3
def makeXtable(data):
"""
Notes:
This function takes the data set and returns a list of times
Args:
data: a list with each element containing a time and a list of the core tempatures at that time
Yields:
a list of times
"""
xTable = []
... | true |
f9e7b9f34a6456884c149fca05ae63188b08ac7e | EliseevaIN/python_lesson_3 | /text_L3.py | 1,584 | 4.1875 | 4 | #Считать текст из файла и выполнить последовательность действий:
print('1) методами строк очистить текст от знаков препинания;')
print()
f = open('text.txt', encoding='utf-8')
text = f.read()
str = text
symbol_list = [' ','.',',','?','!','-','–','—',"'",'"','«','»',':',';','(',')','\n']
for a in range(len(symbol_list... | false |
d8275b0bbc9be8dbf86bd2657ab2a7c4e3768c02 | jack-alexander-ie/data-structures-algos | /Topics/3. Basic Algorithms/1. Basic Algorithms/binary_search_first_last_indexes.py | 2,635 | 4.125 | 4 | def recursive_binary_search(target, source, left=0):
if len(source) == 0:
return None
center = (len(source)-1) // 2
if source[center] == target:
return center + left
elif source[center] < target:
return recursive_binary_search(target, source[center+1:], left+center+1)
el... | true |
d2fdddb9967037869d65f92edf0a93c4a1717c6f | jack-alexander-ie/data-structures-algos | /Topics/2. Data Structures/Recursion/recursion.py | 2,728 | 4.6875 | 5 |
def sum_integers(n):
"""
Each function waits on the function it called to complete.
e.g. sum_integers(5)
The function sum_integers(1) will return 1, then feedback:
sum_integers(2) returns 2 + 1
sum_integers(3) returns 3 + 3
sum_integers(4) returns 4 ... | true |
92d1e98c5ee646d5d8e9811c609af686208cb983 | abhijitmk/Rock-paper-scissors-spock-lizard-game | /rock paper scissors spock lizard game.py | 2,191 | 4.1875 | 4 | # Rock-paper-scissors-lizard-Spock template
# The key idea of this program is to equate the strings
# "rock", "paper", "scissors", "lizard", "Spock" to numbers
# as follows:
#
# 0 - rock
# 1 - Spock
# 2 - paper
# 3 - lizard
# 4 - scissors
import random
# helper functions
def name_to_number(name):
if(name==... | true |
7904febc4341aa06bb4beeefcaad7dc856296da9 | codpro880/project_euler | /python/problem_9.py | 836 | 4.40625 | 4 | """
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a^2 + b^2 = c^2
For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
"""
import math
def main():
for possible_triple in generate_possible_tripl... | false |
2022ee151003dadfd3e1a55b23644e0b37ebe16c | liwei86521/Design-Patterns-Py | /结构型模式/结构型模式-适配器模式.py | 1,393 | 4.125 | 4 | # -*- coding:utf-8 -*-
#适配器模式:由于系统调用方式的原因,需要把不同类里面的方法(名字不一样),用同样的方式来调用
class Bird:
def fly(self):
print('bird is flying ...')
class Dog:
def bark(self):
print('dog is barking ...')
class People:
def speak(self):
print('people is speaking ...')
class Adapter:
d... | false |
0a3caa0649b0442ab39a9d4baebce376191a4767 | jeevan-221710/AIML2020 | /1-06-2020assignment.py | 994 | 4.15625 | 4 | #password picker
import string
from random import *
print("Welcome password Picker!!!!")
adj = ["Excellet","Very Good","Good","Bad","Poor"]
noun = ["jeevan","sai","narra","anaconda","jupyter"]
digits = string.digits
spl_char = string.punctuation
Welcome password Picker!!!!
while True:
password = choice(adj) + choic... | true |
f820b900bce0f1a3de25fca50a91cf8a8a23eab9 | MLameg/computeCones | /computeCones.py | 811 | 4.375 | 4 | import math
print("This program calculates the surface area and volume of a cone.")
r = float(input("Enter the radius of the cone (in feet): "))
h = float(input("Enter the height of the cone (in feet): "))
print("The numbers you entered have been rounded to 2 decimal digits.\nRadius = "
+str(round(r,2))+ "... | true |
1ca49521e467baac5b5022196920c0302e112f4d | Tha-Ohis/demo_virtual | /Hello.py | 619 | 4.15625 | 4 |
name=input("Enter your name: ")
print("Hello" ,name)
# # x=4
# # y=3
# # z=10
# # k=15
# # if x ==y:
# # print (x)
# # elif y > z:
# # print(y)
# # elif k > z:
# # print(k)
# # else:
# # print(z)
# # Johns_age=20
# # Wicks_age=25
# # pauls_age=23
# # if Johns_age>Wicks_age:
# # print("John is old... | false |
4b69f0783a133a08f34e2dc0a1190df3340dc0f1 | Tha-Ohis/demo_virtual | /Functions/Using Funcs to guess highest number.py | 400 | 4.15625 | 4 |
def highest_number(first, second, third):
if first > second and first > third:
print(f"{first}is the highest number")
elif second > first and second > third:
print(f"{second} is the highest number")
elif third > first and third > second:
print(f"{third} is the highest number")
e... | true |
81634c60ec9ab4a5d9c75c7de1eada0e8ec45865 | Tha-Ohis/demo_virtual | /Program that checks the hrs worked in a day and displays the wage.py | 631 | 4.25 | 4 | # #Write a program that accepts the name, hours worked a day, and displays the wage of the person
name=input("Enter your Name: ")
hrs=float(input("Enter the No of Hours Worked in a day: "))
rate=20*hrs
wage=(f"You've earned {rate}$")
print(wage)
# #Write a program that takes in the sides of a rectangle and displays it... | true |
fee363dc717bbae969d71338fd0756e7ddc577a6 | niefy/LeetCodeExam | /explore_medium/sorting_and_searching/SortColors.py | 1,256 | 4.25 | 4 | """
https://leetcode-cn.com/explore/interview/card/top-interview-questions-medium/50/sorting-and-searching/96/
题目:颜色分类
给定一个包含红色、白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。
此题中,我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。
注意:
不能使用代码库中的排序函数来解决这道题。
示例:
输入: [2,0,2,1,1,0]
输出: [0,0,1,1,2,2]
进阶:
一个直观的解决方案是使用计数排序的两趟扫描算法。
首先... | false |
a0b3d022d89f844f0c0c0e577a64b17b64518869 | xvrlad/Python-Stuff | /Lab01A - Q10.py | 294 | 4.125 | 4 | prompt = "Enter a word: "
string = input(prompt)
letter_list = list(string)
letter_list.sort()
new_dict = {}
for letters in letter_list:
if letters not in new_dict:
new_dict[letters] = ord(letters)
for letters, asciis in new_dict.items():
print("{}:{}".format(letters,asciis))
| true |
72f6ecdabe68de3f216b47c50f029dbb20d634cb | KrisNguyen135/PythonSecurityEC | /PythonRefresher/01-control-flow/loops.py | 829 | 4.5625 | 5 | #%% While loops check for the conditions at each step.
x = 1
while x < 10:
print(x)
x += 1
print('Loop finished.')
#%% For loops are used to iterate through a sequence of elements.
a = [1, 2, 3]
for item in a:
print(item)
print()
#%% range(n) returns an iterator from 0 to (n - 1).
for index in range(len(a... | true |
d36fe85647e5b761c392d510b0227c48a40b6d38 | faryar48/practice_bradfield | /python-practice/learn_python_the_hard_way/ex08.py | 2,230 | 4.5 | 4 | def break_words(stuff):
"""THis function will break up words for us."""
words = stuff.split(' ')
return words
def sort_words(words):
"""Sorts the words."""
return sorted(words)
def print_first_word(words):
"""Prints the first word after popping it off."""
word = words.pop(0)
print ... | true |
fbfa8a3040fc10f13a593a4b4bc2661ccac37a81 | farzanakhareem/Python-program | /fibonocci.py | 411 | 4.46875 | 4 | # Python program to display the Fibonacci sequence
def recursive_fibo(n):
if n <= 1:
return n
else:
return(recursive_fibo(n-1) + recursive_fibo(n-2))
nterms =int(input("enter the value: "))
# check if the number of terms is valid
if nterms <= 0:
print("Plese enter a positive integer")
else:
... | false |
44f1516db4a25076cf141b193ebbe1f6e46bced2 | erickbgc/Python-intro | /strings.py | 1,113 | 4.25 | 4 | #Formas de operar con un string
myStr = 'Hola Mundo tarados'
print('respuesta: ' + myStr) #Otras fornas de
print(f'respuesta: {myStr}') #concatenar
print('respuesta: {0}'.format(myStr))
"""
-dir sirve para saber todo
lo que se pueda hacer con una string
"""
# print(dir(myStr))
#El print es solo para m... | false |
4bb152b990e86c9032072f399e94817fa140cf83 | Littlemansmg/pyClass | /Week 2 Assn/Project 4/4-2.py | 343 | 4.1875 | 4 | # created by Scott "LittlemanSMG" Goes on 11/05/2019
def miles_to_feet(miles):
feet = miles * 1520
return int(feet)
def main():
miles_input = input("How many miles did you walk?: ")
miles_input = float(miles_input)
print("You walked {} feet.".format(miles_to_feet(miles_input)))
if __name__ == ... | false |
c119cf284f9e9afe49e906b8f4b1ff771eee66c9 | ddh/codewars | /python/range_extraction.py | 1,817 | 4.625 | 5 | """
A format for expressing an ordered list of integers is to use a comma separated list of either
individual integers
or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. The range includes all integers in the interval including both endpoints. It is not c... | true |
14390a2ae3b6ad53a988c321de9df62ad7110e00 | ddh/codewars | /python/basic_mathematical_operations.py | 1,478 | 4.34375 | 4 | """
Your task is to create a function that does four basic mathematical operations.
The function should take three arguments - operation(string/char), value1(number), value2(number).
The function should return result of numbers after applying the chosen operation.
Examples
basic_op('+', 4, 7) # Output: 11
bas... | true |
160c7cb9ab9719c4d0573ce90bb4c9e70ba1ca9b | junyechen/PAT-Advanced-Level-Practice | /1108 Finding Average.py | 2,573 | 4.34375 | 4 | """
The basic task is simple: given N real numbers, you are supposed to calculate their average. But what makes it complicated is that some of the input numbers might not be legal. A legal input is a real number in [−1000,1000] and is accurate up to no more than 2 decimal places. When you calculate the average, those i... | true |
57b09375d75919214cd994056c2b4013bde55e90 | hrishigadkari/Hackerrank | /staircase.py | 394 | 4.15625 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the staircase function below.
def staircase(n):
for i in range(0,n):
for j in range(0,n-1-i):
print(" ",end="")
for j in range(0,i+1):
print("#", end ="")
print(end="\n... | false |
7ac060f0eaedadd5c18d3dce33afa776639f45f2 | TranD2020/Backup | /lists.py | 1,315 | 4.34375 | 4 | # Make a list
myClasses = ["Algebra", "English", "World History"]
print(myClasses)
# add an item to the list
# append or insert
# append will add to the back of the list
myClasses.append("Coding")
print(myClasses)
favClass = input("What is your favorite class? ")
myClasses.append(favClass)
print(myClasses)... | true |
aa5d7c78bc0e77b5ad660b713b65b918ae20707d | TranD2020/Backup | /practice3.py | 393 | 4.375 | 4 | print("Hello, this is the Custom Calendar.")
day = input("What is today(monday/tuesday/wednesday/thursday/friday/saturday/sunday): ")
if day == "monday":
print("It's Monday, the weekend is over")
elif day == "friday":
print("It's Friday, the weekend is close")
elif day == "saturday" or "sunday":
print("It... | true |
a795152079fe503c87516ab5b753c0c33c504c73 | gouri21/c97 | /c97.py | 491 | 4.25 | 4 | import random
print("number guessing game")
number = random.randint(1,9)
chances = 0
print("guess a number between 1 and 9")
while chances<5:
guess = int(input("enter your guess"))
if guess == number:
print("congratulations you won!")
break
elif guess<number:
print("guess a number hi... | true |
e0883ed37e79623f17ea2eaae85cc49b05e012ea | BigPPython/Name | /name.py | 1,110 | 4.125 | 4 | # Code: 1
# Create a program that takes a string name input,
# and prints the name right after.
# Make sure to include a salutation.
import sys
a = '''**********************************
*WHAT IS YOUR SEXUAL ORIENTATION?*
*TYPE *
*M FOR MALE *
*F FOR FEMALE ... | true |
5cf92bdd9fbd1820297c63dcb370a5d7b3bb1129 | SKosztolanyi/Python-exercises | /11_For loop simple universal form.py | 345 | 4.25 | 4 | greeting = 'Hello!'
count = 0
# This is universal python for loop function form
# The "letter" is <identifier> and "greeting" is <sequence>
# the "in" is crucial. "letter" can be changed for any word and the function still works
for letter in greeting:
count += 1
if count % 2 == 0:
print letter
p... | true |
11cea43282d93c8ff11abe1bd833275be18744c6 | SKosztolanyi/Python-exercises | /88_Tuples_basics.py | 1,136 | 4.6875 | 5 | # Tuples are non-changable lists, we can iterate through them
# Tuples are immutable, but lists are mutable.
# String is also immutable - once created, it's content cannot be changed
# We cannot sort, append or reverse a tuple
# We can only count or index a tuple
# The main advantage of a tuple is, they are more effic... | true |
d0fc126abdd1251d5c7555870ec36b49798c8936 | SKosztolanyi/Python-exercises | /33_Defining factorials functions iterativela and recursively.py | 374 | 4.15625 | 4 | # Recursive and iterative versions of factorial function
def factI(n):
'''
Iterative way
assume that n is an int>0, returns n!
'''
res = 1
while n >1:
res = res*n
n-=1
return res
def factR(n):
'''
Recursive way
assume that n is an int>0, returns n!
'''
... | true |
2827c8423400bfe3d5c7992fd80d1a8d321dbd9f | pmmorris3/Code-Wars-Solutions | /5-kyu/valid-parentheses/python/solution.py | 471 | 4.25 | 4 | def valid_parentheses(string):
bool = False
open = 0
if len(string) == 0:
return True
for x in string:
if x == "(":
if bool == False and open == 0:
bool = True
open += 1
if x == ")" and bool == True:
if open - 1 == 0:
... | true |
bff81845806f726c9ebf0c35c407076314d711ff | borodasan/python-stady | /duel/1duel/1duel.py | 483 | 4.4375 | 4 | def p(p):
for i in range(0,5,2): #The range() function defaults to increment the sequence by 1,
#however it is possible to specify the increment
#value by adding a third parameter: range(0, 5, 2)
#Assignment operators are used to assign values to... | true |
a67e31b47c7be597942229d2f9046e4b7dc4e283 | borodasan/python-stady | /python-collections-arrays/set.py | 1,504 | 4.65625 | 5 | #A set is a collection which is unordered and unindexed.
#In Python sets are written with curly brackets.
print("A set is a collection which is")
print("unordered and unindexed".upper())
print("In Python sets are written with curly brackets.")
#Create a Set
print("Create a Set:")
thisset = {"apple", "banana", "cherry... | true |
423736de6e6515f77cec66aefb7941ba34c623ae | shane806/201_Live | /13. More Lists/live.py | 297 | 4.15625 | 4 | matrix = [[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 1, 2, 3],
[4, 5, 6, 7]]
def create_new_2d_list(height, width):
pass
def main():
# how do I get at the 9?
# how do I loop through the third row?
# how do I loop through the second column?
pass
main()
| true |
5158eedff805fe1a02c30ccc26fbe4027407d813 | untalinfo/holbertonschool-higher_level_programming | /0x0B-python-input_output/100-append_after.py | 570 | 4.125 | 4 | #!/usr/bin/python3
"""
Module
"""
def append_after(filename="", search_string="", new_string=""):
"""
Inserts a line of text to a file
Args:
filename (str, optional)
search_string (str, optional) Defaults to "".
new_string (str, optional) Defaults to "".
"""
with open(file... | true |
85eb2ffc8676179e4c6f23062f20a19e0d0a1906 | HATIMj/MyPythonProblems | /Divisor.py | 1,138 | 4.125 | 4 | #DIVISOR OR NOT
try: #trying the below inputs
n=int(input("Enter the total number of apples:--"))#Taking an input of number of apples
mn=int(input("Enter the minimum no. of students:--")) #Taking the input of minimum number of students
mx=int(i... | true |
ef953085648ad000470656586143e2cefd242470 | pratyushmb/Prat_Python_Repo | /W3Schools/tuples.py | 525 | 4.40625 | 4 | myTuple = ("a", "b", "c")
print(myTuple)
print(myTuple[1])
print(myTuple[-1])
print(myTuple[1:2])
# change tuple value though its unchangable
myList = list(myTuple)
myList[1] = "change"
myTuple = tuple(myList)
print(myTuple)
# iterate thru tuple: need to verify
for x in myTuple:
print(x)
if "change" in myTuple:
... | false |
6ea2887ac7d1679ca5663d773c288bbfc38b40cf | emmanuelnyach/python_basics | /algo.py | 818 | 4.25 | 4 | # num1 = input('enter first number: ')
# num2 = input('enter second number: ')
#
# sum = float(num1) + float(num2)
#
# print('the sum of {} and {} is {}'.format(num1, num2, sum))
# finding the largest num in three
#
# a = 8
# b = 4
# c = 6
#
# if (a>b) and (a>c):
# largest=a
# elif (b>a) and (b>c):
# l... | true |
b3c8b121c0559b7b11c070f102ecd971f7eb28fd | noyonict/Number-conversion-in-Python-3 | /decimal_to_binary.py | 324 | 4.25 | 4 | # Convert Decimal number to Binary Number
def dec_to_bin(dec_num):
"""Convert Decimal Number dec_num to Binary Number"""
bin_num = 0
power = 0
while dec_num > 0:
bin_num += 10 ** power * (dec_num % 2)
dec_num //= 2
power += 1
return bin_num
print(dec_to_bin(46... | false |
03d5fa4ff4dece6cb4e00d200257353e66ce478d | elementbound/jamk-script-programming | /week 4/listsum.py | 738 | 4.125 | 4 | # 4-3) list calculation with type detection
#
# calculate sum and average of elements in the list
# ignore all values in the list that are not numbers
#
# initializing the list with the following values
#
# list = [1,2,3,4,5,6,7,8,9,20,30, "aa", "bee", 11, "test", 51, 63]
def is_int(val):
try:
val = int(va... | true |
bb510d0b1d3e9b30af489969971b3702c03eaf25 | Steven-Chavez/self-study | /python/introduction/numbers.py | 848 | 4.28125 | 4 | # Author: Steven Chavez
# Email: steven@stevenscode.com
# Date: 9/4/2017
# File: numbers.py
''' Expression is used like most other languages.
you are able to use the operators +, -, *, and /
like you would normally use them. You can also group
the expressions with parentheses ()'''
# addition, subtraction, multipli... | true |
7fb4ede2dbd7ba97c78af7fa5cedcef8fcbf7baf | rakesh0180/PythonPracties | /TupleEx.py | 506 | 4.21875 | 4 | items = [
("p1", 4),
("p2", 2),
("p3", 5)
]
# def sort_item(item):
# return item[1]
# print(item.sort(key=sort_item))
# print(item)
# using lambada we avoid above two statement
items.sort(key=lambda item: item[1])
print(items)
# map
x = list(map(lambda item: item[1], items))
print("map", x)
# fil... | true |
7d1d9a1997ec0ad4df02b524784e424cd8a31d95 | devcybiko/DataVizClass | /Week3/RockPaperScissors.py | 812 | 4.125 | 4 | import random
while True:
options = ["r", "p", "s"]
winning_combinations = ["rs", "sp", "pr"]
### for rock, paper, scissors, lizard, spock...
# options = ["r", "p", "s", "l", "x"]
# winning_combinations = ["sp", "pr", "rl", "lx", "xs", "sl", "lp", "px", "xr", "rs"]
user_choice = input(options)
... | true |
62e75902fa73c4b3cf3c0efbbeff4e928cb80119 | BENLINB/Practice-assignment-for-Visual-Studio | /Generate username.py | 536 | 4.125 | 4 | #Problem2
#writing programm that would prompt the username in the format Domain Name-Username.
print("#######################################")
print("WELCOME TO DBS CONSOLE")
print("#######################################")
#asking the user to input his credentials
student=input("enter username")
index= s... | true |
599ecf8e936096c23c02615562f20d5eaf8a2b0e | prince5609/Leet_Code | /Max_Deapth_Binary_Tree.py | 579 | 4.15625 | 4 | # Given the root of a binary tree, return its maximum depth. A binary tree's maximum depth is the number of nodes
# along the longest path from the root node down to the farthest leaf node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
sel... | true |
a0d4f9f823847403700707ce540fa1b6e7aef386 | Nitin-K-1999/Python_script | /Sample Script 1.py | 504 | 4.34375 | 4 | # A list of cricket team is given below. Print the number of possible matches between each of them. Also print each possible match in the format team1 vs team2.
team_list = ['CSK','RCB','Sun Risers','Deccan Chargers','Mumbai Indians']
matches = []
for index in range(len(team_list)) :
for team in team_list[i... | true |
9550534f45044d9b5ee3c3cf3543b39fc2d123b6 | Sudhanshu277/python | /list.py | 373 | 4.21875 | 4 | # crete a list using []
a = [1, 3, 4,5,6,"pninfosys"] #index 0 start
print(a)
#access using index using a[0] , a[1]
print(a[2])
#change the value of list using
a[0] = 40
print(a)
#we can crete a list with items of different types
c = ["pnifosys" , 12,False,7.5]
print(c)
#list slicing
pn = ["vikas" , "ram" , "rohan"... | false |
8978220700fcf7ed48d7b0840bebd70696ee3fd8 | VRamazing/UCSanDiego-Specialization | /Assignment 2/fibonacci/fibonacci.py | 359 | 4.15625 | 4 | # Uses python3
# Task. Given an integer n, find the nth Fibonacci number F n .
# Input Format. The input consists of a single integer n.
# Constraints. 0 ≤ n ≤ 45.
def calc_fib(n):
if n==0:
return 0
elif n==1:
return 1
else:
arr=[1,1]
for i in range(2,n):
arr.append(arr[i-1]+arr[i-2])
return arr[n-1]
n... | true |
077db2a0f5904ba96886cc827b25c8d384e7e1b7 | VRamazing/UCSanDiego-Specialization | /Assignment 3/greedy_algorithms_starter_files/fractional_knapsack/fractional_knapsack.py | 2,169 | 4.15625 | 4 | # Uses python3
import sys
# Task. The goal of this code problem is to implement an algorithm for the fractional knapsack problem.
# Input Format. The first line of the input contains the number n of items and the capacity W of a knapsack.
# The next n lines define the values and weights of the items. The i-th line c... | true |
620323ff5e0c51b2c619e132e57523c07f206efc | ifpb-cz-ads/pw1-2020-2-ac04-team-ricardoweligton | /atividade_4_02/questao_13.py | 590 | 4.28125 | 4 | """
13) Escreva um programa que leia números inteiros do teclado. O programa
deve ler os números até que o usuário digite 0 (zero). No final da
execução, exiba a quantidade de números digitados, assim como a soma e
a média aritmética.
"""
print("\n--------- Questao 13 --------- \n")
n = 0
x = 0
soma = 0
whi... | false |
cbeb6a4b06cd9f36bf351c269ca71de0793e2081 | ktandon91/DataStructures | /3. DyPro/rod_price.py | 1,021 | 4.28125 | 4 | """
Given a rod of length n inches and an array of prices that contains prices of all pieces of size smaller than n.
Determine the maximum value obtainable by cutting up the rod and selling the pieces.
For example, if length of the rod is 8 and the values of different pieces are given as following,
then the maximum obt... | true |
82234bc9ffaa3acb0a0bb64d040ec8e249789414 | iamshubhamsalunkhe/Python | /basics/Continueandbreak.py | 336 | 4.4375 | 4 | #continue is used to skip a iteration and jump back to other iteration
"""
for i in range(1,11,1):
if(i==5):
continue
print(i)
"""
'''
##break is used to break a iteration or stop a iteration at specific point
for i in range(1,11,1):
if(i==5):
continue
if(i==8):
break
... | true |
d54773b3f32729d8076b34ada3d07c1be629e2b3 | standrewscollege2018/2020-year-13-python-classwork-OmriKepes | /classes and objects python.py | 1,650 | 4.625 | 5 | ''' This program demonstrates how to use classes and objects.'''
class Enemy:
''' The enemy class has life, name, and funcations that do something.'''
def __init__(self, name, life):
'''This funcation runs on instantiation and sets up all attributes.'''
self._life = life
self._name = na... | true |
4873d8070a2d54482d0ea387eb1c901cfba8ef9e | Will-is-Coding/exercism-python | /pangram/pangram.py | 503 | 4.21875 | 4 | import re
def is_pangram(posPangram):
"""Checks if a string is a pangram"""
lenOfAlphabet = 26
"""Use regular expression to remove all non-alphabetic characters"""
pattern = re.compile('[^a-zA-Z]')
"""Put into a set to remove all duplicate letters"""
posPangram = set(pattern.sub('', posPangr... | true |
c0593fc5b9d1f0c56ff1039dd16fa37039fd869b | rpinnola47/PYTHON | /CLASES Fdla/clase listas.py | 1,008 | 4.125 | 4 | """
estrucutura de datos:
listas: puede estar conformada por varios elementos, que estan organizados en "fila de cajitas"
cada cajita tiene un solo valor. cada posicion tiene UN SOLO VALOR A LA VEZ pero todas esta agrupadas en una misma variable
*cada caja tiene su indice(arranca desde cero)
"""
#crea... | false |
23eb4288c74348e898b5e987f8755ebf2cc2db62 | Liam-Pigott/python_crash_course | /11-Advanced_Python_Modules/defaultdict.py | 769 | 4.15625 | 4 | from collections import defaultdict
# defaultdict is a dictionary-like object which provides all methods provided by a dictionary but takes a first argument (default_factory)
# as a default data type for the dictionary. Using defaultdict is faster than doing the same using dict.set_default method.
# A defaultdict wil... | true |
aad7fec002bf6717bb2a7e6389c964ec6344cd4a | Liam-Pigott/python_crash_course | /02-Statements/control_flow.py | 1,768 | 4.15625 | 4 | # if, elif and else
if True:
print("It's True")
else:
print("False")
loc = 'Bank'
if loc == 'Work':
print('Time to work')
elif loc == 'Bank':
print('Money maker')
else:
print("I don't know")
name = 'Liam'
if name == 'Liam':
print("Hello Liam")
elif name == 'Dan':
print('Hi Dan')
else:
... | true |
6f2d440071bdacdb59adc4409561dfb6b63683d3 | ksannedhi/practice-python-exercises | /Ex11.py | 618 | 4.34375 | 4 | '''Ask the user for a number and determine whether the number is prime or not. (For those who have forgotten, a prime number is a number that has no divisors.).
You can (and should!) use your answer from Exercise 4 to help you. Take this opportunity to practice using functions.'''
def find_prime_or_not(num):
d... | true |
bbe653b8a4f428b0c7abc5ede7939455abdf2a06 | ksannedhi/practice-python-exercises | /Ex15.py | 532 | 4.4375 | 4 | '''Write a program (using functions!) that asks the user for a long string containing multiple words.
Print back to the user the same string, except with the words in backwards order. For example, say I type the string:
My name is Michele
Then I would see the string:
Michele is name My'''
def reverse_words(inp... | true |
993033a674b3d7a44cc8aacb6f9910d84c8b4531 | pzinz/sep_practice | /22_HarvardX_w01_03.py | 2,199 | 4.25 | 4 | # Static typing mean that the type checking is performed during compile time
# dynamic typing means that the type checking is performed at run time
# Varible, objects and references
# x = 3 ; Python will first create the object 3 and then create the variable X and then finally reference x -> 3
# list defined as foll... | true |
ec68888812b15838438f33bcb97c68e3dac62ba2 | malekhnovich/PycharmProjects | /Chapter5_executing_control/Chapter6_dictionaries/tuple_example.py | 1,336 | 4.59375 | 5 | '''
IF DICTIONARY KEYS MUST BE TYPE IMMUTABLE WHILE LIST TYPE IS MUTABLE
YOU CAN USE A TUPLE
TUPLE CONTAINS A SEQUENCE OF VALUES SEPERATED BY COMMAS AND ENCLOSED IN PARENTHESIS(()) INSTEAD OF BRACKETS([])
'''
#THIS IS A TUPLE BECAUSE THE PARENTHESIS ARE ROUND RATHER THAN SQUARE
#SQUARE PARENTHESIS WOULD BE A LIST
#THE ... | true |
b42ace7c28ad5224af073ba6703128d6f80bfae5 | ses1142000/python-30-days-internship | /day 10 py internship.py | 1,313 | 4.3125 | 4 | Python 3.9.0 (tags/v3.9.0:9cf6752, Oct 5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> import re
>>> string = "a-zA-Z0-9"
>>> if re.findall(r'/w',string):
print("the string contains a set of char")
else:
print("the string does... | true |
9e90c8c11d9352283cd731aec48de88038b64f88 | JanusClockwork/LearnPy | /Py3Lessons/python_ex05.py | 1,597 | 4.125 | 4 | name = 'Janus Clockwork' #according to my computer lol
age = 26
height = 65 #inches. Also, why is height spelled like that. I before E except after C? My ass.
weight = 114 #lbs. also I AM GROWIIINNNG
eyes = 'gray' #'Murrican spelling
teeth = 'messed up'
hair = 'brown'
favePet = 'cats'
faveAnime = 'Yowamushi Pedal'
fav... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.