blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
27fd01098ce6f68a304f25eb885af97217863453 | shivambhojani/Python-Practice | /remove_char.py | 372 | 4.3125 | 4 | # Write a method which will remove any given character from a String?
def remove(str, char):
new_str = ""
for i in range(0, len(str)):
if i != char:
new_str = new_str + str[i]
return new_str
a = input("String: ")
b = int(input("which Character you want to remove: "))
b = b... | true |
4067c6b39abf37b18537c930109aa732e9dfe885 | menliang99/CodingPractice | /PeakingIterator.py | 714 | 4.25 | 4 | # Decorator Pattern is a design pattern that allows behavior to be added to an individual object, either statically or dynamically, without affecting the behavior of other objects from the same class.
class PeekingIterator(object):
def __init__(self, iterator):
self.iter = iterator
self.peekFlag = False
self.n... | true |
0312a221309f546836230b69bf7b6c81f02bac56 | mhetrick29/COS429_Assignments | /A4_P2/relu_backprop.py | 1,208 | 4.15625 | 4 | def relu_backprop(dLdy, x):
import numpy as np
# Backpropogates the partial derivatives of loss with respect to the output
# of the relu function to compute the partial derivatives of the loss with
# respect to the input of the relu function. Note that even though relu is
# applied elementwise to ma... | true |
e56c29cc6afc63b4ec4cf5afc97355e0385ee367 | nunu2021/DijkstraPathFinding | /dijkstra/basic_algo.py | 2,208 | 4.125 | 4 | import pygame
graph = {
'a': {'b': 1, 'c': 1, 'd': 1},
'b': {'c': 1, 'f': 1},
'c': {'f': 1, 'd': 1},
'd': {'e': 1, 'g': 1},
'e': {'g': 1, 'h': 1},
'f': {'e': 1, 'h': 1},
'g': {'h': 1},
'h': {'g': 1},
}
def dijkstra(graph, start,goal):
shortest_distance ={} # records the cost to re... | true |
0fbca70b44d8bcf4fc87316e0b840e40ad8881f0 | guanhejiuzhou/PythonStudy | /Python语言基础/Day001-元素的变量.py | 2,438 | 4.4375 | 4 | """
变量和类型
变量时数据的载体,简单的说就是一块用来保存数据的内存空间,变量的值可以被读取和修改。
python中的几种常用数据类型
整型 int:python中可以处理任意大小的整数
浮点型 float
字符串型 str:字符串是以单引号或者双引号括起来的任意文本
布尔型 bool:布尔值只有true和false两种值,要么true要么false
"""
'''
变量命名
硬性规则:
1、变量名由字母、数字、下划线构成,数字不能开头
2、大小写敏感,大写的A和小写的a是两个不同的变量
3、不要跟Python语言的关键字和保留字(如函数、模块等的名字)发生重名的冲突
非硬性规则:
1、变量名... | false |
19667d8cd7c9c82438df92eff2f4062be06ef339 | echase6/codeguild | /practice/pig-latin-sentence.py | 1,693 | 4.15625 | 4 | """
Program to translate a single word into Pig Latin
This is an individual project by Eric Chase, 7/11/16
Input: a single words
Output: a word converted into Pig Latin
"""
# setup
VOWELS = ['a', 'e', 'i', 'o', 'u']
pig_latin = []
def convert_pig_latin(english_input):
# First, break into three parts: beginning p... | false |
0540aaa6f156d2f017ea12380f97f3a68166fac6 | Deepika-bala/conversion | /main.py | 375 | 4.25 | 4 | decimal=int(input("enter the decimal : "))
convert =int(input("convert into : [1] binary,[2] octal,[3] hexadecimal:\n"))
if convert == 1:
print("convert into binary\n " ,bin(decimal))
elif convert == 2 :
print("convert into octal\n", oct(decimal))
elif convert == 3:
print("convert into octadecimal\n"... | false |
079b0e961c408f6b2b6c8edf65b56eaa0f2b4e61 | WaqasAkbarEngr/Python-Tutorials | /smallest_number.py | 612 | 4.1875 | 4 | def smallest_number():
numbers = []
entries = input("How many number you want to enter? ")
entries = int(entries)
while entries > 0:
entered_number = input("Enter a number? ")
numbers.append(entered_number)
smallest_number = entered_number
entries = entries - 1
... | true |
83265b7915746a67e8240e49d3819e8e6d840526 | cmobrien123/Python-for-Everybody-Courses-1-through-4 | /Ch7Asmt7.2.py | 1,146 | 4.34375 | 4 | # Exercise 7.2: Write a program to prompt for a file name, and then read
# through the file and look for lines of the form:
# X-DSPAM-Confidence:0.8475
# When you encounter a line that starts with "X-DSPAM-Confidence:" pull apart
# the line to extract the floating-point number on the line. count these lines
# and then... | true |
709ccdd4ec3a29f9adca939763015cfa37ee521b | Denysios/Geekbrains | /python/base/dz_lesson1/lesson1_task2.py | 1,338 | 4.1875 | 4 | # Задание 2
# Пользователь вводит время в секундах. Переведите время в часы, минуты и секунды
# и выведите в формате чч:мм:сс. Используйте форматирование строк.
# Простой способ, но с некоторыми недочетами
# time_sec = int(input('Введите время в секундах: '))
# minutes = time_sec // 60
# hours = minutes // 60
# sec = ... | false |
d0a8a00b9834f82ef386fb2d2bc1a93bbd5c092a | arkadym74/pthexperience | /helloworld.py | 1,664 | 4.3125 | 4 | #Prints the Words "Hello World"
'''This is a multiline comment'''
print("Hello World")
userAge, userName = 30, 'Peter'
x = 5
y = 10
y = x
print("x = ", x)
print("y = ", y)
brand = 'Apple'
exchangeRate = 1.235235245
message = 'The price of this {0:s} laptop is {1:d} USD and the exchange rate is {2:4.2f} USD to 1... | true |
4af66f31e555e7fd67d00869653e8c7048c1f472 | mgomesq/neural_network_flappybird | /FlappyBird/brain.py | 1,735 | 4.46875 | 4 | # -*- coding: utf-8 -*-
'''
Brain
=====
Provides a Brain class, that simulates a bird's brain.
This class should be callable, returning True or False
depending on whether or not the bird should flap its wings.
How to use
----------
Brain is passed as an argument to Bird, which is defin... | true |
bba081265a85bbf2988ee18245ba83140fe8bb4a | Tlepley11/Home | /listlessthan10.py | 225 | 4.1875 | 4 | #A program that prints all integers in a list less than a value input by the user
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
x = input("Please enter a number: ")
b = []
for i in a:
if i < x: print(i); b.append(i)
print(b)
| true |
b652e232cb08379678bcdd9173d596a4afef4a05 | jamie0725/LeetCode-Solutions | /566ReshapetheMatrix.py | 1,737 | 4.25 | 4 | """
n MATLAB, there is a very useful function called 'reshape', which can reshape
a matrix into a new one with different size but keep its original data.
You're given a matrix represented by a two-dimensional array, and two positive
integers r and c representing the row number and column number of the wanted
reshap... | true |
293fe7ead7c870e3f25bde546f2b34337eb32378 | optionalg/cracking_the_coding_interview_python-1 | /ch4_trees_and_graphs/4.2_minimal_tree.py | 1,190 | 4.125 | 4 | # [4.2] Minimal Tree: Given a sorted(increasing order)
# array with unique integer elements, write an algorithm
# to create a binary search tree with minimal height
# Space complexity:
# Time complexity:
import unittest
def create_bst(array):
if not array:
return None
elif len(array) == 1:
r... | true |
b0d9de4d3f59d074ea1ffc412a99e8610ddccab6 | optionalg/cracking_the_coding_interview_python-1 | /ch5_bit_manipulation/5.7_pairwise_swap.py | 1,734 | 4.15625 | 4 | # [5.7] Pairwise Swap: Write a program to swap odd and even bits
# in an integer with as few instructions as possible (e.g., bit
# 0 and bit 1 are swapped, bit 2 and bit 3 and swapped, and so on)
import unittest
def pairwise_swap(num):
even_mask = create_even_mask(num)
odd_mask = create_odd_mask(num)
... | true |
3dc3b3e5045027bcccafc7907b667a0d2c8ec606 | optionalg/cracking_the_coding_interview_python-1 | /ch1_arrays_and_strings/1.1_is_unique.py | 798 | 4.1875 | 4 | # Time complexity: O(n) because needs to check each character
# Space complexity: O(c) where c is each character
import unittest
def is_unique(s):
# create a hashmap to keep track of char count
char_count = {}
for char in s:
# if character is not in hashmap add it
if not char in char_c... | true |
738c5f3cfa7d3c58b05c5738822e0d807dbf1f7b | optionalg/cracking_the_coding_interview_python-1 | /ch8_recursion_and_dynamic_programming/8.1_triple_step.py | 1,634 | 4.15625 | 4 | # [8.1] Triple Step: A child is running up a staircase with n
# steps and can hop either 1 step, 2 steps, or 3 steps at a
# time. Implement a method to count how many possible ways
# the child can run up the stairs.
import unittest
def fib(n):
if n < 1:
raise ValueError('Must be positive Integer')
el... | true |
ff7e1c2a4dc59cb1786841b7fff931fc5db1e00f | jutish/master-python | /07-ejercicios/ejercicio4.py | 360 | 4.15625 | 4 | """
Pedir dos numeros al usuario y hacer todas las operaciones
de una calculadora. Suma, resta, multiplicacion y division.
"""
nro1 = int(input("Ingrese Nro1: "))
nro2 = int(input("Ingrese Nro2: "))
print(f"{nro1} + {nro2} = {nro1+nro2}")
print(f"{nro1} - {nro2} = {nro1-nro2}")
print(f"{nro1} * {nro2} = {nro1*nro2}")... | false |
fdee0f3aaae1372696e95ba72cb3ca090df592fb | pieland-byte/Introduction-to-Programming | /week_4/ex_3.py | 1,341 | 4.3125 | 4 | #This program creates a dictionary from a text file of cars and prints the
#oldest and newest car from the original file
#create a list from the text file
def car_list():
car_list = [] #Empty list
with open ("cars_exercise_3.txt" , "r") as car_data: #Open text... | true |
2e0d8cbe84dc1a8a57e90e9c34e015d1c4eebfe5 | pieland-byte/Introduction-to-Programming | /week_1/ex_5.py | 298 | 4.3125 | 4 | # This is a program to convert temperature in fahrenheit to celcius/centigrade
fahrenheit = input("Enter the temperature in fahrenheit: ")
fahrenheit = int(fahrenheit)
celsius = ((5/9) * (fahrenheit - 32))
print(fahrenheit, "Degrees Fahrenheit is",round(celsius,2), "degrees Celsius")
| false |
c546d7555f99c6bb2b2fa6d0266e6615256aecb2 | pieland-byte/Introduction-to-Programming | /week_3/ex_2.py | 1,309 | 4.625 | 5 | #This program calculates the volume of given shapes specified by
#the user using recursion
import math
# creating a menu with options for user input
def main_menu():
menu_choice = input("Please type 1 for sphere, 2 for cylinder and 3 for cone: ")
if menu_choice == "1":
result = sphere(int(inp... | true |
119d31f2c4846ba1416da750b0e87a38d77509f3 | pieland-byte/Introduction-to-Programming | /week_4/ex_2.py | 1,159 | 4.15625 | 4 | #This program asks the user to name a sandwich ingredient and shows
#corresponding sandwiches from the menu
sandwiches = [] #Empty list
with open ("menu.txt","r") as menu: #Read menu.txt
for line in menu: #For each line
sandwiches.append(line.... | true |
401075a7b543a9eb6a6d81c820a371aa3a24a66f | pieland-byte/Introduction-to-Programming | /week_4/ex_1.py | 546 | 4.1875 | 4 | #This program asks the user to name a sandwich and shows corresponding
#sandwiches from the menu
sandwiches = []
with open ("menu.txt","r") as menu:
for line in menu:
sandwiches.append(line.rstrip("\n"))
def sandwich_choice():
choice = input("Enter which sarnie you would like: ")
for... | true |
4879cc84005af321f00c305271d26325fec9a5ae | MetalSkink/Curso-Python | /Bucles/Ejercicios/Ejercicio9.py | 420 | 4.15625 | 4 | '''
Bucles - Ejercicio 9:
Hacer un programa donde el usuario ingrese una frase, se le devolverá la misma frase
pero sin espacios en blanco y además un contador de cuántos
caracteres tiene la frase (sin contar los espacios en blanco).
'''
frase = input("Inserte una frase -> ")
contador=0
for i in frase:
if i != ... | false |
1e3d446c41600a291eccfed2f9b58364ec3019da | MetalSkink/Curso-Python | /Condicionales/Ejercicio2.py | 693 | 4.25 | 4 | '''
Ejercicio2 :
Hacer un programa que pida 3 numeros y determina cual
es mayor
'''
a = float(input("a -> "))
b = float(input("b -> "))
c = float(input("c -> "))
if a == b and b == c:
print("Los 3 numeros son iguales")
if a == b and b > c:
print("Los primeros 2 numero son mayores e iguales")
if b == c and b >... | false |
0cbb1fbbfac2c26c8bba84d4ae8ca5a74ec76b98 | ioana01/Marketplace | /tema/consumer.py | 2,311 | 4.28125 | 4 | """
This module represents the Consumer.
Computer Systems Architecture Course
Assignment 1
March 2021
"""
from threading import Thread
import time
class Consumer(Thread):
"""
Class that represents a consumer.
"""
def __init__(self, carts, marketplace, retry_wait_time, **kwargs):
"""
... | true |
4ff3e99a408d896b4260680980b204794cae01f4 | dnaport22/pyex | /Functions/averageheight.py | 1,081 | 4.15625 | 4 | #~PythonVersion 3.3
#Author: Navdeep Dhuti
#StudentNumber: 3433216
#Code below generate answer for question::
#What is the average value of the numbers in the field [height] in the range(1.75)and(2.48)inclusive?
#Function starts
def Average_height(doc_in):
doc = open(doc_in+'.csv','r') #Open the input file came ... | true |
a9fb3bc90fe2ce347f1ca6ea02239760e35963e6 | PhaniMandava7/Python | /Practice/Sets.py | 591 | 4.40625 | 4 | # Sets are collection of distinct elements with no ordering.
# Sets are good at membership testing.
# empty_set = {} -------> this creates a dict.
empty_set = set()
courses_set = {'History', 'Physics', 'Math'}
print(courses_set)
courses_set.add('Math')
print(courses_set)
print('Math' in courses_set)
courses_set =... | true |
a723af9a1faae81b098e9b79025f031a0f8b2038 | PhaniMandava7/Python | /FirstPythonProj/GetInputFromKeyboard.py | 337 | 4.21875 | 4 | greeting = "Hello"
# name = input("Please enter your name")
# print(greeting + ' ' + name)
# names = name.split(" ")
# for i in names:
# print(i)
print("This is just a \"string 'to test' \"multiple quotes")
print("""This is just a "string 'to test' "multiple quotes""")
print('''This is just a "string 'to test' mu... | true |
6c7d41a18476a461fbceec79924b253d39f9f311 | paalso/learning_with_python | /ADDENDUM. Think Python/10 Lists/10-12_version1.py | 2,415 | 4.28125 | 4 | '''
Exercise 10.12. Two words “interlock” if taking alternating letters from each
forms a new word. For example, “shoe” and “cold” interlock to form “schooled”.
Solution: http://thinkpython2.com/code/interlock.py
1. Write a program that finds all pairs of words that interlock. Hint: don’t
enumerate all pairs!
2... | true |
1a63f54074f8a96a4a3585950a253a25d068a0d0 | paalso/learning_with_python | /18 Recursion/18-7.py | 976 | 4.15625 | 4 | # Chapter 18. Recursion
# http://openbookproject.net/thinkcs/python/english3e/recursion.html
# Exercise 7
# ===========
# Write a function flatten that returns a simple list containing all the values
# in a nested list
from testtools import test
def flatten(nxs):
"""
Returns a simple list cont... | true |
4e13a17fdcaa1022e51da4c4bb808571a02d6177 | paalso/learning_with_python | /26 Queues/ImprovedQueue.py | 2,311 | 4.1875 | 4 | # Chapter 26. Queues
# http://openbookproject.net/thinkcs/python/english3e/queues.html
class Node:
def __init__(self, cargo=None, next=None):
self.cargo = cargo
self.next = next
def __str__(self):
return str(self.cargo)
class ImprovedQueue:
def __init__(self):
... | true |
ec0915fa2463fb1da2bb9ad4a5b55793d40fac93 | paalso/learning_with_python | /09 Tuples/9-01_1.py | 1,138 | 4.5 | 4 | ## Chapter 9. Tuples
## http://openbookproject.net/thinkcs/python/english3e/tuples.html
## Exercise 1
## ===========
# We’ve said nothing in this chapter about whether you can pass tuples as
# arguments to a function. Construct a small Python example to test whether this
# is possible, and write up your finding... | true |
e66ceb92103c0c595bbaa0f6bc829e2208b34dba | paalso/learning_with_python | /18 Recursion/18-11/litter.py | 1,729 | 4.21875 | 4 | # Chapter 18. Recursion
# http://openbookproject.net/thinkcs/python/english3e/recursion.html
# Exercise 11
# ============
# Write a program named litter.py that creates an empty file named trash.txt in
# each subdirectory of a directory tree given the root of the tree as an argument
# (or the current directory... | true |
9ef73be5b8fdf09a171cff7e27c68773fda9963e | paalso/learning_with_python | /06 Fruitful functions/6-9.py | 1,849 | 4.21875 | 4 | ##Chapter 6. Fruitful functions
##http://openbookproject.net/thinkcs/python/english3e/fruitful_functions.html
## Exercise 9
## ===========
##Write three functions that are the “inverses” of to_secs:
##hours_in returns the whole integer number of hours represented
##by a total number of seconds.
##minutes_i... | true |
1ada77a6b13c07c35793d86d7dd8671356910c09 | paalso/learning_with_python | /ADDENDUM. Think Python/09 Case study - word play/9-6.py | 1,370 | 4.15625 | 4 | '''
Exercise 9.6. Write a function called is_abecedarian that returns True if
the letters in a word appear in alphabetical order (double letters are ok).
How many abecedarian words are there?
'''
def is_abecedarian(word):
"""
Returns True if the letters in a word appear in alphabetical order
(doub... | true |
87948f279e5becb72db7deef006590720ddbeaba | paalso/learning_with_python | /08 Strings/8-6.py | 1,569 | 4.4375 | 4 | ## Chapter 8. Strings
## http://openbookproject.net/thinkcs/python/english3e/strings.html
## Exercise 6
## ===========
# Print a neat looking multiplication table like this:
# 1 2 3 4 5 6 7 8 9 10 11 12
# :--------------------------------------------------
# 1: 1 2 3 4 ... | false |
32ec6ec6910b4cb9806e82cfdd8eb22e902c8827 | paalso/learning_with_python | /04 Functions/4_4_ver0_0.py | 1,339 | 4.28125 | 4 | ##4. http://openbookproject.net/thinkcs/python/english3e/functions.html
##4. Draw this pretty pattern:
import turtle
import math
def make_window(colr, ttle):
"""
Set up the window with the given background color and title.
Returns the new window.
"""
w = turtle.Screen()
w.bgc... | true |
c9b466df940ce854e8b362a48c71ab720025b83b | paalso/learning_with_python | /ADDENDUM. Think Python/10 Lists/10-9.py | 2,446 | 4.125 | 4 | '''
Exercise 10.9. Write a function that reads the file words.txt and builds
a list with one element per word. Write two versions of this function, one
using the append method and the other using the idiom t = t + [x]. Which one
takes longer to run? Why?
'''
def load_words(dict_filename):
"""
Return... | true |
3638b74fdff0456af03fd38137c7eceae3ddacb1 | paalso/learning_with_python | /ADDENDUM. Think Python/13 Case study - data structure/13-6.py | 1,209 | 4.21875 | 4 | '''
Exercise 13.5. Write a function named choose_from_hist that takes a histogram
as defined in Section 11.2 and returns a random value from the histogram,
chosen with probability in proportion to frequency.
For example, for this histogram:
>>> t = ['a', 'a', 'b']
>>> hist = histogram(t) # {'a': 2, 'b': 1}
your ... | true |
7783505fb7040ceefdd5794f88507f573b4d6bcf | paalso/learning_with_python | /07 Iterations/7-1.py | 923 | 4.28125 | 4 | ## Chapter 7. Iteration
## http://openbookproject.net/thinkcs/python/english3e/iteration.html
## Exercise 1
## ===========
## Write a function to count how many odd numbers are in a list.
import sys
def count_odds(lst):
counter = 0
for n in lst:
if n % 2 == 1:
counter +... | true |
e0dbd51a977024665d2211a0f4f82f3a7d5ce224 | paalso/learning_with_python | /24 Linked lists/linked_list.py | 1,471 | 4.21875 | 4 | # Chapter 24. Linked lists
# http://openbookproject.net/thinkcs/python/english3e/linked_lists.html
class Node:
def __init__(self, cargo=None, next=None):
self.cargo = cargo
self.next = next
def __str__(self):
return str(self.cargo)
def print_backward(self):
... | true |
af380bf7377bec6c0406d8a5ab9ec2e48c02aa0d | alon211/LearnPython | /Full Course for Beginners/WorkingWithString.py | 331 | 4.25 | 4 | # 最原始的
print("I am John")
# 换行符号
print("I am \n John")
# 转义符号
print("I am \"John")
# 字符串变量
MyStr = "I am John"
print(MyStr)
# 字符串函数
MyStr = "I am John"
print(MyStr.lower())
print(MyStr.upper())
print(MyStr.isupper())
print(MyStr[0])
# 字符串index用法
print(MyStr.index('oh'))
| false |
6dfea9839760f8124ac74143ec886b836d85fa38 | mattwfranchi/3600 | /SampleCode/BasicTCPEchoClient.py | 1,035 | 4.21875 | 4 | from socket import *
# Define variables that hold the desired server name, port, and buffer size
SERVER_NAME = 'localhost'
SERVER_PORT = 3602
BUFFER_SIZE = 32
# We are creating a *TCP* socket here. We know this is a TCP socket because of
# the use of SOCK_STREAM
# It is being created using a with statement, ... | true |
086a3773b74c93e12755271fa0cf25d24399cb60 | hsinjungwu/self-learning | /100_Days_of_Code-The_Complete_Python_Pro_Bootcamp_for_2021/day-12.py | 756 | 4.15625 | 4 | #Number Guessing Game Objectives:
from art import logo
import random
print(logo)
print("Welcome to the Number Guessing Game!\nI'm thinking of a number between 1 and 100.")
ans = random.randint(1, 100)
attempts = 5
if input("Choose a difficulty. Type 'easy' or 'hard': ").lower() == "easy":
attempts = 10
while at... | true |
f3ff778147002322c07f7163b50fc1f8f825e220 | Pattrickps/Learning-Data-Structures-Using-Python | /data-structures/implement stack using linked list.py | 863 | 4.28125 | 4 | # Implement Stack using Linked List
class node:
def __init__(self,node_data):
self.data=node_data
self.next=None
class stack:
def __init__(self):
self.head=None
def push(self,data):
new_node=node(data)
new_node.next=self.head
self.head=new_node
def pop... | true |
8f3263d7c6d0c6850271577d17d7c712116bdead | Pattrickps/Learning-Data-Structures-Using-Python | /data-structures/queue using linked list.py | 1,296 | 4.34375 | 4 | #Implement Queue using Linked List
class node:
def __init__(self,node_data):
self.data=node_data
self.next=None
class queue:
def __init__(self):
self.head=None
def enqueue(self,data):
new_node=node(data)
new_node.next=self.head
self.head=new_node
def d... | false |
fde3c6be1915e11568e8d3d75f24143892d5f319 | mindyzwan/python-practice | /easy1/5.py | 234 | 4.21875 | 4 | def reverse_sentence(string):
return ' '.join(string.split(' ')[::-1])
print(reverse_sentence('') == '')
print(reverse_sentence('Hello World') == 'World Hello')
print(reverse_sentence('Reverse these words') == 'words these Reverse') | false |
8fc847aa8f077e7abec82c05c2f109b324e489ef | code-lucidal58/python-tricks | /play_with_variables.py | 528 | 4.375 | 4 | import datetime
"""
In-place value swapping
"""
# swapping the values of a and b
a = 23
b = 42
# The "classic" way to do it with a temporary variable:
tmp = a
a = b
b = tmp
# Python also lets us use this
a, b = b, a
"""
When To Use __repr__ vs __str__?
"""
# Emulate what the std lib does:hand
today = datetime.date... | true |
467335edf1eafb7cdcf912fe46a75d3f6c712c08 | ugo-en/some-python-code | /extra_old_code/square.py | 326 | 4.5 | 4 | # Step1: Prompt the user to enter the length of a side of the square
length = int(input("Please Enter the LENGHT of the Square: "))
# Step2: Multiply the length by itself and assign it to a variable called area
area = length * length
# Step3: Display the area of the square to the user
print("Your area is: ",... | true |
3653c4987ee75687f3ad08710e803d8724ad244e | ugo-en/some-python-code | /extra_old_code/bmi_calcuator.py | 680 | 4.375 | 4 | #Opening remarks
print("This app calculates your Body Mass Index (BMI)")
#Input variables
weight = float(input("Input your weight in kg but don't include the units: "))
height = float(input("Input your height in m but don't include the units: "))
#Calculate the bmi rnd round off to 1 decimal place
bmi = weight / (hei... | true |
72d67c1ccb8703467153babbd8baae6c15ca226a | ankurt04/ThinkPython2E | /chapter4_mypolygon.py | 1,086 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jul 2 10:45:14 2017
@author: Ankurt.04
"""
#Think Python - End of Chapter 4 - In lessson exercises
import turtle
import math
bob = turtle.Turtle()
def square(t, length):
i = 0
while i <= 3:
t.fd(length)
t.lt(90)
i +=1
... | true |
f1a1d08fa7136a770ca44fbe8dfbf8ffc4eee38e | katelevshova/py-algos-datastruc | /Problems/strings/anagrams.py | 1,721 | 4.15625 | 4 | # TASK
'''
The goal of this exercise is to write some code to determine if two strings are anagrams of each other.
An anagram is a word (or phrase) that is formed by rearranging the letters of another word (or phrase).
For example:
"rat" is an anagram of "art"
"alert" is an anagram of "alter"
"Slot machi... | true |
e56c99d2a16d2819a3209bf3cc27ea86ae2c8fa0 | katelevshova/py-algos-datastruc | /Problems/stacks_queues/balanced_parentheses.py | 1,469 | 4.125 | 4 | """
((32+8)∗(5/2))/(2+6).
Take a string as an input and return True if it's parentheses are balanced or False if it is not.
"""
class Stack:
def __init__(self):
self.items = []
def size(self):
return len(self.items)
def push(self, item):
"""
Adds item to the end
"... | true |
6f495c6f055867f3df8bd832470e3697e89427e9 | NerdJain/Python | /search_tuple.py | 566 | 4.1875 | 4 | def main():
l = []
n = int(input("Enter no. of elements in tuple: "))
for i in range(n):
l.append(input("Enter Element: "))
t1 = tuple(l)
se = input("Enter search element: ")
if se in t1:
print(f"{se} is in {t1}")
else:
print(f"{se} not in {t1}")
if __name__ == '__main__':
main()
... | false |
edbf5b7c45bd43917d56099a020e9f82a21a0f64 | nsuryateja/python | /exponent.py | 298 | 4.40625 | 4 | #Prints out the exponent value eg: 2**3 = 8
base_value = int(input("enter base value:"))
power_value = int(input("enter power value:"))
val = base_value
for i in range(power_value-1):
val = val * base_value
#Prints the result
print(val)
#Comparing the result
print(base_value ** power_value)
| true |
0d760ab53b3b0cb5873064ab0ed74b54a1962db1 | Cookiee-monster/nauka | /Scripts/Python exercises from GIT Hub/Ex 9.py | 567 | 4.34375 | 4 | #! Python 3
# Question 9
# Level 2
#
# Question£º
# Write a program that accepts sequence of lines as input and prints the
# lines after making all characters in the sentence capitalized.
# Suppose the following input is supplied to the program:
# Hello world
# Practice makes perfect
# Then, the output should be:
# HEL... | true |
07bcdd9aaac7533bca685a1e4bc17f21db3733da | Cookiee-monster/nauka | /Scripts/Python exercises from GIT Hub/Ex 19.py | 1,181 | 4.6875 | 5 | #! Python 3
# Question:
# You are required to write a program to sort the (name, age, height) tuples by ascending order where name is string,
# age and height are numbers. The tuples are input by console. The sort criteria is:
# 1: Sort based on name;
# 2: Then sort based on age;
# 3: Then sort by score.
# The priority... | true |
d863997509ddc1bcf91d2217c99681040b2855a6 | Fantendo2001/FORKERD---University-Stuffs | /CSC1001/hw/hw_0/q2.py | 354 | 4.21875 | 4 | def display_digits():
try:
# prompts user for input
num = int(input('Enter an integer: '))
except:
print(
'Invalid input. Please enter again.'
)
else:
# interates thru digits of number and display
for dgt in str(num):
print(dgt)
... | true |
b0b82289495eb50db5191c439cf4f5aa2589c839 | karreshivalingam/movie-booking-project | /movie ticket final.py | 2,810 | 4.125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
global f
f = 0
#this t_movie function is used to select movie name
def t_movie():
global f
f = f+1
print("which movie do you want to watch?")
print("1,Acharya ")
print("2,vakeel saab ")
print("3,chicchore")
print("4,back")
movie = int... | true |
3027f3d2a75a6fad46548ad001b2589aad5c5612 | meenapandey500/Python_program | /program/dict.py | 371 | 4.53125 | 5 | #create a dictionary
student={"rollno":110 ,"name" : "Anu Agrawal","Age":23,"City":"Mumbai"}
print("Type of student :",type(student))
#Loop through a Dictionary student
print("Keys are : ")
for x in student: #only access key of dictionary stduent
print(x)
print("Values are : ")
for x in student.values(): ... | false |
62f00bee8fa502f4025c07c108ca66304417a1c2 | meenapandey500/Python_program | /multilevel_inh1.py | 970 | 4.5 | 4 | #example of multiLevel inheritance
class A: #base class
def __init__(self):
self.__x=int(input("Enter No. x : "))
def show_x(self):
print("X=",self.__x)
class B(A) : #here B derived class ans inherits base class A
def __init__(self):
super().__init__() #call constru... | false |
c31091af418177da7206836e40939b51c8f5afa0 | meenapandey500/Python_program | /asset.py | 497 | 4.125 | 4 | def KelvinToFahrenheit(Temperature):
assert (Temperature >= 0),"Colder than absolute zero!"
return ((Temperature-273)*1.8)+32
print(KelvinToFahrenheit(273))
print(int(KelvinToFahrenheit(505.78)))
print(KelvinToFahrenheit(-5))
'''When it encounters an assert statement, Python evaluates the accompanying
ex... | true |
882d2c3472802213860abae36c9ef9f0e8d65801 | meenapandey500/Python_program | /mini_cal.py | 448 | 4.28125 | 4 | #Write a program to create a Mini Calculator
a=float(input("Enter First Number = "))
b=float(input("Enter Second Number : "))
print("Sum of 2 Nos. : ",a," + ",b," = ",(a+b))
print("Subtract of 2 Nos. : ",a, " - ", b, " = " ,(a-b))
print("Multiply of 2 Nos. : ",(a*b))
print("Divide of 2 Nos. = ",(a/b))
... | false |
c01f1ae280d10c9d4a54f44a5561895a70c9489a | meenapandey500/Python_program | /mini_calculator1.py | 572 | 4.25 | 4 | #write a program to create a mini calculator
a=float(input("Enter First Number : "))
b=float(input("Enter Second Number : "))
print("press 1 for sum")
print("press 2 for subtract")
print("press 3 for multiply")
print("press 4 for divide")
choice=int(input("Enter your choice : "))
if(choice==1):
c=a+b
... | false |
182803c3fbabdc05d4db21adafc2a9800732c499 | victor-lima-142/Exercicios-Logica-Programacao | /Estrutura de Decisao/Exercicio 2/ProdutoBarato.py | 681 | 4.21875 | 4 | '''
Faça um programa que pergunte o preço de três produtos e informe qual produto você deve comprar, sabendo que a decisão é sempre pelo mais barato.
'''
produto1 = float(input('Qual preço do produto 1?\n'))
produto2 = float(input('Qual preço do produto 2?\n'))
produto3 = float(input('Qual preço do produto 3?\n'))
if... | false |
9847bcc11fc8fb376684ec283eb6c13eabf4e44e | nengvang/s2012 | /lectures/cylinder.py | 957 | 4.375 | 4 | # Things we need (should know)
#
# print
# Display a blank line with an empty print statement
# print
# Display a single item on a separate line
# print item
# Display multiple items on a line with commas (,) separated by spaces
# print item1, item2, item3
# print item,
#
# raw_input([prom... | true |
578de93ccb0c029d5ada5b837358451bc4612faa | stechermichal/codewars-solutions-python | /7_kyu/printer_errors_7_kyu.py | 1,260 | 4.28125 | 4 | """In a factory a printer prints labels for boxes. For one kind of boxes the printer has to use colors which, for
the sake of simplicity, are named with letters from a to m.
The colors used by the printer are recorded in a control string. For example a "good" control string would be
aaabbbbhaijjjm meaning that the p... | true |
954696eccde542040c6abd120b33878fead05e65 | stechermichal/codewars-solutions-python | /5_kyu/simple_pig_latin_5_kyu.py | 453 | 4.3125 | 4 | """Move the first letter of each word to the end of it, then add "ay" to the end of the word.
Leave punctuation marks untouched.
Examples
pig_it('Pig latin is cool') # igPay atinlay siay oolcay
pig_it('Hello world !') # elloHay orldway !"""
def pig_it(text):
text_list = text.split()
for i, value in enume... | true |
c062245d21b75405560e771c16b1811bd17d76b8 | NiteshPidiparars/Python-Tutorials | /PracticalProblem/problem4.py | 1,081 | 4.3125 | 4 | '''
Problem Statement:-
A palindrome is a string that, when reversed, is equal to itself. Example of the palindrome includes:
676, 616, mom, 100001.
You have to take a number as an input from the user. You have to find the next palindrome corresponding to that number.
Your first input should be the number of test cas... | true |
b5e59ae88dabef206e1ca8eba2a3029d5e71d632 | phriscage/coding_algorithms | /factorial/factorial.py | 889 | 4.46875 | 4 | #!/usr/bin/python2.7
""" return a factorial from a given number """
import sys
import math
def get_factorial(number):
""" iterate over a given number and return the factorial
Args:
number (int): number integer
Returns:
factorial (int)
"""
factorial = 1
for n in range(int(numbe... | true |
4eb679fa74d8e2bf33d3e58984f4c861ad0b7827 | gauravarora1005/python | /Strings Challenges 80-87.py | 1,973 | 4.21875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[2]:
first_name = input("enter your first name: ")
f_len = len(first_name)
print("Length of First Name ", f_len)
last_name = input("Enter the last name: ")
l_len = len(last_name)
print("Length for last name is: ", l_len)
full_name = first_name + " " + last_name
full_len =... | true |
d95e031490496dec7183f8f3fd21abcf9b0dd23d | fishiraki/Election_Analysis | /Python_practice.py | 2,734 | 4.375 | 4 | #print("Hello World")
counties = ["Arapahoe","Denver","Jefferson"]
#if counties[1] == 'Denver':
# print(counties[1])
#if counties[3] != 'Jefferson':
# print(counties[2])
#temperature = int(input("What is the temperature outside? "))
#if temperature > 80:
# print("Turn on the AC.")
#else:
# print("Open ... | false |
2d44b738e87fd3acc226f5c0a9d980ed58d30beb | kseet001/FCS | /Homework5/homework_qn1.py | 2,248 | 4.125 | 4 | # Homework 5 - Question 1
# Encrypt the following plaintext P (represented with 8-bit ASCII) using AES-ECB,
# with the key of 128-bit 0. You may use an existing crypto library for this exercise.
# P = SUTD-MSSD-51.505*Foundations-CS*
from Crypto.Cipher import AES
from binascii import hexlify, unhexlify
plaintext = "... | true |
133249b5665e99fb2291cff6ab49e0c1cb6c800c | vijaynchakole/Proof-Of-Concept-POC-Project | /Directory Operations/Directory_File_Checksum.py | 2,950 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Feb 19 01:02:26 2020
@author: Vijay Narsing Chakole
MD5 hash in Python
Cryptographic hashes are used in day-day life like in digital signatures, message authentication codes, manipulation detection, fingerprints, checksums (message integrity check), hash tables, password st... | true |
a1e3f0f77b787e2d3e1c4716b1267fc96a588e07 | Verissimosem2/programacao-orientada-a-objetos | /listas/lista-de-exercicios-03/questão9.py | 904 | 4.25 | 4 | numero = float (input("Digite o primeiro numero: "))
numero2 = float(input("Digite o segundo numero: "))
numero3 = float(input("Digite o terceiro numero: "))
if numero > numero2 and numero > numero3:
if numero2 > numero3:
print("",numero)
print("",numero2)
print("",numero3)
if numero3 > ... | false |
ed39c3de6ac1d1296c487fa8206493b46f3c8998 | KrishnaRauniyar/python_assignment_II | /f16.py | 1,567 | 4.125 | 4 | # Imagine you are creating a Super Mario game. You need to define a class to represent Mario. What would it look like? If you aren't familiar with SuperMario, use your own favorite video or board game to model a player.
from pynput import keyboard
def controller(key):
is_jump = False
if str(key) == 'Key.ri... | true |
4969f9c7fdbf0a5239bbf1e1e4d226b5ed336196 | KrishnaRauniyar/python_assignment_II | /f4.py | 629 | 4.25 | 4 | # Create a list. Append the names of your colleagues and friends to it. Has the id of the list changed?
# Sort the list.
# What is the first item on the list? What is the second item on the list?
# no id of list is not changed
def checkId(string):
arr = []
print("The is before append: ", id(arr))
for i ... | true |
8997c7f99aaf30cc10052590b11156b842204423 | LuizFernandoS/PythonCursoIntensivo | /Capitulo06_Dicionarios/06_03Glossary.py | 1,363 | 4.15625 | 4 | #"""6.3 – Glossário: Um dicionário Python pode ser usado para modelar um
#dicionário de verdade. No entanto, para evitar confusão, vamos chamá-lo de
#glossário.
#• Pense em cinco palavras relacionadas à programação que você conheceu
#nos capítulos anteriores. Use essas palavras como chaves em seu glossário e
#arma... | false |
064a70b66d0b9ac03455dedd3c7e857b7bfdb5aa | LuizFernandoS/PythonCursoIntensivo | /Capitulo03_IntroducaoListas/03_02Salute.py | 505 | 4.28125 | 4 | """3.2 – Saudações: Comece com a lista usada no Exercício 3.1, mas em vez de
simplesmente exibir o nome de cada pessoa, apresente uma mensagem a elas.
O texto de cada mensagem deve ser o mesmo, porém cada mensagem deve
estar personalizada com o nome da pessoa."""
#pg73
names=['Jorge', 'Victor', 'Ângelo']
print(... | false |
7b549e195ea36dba547744025e6e9b03fa487a3a | LuizFernandoS/PythonCursoIntensivo | /Capitulo05_InstrucoesIF/05_11OrdinalNumbers.py | 778 | 4.34375 | 4 | #5.11 – Números ordinais: Números ordinais indicam sua posição em uma lista,
#por exemplo, 1st ou 2nd, em inglês. A maioria dos números ordinais nessa
#língua termina com th, exceto 1, 2 e 3.
#• Armazene os números de 1 a 9 em uma lista.
#• Percorra a lista com um laço.
#• Use uma cadeia if-elif-else no laço para ... | false |
73181b0a6495350ba3b6bfd29da0f000da2ca5f2 | Data-Analisis/scikit-learn-mooc | /python_scripts/parameter_tuning_sol_01.py | 2,951 | 4.375 | 4 | # %% [markdown]
# # 📃 Solution for introductory example for hyperparameters tuning
#
# In this exercise, we aim at showing the effect on changing hyperparameter
# value of predictive pipeline. As an illustration, we will use a linear model
# only on the numerical features of adult census to simplify the pipeline.
#
# ... | true |
efc2a9bba1db46e90da4f3d1dffaa98ff3fc76ef | LingyeWU/unit3 | /snakify_practice/3.py | 837 | 4.1875 | 4 | # This program finds the minimum of two numbers:
a = int(input())
b = int(input())
if a < b:
print (a)
else:
print (b)
# This program prints a number depending on the sign of the input:
a = int(input())
if a > 0:
print (1)
elif a < 0:
print (-1)
else:
print (0)
# This program takes the coo... | true |
4bee428ac8e0dd249deef5c67915e62ba1057997 | Matshisela/Speed-Converter | /Speed Convertor.py | 1,100 | 4.34375 | 4 | #!/usr/bin/env python
# coding: utf-8
# ### Converting km/hr to m/hr and Vice versa
# In[1]:
def kmh_to_mph(x):
return round(x * 0.621371, 2) # return to the nearest 2 decimal places
def mph_to_kmh(x):
return round(1/ 0.621371 * x, 2) # return to the nearest 2 decimal places
# In[2]:
speed_km = float(i... | true |
5f90cf3ee2b9a95d877d3a61a5f4691535c182f3 | s-andromeda/PreCourse_2 | /Exercise_4.py | 1,469 | 4.5 | 4 | # Python program for implementation of MergeSort
"""
Student : Shahreen Shahjahan Psyche
Time Complexity : O(NlogN)
Memory Complexity : O(logN)
The code ran successfully
"""
def mergeSort(arr):
if len(arr) > 1 :
# Getting the mid point of the array and dividing the array into 2 using... | true |
1bdfb1dfe2b1d5c7b707a38f071a7167f6f514e8 | arpitsomani8/Data-Structures-And-Algorithm-With-Python | /Stack/Representation of a Stack using Dynamic Array.py | 1,517 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
@author: Arpit Somani
"""
class Node:
#create nodes of linked list
def __init__(self,data):
self.data = data
self.next = None
class Stack:
# default is NULL
def __init__(self):
self.head = None
# Checks if stack is empty
def isempty(self):
if self.head == ... | true |
b6d143eb55b431f047482aaf881c025382483c0a | SHIVAPRASAD96/flask-python | /NewProject/python_youtube/list.py | 432 | 4.1875 | 4 | food =["backing","tuna","honey","burgers","damn","some shit"]
dict={1,2,3};
for f in food:
#[: this is used print how many of the list items you want to print depending on the number of items in your list ]
print(f,"\nthe length of",f,len(f));
print("\n");
onTeam =[20,23,23235,565];
print("Here are the p... | true |
60fc8a28c92e1cf7c9b98260f1dee89940929d68 | tsaiiuo/pythonNLP | /set and []pratice.py | 1,015 | 4.34375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 23 15:24:16 2021
@author: huannn
"""
#list[item1,item2....]
a=['apple','melon','orange','apple']
a.append('tomato')
a.insert(3, 'tomato')
print(a)
a.remove('apple')
print(a)
a.pop(0)#pop out a certain position
print(a)
a1=['fish','pork']
#a.append(... | true |
ad1dcc7b5a7c601125ef8a5db39a1cd393af58a4 | celsopa/CeV-Python | /mundo01/ex028.py | 501 | 4.25 | 4 | # Exercício Python 028: Escreva um programa que faça o computador "pensar" em um número inteiro entre 0 e 5 e peça para o usuário tentar descobrir qual foi o número escolhido pelo computador. O programa deverá escrever na tela se o usuário venceu ou perdeu.
from random import randint
nPC = randint(0,5)
nUser = int(inp... | false |
c5847011cf3d5f5d59fc7fc58b903d0332c71973 | celsopa/CeV-Python | /mundo02/ex036.py | 786 | 4.25 | 4 | # Exercício Python 036: Escreva um programa para aprovar o empréstimo bancário para a compra de uma casa. Pergunte o valor da casa, o salário do comprador e em quantos anos ele vai pagar. A prestação mensal não pode exceder 30% do salário ou então o empréstimo será negado.
valorCasa = float(input("Informe o valor do i... | false |
512efa228df5979cddc8a2295705c3f9ab927177 | celsopa/CeV-Python | /mundo03/ex104.py | 570 | 4.125 | 4 | # Exercício Python 104: Crie um programa que tenha a função leiaInt(), que vai funcionar de forma semelhante
# à função input() do Python, só que fazendo a validação para aceitar apenas um valor numérico.
# Ex: n = leiaInt('Digite um n: ')
def leiaint(msg):
while True:
n = input(msg)
if n.isnumeri... | false |
4ec21acb5c414b5a34db008225502db8576e3003 | pawarspeaks/HACKTOBERFEST2021-2 | /PYTHON/pythagorean_theorem.py | 1,777 | 4.5 | 4 | #A Pythagorean theorem solver that accounts for whether the hypotenuse is known or not
def main():
def is_right():
righty = input("Do you have a right triangle (meaning one of the angles is 90 degrees)? (Y/N) ")
if y_or_n(righty) == "Y":
get_angles()
else:
not_right... | false |
152e7b7430ded1d3593c2ec9b3a2cec89d7d270d | pawarspeaks/HACKTOBERFEST2021-2 | /PYTHON/PasswordGen.py | 606 | 4.125 | 4 | import string
import random
#Characters List to Generate Password
characters = list(string.ascii_letters + string.digits + "!@#$%^&*()")
def password_gen():
#Length of Password from the User
length = int(input("Password length: "))
#Shuffling the Characters
random.shuffle(characters)
#Picking random Characters... | true |
de91aed8808c9c1562ace961b39d5e2f6d3d20bc | leolanese/python-playground | /tips/list-comprehensions.py | 318 | 4.34375 | 4 | # Python's list comprehensions
vals = [expression
for value in collection
if condition]
# This is equivalent to:
vals = []
for value in collection:
if condition:
vals.append(expression)
# Example:
even_squares = [x * x for x in range(10) if not x % 2
even_squares # [0, 4, 16, 36, 64]
| true |
ee2d5fa2d85740d0219040b80426b1ef57087857 | datasciencecampus/coffee-and-coding | /20191112_code_testing_overview/02_example_time_test.py | 1,166 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 11 10:28:55 2019
@author: pughd
"""
from datetime import datetime
class TestClass:
# Difficult to automate test this as depends on time of day!
def test_morning1(self):
assert time_of_day() == "Night"
# Far easier to... | true |
7042b216761fe26ce8ffa3e913f54a0508d19ca4 | sreelekha11/Number-Guessing | /NumberGuessingGame.py | 1,254 | 4.40625 | 4 | #Creating a simple GUI Python Guessing Game using Tkinter and getting the computer to choose a random number, check if the user guess is correct and inform the user.
import tkinter
import random
computer_guess = random.randint(1,10)
def Check():
user_guess = int(number_guess.get())
#Determine ... | true |
80372221944fbf2c560fd597e48d5e447a0bd4dd | henrikac/randomturtlewalk | /src/main.py | 1,077 | 4.375 | 4 | """A Python turtle that does a random walk.
Author: Henrik Abel Christensen
"""
import random
from turtle import Screen
from typing import List
from argparser import parser
from tortoise import Tortoise
args = parser.parse_args()
def get_range(min_max: List[int]) -> range:
"""Returns a range with the turtles ... | true |
53f1f2049a3a31a4a63a0fc38fb77d1466e3ffa3 | therealrooster/fizzbuzz | /fizzbuzz.py | 740 | 4.21875 | 4 | def fizzbuzz():
output = []
for number in range (1, 101):
if number % 15 == 0:
output.append('Fizzbuzz')
elif number % 3 == 0:
output.append('Fizz')
elif number % 5 == 0:
output.append('Buzz')
else:
output.append(number)
... | true |
81c8b00713bdc7169f2dcaf7051c1dc376385a5a | zeyuzhou91/PhD_dissertation | /RPTS/bernoulli_bandit/auxiliary.py | 1,561 | 4.15625 | 4 | """
Some auxiliary functions.
"""
import numpy as np
def argmax_of_array(array):
"""
Find the index of the largest value in an array of real numbers.
Input:
array: an array of real numbers.
Output:
index: an integer in [K], where K = len(array)
"""
# Simple but does... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.