blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
289cc536fb1d4a594155fd8f2ae37bb669feba57 | vishwasanavatti/Interactive-Programming-with-python | /Interactive Programming with python/second_canvas.py | 397 | 4.21875 | 4 | # Display an X
###################################################
# Student should add code where relevant to the following.
import simplegui
# Draw handler
def draw(canvas):
canvas.draw_text("X",[96, 96],48,"Red")
# Create frame and assign callbacks to event handlers
frame=simplegui.create_frame("Test", 200,... | true |
fd503ae0aae52dff9f8d209d72ff86af9943ec63 | j0sht/checkio | /three_words.py | 467 | 4.21875 | 4 | # You are given a string with words and numbers separated by whitespaces.
# The words contains only letters.
# You should check if the string contains three words in succession.
import re
def checkio(s):
return re.search(r'[a-zA-Z]+\s[a-zA-Z]+\s[a-zA-Z]+', s) != None
print(checkio("Hello World hello") == True)
p... | true |
c2991ed8c969b799c5458bac865e478122ec04af | panmari/nlp2014 | /ex1/task3.py | 334 | 4.15625 | 4 | #!/usr/bin/python3
print("Please enter an integer")
try:
input_int = eval(input())
except NameError as e:
print("Oops, that was not an integer!")
exit(1)
print("The first {} numbers of the fibonacci sequence are: ".format(input_int))
fib = [1,1]
for i in range(input_int):
fib.append(fib[-1] + fib[-2]... | true |
52d504ec91089e3b0eb747b99bf580e08883dc73 | cesarg01/AutomateBoringPythonProjects | /collatz.py | 973 | 4.4375 | 4 | # This program take any natural number n. If n is even, divide it by 2 to get n/2,
# if n is odd multiply it by 3 and add 1 to obtain 3n+1. Repeat the process indefinitely.
# The conjecture is that no matter what number you start with, you will always eventually reach 1.
# This is known as the Collatz conjecture.
d... | true |
729f00cf4e463f39588ac965b873b52ba9baf5c4 | CWMe/Python_2018 | /Python_Learn_Night/Python_Dictionaries.py | 729 | 4.46875 | 4 | # Dictionaries in Python
# { }
# Map data type in Python
# key : value paris for data.
my_dictionary = {"name": "CodeWithMe", "location": "library", "learning": "Python"}
# dictionaries may not retain the order in which they were created (before python 3.6.X).
# print(my_dictionary)
# accessing VALUES from a diction... | true |
ac4062b52a08a61400ae7eb41b1554b907b23887 | thewchan/python_oneliner | /ch3/lambda.py | 637 | 4.28125 | 4 | """Lambda function example.
Create a filter function that takes a list of books x and a minimum rating y
and returns a list of potential bestsellers that have higher than minimum
rating, y' > y.
"""
import numpy as np
books = np.array([['Coffee Break Numpy', 4.6],
['Lord of the Rings', 5.0],
... | true |
b9f437acb644e63dbebc2aba451e5f90d7d8c854 | Oyanna/Decode_Python59 | /homeworks/hw_GUI_Zhuldyz.py | 1,269 | 4.125 | 4 | from math import pi
from tkinter import *
window = Tk()
def square(r):
S = pi*r*r
text = "Площадь круга равна %s \n " %(S)
return text
def inserter(value):
output.delete("0.0", "end")
output.insert("0.0", value)
def handler():
try:
r_val = float(r.get())
inserter(square(r_val)... | false |
14f266de9648b45e70a6d58b35e3f44be4611047 | Adriana-ku06/programming2 | /pythom/exercise26.py | 2,959 | 4.125 | 4 | #Adriana ku exercise 26
from sys import argv
print("How old are you?", end=' ')
age = input()
print("How tall are you?", end=' ')
tall=input() #undeclared tall variable
print("How much do you weigh?", end=' ')#first error missing closing parentheses
weight = input()
print(f"So, you're {age} old, {tall} height... | true |
b70e39bcc40473503c1a2cf169c3a7d28d552c92 | Vladigors/pycharm_new | /package1/nums1.py | 211 | 4.15625 | 4 | range(10)
list(range(1, 10))
for i in range(10):
print(i, end= '')
for i in range(3, 20):
print(i, end= '')
for i in range (5, 25, 3):
print(i, end= '')
for i in range(10, 20):
print(i, end= '')
| false |
b7d01a00f0161216a6e5205b31638c9a8ac0a8ca | DavidM-wood/Year9DesignCS4-PythonDW | /CylinderVolCon.py | 377 | 4.21875 | 4 | import math
print("This program calculates the volume of")
print("a cylinder given radius and height")
r = input("what is the radius: ")
r = float(r)
h = input("what is the height: ")
h = float(h)
v = math.pi*r*r*h
v = round(v,3)
print("Given")
print(" radius = ",r," units")
print(" height = ",h," units")
print("... | true |
1a49be8a93de2ed7e8f6136933bcb194d62c168a | DavidM-wood/Year9DesignCS4-PythonDW | /LoopDemo.py | 1,509 | 4.25 | 4 | #A loop is a programjnf structure that can repeat a section of code.
#A loop can run the same coede exactly over and over or
#with domr yhought it can generate a patter
#There are two borad catagories of loops
#Conditional loops: These loop as long as a conditon is true
#Counted Loops (for): These loop usikng a cou... | true |
42959799e73a040a42e2757b422b45313ff4c848 | marcelo-py/Exercicios-Python | /exercicios-Python/desaf033.py | 844 | 4.15625 | 4 | #maior e menor numero
v1 = int(input('digite um numero '))
v2 = int(input('digite o segundo numero '))
v3 = int(input('digite o terceiro numero '))
if v1<v2 and v1<v2:
menor = v1
print('O menor é', v1)
if v2<v1 and v2<v3:
menor = v2
print('O menor é', v2)
if v3<v1 and v3<v2:
menor = v3
print('O ... | false |
9b7fa70f9b7c0cf967d63a5ea24afdaa38e5acdd | shach934/leetcode | /leet114.py | 974 | 4.21875 | 4 | 114. Flatten Binary Tree to Linked List
Given a binary tree, flatten it to a linked list in-place.
For example,
Given
1
/ \
2 5
/ \ \
3 4 6
The flattened tree should look like:
1
\
2
\
3
\
4
\
... | true |
5cfb176a07bdb5473c6317586573525306cba589 | shach934/leetcode | /leet403.py | 2,213 | 4.1875 | 4 | 403. Frog Jump
A frog is crossing a river. The river is divided into x units and at each unit there may or may not exist a stone. The frog can jump on a stone, but it must not jump into the water.
Given a list of stones' positions (in units) in sorted ascending order, determine if the frog is able to cross the ri... | true |
65dc7d8c342a8da41493e7dfc1459e1d468359d6 | Larry-Volz/python-data-structures | /17_mode/mode.py | 1,038 | 4.21875 | 4 | def mode(nums):
"""Return most-common number in list.
For this function, there will always be a single-most-common value;
you do not need to worry about handling cases where more than one item
occurs the same number of times.
SEE TEACHER'S SOLUTION
He uses a dictionary, {}.get(num, 0)+1 to ad ... | true |
24f14855d4cc1565f6dc94c9318315b7ea3c25dc | biodataprog/code_templates | /Regexp/Motif_Match_Bsub.py | 1,769 | 4.3125 | 4 | #!/usr/bin/env python3
#Python code to demonstrate pattern matching
# import the regular expression library
import re
# a random DNA sequence generator
def read_DNA (file):
DNA = ""
fasta_pat = re.compile("^>")
with open(file, 'r') as f:
seenheader = 0
for line in f:
if fasta... | false |
843b0e4e5ae83c783df4ddb4518f56bd974a1ccf | abigailshchur/KidsNexus | /hangman_complete.py | 2,609 | 4.125 | 4 |
import random # we need the random library to pick a random word from list
# Function that converts a list to a string split up be delim
# Ex) lst_to_str(["a","b","c"],"") returns "abc"
# Ex) lst_to_str(["a","b","c"]," ") returns "a b c"
# Ex) lst_to_str(["a","b","c"],",") returns "a,b,c"
def lst_to_str(lst, delim):
... | true |
6b45fe344565cb148d4b0baa4b3ed2b6fe75d583 | heasleykr/Algorithm-Challenges | /recursion.py | 843 | 4.25 | 4 | # Factorials using recursion
def fact(n):
# base. If n=0, then n! = 1
if n == 0:
return 1
# else, calculate all the way until through
return n*fact(n-1)
# one liner
# return 1 if not n else n*fact(n-1)
def fact_loop(n):
# base case return n if 0
# if n == 0:
# return ... | true |
abc9a6b5424c0ef2e574c86f995ef66061746af7 | amarbecaj/MidtermExample | /zadatak 3.py | 1,434 | 4.15625 | 4 | """
=================== TASK 3 ====================
* Name: Negative and Non-Negative Elements
*
* Write a script that will populate a list with as
* many elements as user defines. For taken number
* of elements the script should take the input from
* user for each element. You should expect that
* user will always... | false |
f374c8b57722d4677cbf9cc7cde251df8896b33d | sreerajch657/internship | /practise questions/odd index remove.py | 287 | 4.28125 | 4 | #Python Program to Remove the Characters of Odd Index Values in a String
str_string=input("enter a string : ")
str_string2=""
length=int(len(str_string))
for i in range(length) :
if i % 2 == 0 :
str_string2=str_string2+str_string[i]
print(str_string2)
| true |
a2807475320a5bb3849a943dbe5dd9f9331254ed | sreerajch657/internship | /practise questions/largest number among list.py | 259 | 4.34375 | 4 | #Python Program to Find the Largest Number in a List
y=[]
n=int(input("enter the limit of list : "))
for i in range(0,n) :
x=int(input("enter the element to list : "))
y.append(x)
y.sort()
print("the largest number among list is : %d "%(y[-1]))
| true |
fdd72acf5565bdee962fed5471249461843d01ab | Neil-C1119/Practicepython.org-exercises | /practicePython9.py | 1,511 | 4.28125 | 4 | # This program is a guessing game that you can exit at anytime, and it will
# keep track of the amount of tries it takes for the user to guess the number
# Import the random module
import random
# Define the function that returns a random number
def random_num():
return random.randint(1, 10)
# Self exp... | true |
2c67dd011e851c1e79a23004908cf69bc2c34607 | ifegunni/Cracking-the-coding-interview | /arrays1.7.py | 1,923 | 4.3125 | 4 | # Rotate Matrix: Given an image represented by an NxN matrix, where each pixel in the image is 4
# bytes, write a method to rotate the image by 90 degrees. Can you do this in place?
#This solution is my O(n2) solution
def rotate(matrix):
newMatrix = [row[:] for row in matrix] #we have to copy the matrix so we do... | true |
238ac35d263a55d451dfd2b0f3fb1cfe4d12363d | ifegunni/Cracking-the-coding-interview | /arrays1.6.py | 2,910 | 4.25 | 4 | # String Compression: Implement a method to perform basic string compression using the counts
# of repeated characters. For example, the string aabcccccaaa would become a2blc5a3. If the
# "compressed" string would not become smaller than the original string, your method should return
# the original string.You can assum... | true |
a571e0e9e507b15d778cf7c7210864c47422c138 | kehsihba19/MINI-PYTHON-Beginner-Project | /Hangman.py | 1,190 | 4.28125 | 4 | import random
def word_update(word, letters_guessed):
masked_word = ""
for letter in word:
if letter in letters_guessed:
masked_word += letter
else: masked_word += "-"
print( "The word:", masked_word)
# List of words for the computer to pick from
words = ("basketball", "football"... | true |
650e6537431e2e52e257f8ba04ee285f9ed06405 | UmVitor/python_int | /ex016.py | 238 | 4.15625 | 4 | #Crie um programa que leia um numero real
#Qualquer pelo teclado e mostre na tela
#a sua porção inteira
import math
num = float(input('Digite um numero: '))
print('O numero {} tem a parte inteira {}'.format(num,math.floor(num)))
| false |
8ea2aa3c42278988534f88c66b818b8c25a8ba82 | UmVitor/python_int | /ex100.py | 758 | 4.1875 | 4 | #Faça um programa que tenha uma lista chamada numeros e duas funções
#chamadas sorteia() e somaPar(). A primeira função vai sortear 5 numeros
#e coloca-los dentro de uma lista e a segunda função vai mostrar a soma entre
#todos os valores pares sorteados pela função anterior
from random import randint
lista ... | false |
5137ae95f22550277269ebcaa1d5977f702cf840 | UmVitor/python_int | /ex072.py | 594 | 4.3125 | 4 | #Crie um programa que tenha uma tupla totalmente preenchida com uma
#contagem por extenso, de zero ate vinte.
#Seu programa deverá ler um numero pelo teclado(entre 0 e 20) e mostrálo
#por extenso
extenso = ('zero', 'um','dois','três','quatro','cinco','seis','sete','oito','nove','dez','onze','doze','treze','catorze'... | false |
0071380236913bd4c168c488e35e4ef229d5d457 | UmVitor/python_int | /ex028.py | 438 | 4.125 | 4 | #escreva um programa que faça o computador 'pensar' em um numero inteiro
#entre 0 e 5 e peça para o usuario tentar descobrir qual foi o número escolhido
#pelo computador.
import random
from time import sleep
n1 = int(input('Digite um numero: '))
n2 = random.randint(1,5)
print ('Pensando...')
sleep(2)
print('... | false |
9afd9a445eb308c45d00b446d46b9231306217b5 | UmVitor/python_int | /ex101.py | 641 | 4.125 | 4 | #Crie um programa que tenha uma função chamada voto() que vai receber como
#parametro o ano de nascimento de uma pessoa, retornando um valor literal
#indicando se uma pessoa tem voto Negado, opcional ou obrigatorio
from datetime import date
def voto(i):
n1 = date.today().year
idade = n1 - i
... | false |
236afd3162a72f9c1ee32e4b9f006d77ca2ca4d3 | UmVitor/python_int | /ex026.py | 577 | 4.1875 | 4 | #Faca um programa que leia uma frase pelo teclado e mostre
#Quantas vezes aparece a letra 'a'
#em que posição ela aparece a primeira vez
#em que posição ela aparece a ultima vez
frase = str(input('Digite uma frase: ')).lower().strip()
print(frase)
print('Nesta frase a letra a aparece {} vezes!'.format(frase.cou... | false |
bdd5560416f0615534c7be04edac65b988c804a0 | liviaandressa/exercicios-curso-em-video | /Testes_aulas_guanabara/Desafio_jogo_da_adivinhação.py | 1,123 | 4.5 | 4 | '''escreva um programa que faça o computador pensar em um número inteiro entre 0 e 5
e peça para o usuáro tentar descobrir qua foi o número escolhido pelo computador.
o programa deverá escrever na tela se o usuário venceu ou perdeu'''
'''
1° solução
import random
print('Vou pensar em um número entre 0 e 5. Tente adi... | false |
6c00f55d6f5c28b24afd48cadf14bfee4add3c26 | r121196/Python_exercise | /caluclator/simple calculator.py | 668 | 4.1875 | 4 | operation = input('''
type the required maths operation:
+ for addition
- for substraction
* for multiplication
/ for division
''')
n1 = int(input('Enter the first number: '))
n2 = int(input('Enter the second number: '))
if operation == '+':
print ('{} + {} = '. format(n1, n2))
print (n1 + n2)
... | true |
f32ad9099e69b7a8a70715e988aa2dde959778bf | lengau/dailyprogrammer | /233/intermediate.py | 2,816 | 4.125 | 4 | #!/usr/bin/env python3
# Daily Programmer #233, Intermediate: Conway's Game of Life
# https://redd.it/3m2vvk
from itertools import product
import random
import sys
import time
from typing import List
class Cell(object):
"""A single cell for use in cellular automata."""
def __init__(self, state: str):
... | true |
2f395c7039ae26aa8c75b03f3727cd0c9235bcf5 | Pavan-443/Python-Crash-course-Practice-Files | /chapter 8 Functions/useralbums_8-8.py | 570 | 4.21875 | 4 | def make_album(artist_name, title, noof_songs=None):
"""returns info about music album in a dictionary"""
album = {}
album['artist name'] = artist_name.title()
album['song title'] = title.title()
if noof_songs:
album['no of songs'] = noof_songs
return album
while True:
print('\ntype... | true |
f390c30e06bdacc7e29d38fc519c95fb478bd924 | zemery02/ATBS_notes | /Lesson_Code/hello.py | 631 | 4.125 | 4 | #! python3
# This program says hello and asks for my name
print('Hello World!')
print('What is your name?') #ask for their name
myName = input()
print('It is good to meet you, ' + myName)
print('The length of your name is:')
print(len(myName))
print('What is your age?') #ask for their age
myAge = input()
print('You ... | true |
4f8383ae5d0439bb9972f2852623552e65a06527 | vik13-kr/telyport-submission | /api/build_api/Q-2(Reverse character).py | 494 | 4.3125 | 4 | '''Reverse characters in words in a sentence'''
def reverse_character(p_str):
rev_list = [i[::-1] for i in p_str] #reversed characters of each words in the array
rev_string = " ".join(map(str,rev_list)) #coverted array back to string
return rev_string
n_str = 'My name is Vikas... | true |
ac9e55e127c2972a737cdbdea7db49847381a993 | DonLiangGit/Elements-of-Programming | /data_structure/Linkedlist_Node.py | 1,161 | 4.1875 | 4 | # define a Node class for linked list
# __name__ & __main__
# http://stackoverflow.com/questions/419163/what-does-if-name-main-do
# http://stackoverflow.com/questions/625083/python-init-and-self-what-do-they-do
class Node:
def __init__ (self,initdata):
self.data = initdata
self.next = None
def getData (self):
... | true |
12d289806c1323503a8a6040bc0a14f8d440711f | samuelbennett30/FacePrepChallenges | /Lists/Remove Duplicates.py | 801 | 4.40625 | 4 | '''
Remove the Duplicate
The program takes a lists and removes the duplicate items from the list.
Problem Solution:
Take the number of elements in the list and store it in a variable. Accept the values into the list using a for loop and insert them into the list. Use a for loop to traverse through the elements of the ... | true |
390aef3387103d3c30e03d19ff5dcf9985abee3b | tushar8871/python | /dataStructure/primeNumber.py | 1,689 | 4.125 | 4 | #generate prime number in range 0-1000 and store it into 2D Array
#method to create prime number
def primeNumber(initial,end):
#create a list to store prime number in 0-100,100-200 and so-on
resultList=[]
try:
#initialize countt because when we generate prime number between 0-100 then we have to ini... | true |
d43783ac3758262be6e636db5da6a2725a1c218a | tushar8871/python | /functioalProgram/stringPermutation.py | 1,002 | 4.28125 | 4 | #Generate permutation of string
#function to swap element of string
def swap(tempList,start,count):
#swapping element in list
temp=tempList[start]
tempList[start]=tempList[count]
tempList[count]=temp
#return list of string
return tempList
#generate permutation of string
def strPermutation(Str,... | true |
8973a64b33c9587d2b2f5dd4d1aaffcd54d10e17 | bezdomniy/unsw | /COMP9021/Assignment_1/factorial_base.py | 775 | 4.25 | 4 | import sys
## Prompts the user to input a number and checks if it is valid.
try:
input_integer = int(input('Input a nonnegative integer: '))
if input_integer < 0:
raise ValueException
except:
print('Incorrect input, giving up...')
sys.exit()
integer=input_integer
## Prints factorial base of 0... | true |
eb945c57d13c1364f773dd2bf64c3afcacf865ea | gtanubrata/Small-Fun | /return_day.py | 1,129 | 4.125 | 4 | '''
return_day(1) # "Sunday"
return_day(2) # "Monday"
return_day(3) # "Tuesday"
return_day(4) # "Wednesday"
return_day(5) # "Thursday"
return_day(6) # "Friday"
return_day(7) # "Saturday"
return_day(41) # None
'''
days = {1: "Sunday", 2: "Monday", 3: "Tuesday", 4: "Wednesday", 5: "Thursday", 6: "Friday", 7: "S... | true |
f306b95eff6714bebe60f7b9a3332ec9f1399853 | jackh423/python | /CIS41A/CIS41A_UNITC_TAKEHOME_ASSIGNMENT_1.py | 2,654 | 4.25 | 4 | """
Name: Srinivas Jakkula
CIS 41A Fall 2018
Unit C take-home assignment
"""
# First Script – Working with Lists
# All print output should include descriptions as shown in the example output below.
# Create an empty list called list1
# Populate list1 with the values 1,3,5
# Create list2 and populate it with the valu... | true |
af8dd324cd12deb2647eb541822000c9b377c99b | xurten/python-training | /tips/tip_54_use_lock_for_threads.py | 1,317 | 4.125 | 4 | # Tip 54 use lock for threads
from threading import Thread, Lock
HOW_MANY = 10 ** 5
class Counter:
def __init__(self):
self.count = 0
def increment(self, offset):
self.count += offset
def worker(index, counter):
for _ in range(HOW_MANY):
counter.increment(1)
def thread_exampl... | true |
a7880e35154bb5b0da2498d2907b60a3ecc3f6bc | rohitkrishna094/Data-Structures-And-Algorithms_old | /Problems/Arrays/ReversingArray.py | 851 | 4.4375 | 4 | '''
This is a program to reverse an array or list
'''
def reverse(lst):
return lst.reverse()
# using built in lib functions
l = list([1, 2, 3, 4])
r = list(reversed(l))
print(l, r)
# lst[::-1] # another way to reverse using slicing
# without using built in functions
def reverse_mine(lst):
endIndex = ... | false |
5cdb5e79bcf34192624b2ff88d0a585d60406636 | saddzoe/insurance-calculator | /README.py | 1,348 | 4.375 | 4 | # insurance-calculator
# This is a mini project from codecademy
print(middle_element([5, 2, -10, -4, 4, 5]))
names = ["Mohamed", "Sara", "Xia", "Paul", "Valentina", "Jide", "Aaron", "Emily", "Nikita", "Paul"]
insurance_costs = [13262.0, 4816.0, 6839.0, 5054.0, 14724.0, 5360.0, 7640.0, 6072.0, 2750.0, 12064.0]
# Add y... | false |
28f778bd069323b1883006a8c69aa9c8864242e1 | pengxingyun/learnPython | /basePython/listAndTuple.py | 1,216 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# list 有序集合类型 相当于数组Array
names = ['aaa', 'bbb', 'ccc']
print(names) # ['aaa', 'bbb', 'ccc']
# len 获取list元素个数
print(len(names))
# 索引访问list元素
print(names[0]) # 第一个
print(names[len(names) - 1]) # 最后一个
print(names[-1]) # 最后一个
print(names[-2]) # 倒数第二个
# 追加元素到末尾
names.appen... | false |
ff37f855eacfc27e1a7b1cd5247facac93f4b3c8 | jack-evan/python | /tuples.py | 239 | 4.21875 | 4 | #this is a tuple
someval = ("one","two",345,45.5,"summer")
#print tuple
print someval #prints tuple
print someval[0] #prints first element of the tuple
print someval[2:] #prints third element and on
print someval * 2 #prints tuple twice
| true |
15498baa6391c1f3976f9ac752e66028ae67c632 | jann1sz/projects | /school projects/python/deep copy of 2d list.py | 1,215 | 4.25 | 4 | def deep_copy(some_2d_list):
#new_copy list is the list that holds the copy of some_2d_list
new_copy = []
#i will reference the lists within some_2d_list, and j will reference the
#items within each list.
i = 0
j = 0
#loop that creates a deep copy of some 2d list
for i in ... | true |
cd6d6f7b6b9b4e5e7fc39d1fb56c0995147d33cc | mskaru/LearnPythonHardWay | /ex15.py | 791 | 4.3125 | 4 | # -*- coding: utf-8 -*-
from sys import argv
# script = py file name that I want to run
# filename = the txt or word or whichever other file type
# i want to read the information from
script, filename = argv
# command that calls the content of the file as txt
txt = open(filename)
print "Here's your file %r:" % filen... | true |
87e1314624ce2cfd7672d3f8781b94135aca3796 | rumbuhs/Homeworks | /HW6/hw6_t2.py | 1,046 | 4.4375 | 4 | from math import pi
from math import sqrt
def calculator(shape):
"""
This funktion will find the
square of a rectangle, triangle or circle.
depending on the user's choice.
Input: name of shape
Otput: the square of the shape
"""
shape = shape.upper()
if shape == "RECTANGLE":
... | true |
42959f7f25f93f11e5edf0f200d0f74b2dcf724d | Hunt-j/python | /PP02.py | 546 | 4.15625 | 4 | num = int(input("Pick a number:"))
check = int(input("Pick a second number:"))
if (num % 2 == 0):
print("The number you've chosen is even")
else:
print("The number you've chosen in odd")
if (num % 4 ==0):
print("The number you've chose is divisible by 4")
else:
print("The number you've choses is not d... | true |
529662305609ad9c36fb41a6466c7c90fe4590e8 | FabioZTessitore/laboratorio | /esercizi/liste/reverse.py | 353 | 4.4375 | 4 | # reverse.py
# Riscrive una stringa al contrario
print('Reverse the string\n')
text = input('Enter the message: ')
# crea una lista dalla stringa `text`
# quindi inverte l'ordine delle lettere
# quindi unisce le lettere in una nuova stringa
letters = [letter for letter in text]
letters.reverse()
textReversed = ''.j... | false |
bd320410d6462d80f43620755a40495baa53bc0b | sshridhar1965/subhash-chand-au16 | /FactorialW3D1.py | 201 | 4.34375 | 4 |
# Factorial of a number
num = int(input("Please Enter a number whose factorial you want"))
product=1
while (num>=1):
product = num*product
num = num-1
print("The Factorial is ",product) | true |
77d83b8729fe087a1a38ced864ac363ff53c4165 | jeffreyc86/python-practice | /sequenceoperators.py | 614 | 4.21875 | 4 | string1 = "he's "
string2 = "probably "
string3 = "rooting "
string4 = "for the "
string5 = "knicks"
print(string1 + string2 + string3 + string4 + string5)
# above is same as
print("he's " "probably " "rooting " "for the " "knicks ")
print("hello " * 5)
# hello hello hello hello hello
# print("Hello " * 5 + 4) - wil... | false |
771576a2ea6f1e99200c242e3d53ea510e4a51e5 | DanielVasev/PythonOnlineCourse | /Beginner/most_common_counter.py | 1,244 | 4.34375 | 4 | """
How to count most common words in text
"""
from collections import Counter
text = "It's a route map, but it's only big enough to get to the starting point. Many businesses have been asking\
when they will be allowed to reopen. Now they have some rough indication, pencilled in to the calendar, but far from\
a... | true |
4e2005cd521e0d50e46f64e26530224ceedd53c8 | 515ek/PythonAssignments | /Sample-2-solutions/soln20.py | 1,343 | 4.3125 | 4 | ## Name: Vivek Babu G R
## Date: 26-07-2018
## Assignment: Sample 2
## Question: A simple substitution cipher is an encryption scheme where each letter in an alphabet to replaced by a different letter in the same alphabet
## with the restriction that each letter's replacement is unique. The template for this questio... | true |
cd4e8d94167d991aacdc132a2ca3f22a107e4c16 | 515ek/PythonAssignments | /Sample-1-solutions/soln18.py | 385 | 4.1875 | 4 | ## Name: Vivek Babu G R
## Date: 26-07-2018
## Assignment: Sample 1
## Question: Python Program to Take in a String and Replace Every Blank Space with Hyphen.
############################################################################################
str1 = input('Enter the string\n')
str2 = ''
for s in str1.split(' '... | true |
a455f7a6c96aff192219ef358f796c3f608b52e1 | AMANBAIN/First-Github-Repo | /PythonCalculator.py | 1,241 | 4.21875 | 4 | def menu():
print("\nHello User")
print("1. ADD")
print("2. SUBTRACT")
print("3. MULTIPLY")
print("4. DIVIDE")
print("5. EXIT")
pick = int(input("Enter a Choice: "))
return pick
def main():
choice = menu()
while choice != 5:
if choice == 1:
# adds two number... | false |
64d72e038c18c73bcc5ead26b026a6c3d4826e3d | ClntK/PaymentPlanner | /paymentPlanner.py | 2,030 | 4.1875 | 4 | """
File: paymentPlanner.py
Author: Clint Kline
Last Modified: 5/30/2021
Purpose: To Estimate a payment schedule for loans and financed purchases.
"""
# input collection
price = (float(input("\nPurchase Price: ")))
months = (float(input("Loan Duration(in months): "))) # example "12" for one year, "120" for 10 y... | true |
9731d705b7cb3fdf08c13bb6790daac74765d754 | ManavParmar1609/OpenOctober | /Data Structures/Searching and Sorting/MergeSort.py | 1,275 | 4.34375 | 4 | #Code for Merge Sort in Python
#Rishabh Pathak
def mergeSort(lst):
if len(lst) > 1:
mid = len(lst) // 2
#dividing the list into left and right halves
left = lst[:mid]
right = lst[mid:]
#recursive call for further divisions
mergeSort(left)
mergeSort(right)
... | true |
b44d519c3cf9f4dd9f741d710eff3447d9991a22 | ManavParmar1609/OpenOctober | /Algorithms/MemoizedFibonacci.py | 927 | 4.3125 | 4 | """
@author: anishukla
"""
"""Memoization: Often we can get a performance increase just by
not recomputing things we have already computed."""
"""We will now use memoization for finding Fibonacci.
Using this will not only make our solution faster but also
we will get output for even larger values such as 1... | true |
f107b6b4d03e7557bfd26597d75acd953d1e5cda | EvgenyKirilenko/python | /herons_formula.py | 320 | 4.4375 | 4 | #this code calculates the area of triangle by the length of the given sides
#by the Heron's formula
from math import sqrt
a=int(input("Enter side A:"))
b=int(input("Enter side B:"))
c=int(input("Enter side C:"))
p=float((a+b+c)/2)
s=float(sqrt(p*(p-a)*(p-b)*(p-c)))
print ("Area of the triangle is : ",s)
| true |
c0e3604aff31861c0e38f030e91b3a5b82c29049 | pratikpwr/Python-DS | /strings_6/lenghtOfStrings.py | 329 | 4.34375 | 4 | # length of string can be calculated by len()
name = input("Enter string: ")
length_of_string = len(name)
print("string:", name)
print("length of string:", length_of_string)
# max and min of String or others
maxi = max(name)
mini = min(name)
print("maximum:", maxi + "\nminimum:", mini)
# slicing a String
print(na... | true |
427601166ccc5624317e9fea05adc163236321ae | ARAV0411/HackerRank-Solutions-in-Python | /Numpy Shapes.py | 257 | 4.1875 | 4 | import numpy
arr= numpy.array(map(int, raw_input().split())
print numpy.reshape(arr, (3,3)) # modifies the shape of the array
#print arr.shape() --- prints the rows and columns of array in tuples
# arr.shape()= (3,4) --- reshapes the array
| true |
1c9ab653a40c59ba50f04719d8950a2656fdd6f5 | ybharad/DS_interview_prep_python | /prime_factors.py | 736 | 4.28125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 26 20:43:26 2020
@author: yash
this function calculates the factors of any number which are only prime numbers
it reduces the factors of a number to its prime factors
"""
import math
def primeFactors(n):
# Print the number of two's that divid... | true |
8e132be5f0cc44dd9f44161c9516afd8b61c0e67 | Andrey-Gurevich/Course-Python | /lesson_2_Task_1.py | 998 | 4.21875 | 4 | """
Реализуйте рекурсивную функцию нарезания прямоугольника с заданными пользователем сторонами
a и b на квадраты с наибольшей возможной на каждом этапе стороной.
Выведите длины ребер получаемых квадратов и кол-во полученных квадратов
"""
def square_rec(aa, bb, nn=0):
if aa == bb:
print("Сторон... | false |
b687fa59ae247c922fb7cc0ff003ebdba4834443 | cbesanao/aprendendo_python | /CursoemVideo/aula07a-Operadores-Aritmeticos.py | 1,075 | 4.15625 | 4 | # 1 ()
# 2 **
# 3 * / // %
# 4 + -
'''
nome = input("Qual é o seu nome? ")
print('Prazer em te conhecer {:20}!\n'.format(nome)) # agora a parte do nome terá 20 espaços
print('Prazer em te conhecer {:>20}!\n'.format(nome)) # agora a parte do nome terá 20 espaços e será alinhado à DIREITA
print('Prazer em te c... | false |
77706820160382ec17b7a3f29f2ba2ef6561d4d1 | YuryRazhkov/Rozhkov_GB_ALGO | /Rozhkov_GB_ALGO/Rozhkov_Yury_dz_2/task_2_1.py | 1,638 | 4.15625 | 4 | # 1. Написать программу, которая будет складывать, вычитать, умножать или делить два числа.
# Числа и знак операции вводятся пользователем. После выполнения вычисления программа не должна завершаться,
# а должна запрашивать новые данные для вычислений. Завершение программы должно выполняться при вводе символа
# '0' в к... | false |
db6ef77f8dd537603785af1ca4ff554cb837e9c7 | arshad-taj/Python | /montyPython.py | 260 | 4.28125 | 4 | def reverse(s):
if len(s) == 0:
return s
else:
return reverse(s[1:]) + s[0]
s = "Geeksforgeeks"
print("The original string is : ", end="")
print(s)
print("The reversed string(using recursion) is : ", end="")
print(reverse(s))
| true |
5a770eec9865f4462e2cb412720b18cb1422829a | CQuinlan1/Programming_Python_Problemset | /Problem7.py | 738 | 4.46875 | 4 | #**************************
# Created by Catherine Ann Celeste Quinlan.
# This program will take a FLOATING POINT NUMBER as input and output its square root approximation.
# QUESTION 7
#*************************
import math
Selectednumber = input ("Please enter a positive floating number bigger than 0 : \n " )
try:
... | true |
895d715fb433475c1e0bbac0e0de220755191440 | kmangub/data-structures-and-algorithms | /python/challenges/multi_bracket_validation/multi_bracket_validation.py | 1,571 | 4.65625 | 5 | def multi_bracket_validation(string):
"""
This function will check to see if the brackets are matching. It creates
an empty list, which is our stack and we will iterate through each
character.
Any opening brackets will be appended to our stack.
When it encounters a closing bracket, it wi... | true |
42b0c03db3abb4932e1f8d6ff2471c339a8b5c4d | angusb/puzzles | /inversions.py | 1,175 | 4.15625 | 4 | # Inversions can be used to detect how similar two lists are (Kendall's
#rank correlcation). This is applicable with search engine testing. Futhermore,
# inversions can be used to match a user's preferences with those of others.
#
# Given a list L = x_1, x_2, ..., x_N of distinct integers between 1 and n
# an invers... | true |
f3eee113887465cafb2eebc4c7683489a6581ccb | Charlene-bot/FindAJob | /MoveZeros.py | 556 | 4.1875 | 4 | #Given an array of integers, write a function to move all 0's to the end
#while maintaining the relative order of rest of the elements
#Algorithm -- moving all numbers ahead
#setting the rest of the numbers in the list to 0
def Move_Zeros(arr, length):
j = 0
for num in arr:
if num != 0:
... | true |
b73f14ad6adfcb0005a19a66748fe3a594570b4b | Somanathpy/Py4e-Coursera | /Python_Data_Structures/scriptsandoutputs/ex7.2.py | 1,558 | 4.15625 | 4 | ## Assignment 7.2
# Write a program that prompts for a file name, then opens that file and reads through the file, looking for lines of the form:
# X-DSPAM-Confidence: 0.8475
# Count these lines and extract the floating point values from each of the lines and compute the average of those values and
# produce an ou... | true |
ef6fe1c287eb86fa59d09d1d79d854665d35ea43 | chalk13/softformance_school_exercises | /module_4/convert_user_name.py | 1,638 | 4.21875 | 4 | """Програми, які перетворюють ім'я користувача у:
- послідовність байтів
- unicode code points
- бінарне представлення
"""
USER_NAME = input("Please, enter your name: ")
# ---------------------------------------------------------------------
# Sequence of bytes
# The rules for translating a Unicode string into a sequen... | true |
6e03ebaf48358ad05bc5677876d81bc54ed847f1 | srajeevteaching/lab2-s923 | /lab2.py | 2,028 | 4.53125 | 5 | # Lab Number: 2
# Program Inputs: Births per second (float), deaths per second (float), migration per second (float),
# Program Inputs (2): Current population (integer), number of years in future (float)
# Program Outputs: Estimated population (integer)
# This block asks the user for the three inputs that change popul... | true |
feb404742b6fafaaa68fd0ceecee57c38c67114c | uknamboodiri/z2m | /section-6/115.py | 446 | 4.1875 | 4 | # Given the below class:
class Cat:
species = 'mammal'
def __init__(self, name, age):
self.name = name
self.age = age
# 1 Instantiate the Cat object with 3
cat1 = Cat('Dhanya', 16)
cat2 = Cat('Dhanya2', 18)
cat3 = Cat('Dhanya3', 17)
# 2 Create a function that finds the oldest cat
def get_ol... | true |
42d0ac0a8d6344bf06883958b2db071e1c9a44bf | smit-pate-l/HackerRank | /Sets/symmetric_difference.py | 375 | 4.3125 | 4 | # Given 2 sets of integers, M and N, print their symmetric difference in ascending order.
# The term symmetric difference indicates those values that exist in either M or N but do not exist in both.
m = int(input())
M = set(map(int,input().split()))
n = int(input())
N = set(map(int,input().split()))
r = sorted(list... | true |
e6c56cf411afde329bc8da11a779e548a717a6b3 | fpelaezt/devops | /Python/Workbook/1-2a.py | 902 | 4.4375 | 4 | # Makes a function that will contain the
# desired program.
def example():
# Calls for an infinite loop that keeps executing
# until an exception occurs
while True:
test4word = input("What's your name? ")
try:
test4num = int(input("From 1 to 7, how many hours do you play in you... | true |
4acae9de077b1b1497254d832c393afbff9f7288 | fpelaezt/devops | /Python/Course/4_Managing_lists.py | 1,692 | 4.5 | 4 | #For loop
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(magician)
for magician in magicians:
print(magician.title() + " that was a great trick!!")
print("===")
print("///")
for number in range(2,9):
print(number)
print("That was it")
print("###############")
numbers = li... | true |
f70fbdb665c0e479b32b240950618d59569cf037 | Kunjal9/Project_Euler | /Problem01.py | 598 | 4.21875 | 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.
def multiple_of_3_and_5(num):
list_of_i = []
for i in range(1,num):
if (i %5 ==0) or (i%3==0):
list_of... | true |
d196796bb7db0463ae7f72305630c26d0648b587 | askiefer/practice-code-challenges | /missing_element.py | 619 | 4.21875 | 4 | import collections
def missing_element(lst1, lst2):
lst1.sort()
lst2.sort()
count = 0
for item in lst1:
if item != lst2[count]:
return item
count += 1
def missing_element_two(lst1, lst2):
lst1.sort()
lst2.sort()
for num1, num2 in zip(lst1, lst2):
if num1 != num2:
return num1
return False
# this i... | true |
44c079d95ab1089fbd22e72db89baa863a6ef301 | akshirapov/think-python | /15-classes-and-objects/ex_15_9_2.py | 1,823 | 4.28125 | 4 | # -*- coding: utf-8 -*-
"""
This module contains a code for ex.2 related to ch.15.9 of
Think Python, 2nd Edition
by Allen Downey
http://thinkpython2.com
"""
import math
import turtle
from ex_15_9_1 import Point, Circle, Rectangle
def polyline(t, n, length, angle):
"""Draws n line segments.
:param t: turt... | true |
af934bf769068533c84ccdff2976c26413f6274d | akshirapov/think-python | /12-tuples/ex_12_10_3.py | 1,297 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
This module contains a code for ex.3 related to ch.12.10 of
Think Python, 2nd Edition
by Allen Downey
http://thinkpython2.com
"""
def word_list():
"""Makes a dictionary where the key is the word.
:return: Dictionary
"""
d = {}
with open('words.txt') as fin:
f... | true |
993f6d68415097284dcd543c5a96e6ac61c640ca | akshirapov/think-python | /14-files/ex_14_12_2.py | 1,533 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
This module contains a code for ex.2 related to ch.14.12 of
Think Python, 2nd Edition
by Allen Downey
http://thinkpython2.com
"""
import shelve
def word_list(filename):
"""Makes a dictionary where the key is the word.
:param filename: file with words
"""
d = {}
with... | true |
407190295065104f1c25894e4f1722f5ed0f0f78 | linus1211/Learn-Python-The-Hard-Way | /ex9.py | 675 | 4.21875 | 4 | # Here's some new strange stuff, remember type it exactly.
# Set a variable called days to a string with shortened day names
days = "Mon Tue Wed Thu Fri Sat Sun"
yay111 = "Mon"
# Set a variable called months to a string with shortened month names, separated by \n (newline) characters
months = "Jan\nFeb\nMar\nApr\nMay\... | true |
d63a5ae5a7391fb046373b832d416679fe80c389 | BElgy123/Palindrome | /Palindrome.py | 1,516 | 4.5625 | 5 | def is_palindrome(test_string):
""" A standalone function to check if a string is a palindrome.
:param test_string: the string to test
:return: boolean
"""
t = test_string #Change parameter name cause it's too long for laziness
_t = [] #Will be expanded form of t
t_ = [] #Will be _t backwar... | true |
e3e22a551b6cf3a223f723ca175e7b5ac3056a9c | nkmcheng/Python-Training | /problem2.py | 423 | 4.21875 | 4 | # Question #2:
# Write a program which can compute the factorial of a given numbers.
# The results should be printed in a comma-separated sequence on a single line.
# Suppose the following input is supplied to the program:
# 8 Then, the output should be: 40320
sequence = [8, 5]
results = []
for s in sequence:
resu... | true |
838652f0cb3ace326b9266fa271b39c031f00d52 | User-zwj/Class | /Tim_OOP.py | 1,838 | 4.3125 | 4 | # object oriented programming in python
# string = 'hello'
# print(string.upper())
# print(string.capitalize())
# class Dog:
#
# def __init__(self, name):
# self.name = name #attribute
# print(name)
#
# def add_one(self, x):
# return x+1
#
# def bark(self): #method
# ... | false |
274346c96ad571b3fdc354db141863bdb99a14d5 | udaypandey/BubblyCode | /Python/multiplication-table.py | 360 | 4.40625 | 4 | # Write a program that prints a multiplication table for numbers up to 12.
def printTable() :
num = 1
while num <= 12:
end = 12
start = 1
while start <= end:
print(f"{num} x {start} = {num * start}")
start = start + 1
num = num + 1
... | true |
cb01451575debb5050b412cb3cb3cabb4ce6d30f | tbold5/A01072453_1510_assignments | /A1/phone_fun.py | 2,574 | 4.125 | 4 | """COMP 1510 Assignment 1: PHONE FUN!"""
# Trae Bold
# A01072453
# Feb 03, 2019
import doctest
def number_translator():
"""Translates alphabetical numbers.
A function that translates alphabetical numbers into numerical equivalent.
PRECONDITION: promt user to input 10 character telephone number in the f... | true |
4212b2e337330c2cf72fda3d55a569c0f406a2e3 | Jethet/First-Milestone-Project | /OLDChoice.py | 2,327 | 4.21875 | 4 | # This is the function that asks the choice of a player and links to the
# board squares.
# This function is part of main()
import pickle
from beautifultable import BeautifulTable
board = BeautifulTable()
board.append_row(['1', '2', '3'])
board.append_row(['4', '5', '6'])
board.append_row(['7', '8', '9'])
print(board... | false |
6fc02da1b7a8ae69a06bb8c694061f305e5412e2 | richiabhi/Rock_paper_Scissors | /main.py | 961 | 4.1875 | 4 | import random
# Rock Paper Scissor
def gameWin(comp, you):
if comp == you:
return None
elif comp == 'r':
if you == 'p':
return True
elif you == 's':
return False
elif comp == 'p':
if you == 's':
return True
elif you == ... | false |
0477c1ba458019c51f17f2e8d8689912f53baa8f | limikmag/python | /algorithms/math/fast_exponential.py | 872 | 4.3125 | 4 |
# recursion
def power(base: int, to_power: int) -> int:
if to_power == 0:
return 1
if to_power % 2 != 0:
return base*power(
base=base, to_power=(to_power - 1))
if to_power % 2 == 0:
return power(
base=base, to_power=to_power/2)*power(base=base, to_power=to_p... | true |
50abb7adfbc7d82404e57138b1c3b649b092001e | trinhgliedt/100_days_of_Python | /2021_03_07_Guess_the_number/2021_03_07_Guess_the_number.py | 2,024 | 4.28125 | 4 | # Number Guessing Game Objectives:
# Include an ASCII art logo.
# Allow the player to submit a guess for a number between 1 and 100.
# Check user's guess against actual answer. Print "Too high." or "Too low." depending on the user's answer.
# If they got the answer correct, show the actual answer to the player.
# Trac... | true |
e935334b6eb589c4fbf104c5b6da44e29cd21918 | trinhgliedt/100_days_of_Python | /2021_03_13_Turtle_Racing/main.py | 1,045 | 4.25 | 4 | from turtle import Turtle, Screen
import random
screen = Screen()
screen.setup(width=500, height=400)
user_bet = screen.textinput(title="Make your bet", prompt="Which turtle will win the race? Enter a color: ")
colors = ["red", "orange", "yellow", "green", "blue", "indigo"]
xCor = -240
yCors = [150, 100, 50, 0, -50,... | true |
43d7d16a894ed49f2e25e30c15edb67cc22177b7 | tangowithfoxtrot/beginner_project_solutions | /multi_table.py | 713 | 4.1875 | 4 | '''
Created on Sun 04/20/2020 20:29:08
Multiplication Table
@author: MarsCandyBars
'''
def table(user_num):
'''
Description:
This function creates the table in a matrix format
with nested for loops, left justifying the numbers,
and not causing endlines until the loop is broken.
Args... | true |
7dc1f9e2a0e04c95e0b99c9d9f6b89cfec80f24e | puhaoran12/python_note | /11.数据类型转换.py | 1,252 | 4.28125 | 4 | name='张三'
age=20
print(type(name),type(age))
#print('我叫'+name+',今年'+age+'岁')#当将str类型与interesting类型连接时,报错。解决方案:类型转换
print('我叫'+name+',今年'+str(age)+'岁')#将int类型通过str()函数转换成str类型
print('-------使用str()函数将其他类型转换成str类型---------')
a=10
b=2.2
c=False
print(type(a),type(b),type(c))
print(str(a),type(str(a)))
print(str(b),type(s... | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.