blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
5ec9098bbeaa87dd56a064b55169d4c24569277e | m1ghtfr3e/Number-Guess-Game | /Number_guess_game_3trials_FINE.py | 853 | 4.3125 | 4 | """Guess number game"""
import random
attempt = 0
print("""
I have a number in mind between 1 and 10.
Do you want to guess it?
You have 3 tries!
Enjoy :)
""")
letsstart = input("Do you want to start? (yes/no): ")
if letsstart == 'yes':
print("Let's start")
else:
print("Ok, see you :) ")
computernumb... | true |
10fabfbedc56aa8401cbe038bd69b8d0938d48f3 | mahimadubey/leetcode-python | /maximum_subarray/solution2.py | 675 | 4.15625 | 4 | """
Find the contiguous subarray within an array (containing at least one number)
which has the largest sum.
For example, given the array [−2,1,−3,4,−1,2,1,−5,4],
the contiguous subarray [4,−1,2,1] has the largest sum = 6.
"""
class Solution:
# @param A, a list of integers
# @return an integer
def maxSubA... | true |
dcbe94018816bda8efcd8e5b702eb328c136d52f | binhyc11/MIT-course-6.0001 | /Finger exercise 4.1.1.py | 409 | 4.15625 | 4 | # Write a function isIn that accepts two strings as arguments and
# returns True if either string occurs anywhere in the other, and False otherwise.
# Hint: you might want to use the built-in str operation in.
def isIn (x, y):
if x in y or y in x:
return True
else:
return False
x... | true |
0727891d7bb90fcf5cdf57f35826dc033db1047c | Yogini824/NameError | /PartA_q3.py | 2,401 | 4.53125 | 5 | '''The game is that the computer "thinks" about a number and we have to guess it. On every guess, the computer will tell us if our guess was smaller or bigger than the hidden number. The game ends when we find the number.Also Define no of attemps took to find this hidden number.(Hidden number lies between 0 - 100)'''
... | true |
ceaf43928789e3a45e0d54d0b9bf756506f5a251 | Yogini824/NameError | /PartB_q3.py | 1,082 | 4.15625 | 4 | '''Develop a Python Program which prints factorial of a given number (Number should be User defined)'''
def factorial(n): # calling function to calculate factorial of given number
if n<0: # checking if n is positive or not
print("Enter a positiv... | true |
a139f9e0778fbd1d1fb3754cdcbd02bd308c5cc9 | pagsamo/google-tech-dev-guide | /leetcode/google/tagged/medium/inorder_binary_tree_traversal.py | 886 | 4.1875 | 4 | from typing import List
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
"""
Time complexity: O(N) since visit exactly N no... | true |
20f07ae9d39e0b191f52d4cc155a94493d1525b6 | pagsamo/google-tech-dev-guide | /leetcode/recursion/reverse_string.py | 419 | 4.15625 | 4 | from typing import List
def reverse_string(s:List[str]) -> None:
"""
To practice use of recursion
"""
def helper(start, end):
if start < end:
s[start], s[end] = s[end], s[start]
helper(start + 1, end - 1)
print("before", s)
n = len(s)
if n > 1: helper(0, n - ... | true |
3231ef6292673615fafdfb53aa733d57ffc3c61b | pagsamo/google-tech-dev-guide | /70_question/dynamic_programming/water_area.py | 1,119 | 4.1875 | 4 | """
Water Area
You are given an array of integers. Each non-zero integer represents the
height of a pillar of width 1. Imagine water being poured over all of the
pillars and return the surface area of the water trapped between the pillars
viewed from the front. Note that spilled water should be ignored.
Sample input:... | true |
4983f02c95329f98637ab43444ee4bf4e2da8346 | sresis/practice-problems | /CTCI/chapter-1/string-rotation.py | 799 | 4.125 | 4 | # O(N)
import unittest
def is_substring(string, substring):
"""Checks if it is a substring of a string."""
return substring in string
def string_rotation(str1, str2):
"""Checks if str2 is a rotation of str1 using only one call of is_substring."""
if len(str1) == len(str2):
return is_substring... | true |
23114beb0d00f2b55d54c4c9390c41d6c89dc70e | sresis/practice-problems | /recursion-practice/q6.py | 553 | 4.25 | 4 | """
Write a recursive function that takes in a list and flattens it. For example:
in: [1, 2, 3]
out: [1, 2, 3]
in: [1, [1, 2], 2, [3]]
out: [1, 1, 2, 2, 3]
"""
def flatten_list(lst, result=None):
## if length of item is > 1, flatten it
result = result or []
for el in lst:
if type(el) is list:
... | true |
dbd89843d85f927c8fb764183a2516d10863b26f | KyrillMetalnikov/A01081000_1510_V2 | /lab07/exceptions.py | 1,761 | 4.375 | 4 | import doctest
"""Demonstrate proper exception protocol."""
def heron(number) -> float:
"""
Find the square root of a number.
A function that uses heron's theorem to find the square root of a number.
:param number: A positive number (float or integer)
:precondition: number must be positive.
:... | true |
6962206a6b3052cb75d5887eefc836a25b73df7e | KyrillMetalnikov/A01081000_1510_V2 | /lab02/base_conversion.py | 1,924 | 4.40625 | 4 | """
Convert various numbers from base 10 to another base
"""
def base_conversion():
"""
Convert a base 10 number to another base up to 4 digits.
A user inputs a base between 2-9 then the program converts the input into an integer and displays the max number
possible for the conversion. The use... | true |
b0bdc1aef3cbdb35b9d6745ef02046a1449d389a | nandansn/pythonlab | /Learning/tutorials/chapters/operators/bitwise.py | 477 | 4.3125 | 4 | # Bitwise operators act on operands as if they were string of binary digits. It operates bit by bit, hence the name.
x = input("enter number x:")
y = input("enter number y:")
x = int(x)
y = int(y)
print("bitwise {} and {}".format(x,y), x & y)
print("bitwise {} or {}".format(x,y), x | y)
print("bitwise not of {} ".... | true |
83e8412a46c0f05b0d7c37a92f90bd768ddb073f | nandansn/pythonlab | /Learning/tutorials/chapters/operators/comparison.py | 556 | 4.125 | 4 | x = input("enter number x:")
y = input("enter number y:")
x = int(x)
y = int(y)
#check equal
print("check {} and {} are equal".format(x,y),x == y)
#check not equal
print("check {} and {} are not equal".format(x,y),x != y)
#check less than
print("check {} is less than {} ".format(x,y),x <y)
#check greater than
pri... | true |
a15aa28ac9f40f41a1b9c49ba70254c10d224139 | nandansn/pythonlab | /durgasoft/chapter35/dict.py | 797 | 4.25 | 4 | '''
update dictionary,
'''
d = {101:'durga',102:'shiva'}
d[103] = 'kumar' #if key not there, new value will be added.
d[101]='nanda' #if key already available, new value will be updated.
print(d)
' how to delete elements from the dictionary '
del d[101] # if the key present, then the key and value w... | true |
b002c745c7813fb63f8ab1b327697342df62cbd7 | nandansn/pythonlab | /durgasoft/chapter47/random-example.py | 427 | 4.15625 | 4 | from random import *
for i in range(10):
print(random())
for i in range(10):
print(randint(i,567)) # generat the int value, inclusive of start and end.
for i in range(10):
print(uniform(i,10)) #generate the float value, within the range. not inclusive of start and end values.
for i in range(1... | true |
89bad08e5b41e99386f42b0913f5434a4f6e9845 | nandansn/pythonlab | /Learning/tutorials/chapters/operators/identity.py | 331 | 4.28125 | 4 | # is and is not are the identity operators in Python.
# They are used to check if two values (or variables) are located on the same part of the memory.
x ="hello"
y ="hello"
print("x is y", x is y)
y = "Hello"
print("x is y", x is y)
print(" x is not y", x is not y)
x = [1,2,3]
y = [1,2,3]
print("x is not y", x... | true |
20fde4ae652feef6eca4d69dbb116d740b9a2e28 | nandansn/pythonlab | /Learning/forloopexample.py | 311 | 4.1875 | 4 | week_days = ['monday','tuesday','wednessday','thursday','friday']
week_ends= ['saturday','sunday']
count = 10;
for c in range(count):
print(c)
for day in week_days:
print(day)
else:
for day in week_ends:
print(day)
employees = {'name':'nanda'}
for emp in employees:
print(emp)
| false |
12fe67f6785b89a35ace0769e2733d45660b6b23 | nandansn/pythonlab | /durgasoft/chapter33/functions_of_tuple.py | 395 | 4.34375 | 4 | ''' functions of tuple: '''
'len()'
t = tuple(input('enter tuple:'))
print(t)
print(len(t))
'count occurence of the elelement'
print(t.count('1'))
'''sorting:
natural sorting order
'''
t=(4,3,2,1)
print(sorted(t))
print(tuple(sorted(t)))
print(tuple(sorted(t,reverse=True)))
'min and ma... | true |
13477e55ca09f571ac8ed4a1d2c0bf8ee6b87a45 | nandansn/pythonlab | /durgasoft/chapter15/using-eval-function.py | 716 | 4.1875 | 4 | print(""" we can use eval function to read data, when we use eval function no need to make type conversion""")
#a,b,c,d,e=eval([x for x in input("Enter data:").split()])
a = eval(input("enter a:"))
b = eval(input("enter b:"))
c = eval(input("enter c:"))
d = eval(input("enter d:"))
e = eval(input("enter e:"))
print(... | false |
581ad96b03b49138a25783d9cacd4bb132984259 | nandansn/pythonlab | /durgasoft/chapter13/shiftoperators.py | 272 | 4.53125 | 5 | print(""" shift operators how it works""")
print (1 << 2) # Rotate left most 2 bits to the right most.
print ( 10 >> 2) # Rotate right most 2 bits to the left most.
# for positive numbers left most bit is 0
# for negative numbers right most bit is 1
print (-10 >> 2) | true |
9ff4380dbf6e147c1ed42a320aa4fc16a123b92c | nandansn/pythonlab | /durgasoft/chapter35/functions-in-dict.py | 1,274 | 4.5 | 4 | 'function: to create empty dict'
d = dict()
'function: to create dict, by using list of tuples'
d= dict([(100,'nanda'),(200,'kumar'),(300,'nivrithi'),(400,'valar')])
print(d)
'''functions: dict()
list of tuples,
set of tuples,
tuple of tuples.
'''
'fucntion:length of dict'
print(len(d))
prin... | true |
12ce3055d8595e5e0be0910da1498e92cad8256e | nandansn/pythonlab | /durgasoft/chapter15/read-data.py | 256 | 4.3125 | 4 | print("""We have input function to read data from the console.
The data will be in str type we need to do type conversion.""")
dataFromConsole = input("Enter data:")
print("type of input is:", type(dataFromConsole))
print(type(int(dataFromConsole)))
| true |
ca5af9fee83c047ecce7df3a506a0bcaf779ee7c | ziGFriedman/Useful_code_snippets | /Strings/Is_lower_case.py | 314 | 4.21875 | 4 | '''Преобразует строку в верхний регистр при помощи метода str.lower() и сравнивает ее с оригиналом.'''
def is_lower_case(str):
return str == str.lower()
print(is_lower_case('abc'))
print(is_lower_case('a3@$'))
print(is_lower_case('Ab4'))
| false |
8b747601f10131996032aecdfc6375f4c2e99c4e | ziGFriedman/Useful_code_snippets | /Mathematics/Factorial.py | 638 | 4.53125 | 5 | '''Вычисляется факториал числа.'''
# Используется рекурсия. Если num меньше или равно 1, возвращается 1, а
# иначе – произведение num и factorial из num — 1. Сработает исключение,
# если num будет отрицательным или числом с плавающей точкой.
def factorial(num):
if not ((num >= 0) & (num % 1 == 0)):
raise Ex... | false |
d667e5a3f4185900a22a751283b9346b5af2613d | aalabi/learningpy | /addition.py | 233 | 4.1875 | 4 | # add up the numbers
num1 = input("Enter first number ")
num2 = input("Enter second number ")
# sum up the numbers
summation = num1 + num2
# display the summation
print("The sum of {0} and {1} is {2}".format(num1, num2, summation)) | true |
aa478143bf9f657b6938650e8d174dcb016d5f39 | Yvonnekatama/control-flow | /conditionals.py | 875 | 4.125 | 4 | # if else
age=25
if age >= 30:
print('pass')
else:
print('still young')
# ternary operator
temperature=30
read="It's warm today" if temperature >= 35 else "Wear light clothes"
print(read)
# if elif else
name='Katama'
if name=='Yvonne':
print('my name')
elif name=='Katama':
print("That's my sur name")
el... | true |
ee9e2becf70d3d9fc94ee4b6121913fa3cffd1ce | maloMal/Spirograph | /drawCircle.py | 345 | 4.28125 | 4 | import math
import turtle
#Draw the circle using turtle.
def drawCircleTurtle(x, y, r):
#move to the start of circle
turtle.up()
turtle.setpos(x + r, y)
turtle.down()
#Draw the circle
for i in range(0, 365, 6):
a = math.radians(i)
turtle.setpos(x + r*math.cos(a), y + r*math.sin(a))
drawCircleTurtle(100, 1... | false |
a4509cc29dfe24626d1f60e8c067b8078d039f75 | syurskyi/Math_by_Coding | /Programming Numerical Methods in Python/2. Roots of High-Degree Equations/2.1 PNMP_2_01.py.py | 287 | 4.15625 | 4 | '''
Method: Simple Iterations (for-loop)
'''
x = 0
for iteration in range(1,101):
xnew = (2*x**2 + 3)/5
if abs(xnew - x) < 0.000001:
break
x = xnew
print('The root : %0.5f' % xnew)
print('The number of iterations : %d' % iteration)
| true |
995c5e8d0ebb7a3012580a18c3bc14fcc15b187b | koheron2/pyp-w1-gw-language-detector | /language_detector/main.py | 1,194 | 4.25 | 4 | # -*- coding: utf-8 -*-
"""This is the entry point of the program."""
from collections import Counter
def detect_language(text, languages):
words_appearing = 0
selected_language = None
"""Returns the detected language of given text."""
for language in languages:
words = len([word for word in l... | true |
2970e898dbf7767dded0fca56e0c7cc30b32c3b9 | bmallia/python_exercise | /source/symetric_difference.py | 890 | 4.125 | 4 | """
O termo matemático Symetric Difference (t ou B) de 2 conjuntos é um conjunto de elementos
no qualquer um dos conjuntos mas não em ambos. Por exemplo: A = {1,2,3} e B = {2,3,4},
A E B = {1,4}
Symetric difference é uma operação binária, isso significa que ela opera em apenas elementos.
Então para... | false |
ed9c6d0b1ed6101d3aac0c6c75eaff51152b851d | joecmama/Python_0a | /02.py | 868 | 4.21875 | 4 | #!/usr/bin/env python
# basic math
print(2+3) # addition
print(2*3) # multiplication
print(2**3) # exponentiation
#
# # in python2: / means integer division (truncation) for integers
# # and floating pt division for floating point number
# #
# # in python3: / always means floating point division (like perl)
print(... | false |
77dec46a9d7fe561822d3ca4507ecbf773c433c0 | joecmama/Python_0a | /03.py | 469 | 4.28125 | 4 | #!/usr/bin/env python
# basic string operations
a = 'hello '
b = 'world'
c = a+b
print(c)
print(a == 'hello')
print(a < 'zebra')
print(a > 'zebra')
print(a < 'aardvark')
print(a != 'hello ')
#
print(c)
print(c.startswith('hello'))
print(c.endswith('world'))
print(len(c)) # length of a string
#
print('lo wo' in c) ... | false |
690170d51cd1f93932925e019f01d1f7dd90712e | gladysmae08/project-euler | /problem19.py | 1,430 | 4.375 | 4 | # counting sundays
'''
You are given the following information, but you may prefer to do some research for yourself.
1 Jan 1900 was a Monday.
Thirty days has September,
April, June and November.
All the rest have thirty-one,
Saving February alone,
Which has twenty-eight, rain or shine.
And on leap years, twe... | true |
c9f7b46835e56102fd280a80f992b6b2a5d76cd3 | shubhamrocks888/linked_list | /create_loop_or_length_loop.py | 1,198 | 4.125 | 4 | class node:
def __init__(self,data=None):
self.data = data
self.next = None
class linked_list:
def __init__(self):
self.head = None
def push(self,data):
new_node = node(data)
new_node.next = self.head
self.head = new_node
# Function to create a loop in the ... | true |
5e82215b548f332f5f56d1270345d01d38db1c80 | Explorerqxy/review_practice | /025.py | 1,049 | 4.28125 | 4 | def PrintMatrixClockwisely(numbers, columns, rows):
if numbers == None or columns <= 0 or rows <= 0:
return
start = 0
while columns > start * 2 and rows > start * 2:
PrintMatrixInCircle(numbers, columns, rows, start)
start += 1
def PrintMatrixInCircle(numbers, columns, rows, start):... | true |
47a42cfced82ca19f33265c6d5752766e7163756 | mariocpinto/0009_MOOC_Python_Data_Structures | /Exercises/Week_03/assignment_7_1.py | 502 | 4.6875 | 5 | # 7.1 Write a program that prompts for a file name,
# then opens that file and reads through the file,
# and print the contents of the file in upper case.
# Use the file words.txt to produce the output below.
# You can download the sample data at http://www.pythonlearn.com/code/words.txt
file_name = input('Enter Fi... | true |
55a730379685d64d717df81c1306430f6c6c5255 | brash99/phys441 | /nmfp/Cpp/cpsc217/area_triangle_sides.py | 775 | 4.25 | 4 | #!/usr/bin/env python
import math
s1 = input('Enter the first side of the triangle: ')
s2 = input('Enter the second side of the triangle: ')
s3 = input('Enter the third side of the triangle: ')
while True:
try:
s1r = float(s1)
s2r = float(s2)
s3r = float(s3)
if s1r<=0 or s2r<=0 or... | true |
c8216213d129bd12d845771e8a87f7b06eeb11fa | brash99/phys441 | /digits.py | 783 | 4.21875 | 4 | digits = [str(i) for i in range(10)] + [chr(ord('a') + i) for i in range(26)] # List of digits: 0-9, a-f
num_digits = int(input("Enter the number of digits: ")) # User input for the number of digits
possible_numbers = [] # List to store the possible numbers
def generate_numbers(digit_idx, number):
if digit_idx ... | true |
4ccceec7ce99deb87c2465b14de535a4108100f7 | brash99/phys441 | /JupyterNotebooks/DataScience/linear_regression.py | 1,380 | 4.34375 | 4 | import numpy as np
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
# create some data
#
# N.B. In linear regression, there is a SINGLE y-value for each data point, but there
# may be MULTIPLE x-values, corresponding to the multiple factors that might affect the
# experime... | true |
b3fc68dceb1f57d89daa42ec09c214fe0807897c | mbarbour0/Practice | /Another Rock Paper Scissors Game.py | 1,481 | 4.15625 | 4 | # Yet another game of Rock Paper Scissors
import os
import random
from time import sleep
options = {"R": "Rock", "P": "Paper", "S": "Scissors"}
def clear_screen():
"""Clear screen between games"""
if os.name == 'nt':
os.system('cls')
else:
os.system('clear')
def play_game():
"""General... | true |
dcb6d89fedc9ab9c2cd884a73904cf27633ba719 | shraysidubey/pythonScripts | /Stack_using_LinkedList.py | 1,634 | 4.21875 | 4 | #Stack using the LinkedList.
class Node:
def __init__(self,data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def appendHaed(self,new_data):
new_node = Node(new_data) #create the new node 370__--> head
... | true |
f0e18b65f8e66a9255a9dc7d110b775f916b6ff4 | nvcoden/working-out-problems | /py_2409_1.py | 744 | 4.21875 | 4 | '''
Question 1
Create methods for the Calculator class that can do the following:
1. Add two numbers.
2. Subtract two numbers.
3. Multiply two numbers.
4. Divide two numbers.
Sample Output :-
calculator = Calculator()
calculator.add(10, 5) ➞ 15
calculator.subtract(10, 5) ➞ 5
calculator.multiply(10, 5) ➞ 50
calcula... | true |
d16573cb2c78191a598895329f1889df7258c235 | chaoshenglu/learnPythonEasily | /5基本数据类型之Tuple/2.Tuple.py | 547 | 4.125 | 4 | # 如何用元祖来表示全班同学的姓名?
students = ('小明', '小红', '小强')
# 如何获取元祖中第三个同学的姓名?
print(students[2])
# 如何获取元祖中倒数第二个同学的姓名?
print(students[-2])
# 如何获取元祖的第1个到第3个元素?
print(students[0:3])
# 如何获取元祖的第1个到第-3个元素
print(students[0:-2])
# 将这个元祖重复两遍,形成一个新的元祖
students = students * 2 # 方法一
# students = students + students # 方法二
print(studen... | false |
eed94415f3966db3f3a0f7cd64af3ca53211b703 | chaoshenglu/learnPythonEasily | /4基本数据类型之List/4.List.py | 423 | 4.1875 | 4 | cities = ['北京', '上海', '深圳', '广州']
# 访问数组的第1个元素
print("cities[0]: ", cities[0])
# 访问数组的第1个到第3个元素
print("cities[0:3]: ", cities[0:3])
# 访问数组的第1个到第-3个元素
print("cities[0:-2]: ", cities[0:-2])
# 将这个数组重复两遍,形成一个新的数组
cities = cities * 2
print(cities)
# 遍历这个数组
for city in cities:
print(city)
| false |
ff659057aa4b939990bb320b3e2223d0e368ef20 | yujun858/mypython | /day29_1121_python/example02.py | 1,246 | 4.34375 | 4 | # 享元模式;
# 咖啡出售系统
class Coffee():
name =''
price=0
def __init__(self,name):
self.name = name
self.price = len(name)#假设咖啡价格咖啡名字
def show(self):
print('Coffee Name: %s Coffee Price %f'%(self.name,self.price))
class Customer():
name =''
coffeeFactory = ''
def __init__(se... | false |
e2164210c928ad2d6db88c61eab833d8ab5a199a | rajjoan/PythonSamples | /Chapter 5/ADcalculator.py | 729 | 4.34375 | 4 | # Get user input
num1 = input("Enter a number : ")
num2 = input("Enter another number : ")
symbol = input("Enter a symbol (* + - /) : ")
# Subtraction
if symbol == "-":
if num2 >= num1:
print(int(num2)-int(num1))
else:
print(int(num1)-int(num2))
# Division
if symbol == "/":
if nu... | false |
e853965a25662783b57054c0bf75a09a9ebe3615 | rajjoan/PythonSamples | /Chapter 13/function7.py | 215 | 4.25 | 4 | def evenorodd(number):
if number % 2 == 0:
print("The number is even")
else:
print("this number is odd")
n=int(input("Enter a number to finf even or odd : "))
evenorodd(n)
| true |
7fcf47e618ff34c9011d3cbd6ffca9bbaebff4b7 | kuxingseng/learnPython | /TestItertools.py | 544 | 4.1875 | 4 |
# 操作迭代器对象
# count
# 死循环
# import itertools
# natuals = itertools.count(1)
# for n in natuals:
# print(n)
import itertools
ns = itertools.repeat('abc', 2)
for n in ns:
print(n)
# chain 串联迭代器
for c in itertools.chain('abc', 'def'):
print(c)
# groupby 把迭代器中相邻的重复元素挑出来放在一起
for key, group in itertools.g... | false |
5bcf95b1954ac33b4698863f3900d466a6805539 | angelblue05/Exercises | /codeacademy/python/while.py | 1,298 | 4.21875 | 4 | num = 1
while num < 11: # Fill in the condition
# Print num squared
print num * num
# Increment num (make sure to do this!)
num += 1
# another example
choice = raw_input('Enjoying the course? (y/n)')
while choice != "y" and choice != "n": # Fill in the condition (before the colon)
choice = ... | true |
98c0a56d846d180558421ee8ad664466349e85fd | Gaoliu19910601/python3 | /tutorial2_revamp/tut4_boolean_cond.py | 1,418 | 4.1875 | 4 | print('')
print('-----------------BOOLEAN AND CONDITION-----------------------')
print('')
language = 'Java'
# If the language is python then it is a true condition and would print
# the first condition and so forth for the next. However if everything
# is False there would be no match
if language is 'Python':
p... | true |
e4771801e9edfa915000c7522e092b4447189169 | Gaoliu19910601/python3 | /tutorial2_revamp/tut5_loops.py | 525 | 4.15625 | 4 |
nums = [1, 2, 3, 4, 5]
# The for loop with an if condition along with a continue statement
for num in nums:
if num == 3:
print('Found it!')
continue
print(num)
print('')
# Nested For loop
for letter in 'abc':
for num in nums:
print(num,letter)
print('')
for i in range(1, 11):
... | true |
47de4cf8b2e8ac30e5ed01605a5fc48f0c784224 | AakashKB/5_python_projects_for_beginners | /magic_8_ball.py | 670 | 4.125 | 4 | import random
#List of possible answer the 8 ball can choose from
potential_answers = ['yes','no','maybe','try again later',
'you wish','100% yes','no freaking way']
print("Welcome to the Magic 8 Ball")
#Infinite loop to keep the game running forever
while True:
#Asks user for inpu... | true |
c1f77aca918cb0b177d9f42a314ff9186c4cb051 | rdegraw/numbers-py | /fibonacci.py | 423 | 4.25 | 4 | #----------------------------------------
#
# Fibonacci number to the nth position
#
#----------------------------------------
position = int( raw_input( "Please enter the number of Fibonacci values you would like to print: " ))
sequence = [0]
while len(sequence) < position:
# F(n) = F(n-1) + F(n-2)
if len(sequen... | true |
4d0987b5fca0c8342c604f9e18cec3493dbea869 | limchiahau/ringgit | /ringgit.py | 2,001 | 4.15625 | 4 | from num2words import num2words
import locale
locale.setlocale(locale.LC_ALL,'')
def to_decimal(number):
'''
to_decimal returns the given number as a string
with groupped by thousands with 2 decimal places.
number is a number
Usage:
to_decimal(1) -> "1.00"
to_decimal(1000) -> "1,000.00... | true |
20f1dbf7f0016a9a37158b325682504e3ca3fae9 | Idealistmatthew/MIT-6.0001-Coursework | /ps4/ps4a.py | 2,185 | 4.375 | 4 | # Problem Set 4A
# Name: <your name here>
# Collaborators:
# Time Spent: x:xx
def get_permutations(sequence):
'''
Enumerate all permutations of a given string
sequence (string): an arbitrary string to permute. Assume that it is a
non-empty string.
You MUST use recursion for this part. Non-recursi... | true |
16865ccc69e24a0ab37cc8b9dfa4f1e3ec7dbfac | sd-karthik/karthik-repo | /Training/5.python/DAY2/fun_var_arguments.py | 264 | 4.40625 | 4 | # FILE : fun_var_arguments.py
# Function : Factorial of a number using recursion
def recur(num):
if not num:
return num*recur(num-1)
else:
return 1
num1 = input("Enter a number to find its Factorial\n")
total = recur(num1 )
print "FACT(", num1,"):", total
| true |
c665108b6cf623aae18c528df3fda336d7ce0864 | sd-karthik/karthik-repo | /Training/python/DAY1/FIbanacci.py | 711 | 4.125 | 4 | # Print Fibonacci series
print "PRINTING FIBONACCI SERIES"
print "Choose your choice\n1.\t Using Maximum limit"
print "2.\t Using Number of elements to be prtinted"
choice = input()
ele = 1
ele2 = 0
# Printing Fibonacci the maximum limit
if choice == 1 :
limit = input("Enter the Maximum limit")
if (ele < 1):
pr... | true |
0124d1b39ff94f880401d0ece0b0ef7612e9a8cc | sd-karthik/karthik-repo | /Training/5.python/DAY5/map.py | 536 | 4.4375 | 4 | # FILE: map.py
# Functions : Implementation of map
# -> Map will apply the functionality of each elements# in a list and returns the each element
def sqr(x):
return x*x
def mul(x):
return x*3
items = [1,2,3,4,5]
print "map: sqr:", map(sqr, items)
# returns a list
list1 = map(lambda x:x*x*x, items )
prin... | true |
329a3366d612789862c773edaded12703b68da32 | wwymak/algorithm-exercises | /integrator.py | 1,718 | 4.6875 | 5 | """
Create a class of Integrator which numerically integrates the function f(x)=x^2 * e^−x * sin(x).
You need to provide the class with the minimum value xMin, maximum value xMax and the number of steps N for integration.
Then the integration process should be carried out accroding to the below information.
Suppose t... | true |
d79fbe4393091a929a8d1e645d17e73510275986 | ryokugyu/machine-learning-models | /basic_CNN.py | 1,692 | 4.1875 | 4 | '''
Implementing a simple Convolution Neural Network aka CNN
Adapated from this article: https://towardsdatascience.com/building-a-convolutional-neural-network-cnn-in-keras-329fbbadc5f5
Dataset: MNIST
'''
import tensorflow as tf
from keras.dataset import mnist
from keras.utils import to_categorical
from keras.models im... | true |
72cf8c17498315d97182bec675578d40e254633a | Chippa-Rohith/daily-code-problems | /daily problems pro solutions/problem4_sorting_window_range.py | 835 | 4.1875 | 4 | '''Hi, here's your problem today. This problem was recently asked by Twitter:
Given a list of numbers, find the smallest window to sort such that the whole list will be sorted. If the list is already sorted return (0, 0). You can assume there will be no duplicate numbers.
Example:
Input: [2, 4, 7, 5, 6, 8, 9]
Output:... | true |
e3bfbdcefaa83965cf00323b9ed21e584d49a118 | tdtshafer/euler | /problem-5.py | 644 | 4.125 | 4 | """
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
"""
UPPER_LIMIT = 20
def main():
divisible_number = get_divisible_number()
print("The smallest positive num... | true |
e12925a5059f4578698810992b1af350f525c099 | rndmized/python_fundamentals | /problems/palindrome_test.py | 632 | 4.53125 | 5 |
#Funtion will take a string, format it getting rid of spaces and converting all
# characters to lower case, then it will reverse the string and compare it to
# itself (not reversed) to chek if it matches or not.
def is_palindrome(word):
formated_word = str.lower(word.replace(" ",""))
print(formated_word)
... | true |
2c10cf1677039d7ddb669acf31f16cae1027d72d | bluelotus03/build-basic-calculator | /main.py | 2,215 | 4.34375 | 4 |
# This is a basic calculator program built with python
# It does not currently ensure numbers and operators are in the correct format when input, so if you want to enjoy the program, make sure you input numbers and operators that are allowed and at the right place <3
# ------------FUNCTIONS---------------------------... | true |
99bd1373e5c05ab985ec744988b9d25ba002b0aa | reeynaldo/Ejercicios-1er-Parcial | /Nota Final.py | 411 | 4.15625 | 4 | nota = int(input("¿Cuánto sacaste en tu nota final?: "))
if nota <= 0:
print("Error, ingrese calificacion correcta")
elif nota < 5:
print("Suspenso")
elif nota == 5:
print("Suficiente")
elif nota == 6:
print("Aprobado")
elif nota == 7:
print("Notable")
elif nota > 10:
pri... | false |
552c626ee36d4c5bdf4f983872582ed95430ad40 | I3at57/ScribUTT | /build/src/parts/code/example.py | 651 | 4.21875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
def square_and_multiply(x: int, exponent: int, modulus: int = None, Verbose: bool = False):
"""
Square and Multiply Algorithm
x: positive integer
exponent: exponent integer
modulus: module
Returns: x**exponent or x**exponent mod modul... | false |
6789ade79015ec8d4fa7552882a90b21efe697de | rushabh95/practice-set | /1.py | 306 | 4.1875 | 4 | # Write a Python program which accepts a sequence of comma-separated numbers from user and generate a list and a
#tuple with those numbers.
#Sample data : 3, 5, 7, 23
m=()
n = []
i = 0
while i < 4:
a = int(input("enter a number: "))
n.append(a)
i+=1
print(n)
m = tuple(n)
print(m)
| true |
4ddda8da0be4ee303de96079c0ee4e247343836a | Jdicks4137/function | /functions.py | 1,419 | 4.46875 | 4 | # Josh Dickey 9/21/16
# This program solves quadratic equations
def print_instructions():
"""This gives the user instructions and information about the program"""
print("This program will solve any quadratic equation. You will be asked to input the values for "
"a, b, and c to allow the program to s... | true |
575de7537ae45b6d88a0b208999b95fd34dcb314 | birkoff/data-structures-and-algorithms | /minswaps.py | 1,856 | 4.40625 | 4 | '''
There are many different versions of quickSort that pick pivot in different ways.
- Always pick first element as pivot.
- Always pick last element as pivot (implemented below)
- Pick a random element as pivot.
- Pick median as pivot.
'''
def find_pivot(a, strategy='middle'):
if strategy and 'middle' == strate... | true |
4bc3fc901daf36615ffb6d76dc103c1fc56c9c69 | alex-rantos/python-practice | /problems_solving/binaryTreeWidth.py | 1,597 | 4.125 | 4 | import collections
"""Given a binary tree, write a function to get the maximum width of the given tree. The width of a tree is the maximum width among all levels.
The binary tree has the same structure as a full binary tree, but some nodes are null.
The width of one level is defined as the length between the end-node... | true |
2991deeeb5aa13cc1a542f989111479f0b5680a8 | alex-rantos/python-practice | /problems_solving/sortColors.py | 1,248 | 4.21875 | 4 | from typing import List
"""
Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue.
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
"""
class Solu... | true |
4d8a8b1dc9e26df64db21565ae4f6ba97d9120fd | alex-rantos/python-practice | /problems_solving/hammingDIstance.py | 529 | 4.15625 | 4 | """
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Given two integers x and y, calculate the Hamming distance.
"""
class Solution:
def hammingDistance(self, x: int, y: int) -> int:
xorResult = x ^ y
hd = 0
while xorResult... | true |
6fd1b9e364aa0650e4601f0973d79e8927c8759a | alex-rantos/python-practice | /problems_solving/remove_unnecessary_lists.py | 906 | 4.375 | 4 | """
Extracts all inner multi-level nested lists and returns them in a list.
If an element is not a list return the element by itseft
"""
from itertools import chain
# stackoverflow answer
def remove_unnecessary_lists(nested_list):
for item in nested_list:
if not isinstance(item,list):
yield ... | true |
20bd0c0f04c09ad0bb8fa522b113e43c5a99c0db | shilihui1/Python_codes | /dict_forloop.py | 565 | 4.40625 | 4 | '''for loop in dictionary, using dictionary method a.items()'''
a = {1: 'a', 2: 'b', 3: 'c', 4: 'd'}
# items method for dictionary
for key, value in a.items():
print(str(key) + "--" + str(value))
# keys method for dictionary
for key in a.keys():
print(key)
# values method for dictionary
for value in a.values(... | true |
9de6c6484fb918a933fe19a4f8d90d0c7e4e91ed | Maksov/geekbrains-python | /lesson01/home_work/hw01_hard.py | 804 | 4.34375 | 4 | __author__ = 'Povalyaev Ivan'
# Задание-1:
# Ваня набрал несколько операций в интерпретаторе и получал результаты:
# Код: a == a**2
# Результат: True
# Код: a == a*2
# Результат: True
# Код: a > 999999
# Результат: True
# Вопрос: Чему была равна переменная a, если точно известно, что её
# значение не из... | false |
e4960cabf2330beb1601b933756820e83b9f87f0 | rickjiang1/python-automate-boring-stuff | /RegExp_Basic.py | 915 | 4.375 | 4 | #regular expression basics!!
#this is the way of how to define a phonenumber
'''
def isPhoneNumber(text):
if len(text)!=12:
print('This is more than 12 digit')
return False
for i in range(0,3):
if not text[i].isdecimal():
return False #no area code
if text[3]!='-':
... | true |
81c049631b64733a1583de85fdd078133dfd1476 | Kennedy-Njeri/All-python | /scope.py | 753 | 4.25 | 4 | #x = 25
#def my_func():
# x = 50
#return x
#print(x)
#print(my_func())
x = 25
def my_func():
x = 50
return x
#print(x)
#print(my_func())
my_func()
print (x)
#example 2
name = "kennedy"
def full():
#name = "sammy"
def hello():
print ("hello "+ name)
hello()
full(... | false |
fad659a950108ac733dc6821e1506181c21c7fe5 | makaiolam/conditions-and-loops | /main.py | 1,955 | 4.125 | 4 |
# first = input("what is your first name")
# last = input("what is your last name")
# print(f"you are {last}, {first}")
#loops
#-----------------------------
# print(1)
# print(2)
# print(3)
# print(4)
# print(5)
#while loop
# while loop takes a boolean epxression (t/f)
#boolean operations
#---------------------... | true |
d26cd8f44b032e6233a2aa5399b4623ce2b3cfaf | TL-Web30/CS35_IntroPython_GP | /day1/00_intro.py | 1,407 | 4.25 | 4 |
# This is a comment
# lets print a string
# print("Hello, CS35!", "Some other text", "and theres more...")
# variables
# label = value
# let const var (js)
# int bool short (c)
# first_name = "Tom"
# # print("Hello CS35 and" , first_name)
# num = 23.87
# # f strings
# my_string = " this is a string tom"
# print(m... | true |
34ca0dcd4b1d1fe1187faa5e271f7cd58a8766f1 | JasonLuis/python-basico | /estrutura_de_repeticao_for.py | 549 | 4.3125 | 4 | """
## Estrutura de repetição – for
"""
print(1)
print(2)
print(3)
print(4)
print(5)
for numero in range(1, 6):
print(numero)
5 + 4 + 3 + 2 + 1
print("\n\n")
for numero in range(5, 0, -1):
print(numero)
print("\n\n")
soma = 0
for numero in range(1, 6):
soma = soma + numero
#print(soma)
print(soma)
print... | false |
166366c2f5457e02d5aee7dd44936a966ca17f56 | tringhof/pythonprojects | /ex15.py | 806 | 4.21875 | 4 | #import argv from sys module
from sys import argv
#write the first argv argument into script, the second into filename
script, filename = argv
#try to open the file "filename" and save the file object into txt
txt = open(filename)
print "Here's your file %r: " %(filename)
#use the read() command on that file object... | true |
3868ad37a26a7ca1b5799e155c5433200e5c98ff | bmilne-dev/cli-games | /hangman.py | 2,259 | 4.40625 | 4 | # a hangman program from scratch.
from random import randint
filename = "/home/pop/programming/python_files/word_list.txt"
with open(filename) as f:
words = f.read()
word_list = words.split()
# define a function to select the word
def word_select(some_words):
"""choose a word for hangman from a word list"""... | true |
4b4a167aaefb2d6ccb840937f02b32a2fab0ae71 | jamesledwith/Python | /PythonExercisesWk2/4PercentageFreeSpace.py | 627 | 4.28125 | 4 | #This program checks the percentage of disk space left and prints an apropiate response
total_space = float(input("Enter total space: "))
amount_used = float(input("Enter amount used: "))
free_space_percent = 100 * (total_space - amount_used) / total_space;
print(f"The percentage of free space is {free_space_perc... | true |
25f42be209ce937b382bd74243f2ce5a4df391c5 | jamesledwith/Python | /PythonExercisesWk2/3MatchResults.py | 472 | 4.125 | 4 | #This program displays a match result of two teams
hometeam_name = input("Home team name? ")
hometeam_score = int(input("Home team score? "))
awayteam_name = input("Away team name? ")
awayteam_score = int(input("Away team score? "))
if hometeam_score > awayteam_score:
print("Winner: ",hometeam_name)
elif away... | true |
1de73cda72d4391293a1631173215ba74174d025 | jamesledwith/Python | /PythonExercisesWk1/11VoltageToDC.py | 327 | 4.40625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 23 12:59:21 2020
@author: James
"""
import math
print("This program calculates the Voltage in a DC Circuit")
power = int(input("Enter the power: "))
resistance = int(input("Enter the resistance: "))
voltage = math.sqrt(power * resistance)
print(f"Voltage is {volta... | true |
e8cd3d172cba768564a53ad50340913e243ef8fa | hsalluri259/scripts | /python_scripts/odd_even.py | 946 | 4.53125 | 5 | #!/opt/app/python3/bin/python3.4
'''
Ask the user for a number. Depending on whether the number is even or odd, print out an appropriate message to the user. Hint: how does an even / odd number react differently when divided by 2?
Extras:
If the number is a multiple of 4, print out a different message.
Ask th... | true |
5f33814fd3a76665dd4deef46a623231757236b1 | MrWQ/Parser | /Analysis/Stack.py | 1,323 | 4.25 | 4 | class Stack(object):
# 初始化栈为空列表
def __init__(self):
self.items = []
# 判断栈是否为空,返回布尔值
def is_empty(self):
return self.items == []
# 返回栈顶元素
def peek(self):
if (self.is_empty() == False):
return self.items[len(self.items) - 1]
# 返回栈的大小
def size(self):
... | false |
8026ce987b2ed319dee7faf702c82772be01e708 | dzhonapp/python_programs | /Loops/averageRainfall.py | 1,003 | 4.375 | 4 | '''Write a program that uses nested loops to collect data and calculate the average rainfall
over a period of years. The program should first ask for the number of years. The outer loop
will iterate once for each year. The inner loop will iterate twelve times, once for each month.
Each iteration of the inner loop will ... | true |
94b675bb81acbb2d07829c4180920a36bb601b8b | dzhonapp/python_programs | /Basics/Celsius to Fahreneit Temperature Converter.py | 429 | 4.25 | 4 | '''9. Celsius to Fahrenheit Temperature Converter
Write a program that converts Celsius temperatures to Fahrenheit temperatures. The formula
is as follows:
F =9/5C+32
The program should ask the user to enter a temperature in Celsius, and then display the
temperature converted to Fahrenheit.
'''
fahreneit= int(input('... | true |
8d0ae7668e921e6e0047c1143cfbcdbf56f701a6 | dzhonapp/python_programs | /functions/milesPerGallon.py | 507 | 4.34375 | 4 | '''Miles-per-Gallon
A car’s miles-per-gallon (MPG) can be calculated with the following formula:
MPG = Miles driven / Gallons of gas used
Write a program that asks the user for the number of miles driven and the gallons of gas
used. It should calculate the car’s MPG and display the result.
'''
def mpgCalculate():
... | true |
ebec474eb20cfa6f338595a9bccf23b95a541dfd | dzhonapp/python_programs | /Loops/oceanLevels.py | 382 | 4.3125 | 4 | '''
Assuming the ocean’s level is currently rising at about 1.6 millimeters per year, create an
application that displays the number of millimeters that the ocean will have risen each year
for the next 25 years.
'''
millimeters=1.6
for years in range(25):
print("Year #", years+1)
print('Millimeters risen so far... | true |
7780f37587dc6bc07109b72911dc720f332268ad | garimadawar/LearnPython | /DynamicAvg.py | 262 | 4.1875 | 4 | print("Calculate the sum and average of two numbers")
number1 = float(input("Enter the first number"))
number2 = float(input("Enter the second number"))
print("the sum equals to " , number1 + number2)
print("average equals to " , (number1 + number2) / 2)
| true |
c1fa73caced9e5aeafe0e282ae88e6cb5c58a7fd | justinhinckfoot/Galvanize | /github/Unit 1 Exercise.py | 1,662 | 4.34375 | 4 | # Unit 1 Checkpoint
# Challenge 1
# Write a script that takes two user inputted numbers
# and prints "The first number is larger." or
# "The second number is larger." depending on which is larger.
# If the numbers are equal print "The two numbers are equal."
first = int(input('Enter first test value: '))
second = int... | true |
2c86f82938fc6dd74902d3b17969b435f73a0f49 | Dragonet-D/python3-study | /10-30/集合.py | 1,801 | 4.15625 | 4 | # 去重 关系测试 测试两个列表的 交集 并集
# 集合也是无序的
a = set([3, 4, 5, 6, 2, 3])
print(a)
list_1 = [1, 3, 4, 5, 234, 23, 2, 2, 3, 4, 5]
list_1 = set(list_1)
list_2 = set([2, 3, 45, 4, 6, 12, 34])
list_3 = set([1, 2, 4])
'''
print(list_1, type(list_1)) # <class 'set'>
print(list_1, list_2)
# 取交集 intersection &
print(list_1.intersectio... | false |
9519d3910c4cd9122b1cb633016d1f72e5c3a080 | yash001dev/learnpython | /_13.if_Project.py | 248 | 4.125 | 4 | weight=input("Enter Weight:")
unit=input('(L)bs or (K)g:')
if unit.upper()=="L":
converter=float(weight)*0.45
print(f"You are {converter} Kilos")
else:
converter=float(weight)/0.45
print(f"You are {converter} Pounds")
| false |
95350d0995ec53e75601c3db0010b9da7ce90ebe | ricek/lpthw | /ex11/ex11-1.py | 265 | 4.40625 | 4 | # Prompt the user to enter their name
# end='' arg tells print function to not end the line
print("First Name:", end=' ')
first = input()
print("Last Name:", end=' ')
last = input()
# Prints out formatted string with the given input
print(f"Hello {first} {last}")
| true |
9013585a902e8aa2384f162b4a8c25e730429778 | arossholm/Py_Prep | /egg_problem.py | 1,347 | 4.125 | 4 | # A Dynamic Programming based Python Program for the Egg Dropping Puzzle
# http://www.geeksforgeeks.org/dynamic-programming-set-11-egg-dropping-puzzle/
INT_MAX = 32767
def eggDrop(n, k):
# A 2D table where entery eggFloor[i][j] will represent minimum
# number of trials needed for i eggs and j floors.
eggFl... | true |
15736fddabeae0cc481fec6bc6c40bdecae06799 | KabanguJDTshikuma/my-practices | /Who likes it/whoLikesIt.py | 546 | 4.125 | 4 | def likes(names):
if len(names) == 1:
return names[0] + ' likes this'
elif len(names) == 2:
return str(names[0]) + ' and ' + str(names[1]) + ' like this'
elif len(names) == 3:
return str(names[0]) + ', ' + str(names[1]) + ' and ' + str(names[2]) + ' like this'
elif len(... | false |
7059aba4cb753cfbd24f357b8ca4a1aac5cea3ae | sagaar333/Python | /mergeSort.py | 573 | 4.25 | 4 | import Bubble_Sort
def mergeSort(l1,l2):
l3=[]
i=0
j=0
while(i<len(l1))&(j<len(l2)):
if(l1[i]<l2[j]):
l3.append(l1[i])
i+=1
else:
l3.append(l2[j])
j+=1
if(i<len(l1)):
l3.extend(l1[i:])
else:
l3.exten... | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.