blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
d5c1e62a45a8f54b456a5222850a37b3b0575df8 | atehortua1907/Python | /MasterPythonUdemy/10-EjerciciosBloque2/10.1-Ejercicio1.py | 967 | 4.46875 | 4 | """
Hacer un programa que tenga una lista de
8 numeros enteros y haga lo siguiente:
- Recorrer la lista y mostrarla
- Hacer funcion que recorra listas de numeros y devuelva un string
- Ordenarla y mostrarla
- Mostrar su longitud
- Busca algun elemento (que el usuario pida por teclado)
"""
... | false |
dcdbd68cea46053d4c116d19d5ed64f0d26eca1f | obaodelana/cs50x | /pset6/mario/more/mario.py | 581 | 4.21875 | 4 | height = input("Height: ")
# Make sure height is a number ranging from 1 to 8
while (not height.isdigit() or int(height) not in range(1, 9)):
height = input("Height: ")
# Make range a number
height = int(height)
def PrintHashLine(num):
# Print height - num spaces
print(" " * int(height - num), end="")
... | true |
014130aa0b43faecfbb0737cb47bf66bbf6bd318 | carriekuhlman/calculator-2 | /calculator.py | 2,425 | 4.25 | 4 | """CLI application for a prefix-notation calculator."""
from arithmetic import (add, subtract, multiply, divide, square, cube,
power, mod, )
# loop for an input string
# if q --> quit
# otherwise: tokenize it
# look at first token
# do equation/math for whatever it corresponds to
# return as a... | true |
61d8cb65ed02a9dbd905897290709080c49ba886 | benjiaming/leetcode | /validate_binary_search_tree.py | 1,596 | 4.15625 | 4 | """
Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
The left subtree of a node contains only nodes with keys less than the node's key.
The right subtree of a node contains only nodes with keys greater than the node's key.
Both the left and righ... | true |
f7c50862b43c8c0386195cd4b01419c0ac6f7b21 | benjiaming/leetcode | /find_duplicate_subtrees.py | 1,636 | 4.125 | 4 | """
Given a binary tree, return all duplicate subtrees. For each kind of duplicate subtrees, you only need to return the root node of any one of them.
Two trees are duplicate if they have the same structure with same node values.
Example 1:
1
/ \
2 3
/ / \
4 2 4
/
4... | true |
f2d07b36bb42c0d8b1ec205cb3fa338d18719363 | benjiaming/leetcode | /rotate_image.py | 1,571 | 4.1875 | 4 | #!/bin/env python3
"""
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Note:
You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
Example 1:
Given input matrix =... | true |
31f07756faaa6a84752cc672f676c44554821b74 | Developer-Student-Club-Bijnor/Data_Structure_and_Algorithm | /DataStructure.py/Queue.py | 1,529 | 4.21875 | 4 | class Queue(object):
"""
Queue Implementation: Circular Queue.
"""
def __init__(self, limit=5):
self.front = None
self.rear = None
self.limit = limit
self.size = 0
self.que = []
def is_empty(self):
return self.size <= 0
def enQueue(self, item):
... | false |
b048988bbaa1a55c3010042e642d232d7e1e4698 | SDSS-Computing-Studies/004c-while-loops-hungrybeagle-2 | /task2.py | 520 | 4.21875 | 4 | #! python3
"""
Have the user enter a username and password.
Repeat this until both the username and password match the
following:
Remember to use input().strip() to input str type variables
username: admin
password: 12345
(2 marks)
inputs:
str (username)
str (password)
outputs:
Access granted
Access denied
example:... | true |
7779633f0c8bf9a73c3eafcc06e21beed0200332 | Nivedita01/Learning-Python- | /swapTwoInputs.py | 967 | 4.28125 | 4 | def swap_with_addsub_operators(x,y):
# Note: This method does not work with float or strings
x = x + y
y = x - y
x = x - y
print("After: " +str(x)+ " " +str(y))
def swap_with_muldiv_operators(x,y):
# N... | true |
43927a3adcc76846309985c0e460d64849de0fa7 | Nivedita01/Learning-Python- | /guess_game.py | 560 | 4.21875 | 4 | guess_word = "hello"
guess = ""
out_of_attempts = False
guess_count = 0
guess_limit = 3
#checking if user entered word is equal to actual word and is not out of guesses number
while(guess != guess_word and not(out_of_attempts)):
#checking if guess count is less than guess limit
if(guess_count < guess_lim... | true |
12f9dbff51caec4d245d00d5d6cc71d0c3c88b5f | rdumaguin/CodingDojoCompilation | /Python-Oct-2017/PythonFundamentals/Lists_to_Dict.py | 1,020 | 4.21875 | 4 | name = ["Anna", "Eli", "Pariece", "Brendan", "Amy", "Shane", "Oscar"]
favorite_animal = ["horse", "cat", "spider", "giraffe", "ticks", "dolphins", "llamas"]
def zipLists(x, y):
zipped = zip(x, y)
# print zipped
newDict = dict(zipped)
print newDict
return newDict
zipLists(name, favorite_animal)
# C... | true |
503355cdd49fa7399ed1062a112b8de55f1c0654 | tme5/PythonCodes | /Daily Coding Problem/PyScripts/Program_0033.py | 926 | 4.25 | 4 | '''
This problem was asked by Microsoft.
Compute the running median of a sequence of numbers. That is, given a stream of numbers, print out the median of the list so far on each new element.
Recall that the median of an even-numbered list is the average of the two middle numbers.
For example, given the sequence [2, 1, ... | true |
42716bcb27499c2079a9eda6925d9ae969217adf | tme5/PythonCodes | /CoriolisAssignments/pyScripts/33_file_semordnilap.py | 1,780 | 4.53125 | 5 | #!/usr/bin/python
'''
Date: 19-06-2019
Created By: TusharM
33) According to Wikipedia, a semordnilap is a word or phrase that spells a different word or phrase backwards. ("Semordnilap" is itself "palindromes" spelled backwards.) Write a semordnilap recogniser that accepts a file name (pointing to a list of wor... | true |
9801097af0d4a761dc1f96039b2cf86cac257c26 | tme5/PythonCodes | /CoriolisAssignments/pyScripts/21_char_freq.py | 1,200 | 4.40625 | 4 | #!/usr/bin/python
'''
Date: 18-06-2019
Created By: TusharM
21) Write a function char_freq() that takes a string and builds a frequency listing of the characters contained in it. Represent the frequency listing as a Python dictionary. Try it with something like char_freq("abbabcbdbabdbdbabababcbcbab").
'''
def... | true |
f869321ad3d5a053c4e10c8c0e84c83d25b33974 | tme5/PythonCodes | /CoriolisAssignments/pyScripts/30_translate_to_swedish.py | 1,031 | 4.15625 | 4 | #!/usr/bin/python
# -*- coding: latin-1 -*-
'''
Date: 19-06-2019
Created By: TusharM
30) Represent a small bilingual lexicon as a Python dictionary in the following fashion {"merry":"god", "christmas":"jul", "and":"och", "happy":gott", "new":"nytt", "year":"r"} and use it to translate your Christmas cards from E... | true |
34bf5628fe0ba8ef8d65065cfb3172b781f6ae08 | jonathanjchu/algorithms | /fibonacci.py | 997 | 4.4375 | 4 | import math
# comparison of different methods of calculating fibonacci numbers
def fibonacci_iterative(n):
a, b = 0, 1
for i in range(n):
a, b = b, a + b
return a
# slows down after around n=30
def fibonacci_recursive(n):
if n < 2:
return n
elif n < 3:
return 1
else:
... | false |
46bcbbe3a779b19a3c021be114ebb33846785e49 | thien-truong/learn-python-the-hard-way | /ex15.py | 617 | 4.21875 | 4 | from sys import argv
script, filename = argv
# A file must be opened before it can be read/print
txt = open(filename)
print "Here's your file {}:".format(filename)
# You can give a file a command (or a function/method) by using the . (dot or period),
# the name of the command, and parameteres.
print txt.read() # ca... | true |
8a745e216a89e5a3f6c9d4111ea2bc38d37e4eb7 | thien-truong/learn-python-the-hard-way | /ex18.py | 1,209 | 4.59375 | 5 | # Fuctions: name the pieces of code the way ravirables name strings and numbers.
# They take arguments the way your scripts take argv
# They let you make "tiny commands"
# this one is like your scripts with argv
# this function is called "print_two", inside the () are arguments/parameters
# This is like your script... | true |
4a98b19419c953a3b12a1df262c3674a6b3a8967 | kahuroA/Python_Practice | /holiday.py | 1,167 | 4.53125 | 5 | """#Assuming you have a list containing holidays
holidays=['february 14', 'may 1', 'june 1', 'october 20']
#initialized a list with holiday names that match the holidays list
holiday_name=['Valentines', 'Labour Day', 'Mashujaa']
#prompt user to enter month and date
month_date=input('enter month name and date')
#check i... | true |
3987d9b65bb9e9e5555e92c42bcdde97b3464e18 | linxiaoru/python-in-action | /examples/basic/function_default.py | 435 | 4.21875 | 4 | """
⚠️
只有那些位于参数列表末尾的参数才能被赋予默认参数值,意即在函数的参数列表中拥有默认参数值的参数不能位于没有默认参数值的参数之前。
这是因为值是按参数所处的位置依次分配的。举例来说,def func(a, b=5) 是有效的,但 def func(a=5, b) 是无效的。
"""
def say(message, times=1):
print(message * times)
say('Hello')
say('World', 5) | false |
ec3010b56ca544f4910d38d6bf5c5dc8e61ff30e | l-ejs-l/Python-Bootcamp-Udemy | /Lambdas/filter.py | 883 | 4.15625 | 4 | # filter(function, iterable)
# returns a filter object of the original collection
# can be turned into a iterator
num_list = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, num_list))
print(evens)
users = [
{"username": "Samuel", "tweets": ["IO love cake", "IO love cookies"]},
{"username": "Kat... | true |
c59e167d00e927e6ca41268b9490b3eb6722ad3d | l-ejs-l/Python-Bootcamp-Udemy | /Iterators-Generators/generator.py | 410 | 4.1875 | 4 | # A generator is returned by a generator function
# Instead of return it yields (return | yield)
# Can be return multiple times, not just 1 like in a normal function
def count_up_to(max_val):
count = 1
while count <= max_val:
yield count
count += 1
# counter now is a generator and i can call... | true |
d3b10c9fdd390fdf8068c1e343da8c334c034437 | l-ejs-l/Python-Bootcamp-Udemy | /Lambdas/zip.py | 437 | 4.4375 | 4 | # zip(iterable, iterable)
# Make an iterator that agregate elements from each of the iterables.
# Returns an iterator of tuples, where the i'th tuple contains the i'th element from each of the of the argument
# sequences or iterables.
# The iterator stops when the shortest input iterable is exhausted
first_zip = zip([... | true |
74e0cdcdf5b7d6c141295e055200eadec3a8619c | victoorraphael/wppchatbot | /maisOpção_Joao.py | 1,401 | 4.1875 | 4 | def saudacao():
print('Olá, digite seu nome: ')
nome = input()
while(True):
print('{}, digite o numero referente a opção desejada:'.format(nome))
print('\n')
print('1 - Novo pedido')
print('2 - Alteração de pedido')
print('3 - Mais opções')
op = int(i... | false |
448784979c9edc5a47e210b51f3eb317f81dad70 | rajeshpandey2053/Python_assignment_3 | /merge_sort.py | 939 | 4.1875 | 4 | def merge(left, right, arr):
i = 0
j =0
k = 0
while ( i < len(left) and j < len(right)):
if (left[i] <= right[j]):
arr[k] = left[i]
i = i + 1
else:
arr[k] = right[j]
j = j + 1
k = k + 1
# if remaining in left
while(i ... | false |
fae187d17f928d0791df8d0f4f7d5f678d09c5cd | AnanyaRao/Python | /tryp10.py | 224 | 4.28125 | 4 | def factorial(num):
fact=1;
i=1;
for i in range(i,num+1):
fact=fact*i;
return fact;
num=int(input('Enter the number:'))
fact=factorial(num);
print('The factorial of the number is:',fact) | true |
bf5ca4a2000a7d1ffa895ec758308b80ef1cb93a | calwoo/ppl-notes | /wengert/basic.py | 1,831 | 4.25 | 4 | """
Really basic implementation of a Wengert list
"""
# Wengert lists are lists of tuples (z, g, (y1,...)) where
# z = output argument
# g = operation
# (y1,...) = input arguments
test = [
("z1", "add", ["x1", "x1"]),
("z2", "add", ["z1", "x2"]),
("f", "square", ["z2"])]
# Hash table to... | true |
d3b6d836f217cfc764986f9873ab9d2dd92deb4c | wolfblunt/DataStructure-and-Algorithms | /Sorting/BubbleSort.py | 336 | 4.125 | 4 | def bubble_sort(nums):
for i in range(len(nums)-1):
for j in range(0,nums-1-i,1):
if nums[j] > nums[j+1]:
swap(nums, j ,j+1)
return nums
def swap(nums, i ,j):
temp = nums[i]
nums[i] = nums[j]
nums[j] = temp
if __name__ == '__main__':
nums = [12,34,23,1,5,0,56,22,-1,-56,-34,88,97,57]
bubble_sort(nu... | false |
936ce5e1d8181e03d394ba350ef26c10ee575bb6 | sonias747/Python-Exercises | /Pizza-Combinations.py | 1,614 | 4.15625 | 4 | '''
On any given day, a pizza company offers the choice of a certain
number of toppings for its pizzas. Depending on the day, it provides
a fixed number of toppings with its standard pizzas.
Write a program that prompts the user (the manager) for the number of
possible toppings and the number of toppings offered on th... | true |
62021b456a4f6fbaeed24422fa09429698a7459d | ethanschreur/python-syntax | /words.py | 346 | 4.34375 | 4 | def print_upper_words(my_list, must_start_with):
'''for every string in my_list, print that string in all uppercase letters'''
for word in my_list:
word = word.upper()
if word[0] in must_start_with or word[0].lower() in must_start_with:
print(word)
print_upper_words(['ello', 'hey', '... | true |
b5887edb1d489421105fe45ca7032fb136c479df | KenMatsumoto-Spark/100-days-python | /day-19-start/main.py | 1,614 | 4.28125 | 4 | from turtle import Turtle, Screen
import random
screen = Screen()
#
# def move_forwards():
# tim.forward(10)
#
#
# def move_backwards():
# tim.backward(10)
#
#
# def rotate_clockwise():
# tim.right(10)
#
#
# def rotate_c_clockwise():
# tim.left(10)
#
#
# def clear():
# tim.penup()
# tim.clear(... | true |
d3145d494d82b2757f415946e7240c3171d39dcb | ARSimmons/IntroToPython | /Students/SSchwafel/session01/grid.py | 2,264 | 4.28125 | 4 | #!/usr/bin/python
#characters_wide_tall = input('How many characters wide/tall do you want your box to be?: ')
##
## This code Works! - Commented to debug
##
#def print_grid(box_dimensions):
#
# box_dimensions = int(box_dimensions)
#
# box_dimensions = (box_dimensions - 3)/2
#
# print box_dimensions
#
# ... | false |
c56d992234d558fd0b0b49aa6029d6d287e90f2a | ARSimmons/IntroToPython | /Students/Dave Fugelso/Session 2/ack.py | 2,766 | 4.25 | 4 | '''
Dave Fugelso Python Course homework Session 2 Oct. 9
The Ackermann function, A(m, n), is defined:
A(m, n) =
n+1 if m = 0
A(m-1, 1) if m > 0 and n = 0
A(m-1, A(m, n-1)) if m > 0 and n > 0.
See http://en.wikipedia.org/wiki/Ackermann_funciton
Create a new module called ack.py in... | true |
d5071d9e6bac66ad7feae9c7bdaafb086c562f0f | ARSimmons/IntroToPython | /Students/SSchwafel/session01/workinprogress_grid.py | 1,630 | 4.28125 | 4 | #!/usr/bin/python
#characters_wide_tall = input('How many characters wide/tall do you want your box to be?: ')
##
## This code Works! - Commented to debug
##
#def print_grid(box_dimensions):
#
# box_dimensions = int(box_dimensions)
#
# box_dimensions = (box_dimensions - 3)/2
#
# print box_dimensions
#
# ... | false |
688ede91119829d5ec4b75452ef18a5a29d6bd29 | akidescent/GWC2019 | /numberWhile.py | 1,018 | 4.25 | 4 | #imports the ability to get a random number (we will learn more about this later!)
from random import *
#Generates a random integer.
aRandomNumber = randint(1, 20) #set variable aRandomNumber to random integer (1-20)
#can initialize any variable
# For Testing: print(aRandomNumber)
numGuesses = 0
while True: #set a ... | true |
694c11011b30fe791dcc3dda50955d0a3610380f | Diogo-Miranda/Curso-Python-3 | /exercicios/exercicio001-func.py | 1,161 | 4.28125 | 4 | """""
1 - Crie uma função que exibe uma saudação com os parâmetros saudacao e nome
"""""
def saudacao(saudacao="Seja bem-vindo", nome="Diogo"):
print(f'{saudacao} {nome}')
saudacao("Olá", "Erika")
"""""
2 - Crie uma função que recebe 3 números como parâmetros e exiba a soma entre eles
"""""
def sum(n1=0, n2=0, n3... | false |
4ff2b4316f03556cd8ef992efc1121b7e6c4fe18 | wiecodepython/Exercicios | /Exercicio 2/AdrianneVer/Exercicio_Apostila.py | 1,244 | 4.5625 | 5 | # >> Python como Calculadora
from math import pi, pow, sqrt
print("Hello, world!")
# Hello, world
#------------------Operadores matemáticos---------------#
# Operador Soma (+)
print(3 + 5)
print(9 + 12)
print(7 + 32)
print(4.5 + 7.3)
print(7.9 + 18.2)
print(3.6 + 34.1)
# Operador Subtração (-)
print(9-7)
print(15-20... | false |
6e53d955acd35f5f1da0fcdde636fa234e57bfcb | snail15/CodingDojo | /Python/week3/Dictionary/dictionary.py | 227 | 4.375 | 4 | dict = {
"name": "Sungin",
"country of birth": "Korea",
"age": 30,
"favorite language": "Korean"
}
def printdict(dict):
for key in dict:
print("My {0} is {1}".format(key, dict[key]))
printdict(dict) | false |
42f6e8a1a8cbd172c92d6ba4ad7a115ac3982bb7 | EugeneStill/PythonCodeChallenges | /open_the_lock.py | 2,132 | 4.125 | 4 | import unittest
import collections
# https://www.geeksforgeeks.org/deque-in-python/
class OpenTheLock(unittest.TestCase):
"""
You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: '0' through '9'.
The wheels can rotate freely and wrap around: for example we can turn '9' to be '0... | true |
3ea411d749f483c8fd5c63ad0ac7fd8a5c8c0a01 | EugeneStill/PythonCodeChallenges | /rotting_oranges.py | 2,767 | 4.125 | 4 | import unittest
from collections import deque
class OrangesRotting(unittest.TestCase):
"""
You are given an m x n grid where each cell can have one of three values:
0 representing an empty cell,
1 representing a fresh orange, or
2 representing a rotten orange.
Every minute, any fresh orange t... | true |
59a8864a5f317ead31eb8d93246776eed2342fec | EugeneStill/PythonCodeChallenges | /word_break_dp.py | 1,621 | 4.125 | 4 | import unittest
class WordBreak(unittest.TestCase):
"""
Given a string s and a dictionary of strings wordDict, return true if s can be segmented
into a space-separated sequence of one or more dictionary words.
Note that the same word in the dictionary may be reused multiple times in the segmentation.... | true |
26d1d171bfa5feab074dd6dafef2335befbc4ca7 | EugeneStill/PythonCodeChallenges | /unique_paths.py | 2,367 | 4.28125 | 4 | import unittest
import math
class UniquePaths(unittest.TestCase):
"""
There is a robot on an m x n grid. The robot is initially located at the top-left corner (i.e., grid[0][0]).
The robot tries to move to the bottom-right corner (i.e., grid[m - 1][n - 1]).
The robot can only move either down or right ... | true |
fdd5987f684a90e78ba5622fd37919c43951bd20 | EugeneStill/PythonCodeChallenges | /course_prerequisites.py | 2,711 | 4.34375 | 4 | import unittest
import collections
class CoursePrereqs(unittest.TestCase):
"""
There are a total of num_courses courses you have to take, labeled from 0 to num_courses - 1.
You are given an array prerequisites where prerequisites[i] = [ai, bi]
meaning that you must take course bi first if you want to t... | true |
57d16b965de6e4f82979f42656042af956145410 | EugeneStill/PythonCodeChallenges | /reverse_polish_notation.py | 2,516 | 4.21875 | 4 | import unittest
import operator
class ReversePolishNotation(unittest.TestCase):
"""
AKA Polish postfix notation or simply postfix notation
The valid operators are '+', '-', '*', and '/'.
Each operand may be an integer or another expression.
The division between two integers always truncates toward ... | true |
47656bdd5d6b6f46cb957f38ecc32184198f9829 | MariamBilal/python | /List.py | 1,008 | 4.65625 | 5 | # Making and Printing list
my_list = ['fish','dog','cat','horse','frog','fox','parrot','goat']
print(my_list)
#Using Individual Values from a List
for i in my_list:
print(i)
#Accessing elements in a List
print(my_list[0])
#To title the the items in list.
print(my_list[2].title())
#To print last character from t... | true |
4bc82f2bdf496610241ad272ee9f76b69713c51d | codilty-in/math-series | /codewars/src/highest_bi_prime.py | 1,100 | 4.1875 | 4 | """Module to solve https://www.codewars.com/kata/highest-number-with-two-prime-factors."""
def highest_biPrimefac(p1, p2, end):
"""Return a list with the highest number with prime factors p1 and p2, the
exponent for the smaller prime and the exponent for the larger prime."""
given_primes = set([p1, p2])
... | true |
d20b15088e93c670f2ddd84ec8d2b78ad0d63199 | codilty-in/math-series | /codewars/src/surrounding_prime.py | 1,328 | 4.25 | 4 | def eratosthenes_step2(n):
"""Return all primes up to and including n if n is a prime
Since we know primes can't be even, we iterate in steps of 2."""
if n >= 2:
yield 2
multiples = set()
for i in range(3, n+1, 2):
if i not in multiples:
yield i
multiples.updat... | true |
7a291a64dea198b5050b83dc70f5e30bcf8876f5 | codilty-in/math-series | /codewars/src/nthfib.py | 524 | 4.1875 | 4 | """This module solves kata https://www.codewars.com/kata/n-th-fibonacci."""
def original_solution(n):
"""Return the nth fibonacci number."""
if n == 1:
return 0
a, b = 0, 1
for i in range(1, n - 1):
a, b = b, (a + b)
return b
#better solution
def nth_fib(n):
"""Return the nth f... | true |
9b4a1f7ef0879176a70ee0324c49914d24c76c80 | achiengcindy/Lists | /append.py | 347 | 4.375 | 4 | # define a list of programming languages
languages = ['java', 'python', 'perl', 'ruby', 'c#']
# append c
languages.append('c')
print(languages)
# Output : ['java', 'python' ,'perl', 'ruby', 'c#', 'c']
# try something cool to find the last item,
# use **negative index** to find the value of the last item
print(language... | true |
3c35233bf3598594d8a13645d950d25ac4d05bca | psycoleptic/Python_class | /Funk Task 8.py | 747 | 4.34375 | 4 | #Определите функцию, которая принимает значение коэффициентов квадратного уравнения и выводит значение корней или
#предупреждение, что уравнение не имеет корней (в случае если детерминант оказался отрицательным)
def s_eq(a, b, c):
tmp = b**2 - 4*a*c
if tmp < 0:
print("Уравнение не имеет корней!... | false |
08704a8d03cabc6a757eb3b85b46d39183095dfc | psycoleptic/Python_class | /Funk Task 10.py | 486 | 4.40625 | 4 | #Напишите функцию, которая для заданного в аргументах списка, возвращает как результат перевернутый список
def revers(a, b):
old_list = []
for i in range(a, b):
l = i+1
old_list.append(l)
i+= 3
new_list = list(reversed(old_list))
print(old_list)
print(new_list)
... | false |
d7a0d968a0b1155703ec27009f4c673bab32416f | johnmcneil/w3schools-python-tutorials | /2021-02-09.py | 2,405 | 4.40625 | 4 | # casting to specify the data type
x = str(3)
y = int(3)
z = float(3)
# use type() to get the data type of a variable
print(x)
print(type(x))
print(y)
print(type(y))
print(z)
print(type(z))
# you can use single or double quotes
# variables
# variable names are case-sensitive.
# must start with a letter or the u... | true |
df2a11b4b05eb2a086825a7a996347f0f56a75ee | johnmcneil/w3schools-python-tutorials | /2021-03-05.py | 1,466 | 4.65625 | 5 | # regexp
# for regular expressions, python has the built-in package re
import re
txt = "The rain in Spain"
x = re.search("^The.*Spain$", txt)
print(x)
# regex functions
# findall() - returns a list of all matches
x = re.findall("ai", txt)
print(x)
x = re.findall("sdkj", txt)
print(x)
# search() - returns a match ob... | true |
c31786c6ad2645c08348c68592c2e95c1b924be9 | krishnakesari/Python-Fund | /Operators.py | 1,296 | 4.15625 | 4 |
# Division (/), Integer Division (//), Remainder (%), Exponent (**), Unary Negative (-), Unary Positive (+)
y = 5
x = 3
z = x % y
z = -z
print(f'result is {z}')
# Bitwise operator (& | ^ << >>)
x = 0x0a
y = 0x02
z = x << y
print(f'(hex) x is {x:02x}, y is {y:02x}, z is {z:02x}')
print(f'(bin) x is {x:08b}, y is ... | true |
4e0088bb25588855455f58537abbabb1769b2459 | ETDelaney/automate-the-boring-stuff | /05-01-guess-the-number.py | 1,343 | 4.21875 | 4 | # a game for guessing a number
import random
num_of_chances = 5
secret_number = random.randint(1,20)
#print(secret_number)
print('Hello, what is your name?')
name = input()
print('Well, ' + name + ', I am thinking of a number between 0 and 20.')
print('Can you guess the number? I will give you ' + str(num_of_chance... | true |
8d37af2dc7cf5fba984f7c35f343c6741a30653e | rustybailey/Project-Euler | /pe20.py | 425 | 4.15625 | 4 | """
n! means n * (n - 1) * ... * 3 * 2 * 1
For example, 10! = 10 * 9 * ... 3 * 2 * 1 = 3628800,
and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
Find the sum of the digits in the number 100!
"""
import math
def sumFactorial(n):
num = math.factorial(n)
total = 0
whil... | true |
d23909d63299735beebb3954cc835727b87fa38b | myworkshopca/LearnCoding-March2021 | /basic/types.py | 564 | 4.15625 | 4 | age = input("How old are you?")
print("Age is: {0}".format(age))
print("35 / 2 = ", 35 / 2)
print("35 // 2 = ", 35 // 2)
a = 'Hello Somebody'
print("Repeating \"{0}\" {1} times: {2}".format(a, 4, a * 4))
print("Try the named index placeholder:")
print("Name: {name}, Age: {age}".format(age=100, name="Sean"))
b = "He... | false |
b495c945cfed8db9787f8d9fab4e3c02a5232dfb | shagunsingh92/PythonExercises | /FaultyCalculator.py | 1,122 | 4.53125 | 5 | import operator
'''Exercise: My_faulty_computer
this calculator will give correct computational result for all the numbers except [45*3 = 555, 56+9=77
56/6=4]
'''
def my_faulty():
allowed_operator = {'+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.truediv}
# ask the user for an input
... | true |
3302de8bad34c27c4ed7216b5d4b9fb786979c6c | allenc8046/CTI110 | /P4HW4_Chris Allen.py | 356 | 4.21875 | 4 | import turtle
redCross = turtle.Screen()
x = turtle.Turtle()
x.color("red") # set x turtle color
x.pensize(3) # set x turtle width
print("It's a red cross!")
print ()
# use a for loop
for redCross in range (4):
x.forward(150)
x.left(90)
x.forward(150)
x.left(90)
... | true |
00129adf4cbb2fda2215c499ba7392ca17e90b10 | rafaelalmeida2909/Python-Data-Structures | /Linked Queue.py | 2,268 | 4.28125 | 4 | class Node:
"""Class to represent a node in Python3"""
def __init__(self, data):
self.data = data # Node value
self.next = None # Next node
class LinkedQueue:
"""Class to represent a Linked Queue(without priority) in Python3"""
def __init__(self):
self._front = None # The ... | true |
b314cc818cdf04d37dbc36fae60f5f0ca354182e | divineunited/casear_cipher | /casear_cipher.py | 2,649 | 4.125 | 4 | def casear(message, n, encrypt=True):
'''This casear encryption allows for undercase and capital letters. Pass a message to encrypt or decrypt, n number of positions (must be less than 26) where n will add to the alphabet for encryption and subtract for decryption, and optional encrypt=False to allow for decryption... | true |
7c4f5a725fb49a86333809956941866f45d0effb | MeghaSajeev26/Luminar-Python | /Advance Python/Test/pgm5.py | 448 | 4.4375 | 4 | #5. What is method overriding give an example using Books class?
#Same method and same arguments --- child class's method overrides parent class's method
class Books:
def details(self):
print("Book name is Alchemist")
def read(self):
print("Book is with Megha")
class Read_by(Books):
def rea... | true |
9f9a506baa32ca4d7f7c69ed5d66eac431d0c37f | MeghaSajeev26/Luminar-Python | /Looping/for loop/demo6.py | 212 | 4.21875 | 4 | #check whether a number is prime or not
num=int(input("enter a number"))
flag=0
for i in range(2,num):
if(num%i==0):
flag=1
if(flag>0):
print(num,"is not a prime")
else:
print(num,"is prime") | true |
cd4a8b02ac32153c308a9461a170c9086c91e948 | MeghaSajeev26/Luminar-Python | /Advance Python/Regular Expression/Rulesof_Quantifiers/Rule7.py | 212 | 4.375 | 4 | #ending with 'a'----consider the whole string
import re
x="a$"
r="aaa abc aaaa cga" #check string ending with 'a'
matcher=re.finditer(x,r)
for match in matcher:
print(match.start())
print(match.group()) | false |
6bd7154a5b9369d2a4cde07b1b60d62f8bee1a71 | leonelparrales22/Curso-Python | /Clase_2-Operadorers_y_Expresiones/Clase_Parte_2_codigo.py | 1,122 | 4.3125 | 4 | # Expresiones Anidadas
print("EXPRESIONES ANIDADAS")
x = 10
# QUEREMOS SABER SI UN NUMERO ESTRA ENTRE 8 Y 10
# Si no cumple nos va a devolver un False
# Si se cumple nos va a devolver un True
# resultado = x>=8 and x<=10
resultado = 8 <= x <= 10
print(resultado)
# Operadores con Asignación
print("OPERADORES CON ASIGN... | false |
05984d56459fb9738b27f9bc1fe070ede6d948ea | uttam-kr/PYTHON | /Basic_oops.py | 1,042 | 4.1875 | 4 | #!/usr/bin/python
#method - function inside classes
class Employee():
#How to initialize attribute
#init method
def __init__(self, employee_name, employee_age, employee_weight, employee_height):
print('constructor called')
#('init method or constructor called') ---->This __init__ method called constructor
self... | true |
49f4d48bc9ccc29332f76af833fefa0383defea3 | fadhilahm/edx | /NYUxFCSPRG1/codes/week7-functions/lectures/palindrome_checker.py | 631 | 4.15625 | 4 | def main():
# ask for user input
user_input = input("Please enter a sentence:\n")
# sterilize sentence
user_input = sterilize(user_input)
# check if normal equals reversed
verdict = "is a palindrome" if user_input == user_input[::-1] else "is not a palindrome"
# render result
print("Y... | true |
4872a55bfbdc17106db2640bbbf988bdab42ee65 | fadhilahm/edx | /NYUxFCSPRG1/codes/week4-branching_statements/lectures/24_to_12.py | 492 | 4.21875 | 4 | print("Please enter a time in a 24-hour format:")
hours24 = int(input("Hour: "))
minutes24 = int(input("Minute: "))
condition1 = hours24 // 12 == 0
condition2 = hours24 == 0 or hours24 == 12
time_cycle = "AM" if condition1 else "PM"
hours12 = 12 if condition2 else (hours24 if condition1 else hours24 % 12)
print("{hou... | false |
c90774a80721049b89b00f43f9bab31a1ed7285e | Jason-Cee/python-libraries | /age.py | 879 | 4.1875 | 4 | # Python Libraries
# Calculating Age
from datetime import datetime
year_born = int(input("Enter year born: "))
month_born = int(input("Enter your month born: "))
day_born = int(input("Enter your day born: "))
current_year = int(datetime.today().strftime("%Y"))
current_month = int(datetime.today().strftime("%m"))
curr... | false |
d77058bbe4637423834c5f59e905f21721e16674 | DiksonSantos/Bozon_Treinamentos_Python | /Aula_31_Modulos_Criando e Importando.py | 966 | 4.125 | 4 | # Modulo com funções variadas
#Função que exibe mensagem de boas vindas:
def mensagem ():
print('Ralando pra sair dessa vida!\n')
# Função para calculo de fatorial de um numero:
def fatorial(numero):
if numero < 0:
return 'Digite um valor maior ou igual a Zero'
else:
if numero ==0 or numero ==1:
return
... | false |
264e9468222fb4e6674410eab08618580ed09cf4 | jeonghaejun/01.python | /ch08/ex04_리스트 관리 삽입.py | 743 | 4.1875 | 4 | # .append(값)
# 리스트의 끝에 값을 추가
# .insert(위치, 값)
# 지정한 위치에 값을 삽입
nums = [1, 2, 3, 4]
nums.append(5)
print(nums) # [1, 2, 3, 4, 5]
nums.insert(2, 99)
print(nums) # [1, 2, 99, 3, 4, 5]
nums = [1, 2, 3, 4]
nums[2:2] = [90, 91, 92] # 새로운 값들을 삽입 슬라이싱
print(nums) # [1, 2, 90, 91, 92, 3, 4]
nums = [1, 2, 3, 4]
nums[2] ... | false |
cd1f058045cc9414ca8d8f2d5ed0e7f0d4ef231d | suiody/Algorithms-and-Data-Structures | /Data Structures/Circular Linked List.py | 1,248 | 4.125 | 4 | """
* Author: Mohamed Marzouk
* --------------------------------------
* Circular Linked List [Singly Circular]
* --------------------------------------
* Time Complixty:
* Search: O(N)
* Insert at Head/Tail: O(1)
* Insert at Pos: O(N)
* Deletion Head/Tail: O(1)
* Deletion [middle / pos]: O(N)
* Spa... | true |
16c3c7b2302a7fd892b67a00b09d41e058a3cff5 | sula678/python-note | /basic/if-elif-else.py | 233 | 4.125 | 4 | if 3 > 5:
print "Oh! 3 is bigger than 5!"
elif 4 > 5:
print "Oh! 4 is bigger than 5!"
elif 5 > 5:
print "Oh! 5 is bigger than 5!"
elif 6 > 5:
print "Of course, 6 is bigger than 5!"
else:
print "There is no case!"
| true |
e707b084c1932e484b5023eae4052fc606332c3c | mreboland/pythonListsLooped | /firstNumbers.py | 878 | 4.78125 | 5 | # Python's range() function makes it easy to generate a series of numbers
for value in range(1, 5):
# The below prints 1 to 4 because python starts at the first value you give it, and stops at the second value and does not include it.
print(value)
# To count to 5
for value in range(1, 6):
print(value)
... | true |
8a9b9a790d09aa9e7710b48b67575553224a497b | EvheniiTkachuk/Lessons | /Lesson24/task1.py | 949 | 4.15625 | 4 | # Write a program that reads in a sequence of characters and prints
# them in reverse order, using your implementation of Stack.
class MyStack:
def __init__(self):
self.array = []
def push(self, item):
self.array.append(item)
def pop(self):
return self.array.pop()
... | true |
f12695405b54a25339bbd9b7098502bee4bd0d42 | EvheniiTkachuk/Lessons | /Lesson13/task3.py | 965 | 4.46875 | 4 | # Напишите функцию под названием `choose_func`, которая принимает список из числа и 2
# функции обратного вызова. Если все числа внутри списка положительны, выполнить
# первую функцию в этом списке и вернуть ее результат. В противном случае вернуть результат второго
def square_nums(nums):
return [num ** 2 f... | false |
d69a710becdd434773d15def23dbe71e3c426b75 | EvheniiTkachuk/Lessons | /Lesson24/task3_2.py | 1,856 | 4.125 | 4 | # Extend the Queue to include a method called get_from_stack that
# searches and returns an element e from a queue. Any other element must
# remain in the queue respecting their order. Consider the case in which the element
# is not found - raise ValueError with proper info Message
class Queue:
def __init_... | true |
02ffe7089ad2b5c05246949bf9731c73130e3ebd | EvheniiTkachuk/Lessons | /Lesson24/task2.py | 1,596 | 4.15625 | 4 | # Write a program that reads in a sequence of characters,
# and determines whether it's parentheses, braces, and curly brackets are "balanced."
class MyStack:
def __init__(self):
self.array = []
def push(self, item):
self.array.append(item)
def pop(self):
return sel... | true |
7191a0743560cc83b9522c6fae2f5bdffb721bc0 | EvheniiTkachuk/Lessons | /Lesson5/task1.py | 460 | 4.125 | 4 | # #The greatest number
# Write a Python program to get the largest number from a list of random numbers with the length of 10
# Constraints: use only while loop and random module to generate numbers
from random import randint as rand
s = []
i = 1
while i <= 10:
s.append(rand((10**9), (10**10) - 1))
... | true |
55062a569b72f7a94548b73ed83539de1c57adb0 | kookoowaa/Repository | /SNU/Python/BigData_Programming/170619/Programming_1.py | 537 | 4.1875 | 4 | print('\nWelcome to Python Programming') #Greetings
print('This is Your First Python Program\n')
print('What is your name?') #Ask for your input
name = input()
print('Hi! ' + name) #compare this with the following line
print('Hi!', name)
print('The length of your name is:')
print(len(name))
age = input (... | false |
9a9f02d7d36150749820c11ad1815e1939c21fad | kookoowaa/Repository | /SNU/Python/코딩의 기술/zip 활용 (병렬).py | 774 | 4.34375 | 4 | ### 병렬에서 루프문 보다는 zip 활용
names = ['Cecilia', 'Lise', 'Marie']
letters = [len(n) for n in names]
longest_name = None
max_letters = 0
# 루프문 활용
for i in range(len(names)):
count = letters[i]
if count > max_letters:
longest_name = names[i]
max_letters = count
print(longest_name)
print(max_letters)
#... | true |
fb57296132ee3c28d5940f746bbc1496e566c946 | nidhi988/THE-SPARK-FOUNDATION | /task3.py | 2,329 | 4.34375 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Task 3: Predicting optimum number of clusters and representing it visually.
# ## Author: Nidhi Lohani
# We are using Kmeans clustering algorithm to get clusters. This is unsupervised algorithm. K defines the number of pre defined clusters that need to be created in the proce... | true |
65d2ba3d984567002d83f04bbf0fa42ded16a5bb | dineshneela/class-98 | /file.py | 678 | 4.125 | 4 | # program to read and open a file.
#>>> f= open("test.txt")
#>>> f.read()
#'test filllles'
#>>> f= open("test.txt")
#>>> filelines=f.readlines()
#>>> for line in filelines:
#... print(line)
#...
#test filllles. somettttthing else
# program to split the words in a string.
#>>> introstring="my name is Di... | true |
1a7c48054418adef604c72fa24c62904e6a41525 | Oli-4ction/pythonprojects | /dectobinconv.py | 556 | 4.15625 | 4 | """*************************
Decimal to binary converter
*************************"""
#function
def function():
#intialize variables
number = 0
intermediateResult = 0
remainder = []
number = int(input("Enter your decimal number: "))
base = int(input("Choose the number format: "))
... | true |
cd0e31fec220f4c3e9a04262de709ed86c91e37f | posguy99/comp644-fall2020 | /L3-12.py | 270 | 4.125 | 4 | # Create a while loop that will repetitively ask for a number.
# If the number entered is 9999 stop the loop.
while True:
answer = int(input('Enter a number, 9999 to end: '))
if answer == 9999:
break
else:
print('Your number was: ', answer)
| true |
5da4e0552096abe360fcab61e2cf883924fa8baf | posguy99/comp644-fall2020 | /L5-13.py | 378 | 4.125 | 4 | # python lab 5 10-6-20
# l5_13 shallow copy of a list, the id() are the same indicating
# that they are both pointers to the same list object
the_list = ['Apples', 'Pears', 'Oranges', 'Mangoes', 'Tomatoes']
print('the_list: ', the_list)
the_new_list = the_list
print('the_new_list: ', the_new_list)
print('the_list... | false |
266855d66e3b769f19350e5fa22af81c7b367811 | stfuanu/Python | /basic/facto.py | 268 | 4.125 | 4 |
num = input("Enter a number: ")
num = int(num)
x = 1
if num < 0:
print("Factorial doesn't exist for -ve numbers")
elif num == 0:
print("Factorial of 0 is 1")
else:
for i in range(1,num + 1):
x = x*i
print("Factorial of",num,"is",x) | true |
3ab084579276659c14fca1a6421903dc47227b27 | jrngpar/PracticePython | /15 reverse word order.py | 1,273 | 4.28125 | 4 | #reverse word order
#ask for a long string with multiple words
#print it back with the words in backwards order
#remove spaces? Maybe print back with words in reverse
#2 functions, one to reverse order of words, one to reverse letters in words?
#Can call both functions to reverse order and letters if wanted
def rever... | true |
1341c50fd7e58931c55c79478479d0b29deb0787 | MrazTevin/100-days-of-Python-Challenges | /SolveQuiz1.py | 695 | 4.15625 | 4 | # function to determine leap year in the gregorian calendar
# if a year is leap year, return Boolean true, otherwise return false
# if the year can be evenly divided by 4, it's a leap year, unless: The year can be evenly divided by 100 it is# not a leap year,unless the year is also divisible by 400, then its a leap yea... | true |
82573c7abbdd044e489e75c4b53f7840c10873ae | rdstroede-matc/pythonprogrammingscripts | /week5-files.py | 978 | 4.28125 | 4 | #!/usr/bin/env python3
"""
Name: Ryan Stroede
Email: rdstroede@madisoncollege.edu
Description: Week 5 Files Assignment
"""
#1
with open("/etc/passwd", "r") as hFile:
strFile = hFile.read()
print(strFile)
print("Type:",type(strFile))
print("Length:",len(strFile))
print("The len() function counts the numb... | true |
1bdfad55963a5ca778fc06d402edc95abcf8fb16 | stak21/DailyCoding | /codewarsCodeChallenge/5-anagram.py | 1,300 | 4.28125 | 4 | # Anagram
# Requirements:
# Write a function that returns a list of all the possible anagrams
# given a word and a list of words to create the anagram with
# Input:
# 'abba', ['baab', 'abcd', 'baba', 'asaa'] => ['baab, 'baba']
# Process:
# Thoughts - I would need to create every permutation of the given word... | true |
afc80165e3d0f02bbc8d49ce2ba2dae80092abc2 | HarithaPS21/Luminar_Python | /Advanced_python/Functional_Programming/dictionary.py | 632 | 4.125 | 4 | employees={
1000:{"eid":1000,"ename":"ajay","salary":34000,"Designation":"developer"},
1001:{"eid":1001,"ename":"arun","salary":38000,"Designation":"developer"},
1002:{"eid":1002,"ename":"akhil","salary":21000,"Designation":"hr"},
1003:{"eid":1003,"ename":"anu","salary":45000,"Designation":"Analyst"}
}
id=int(input("... | false |
aaad26766dbaf3819cebe370c7f5117283fd1630 | HarithaPS21/Luminar_Python | /python_fundamentals/flow_of_controls/iterating_statements/while_loop.py | 339 | 4.15625 | 4 | # loop - to run a block of statements repeatedly
# while loop -run a set of statements repeatedly until the condition becomes false
#Syntax
# while condition:
# code
# inc/dec operator
a=0
while a<=10:
print("hello") # prints "hello" 11 times
a+=1
print("\nwhile decrement example")
i=10
while i>0:
... | true |
85b7319bc24340a96ce0e3a97791d6eee2643c32 | Syconia/Harrow-CS13 | /Stacks.py | 1,611 | 4.125 | 4 |
# Stack class
class Stack():
# Put in a list and set a limit. If limit is less than 0, it's basically infinitely large
def __init__(self, List, INTlimit):
self.Values = List
if INTlimit < 0:
INTlimit = 99999
self.Limit = INTlimit
# Set up pointer. It's set by list in... | true |
c353be9014cb341a5a04e1f55ef53661f88175ef | JoshTheBlack/Project-Euler-Solutions | /075.py | 1,584 | 4.125 | 4 | # coding=utf-8
'''It turns out that 12 cm is the smallest length of wire that can be bent to form an integer sided right angle triangle in exactly one way, but there are many more examples.
12 cm: (3,4,5)
24 cm: (6,8,10)
30 cm: (5,12,13)
36 cm: (9,12,15)
40 cm: (8,15,17)
48 cm: (12,16,20)
In contrast, some lengths of... | true |
c8509d347b9d8dce353f1e40f9ba2a1c4d3df4f2 | RaviC19/Dictionaries_Python | /more_methods.py | 625 | 4.375 | 4 | # pop - removes the key-value pair from the dictionary that matches the key you enter
d = dict(a=1, b=2, c=3)
d.pop("a")
print(d) # {'b': 2, 'c': 3}
# popitem - removes and returns the last element (key, value) pair in a dictionary
e = dict(a=1, b=2, c=3, d=4, e=5)
e.popitem()
print(e) # {'a': 1, 'b': 2, 'c': 3, 'd'... | true |
44291c2c7fe818202a9d424139eba73e90dfd5ce | Jwbeiisk/daily-coding-problem | /mar-2021/Mar15.py | 1,643 | 4.4375 | 4 | #!/usr/bin/env python3
"""
15th Mar 2021. #558: Medium
This problem was asked by Google.
The area of a circle is defined as πr^2. Estimate π to 3 decimal places using a Monte Carlo method.
Hint: The basic equation of a circle is x^2 + y^2 = r^2.
"""
"""
Solution: We sample random points that would appear in the f... | true |
f2c376ba14e0c328cc64f9985d080d4968a57431 | Jwbeiisk/daily-coding-problem | /mar-2021/Mar10.py | 1,667 | 4.5 | 4 | #!/usr/bin/env python3
"""
10th Mar 2021. #553: Medium
This problem was asked by Google.
You are given an N by M 2D matrix of lowercase letters. Determine the minimum number of columns that can be removed to
ensure that each row is ordered from top to bottom lexicographically. That is, the letter at each column is ... | true |
14b70002c95cdd503190e523f840b543a272f481 | Jwbeiisk/daily-coding-problem | /feb-2021/Feb17.py | 1,784 | 4.40625 | 4 | #!/usr/bin/env python3
"""
17th Feb 2021. #532: Medium
This problem was asked by Google.
On our special chessboard, two bishops attack each other if they share the same diagonal. This includes bishops that
have another bishop located between them, i.e. bishops can attack through pieces.
You are given N bishops, re... | true |
f98b5090fbc532098ebbcd8026efae383bfcc507 | Jwbeiisk/daily-coding-problem | /jan-2021/Jan30.py | 1,092 | 4.34375 | 4 | #!/usr/bin/env python3
"""
30th Jan 2021. #514: Medium
This problem was asked by Microsoft.
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
For example, given [100, 4, 200, 1, 3, 2], the longest consecutive element sequence is [1, 2, 3, 4]. Return its
length: 4.
... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.