blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
0b9b8fe6fabd72a052c5317ff141064693f21d96 | erikaosgue/python_challenges | /easy_challenges/16-minimun_by_key.py | 984 | 4.40625 | 4 | #!/usr/bin/python3
# As a part of this problem, we're going to build, piece-by-piece,
# the part of a relational database that can take a list of rows and
# sort them by multiple fields:
# i.e., the part that implements
# ORDER BY name ASC, age DESC
# Step 1: we want to write a function that returns the record... | true |
7bf8176a07d3a2573cc4047176e80da80944baec | ThomasSessions/Rock-Paper-Scissors | /RPSgame.py | 2,369 | 4.53125 | 5 | # Rock, paper, scissors game B05:
from random import randint # Allows the generation of random numers, "randint" means random integer
# Lets define some values
player_score = 0
computer_score = 0
x = player_score
y = computer_score
# Using a dictionary with winning results makes for a much cleaner results s... | true |
ee2a377708e520e9f316eefcb10665f07d4b816b | Zakir44/Assignment.4 | /04.py | 203 | 4.125 | 4 | #Accept number from user and calculate the sum of all number from 1 to a given number
a = int(input("Enter The Value: "))
SUM = 0
for i in range(a, 0, -1):
SUM = SUM+i
print("Sum :", SUM)
| true |
310f09091114e7e0068f092a986cb8021891fa80 | jalondono/holbertonschool-machine_learning | /math/0x05-advanced_linear_algebra/0-determinant.py | 1,270 | 4.125 | 4 | #!/usr/bin/env python3
"""Determinant"""
def check_shape(matrix):
"""
Check if is a correct matrix
:param matrix: matrix list
:return:
"""
if len(matrix):
if not len(matrix[0]):
return 3
if not isinstance(matrix, list) or len(matrix) == 0:
return 2
for row i... | true |
b31231c2ef1775c518afe43afd92db7d235df346 | jalondono/holbertonschool-machine_learning | /supervised_learning/0x00-binary_classification/0-neuron.py | 840 | 4.125 | 4 | #!/usr/bin/env python3
""" Neuron """
import numpy as np
class Neuron:
"""Neuron Class"""
def __init__(self, nx):
"""
constructor method
nx is the number of input features to the neuron
"""
if not isinstance(nx, int):
raise TypeError('nx must be an integer'... | true |
0e10d0d6502e8acb640f20d509ec37ea9319b9d5 | bpbpublications/Advance-Core-Python-Programming | /Chapter 02/section_2_2.py | 783 | 4.15625 | 4 | class Students:
student_id = 50
# This is a special function that Python calls when you create new instance of the class
def __init__(self, name, age):
self.name = name
self.age = age
Students.student_id = Students.student_id + 1
print('Student Created')
# Thi... | true |
5531feb525cabab21c61164afec1eba78ef088ce | bpbpublications/Advance-Core-Python-Programming | /Chapter 02/section2_1.py | 2,502 | 4.4375 | 4 | ### All code boxes of section 2.1 Classes and Objects
class Employee:
def __init__(self, name, email, department, age, salary):
self.name = name
self.email = email
self.department = department
self.age = age
self.salary = salary
#####
class Employee:
def __ini... | false |
34965ac46691239e08b86dab83ee6b52929c9900 | palani19/thilopy | /12.py | 220 | 4.15625 | 4 | a=int(input("Enter a value for a"))
b=int(input("Enter a value for b"))
#comparing no.
if(a>b):
print(a,"is greater than ",b)
elif(a==b):
print(a,"is equal to",b)
elif(b>a):
print(a,"is greater than",b) | true |
ccd1f00eea5df48e73e66af0f9a15ca86f1b82bb | xiaoqiangjava/python-algorithm | /learn/101.py | 1,865 | 4.21875 | 4 | #!/usr/bin/python
# -*- encoding: utf-8 -*-
from tree import TreeNode
# 对称二叉树
class Solution:
@staticmethod
def isSymmetric(root: TreeNode) -> bool:
"""
迭代实现: 按照左节点的左节点与右节点的右节点进行比较,左节点的右节点跟右节点的左节点进行比较的规则
按照次序将节点入队,出队时比较两个节点的值是否相同,或者两个都为None
"""
if not root:
... | false |
37735d424718aaab2db2dab0956cef77fb8b51fd | rvmoura96/exercicios-aleatorios | /Collatz/collatz.py | 1,248 | 4.21875 | 4 | """Enunciado do exercício.
Analisando a conjectura de Collatz
Você está resolvendo este problema.
Este problema foi utilizado em 223 Dojo(s).
Para definir uma seqüência a partir de um número inteiro o positivo, temos as seguintes regras:
n → n/2 (n é par)
n → 3n + 1 (n é ímpar)
Usando a regra acima e iniciando com... | false |
5f8b0aa422823da65f7d147ec85a0b3901f73982 | galenscovell/Project-Euler | /Python/Euler02.py | 736 | 4.1875 | 4 |
# Each new term in the Fibonacci sequence is generated by adding the previous two terms.
# By considering the terms in the Fibonacci sequence whose values do not exceed four million,
# find the sum of the even-valued terms.
# Personal challenge: Find sum of even or odd value terms up to given input value.
limit = ... | true |
b6b971560131267695b3f5a055f2dabd972e60cf | Python-Geek-Labs/learn-python- | /tut5 - dictionary, dict. function.py | 581 | 4.21875 | 4 | # Dictionary is nothing but key value pairs
d1 = {}
# print(type(d1))
d2 = {"Harry":"Burger",
"Rohan":"Fish",
"SkillF":"Roti",
"Shubham":{"B":"maggie", "L":"roti", "D":"Chicken"}}
# d2["Ankit"] = "Junk Food"
# d2[420] = "Kebabs"
# print(d2)
# del d2[420]
# print(d2["Shubham"])
# below code will not c... | false |
3a299e5a203d3d4e54d2e92e06ed4d8c82c8c35d | Python-Geek-Labs/learn-python- | /tut16 - functions and docstrings.py | 695 | 4.21875 | 4 | # Built-In function (pre-defined fucntions)
# for eg - sum(param) where param must be an iterable var
# like list, tuple, set
# c = sum((9, 8)) or c = sum([9, 8]) or c = sum({9, 8})
def func():
print('Hello, u are in function')
func() # only print the hello statement
print(func()) # print hello statement and ... | true |
69773915f28a21e255badc11e9288ab18b914483 | Python-Geek-Labs/learn-python- | /tut7 - set, set functions.py | 1,237 | 4.1875 | 4 | s = set()
print(s)
# s = set(1, 2, 3, 4, 5) ----> Wrong !!
s = set([1, 2, 3, 4, 5, 10]) # ----> Right :)
# print(type(s))
l = [1, 2, 3, 4, 4]
setFromList = set(l)
print(setFromList)
print(type(setFromList))
print(len(s))
print(min(s))
print(max(s))
s.add(6)
s.remove(10)
print(s)
newSet = {2, 3, 45, 'hello cool d... | true |
265289d883461b3a23dc756e1044a9eefa62ec3e | Techie1212/myprograms | /practice13.py | 339 | 4.1875 | 4 | number=int(input("enter input:"))
result1=5*(number*number)+4
result2=5*(number*number)-4
Number1=result1
Number2=result2
number1=int(Number1**0.5)
number2=int(Number2**0.5)
if(number1*number1==Number1 or number2*number2==Number2):
print(f"'{number}' is fibonacci number")
else:
print(f"'{number}'is not ... | false |
8c31921e9ee9391f6088bff58c1ed556ef910f5d | muskan1301/PyProjects | /sps.py | 983 | 4.125 | 4 | import random
print("Rules")
print("stone vs paper -> paper ")
print("stone vs Scissor -> stone ")
print(" Scissor vs paper -> Scissor ")
n = "Continue"
computer = 0
user = 0
l1 = ['stone','paper','scissor']
while(n == 'Continue'):
i = input("Please Enter your choice:")
a = random.choice(l1)
print("Computer... | false |
3a489ad75cbae06ce788c1acf29103630a841b83 | ohduran/problemsolvingalgorithms | /LinearStructures/Queue/hotpotato.py | 592 | 4.125 | 4 | from queue import Queue
def hot_potato(names, num):
"""
Input a list of names,
and the num to be used for counting.
It returns the name of the last person
remaining after repetitive counting by num.
Upon passing the potato, the simulation
will deque and immediately enqueue that person.
... | true |
1f3963d9ac195ac26cc3c4129f719f66a5cc37bc | ohduran/problemsolvingalgorithms | /Trees and Tree Algorithms/trees.py | 1,652 | 4.1875 | 4 | """Tree Data Structures."""
class BinaryTree():
"""A Binary Tree is a Tree with a maximum of two children per node."""
def __init__(self, key):
"""Instantiate a Binary Tree."""
self.key = key
self.left_child = None
self.right_child = None
def get_left_child(self):
... | true |
0bc39ebe68a11c02e724e50f4af7cdada6e47628 | hyperc54/ml-snippets | /supervised/linear_models/linear_regression.py | 1,644 | 4.28125 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 29 13:17:51 2018
This example is about using Linear Regression :
- in 1D with visualisation
- in ND
Resources
Trying to understand the intercept value :
http://blog.minitab.com/blog/adventures-in-statistics-2/regression-analysis-how-to-... | true |
bc91c6f05a549c07334497025e8329e558d306a2 | leemarreros/coding-challenges-explained | /max-sum-of-pyramid/pyramid-reduce-solution.py | 998 | 4.25 | 4 | from functools import reduce
# The returned value of 'back_slide' will become 'prev_array'
# in the next iteration.
# At first, we only take the last two arrays of 'pyramid'.
# After we calculate the greatest path between those two
# arrays, that same result is represented by 'prev_array'
# and computed again
# The '... | true |
e5a0042d0114448f9bf78e10b74e86778c73afcb | qalp34/100DaysOfCode | /week06/Day38.py | 243 | 4.1875 | 4 | cars = ["Ford", "Volvo", "BMW"]
for x in cars:
print(x)
cars = ["Ford", "Volvo", "BMW"]
cars.append("honda")
print(cars)
cars = ["Ford", "Volvo", "BMW"]
cars.pop(1)
cars = ["Ford", "Volvo", "BMW"]
cars.remove("Volvo")
print(cars)
| false |
85725c7b415e438578303cc522456b9fdb0f020d | Nishimirwe/python-algorithms | /src/interview_questions/recursionAndDynamicProgramming/easy/flatten.py | 558 | 4.1875 | 4 | # Flatten --> write a recursion function called flatten
# which accepts an array of arrays and returns a new array with all the values flattened
def flatten(arr):
resultArr = []
for custItem in arr:
if type(custItem) is list:
resultArr.extend(flatten(custItem))
else:
r... | true |
fa1f73a816833b275067a434c25e5f7362eeb9ce | Nishimirwe/python-algorithms | /src/interview_questions/recursionAndDynamicProgramming/hard/robot_in_a_grid.py | 2,263 | 4.21875 | 4 | #Robot in a Grid: Imagine a robot sitting on the upper left corner of grid with r rows and c columns.
#The robot can only move in two directions, right and down, but certain cells are "off limits"
#such that the robot cannot step on them. Design an algorithm to find a path for the
#robot from the top left to the bot... | true |
c1111f1933aeab8fa21b81df7299979e7ab2ff68 | Nishimirwe/python-algorithms | /src/interview_questions/recursionAndDynamicProgramming/easy/isPalindrome.py | 1,395 | 4.375 | 4 | # IsPalindrome --> Write a recursive function if the string passed to is a palindrome, otherwise return false
def isPalindrome(str):
strLength = len(str)
assert strLength > 0, "Length of string should be greater than 0"
# if initial length of string is one -> it definitely a palindrome
# Also handles,... | true |
8267427bbd6bc2c91ec94852d0f64f80e47c7d16 | Supernovacs/python | /main.py | 476 | 4.125 | 4 | def encrypt(text,s):
result = ""
for i in range(len(text)):
char = text[i]
if (char.isupper()):
result += chr((ord(char) + s-65) % 26 + 65)
elif (char == " "):
result += " "
else:
result += chr((ord(char) + s-97) % 26 + 97)
return result
p... | true |
e414ae359f0c48d04fa08f3535a62a137b7dd299 | VVivid/python-programs | /list/16.py | 217 | 4.1875 | 4 | """Write a Python program to generate and print a list of first and last 5 elements
where the values are square of numbers between 1 and 30 (both included)."""
l = [i ** 2 for i in range(1,31)]
print(l[:5],l[-5:])
| true |
cc9865ca878ab7af94ad00db8d1f6b7cf722e23a | VVivid/python-programs | /array/9.py | 297 | 4.125 | 4 | """Write a Python program to append items from a specified list."""
from array import *
array_test = array('i', [4])
num_test = [1, 2, 3, 4]
print(f"Items in the list: {num_test}")
print(f"Append items from the list: ")
array_test.fromlist(num_test)
print("Items in the array: "+str(array_test)) | true |
6d2f899345647d05fcb2666489eef6588c6df66d | VVivid/python-programs | /array/3.py | 263 | 4.34375 | 4 | """Write a Python program to reverse the order of the items in the array."""
from array import *
array_test = array('i',[1,2,3,4,5,6,7])
array_test_reverse = array_test[::-1]
print(f"Original Array: {array_test}\n"
f"Reverse Array: {array_test_reverse}")
| true |
d6cb540d3560e112018ee3372a8cc1151f5c8497 | VVivid/python-programs | /Strings/2.py | 229 | 4.21875 | 4 | """Write a Python program to count the number of characters (character frequency) in a string."""
Sample_String = 'google.com'
result = dict()
for item in Sample_String:
result[item] = Sample_String.count(item)
print(result) | true |
df5f7843f3a344c0ab4591dff759180561116413 | VVivid/python-programs | /Strings/3.py | 430 | 4.34375 | 4 | """Write a Python program to get a string made of the first 2 and the last 2 chars from a given a string.
If the string length is less than 2, return instead of the empty string."""
def string_both_ends(user_input):
if len(user_input) < 2:
return 'Length smaller than 2'
return user_input[0:2] + user_... | true |
79762246ffac80b3d8e2acb35c05a13fdc843598 | VVivid/python-programs | /array/2.py | 260 | 4.125 | 4 | """Write a Python program to append a new item to the end of the array. """
from array import *
array_test = array('i', [1, 2, 3, 4, 5, 6, 7, 8, 9])
print("Original Array {}".format(array_test))
array_test.append(10)
print('Update array :')
print(array_test)
| true |
6a24b4feda7f21aea7fcbc9e137ec929a8f02ac2 | david-weir/Programming-3-Data-Struct-Alg- | /week3/slice.py | 651 | 4.15625 | 4 | #!/usr/bin/env python3
def get_sliced_lists(lst):
final = []
no_last = lst[:-1]
no_first_or_last = lst[1:-1]
reverse = lst[::-1]
final.append(no_last)
final.append(no_first_or_last)
final.append(reverse)
return final
# def main():
# # read the list from stdin
# nums = []
# ... | true |
0a215ca7d79e7e96bf17c5157b1b9799c7adb238 | khollbach/euler | /1_50/19/euler.py | 1,347 | 4.3125 | 4 | #!/usr/bin/python3
days_per_month = [
31, # Jan
28, # Feb
31, # Mar
30, # Apr
31, # May
30, # Jun
31, # Jul
31, # Aug
30, # Sep
31, # Oct
30, # Nov
31 # Dec
]
def is_leap_year(year):
if year % 4 == 0:
if year % 100 == 0:
return year % 400 == 0
... | false |
416ee19ddef2547d51537911b5fc40298318f4fc | alextodireanu/check_palindrome_app | /check_palindrome.py | 877 | 4.5625 | 5 | # an app that checks if a given word is a palindrome
# first method using a reversed string
def check_palindrome(word):
"""Method to validate if a word is a palindrome"""
if word == word[::-1]:
return True
else:
return False
word_to_be_checked = input('Please type the word you want to che... | true |
bf5c393937be0e9fb8c5fbf17b55ef45baeb60a5 | joon628/ReadingJournal | /shapes.py | 1,706 | 4.5 | 4 | import turtle
#------------------------------------------------------------------------------
# Starter code to get things going
# (feel free to delete once you've written your own functions
#------------------------------------------------------------------------------
# Create the world, and a turtle to put in it
b... | true |
17bdeb8ccdb7aca974227a921418230411756335 | RobertNeuzil/leetcode | /fatherson.py | 497 | 4.125 | 4 | """
Use a recursion function to find out when the father will be twice as old as his son
"""
def father_son(fatherAge, sonAge):
while sonAge < 1000:
if fatherAge / 2 == sonAge:
print (f"The father will be twice as old as the son when the son is {sonAge} and the father is {fatherAge}")
... | true |
082f48d4ab9ce8e939954ca0eeb3244e7f08344c | stanmark2088/FizzBuzz | /fizzbuzz/fizbuzz.py | 516 | 4.25 | 4 | """
Write a program that prints the numbers from 1 to 100. But:
- for multiples of three print “Fizz” instead of the number and
- for the multiples of five print “Buzz”.
- For numbers which are multiples of both three and five print “FizzBuzz”.
"""
def fizzbuzz():
for i in range(1, 101):
if i % 3 == 0 a... | true |
78ff2fa79302a923062788129b316090657da57d | sudhamshu4testing/PracticePython | /Program_to_count_vowels.py | 316 | 4.15625 | 4 | #Program to count the vowels in a given sentence/word
#Vowels
v = 'aeiou'
statement = 'Sudhamshu'
#Take input from the user
#statement = input("Enter a sentence or word: ")
statement = statement.casefold()
count = {}.fromkeys(vowels,0)
for char in statement:
if char in count:
count[char] += 1
print(count) | true |
51b1a59808f936b2dbbdcfcaab3dd5fa18b06348 | sudhamshu4testing/PracticePython | /ConverToListAndTuple.py | 447 | 4.4375 | 4 | #Program to convert the user entered values to List and Tuple
#Ask user to provide a sequence of comma seperated numbers
numbers = input("Proved the sequence of comma seperated numbers: ")
l = list(numbers)
#list can also be written as follow
#l = numbers.split(",")
t = tuple(numbers)
print("The sequence of the numb... | true |
c320948b0612cf1459bbcaae34aa045c6a03d084 | sudhamshu4testing/PracticePython | /Rock_Scissor_Paper_Game.py | 1,434 | 4.4375 | 4 | #Program for a game to play between 2 users and decide who wins the "Rock, Scissor and Paper" game
#Importing "sys" module to use "exit"
import sys
#Let's say if user1 selects "Rock" and user2 selects "Scissor", user1 will win because "Scissor" can't break the rock
#Similar way if user1 selects "Paper" and user2 sele... | true |
4c8756c4a16ee1fa314cf15aff1527902709cbf7 | sudhamshu4testing/PracticePython | /Email_Extraction.py | 209 | 4.125 | 4 | #Program to understand the regular expressions in detail
import re
pattern = r"([\w\.-]+)@([\w\.-]+)(\.[\w\.]+)"
str = "Please contact test@email.com"
match = re.search(pattern,str)
if match:
print(match.group()) | true |
6043f021003d5daf6a77c89e5d5d1b5493465b96 | abhimanyupandey10/python | /even_function_sum.py | 345 | 4.1875 | 4 | # This program finds sum of even numbers of array using function
def findSumOfEvenNmbers (numbers):
sum = 0
for x in numbers:
if x % 2 == 0:
sum = sum + x
return sum
####################### Main code starts #####################
numbers = [6,7,8,9,1,2,3,4,5,6]
sum = findSumOfEvenNmb... | true |
8a3c0e55429879985ff9683e22aba23055148f9f | AmreshTripathy/Python | /59_recursion_factorial.py | 442 | 4.1875 | 4 | # n = int(input('Enter a number: '))
# product = 1
# for i in range(1, n+1):
# product = product * i
# print (product)
# def factorial_iter(n):
# product = 1
# for i in range(1, n+1):
# product = product * i
# return product
def factorial_recurse(n):
if ( n == 1 or n == 0):
... | false |
9ae92c18a01a8ac79334573b3488606ccd9889a9 | AmreshTripathy/Python | /35_pr6_05.py | 226 | 4.1875 | 4 | names = ['harry', 'subham', 'rohit', 'Aditi', 'sipra']
name = input('Enter the name to check:\n')
if (name in names):
print ('Your name is present in the list')
else:
print ('Your name is not present in the list') | true |
6669679241d42a449d45ceb9c3a1601bd29e0e0a | ConradMare890317/Python_Crash.course | /Chap07/even_or_odd.py | 349 | 4.25 | 4 | prompt = "Enter a number, and I'll tell you if it's even or odd: "
prompt += "\nEnter 'quit' to end the program. "
active = True
while active:
number = input(prompt)
if number == 'quit':
active = False
elif int(number) % 2 == 0:
print(f"\nThe number {number} is even.")
elif int(number) % 2 != 0:
print(f"\nT... | true |
caf7c299c5edfb43bd8a7e4d2d01506a72c62494 | samarthgowda96/oop | /interface.py | 911 | 4.375 | 4 | # Python Object Oriented Programming by Joe Marini course example
# Using Abstract Base Classes to enforce class constraints
from abc import ABC,abstractmethod
class JSONify(ABC):
@abstractmethod
def toJSON(Self):
pass
class GraphicShape(ABC):
def __init__(self):
super().__init__()
@a... | true |
50e430e625a115ba20ab470dc0e5c36e9cf4ee8d | kerrymcgowan/AFS_505_u1_spring_2021 | /assignment2/ex6_studydrill1.py | 829 | 4.34375 | 4 | # Make a variable
types_of_people = 10
# Make a variable with an fstring
x = f"There are {types_of_people} types of people."
# Make a variable
binary = "binary"
# Make a variable
do_not = "don't"
# Make a variable with an fstring
y = f"Those who know {binary} and those who {do_not}."
# Print a variable
print(x)
# Pri... | true |
8e2d9c92757f8db4b93c3be98d28a5fd5311f6a8 | trodfjell/PythonTeachers2021 | /Matematikk/Pytagoras.py | 986 | 4.1875 | 4 | # Dette programmet kan brukes for å finne lengden på en ukent side av en rettvinklet trekant
# Programmet ber først brukeren å fortelle om det er hypotenusen eller et av katetenes lengde som er ukjent
# Så ber den om lengden på begge katetene eller hypotenusen og kateten
# Så regner den seg frem til lengden av den ukje... | false |
0761ca27262a5e66f956eddf201448f3a5f35cc1 | BMorgenstern/MergeSort | /MergeSort/mtest.py | 1,034 | 4.28125 | 4 | from mergesort import *
import sys
def getIntArray():
retlist = []
while True:
num = input("Enter an integer value to add to the array, or hit Enter to stop inputting values ")
if num == "":
return retlist
try:
retlist.append(int(num,10))
except ValueError:
print(num+" is not a number")
def main(ar... | true |
e768ac54492abadfc2a859e1272e8d0747560507 | aniketrathore/py-dsa | /stacks/stack.py | 1,131 | 4.125 | 4 | class Node:
def __init__(self, value):
self.value = value
self.prev = None
class Stack:
def __init__(self):
self.head = None
self.size = 0
def push(self, value):
if self.head:
new_node = Node(value=value)
new_node.prev = self.head
... | false |
9fa47ad84849bdc739cff0462629cd2b1a31e594 | adriandrag18/Tema1_ASC | /tema/consumer.py | 1,679 | 4.21875 | 4 | """
This module represents the Consumer.
Computer Systems Architecture Course
Assignment 1
March 2021
"""
from threading import Thread, current_thread
from time import sleep
class Consumer(Thread):
"""
Class that represents a consumer.
"""
def __init__(self, carts, marketplace, retry_wait_time, **k... | true |
83c85f73f8dfac3b5d543f189e2f6939bf47dfc1 | nadia1038/Assignment-4 | /OneFour.py | 485 | 4.4375 | 4 | #1. Write a Python program to calculate the length of a string
String = "abcdefghijklmnopqrstuvwxyz"
print(len(String))
#4. Write a Python program to get a string from a given string where all occurrences of its first char have been changed to '$', except the first char itself.
#Sample String: 'restart'
#Expected... | true |
607d16b743dddf662f6a306422e65b936277e375 | milenaS92/HW070172 | /L04/python/chap3/exercise02.py | 472 | 4.28125 | 4 | # this program calculates the cost per square inch
# of a circular pizza
import math
def main():
print("This program calculates the cost per square inch of a circular pizza")
diam = float(input("Enter the diameter of the pizza in inches: "))
price = float(input("Enter the price of a pizza: "))
radius =... | true |
9b692103e23ee713b3c9e166c9832cad321c9f54 | milenaS92/HW070172 | /L04/python/chap3/exercise11.py | 318 | 4.25 | 4 | # This program calculates the sum of the first n natural numbers
def main():
print("This program calculates the sum of the first n natural numbers")
n = int(input("Please enter the natual number: "))
sum = 0
for i in range(0,n+1):
sum += i
print("The sum of the numbers is: ", sum)
main()
| true |
925177ca3178674f1b11986f0fd85ba0c2edac1a | milenaS92/HW070172 | /L05/python/chap7/excercise05.py | 459 | 4.125 | 4 | # exercise 5 chap 7
def bmiCalc(weight, height):
bmi = weight * 720 / (height**2)
if bmi < 19:
return "below the healthy range"
elif bmi < 26:
return "within the healthy range"
else:
return "above the healthy range"
def main():
weight = float(input("Please enter your weight... | true |
7a30a96b59ea58675216e5f9d00d2b4e243303e8 | kjempire9/python-beginner-codes | /factorial.py | 354 | 4.4375 | 4 |
# The following codes takes in a number and returns its factorial.
# For example 5! = 120.
def factorial(a):
try:
if int(a) == 1:
return 1
else:
return int(a)*factorial(int(a)-1)
except ValueError:
print("You did not enter an integer!!")
x = input("Enter an i... | true |
0e861f7d9e7fb8da98ddbc0cdd1256bf5e0ff958 | feeka/python | /[4]-if else try-catch.py | 447 | 4.15625 | 4 | # -*- coding: utf-8 -*-
x=int(input("Enter 1st number: "))
y=int(input("Enter 2nd number: "))
#line indenting plays great role in this case!
if x>y:
print(str(x)+" is GREATER than "+str(y))
elif x<y:
print(str(x)+" is LESS than "+str(y))
else:
print(str(x)+" is EQUAL to "+str(y))
#try-catc... | true |
6cc15739329b791ad5f36f630fd163814e946e24 | ppmx/cryptolib | /tools/hamming.py | 1,394 | 4.375 | 4 | #!/usr/bin/env python3
""" Package to compute the hamming distance.
The hamming distance between two strings of equal length is the number of
of positions at which the corresponding symbols are different.
"""
import argparse
import unittest
def hamming(string_a, string_b):
""" This function returns the hamming ... | true |
44e69f64edbe5493a73bc28b79ed4c14262163c5 | melissafear/CodingNomads_Labs_Onsite | /week_01/04_strings/05_mixcase.py | 682 | 4.625 | 5 | '''
Write a script that takes a user inputted string
and prints it out in the following three formats.
- All letters capitalized.
- All letters lower case.
- All vowels lower case and all consonants upper case.
'''
text = "here is a string of text"
print(text.upper())
print(text.lower())
# OPTION ONE
... | true |
4dffd43a38bb6413563021c5d20009090238120b | melissafear/CodingNomads_Labs_Onsite | /week_02/06_tuples/01_make_tuples.py | 615 | 4.34375 | 4 | '''
Write a script that takes in a list of numbers and:
- sorts the numbers
- stores the numbers in tuples of two in a list
- prints each tuple
Notes:
If the user enters an odd numbered list, add the last item
to a tuple with the number 0.
'''
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
sorted_list = sort... | true |
158c564cc85e5e7ebb9c6943f67f1672c1ea0d4f | melissafear/CodingNomads_Labs_Onsite | /week_02/08_dictionaries/09_01_duplicates.py | 483 | 4.1875 | 4 | '''
Using a dictionary, write a function called has_duplicates that takes
a list and returns True if there is any element that appears more than
once.
'''
# count the occurrences of each item and store them in ther dictionary
def has_duplicates(list_):
my_dict = {}
for item in my_list:
if item in my... | true |
09c9533f5c28e11aff42f91813f61e4fae6891f4 | melissafear/CodingNomads_Labs_Onsite | /week_03/02_exception_handling/04_validate.py | 537 | 4.625 | 5 | '''
Create a script that asks a user to input an integer, checks for the
validity of the input type, and displays a message depending on whether
the input was an integer or not.
The script should keep prompting the user until they enter an integer.
'''
isinteger = "nope"
while isinteger == "nope":
user_input = ... | true |
bd8e455a8c043737ed67f8db322bea469758e3ac | melissafear/CodingNomads_Labs_Onsite | /week_02/07_conditionals_loops/Exercise_02.py | 799 | 4.3125 | 4 | '''
Take in a number from the user and print "Monday", "Tuesday", ...
"Sunday", or "Other" if the number from the user is 1, 2,... 7,
or other respectively. Use a "nested-if" statement.
'''
days_of_week = ["Mon", "Tues", "Wed", "Thurs", "Fri", "Sat", "Sun", "That's not a day of the week!"]
user_input = int(input("pls... | true |
b9ade628410db43de3d0448901ff69ecd70762c3 | treetrunkz/CalorieTracker | /caltrack.py | 1,648 | 4.3125 | 4 |
# this function uses sum and len to
# return the sum of the numbers=
def list_average(nums_list):
return sum(nums_list) + len(nums_list)
print('\n Welcome to the calorie goals calculator! \n \n We will be going through your diet and calculating and comparing your calorie goals and your caloric intake. \n')
goals = ... | true |
2e58bc18c81abfb4563c2c74d99bcc131255e304 | anmol-sinha-coder/LetsUpgrade-AI_ML | /Week-1/Assignment-1.py | 2,186 | 4.3125 | 4 | #!/usr/bin/env python
# coding: utf-8
# # <font color="blue">Question 1: </font>
# ## <font color="sky blue">Write a program to subtract two complex numbers in Python.</font>
# In[1]:
img1=complex(input("Enter 1st complex number: "))
img2=complex(input("Enter 2nd complex number: "))
print("\nSubtracting 2nd complex... | true |
35801887a4e6628db3c7175e0aa7360949426435 | vivekdevaraju/Coding-Challenges | /letterCount.py | 936 | 4.1875 | 4 | '''
Have the function LetterCountI(str) take the str parameter being passed
and return the first word with the greatest number of repeated letters. For
example: "Today, is the greatest day ever!" should return 'greatest' because
it has 2 e's (and 2 t's) and it comes before 'ever' which also has 2 e's. If
there ar... | true |
97ef4e5aa4ebc325bf26ad70cba98fc179671456 | randyarbolaez/pig-latin | /src/main.py | 1,262 | 4.40625 | 4 | VOWELS = ['a','e','i','o','u']
def remove_punctuation(string):
correct_string = ''
for letter in string:
if letter.isalpha():
correct_string += letter
return correct_string
def input_string_to_translate_to_pig_latin(prompt):
return input(prompt).strip().lower()
def split_str(input... | false |
50b7cecd46498a3bc6bc7cc5383f2152b3f3b2ba | christian-miljkovic/interview | /Leetcode/Algorithms/Medium/Arrays/CampusBikes.py | 2,282 | 4.3125 | 4 | """
On a campus represented as a 2D grid, there are N workers and M bikes, with N <= M. Each worker and bike is a 2D coordinate on this grid.
Our goal is to assign a bike to each worker. Among the available bikes and workers, we choose the (worker, bike) pair with the shortest Manhattan distance between each other, an... | true |
643ebd3619eef099d5bc905e5d05944720fe4f5f | christian-miljkovic/interview | /Leetcode/Algorithms/Easy/Trie/LongestWordInDict.py | 2,397 | 4.125 | 4 | """
Given a list of strings words representing an English Dictionary, find the longest word in words that can be built one character at a time by other words in words. If there is more than one possible answer, return the longest word with the smallest lexicographical order.
If there is no answer, return the empty str... | true |
c97cda747343a105c055e5f66bcbc6230d193aff | christian-miljkovic/interview | /Algorithms/TopologicalSort.py | 1,182 | 4.25 | 4 | # Topological sort using Tarjan's Algorithm
from DepthFirstSearch import AdjacencyList
def topologicalSort(graph, vertexNumber, isVisited, stack):
"""
@graph: an adjacency list representing the current
@vertex: vertex where we want to start the topological sort from
@isVisited: list that determines if ... | true |
15cd88ccd33ef96a95b333f5bae7db1037c8b674 | christian-miljkovic/interview | /CrackingCodingInterview/ArraysStrings/Urlify.py | 571 | 4.375 | 4 | """
Chapter 1 Array's and Strings URLify problem
Write a method to replace all spaces in a string with '%20'. You may assume that the string
has sufficient space at the end to hold the additional characters, and that you are given the "true"
length of the string.
"""
def urlIfy(strToUrl):
str_list = strToUrl.spli... | true |
d148820c8eed0b6bc590f5e6f4816a3285cef81f | christian-miljkovic/interview | /CrackingCodingInterview/DynamicProgramming/RecursiveMultiply.py | 286 | 4.21875 | 4 | # Chapter 8
# Recursive Multiply
# Time Complexity: O(b)
def multiply(a, b):
if a == 0 or b == 0:
return 0
elif b == 1:
return a
else:
b -= 1
a += multiply(a, b)
return a
if __name__ == "__main__":
print(multiply(4,2))
| false |
68198a14cc31ac3625adc8b9bdf7946f051304b9 | christian-miljkovic/interview | /Leetcode/Algorithms/Easy/DynamicProgramming/ClimbingStairs.py | 1,406 | 4.125 | 4 | """
You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
Note: Given n will be a positive integer.
Example 1:
Input: 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2.... | true |
8abe091f2738279cee6ca403284c1217dcea9e2c | christian-miljkovic/interview | /CrackingCodingInterview/DynamicProgramming/RobotGrid.py | 931 | 4.3125 | 4 | """
Chapter 8 Dynamic Programming and Recursion
Problem - Robot in a Grid: Imagine a robot sitting on the upper left corner of grid with r rows and c columns.
The robot can move in two direction, right and down, but certain cells are "off limits" such that
the robot cannot step on them. Design an algorithm to find a p... | true |
6711996b47819cb7d35bca835c41e2f80637b5e6 | christian-miljkovic/interview | /CrackingCodingInterview/ArraysStrings/RotateMatrix.py | 802 | 4.21875 | 4 | """
Chapter 1
Problem - Rotate Matrix: Rotate a Matrix 90 degrees
"""
def rotateMatrix(matrix):
size = len(matrix)
for layer in range(size//2):
first = layer
last = size - layer - 1
for i in range(first, last):
top = matrix[layer][i]
# left to top
... | true |
2981f3195c66cdf86858edea161cd51ef561650a | Neogarsky/phyton | /main1.py | 450 | 4.34375 | 4 | ''' 1-ая задача Выяснить тип результата выражений:
doc = 15 * 3
15 / 3
15 // 2
15 ** 2 '''
print(type(15 * 3))
print(type(15 / 3))
print(type(15 // 2))
print(type(15 ** 2))
#первый вариант
print(f'type 15 * 3 {type(15 * 3)},'
f'type 15 / 3 {type(15 / 3)},'
f'type 15 // 2 {type(15 // 2)},'
... | false |
de80743e4c1e82678c0c543317bf6d5fa09f6ff9 | cooltreedan/NetworkProgrammability | /tried/json-example.py | 783 | 4.25 | 4 | #!/usr/bin/env python3
# -*- coding=utf-8 -*-
# Python contains very useful tools for working with JSON, and they're
# part of the standard library, meaning they're built into Python itself.
import json
# We can load our JSON file into a variable called "data"
with open("json-example.json") as f:
data = f.read(... | true |
d648148ab5acd683aacf3b8cef81dbd0c53a0213 | joeysal/astr-119-hw-2 | /dictionary.py | 467 | 4.375 | 4 | #define a dictionary data structure
#dictionaries have key:valyue pairs for the elements
example_dict = {
"class" : "ASTR 119",
"prof" : "Brant",
"awesomeness" : 10
}
print ("The type of example_dict is ", type(example_dict))
#get value via key
course = example_dict["class"]
print(course)
example_dict["awesomene... | true |
d010f9ac5a0e794325476ad3f6b7e7d17e8e6706 | Tahaa2t/Py-basics | /Conditions.py | 1,231 | 4.34375 | 4 | #-----------------------------simple if else ------------------------------------
#BMI calculator
height = float(input("Enter height in cm: "))
weight = float(input("Enter weight in kg: "))
height = height/100
bmi = round(weight/(height**2)) #round = round off to nearest whole number
if bmi < 18.5:
print(f"{... | false |
1dd908f565bfacec361dcfec080dac61c86146ca | Tahaa2t/Py-basics | /filing.py | 1,020 | 4.5625 | 5 |
#-----------------Reading from file-------------------------------
#Normal way to open and close a file
file = open("py_file.txt") #it will give error if no file exist with that name
contents = file.read()
print(contents)
file.close()
#this works same but you don't need to close file in the end
with open("py_fil... | true |
00260055e446f7cca3815b6c90bfa05ee074d867 | jormarsikiu/PracticasPython | /4-Diccionarios/2_respuesta.py | 762 | 4.375 | 4 | """2)Introducir por teclado una cadena y devuelva un diccionario con la cantidad de apariciones de cada palabra en la cadena. Por ejemplo, si recibe _"que lindo dia que hace hoy"_ debe devolver: `'que': 2, 'lindo': 1, 'dia': 1, 'hace': 1, 'hoy': 1`."""
#!/usr/bin/python
# -*- coding: utf-8 -*-
dic = []
frecuencia ... | false |
5511400414bd3f0d430800655eb9c719883f8ba1 | jormarsikiu/PracticasPython | /2-Listas y Estructuras de Repeticion/3_respuesta.py | 362 | 4.28125 | 4 | """3) Dado la siguiente lista [9,5,1,7,6,3,4,7,2,22,11,85,69,42,45,65] ordenar de menor a mayor y de mayor a menor"""
#!/usr/bin/python
# -*- coding: utf-8 -*-
lista = [9,5,1,7,6,3,4,7,2,22,11,85,69,42,45,65]
l1 = []
l2 = []
l1 = sorted(lista)
l2 = sorted(lista, reverse=True)
print "Lista de menor a mayor: \n", l1... | false |
0a4e01f59e68f77d5b8b40c0fd1f93f31bb2eba4 | jormarsikiu/PracticasPython | /5-Funciones/2-respuesta.py | 657 | 4.28125 | 4 | """2)Definir una funcion que calcule la longitud de una lista o una cadena dada. (Es cierto que python tiene la funcion len() incorporada, pero escribirla por nosotros mismos resulta un muy buen ejercicio."""
#!/usr/bin/python
# -*- coding: utf-8 -*-
lista=[1,11,8,6,4,3,7,2,14,9]
cadena="Hoy voy a caminar"
def long... | false |
6cae48a710c7987a9bb2f99422078f762e0683bd | Qazi-05/WAC | /Day 1/basics.py | 2,576 | 4.40625 | 4 | #print( 'today', 'is', 'the', 'first' , sep='-')
#print("hello",end= ' ')
#print ("world")
'''
multi line
comment
'''
#taking input
# n = input ("Enter your name :")
# print(n)
# variables and data types
# a = 15 #int
# print(a)
# print(type(a)) # type function is used to print type of variable
# b = 10.2 #float... | false |
94e5da06b5afd9f2583b47047f37eda1cf7e6efe | amitdshetty/PycharmProjects | /PracticePythonOrg/Solutions/30_Pick_Word.py | 910 | 4.40625 | 4 | """
Problem Statement
This exercise is Part 1 of 3 of the Hangman exercise series. The other exercises are: Part 2 and Part 3.
In this exercise, the task is to write a function that picks a random word from a list of words from the SOWPODS dictionary.
Download this file and save it in the same directory as your Python... | true |
63b280c5c5791f4c2a98663fb56cc4c44dc3703f | amitdshetty/PycharmProjects | /PracticePythonOrg/Solutions/13_Fibonacci_Sequence.py | 833 | 4.4375 | 4 | """
Problem Statement
Write a program that asks the user how many Fibonnaci numbers to generate and then generates them.
Take this opportunity to think about how you can use functions.
Make sure to ask the user to enter the number of numbers in the sequence to generate.
(Hint: The Fibonnaci seqence is a sequence of nu... | true |
056c480a7bfca09e83ea61d12575ea46a26ec7c6 | codeBeefFly/bxg_python_basic | /Day03/test/01.输入输出练习.py | 421 | 4.1875 | 4 | """
需求:
收银员输入苹果的价格,单位:元/斤
收银员输入用户购买苹果的重量,单位:斤
计算并输出付款金额
"""
# 收银员输入苹果的价格,单位:元/斤
price = float(input('请输入苹果价格:'))
# 收银员输入用户购买苹果的重量,单位:斤
weight = float(input('请输入购买的重量:'))
# 计算并输出付款金额
money = price*weight
print(money) | false |
cbaffbcb484261206d837878922e062c9d929b0c | NealWhitlock/cs-module-project-algorithms | /moving_zeroes/moving_zeroes.py | 1,239 | 4.21875 | 4 | '''
Input: a List of integers
Returns: a List of integers
'''
# def moving_zeroes(arr):
# # Loop through items in array
# for i, num in enumerate(arr):
# # If item zero, pop off list and put at end
# if num == 0:
# arr.append(arr.pop(i))
# # Return array
# return arr
def moving_... | true |
94bc19906a2eeab0ed695d1a408b7c748efc8bd6 | rajashekharreddy/second_repo | /practice/3_tests/8_conversion_system.py | 752 | 4.21875 | 4 | """
This problem was asked by Jane Street.
The United States uses the imperial system of weights and measures, which means
that there are many different, seemingly arbitrary units to measure distance.
There are 12 inches in a foot, 3 feet in a yard, 22 yards in a chain, and so on.
Create a data structure that can e... | true |
067d6afb89cb1ee5e244eea82fa3e6f2aaf934c8 | beautilut/Algorithm-learning | /Sort.py | 1,694 | 4.125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#Sort
# 选择排序
# 1.运行时间和输入无关 2.数据移动是最少的
# 交换总次数N 需要N^2/2次比较
def selectSort(array):
length = len(array)
for i in range(length):
min = i
for j in range(min + 1 , length):
if (array[j] < array[min]):
min = j
array[i] ,... | false |
1e2323818c35fae23972cb1c1ec9b532a43abf15 | heartnoxill/cpe213_algorithm | /divide_and_conquer/quicksort_1.py | 977 | 4.21875 | 4 | # Alphabetically QuickSort
__author__ = "Samkok"
def quick_sort(unsorted_list):
# Initiate the hold lists
less = []
equal = []
greater = []
# if list has more than one element then
if len(unsorted_list) > 1:
print("------------------------------")
pivot = unsorted_list[0]
... | true |
e80156d1329c7813d41d867c878155827cb2dddf | madhumati14/Assignment2 | /Assignment2_1.py | 714 | 4.21875 | 4 | #1.Create on module named as Arithmetic which contains 4 functions as Add() for addition, Sub()
#for subtraction, Mult() for multiplication and Div() for division. All functions accepts two
#parameters as number and perform the operation. Write on python program which call all the
#functions from Arithmetic module by a... | true |
ea564ec3f1fb1b9fb08550bebcf80f38ab3f7320 | rajpravali/Simple_chatbot | /index.py | 1,040 | 4.25 | 4 | from tkinter import * #importing tkinter library used to create GUI applications.
root=Tk() #creating window
def send():#function
send="YOU =>"+e.get()
txt.insert(END,'\n'+send)
if(e.get()=="hello"):
txt.insert(END,'\n'+"Bot => hi")
elif(e.get()=="hi"):
txt.insert(END,'\n'+"Bot => Hello... | true |
baa5e4999ca07b308b9c1bc3ef2bc3a603d39beb | jmocay/solving_problems | /linked_list_reverse.py | 1,212 | 4.1875 | 4 | """
Given the head of a singly linked list, reverse it in-place.
"""
class LinkedListNode(object):
def __init__(self, val=None):
self.val = val
self.next = None
def reverse_linked_list(head):
prev = None
curr = head
while curr != None:
curr_next = curr.next
... | true |
0249089bafa357f4e13b093f0730b15e758b69c0 | win911/UT_class | /for_pytest/exercises/2/my_math.py | 259 | 4.21875 | 4 | # my_math.py
def is_multiples_of_three(num):
if num % 3 == 0:
return True
else:
return False
def insert_number(my_list, number_list):
for num in number_list:
if is_multiples_of_three(num):
my_list.append(num) | false |
6412177952d87e19aa29319fe4026098d97cc9f1 | Take-Take-gg/20460065-Ejercicios-Phyton | /Ejercicios-01/Funciones-01.py | 627 | 4.125 | 4 | # Funciones 01
"""
1.- Realiza una función llamada area_rectangulo(base, altura) que devuelva el área
del rectángulo a partir de una base y una altura. Calcula el área de un rectángulo de
15 de base y 10 de altura.
"""
base = 15
altura = 10
def area_rectangulo(base,altura):
res = base * altura
return res
pri... | false |
5e7569bd53dd6c635fd783784efca77b4e10b388 | srikanthjg/Functional-Programming | /arg_kwarg.py | 640 | 4.21875 | 4 | #https://www.geeksforgeeks.org/args-kwargs-python/
def myFun(*argv):
for arg in argv:
print (arg)
myFun('Hello', 'Welcome', 'to', 'GeeksforGeeks')
print ""
def myFun(**kwargs):
for key, value in kwargs.items():
print ("%s == %s" %(key, value))
# Driver code
myFun(first ='Geeks', mid ='for', ... | false |
529d42990455129b6d605cb0f34a2d2c4429a7bf | ChiDrummer/PythonCrashCourse | /Chapter4/slices.py | 740 | 4.125 | 4 | #looping through a slice
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print("Here's the first three players on my team.")
for player in players[:3]:
print(player.title())
print("\n")
#copying a list
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:]
print("My ... | false |
8e2815ae5f0f26829be3f7b136c32f68bb835e1e | u104790/hafb2 | /for_loop.py | 328 | 4.34375 | 4 | """
Practice for loops
Keyword: for
"""
cities = ["London", "New York", "Madrid", "Paris", "Ogden"]
# iterate over a list
for city in cities:
print (city)
# iterate over a dictionary
d = {'alice':'801-123-4567',
'pedro': '956-445-78-8966',
'john':'651-321-66-4477'}
for item in d:
print(item, "=>", d[... | false |
cf4dff847c730d28b778e5d883c23370a32d9890 | ccrain78990s/Python-Exercise | /0317 資料定義及字典/0317-3-切割.py | 1,485 | 4.15625 | 4 | # 0317 切割
list1=[0,1,2,3,4]
list2=[10,11,12,13,14]
print(list1)
print(list1[3]) #3
print(list2)
print(list2[3]) #13
# 切割 1***
list1=[0,1,2,3,4]
print(list1[0:2]) #[0,1] # 2之前的數字不包含2
print(list1[2:4]) #[2,3]
# 切割 2***
list1=[0,1,2,3,4]
print(list1[1:]) #[1,2,3,4] #1後面的全部數字
print(list1[2:... | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.