blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
3cee29d8ee596d508122d7e4d1349b6e226f148e | iampaavan/Pure_Python | /Exercise-95.py | 260 | 4.21875 | 4 | """Write a Python program to convert a byte string to a list of integers."""
def byte_str_list_integers(string):
"""return list of integers."""
my_list = list(string)
return my_list
print(f"List of integers: {byte_str_list_integers(b'Abc')}")
| true |
1ae7da4a80ff13e6e38a6f1ef9ec8c092208002d | iampaavan/Pure_Python | /Exercise-15.py | 494 | 4.3125 | 4 | from datetime import date
"""Write a Python program to calculate number of days between two dates."""
first_date = date(2014, 7, 2)
last_date = date(2014, 7, 11)
delta = last_date - first_date
print(f"First Date: {first_date}")
print(f"Second Date: {last_date}")
print(f'******************************************... | true |
9b279f74643634d02aae4969267a3fee44e10a78 | iampaavan/Pure_Python | /Exercise-4.py | 372 | 4.3125 | 4 | from math import pi
"""Write a Python program which accepts the radius of a circle from the user and compute the area."""
def radius():
"""Calculate the radius"""
r = int(input(f"Enter the radius of the circle:"))
Area = pi * (r * r)
return f"Area of the circle is: {Area}"
c = radius()
print(c)
pri... | true |
c35a1b8ecdab55a9c6a3dcabc2bdbd241a5e93f5 | iampaavan/Pure_Python | /Exercise-28.py | 291 | 4.21875 | 4 | """Write a Python program to concatenate all elements in a list into a string and return it."""
def concatenate(my_list):
"""Return a string."""
output = ''
for i in my_list:
string = str(i)
output += string
return output
print(concatenate([1, 2, 3, 4, 5]))
| true |
d8b11d176fb47a44390c72b979370931cf9f6ce8 | mtrunkatova/Engeton-projects | /Project2.py | 2,521 | 4.25 | 4 | def welcoming():
print("WELCOME TO TIC TAC TOE")
print("GAME RULES:")
print("Each player can place one mark (or stone) per turn on the 3x3 grid")
print("The WINNER is who succeeds in placing three of their marks in a")
print("* horizontal,\n* vertical or\n* diagonal row\nLet's start the game")
def ... | true |
e53fe6f2b910c285b7851783b61c4d7939638b71 | manoznp/LearnPython-Challenge | /DAY3/list.py | 1,519 | 4.34375 | 4 | #list
names = ['raju', 'manoj']
length_names = len(names)
print("Length of the array name is {}".format(length_names))
names.append("saroj")
length_names = len(names)
print("Length of the array name is {}".format(length_names))
print(names)
names.insert(1, "sudeep")
print("After inserting sudeep at position second:... | true |
6db5f977cc64e90e243d62f3b882c7d77371a86f | Williano/Python-Scripts | /turtle_user_shape/turtle_user_shape.py | 2,734 | 4.1875 | 4 | import turtle
window = turtle.Screen()
window.setup()
window.title("Draw User Shape")
window.bgcolor("purple")
mat = turtle.Turtle()
mat.shape("turtle")
mat.color("black")
mat.pensize(3)
mat.speed(12)
drawing = True
while drawing:
mat.penup()
SQUARE = 1
TRIANGLE = 2
QUIT = 0
shape_choice = i... | true |
532f8be7df48120a466f060ae0b80ebb6b2a7dfa | p3dr051lva/hanoi-s_tower.py | /hanoi.py | 1,293 | 4.1875 | 4 | print('Ola, este eh o jogo, torre de hanoi, o jogo tem o objetivo de voce transferir \
os numero da tore um para a torre 3, sem que numeros maiores fiquem em cima de numeros menores, voce\
so pode mover o disco do "topo", e uma por vez, a primeira torre de baixo para cima eh a t1, a segunda a\
t2, e a terceira a t3, pa... | false |
830802e627fe7aaed1057d4ed66ccadf532bf357 | tanpv/awesome-blockchain | /algorithm_python/move_zeros_to_end.py | 378 | 4.25 | 4 | """
Write an algorithm that takes an array and moves all of the zeros to the end,
preserving the order of the other elements.
move_zeros([false, 1, 0, 1, 2, 0, 1, 3, "a"])
returns => [false, 1, 1, 2, 1, 3, "a", 0, 0]
The time complexity of the below algorithm is O(n).
"""
input_list = [false, 1, 0, 1, 2, 0... | true |
eda4f62ffe3d1771eb868d4325d8310348d521c7 | Jayson22341/CS362HW3 | /LeapYearProg.py | 493 | 4.21875 | 4 | def leap(n):
if n % 4 == 0:
if n % 100 == 0:
if n % 400 == 0:
print(n, 'is a leap year')
return
print(n, 'is not a leap year')
return
print(n, 'is a leap year')
return
print(n, 'is not a leap year')
return
import ti... | false |
048ab8c2e21afc334d5cd093b47e7633f3530520 | ravenusmc/algorithms | /HackerRank/algorithms/diagonal_diff.py | 938 | 4.1875 | 4 | # Given a square matrix, calculate the absolute difference between the sums of its diagonals.
# For example, the square matrix arr is shown below:
# URL https://www.hackerrank.com/challenges/diagonal-difference/problem?h_r=next-challenge&h_v=zen
# Rank: 1,670,172
arr = [
[1, 2, 3],
[4, 5, 6],
[9, 8, 9]
]
# arr = [
#... | true |
c4bbc4e04d3ab14ecb92baad254d46959fc4329e | Sandeep0001/PythonTraining | /PythonPractice/SetConcept.py | 2,742 | 4.34375 | 4 | #Set: is not order based
#it stores different type of data like list and tuple
#it performs different mathematical operations
#does not store duplicate elements
#define a set: use {}
s1 = {100, "Tom", 12.33, True}
s2 = {1,1,2,2,3,3,}
print(s2) #Output: {1, 2, 3}
print(s1) #Output: {True, 1... | true |
e6270e723cfdb8d2895bb82a66b9fce05f3dfecc | soyolee/someLer | /euler/euler_009_Special_Pythagorean_triplet.py | 1,729 | 4.15625 | 4 | __author__ = "chlee"
import sys
import math
'''
#Problem 9
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.
'''
try:
if __name_... | false |
c4bd3a327087bdc0795e06d4c4125f93ed315255 | chaita18/Python | /Programms/check_multiply_by_16.py | 233 | 4.1875 | 4 | #!C:/Users/R4J/AppData/Local/Programs/Python/Python37-32
num = eval(input("Enter number to check if it is multiply by 16 : "))
if (num&15)==0 :
print("The number is multiple of 16")
else :
print("The number is not multiple of 16") | true |
bc8069602e13e364e7ad656ed67b04f81f45f9ab | chaita18/Python | /Programms/check_multiple_by_any_number.py | 298 | 4.1875 | 4 | #!C:/Users/R4J/AppData/Local/Programs/Python/Python37-32
num = eval(input("Enter number : "))
multiplier = eval(input("Enter multiplier : "))
if (num&multiplier-1)==0 :
print("The number %d is multiple of %d"%(num,multiplier))
else :
print("The number %d is not multiple of %d"%(num,multiplier)) | true |
6e4c88b8ac4cbcfeb167765e6aae299067db8b24 | TomchenEDG/LeetCode | /12.232. Implement Queue using Stacks.py | 1,553 | 4.40625 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
class MyQueue:
def __init__(self):
"""
defInitialize your data structure here.
"""
# 初始化两个列表,当作栈来使用
self.stack_in = []
self.stack_out = []
def push(self, x):
"""
Push element x to ... | false |
c626414f3ea6fd8a358b8be7d66f8c3c6a9bb387 | moyinmi/beginner-project-solution | /triplechecker.py | 381 | 4.375 | 4 | def triple_checker():
while True:
a = int(input("Enter a side: "))
b = int(input("Enter a side: "))
c = int(input("Enter a side: "))
h = max(a, b, c)
if (a**2) + (b**2) == (h**2):
print("Triangle is a pythagorean triple")
else:
print("... | false |
a20e4cd321b23d2b35abbe8233fca1c1e52cc410 | TechnologyTherapist/BasicPython | /02_var_datatype.py | 396 | 4.15625 | 4 | # innilize a value of data types
a=10
b='''hi
am
akash iam
good boy'''
c=44.4
d=True
e=None
# Now print the varaible value
print(a)
print(b)
print(c)
print(d)
print(e)
#now using type function to find data type of varaible
print(type(a))
print(type(b))
print(type(c))
print(type(d))
print(type(e))
#now i use how to fi... | true |
18281b137fad3eae028f4888a19b066627403125 | axeMaltesse/Python-related | /Learning-Python/anti_vowel_v2.py | 395 | 4.15625 | 4 | #definition
def anti_vowel(text):
#value to hold new string
b = ''
#for loop to chceck single letter
for a in range(len(text)):
#if the letter is in that string, do nothing; continue
if (text[a] in "aeiouAEIOU"):
continue
#add to the string
else:
b... | true |
0156518036d2d08de0d6a6635c3a9ecf5146bf6d | lovit/text_embedding | /text_embedding/.ipynb_checkpoints/fasttext-checkpoint.py | 688 | 4.125 | 4 | def subword_tokenizer(term, min_n=3, max_n=6):
"""
:param term: str
String to be tokenized
:param min_n: int
Minimum length of subword. Default is min_n = 3
:param max_n: int
Minimum length of subword. Default is max_n = 6
It returns
subwords: list of str
It cont... | true |
af90f9d14f0800526910d3c2c3fbb9356f3f564b | RaphaelPereira88/weather-report | /weather.py | 2,445 | 4.125 | 4 | import requests
API_ROOT = 'https://www.metaweather.com'
API_LOCATION = '/api/location/search/?query='
API_WEATHER = '/api/location/' # + woeid
def fetch_location(query):
return requests.get(API_ROOT + API_LOCATION + query).json() # convert data from json text to python dictionary accordint to u... | true |
1f31d271aac9c0d58683fd3b6401b1d37a706fb6 | tooreest/ppkrmn_gbu_pdf | /python_algorithm/l01/examples/times_compare/task_1.py | 964 | 4.3125 | 4 | """
Вычисление суммы первых n целых чисел
"""
def get_sum_1(n):
"""
В основе идеи алгоритма - переменная-счетчик, инициализируемая нулем
и к которой в процессе решения задачи прибавляются числа, перебираемые в цикле
:param n:
:return:
"""
res = 0
for i in range(1, n + 1):
... | false |
0edb1bcc113319362b8373404d583c9a278e935f | tooreest/ppkrmn_gbu_pdf | /pyhton_basic/q01l04/task_06.py | 1,247 | 4.15625 | 4 | #!
'''
Geekbrains. Факультет python-разработки
Четверть 1. Основы языка Python
Урок 4. Функции
Домашнее задание 6.
Реализовать два небольших скрипта:
а) бесконечный итератор, генерирующий целые числа, начиная с указанного,
б) бесконечный итератор, повторяющий элементы некоторого списка, определенного заранее.
Подсказк... | false |
1faac741cb2dc5e859673a87df828aed84eaa06f | tooreest/ppkrmn_gbu_pdf | /pyhton_basic/q01l04/task_02.py | 801 | 4.125 | 4 | #!
'''
Geekbrains. Факультет python-разработки
Четверть 1. Основы языка Python
Урок 4. Функции
Домашнее задание 2.
Представлен список чисел. Необходимо вывести элементы исходного списка,
значения которых больше предыдущего элемента. Подсказка: элементы,
удовлетворяющие условию, оформить в виде списка. Для формирования... | false |
d9657392a98a7f268a2b61e130158a6825765adf | tooreest/ppkrmn_gbu_pdf | /python_algorithm/l01/examples/structures_examples/stack/task_12.py | 1,601 | 4.15625 | 4 | """Пример создания стека через ООП"""
class StackClass:
def __init__(self):
self.elems = []
def is_empty(self):
return self.elems == []
def push_in(self, el):
"""Предполагаем, что верхний элемент стека находится в начале списка"""
self.elems.insert(0, el)
... | false |
b84ab2f45e8a33db98518c3b888f6447ac46040a | goosegoosegoosegoose/springboard | /python-ds-practice/33_sum_range/sum_range.py | 922 | 4.125 | 4 | def sum_range(nums, start=0, end=None):
"""Return sum of numbers from start...end.
- start: where to start (if not provided, start at list start)
- end: where to stop (include this index) (if not provided, go through end)
>>> nums = [1, 2, 3, 4]
>>> sum_range(nums)
10
>>>... | true |
c8eff632a0146b35ed1c97c43501956c63ae8046 | goosegoosegoosegoose/springboard | /python-syntax/in_range.py | 572 | 4.34375 | 4 | def in_range(nums, lowest, highest):
"""Print numbers inside range.
- nums: list of numbers
- lowest: lowest number to print
- highest: highest number to print
For example:
in_range([10, 20, 30, 40], 15, 30)
should print:
20 fits
30 fits
"""
nums.sort()
nums_r... | true |
912382a53ecbdf760a14c7b372c14df45d558f42 | ly989264/Python_COMP9021 | /Week2/lab_1_1_Temperature_conversion_tables.py | 418 | 4.28125 | 4 | '''
Prints out a conversion table of temperatures from Celsius to Fahrenheit degrees,
the former ranging from 0 to 100 in steps of 10.
'''
# Insert your code here
start_celsius=0
end_celsius=100
step=10
print('Celsius\tFahrenheit')
for item in range(start_celsius,end_celsius+step,step):
celsius=item
fahrenheit=int(... | true |
4ece48f5629219360d3cd195c0242f4e67805104 | imscs21/myuniv | /1학기/programming/basic/파이썬/파이썬 과제/11/slidingpuzzle.py | 2,053 | 4.125 | 4 | # Sliding Puzzle
import random
import math
def get_number(size):
num = input("Type the number you want to move (Type 0 to quit): ")
while not (num.isdigit() and 0 <= int(num) <= size * size - 1):
num = input("Type the number you want to move (Type 0 to quit): ")
return int(num)
def create_board(nu... | true |
a41d8b1e58f7c92013a67d53fdf9aee4c169c07d | foqiao/A01027086_1510 | /lab_09/factorial.py | 1,301 | 4.15625 | 4 | import time
"""
timer function store the procedures needed for time consumes during factorial calculations happened on two different
methods.
"""
def timer(func):
def wrapper_timer(*args, **kwargs):
start_time = time.perf_counter()
value = func(*args, **kwargs)
end_time = time.perf_counter(... | true |
ecb18199f9d45503e9585a723350d3d8c01c1d03 | foqiao/A01027086_1510 | /midterm_review/most_vowels.py | 899 | 4.21875 | 4 | def most_vowels(tuple):
vowel_in_tuple = []
vowel_rank = set()
vowel_amount = 0
tuple_of_string = range(0, len(tuple))
for i in tuple_of_string:
if tuple[i] == ',':
vowel_in_tuple.append(" ")
if tuple[i] == 'a':
vowel_in_tuple.append(tuple[i])
if tuple[... | false |
b8dc36c78448c0e58abcf2fffd77cb20dee69d2f | CINick72/project_euler | /pe9.py | 548 | 4.21875 | 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
"""
done = False
for a in range(500):
for b in range(500):
c = 2 * a... | false |
3166baaa4c08d4d7eca67acd85aa03d7dd6b253c | amshekar/python-mania | /day2/Classself.py | 812 | 4.15625 | 4 | students = []
class Student:
school_name="UPS"
#constructor self is equal to this in other languages
def __init__(self,name,student_id=332):
self.name=name
self.student_id=student_id
students.append(self)
# constructor to get rid of returning student object memory reference when we prin... | true |
0f0b07648567d31d44f309d19661c8c7a4f191f0 | xuting1108/Programas-de-estudo | /pdf_Bia/lista12_Bia/4.py | 758 | 4.125 | 4 | # Crie uma função que recebe uma lista de strings e
# a. retorne o elemento com mais caracteres
# b. retorne a média de vogais nos elementos ( no de vogais de cada elemento/no de
# elementos)
# c. retorne o número de ocorrências do primeiro elemento da lista
# d. retorne a palavra lexicograficamente maior
# e. conte ... | false |
defcb65c2bf687a8b6fc60b34bad34ae87884771 | xuting1108/Programas-de-estudo | /exercicios-pythonBrasil/estrutura-de-repeticao/ex3.py | 1,343 | 4.15625 | 4 | # Faça um programa que leia e valide as seguintes informações:
# Nome: maior que 3 caracteres;
# Idade: entre 0 e 150;
# Salário: maior que zero;
# Sexo: 'f' ou 'm';
# Estado Civil: 's', 'c', 'v', 'd';
nome = ''
idade = 0
salario = 0
sexo = ''
relacionamento = ''
while True:
nome = input('infor... | false |
2dcc4ae4feeaebade03f571ec4d09b7ce5b5d9fe | xuting1108/Programas-de-estudo | /exercicios-pythonBrasil/estrutura-de-decisao/ex8.py | 416 | 4.15625 | 4 | # Faça um programa que pergunte o preço de três produtos e informe qual produto você deve comprar, sabendo que a decisão é sempre pelo mais barato.
p1 = float(input('informe o preço do primeiro produto: '))
p2 = float(input('informe o preço do segundo produto: '))
p3 = float(input('informe o preço do terceiro produto:... | false |
8abfcad9dd32c44cdca5763e06c682bddb67cb04 | xuting1108/Programas-de-estudo | /python-para-zumbis/lista1/exercicio7.py | 251 | 4.25 | 4 | #Converta uma temperatura digitada em Celsius para Fahrenheit. F = 9*C/5 + 32
graus_celsius = float(input('Informe a temperatura em graus Celsius: '))
fahrenheit = (9 * graus_celsius) / 5 + 32
print(f'A temperatura em fahrenheit é: {fahrenheit}')
| false |
70d92acdff6f98f03cd5fab21d7ca7a3bdbfa335 | xuting1108/Programas-de-estudo | /exercicios-pythonBrasil/estrutura-de-decisao/ex5.py | 611 | 4.125 | 4 | #Faça um programa para a leitura de duas notas parciais de um aluno. O programa deve calcular a média alcançada por aluno e apresentar:
# A mensagem "Aprovado", se a média alcançada for maior ou igual a sete;
# A mensagem "Reprovado", se a média for menor do que sete;
# A mensagem "Aprovado com Distinção",... | false |
09494afbe608c3b8d1f67a86fba3e6ab2f800d63 | xuting1108/Programas-de-estudo | /exercicios-pythonBrasil/Listas/11.py | 454 | 4.125 | 4 | #Altere o programa anterior, intercalando 3 vetores de 10 elementos cada.
l1 = ['fernanda', 'roberta', 'lucas', 'elzi', 'filipe', 'igor', 'katia', 'pedro', 'thiago', 'bia']
l2 = [1,6, 9, 15, 16, 12, 18, 25, 62, 84]
l3 = ['Macaco', 'Galo', 'Cão', 'Porco', 'Rato', 'Boi', 'Tigre', 'Coelho', 'Dragão', 'Serpente']
# l3.... | false |
427bef40fca68167da9a854640161e0078177702 | yung-pietro/learn-python-the-hard-way | /EXERCISES/ex40.py | 2,301 | 4.71875 | 5 | # You can think of a module as a specialized dictionary, where I can store code
# and access it with the . operator
# Similarly, a Class is a way of taking a grouping of functions and data and place
# them in a similar container so as to access with the . (dot) operator
# The difference being, a module is used once, ... | true |
b62110eca69bd06a29dac605b378d4a26e527f02 | 0x0584/cp | /nizar-and-grades.py | 724 | 4.125 | 4 | # File: nizar-and-grades.py
# Author: Anas
#
# Created: <2019-07-10 Wed 09:08:32>
# Updated: <2019-07-11 Thu 22:01:51>
#
# Thoughts: I was wrong! the idea is to give a count of how many grades
# are between min and max
#
# D. #247588
def find_best(grades):
unique = list(set(sort... | true |
44dd93465f283d91d89d3a02b12a0c9dae91bb9f | irrlicht-anders/learning_python | /number_posneg.py | 419 | 4.5625 | 5 | # Program checks wether the number is negative
# or not and displays an approbiate message
# ------------------------------------------------
# added additional line whicht checks wether the
# input is zero OR negative
num = input("Please enter a postive or negative number! ")
a = int(num) #convert from string to int
... | true |
a4ca15cb046c26c2c539eadf741c63aa44eb43c8 | rubenhortas/shows_manager | /application/utils/time_handler.py | 647 | 4.375 | 4 | def print_time(seconds):
"""
__print_time(num_secs)
Prints the time taken by the program to complete the moving task.
Arguments:
seconds: (int) Time taken by the program in seconds.s
"""
string_time = ""
hours = int(seconds / 3600)
if hours > 0:
seconds = seconds(3... | true |
aa72775b408ea78214f4e9f7f3e85c6bde6a397e | bobmitch/pythonrt | /polynomials.py | 1,095 | 4.125 | 4 | # Newton's method for polynomials
import copy
def poly_diff(poly):
""" Differentiate a polynomial. """
newlist = copy.deepcopy(poly)
for term in newlist:
term[0] *= term[1]
term[1] -= 1
return newlist
def poly_apply(poly, x):
""" Apply a ... | true |
c1c1cff04003b75dc832d56511c0b3a467ecc59d | kiransy015/PythonProjectFlipkart | /com/org/comp/Pgm45B.py | 719 | 4.25 | 4 | class circle:
pie = 3.142
def __init__(self,r):
self.radius = r
def area_of_circle(self):
area = circle.pie*self.radius*self.radius
print("Area of a circle is",area)
def circ_of_circle(self):
circ = 2*circle.pie*self.radius
print("Crc of circle is",circ)
d... | false |
1433cab8476daf733f6a9ce32e499302bae5ecdb | Md-Hiccup/python-DS | /Linked-List/delete.py | 1,216 | 4.15625 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
def printList(self):
... | false |
9f12127bc115ea0c20b9cfb26eac5bb26eda4a7b | Steveno95/Whiteboard-Pairing-Problems | /Balanced Binary Tree/balancedBinaryTree.py | 1,350 | 4.34375 | 4 | # write a function that checks to see if a given binary tree is perfectly balanced, meaning all leaf nodes are located at the same depth.
# Your function should return true if the tree is perfectly balanced and false otherwise.
def checkBalance(root):
# An empty tree is balanced by default
if root == None:
... | true |
b16d2082327d3845fdfe46955c71c4620e1f2711 | khushali19/Py-assign1 | /A6.py | 297 | 4.125 | 4 | list1 = []
list2 = []
list3 = []
for n in range(1,21):
list1.append(n)
print("Main list ",list1)
for i in list1:
if (i % 2 == 0):
list2.append(i)
else:
list3.append(i)
print("Even list ", list2)
print("Odd list ", list3)
| false |
5fab35331ecd4a0319d3391f4a90639b900b3894 | Jimam-Tamimi/Basic-Python-Programs | /rock_sizer_paper_game.py | 1,834 | 4.5 | 4 | import random
# print(randNo)
# For comp 1 is rock 2 is Scissor and 3 is paper
# The computer is choosing
randNo = random.randint(1,3)
if randNo == 1:
comp = 'rock'
elif randNo == 2:
comp = 'Scissor'
elif randNo == 3:
comp = 'paper'
# print(comp)
# Function for player
# 1 = rock 2 = Scissor, 3 = paper
def... | false |
85573993f237c888ad1f7e84e1a641c0ad7771d6 | aritse/practice | /Unique Paths II.py | 1,771 | 4.1875 | 4 | # A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
# The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
# Now consider if some obstacles are added to... | true |
2af620754b574963a8a7375553d0897e40c4827c | wenqianli150/hello-world | /palindrome.py | 753 | 4.1875 | 4 | """
Name: Wenqian Li
UWNetId: wli6
TimeComplexity = O(n)
"""
"""
Evaluates a given string and determines whether or not it is a palindrome.
:param the_string: The string to evaluate.
:returns: True when the string is a palindrome, False otherwise.
"""
def is_palindrome(the_string):
# Run... | true |
f7fd9c14a1461203b376746528c2a1b0b365d3b7 | souvikhaldar/Data-Structures-in-Python-and-Go | /recursion/printFromNto1.py | 603 | 4.28125 | 4 | # Write a recursive function to print all numbers from N to 1 for a given number N.
# tail recursion
def printN(N):
if N == 0:
return
print(N)
printN(N-1)
# Write a recursive function to print all numbers from 1 to N for a given number N.
#head recursion
def print_one_to_n(N):
if N == 0:
... | false |
77617485ca3d6b3e799c5b242fc7154673ef2691 | yuriyberezskyy/python-code-challege-loops | /code.py | 1,843 | 4.375 | 4 | # Create a function named exponents() that takes two lists as parameters named bases and powers. Return a new list containing every number in bases raised to every number in powers.
# For example, consider th
# Write your function here
def exponents(lst1, lst2):
new_list = []
for num1 in lst1:
for nu... | true |
05af06eabaf6395710df33a673938041e0e99ec3 | Piinks/CSI_Python | /Exercises/Exercise17.py | 1,399 | 4.1875 | 4 | # Exercise 17
# Kate Archer
# Program Description: This program reads a file name and the fileâs contents
# and determines the following:
# 1) The number of alphabetic (upper and lower case) letters in the file
# 2) The number of digits in the file
# 3) The number of lines in the file
# CSCI 1170-08
# Novembe... | true |
407e1805d35d802fc9c319f454a215848c2a8731 | Rokiis/Chat-Bot | /login_system.py | 2,228 | 4.25 | 4 | usernames = ['teacher','mentor','tutor','technican'] #storing usernames that (in theory) only uni staff has access to
passwords = ['SecurePassword','password123','safepass','12345'] #storing passwords that (in theory) only uni staff has access to
status = "" #set status to nill
def login_menu(): #login function th... | true |
996be87ec1c34eafac76dd401dc6248b15b7d847 | PrashantRBhargude/Python | /Dictionary.py | 1,842 | 4.21875 | 4 | #Dictionary allows us to work with key value pairs similar to hash maps in other prog languages
#The values in the dictionary can be of any datatype
Lead_Details={'Name':'Nikunj','Role':'ETL','Associates':['Prashant','Dixita']}
print(Lead_Details['Associates'])
#print(Lead_Details['Phone']) -- gives a key error
prin... | true |
189d2878517aca5a838d14c0d72ef2fd120fb605 | DJ-Watson/ICS3U-Unit3-01-Python | /adding.py | 429 | 4.15625 | 4 | #!/usr/bin/env python3
# Created by: DJ Watson
# Created on: September 2019
# This program adds two numbers together
def main():
# input
number1 = int(input("type first number (integer): "))
number2 = int(input("type second number (integer): "))
# process
answer = number1 + number2
# output
... | true |
aab6031fc2c812af2a147e574c1e8e748fb38e6a | BazzaOomph/Templates | /python/fundamentals/01_beginner/01_print.py | 1,648 | 4.8125 | 5 | #A basic print statement, which will print out the text string "Hello, World!"
#The expected output to the console is "Hello, World!" and includes a New Line character at the end
print("Hello, World!")
#Printing using two separate arguments
#The expected outcome is "Hello how are you?" with a new line character at the... | true |
a0a02a0b72762241bf5a5a32cb7e59e696529ccb | code-lighthouse/tests | /sushi_store.py | 587 | 4.125 | 4 | #! /usr/bin/env python
# Creating a list to hold the name of the itens
shopping = ['fugu', 'ramen', 'sake', 'shiitake mushrooms', 'soy sauce',
'wasabi']
# Creating a dictionary to hold the price of the itens
prices = {'fugu': 100.0, 'ramen': 5.0, 'sake': 45.0, 'shiitake mushrooms': 3.5,
'soy sauce': 7.50, ... | true |
3e8cf44f0c882fe70c5e83dc655108d109cc4b81 | ssgantayat/cleaning-data-in-python | /1-exploring-your-data/06-visualizing-multiple-variables-with-boxplots.py | 1,109 | 4.1875 | 4 | '''
Visualizing multiple variables with boxplots
Histograms are great ways of visualizing single variables. To visualize multiple variables,
boxplots are useful, especially when one of the variables is categorical.
In this exercise, your job is to use a boxplot to compare the 'initial_cost' across the
differen... | true |
9c0e414567cb96f9942edbfbbb6688fd8b28185a | arnabs542/DS-AlgoPrac | /twoPointers/countSubarrays.py | 1,344 | 4.1875 | 4 | """Count Subarrays
Problem Description
Misha likes finding all Subarrays of an Array. Now she gives you an array A of N elements and told you to find the number of subarrays of A, that have unique elements. Since the number of subarrays could be large, return value % 109 +7.
Problem Constraints
1 <= N <= 105 1 <= A[... | true |
d6c0ce60d39c532224a44cf1c423bffe359f5f44 | eriktja/SEogT-oblig | /Leap_year/project/leap_year/main.py | 270 | 4.40625 | 4 | from is_leap_year import *
print("This program will tell if you if a year is a leap year")
year = int(input("Enter the year do you want to check: "))
if is_leap_year(year):
print(str(year) + " is a leap year")
else:
print(str(year) + " is not a leap year")
| true |
70d71ef0d03cf708ec70da31211d8664833bffa2 | hbreauxv/shared_projects | /simple_tests/whatsTheWord.py | 201 | 4.21875 | 4 | while True:
word = input('Whats the word?')
word = word.lower()
if word != ('the bird'):
continue
else:
print('The Bird Bird Bird, The Bird is the Word')
break
| true |
542f107e72693592bbf1e253b06627f682a9ba73 | MDCGP105-1718/portfolio-MichaelRDavis | /Python/Week 2/ex5.py | 709 | 4.125 | 4 | #Loop for number of bottles and print number of bottles
for n in range(99, -1, -1):
print("99 bottles of beer on the wall, 99 bottles of beer.")
print(f"Take one down, pass it around, {n} bottles of beer on the wall…\n")
#If number bottles equal to 1 print this message
if(n == 1):
print("1 bottl... | true |
e83794970b07265039880ed2d45869872ec25a7d | lbrindze/excercises | /ex6.py | 1,691 | 4.1875 | 4 | import math
#ex 6.1
def compare(x,y):
if x > y:
return 1
elif x == y:
return 0
else:
return -1
#test functions
print(compare(4,6))
print(compare(6,6))
print(compare(4,3))
#ex 6.2 (this is an exercise in incremental development. what you see is the final product)
def hypotenuse... | false |
7a1d06f477560144059bcb1211c1eb5b02e31555 | lbrindze/excercises | /ex5.py | 1,027 | 4.1875 | 4 | from math import *
#ex 3
print('a?\n')
a = int(userInput)
except ValueError:
print("That's not an int!")
print('b?\n')
b = int(userInput)
except ValueError:
print("That's not an int!")
print('c?\n')
c = int(userInput)
except ValueError:
print("That's not an int!")
print('n?\n')
n = int(userInp... | false |
b1d2f5b4d2e58d8cfe800602766b217ddf4be757 | johnerick-py/PythonExercicios | /ex018.py | 474 | 4.15625 | 4 | # faça um programa que leia um angulo qualquer e mostre na tela o valor do seno,cosseno,tangente desse angulo
import math
angulo = float(input('Digite o angulo:'))
seno = math.sin(math.radians(angulo))
cos = math.cos(math.radians(angulo))
tan = math.tan(math.radians(angulo))
print('O angulo {} tem o SENO de {:.2f}'.fo... | false |
328a3dcb5ac2524b33cd18f8a5c7b60db4e12e2b | AhmedEissa30/SIC202 | /Python week/Day 2/Checker.py | 1,777 | 4.3125 | 4 | def displayInstruction(): #display function to show the user instructions
print("\nChoose your operation: ")
print("Press (8) to check Palindrome. Press (1) to check if the number PRIME. \n")
print(" Press (0) to EXIT... :(")
return True
def prim... | true |
da923a5f7797d953aee3209f9da071d1b387f529 | effyhuihui/leetcode | /sort/merge_two_sorted_array.py | 2,333 | 4.28125 | 4 | # -*- coding: utf-8 -*-
def merge(A, m, B, n):
'''
Given two sorted integer arrays A and B, merge B into A as one sorted array.
Note:
You may assume that A has enough space (size that is greater or equal to m + n)
to hold additional elements from B. The number of elements initialized in A and
B are m and n res... | false |
58b9f2c8704396d6302bfcb8223e034781a104fb | effyhuihui/leetcode | /uncategoried/rotateArray.py | 2,407 | 4.25 | 4 | __author__ = 'effy'
#-*- coding: utf-8 -*-
'''
Rotate an array of n elements to the right by k steps.
For example, with n = 7 and k = 3,
the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].
Note:
Try to come up as many solutions as you can,
there are at least 3 different ways to solve this problem.
hint: 看起来好多ro... | true |
6e754d747744f574a26e56f861e828e2f49602e6 | GoYMS/localhost_python | /爬虫/案例/v20.py | 969 | 4.1875 | 4 | """
python中正则模块是re
使用大致步骤 ;
1.compile函数将正则表达式的字符串变为一个Pattern对象
2.通过Pattern对象的一些列方法对文本进行匹配,匹配结果是一个Match对象
3.用Match对象的方法,对结果进行模拟
"""
import re
#\d表示数字,后边+表示这个数字可以出现一次或者多次
#r表示后边的是原生字符串,后边不需要转义
s=r"\d+"
#返回Pattern对象
pattern = re.compile(s)
m = pattern.match("one123two13213")
#默认匹配从头部开始,返回... | false |
162f59fb97253adce1ff39b40fa641ddd1cfcf24 | jcbrockschmidt/project_euler | /p010/solution.py | 697 | 4.125 | 4 | #!/usr/bin/env python3
from time import time
def sum_primes_below(n):
""" Calculates the sum of all primes below `n`. """
primes = [2, 3]
num = primes[-1] + 2
while num < n:
is_prime = True
limit = int(num**0.5)
for p in primes:
if p > limit:
break
... | true |
132ed1d71d5f8406474b25de8de3f55dad2def45 | tebannz/pruebadedesarrollopy | /Prueba.py | 2,834 | 4.15625 | 4 | # Deberán crear un programa, el cual deberá recibir un parámetro n ingresado por el usuario, y mostrar los primeros n pares.
def obtenerNumero():
return int(input("Ingrese un número: "));
# Ahora deberán crear el programa, donde no se considere el cero. Si , la salida del programa deberá ser:
def mostrarP... | false |
c289fec7d585d06c696bd94d9c0b8590cfa30110 | ibbocus/oop_polymorphism | /polymorphism.py | 839 | 4.65625 | 5 | """
This is the parent/base/super class
"""
class Planet:
def __init__(self, mass, spin, magnetic_field):
self.mass = mass
self.spin = spin
self.magnetic_field = magnetic_field
# this is a subclass of planets, which includes the parent class attributes as well as attributes specific to th... | true |
3d658085a747514cdadebcbf57479e6a57901d81 | SperZ/PythonFirstPractice | /array.py | 372 | 4.25 | 4 | arr1 = [1,2,3,4,5]
arr2 = [4,5,6,7,8]
# combines to arrays together to create one array with all elements of both arrays
arr3 = arr1 + arr2;
print(arr3);
#
arr_repeat = [];
arr_repeat.append("eat");
arr_repeat.append("sleep");
arr_repeat.append("repeat");
arr_repeat.pop();# removes the item from the array/list at... | true |
d9e075e78cf95649c0a1b2fc7df2febff46b2e2b | grayey/hackerrank-playful-py | /recursion.py | 520 | 4.21875 | 4 | #!/bin/python3
"""
Task
Write a factorial function that takes a positive integer, N as a parameter and prints the result of N!(N factorial).
"""
import math
import os
import random
import re
import sys
# Complete the factorial function below.
def factorial(n):
new_n = n-1;
return 1 if new_n == 0 else n * fa... | true |
5012f094648baf39d78856f1ce9906c1e45d9f8e | wmontanaro/AdventOfCode2017 | /day3.py | 2,436 | 4.34375 | 4 | def is_down(k):
n = 0
while ((2*n + 1)**2 - n) < k:
n += 1
if (2*n + 1)**2 - n == k:
return n
return False
def is_right(k):
n = 0
while ((2*n - 1)**2 + n) < k:
n += 1
if (2*n - 1)**2 + n == k:
return n
return False
def is_left(k):
n = 0
while ((2... | false |
592648f17627d10b2154f94c3dc20cc8136722d9 | Nick2253/project-euler | /Python/euler007/euler007.py | 1,233 | 4.15625 | 4 | import math
def isPrime(num):
'''Determines if num is prime
input:
numList = list of ints
maxNum = int
output:
sumTotal = int sum of all multiples of numbers in numList less than maxNum
'''
isPrime = True
i = 2 #We don't care if num is divi... | true |
98796dc9365babd222ddd97216558daac34d7c9d | FlyingJ/kaggle-learn-python | /roulette_probabilites.py | 1,901 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 7 17:44:46 2019
@author: jason
"""
def conditional_roulette_probs(history):
"""Given a history of roulette spins (as list of integer values)
return a dictionary where the keys are numbers on the roulette wheel, and
the values are dictio... | true |
c353caa38ab6021b987657320054050a65a7e365 | Nobodylesszb/python_module | /Algorithms/itertools/itertools_accumulate.py | 427 | 4.34375 | 4 | #该accumulate()函数处理输入iterable,
# 将第n和第n + 1项传递给函数并生成返回值而不是任何一个输入。
# 用于组合这两个值的默认函数会将它们相加,
# 因此accumulate()可用于生成一系列数字输入的累积和
from itertools import *
print(list(accumulate(range(5))))
print(list(accumulate('abcde')))
"""
output:
[0, 1, 3, 6, 10]
['a', 'ab', 'abc', 'abcd', 'abcde']
""" | false |
a88ee14815298cea657eb0de403a77b6a3d2569a | Nobodylesszb/python_module | /Algorithms/itertools/itertools_product_repeat.py | 860 | 4.21875 | 4 | from itertools import *
#要计算序列与自身的乘积,请指定输入应重复的次数
def show(iterable):
for i, item in enumerate(iterable, 1):
print(item, end=' ')
if (i % 3) == 0:
print()
print()
print('Repeat 2:\n')
print(list(product(range(3), repeat=2)))
show(list(product(range(3), repeat=2)))
print('Repeat 3:... | false |
b934a8fa0d994cc3ae00ab2fe7a8e7d867db7dd8 | zayzayzayzay/Introduction_python | /Comrehension_part2.py | 757 | 4.28125 | 4 | #Dictionary comprehension
word = "letters"
letter_count = {letter: word.count(letter) for letter in word}
print(letter_count)
letter_counts = {letter: word.count(letter) for letter in set(word)}
print(letter_counts)
#Set Comprehensions
a_set = {number for number in range(1,6) if number % 3 == 1}
print(a_set)
#generator... | true |
b6d148a52d674bad4b4561b26d26deaebd5d9e9b | zayzayzayzay/Introduction_python | /class2.py | 1,829 | 4.125 | 4 | #name mangling for privacy
class Duck(): #class definition
def __init__(self,input_name): #constructor
self.__name = input_name
@property #getter
def name(self):
print('inside the getter')
return self.__name
@name.setter #setter
def name(self,input_name):
print('inside the setter')
self.__name = input_na... | false |
c6e9e1f1724312e6ec7213807ae5533a78a3da8a | cs-fullstack-2019-fall/python-classobject-b-cw-marcus110379 | /cw.py | 2,534 | 4.125 | 4 | def main():
problem1()
problem2()
problem3()
# Create a class Dog. Make sure it has the attributes name, breed, color, gender. Create a function that will print all attributes of the class. Create an object of Dog in your problem1 function and print all of it's attributes.
class Dog:
def __init__(self,... | true |
9a60a94ac5ddd89bf5aab0c03d5a5bada2d0dc8f | Rastwoz/python101 | /3. Data Structures/Challenges and Solutions/Dictionaries/homework2.py | 921 | 4.53125 | 5 |
#create dictionary with Hello in each language
translator = {"French":"Bonjour",
"Spanish":"Hola",
"Italian":"Ciao",
"German": "Guten Tag",
"Indian": "Namaste"
}
#if user enters a language in dictionary, translate the word. Otherwise, let ... | true |
5bb5f7ed6d3aa6f4cbf0d311543506363dc6f589 | yoontrue/Python_work | /python_day03/day03ex102_class.py | 784 | 4.125 | 4 | # 앞에서 사용한 딕셔너리 구조를 class로 변경
# 클래스 선언은 class 키워드를 이용한다.
'''
class 클래스명(상속) :
생성자메소드
멤버메소드
멤버필드
'''
class People:
# 생성자 메소드 선언, 생성자와 멤버메소드는 self 매개변수가 선언 되어야한다.
def __init__(self, name):
self.name = name
def setName(self, name):
self.name = name
def getName(self):
... | false |
0df5dc3aeeb90af857f68060156591461bbdb2eb | hugoreyes83/scripts | /fibonacci.py | 268 | 4.28125 | 4 | def fibonacci(n):
'''function returns fibonacci sequence up to provided number'''
fibonacci_list = [0,1,1]
for i in range(3,n+1):
fibonacci_list.insert(i,fibonacci_list[i-1]+fibonacci_list[i-2])
return fibonacci_list[n-1]
print(fibonacci(10))
| false |
8905adda00560a3cf143b8faba96d4f17b4429af | priestd09/project_euler | /e_16.py | 497 | 4.125 | 4 | #!/usr/bin/env python
"""
##---
# jlengrand
#Created on : Fri Jan 13 15:24:59 CET 2012
#
# DESCRIPTION : Solves problem 16 of Project Euler
2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
What is the sum of the digits of the number 2^1000?
##---
"""
def sum_power_2(value):
"""
Returns... | true |
d0a181c79d71fa82a8fdc193768ebc54ace30937 | priestd09/project_euler | /e_4.py | 979 | 4.25 | 4 | #!/usr/bin/env python
"""
#---
Julien Lengrand-Lambert
Created on : Wed Jan 11 14:42:54 CET 2012
DESCRIPTION : Solves problem 4 of Project Euler
A palindromic number reads the same both ways. The largest palindrome made
from the product of two 2-digit numbers is 9009 = 91 99.
Find the largest palindrome made ... | true |
38f49214e119612b127236bd230f2b11bba088ee | priestd09/project_euler | /e_6.py | 924 | 4.125 | 4 | #!/usr/bin/env python
"""
#---
Julien Lengrand-Lambert
Created on : Wed Jan 11 14:42:54 CET 2012
DESCRIPTION : Solves problem 6 of Project Euler
Find the difference between the sum of the squares of the first one hundred
natural numbers and the square of the sum.
#---
"""
def diff_sum_squares(value):
"""
... | true |
75bbb63e6278cca0465f5ff4b1d7aebc10ce77ee | ChenlingJ/cj | /hackerrank/lists.py | 1,663 | 4.125 | 4 | # Consider a list (list = []). You can perform the following commands:
#
# insert i e: Insert integer e at position i.
# print: Print the list.
# remove e: Delete the first occurrence of integer e.
# append e: Insert integer e at the end of the list.
# sort: Sort the list.
# pop: Pop the last element from the list.
# r... | true |
6c82dd1a17cb90a870d009e5ea8ac40772dafcf0 | GeekGoutham/Python-Interactive-Challenges | /Unique_String.py | 1,122 | 4.15625 | 4 | #Author = Vignesh Goutham
def check_unique_dict(string_input): #Implmented using dict -- Poor performance as you need to check if there is more than one entry
char_dict = {} #Still O(n) but dict takes more space then list
for character in string_input:
if ch... | true |
25bf8924786bb17333d9425a722c74755e8c5768 | GeekGoutham/Python-Interactive-Challenges | /String_reverse_inplace.py | 1,306 | 4.28125 | 4 | #Author = Vignesh Goutham
def string_reverse(charlist):
if charlist == None: #strings are immutable in python, we cant do a strict in-place string reverse
print("No character array sent") #In-place algo = where the input is changed to output and a new memory/variable for o/p i... | true |
943e612b6887ec0ad85c23fd2a2c7f4383b8c29a | napte/python-learn | /08_list_for_each.py | 578 | 4.1875 | 4 | def main():
a = [1, 2, 3]
print 'List a = ' + str(a)
print 'Doing for-each loop and printing numbers and their squares\n'
for num in a:
print '\n------\n'
print 'num = ' + str(num)
print str(num) + '^2 = ' + str(num**2)
print '\n------\n'
a = [1, 2, 3, 4, 5, 6, 7, 8]
even = []
print 'List a... | true |
030fee26786b2675ffa42a974a308af70cacc2c8 | minji-o-j/Python | /대학원 파이썬 수업/수업/1027/city.py | 272 | 4.15625 | 4 | city = ['DC','NY','Seoul', 'Tokyo','Paris']
print("what is the capital of S.Korea?")
for i in range(len(city)):
print('{}. {}'.format(i+1,city[i]))
answer = int(input('choose an answer: '))
if answer == 3:
print('correct')
else:
print('incorrect')
| false |
ec6cd149c7835a225125b541c44d6e33d1e69765 | richardcinca/CursuriPY | /ex4.py | 573 | 4.28125 | 4 | iterator=0
reversed_word=""
word = input("Insert word: ")
print("Your word is '{}'".format(word))
length=len(word)
print("The length of the word is {} letters".format(length))
for var in word:
#print("Var is {}".format(var))
#print(word[iterator])
#iterator+=1
#reversed_word=var+reversed_word
#pri... | true |
63f722f1667e843eb0a0d42e2030b215fe65913f | jayadams011/KalPython | /bmi claculator.py | 464 | 4.21875 | 4 | weight = eval(input("Enter weight in pounds: "))
height = eval(input("enter height in inches: "))
KILOGRAMS_PER_POUND = 0.45359237
METERS_PER_INCH = 0.0254
weightInKg = weight * KILOGRAMS_PER_POUND
heightInMt = height * METERS_PER_INCH
bmi = weightInKg / (heightInMt ** 2)
print ("BMI is" , format(bmi, ".2f"))
if b... | false |
72d3ee8cb18777b39a4d19f8c9ff1338b121681f | jayadams011/KalPython | /2_4_poundsToKilograms.py | 628 | 4.1875 | 4 | """
(Convert pounds into kilograms) Write a program that converts pounds into kilograms. The program
prompts the user to enter a value in pounds, converts it to kilograms, and displays the result. One
pound is 0.454 kilograms. Here is a sample run:
Enter a value in pounds: 55.5
55.5 pounds is 25.197 kilograms
"""
#user... | true |
e4bf2decd4a1b5c8c246d5a50908abbd9e7b9f89 | stevenb92/PythonShizzle | /numchar.py | 310 | 4.34375 | 4 | #Prompts for an input string and then returns the input string
#along with the number of charcters in the string
inputString = ""
length = 0
while length == 0:
print ("Enter an input string:")
inputString = str(input())
length = len(inputString)
print ("{} has {} characters".format(inputString,length)) | true |
3864a6a4ed3038f46d45dd19ab2b41a930b2a8fd | JoshOrndorff/LearnPythonByExample | /Unit6-2DLists/lesson2-WheresWaldo.py | 1,737 | 4.21875 | 4 | # Let's make a 2D list that contains a bunch of people. Since all these strings
# are different lengths it would be easy for this table to look messy. Using
# white space effectively can help the data look more organized.
people = [["Jack", "Abagail", "Waleed" ],
["Rebeca", "Obi", "Orndorff"],
... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.