blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
a3b988261743a290910d8c3110733d393ef01512 | wolverinez/T_Mud | /dice.py | 1,099 | 4.15625 | 4 | """this module contains functions for rolling dice from a cointoss
to a one hundred sided dice the
funtions are named with the letter 'd' and then a number forinstance
the function to simulate a d20 is simply named d20(pluss=0) where the pluss argument
makes it possible to modify the roll
"""
import random as R
de... | true |
4125db8aaa60416d0ccd30d7c23fea23b20c4246 | divir94/Python-Projects | /Algorithms Practice/Reducible Word.py | 1,572 | 4.15625 | 4 | # http://www.greenteapress.com/thinkpython/thinkpython.pdf
# Exercise 12.6
def make_word_dict():
d = dict()
fin = open('../Data/English Wordlist.txt')
for line in fin:
word = line.strip().lower()
d[word] = word
return d
"""memo is a dictionary that maps from each word that is known
to ... | false |
2b953aeab24e60b0a44915565b05b7cb3f1a4dd6 | kosskiev/University-of-Michigan | /turtle_and_color_figure.py | 873 | 4.46875 | 4 | #Write a program that asks the user for the number of sides, the length of the side, the color, and the fill color of a regular polygon.
#The program should draw the polygon and then fill it in.
import turtle
number_side = int(input('How many sides would you like?(Сколько сторон у вашей фигуры?) '))
angle = 360 / nu... | true |
429a1d0562b5385edfa9a443c0732272e82bef4d | hutor04/UiO | /in1000/oblig_3/ordbok.py | 1,197 | 4.34375 | 4 | # The program initiates a dictionary with product names as keys and their prices as values. It then prints out the list
# Then the program asks the user to input a new product and its price two times.
# It ads new products to the dictionary and then prints a new dictionary.
# We create a dictionary that holds product ... | true |
215b78a3a4ae410b55ea532938f4d337b338ee1f | hutor04/UiO | /in1000/oblig_1/hei_student.py | 361 | 4.21875 | 4 | # The following program prints salutation, asks the user to input its name.
# Then it prints out salutation and the name that was provided by the
# user.
# Prints to screen the first salutation
print('Hei Student!')
# Asks to input the name of the user
navn = input('Scriv navnet ditt nå: ')
# Prints to screen new salu... | true |
e4279841462864909d41865df0c27e91b156831d | CharlieHuang95/Algorithms | /Sorting/quick_sort.py | 1,188 | 4.25 | 4 | # Quicksort works by randomly selecting an element to be its pivot, and shifting
# smaller elements to its left side, and larger elements to its right side.
# At the end of all the shifting, the pivot should ultimately be in the correct
# location.
import random
def quick_sort_helper(array, left, right):
if left ... | true |
fd2a94cec38175d7ff35a93814bc5815df69dcd0 | MeenaRepo/augustH2K | /DictionaryTest.py | 1,285 | 4.1875 | 4 | sampleDictionary = {
"Warm":"Red",
"Cold":"Baige",
"Nuetral":"Grey",
"Common":"Black",
}
print(sampleDictionary)
print(sampleDictionary["Cold"])
print(sampleDictionary.get("Warm"))
# Add - replaces the old value
sampleDictionary["Warm"] = "Blue"
print(sampleDictionary)
# Membership
if... | true |
10cd5c0f8f3bf6fae6e03e1e740a115f505a1aba | duthaho/python-design-patterns | /creational/builder.py | 2,288 | 4.15625 | 4 | from abc import abstractmethod
from typing import Optional
class Car:
def __init__(self):
self.seat = 0
self.engine = ""
self.trip_computer = False
self.gps = False
def info(self):
print(f"Car: {self.seat} - {self.engine} - {self.trip_computer} - {self.gps}")
class B... | true |
e3eacc2e7aef6a075a6b3c6a9810739b1ff6e15e | VandalTryHard/Test-Task-for-work | /Consult_Test_task/task3.py | 559 | 4.125 | 4 | """3. Создать процедуру обратного отражения порядка строк (сортировки по номеру строки в обратном порядке.
Например номер строки был
1 ae1234
2 bc5678
стал
10000 ae1234
9999 bc5678"""
import csv
with open('file_task3.csv', 'r') as textfile:
for row in reversed(list(csv.reader(textfile))): #reversed возвращ... | false |
259d53c7b2581e146cc8b1c5c9d75da5f04ee845 | joelbd/CSC110 | /convertmiles.py | 244 | 4.3125 | 4 | # File: convertmiles.py
# This program converts distance in miles to distance in kilometers
# Day
def main():
miles = eval(input("Enter the distance in miles:"))
kilometers = miles * 1.60934
print("The distance is:",kilometers,"km")
main() | true |
a80ddf31a4e28b238ebd83d30c80ef432bd25a16 | Raktacharitra/TrueCaller-search | /truecaller.py | 1,022 | 4.125 | 4 | from sys import argv
choice = input("Tell us if you want to 'search' a particular contact or 'add' a contact (s / a): ")
if choice.lower() == "s" or choice.lower() == "search":
with open(argv[1], "r") as phone_book:
search_type = input("search by name or number: ")
try:
a = int(search_t... | true |
b25989f7358daf4ac3813f19a9aaf9f065fc0c44 | rogeriosilva-ifpi/teaching-tds-course | /programacao_estruturada/20192_186/Bimestral1_186_20192/ANTONIO_FRANCISCO_OLIVEIRA___EDRAS/negativo_para.py | 218 | 4.21875 | 4 | numero = int(input('Digite um numero'))
contador1 = 1
while (numero > 0):
contador = numero
contador1 = contador1 + 1
numero = int(input('Digite o próximo numero'))
print(contador, contator/contador1)
| false |
edd06834320697ac884f503a1dc4c756443aa72b | rogeriosilva-ifpi/teaching-tds-course | /programacao_estruturada/20192_186/Bimestral1_186_20192/FRANCISCO ROBERTO E REGINALDO JOSE - TURMA 186N/angulo.py | 412 | 4.125 | 4 | print('Qual o quadrante do angulo?')
# entrada
angulo = float(input('Digite o valor do angulo entre 0° e 360°: '))
# processamento
if angulo < 90:
print('este angulo percente ao 1° quadrante')
elif 90 < angulo < 180:
print('este angulo percente ao 2° quadrante')
elif 180 < angulo < 270:
print('este angul... | false |
1f527d83890651daeebb1874a70225fa013d07e4 | louisbranch/hello-py | /ProblemSet3/ps3_newton.py | 1,757 | 4.21875 | 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
'''
s =... | true |
ae069876ea6409ad4a9ff29f1fb23a915d707e01 | priyankagoma/learningpython | /src/python_scripts/print_examples/printexamples.py | 290 | 4.15625 | 4 | #below are few examples that how we can print numbers.
print(2 + 8)
print(3 * 5)
print(6 - 3)
#Example of a string.
print("The end", "it should be nice", "we will able to make it")
#Exapme of integers.
print(1, 2, 3, 4, 5)
#Example of words.
print("one two three four five cat dog") | true |
df53ec293bedda6a6954334daca394536dc0e02b | Junhee-Kim1/RandomNumber | /RandomNumberGuesser.py | 442 | 4.15625 | 4 | import random
print("number Guessing Game!")
number=random.randint(1,9)
chance=0
print("guess number")
while chance<5:
guess=int(input("enter your guess!: "))
if guess == number:
print("you win!")
break
elif guess<number:
print("your number is too low")
else:
... | true |
2c4da32e1420daae3f9401ca78d4be75b6af5f9d | prathmesh2606/DSA_LU | /a1q1.py | 344 | 4.4375 | 4 | # Assignment 1 - Q1
# Write a python program that takes two numbers as the input such as X and Y and print the result
# of X^Y(X to the power of Y).
# Taking input
x,y = [int(i) for i in input("Enter base value and then power value by giving space between them (eg: 2 3 ans: 8): ").split()]
print(f"{x} to the pow... | true |
b1b7f0de711f5d40447d83553dc3e8c4bbe3209f | charliettaylor/CSA231 | /Projects/4/project4.py | 2,286 | 4.28125 | 4 | # Turtle Project by Charlie Taylor
from turtle import *
import random as rand
SCALE = "Enter the size of the spiral (recommend 1-10): "
LOW = "Enter low bound of shake (rec. negative or 0): "
HIGH = "Enter high bound of shake (rec. positive or 0): "
def draw_c(t) -> None:
'''
draws letter C
'''
t.do... | true |
e307eb42c7b796d5e927e7f03720a4b3abfca74b | NankuF/PythonKnowledge | /classes/1.py | 596 | 4.125 | 4 | # Определите класс car с двумя атрибутами: color и speed.
# Затем создайте экземпляр и верните speed
"""
class Car:
color = 'red'
speed = 20
car_ex = Car()
print(car_ex.speed)
"""
class Car:
def __init__(self, color, speed):
self.color = color
self.speed = speed
def __str__(self):
... | false |
101cedb9b67c9004b1a4a5af955197ed7b71a4b9 | yingl910/MongoDB | /Basics/mdb_update.py | 1,899 | 4.25 | 4 |
'''These are examples of MongoDB example codes of save and update, two methods for updating'''
'''update method one: save'''
# a method on collection objects
# find_one just returns the first document it finds
city = db.cities.find_one({'name':"munchen",'country':'Germany'})
city['isoCountryCode'] = 'DEU'
db.cities.s... | true |
cd890912e0574154ac18385ac92f43fdd68f430d | PrabhudevMishra/PRO-97 | /numberGuessingGame.py | 497 | 4.15625 | 4 | import random
number = random.randint(0,10)
chances = 0
while chances < 5 :
guess = int(input("Enter your guess"))
chances = chances + 1
if guess < number:
print('Your guess is too low')
if guess > number:
print('Your guess is too high')
if guess == number:
brea... | true |
c43c7f51aff65b851a591bf7d00c96a0d8a160be | shivesh01/Python-Basics | /Project&problems/Example_30.py | 425 | 4.28125 | 4 | # Shuffle Deck of cards
import random
# In the program, we used the product() function in itertools module to create a deck of cards. This function performs the Cartesian product of the two sequences.
from itertools import product
deck = list(product(range(1, 14), ["Spade", "Heart", "Club", "Diamond"]))
random.sh... | true |
65e62f4761054c0cf0ac8911e1715c5537608c7c | shivesh01/Python-Basics | /Project&problems/Example_10.py | 233 | 4.375 | 4 | # check number +,- or 0
num = float(input("Enter number"))
if num == 0:
print("your entered number is zero")
elif num > 0:
print("You have entered a positive number")
else:
print("You have entered a negative number")
| true |
918af8577d167cb37357196e2509ea35569e4682 | shivesh01/Python-Basics | /Datatype/datatype_explict_3.py | 327 | 4.21875 | 4 | num_int = 123
num_str = "456"
print("data type of num_int",type(num_int))
print("data type of num_str",type(num_str))
num_str = int(num_str)
print("data type of num integer after typecasting:",type(num_str))
num_sum= num_int + num_str
print("sum of num_int and num_str ",num_sum)
print("data type of num_sum",type(nu... | false |
dd701404bbf09b357bdd5faec5512de7093ca871 | lmjim/year1 | /cs210/p61_testfunc_key.py | 1,584 | 4.21875 | 4 | """
CIS210 Project 6-1 Fall 2017
Author: [Solution]
Credits: N/A
Implement a function to test the string
reverse functions from project 5
(iterative and recursive).
Practice:
-- user-defined test functions
-- functions as parameters
"""
import p52_stringreverse_key as p5
def test_reverse(f):
'''(fun... | true |
826fb885f233ea03edffde38cb2342bda0236dea | dudulydesign/python_web_pratice | /webserver/py_though/bubble sort.py | 747 | 4.15625 | 4 | #Bubble Sort
sampleList = [6,5,4,3,2,1]
def bubbleSort(sourceBubbleSortList):
#how long the list
listLength = len(sourceBubbleSortList)
i = 0
# the i here to count how many value not in
while i < listLength-1:
j = listLength - 1
# here to compare two value
while j > i:
print(" sourceBubble... | true |
62f8410ff45e2352f7ac48cf8327c35a62371895 | geraldfan/Automate-The-Boring-Stuff | /Chapter_9_Organizing_Files/selectiveCopy.py | 699 | 4.25 | 4 | #! python3
# selectiveCopy.py - Walks through a folder tree, then searches and copies for files with a particular extension (i.e. .jpg)
import shutil, os
folder = input('Enter the absolute filepath of'
' the directory you wish to copy from: ')
extension = input("Enter the extension you'd like to copy:... | true |
8b0e1fb5a628c393ee871205478499cf48cf5306 | rodrigosantosti01/LingProg | /Exercicio3/atv11.py | 1,054 | 4.1875 | 4 | # 11. Faça um programa que faça 5 perguntas para uma pessoa sobre um crime. As perguntas são:
# "Telefonou para a vítima?"
# "Esteve no local do crime?"
# "Mora perto da vítima?"
# "Devia para a vítima?"
# "Já trabalhou com a vítima?"
# O programa deve no final emitir uma classificação sobre a participação da pes... | false |
860f2ff85024e2668c3268b1f98012f86fbc8863 | rodrigosantosti01/LingProg | /Exercicio4/atv01.py | 389 | 4.1875 | 4 | # 1 Menor de dois pares: Escreva uma função que retorne o menor de dois números
# dados se ambos os números forem pares, mas retorna o maior se um dos dois for
# ímpar. Exemplo:
# menor_de_dois_pares(2,4) --> 2
# menor_de_dois_pares (2,5) --> 5
def f(a,b):
if a%2==0 and b%2==0:
if a<b:
return a
return b
else... | false |
578494d75a99a79091946b96a93a13fc485c6c50 | Szkeller/TDD_lab | /FizzBuzz.py | 867 | 4.125 | 4 | class FizzBuzz:
'''
This is for TDD sample
Author: Keller Zhang
create date: 04/27
description: FizzBuzz Quiz
When given number just can be divided by 3, then return 'Fizz';
When given number just can be divided by 5, then return 'Buzz';
Whe... | true |
383c7b66d2e6c025f09270cf1e547d64556954aa | Shilinana/LearnPythonTheHardWayPractices | /ex18.py | 633 | 4.3125 | 4 | """
@Author:ShiLiNa
@Brief:The exercise18 for Learn python the hard way
@CreatedTime:28/7/2016
"""
# this one is like your scripts with argv
def print_two(*args):
arg1, arg2 = args
print "arg1:%r, arg2:%r" % (arg1, arg2)
# ok, that *arg is actually pointless, we can just do this
def print_two_again(ar... | true |
89768748cf4abc99b56f383e025fe37a851579f8 | justinelai/Sorting | /src/iterative_sorting/iterative_sorting.py | 2,598 | 4.5625 | 5 | def insertion_sort(list):
for i in range(1, len(list)):
# copy item at that index into a temp variable
temp = list[i]
# iterate to the left until reaching correct .
# shift items to the right
j = i
while j > 0 and temp < list[j-1]:
list[j] = list[j-1]
... | true |
2851a656bd9f2bdc1b7877c587dd09a17e0fe219 | Tech-Amol5278/Python_Basics | /c5 - list/c5_more_methods_to_add_data.py | 626 | 4.15625 | 4 | # count
# sort method
# sorted function
# reverse
# clear
# copy
# Count: Counts the string available in list
fruits = ['apple','orange','banana','grapes','apple','apple','guava']
print(fruits.count('apple'))
# Sort: sort the list contains in alphabetical/numeric order
fruits.sort()
print(fruits)
numbers = [3,51,8... | true |
43bce6c540aa4ad249c33ab9650e4e1b739a73cb | Tech-Amol5278/Python_Basics | /c5 - list/c5e4.py | 522 | 4.4375 | 4 | # define a function which returns a lists inside list, inner lists are odd and even numbers
# for example
# input : [1,2,3,4,5,6,7,8]
# returns : [[1,3,5,7],[2,4,6,8]]
####### Sol ###############################################
num1 = [1,2,3,4,5,6,7,8]
def separate_odd_even(list1):
sep_list = []
odd = []
... | true |
f383537b4da9f340610aaa7e4ee2e1fbf5b73147 | Tech-Amol5278/Python_Basics | /c2 - strings methods/c2e2.py | 218 | 4.21875 | 4 | # ask username and print back username in reverse order
# note: try to maje your program in 2 lines using string formatting
#### Sol ##########################3
u_name = input("Enter your name: ")
print(u_name[::-1])
| true |
4e09df38fd41bfaa63801dffa2f1a822878deab4 | Tech-Amol5278/Python_Basics | /c17 - debugging and exceptions/else and finally.py | 675 | 4.28125 | 4 | # Else and fianlly
while True: ## Loop to accept input til true comes
try:
age = int(input("Enter a number: "))
except ValueError: # valueerror : optional only if we know the error which can come
print("Please enter age only in integer ")
except: # when error is unpredicta... | true |
e3a71a4f1447e3fc0e6bf03654df9c63e1af56f2 | Tech-Amol5278/Python_Basics | /c16 - oops/property and setter decorator.py | 2,526 | 4.21875 | 4 | # property and setter decorator
# the below code from last slide it has below problems
# 1. this accepts the negative amount for price
# sol: write a validation not to accept negative numbers
# using getter(),setter()
# 2. After changing the price , complete specification shows the old price.
... | true |
1990af0b8f76c76eaa907f985d091f44a32cad62 | Tech-Amol5278/Python_Basics | /c5 - list/c5_list_intro.py | 649 | 4.5 | 4 | # Data Structures
# List
# List is ordered collection of items
# We can store anything in lits like int, float, string
numbers = [1,2,3,4]
print(numbers)
## to print 2 from list
print(numbers[1])
## to access only and 1 and 2
print(numbers[:2])
## to reverse the elements in list
print(numbers[::-1])
## to access only... | true |
19eb4162a092c37319cccc4e1743978ac34653ed | ITlearning/ROKA_Python | /2021_03/03_14/CH04_Problem/029_If_string02.py | 519 | 4.125 | 4 | # 이 문제를 해결하려면 다음과 같이 코딩한다.
# if 조건문과 여러 줄 문자열(3)
number = int(input("정수 입력 > "))
if number % 2 == 0 :
print("""입력한 문자열은 {}입니다.\n{}는 짝수입니다.""".format(number,number))
else :
print("""입력한 문자열은 {}입니다.\n{}는 홀수입니다.""".format(number,number))
# 이렇게 하면 코드가 다행히 잘 보이긴 하는데, 길게 적음으로 인해 다소 복잡해보일수가 있다.
| false |
240bf5eb01603c73b773ae7bda168bc2407e28a5 | 0gravity000/IntroducingPython | /06/0609.py | 1,114 | 4.3125 | 4 | # 6.9 非公開属性のための名前のマングリング
# Pythonは、クラス定義の外からが見えないようにすべき属性の命名方法を持っている
# 先頭にふたつのアンダースコア__を付ける
class Duck():
def __init__(self, input_name):
self.__name = input_name #外からアクセスできないプロパティ
@property
def name(self): #ゲッター
print('inside the getter')
return self.__name
@name.setter
d... | false |
b8d0130e85142df007aed7951d6ec07988bddc9a | 0gravity000/IntroducingPython | /04/040601.py | 1,312 | 4.3125 | 4 | # 4.6.1 リスト内包表記
number_list = []
for number in range(1, 6):
number_list.append(number)
number_list
number_list = list(range(1, 6))
number_list
# リスト内包表記を使った Pythonらしいコード
# [ expression for item in iterable ]
number_list = [number for number in range(1, 6)]
number_list
number_list = [number -1 for number in rang... | false |
9fe26472b3e65060b858040cdacc132387283fbd | mansi135/mansi_prep | /practice/new_problems.py | 2,850 | 4.1875 | 4 | # Given two sorted lists, return the interesection (ie the common elements b/w the two sorted lists)
# For example given l1 = [1, 2, 3] and l2 = [2, 3, 5, 10] (they can be different sizes)
# return [2, 3]
# LINEAR TIME
# 4
def get_intersection(l1, l2):
pass
# given two sorted lists l1 and l2, merge them such that ... | true |
bf5541aff5d60357f0a736f7689cfeb3aa8b46e7 | snidarian/Algorithms | /factorial_recursion.py | 429 | 4.46875 | 4 | #! /usr/bin/python3
# Factorial recursive algorithm
import argparse
parser = argparse.ArgumentParser(description="Returns factorial of given integer argument")
args = parser.add_argument("intarg", help="Int to be factored", type=int)
args = parser.parse_args()
def factorial_recursive(n):
if n == 1:
r... | true |
aa952649de3e87a99472f6cc2b92e7b2b8bf57ea | Factumpro/HackerRank | /Python/Practice/Sets/intersection.py | 535 | 4.15625 | 4 | '''
Set .intersection() Operation
https://www.hackerrank.com/challenges/py-set-intersection-operation/problem
'''
'''
The .intersection() operator returns the intersection of a set and the set of elements in an iterable.
Sometimes, the & operator is used in place of the .intersection() operator, but it only operate... | true |
9cd9cb9efd74fd3e3ff798b3865ace2590249fa4 | Factumpro/HackerRank | /Python/Practice/Sets/union.py | 481 | 4.1875 | 4 | '''
Set .union() Operation
https://www.hackerrank.com/challenges/py-set-union/problem
'''
'''
The .union() operator returns the union of a set and the set of elements in an iterable.
Sometimes, the | operator is used in place of .union() operator, but it operates only on the set of elements in set.
Set is immutable... | true |
42d6fba978a62e664aad1dbb1aa10fe161d51fab | Epic-R-R/Round-robin-tournament | /main.py | 1,536 | 4.125 | 4 | from pprint import pprint as pp
def make_day(num_teams, day):
# using circle algorithm, https://en.wikipedia.org/wiki/Round-robin_tournament#Scheduling_algorithm
assert not num_teams % 2, "Number of teams must be even!"
# generate list of teams
lst = list(range(1, num_teams + 1))
# rotate
day ... | true |
9f815235eb7c74e01c17cd19ef5622bd843c8f1d | Elsie0312/pycharm_code | /two_truths-lie.py | 584 | 4.15625 | 4 | print('Welcome to Two Truths and a Lie! /n One of the following statements is a lie...you need to identify which one!')
print('1. I have a donkey living in my backyard.')
print('2. I have three fur babies')
print('3. I speak 4 languages')
truth_or_lie = input('Now put in the number of the statement you think is the li... | true |
21078417d8209bf5d35ba40a0e351750f28d8d36 | GABIGOLeterno/CursoemV-deoExerc-cios | /desafio33.py | 277 | 4.15625 | 4 | while True:
num = str(input("Digite três valores: ").strip())
num2 = num.split()
if len(num2) == 3:
maxi = max(num2)
mini = min(num2)
print("O valor máximo é {}.".format(maxi))
print("O valor mínimo é {}.".format(mini))
| false |
2492520b1fc91cf095c964e1b178c483046766b6 | besslwalker/algo-coding-practice | /4.1 Quicksort/quicksort.py | 1,534 | 4.125 | 4 | # Quicksort
# Bess L. Walker
# 2-21-12
import random
def quicksort(unsorted):
real_quicksort(unsorted, 0, len(unsorted))
def real_quicksort(unsorted, low, high):
if high - low <= 1:
return
pivot_index = partition(unsorted, low, high)
real_quicksort(unsorted, low, pivot_index)
real_quicksort(unsorted, pivot_i... | true |
c7c008011e3694dae55fa8a676721bd8e9f5e78b | jaypsingh/PyRecipes | /String_n_Text/Str_n_Txt_07.py | 710 | 4.4375 | 4 | '''
This program demonstrates how can we specify a regular expression to search shortest possible match.
By Default regular expression gives the longest possible match.
'''
import re
myStr = 'My heart says "no." but mind says "yes."'
# Problem demonstration
'''
Here we ar etrying to match a text inside a quote.
So i e... | true |
8132dc8fd2f2ed88fab536995f8acc2968700ed2 | jaypsingh/PyRecipes | /DS_and_Alg/DS_and_Alg_12.py | 1,562 | 4.3125 | 4 | '''
This program demos the use of Counter class from collections module.
Counter objects are very helpful in any case where you need to tabulate or count the data.
'''
from collections import Counter
mySong = ['I', 'wanna', 'be', 'your', 't-shirt', 'when', 'it', 'is', 'wet', 'I', 'wanna', 'be', 'the', 'shower', 'when'... | false |
f8d563e8c1ce87996fe1f0df6ebe05e65ff8a543 | jaypsingh/PyRecipes | /String_n_Text/Str_n_Txt_05.py | 445 | 4.1875 | 4 | '''
This function demonstrates how can we search and replace strings
'''
import re
myStr = "Today is 03/09/2016. Game of Thrones starts 21/07/2017"
# Simple replace using str.replace()
print (myStr.replace('Today', 'Tomorrow'))
# Replace using re.sub() - Approach 1
print(re.sub(r'(\d+)/(\d+)/(\d+)', r'\3\-2\-1', my... | true |
c8913860b13c4619cd5119cacdce93fce0e6bcb7 | DHSZ/programming-challenge-2 | /seven-seg-words.py | 300 | 4.40625 | 4 | def longest_word():
longest_word = ""
## Write your Python3 code inside this function.
## Remember to find words that only use the following letters:
## A, B, C, E, F, H, I, J, L, N, O, P, S, U, Y
## Good luck!!
return longest_word
print(longest_word())
| true |
5f4313bc5806a145daf721c578f7120dd2755c01 | HarrisonPierce/Python-Class | /pierce-assignment2.py | 1,258 | 4.28125 | 4 | ##Harrison Pierce
##This program calculates the factorial of a user defined number
##Set factorial variable to 1
factorial = 1
k = int(input('Enter a postitive integer: '))
##Ask user for an integer and set equal to the variable k
for k in range(1,k + 1):
##start for loop for k. while between 1 and the n... | true |
a9f0b22836ca6ae81e7d60383386fffdc7ef8011 | Rayansh14/Term-1-Project | /rock paper scissors.py | 2,289 | 4.25 | 4 | import random
score = 0
def generate_random():
return random.choice(["rock", "paper", "scissors"])
def is_valid(user_move):
if user_move in ["rock", "paper", "scissors", "r", "p", "s"]:
return True
return False
def result(comp_move, user_move):
if comp_move == user_move:
return "ti... | true |
b3e22b635a04c95e29734074c2296ffb64226552 | Julian-J0/MadlibProject | /main.py | 1,692 | 4.15625 | 4 | from random import randint
uinput = input("Choose from 1-2 or type random: " )
def story_1():
Title_1 = input("Input a title: ")
Name_1 = input("Input a name: ")
Adjective_1 = input("Input an adjective: ")
Group_1 = input("Input a group, ex. soldiers: ")
Verbed_1 = input("Input a verb ending in -ed: ")
Feel... | false |
1bd93d500350c63fca4ba7e6a8ed3e1fb80bd1fe | UnKn0wn27/PyhonLearning-2.7.13 | /ex11.py | 505 | 4.21875 | 4 | #raw_input() presents a prompt to the user(the optional arg of raw_intput([arg])
#gets input from the user and returns the data input by the user in a string.
#Exemple:
# name = raw_input("What is your name?")
# print "Hello, %s." % name
#raw_input was renamed input() in Python 3
print "How old are you?",
age = raw_in... | true |
4d7eb9d814d4cd5db77400c7a96e1c18900eb00f | cantayma/web-caesar | /caesar.py | 1,197 | 4.21875 | 4 | import string
def alphabet_position(letter):
"""
receives a letter, returns 0-based numerical position in the alphabet;
case-sensitive; assumes letters only input
"""
if letter in string.ascii_uppercase:
position = string.ascii_uppercase.find(letter)
elif letter in string.ascii_lowerc... | true |
00585bc27141ada23149b8f272f33ab23710a2ee | tlananthu/python-learning | /98_tools/training_ram/day1/ex4.py | 529 | 4.25 | 4 | #fizzbuzz problem
# take number as input (1-100)
# if divisible by 3 print Fizz
# if divisible number is divisible by 5 print buzz
# if both print fizzbuzz
# none: print number
num=int(input('Number between 1 to 100: '))
# if num%3 == 0 and num%5 == 0:
# print('FizzBuzz')
# elif num%5 == 0:
# print('Buzz')
#... | false |
36d1432db82c986858bf650aa2c8281d494e01ac | tlananthu/python-learning | /00_simple_examples/06_maths.py | 336 | 4.1875 | 4 | number1=int(input('Please input a number'))
number2=int(input('Please input another number'))
operation=input('Please input an operation. +-/*')
if operation=='+':
print(number1+number2)
elif operation=='-':
print(number2-number2)
elif operation=='/':
print(number2/number2)
elif operation=='*':
print(... | true |
90094aafd436e093d00d2300a8278938caa788c1 | Shwebs/Python-practice | /BasicConcepts/3.strings/string-multiplication.py | 567 | 4.15625 | 4 | #Strings can also be multiplied by integers. This produces a repeated version of the original string.
# The order of the string and the integer doesn't matter, but the string usually comes first.
print("spam" * 3) #O/p:spamspamspam
print (4 * '2') #O/p: 2222
#Strings can't be multiplied by other strings.
#Strings ... | true |
28b923b625a0d8e716f3a85b98cfea1ac81d285b | Shwebs/Python-practice | /ControlStructure/List/List-method-count.py | 305 | 4.125 | 4 | #list.count(obj): Returns a count of how many times an item occurs in a list
letters = ['p', 'q', 'r', 's', 'p', 'u']
print(letters.count('r')) #O/P:-1
print(letters.count('p')) #O/P:-2 # index method finds the "first occurrence" of a list item and returns its index
print(letters.count('z')) #O/P:-0 | true |
2fd82e086ef9fd6b383c2055f70ced123c94963d | Shwebs/Python-practice | /BasicConcepts/3.strings/string-methods/split.py | 489 | 4.21875 | 4 | #Splits string according to delimiter string, returns list of substrings.
#Default delimiter is ' ' .
str='Test My Skill'
output=str.split()
print(output) #o/p:- ['Test', 'My', 'Skill']
for x in output:
print(x) #o/p:-Test
# My
# Skill
#Delimiter can be change... | true |
e21cba589f4928a7ad09bd7ad84d786b5a4fb73c | Shwebs/Python-practice | /ControlStructure/range/basic-range.py | 727 | 4.75 | 5 | #The range function creates a sequential list of numbers.
#The call to list is necessary because range by itself creates a range object,
# and this must be converted to a list if you want to use it as one.
#If range is called with one argument, it produces an object with values from 0 to that argument.
numbers = li... | true |
909325fdb03654071ecb54104d622e35e96a3497 | Shwebs/Python-practice | /python-fundamentals-by-pluralsight/Object_Reference.py | 1,065 | 4.25 | 4 | #Pass by Object Reference
#The value of the reference is copied , not the value of the object
# Helpful Link https://robertheaton.com/2014/02/09/pythons-pass-by-object-reference-as-explained-by-philip-k-dick/
m = [9, 15, 24]
def modify(k):
"""Appending a value to function.
Args:
A any literal can be added.
R... | true |
79699f6e7d3ab0c9ad08ad75dcf510fae492166d | Shwebs/Python-practice | /ControlStructure/List/List-operation.py | 1,186 | 4.53125 | 5 | #The item at a certain index in a list can be reassigned.
#In the below example , we are re-assigned List[2] to "Bull"
nums = [7, 8, 9, 10, "spring"]
nums[2] = "Bull"
print(nums)
print("===================================")
#What is the result of this code?
nums = [1, 2, 3, 4, 5]
nums[3] = nums[1] # We are re-as... | true |
18f795a10eb2da066a1599fd909069e2d00216fc | Shwebs/Python-practice | /ControlStructure/List/List-method-insert.py | 797 | 4.25 | 4 | #The insert method is similar to append,
#except that it allows you to insert a new item at any position in the list,
#as opposed to just at the end.
words = ["Python", "fun"]
index = 1
words.insert(index, "is")
print (words)
print("================================")
nums = [1,2,3,5,6,7]
index = 3
nums.insert(index,... | true |
fba81294a158815848dded2ca40206fb46b6ccd5 | Shwebs/Python-practice | /BasicConcepts/3.strings/string-methods/string-is-check.py | 1,386 | 4.21875 | 4 | str=input("Enter a String: ")
#isalnum()
#Returns true if string has at least 1 character and all characters are alphanumeric and false otherwise.
print('Checking If it is an alphanumeric :-',str.isalnum())
#isalpha()
#Returns true if string has at least 1 character and all characters are alphabetic and false otherwis... | true |
292b8675c84630e557c9282cf2fc4567a3cd68c5 | alessandrogums/Desafios-Python_Variaveis_compostas-listas- | /Exercicio.86_CV.py | 468 | 4.25 | 4 | # Crie um programa que declare uma matriz de dimensão 3×3 e preencha com valores lidos pelo teclado.
# No final, mostre a matriz na tela, com a formatação correta.
matriz=[[],[],[]]
for l in range(0,3):
for c in range(0,3):
num=int(input('digite um número:'))
matriz[c].append(num)
print('='*15)
fo... | false |
7a33ee3d407ac8ec09a4898cd2cfd53eca320f1f | Abeelha/Udemy | /Curso Udemy/ex1.py | 1,334 | 4.25 | 4 | #Idade
Idade = int(input("Digite sua idade "))
#Condição da idade
if Idade >= 18:
print("Maior de idade")
elif 0 < Idade < 18:
print ("Menor de idade")
else:
print("idade inválida")
#Notas
Nota1 = float(input("Digite sua nota em Matemática "))
Nota2 = float(input("Digite sua nota em Filosofia "))
#Mé... | false |
9539c945b6063ffdcd398710f03d371056ec52f7 | IlyaTroshchynskyi/python_education_troshchynskyi | /algoritms/algoritms.py | 2,512 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""calc
Implements algorithms:
- Binary search
- Quick sort (iterative)
- Recursive factorial
"""
def factorial(number):
"""
Define factorial certain number.
"""
if number <= 0:
return 1
return number * factorial(number-1)
print(factorial(50))
tes... | true |
cb912718e0b5494a24bde392beee25915729e409 | IlyaTroshchynskyi/python_education_troshchynskyi | /python_advanced/iterator_.py | 687 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Implements simple iterator
"""
class MyIterator:
"""
Implements simple iterator
"""
def __init__(self, value):
self.data = value
self.index = 0
def __getitem__(self, index):
return self.data[index]
def __iter__(self):
return ... | false |
e4b018aa44483d0eeed003818634cd3d785c2714 | Zahidsqldba07/python_exercises-1 | /exercise_7.py | 348 | 4.4375 | 4 | '''
Write a Python program to accept a filename from the user and print the extension of that. Go to the editor
Sample filename : abc.java
Output: java
'''
file_name = input('Enter file name with extension, example: abc.java')
if file_name == '':
file_name = 'abc.java'
name = file_name.split('.')[0]
ext = file_name... | true |
5f6bb76bc267af3a1ada99721556bc61637bc229 | anhuafeng123/python | /王者荣耀1.py | 336 | 4.125 | 4 | num = 0
while num<3:
weizhi = input("请输入一个位置")
if weizhi == "ABC":
print("后裔,黄忠,虞姬")
elif weizhi == "肉盾":
print("程咬金,亚瑟")
elif weizhi =="法师":
print("王昭君,妲己")
elif weizhi == "刺客":
print("兰陵王,阿科")
num+=1
| false |
31e0794ad9981a270497e4cd91c2b9dbe52ea0f3 | tohungsze/Python | /other_python/palindrome.py | 869 | 4.1875 | 4 | '''
check if a given word is a palindrome
'''
def main():
input = ['abcba', 'abc1cba', 'abcba ', 'abc1cba1']
for word in input:
if is_palindrome(word):
print('\'%s\' is a palindrome'%word)
else:
print('\'%s\' is a NOT palindrome'%word)
def is_palindrome(input): #... | true |
9ce0cec8b92e20b92a39e6e5d1af707c3db4fb27 | tohungsze/Python | /other_python/fibonacci.py | 1,139 | 4.28125 | 4 | # demonstrate fibonacci with and without caching
'''
# this is really slow, can't handle more than 30 ish numbers
def fibonacci_n(n):
if n == 0 or n ==1:
return 1
else:
return fibonacci_n(n-1) + fibonacci_n(n-2)
for i in range(1, 11):
print("fibonacci(", i, ") is:", fibonacci_n(i))
'''
''... | true |
ff7c0a83280f5080fcef88e288d96fbeda29289e | prashantkgajjar/Machine-Learning-Essentials | /16. Hierarchical Clustering.py | 2,929 | 4.15625 | 4 | # Hierarchical Clustering
'''
1. Agglomerative Hierarchical Clustering (Many single clusters to one single cluster)
1. Make each data point as a single point Cluster.
2. Take the two closest datapoints, and make them one cluster.
3. Take to closest clusters, and make them one cluster.
4. Repeat STEP 3 ... | true |
a37060def6b1333ff99fef976a78199d6b9603da | Jahishigh/TTR-python | /For Loop.py | 724 | 4.25 | 4 | # for prend une condition en variable, à chaque passage de la loop la variable va changer jusqu'à arriver à la condition
# la variable après le for peut avoir n'importe quel nom, c'est la condition final qui compte
for letter in "Hello":
print(letter)
list_de_value = [1, 2, 3]
for value_in_list in list_de_value:
... | false |
5f4d01e512104db3e264784891663d304937ed96 | HsiaoT/Python-Tutorial | /data_structure/Sorting/Selection_sort.py | 802 | 4.28125 | 4 |
# The selection sort algorithm sorts an array by repeatedly finding the
# minimum element (considering ascending order) from unsorted part and
# putting it at the beginning. The algorithm maintains two subarrays in a given array.
# Time complexity (average): O(n^2)
# Time complexit (best): O(n^2) (list already sor... | true |
d9bc14d8ae35cb2475bb92bcc8d99446694bc590 | sunDalik/Information-Security-Labs | /lab1/frequency_analysis.py | 2,879 | 4.3125 | 4 | import argparse
# Relative letter frequencies in the English language texts
# Data taken from https://en.wikipedia.org/wiki/Letter_frequency
theory_frequencies = {'A': 8.2, 'B': 1.5, 'C': 2.8, 'D': 4.3, 'E': 13.0, 'F': 2.2, 'G': 2.0, 'H': 6.1, 'I': 7.0,
'J': 0.15, 'K': 0.77, 'L': 4.0, 'M': 2... | true |
50d5314cda34ce36b4af6d37acdc81b3a87a17f8 | luckychummy/practice | /queueUsingStack.py | 1,222 | 4.28125 | 4 | from queue import LifoQueue
class MyQueue(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.q1=LifoQueue()
self.q2=LifoQueue()
def push(self, x):
"""
Push element x to the back of queue.
:type x: int
... | true |
0490aadbd1ad9867125da762b31557a61d901434 | tony-ml/algs200x-4 | /fibonacci-sum-last-digit/solution.py | 587 | 4.1875 | 4 | def fibonacciSumLastDigit(n):
KNOWN_VALUES = [0, 1, 2, 4, 7, 2, 0, 3, 4, 8,
3, 2, 6, 9, 6, 6, 3, 0, 4, 5,
0, 6, 7, 4, 2, 7, 0, 8, 9, 8,
8, 7, 6, 4, 1, 6, 8, 5, 4, 0,
5, 6, 2, 9, 2, 2, 5, 8, 4, 3,
8, 2, 1, 4, 6, 1, 8,... | false |
34f84a9883b3d57911b30aea2ab4470efa57e482 | AsharGit/Python-ICP | /Source/ICP-3/Employee.py | 1,137 | 4.28125 | 4 | class Employee:
num_employees = 0
total_salary = 0
def __init__(self, name, family, salary, department):
self.emp_name = name
self.emp_family = family
self.emp_salary = salary
self.emp_dept = department
self.increment(salary)
# Increment num_employees and total_... | true |
e50d45dda524f0471a01371f202cb2f7384ca07f | stompingBubble/Asteroids | /shape.py | 2,492 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Gruppuppgift: Asteroids - Objektorienterad Programmering
Nackademin IOT 17
Medverkande:
Isa Sand
Felix Edenborgh
Christopher Bryant
Stomme källkod:
Mark Dixon
"""
from abc import ABC, abstractmethod
import math
from point import Point
class Shape(ABC):
def __init__( self, x=0, y=0,... | true |
ffd1c6706c107f8fa4ca74bf33d36650046d0608 | thechemist54/PYth0n-and-JaVa | /Area calculation.py | 1,663 | 4.4375 | 4 |
#printing the options
print("Options:")
print("-"*8)
print("1. Area of Rectangle")
print("2. Area of Triangle")
print("3. Area of Circle")
print("4. Quit")
#assigning a value to flag
flag = False
#analyzing responses and displaying the respective information
#looping statement
while f... | true |
b116a4dad9540ecd3ca827cc96f1748ddb2ad20a | kasapenkonata/python | /13_09/task9.py | 384 | 4.21875 | 4 | import turtle
import math
#осталось центрировать
turtle.shape('turtle')
def draw(n):
R = 10*n
a = 2 * R * math.sin(2 * math.pi / n)
turtle.penup()
turtle.goto(-a/2, R)
turtle.pendown()
for i in range(n):
turtle.forward(a)
turtle.right(360/n)
return(0)
for ... | false |
a948e2106b7150b3a41ae7486415a8dc17842292 | AndrejLehmann/my_pfn_2019 | /Vorlesung/src/Basic/example4_2.py | 769 | 4.65625 | 5 | #!/usr/bin/env python3
# Example 4-2 Concatenating DNA
# store two DNA sequences into two variables called dna1 and dna2
dna1 = 'ACGGGAGGACGGGAAAATTACTACGGCATTAGC'
dna2 = 'ATAGTGCCGTGAGAGTGATGTAGTA'
# print the DNA onto the screen
print('Here are the original two DNA sequences:')
print(dna1)
print(dna2)
# concaten... | true |
e2802f46eeb773f497cab112e4a74fe96b763f8f | pravalikavis/Python-Mrnd-Exercises | /finaltest_problem3.py | 2,052 | 4.34375 | 4 | __author__ = 'Kalyan'
max_marks = 25
problem_notes = '''
For this problem you have to implement a staircase jumble as described below.
1. You have n stairs numbered 1 to n. You are given some text to jumble.
2. You repeatedly climb down and up the stairs and on each step k you add/append starting k chars fr... | true |
2873efc5e996028da3dbe1d1a3a70e8046511c65 | pankajdahilkar/python_codes | /prime.py | 268 | 4.1875 | 4 | def isPrime(a=0):
i=2
if a==0 :
return 0
while(i<a):
if a%i==0:
return 0
i=i+1
return 1
x=int(input("Enter The number : "))
if(isPrime(x)):
print(x, "is Prime number ")
else :
print(x," is not Prime number")
| true |
b87ef01cecfa2e6d4b86866f75cfd256b24bac5f | SMKxx1/Very-Very-Very-Basic-1-Plus-1-1-Plus-0-Program | /Very Very Very Basic 2.py | 2,798 | 4.21875 | 4 | def student1(eng_marks1, acc_marks1, ip_marks1):
dic_std_name1 = {'eng':eng_marks1,'accounts':acc_marks1,'ip':ip_marks1}
av1 = (eng_mark1 + ip_mark1 + acc_mark1) / 3
return av1 #Return command is explained in line 43
def student2(eng_marks2, acc_marks2, ip_marks2):
dic_std_name2 = {'eng':eng_marks2,'ac... | false |
6ec568987a0315308f70ea53a710a341e15a5a2a | Camilo1318/EjerciciosPython | /Cadenas/ejercicio3.py | 645 | 4.625 | 5 | #Escribir un programa que pregunte el nombre del usuario en la consola y después de que el usuario lo introduzca muestre por pantalla <NOMBRE> tiene <n> letras, donde <NOMBRE> es el nombre de usuario en mayúsculas y <n> es el número de letras que tienen el nombre.
#Cristian Pérez
nombre = input("Ingrese su nombre: ")... | false |
44894e050247f38dc88e2184ed65b8e7fc3e868e | pravishbajpai06/Projects | /6.py | 1,483 | 4.1875 | 4 |
#6-Change Return Program - The user enters a cost and then the amount of money given. The program will figure out the change and the number of quarters, dimes, nickels, pennies needed for the change.
import math
cent=0.01
penny=0.01
nickel=0.05
dime=0.1
quarter=0.25
do=1
cost=float(input("Enter the costt"))
amount=flo... | true |
b2b10777497bf79f6353bd04ac19ddb0d69fc281 | 0x0all/coding-challenge-practices | /python-good-questions/reverse_vowels.py | 542 | 4.28125 | 4 | """
The Problem:
Write a function to reverse the vowels in a given string
Example:
input -> output
"hello elephant" -> "halle elophent"
"abcde" -> "ebcda"
"abc" -> "abc"
"""
def reverse_vowels(s):
vowels = 'aeiou'
res = list(s)
pos = [index for index, char in enumerate(s) if char in vowels]
... | true |
d8b0261cbd5a4534ef7012794164d4c063cc2ecc | Shilla-crypto/Simple-BMI-calculator | /app.py | 1,638 | 4.28125 | 4 | import datetime
print('Hello world!')
print('*' * 25)
print("Python-3.7.3")
print("*" * 25)
def print_python():
print("__")
print("L"), print("__")
print("I"), print("__")
print("N"), print("__")
print("U"), print("__")
print("X"), print("__")
print_python()
now = datetime.datetime.now()
... | false |
6736443ed68910ee2e4d2d665da47667024e19c3 | vasanth9/10weeksofcp | /basics/classesandobjects.py | 1,491 | 4.21875 | 4 | #classes and objects
"""
Python is an object oriented programming language.
Almost everything in Python is an object, with its properties and methods.
A Class is like an object constructor, or a "blueprint" for creating objects.
"""
class myclass:
x=5
p1=myclass()
print(p1.x)
"""
All classes have a function cal... | true |
6bc780d508f837ca9c0428fa160e72932b2060c8 | futurice/PythonInBrowser | /examples/session1/square.py | 837 | 4.5625 | 5 | # Let's draw a square on the canvas
import turtle
##### INFO #####
# Your goal is to make the turtle to walk a square on the
# screen. Let's go through again turtle commands.
# this line creates a turtle to screen
t = turtle.Turtle()
# this line tells that we want to see a turtle shape
t.shape("turtle")
# this lin... | true |
14207390dc1852453b97d8922b1f8b3607f26e64 | futurice/PythonInBrowser | /examples/session1/wall.py | 998 | 4.46875 | 4 | # Goal: help the turtle to find a hole in the wall
# We need to remember to import a turtle every time we want
# to use it.
import turtle
##### INFO #####
# The following code draws the wall and the target. You can
# look at the code but to get to the actual exercise, scroll
# down.
# Here we create a wall to the m... | true |
5f66bea9207f8a7149844204245dc09345a636aa | futurice/PythonInBrowser | /examples/session3/function.py | 2,912 | 4.8125 | 5 | # Computing with functions
import turtle
t = turtle.Turtle()
##### INFO #####
# Fucntions can be used for computing things.
#
# As an example, let's consider computing an area of a
# circle. You may remember form a math class that the area
# of a circle is computed by multiplying the radius of the
# circle by itself ... | true |
35c92a9c66af8bcf6ee2eeec1eb9f3743e375091 | ShaneKoNaung/Python-practice | /stack-and-queue/linked_list_queue.py | 1,222 | 4.25 | 4 | ''' implementing queue using linked-list'''
class LinkedListQueue(object):
class Node(object):
def __init__(self, data, next=None):
self._data = data
self._next = next
def __init__(self):
self._head = None
self._tail = None
self._size = 0
def __len... | true |
2f9976e9ae634c5d370e0a45e4484a9c63e7d363 | ShaneKoNaung/Python-practice | /stack-and-queue/linked_list_stack.py | 1,171 | 4.125 | 4 | ''' Implementation of stack using singly linked list '''
class LinkedListStack(object):
class Node(object):
def __init__(self, data, next=None):
self._data = data
self._next = next
def __init__(self):
''' create an empty stack '''
self._head = None
sel... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.