blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
2c6339f7d99d3cce98ea92d7bd71a80ff6d0efd9 | Sahale/algo_and_structures_python | /Lesson_2/2.py | 1,370 | 4.15625 | 4 | """
2. Посчитать четные и нечетные цифры введенного натурального числа.
Например, если введено число 34560, то у него 3 четные цифры
(4, 6 и 0) и 2 нечетные (3 и 5).
"""
# Отсутствует обработка для случая, если пользователь ввел не число
def cycle():
while True:
a = str(input('Введите число: '))
e... | false |
081d354575e425e7e2a8f9f32d6729df27b3ca88 | Cyansnail/Backup | /PythonLists.py | 1,378 | 4.28125 | 4 | # how to make a list
favMovies = ["Star Wars", "Avengers", "LOTR"]
# prints the whole list
print(favMovies)
#prints only one of the items
print(favMovies[1])
# to add you can append or insert
# append adds to the end
favMovies.append("Iron Man 1")
print(favMovies)
# insert will put the item wherevre you want
... | true |
b0a55be05b1fc2e33561b8e676a8e3bd8916e489 | Munster2020/HDIP_CSDA | /labs/Topic04-flow/lab04.05-topthree.py | 687 | 4.1875 | 4 | # This program generates 10 random numbers.
# prints them out, then
# prints out the top 3
# I will use a list to store and
# manipulate the number
import random
# I programming the general case
howMany = 10
topHowMany = 3
rangeFrom = 0
rangeto = 100
numbers = []
for i in range(0,10):
numbers.append(random.randi... | true |
a1a02e09b242546b8003baf6caff98e293370a50 | makthrow/6.00x | /ProblemSet3/ps3_newton.py | 2,692 | 4.34375 | 4 | # 6.00x Problem Set 3
#
# Successive Approximation: Newton's Method
#
# Problem 1: Polynomials
def evaluatePoly(poly, x):
'''
Computes the value of a polynomial function at given value x. Returns that
value as a float.
poly: list of numbers, length > 0
x: number
returns: float
'''
in... | true |
b39ca0c3cfb9a13ef5b02d0b8f705e89e9b4971f | makthrow/6.00x | /ProblemSet2/PS2-2.py | 1,165 | 4.21875 | 4 | balance = 4773
annualInterestRate = 0.2
# result code should generate: Lowest Payment: 360
# Variables:
# balance - the outstanding balance on the credit card
# annualInterestRate - annual interest rate as a decimal
# The monthly payment must be a multiple of $10 and is the same for all months
# TODO: CALCULATE MONT... | true |
f2a6bda380939c9e4514a736633121a5270a9a44 | AnthonyArg1/mc-AntonioArguello | /Taller 7/programaA.py | 1,540 | 4.125 | 4 | import math
# Se pide x en: e^-x
valor = int(input('Digite x en e^-x: '))
# Definiciones
error_esperado = ((0.5 * math.pow(10, -7)) * 100)
error_relativo = 100
iteraciones = 0
potencia = 0
x = 0
y = 0
# Bucle infinito
while True:
# Mientras el error esperado sea menor que el error relativo
if(error_esperad... | false |
ca3e671fd66ef9063da94334696dd8b11ebab69a | yueyueyang/inf1340_2015_asst2 | /exercise1.py | 1,481 | 4.125 | 4 | vowels = "aeiou"
def pig_latinify(word):
"""
Main translator function.
:param : string from function call
:return: word in pig latin
:raises:
"""
# convert string to all lowercase
word = word.lower()
# if string has numbers -> error
if not word.isalpha():
result = "Pl... | true |
02272ce4fee1b49d2c7d137bf7d930a18d3b6394 | key36ra/m_python | /log/0723_PickleSqlite3/note_sqlite3.py | 2,033 | 4.125 | 4 | import sqlite3
"""
Overview
"""
# Create "connection" obect.
conn = sqlite3.connect('example.db')
# Create "cursor" onject from "connection" object.
c = conn.cursor()
# Create table
c.execute('''CREATE TABLE stocks
(date text, trans text, symbol text, qty real, price real)''')
# Insert a row of data
c... | true |
f5f3cdd35da4181147b35d2ba1f300117a04978c | key36ra/m_python | /seireki-gengou.py | 935 | 4.125 | 4 | #!/usr/bin/env python3
"""
We post our birthday.
And this code translate the year to the gengou,
for example "heisei", "shouwa" and so on.
"""
from datetime import datetime
now = datetime.now()
print("あなたの生まれ年(西暦)を元号に変換します")
# python3では、input()はstr型になっている(python2はint型)
year = int(input("生まれ年:"))
print()
if year ... | false |
8bc413580dd92b6ab78befe3ec6cc045b6698cd4 | GMcghn/42---Python-Bootcamp-Week1 | /day01/ex01/game.py | 1,498 | 4.25 | 4 | class GotCharacter:
# https://www.w3schools.com/python/python_inheritance.asp
def __init__(self, first_name, is_alive = True):
#properties (ne doivent pas forcément être en attributes)
self.first_name = first_name
self.is_alive = is_alive
# Inheritance allows us to define a class that inhe... | true |
7cc8e38f5fcd767d522c5289fc2f9e60ecb00e71 | Sepp1324/Python---Course | /tut010.py | 595 | 4.53125 | 5 | #!/usr/bin/env python3
# strip() -> Removes Spacings at the beginning and the end of a string
# len() -> Returns the length of a String (w/0 \n)
# lower() -> Returns the string with all lowercase-letters
# upper() -> Returns the string with all uppercase-letters
# split() -> Split a string into a list where each wor... | true |
4a9bdc08f081dee7c1e469e016eaba575cece2f8 | kalpanayadav/shweta | /shweta1.py | 776 | 4.3125 | 4 | def arearectangle(length,breadth):
'''
objective: to calculate the area of rectangle
input:
length and breadth of rectangle
'''
# approach: multiply length and breadth
area = length*breadth
return area
def areasquare(side):
'''
objective: to calculate the area of square
... | true |
0f6fc453225f9495703a7e4118e2e2d3b146860b | MnAkash/Python-programming-exercises | /My solutions/Q21.py | 1,248 | 4.59375 | 5 | '''
A robot moves in a plane starting from the origin point (0,0). The robot can move toward UP, DOWN, LEFT and RIGHT with a given steps.
The trace of robot movement is shown as the following:
UP 5
DOWN 3
LEFT 3
RIGHT 2
The numbers after the direction are steps.
Please write a program to compute the distance fr... | true |
79fc392902b97b50a7506f7e83441e1f04dc53e9 | timeispreciousFeng/pythonForTest | /test20180716-Function/test4-parameter.py | 2,313 | 4.4375 | 4 | # -*- coding: UTF-8 -*-
# 参数
# 以下是调用函数时可使用的正式参数类型:
#
# 必备参数
# 关键字参数
# 默认参数
# 不定长参数
#=====================================================================#
# 必备参数
# 必备参数须以正确的顺序传入函数。调用时的数量必须和声明时的一样。
#可写函数说明
def printme( str ):
"打印任何传入的字符串"
print(str);
return;
#调用printme函数
# printme();
printme("11");
#===... | false |
4074246e3cb5b70bd035663133ce58f9a68a69b8 | KaptejnSzyma/pythonexercises | /ifChallenge/ifChallenge.py | 233 | 4.1875 | 4 | name = input("Please enter your name: ")
age = int(input("Enter your age: "))
if 18 <= age < 31:
# if age <= 18 or age > 31:
print("Welcome to holiday, {}".format(name))
else:
print("Kindly, fuck off {}".format(name))
| true |
99f672c74e220a309801e670abfed73990a36d9a | mepragati/100_days_of_Python | /Day 019/TurtleRace.py | 1,229 | 4.34375 | 4 | from turtle import Turtle, Screen
import random
is_race_on = False
all_turtles = []
screen = Screen()
screen.setup(width=500,height=400)
color_list = ["red","green","blue","yellow","orange","purple"]
y_position = [-70,-40,-10,20,50,80]
user_input = screen.textinput("Enter here: ","Who do you think will win the race ou... | true |
4d3abca3e150456c322d7ea7b2dd276ea5f98d37 | hyqinloveslife/javabasetest | /PythonDemo/com/test.py | 427 | 4.125 | 4 | # -*- coding: UTF-8 -*-
'''
Created on 2017年12月7日
@author: 黄叶钦
'''
##循环 将奇数和偶数分开 感觉Python语言好傻,语法太不符合规范了
numbers_ = [12,37,8,65,25]
even =[]
odd = []
while len(numbers_)>0:
element__ = numbers_.pop()
if(element__%2==0):
even.append(element__)
else:
odd.append(element__)
... | false |
b218e1c5be5716b1b0e645018e64ea2f76a4e593 | SeyyedMahdiHP/WhiteHatPython | /python_note.py | 1,361 | 4.21875 | 4 | #PYTHON note
##########################List Slicing: list[start:end:step]######################################
user_args = sys.argv[1:] #sys.argv[1],sys.argv[2],....
#note that sys.argv is a collection or list of stringsT and then with above operation , user_args will be too
user_args = sys.argv[2:4]#sys.a... | true |
77c2de7efe762112bd76127282348f28fa9235f0 | Nishanky/Know-Your-Age | /main.py | 1,236 | 4.28125 | 4 | thisyear = 2021
name = input("Hey there! Please Enter your name..")
if name.isnumeric():
print("You entered some numbers instead of your name!!")
exit()
age = 0
try:
age = int(input(f"Hello {name}:)\nEnter your age or year of birth:"))
except ValueError:
print("Enter a numeric value..")
exit()
... | false |
74f6bb45f38a8351d3a5b918ca3e571bfaec6441 | Vlad-Yekat/py-scripts | /sort/sort_stack.py | 454 | 4.15625 | 4 | # sort stack recursively using only push, pop and isepmpty
def insert(element, stack):
if len(stack) != 0 and element > stack[-1]:
top = stack.pop()
insert(element, stack)
stack.append(top)
else:
stack.append(element)
def stack_sort(stack):
if len(stack) != 0:
top... | true |
cfca498a6f0f3f73f698ba67ea6589fac8f7d29d | Nithi07/hello_world | /sum_of_lists.py | 335 | 4.375 | 4 | """1.(2) Write a python program to find the sum of all numbers in a list"""
def sum_list(numbers):
a = range(numbers)
c = []
for _ in a:
b = int(input('enter your number: '))
c.append(b)
return sum(c)
message = int(input('how many numbers you calculate: '))
print(sum... | true |
809e901bd59261096a299234c7fc7e45d996f5c1 | Nithi07/hello_world | /sum&avg.py | 336 | 4.15625 | 4 | """ 8. (3)Given a string, return the sum and average of the digits that appear in the string,
ignoring all other characters
"""
message = input('Enter: ')
a = []
for i in message:
if i.isdigit():
a.append(int(i))
tot = sum(a)
ave = tot / len(a)
print(f'sum of digit: {tot}\n average of digits: {av... | true |
eb7d3ce1447378e96790b98903528afc3a2efc5f | Nithi07/hello_world | /div3and5.py | 437 | 4.25 | 4 | """
Write a function that returns the sum of multiples of 3 and 5 between 0 and limit (parameter).
For example, if limit is 20, it should return the sum of 3, 5, 6, 9, 10, 12, 15, 18, 20.
"""
def sum (limit):
i = limit + 1
x = range(0, i)
res = []
for num in x:
if num % 3 == 0 or num ... | true |
70a74f5c8a7603f20958dea54051eb4b842168a3 | emellars/euler-sol | /019.py | 1,672 | 4.40625 | 4 | #Runtime ~0.07s.
#Determines if the year "n" is a leap year.
def is_leap_year(n):
if n % 400 == 0: return True
elif n % 100 == 0: return False
elif n % 4 == 0: return True
else: return False
#Determines if a month started with Sunday.
def month_starting_sunday(days):
if days % 7 == 2: r... | true |
f9398e1f459c0713816924539bd642ba9d206a76 | sry19/python5001 | /hw06/turtle_draw.py | 2,003 | 4.8125 | 5 | # Author: Ruoyun Sun
# The program uses the star's segment to draw a star and a circle around the
# star
import turtle
import math
TRIANGLE_DEGREE = 180
TAN_18_DEGREE = 0.325
STAR_SEG = 500
COS_18_DEGREE = 0.951
STAR_DEGREE = 36
STAR_SIDE = 5
CIRCLE_ANGLE = 360
def main():
'''give the star's segment, draw a sta... | true |
9d162e4b60638bc81f79889ad5adc8d223fc8f1c | STJRush/handycode | /Python Basics Loops, Lists, Logic, Quiz etc/time&date/timesDates.py | 794 | 4.25 | 4 | from time import sleep
from datetime import datetime
now = datetime.now()
print("The full datetime object from the computer is", now)
print("\n We don't want all that, so we can just pick out parts of the object using strftime. \n")
# It's not necessary to list all of these in your own program, think of this a s... | true |
0b569dc264fb884868bd7d98ebe2ade16b153c1e | STJRush/handycode | /ALT2 Analytics and Graphing/Live Web Data/openWeatherMapperino.py | 2,512 | 4.125 | 4 | # Python program to find current
# weather details of any city
# using openweathermap api
# 0K = 273.15 °C
# import required modules
import requests, json
# Enter your API key here. Uf you're using this in a progect, you should sign up and get your OWN API key. This one is Kevin's.
api_key = "a19c355c905cbcb... | true |
b4f7d2810b41752a75c3c457e44a3af88972dc8b | STJRush/handycode | /Python Basics Loops, Lists, Logic, Quiz etc/runBetweenHoursOf.py | 810 | 4.4375 | 4 | # modified from https://stackoverflow.com/questions/20518122/python-working-out-if-time-now-is-between-two-times
import datetime
def is_hour_between(start, end):
# Get the time now
now = datetime.datetime.now().time()
print("The time now is", now)
# Format the datetime string to just be hour... | true |
76d7ff9b2e77cc3e3b0027c3d816339cd137002a | pparaska/pythonAssignments | /stringAssignment/stringOfMiddleThreeNumber.py | 514 | 4.40625 | 4 | def get_three_middle_characters(given_string):
print('given String is', given_string)
index_of_middle_character = int(len(given_string) / 2)
print(
f'index of middle character is : {index_of_middle_character} and middle character is {given_string[index_of_middle_character]}')
three_middle_charac... | false |
273f452623d2bc46108bcf359ab1d02b8d54ddac | TheMacte/Py | /lesson_2/task_5.py | 750 | 4.40625 | 4 | """
5. Вывести на экран коды и символы таблицы ASCII, начиная с символа под номером 32 и заканчивая 127-м включительно.
Вывод выполнить в табличной форме: по десять пар "код-символ" в каждой строке.
"""
def tbl(start, stop, cnt=10, string='') -> str:
if start == stop + 1:
return string
else:
... | false |
1b6c299cc1dfde6fb9049cba1af4b37494123774 | AyushGupta05/Coding-Lessons | /Python/string.py | 594 | 4.3125 | 4 | username=input("Please enter your name")
print("Hello",username,"welcome to this class")
print("Hello "+username+ " welcome to this class")
print(f"Hello {username},welcome to this class")
print ("Hello {},welcome to this class".format(username))
#Ways to put a print statement
age=input("Please enter your age")
print("... | true |
cd2f045291ce3ce1d0b9c1653752b989fb3a1860 | jordan-carson/Data_Structures_Algos | /HackerRank/staircase.py | 594 | 4.15625 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the staircase function below.
def staircase(n):
# get the number of the base
# calculate the number of blank spaces for the first row, (do we need an empty row)
# so if we are at 1 and n = 10 then we need to print 1 '#' whi... | true |
a6ee152b820fa607e090e0d5c44a8f8e854fb190 | jordan-carson/Data_Structures_Algos | /Udacity/1. Data Structures/0. Strings/anagram_checker.py | 1,085 | 4.28125 | 4 | # Code
def anagram_checker(str1, str2):
"""
Check if the input strings are anagrams of each other
Args:
str1(string),str2(string): Strings to be checked
Returns:
bool: Indicates whether strings are anagrams
"""
if len(str1) != len(str2):
# remove the spaces and lower the ... | true |
a5e5305b4997a6fa42444dc521c311506558fbfc | jordan-carson/Data_Structures_Algos | /HackerRank/30daysofcode/day3.py | 837 | 4.40625 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Given an integer, , perform the following conditional actions:
# If is odd, print Weird
# If is even and in the inclusive range of to , print Not Weird
# If is even and in the inclusive range of to , print Weird
# If is even and greater... | true |
7ee8d81ca6f796c8a6934e30ac80873de2d9034b | jordan-carson/Data_Structures_Algos | /Udacity/0. Introduction/Project 1/Task4.py | 1,575 | 4.21875 | 4 | """
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
TASK 4:
The telephone company want to i... | true |
7bf93a3bc135b7981e7d51910f7bbd78a745a0bf | jordan-carson/Data_Structures_Algos | /Coursera/1. AlgorithmicToolbox/week2_algorithmic_warmup/8_last_digit_of_the_sum_of_squares_of_fibonacci_numbers/fibonacci_sum_squares.py | 1,951 | 4.21875 | 4 | # Uses python3
from sys import stdin
import time
## a simple Fibonacci number genarator
def get_next_fib():
previous, current = 0, 1
yield previous
yield current
while True:
previous, current = current, previous + current
yield current
## find the Pisano sequence for any given number
#... | true |
6829e40eebf18276067138b8e59cb87c3a091073 | jordan-carson/Data_Structures_Algos | /Udacity/1. Data Structures/5. Recursion/staircase.py | 609 | 4.375 | 4 |
def staircase(n):
"""
Write a function that returns the number of steps you can climb a staircase that
has n steps.
You can climb in either 3 steps, 2 steps or 1 step.
Example:
n = 3
output = 4
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps +... | true |
fcd90e605a660a2a6190b8a28411c943adfc8ac5 | cleelee097/MIS3640 | /Session06/calc.py | 2,695 | 4.1875 | 4 | # age = input('please enter your age:')
# if int(age) >= 18:
# print('adult')
# elif int(age) >=6:
# print('teenager')
# else:
# print('kid')
# if x == y:
# print('x and y are equal')
# else:
# if x < y:
# print('x is less than y')
# else:
# print('x is greater than y')
... | true |
2f5d0a2673e142b6753b704659fef639b0b586d3 | JdeH/LightOn | /LightOn/prog/pong/pong4.py | 2,526 | 4.125 | 4 | class Attribute: # Attribute in the gaming sense of the word, rather than of an object
def __init__ (self, game):
self.game = game # Done in a central place now
self.game.attributes.append (self) # Insert each attribute into a list held by the game
# ============ Stan... | true |
e9be930cb5bf1cab43b288ccb2b68d0d8f1dd003 | felipeng/python-exercises | /12.py | 370 | 4.34375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Write a program that takes a list of numbers (for example, a = [5, 10, 15, 20, 25])
and makes a new list of only the first and last elements of the given list. For practice, write this code inside a function.
'''
a = [5, 10, 15, 20, 25]
def first_last(list):
retu... | true |
25c85e50548c1d465bdccb3e396f3c98b1f74c4c | felipeng/python-exercises | /11.py | 615 | 4.25 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
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 to Exercise 4 to help you.
Take this opportunity to practice using funct... | true |
d38a0334a8851b5e69809e73aef8cc758ea0e9a6 | harrytouche/project-euler | /023/main.py | 2,669 | 4.1875 | 4 | """
A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number.
A number n is called deficient if the sum of its proper divisors is less than n and it i... | true |
69c35b2065585d91bb59322b28d0664df638d254 | harrytouche/project-euler | /009/main.py | 733 | 4.21875 | 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.
a + b + c = 1000
a**2 + b**2 = c**2
"""
sum_number = 1000
complete = 0
loop_max ... | true |
6a9c0f0926fa39305376a3632ef442fb4062c2c3 | harrytouche/project-euler | /019/main.py | 933 | 4.25 | 4 | """
You are given the following information, but you may prefer to do some research for yourself.
1 Jan 1900 was a Monday.
Thirty days has September,
April, June and November.
All the rest have thirty-one,
Saving February alone,
Which has twenty-eight, rain or shine.
And on leap years, twenty-nine.
A leap year occurs ... | true |
7b42438ae5b38d28c48a7150b74fc91ad645a6b3 | vonzhou/py-learn | /byte-python/chapter8/func_param.py | 239 | 4.21875 | 4 |
def print_max(a,b):
if (a>b):
print a,'is bigger'
elif (a==b):
print a, 'is equal to ',b
else:
print b, 'is bigger'
print_max(34, 87)
print_max(34, 8)
print_max(87, 87)
x = 0
y = -3
print_max(x, y)
| false |
560cfe8aacfa94fe1c35a6b33a68b61648424f3b | k64pony/Module7 | /Module7.py | 1,016 | 4.21875 | 4 | #Assignment 1
import sys
import datetime
data = datetime.datetime.now()
print("The current datetime is: ")
print(data)
#Assignment 2
import sys
import datetime
from datetime import timedelta
dt = datetime.datetime.now()
addyears = datetime.timedelta(days=730)
minussecs = datetime.timedelta(seconds = 60)
date = dt+add... | false |
1d0985e745bd74bd9b5eced8947242e0629649e0 | NamanManocha/HeapApplications | /FindNumber.py | 687 | 4.125 | 4 | ''' O(m+n)-time algorithm to determine whether a given number is stored in a given m×n Young tableau. '''
def search(list_search,element):
for i in range(0,len(list_search)):
if list_search[i][0] == element:
return 1;
elif list_search[i][0] > element:
row = i-1
... | false |
e4eee2f6325eb055064b9f94c82eb278296e7c03 | Parnit-Kaur/Learning_Resources | /Basic Arithmetic/fibonacci.py | 237 | 4.28125 | 4 | print("Enter the number till you want fibonacci series")
n = int(input())
a = 1
b = 1
print("The fibonacci sequence will be")
print(a)
print(b)
for i in range(2, n):
fibonacci = a + b
b = a
a = fibonacci
print(fibonacci)
| true |
39dfeeb264d7dc50e7c7acd992e442b789dcf029 | bnewton125/MIT-OpenCourseWare | /6.0001/ps4/ps4a_edited.py | 2,539 | 4.1875 | 4 | # Problem Set 4A
# Name: <your name here>
# Collaborators:
# Time Spent: x:xx
def get_permutations(sequence):
'''
Enumerate all permutations of a given string
sequence (string): an arbitrary string to permute. Assume that it is a
non-empty string.
You MUST use recursion for this p... | true |
99b08d79c104a1995e201ff2cccae06b131a6ee6 | mareliefi/learning-python | /calendar.py | 1,977 | 4.40625 | 4 | # This is a calender keeping track of events and setting reminders for the user in an interactive way
from time import sleep,strftime
your_name = raw_input("Please enter your name: ")
calender = {}
def welcome():
print "Welcome " + your_name
print "Calender is opening"
print strftime("%A, %B, %d, %Y")
print str... | true |
23b21cec45b892ff56c982f21ec07b78d61b9c87 | borisBelloc/onlineChallenges_Algorithms_RecruitmentTests | /Algorithms/sort_on_the_fly.py | 305 | 4.1875 | 4 | # Sort on the fly
# we ask user 3 numbers and we sort them as they arrive
lst = []
while len(lst) < 3:
value = int(input("enter one number (sort on the fly) :\n"))
i = 0
while i < len(lst) and value > lst[i]:
i += 1
lst.insert(i, value)
print("here is the sorted array {}\n".format(lst))
| true |
95e140f15ce99d2d718b65cf751b14e7b3333684 | mattheuslima/Projetos-Curso_Python | /Aulas/Aula 17.py | 1,565 | 5.03125 | 5 | '''Lista
Listas são declaradas através de colchetes.
Diferente das tuplas, listas são mutáveis.
Existem 2 métodos para adicionar um elemento a uma lista:
".append": Com ele você adiciona um elemento sempre ao fim da lista. Ex.: lista.append('Carro')
".insert": Com ele você consegue especificar em que posição da li... | false |
5497cec2acba334140863086e3c590a621324b2d | mattheuslima/Projetos-Curso_Python | /Exercícios/Ex.37.py | 792 | 4.1875 | 4 | #Escreva um programa que leia um numero inteiro qualquer e peça para escolher qual será a base de conversão: binário,octal ou hexadecimal
#Header
print('{:=^38}'.format('Desafio 37'))
print('='*5,'Conversor de base numérica','='*5)
#Survey
num=int(input('Digite um número inteiro: '))
print('''Escolha uma das bases... | false |
93dc0a880bf9d61481d40f0e9f49e7e2e034d8d2 | cg342/iWriter | /start.py | 1,728 | 4.21875 | 4 | '''
https://hashedin.com/blog/how-to-convert-different-language-audio-to-text-using-python/
Step 1: Import speech_recognition as speechRecognition. #import library
Step 2: speechRecognition.Recognizer() # Initializing recognizer class in order to recognize the speech. We are using google speech recognition.
Step 3: ... | true |
f06d11254eda94677d3d723852e6b214222bd85a | BlissfulBlue/linux_cprogramming | /sample_population_deviation.py | 1,550 | 4.4375 | 4 | # Number values in the survey
survey = [10, 12, 6, 11, 8, 13]
# sorts numbers into ascending order and prints it out
survey.sort()
print(f"The order from lowest to highest: {survey}")
# assigns variable number of values in the list and prints
list_length = (len(survey))
print(f"There are {list_length} va... | true |
c443f35ec994c303b74cd3a8000f5a7ed751a027 | bhushan5890/My_new_repo | /My_new_repo/check_palindrome.py | 433 | 4.28125 | 4 | # Python code to check palindrome
def check_palindrome(ip_string):
ip_string = ip_string.replace(' ', '')
return ip_string == ip_string[::-1]
if __name__ == "__main__":
input_string = input("Enter the string to be validated-Case sensetive : ")
if check_palindrome(input_string) == True:
print... | false |
119af8834d42cf7fae4effba7fb229b0e42983c6 | Pratik-sys/code-and-learn | /Modules/sorted_random_list.py | 620 | 4.25 | 4 | #!/usr/bin/python3
# Get a sorted list of random integers with unique elements
# Given lower and upper limits, generate a sorted list of random numbers with unique elements, starting from start to end.
"""
Input: num:10, start:100, end:200
Output: [102, 118, 124, 131, 140, 148, 161, 166, 176, 180]
Input: num:5, star... | true |
b2d11e2223b46cce0f39978d561dd96bead9e03c | Pratik-sys/code-and-learn | /Modules/password_gen.py | 2,736 | 4.25 | 4 | #!/usr/bin/python3
# Write a password generator in Python.
# Be creative with how you generate passwords - strong passwords have a mix of lowercase letters, uppercase letters, numbers, and symbols.
# The passwords should be random, generating a new password every time the user asks for a new password.
"""
No test cas... | true |
7b6e3af7a399d49e8cc7979d658c3dfe7e4349cc | Pratik-sys/code-and-learn | /Recursion/Fibonacci/fibonacci_using_recursion.py | 535 | 4.15625 | 4 | #!/usr/bin/python3
# Write a function int fib(int n) that returns Fn. For example, if n = 0, then fib() should return 0. If n = 1, then it should return 1. For n > 1, it should return Fn-1 + Fn-2.
"""
Input: 9
Output : 34
"""
# Solution: Method 1 ( Use recursion )
def fib(n):
"""
This function returns the ... | true |
9cf37d2ecef5737c12ba23a5e6b99a0380c051ef | Pratik-sys/code-and-learn | /Dictionary/winner.py | 1,350 | 4.15625 | 4 | # Given an array of names of candidates in an election. A candidate name in array represents a vote casted to the candidate. Print the name of candidates received Max vote. If there is tie, print lexicographically smaller name.
# Check lexographically smaller/greater on wiki.
"""
Input : votes[] = {"john", "johnny", ... | true |
73830104de32918b17b0ed1061b60a1d10a186c0 | caronaka/ParadigmasIFTS2020 | /CLASE2/funcionlambda.py | 581 | 4.21875 | 4 | #LAMBDA
# son funciones matematicas y anonimas
# no le tenes que poner nombre
# o usarla sin nombrarla
#si la funcion la vas a usar mucho, conviene nombrarla con def
#
# no funciona con funciones muy largas
# hay que reducirlas a una linea de codigo
# si requiere mas, yo no podemos usar lambda
#
# SIMPLIFICANDO
def ... | false |
10f55cdc4a5acee3e1ece322810f64f1f30ecd25 | RealMirage/Portfolio | /Python/ProjectEuler/Problem1.py | 637 | 4.28125 | 4 | '''
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.
'''
# List comprehension method
def solve_with_lc():
numbers = range(1000)
answer = sum([x for x in numbers if x ... | true |
16e5b1ca44fb64f6c79bf8afeb956963ec6fa4a1 | Danish15/TalkPythonTraining | /apps/03_birthday/you_try/program.py | 1,022 | 4.34375 | 4 | import datetime
def print_header():
print('-----------------------')
print('BIRTHDAY APP')
print('-----------------------')
print()
def get_birthday_from_user():
print('Tell us when you were born: ')
year = int(input('Year [YYYY]: '))
month = int(input('Month [MM]: '))
day = int(input('Day [DD]: '))
birthda... | false |
c53a436856008c3a632339f8267823e990d7dcbe | syudaev/lesson01 | /lesson01_task01.py | 1,910 | 4.21875 | 4 | # переменные, запрос ввода чисел и строк, сохранение в переменные, вывод на экран,
# форматирование строки ( f, %, format() )
# функция проверки строковых переменных на ввод чисел, чтобы избежать ошибок при вводе
def chek_numeric(user_str):
if user_str.isdigit():
return 0
else:
try:
... | false |
7ec6facac795aff55fc277f331fe57fcaf63d312 | juliusortiz/PythonTuts | /ListAndTuplesTutorial.py | 1,405 | 4.28125 | 4 | # #+INDEX - 0 1 2
# courses = ["BSIT","BSCS","BLIS","BA","ACS","BSCS","BSIT"]
#
# #Range selection
# print(courses[1:5])
#
# #Changing index value
# courses[0] = "Accountancy"
# print(courses)
#
# #Printing the length of the list
# print(len(courses))
#
# #Printing the number of duplicates from the list
#... | true |
42fd81d68d74a7e10e1b86ceec1f28395faad54f | backfirecs/python_pratice | /20191207/varconvert_demo.py | 1,300 | 4.3125 | 4 | """
内置函数变量类型转换
Version:1.0
Author:chaishuai
"""
# 将一个数值或者字符串转换成整数,不能转换成整数的将会报错(浮点数类型,浮点数字符串,不是数字的字符串,None,空串,空格),False=>0,true=>1
a = '123'
print(int(a))
# b = '123.00'
# print(int(b))
# c = 123.00
# print(int(c))
# d = None
# print(int(d))
e = True
print(int(e))
f = False
print(int(f))
# g = ''
# print(int(g))
# h =... | false |
9c0248558be0e378d8468f7424db799f676da20d | backfirecs/python_pratice | /20191211/which_day.py | 782 | 4.34375 | 4 | """
计算给定的年月日是哪一天
Version:1.0
Author:chaishuai
"""
def is_leap_year(year):
if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0 or (year % 3200 == 0 and year % 172800):
return True
return False
def which_day(year, month, day):
big_month = [1, 3, 5, 7, 8, 10, 12]
day_counter = 0
for ... | false |
95829d0e11c21cbd29e53f6ad71211e4fb320bf7 | amitsubedi353/Assignment | /assign2.py | 412 | 4.21875 | 4 | def is_Anagram(str1, str2):
n1 = len(str1)
n2 = len(str2)
if n1 != n2:
return 0
str1 = sorted(str1)
str2 = sorted(str2)
for i in range(0, n1):
if str1[i] != str2[i]:
return 0
return 1
str1 = "realmadrid"
str2 = "elarmdiard"
if is_Anagram(str1, str2):
print ("The two strings ar... | true |
caacf3eb5c43161a4dd3e05156c3a85e8373b429 | calvinsettachatgul/caty | /python_class/city.py | 1,615 | 4.40625 | 4 | class Location:
def __init__(self, latitude, longitude):
self.latitude = latitude
self.longitude = longitude
# Inheritance
# Every City is a kind of Location
class City(Location):
def __init__(self, name, county, state, population, latitude, longitude):
Location.__init__(self, ... | false |
4b1781ce2dd5daf4d86257ec3365995270b3b85c | humid1/python_learn | /python_study/案例代码/变量和数据格式化案例.py | 748 | 4.125 | 4 | # 案例
# price_str = input("请输入苹果的价格:")
# weight_str = input("请输入苹果的总量:")
# weight = float(weight_str)
# price = float(price_str)
# print(weight * price)
# 以上方式定义了多个变量 (改进方法),
# 1.节约空间,只需要为一个变量分配空间
# 2.起名字方便,不需要为中间变量起名
price = float(input("请输入苹果的价格:"))
weight = float(input("请输入苹果的总量:"))
# 格式化输出
print("苹果单价 %.02f ... | false |
160ef0394e57547b4fac0d3afd7b8ef11a21d42f | SushanKattel/LearnBasicPython | /Dictionaries_example.py | 1,023 | 4.375 | 4 | month_names = {
"jan": "January",
1: "January",
"feb": "February",
2: "February",
"mar": "March",
3: "March",
"apr": "April",
4: "April",
"may": "May",
5: "May",
"jun": "June",
6: "June",
"jul": "July",
7: "July",
"aug": "August",
8: "August",
"sep": "... | true |
b4ae05891fe87614b461f12bb04a933d48093c67 | SaiAshish9/PythonProgramming | /generators/size.py | 934 | 4.28125 | 4 | # generator functions are a
# special kind of function that
# return a lazy iterator. These are objects
# that you can loop over like a list. However, unlike
# lists, lazy iterators do not store their conten
# Python generators are a simple way of creating iterators.
def rev_str(my_str):
length = len(my_str)
f... | true |
06100aee24e1c23fa77cbd1cd43b8ef89bf01d77 | Christopher-Caswell/holbertonschool-higher_level_programming | /0x0A-python-inheritance/1-my_list.py | 495 | 4.25 | 4 | #!/usr/bin/python3
"""
Write a class My_List that inherits from list
Public instance meth: def print_sorted(self):
that prints the list, but sorted (ascending sort)
"""
class MyList(list):
"""Top shelf, have some class"""
def __init__(self):
"""Superdot inits with parent parameters"""
super().... | true |
9748755004c7e42dd8817a6a52bd83ff29765926 | Christopher-Caswell/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/5-text_indentation.py | 1,186 | 4.34375 | 4 | #!/usr/bin/python3
"""
Print a pair of new lines between the strings
separators are . ? :
raise a flag if not a string, though
"""
def text_indentation(text):
"""Consider me noted"""
if not isinstance(text, str):
raise TypeError("text must be a string")
"""
chr(10) is a new line.
Written... | true |
d101baa4a1ecbde443c85ea6c6f2accbf3d3ab2a | pankilshah412/P4E | /Assignment 3.2.py | 742 | 4.375 | 4 | #Write a program to prompt for a score between 0.0 and 1.0. If the score is out of range, print an error. If the score is between 0.0 and 1.0, print a grade using the following table:
#Score Grade
#>= 0.9 A
#>= 0.8 B
#>= 0.7 C
#>= 0.6 D
#< 0.6 F
#If the user enters a value out of range, print a suitable error message a... | true |
abdb72a1cd2ffd7b69580cc63730d797d4cbcc2a | ZombieSave/Python | /Урок1.2/Задача3.py | 657 | 4.21875 | 4 | # 3. Пользователь вводит месяц в виде целого числа от 1 до 12. Сообщить к какому времени года относится месяц
# (зима, весна, лето, осень). Напишите решения через list и через dict.
monthString = input("Введите месяц: ")
month = int(monthString)
seasons = {"зима": [1, 2, 12],
"весна": [3, 4, 5],
... | false |
020749fd6c1c702e6212c5df834d5b83ae20d92f | bikenmoirangthem/Python | /reverse_string.py | 361 | 4.59375 | 5 | #program to reverse a string
#function to reverse a string
def reverse(s):
str = ''
for i in s:
str = i + str
return str
#getting a string from user
str = input('Enter any string : ')
#printing the original string
print('Your original string : ',str)
#printing the reverse string
... | true |
6780b2fa26b4c1649f2787738e03ee7c042a453b | chetan4151/python | /positivelist.py | 341 | 4.15625 | 4 | # Write a Python program to print all positive numbers in a range.
list1=[]
n=int(input("Enter number of elements you want in list :"))
print(f"Enter {n} elements:")
for i in range(0,n):
a=int(input())
list1.append(a)
print("list1=",list1)
list2=[]
for i in range(0,n):
if list1[i]>0:
list2.append(li... | true |
4229ec2c151a99ef52eec1c7841e31e2e12d8794 | JanviChitroda24/pythonprogramming | /10 Days of Statistics/Day 0/Weighted Mean.py | 1,512 | 4.28125 | 4 | '''
Objective
In the previous challenge, we calculated a mean. In this challenge, we practice calculating a weighted mean. Check out the Tutorial tab for learning materials and an instructional video!
Task
Given an array, , of integers and an array, , representing the respective weights of 's elements, calcula... | true |
2a18ab3e5918b5518454ac41565769a3912d7d1f | JanviChitroda24/pythonprogramming | /Hackerrank Practice/RunnerUp.py | 879 | 4.25 | 4 | '''
Given the participants' score sheet for your University Sports Day, you are required to find the runner-up score. You are given scores. Store them in a list and find the score of the runner-up.
Input Format
The first line contains . The second line contains an array of integers each separated by a space.... | true |
eae94c125d5a7b3f733c77573111e92cc1fdb527 | JanviChitroda24/pythonprogramming | /Hackerrank Practice/Mini_Max Sum.py | 1,796 | 4.40625 | 4 | '''
Given five positive integers, find the minimum and maximum values that can be calculated by summing exactly four of the five integers. Then print the respective minimum and maximum values as a single line of two space-separated long integers.
For example, . Our minimum sum is and our maximum sum is . We would ... | true |
08d15907da0916342026766888602ebb9c9c9e56 | JanviChitroda24/pythonprogramming | /Hackerrank Practice/Time Conversion.py | 1,395 | 4.15625 | 4 | '''
Given a time in -hour AM/PM format, convert it to military (24-hour) time.
Note: Midnight is 12:00:00AM on a 12-hour clock, and 00:00:00 on a 24-hour clock. Noon is 12:00:00PM on a 12-hour clock, and 12:00:00 on a 24-hour clock.
Function Description
Complete the timeConversion function in the editor below... | true |
d908a2c337533ac0f25113b1ca7ac994247cb4ec | JanviChitroda24/pythonprogramming | /Hackerrank Practice/Lists.py | 1,889 | 4.65625 | 5 | ```
Consider a list (list = []). You can perform the following commands:
insert i e: Insert integer at position .
print: Print the list.
remove e: Delete the first occurrence of integer .
append e: Insert integer at the end of the list.
sort: Sort the list.
pop: Pop the last element from the list.
reverse: ... | true |
3ce7edd59141cefc007942f7ddbd53ba0a12c8ad | fahimkk/automateTheBoringStuff | /chapter_5/birthdays.py | 491 | 4.15625 | 4 | birthdays = {'Alice':'April 1', 'Bob':'March 21', 'Carol':'Dec 4'}
while True:
name = input('Enter a name: (blank to Quit)\n')
if name == '':
break
if name in birthdays:
print(birthdays[name]+' is the birthday of '+name)
print()
else:
print('I dont have birthday informato... | true |
726eca08e0049d17f4000037c283bacc627d1eb2 | larsnohle/57 | /21/twentyoneChallenge2.py~ | 1,239 | 4.15625 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
def get_positive_number_input(msg, to_float = False):
done = False
while not done:
try:
i = -1.0
if to_float == True:
i = float(input(msg))
else:
i = int(input(msg))
if i < 0:
... | true |
f6fcd47c5084c99cf3738301b304398fde52d508 | larsnohle/57 | /18/eighteenChallenge2.py | 1,682 | 4.1875 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
def get_positive_number_input(msg, to_float = False):
done = False
while not done:
try:
i = -1.0
if to_float == True:
i = float(input(msg))
else:
i = int(input(msg))
if i < 0:
... | true |
de6c5c6492335f75b402a2d5228bcf8d25511b98 | larsnohle/57 | /8/eightChallenge3.py | 921 | 4.21875 | 4 | def get_positive_integer_input(msg):
done = False
while not done:
try:
i = int(input(msg))
if i < 0:
print("Please enter a number > 0")
else:
done = True
except ValueError:
print("That was not a valid integer. Please... | true |
e42960bffe6815300320f8d19fb6ea226e6ac0cd | larsnohle/57 | /24/twentyfour.py~ | 634 | 4.3125 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
def is_anagram(first_string, second_string):
if len(first_string) != len(second_string):
return False
HERE
def main():
print("Enter two strings and I'll tell you if they are anagrams")
first_string = input("Enter the first string:")
second_string =... | true |
df74617e4ce1f7c9f79e8e22004f44933b140006 | larsnohle/57 | /34/thirtyFourChallenge1.py | 549 | 4.21875 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
EMPLOYEES = ["John Smith", "Jackie Jackson", "Chris Jones", "Amanda Cullen", "Jeremy Goodwin"]
def main():
while len(EMPLOYEES) > 0:
print("\nThere are %d employees: " % len(EMPLOYEES))
for employee in EMPLOYEES:
print(employee)
employ... | false |
73c23d579194a4b068c24d0336e5fbd5e506ae3e | eric-mahasi/algorithms | /algorithms/linear_search.py | 808 | 4.1875 | 4 | """This script demonstrates the linear search algorithm in Python 3."""
AGES = [19, 20, 13, 1, 15, 7, 11, 3, 16, 10]
def display():
"""Prints all the items in the list."""
print("The ages are: ")
for i in range(len(AGES)):
print(AGES[i])
def linear_search(array, x):
"""Sequentially check ea... | true |
5fca17139a2fb3bcfb68acedd4ee3428735b32f6 | eric-mahasi/algorithms | /algorithms/bubble_sort.py | 895 | 4.4375 | 4 | """This script demonstrates the bubble sort algorithm in Python 3."""
AGES = [19, 20, 13, 1, 15, 7, 11, 3, 16, 10]
def display():
"""Prints all the items in the list."""
print("The ages are: ")
for i in range(len(AGES)):
print(AGES[i])
print("\n")
def bubble_sort(array):
"""Repeatedly s... | true |
c0c1dbd89be9a529c9cb3b78e8a913d66fa6a89e | MirzaRaiyan/The-Most-Occuring-Number-In-a-String-Using-Regex.py | /Occuring.py | 1,132 | 4.375 | 4 | # your code goes here# Python program to
# find the most occurring element
import re
from collections import Counter
def most_occr_element(word):
# re.findall will extract all the elements
# from the string and make a list
arr = re.findall(r'[0-9] +', word)
def most_occr_element(word):
... | true |
14baefcd782e3e232ccc333a7ab437c1cd3f8120 | tinxo/Tutorias-PL-SEM1-TTI | /Clase #1/variables.py | 1,288 | 4.4375 | 4 | # Declaración de variables
# <nombreVariable> = <valor>
numeroEntero = 101
numeroDecimal = 34.2
valorBoolean = True
texto = 'Texto a guardar'
# Se pueden usar tanto comillas simples como dobles
# -------------------------
# Tipos de datos: detección y conversiones
# 1ro: Obtener el tipo de datos de una variab... | false |
9e675b13c7217efa27655e0950b31b8525e2bbda | pereiralabs/publiclab | /python/csv_filter_lines/ex_csv.py | 903 | 4.125 | 4 | #This script reads a CSV file, then return lines based on a filter
#Setting the locale
# -*- coding: utf-8 -*
#Libraries section
import csv
#List of files you want to extract rows from
file_list = ["/home/foo/Downloads/20180514.csv"]
#List of columns you want to extract from each row
included_cols = [5,2,1]
#Now l... | true |
b5e47b5711987b4345d86f64992ddc3709d014bf | tiwanacote/Pythonic-2021 | /05-Colecciones/4-Set.py | 517 | 4.34375 | 4 | """
No mantiene el orden -> no se puede indexar
-> Cada vez que imprimo veo orden diferente
Los elementos se almacenan una sola vez
Creo que desde Python 3.algo ya mantiene el orden y siempre se imprime lo mismo
"""
planetas = {"Marte","Jupiter","Venus"}
print(planetas)
print(planetas)
pr... | false |
a52b5830ce6e24ae87193c9d2b51fa4a97160959 | yun-lai-yun-qu/patterns | /design-patterns/python/creational/factory_method.py | 1,620 | 4.59375 | 5 | #!/usr/bin/python
# -*- coding : utf-8 -*-
"""
brief:
Factory method. Use multiple factories for
multiple products
pattern:
Factory method:
Define an interface for creating an object,
but let subclasses decide which class to
instantiate.Factory Method lets a class defer
instantiation to subclasses... | true |
46bde43ea1468e8b0e96c26935a4bb77baec0e7e | vkagwiria/thecodevillage | /Python Week 2/Day 1/exercise4.py | 573 | 4.21875 | 4 | # User Input: Ask the user to input the time of day in military time without a
# colon (1100 = 11:00 AM). Write a conditional statement so that it outputs the
# following:
# a. “Good Morning” if less than 1200
# b. “Good Afternoon” if between 1200 and 1700
# c. “Good Evening” if equal or above 1700
time=int(i... | true |
bb8a0d849cd2a47df53088fee0b8c926f8654c9a | vkagwiria/thecodevillage | /Python Week 2/Day 2/exercise1.py | 464 | 4.1875 | 4 | # Ask the user for 3 numbers
# Calculate the sum of the three numbers
# if the values are equal then return thrice of their sum
# else, return the sum
num1=int(input("Please insert the first number here: "))
num2=int(input("Please insert the second number here: "))
num3=int(input("Please insert the third number... | true |
85d969c057da158c9b16bd1143b78e7f1be1a990 | vkagwiria/thecodevillage | /Python Week 2/Day 1/02_else_statements.py | 1,073 | 4.5625 | 5 | """
Else statements
The final part of a good decision is what to do by default. Else statements are used to cater for this.
How They Work
Else conditional statements are the end all be all of the if statement. Sometimes you’re
not able to create a condition for every decision you want to make, so that’s where t... | true |
54ebed866e5e015a47b3e2a23ff660dab7adf0af | vkagwiria/thecodevillage | /Python Week 2/Day 1/exercise2.py | 381 | 4.28125 | 4 | # ask the user to input a number
# check whether the number is higher or lower than 100
# print "Higher than 100" if the number is greater than 100
# print "Loweer than 100" if the number is lower than 100
num=int(input("Please insert your number here: "))
if(num>100):
print("The number is greater than 100.... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.