blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
1ec4bcaf1bc0ce36c63b85550a43ff73a25cada7 | GhimpuLucianEduard/CodingChallenges | /challenges/leetcode/unique_paths.py | 1,433 | 4.15625 | 4 | """
62. Unique Paths
A robot is located at the top-left corner
of a m x n grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time.
The robot is trying to reach the bottom-right corner of
the grid (marked 'Finish' in the diagram below).
How many possible unique pa... | true |
df439ada7c1e5616bc8812c5abc7ed7ce2fae406 | GhimpuLucianEduard/CodingChallenges | /challenges/leetcode/symmetric_tree.py | 2,995 | 4.3125 | 4 | """
101. Symmetric Tree
Given a binary tree, check whether
it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3
But the following [1,2,2,null,3,null,3] is not:
1
/ \
2 2
\ \
3 3
Follo... | true |
3b7856ab73bc783a93a51fbfe62ec3ae546574e2 | GhimpuLucianEduard/CodingChallenges | /challenges/leetcode/reverse_linked_list.py | 2,662 | 4.1875 | 4 | """
206. Reverse Linked List
Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
Follow up:
A linked list can be reversed either iteratively or recursively. Could you implement both?
"""
import unittest
class ListNode:
def __init__(self, val=0, next=None):
sel... | true |
4fc04b7cec358f3946f318aa120ae8276c56e0f1 | ellynhan/challenge100-codingtest-study | /hall_of_fame/lysuk96/List/LTC_49.py | 1,467 | 4.1875 | 4 | '''
Given an array of strings strs, group the anagrams together. You can return the answer in any order.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Example 1:
Input: strs = ["eat","tea","tan","ate","nat","b... | true |
39cff954f66ca2d3c6ef3b2b628c2acdf51adaed | HrutvikPal/MyCompletedPrograms | /PrimeNumberChecker.py | 1,385 | 4.21875 | 4 | print("Prime Number Checker")
print("This calculator tells you if the number you entered is a prime or not.")
def checker():
while True:
try:
number = (input("Enter the number:"))
number = int(number)
break
except ValueError:
print("Error ... | true |
1b1e0d49e78ca1ee05757c973948a8634e5f5efe | Lobanova-Dasha/my_python | /hackerrank/classes.py | 2,821 | 4.34375 | 4 | #! python3
# classes.py
import math
# Classes: Dealing with Complex Numbers
# you are given two complex numbers,
# and you have to print the result of their
# addition, subtraction, multiplication, division and modulus operations.
# The real and imaginary precision part should be correct up to
# two decimal places... | true |
7ea118afbecab6b19273e8ccd34ede14e5448e6e | raelasoul/python-practice | /ex19.py | 1,846 | 4.3125 | 4 | # FUNCTIONS & VARIABLES
#
# Variables in the function are different from others that are listed below
# cheese_count and boxes_of_crackers can accept values that are assigned to
# variables. (i.e., cheese_count can be passed the value that is assigned to amount_of_cheese)
# define function, indicate arguments
# indi... | true |
ecac4825a12c77f37ea529c9ccf44492f7aacf22 | Catalincoconeanu/Python-Learning | /Python apps&practice/Entry level/Prompt - Exercise - eliminate vowels .py | 1,125 | 4.59375 | 5 | # The continue statement is used to skip the current block and move ahead to the next iteration, without executing the statements inside the loop.
# It can be used with both the while and for loops.
# Your task here is very special: you must design a vowel eater! Write a program that uses:
# a for loop;
# the concept o... | true |
c28ca6c77cf0a37dc9fe4f2714387083e68f02cd | Catalincoconeanu/Python-Learning | /Python apps&practice/Entry level/Prompt - Exercise - Eliminate vowels 2.py | 1,328 | 4.53125 | 5 | # Your task here is even more special than before: you must redesign the (ugly) vowel eater from the previous lab (3.1.2.10) and create a better, upgraded (pretty) vowel eater! Write a program that uses:
# a for loop;
# the concept of conditional execution (if-elif-else)
# the continue statement.
# Your program must:
#... | true |
9ae70ab4d13fff5d34956e75254312ecd297c505 | Catalincoconeanu/Python-Learning | /Python apps&practice/Entry level/Prompt - Exercise - Calculate pyramid height.py | 537 | 4.34375 | 4 | # Listen to this story: a boy and his father, a computer programmer, are playing with wooden blocks. They are building a pyramid.
# Their pyramid is a bit weird, as it is actually a pyramid-shaped wall - it's flat. The pyramid is stacked according to one simple principle: each lower layer contains one block more than t... | true |
924a0f5b9132067a5568993d54fa925b9bfd9471 | Catalincoconeanu/Python-Learning | /Python apps&practice/Entry level/Prompt Simple IF - ELSE statement.py | 325 | 4.21875 | 4 | #Sample of simple if - else statement
#This app will ask you for a nr then compare it with nr 5, if is bigger then 5 will print first block of code if not will print the second.
x = input("Enter a nr: ")
y = int(x)
if y > 5:
print("The nr is greater then 5")
else:
print("The nr is smaller then 5")
print("All Do... | true |
60c08f8f81efe91b31b48d81ee5f0b1f2c392f57 | ilyaLihota/Homework | /4/like.py | 608 | 4.21875 | 4 | #!/usr/bin/python3.7
# -*- coding: utf-8 -*-
"""Describes amount of likes."""
def likes(*arr: str) -> str:
if len(arr) == 0:
return "no one likes this"
elif len(arr) == 1:
return "{} likes this".format(*arr)
elif len(arr) == 2:
return "{} and {} like this".format(*arr)
... | true |
dca174b710bca78ba469904b35f3c18518bc6c80 | gautam-balamurali/Python-Programs | /alternating.py | 608 | 4.21875 | 4 | #Define a Python function "alternating(l)" that returns True if the values in the input list alternately go up and down (in a strict manner).
#For instance:
#>>> alternating([])
#True
#>>> alternating([1,3,2,3,1,5])
#True
#>>> alternating([3,2,3,1,5])
#True
#>>> alternating([3,2,2,1,5])
#False
#>>> alternating([3... | false |
8aa0b06eaaf38499b0b84acb870c114def3fa7bb | dirham/pyhton-hard-way | /ex2.py | 527 | 4.25 | 4 | print "i will count my chickern :"
print "hens ", 25 + 30 / 2
print "Roosters ", 100 - 25 * 3 / 4
print "now i will count the egs :"
print 2 + 3 + 1 - 5 + 4 % 2 - 1 / 4 + 6
print "Is true that 3 + 2 < 5 - 7 ?"
print 3 + 2 < 5 - 7
print "What is 3 + 2 ?", 2 + 3
print "What is 5 - 7 ?", 5 - 7
print "oh, that's why is... | false |
e793c31d5aad2b6bade7b2be47bce8272974789d | ReynaCornelio/Computacional1 | /Actividad 2/programa4.py | 562 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jan 25 20:34:57 2016
@author: Reyna
"""
n = int(input("Enter an integer: " ))
if n%2==0:
print("even")
else:
print("odd")
print ("Enter two integers, on even, one odd.")
m = int(input("Enter the first integer: 1") )
n = int(input("Enter the second ... | true |
f506fee048da6fafd27321c7ed60b55423c9d0b5 | Johnathanseymour696/Python | /check.py | 1,707 | 4.15625 | 4 | #This is a check/review to make sure nothing was "lost" over break
#Johnathan Seymour
#P1
#Variable declaration and assignment
#example
myVar = "hello"
# Try to , declare two variables 1 string and 1 a number, and assign values
myNum = 1
#while loop
# Example
x = 11
while x > 0:
print(x)
x = x - 1... | true |
05d858ffea04704c16191ad260c24a728b1df156 | jTCode2408/Intro-Python-I | /src/14_cal.py | 2,309 | 4.5625 | 5 | """
The Python standard library's 'calendar' module allows you to
render a calendar to your terminal.
https://docs.python.org/3.6/library/calendar.html
Write a program that accepts user input of the form
`14_cal.py [month] [year]`
##2 args
and does the following:
- If the user doesn't specify any input, your pro... | true |
1b3cc20b4d0abdb6af7442bc574a9819b12695b5 | LennyBoyatzis/compsci | /problems/inflight_entertainment.py | 1,017 | 4.34375 | 4 | from typing import List
def can_two_movies_fill_flight(movie_lengths: List,
flight_length: int) -> bool:
"""Determines whether there are two movies whose length is equal to flight
length
Args:
flight_length: Length of the flight in minutes
movie_lengths: Lis... | true |
caea37fde1f2b0f8871ae93802951fcc9b439fc7 | LennyBoyatzis/compsci | /problems/reverse_words.py | 1,112 | 4.25 | 4 | from typing import List
def reverse_words(message: List) -> List:
"""Reverses words in a message
Args:
message: lists of words to be reversed
Returns:
Reversed words in a list
"""
return ''.join(message).split(' ')[::-1]
def reverse_chars_in_place(message: List) -> List:
""... | true |
b1be35f0320b213d35ab5434c7d985d290c08a94 | LennyBoyatzis/compsci | /problems/get_max_profit.py | 840 | 4.1875 | 4 | from typing import List
def get_max_profit(stock_prices: List) -> int:
"""Calculates the max profit for a given set of stock prices
Args:
List of stock prices
Returns: Maximum profit
"""
if len(stock_prices) < 2:
raise ValueError('Getting a profit requires at least 2 prices')
... | true |
ef0b085234cd62c3bf843989e43843be82f5116d | pranali0127/Python-AI-Ml | /Python_program_3_list.py | 1,092 | 4.3125 | 4 | #List
#let's first create demo list
numbers = [1,2,3,4,5,6,7,8,9,10]
#printing a list
print(numbers)
#method 1 : append(value)
# add new elements to the list
# can only add one element at a time
numbers.append(11)
print(numbers)
#method 2 : extend(values)
# add one or more than one element at a time
new = [12,13,14]... | true |
ccd0b3314bfbd668bc1ad44b72a130eeca0611aa | dbialon/LPTHW | /ex20.py | 1,905 | 4.3125 | 4 | from sys import argv, exit
script, input_file = argv
## print the whole file f using .read()
## could use this instead
## print open(input_file).read()
## but we want to use the file globally
## not just in this function
def print_all(f):
print(f.read())
## we're using .seek to go back to a line in fil... | true |
1c71fa4139919cc9960dee2e49b0f7d0961569fa | igoroya/igor-oya-solutions-cracking-coding-interview | /crackingcointsolutions/chapter1/excersisenine.py | 1,097 | 4.125 | 4 | '''
Created on 11 Aug 2017
String rotation: Assume you have a method isSubstring which checks if one word is a substring
of another. Given two strings, s1 and s2, write code to check if s2 is a rotation of s1 using only one
call to isSubstring (e.g. "waterbottle" is rotation of "erbottlewat)
@author: igoroya
'''
def ... | true |
416d4b5679807fff1a1d780250cb43e25dd6445e | Kulchutskiyyura/Yura | /classwork/classwork.py | 1,507 | 4.125 | 4 |
try:
number=int(input("enter nymber: "))
if number%2==0:
print("парне")
else:
print("непарне")
except ValueError:
print("некоректні дані")
def chack(age):
if age<=0:
raise ZeroDivisionError("That is not a positive number!")
while 1:
try:
age = int(input("ent... | false |
e6e5292490e46de3c51faa44ca7d88a7cdc51c64 | Kulchutskiyyura/Yura | /Multiples_of_3_or_5/Multiples_of_3_or_5.py | 252 | 4.25 | 4 | def find_sum_of_multiples_3_5(number):
sum=0
for i in range(number):
if(i%3==0):
sum+=i
print(i)
elif(i%5==0):
sum+=i
print(i)
return sum
print(find_sum_of_multiples_3_5(10))
| false |
d623377f72ea7bcb440d001b456e676a39cd642c | gungorahmet/algorithm-practices | /question_4/solution_4/division_without_divide_solution.py | 1,932 | 4.28125 | 4 | #!/usr/bin/python3
'''
Applied PEP8 (pycodestyle)
Author: Ahmet Gungor
Date : 03.01.2020
Description : This problem was asked by Nextdoor.
Implement integer division without using the
division operator. Your function should return a tuple of (dividend, remainder)
... | true |
6aa200771edd89a5c97c301512a6fedc2c608fbe | shitalmahajan11/letsupgrade | /Assingment2.py | 2,854 | 4.25 | 4 |
# LetsUpgrade Assignment 2
1. Back slash:- it is continuation sign.
Ex. print*("hello \
welcome")
2. triple Quotes:-represent the strings containing both single and double quotes to eliminate the need of escaping any.
Ex:- print("""this is python session""")
3.String inside the quotes:-there a... | true |
eb1289f5ae2fc5e25f5bc827eadf37748b35953b | ShantanuJhaveri/LM-Python_Basics | /learning_modules/learning_Expressions&Operators/experssions&operators_A1.py | 2,673 | 4.1875 | 4 | # Shantanu Jhaveri, sj06434@usc.edu
# ITP 115, Spring 2020
# Assignment 1
# Description:
# This program creates a Mad Libs story that was generated through an interview with a 10 year old cousin.
# The text generated is what he wanted.
# The code takes an input from the user and prints output, which in this case is the... | true |
110ef2545cbf3634c0caf1c0dec15d50f7f15567 | jhcoolidge/AffineCipher | /main.py | 1,700 | 4.28125 | 4 |
def encrypt(message, magnitude, shift):
encrypted_message = ""
for index in range(len(message)):
character = ord(message[index])
encrypted_char = character * magnitude
encrypted_char = encrypted_char + shift
encrypted_char = chr((encrypted_char % 26) + 65) # Mod 26 to ... | true |
7286241364f3ae973ef2f71a2d5d8e0835eaf24f | Catalin-Ioan-Sapariuc/Pet-Python-projects | /quadraticeqsolver.py | 1,769 | 4.4375 | 4 | ## this code solves the quadratic equation : a*x^2+b*x+c=0
## for modularization, we solve the problem in a function: quadraticeqsolver(a,b,c) , which returns (as a list)
## the solution of the quadratic equation a*x^2+b*x+c=0
## a, b and c are inputted by the user, they could be hard coded as well
## by Ioan Sap... | true |
1aa2ae45a863d872aacd544e677ed69a48899842 | VishalVema/Python-Automation | /ceasar cipher.py | 1,295 | 4.5 | 4 | import pyperclip
message = 'this is my secret message '
key = 13
mode = 'encrypt'
LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
translated = ''
message = message.upper()
for symbol in message:
if symbol in LETTERS:
num = LETTERS.find(symbol) #this function is used to find and return index of... | true |
a7d117a1c0df7b2a3012f9d6b76379a5ab60c1dd | talhabalaj/card-game | /server/src/GameLogic.py | 872 | 4.15625 | 4 | from random import shuffle
class Card:
CARD_TYPES = ["PAN", "PATI", "DIL", "DIAMOND"]
CARD_NUMBERS = ["A", 2, 3, 4, 5, 6, 7, 8, 9, 10, "J", "Q", "K"]
def __init__(self, number, card_type):
assert number >= 1 and number <= 13, 'Card number not valid'
assert card_type in Card.CARD_TYPES, 'Card type not v... | true |
c4e6f649990badfa983138498f18aab6828509c7 | hmunduri/MyPython | /datatype/ex14.py | 276 | 4.15625 | 4 | # Python program that accepts a comma serperate sequence of words as input and prints the unique words in sorted form
import sys
items = raw_input("Input comma seperated sequence of words")
words = [word for word in items.split(",")]
print(",".join(sorted(list(set(words)))))
| true |
891e45c0720ad58c8a116bf0b8197f14f419340a | hmunduri/MyPython | /datatype/ex8.py | 309 | 4.34375 | 4 | #python function that takes a list of words and returns the length of the longest one
def find_longest_word(words_list):
word_len = []
for n in words_list:
word_len.append((len(n), n))
word_len.sort()
return word_len[-1][1]
print(find_longest_word(["PHP", "EXCERCISE", "Eventually"]))
| true |
92ec5004591291e5c1f4a8d1054cc13de2360120 | misscindy/Interview | /Bit_Manipulation/Bit_Manipulation_Notes.py | 2,758 | 4.5 | 4 | '''
Basic Facts
The Operators:
x << y
Returns x with the bits shifted to the left by y places (and new bits on the right-hand-side are zeros). This is the same as multiplying x by 2**y.
x >> y
Returns x with the bits shifted to the right by y places. This is the same as //'ing x by 2**y.
x & y
Does a "bitwise and". Ea... | true |
a49839096b6331714fc25f9f60024ad2295d1af1 | nnquangw/aivietnam.ai-week2 | /pie_estimate.py | 609 | 4.125 | 4 | import math
import random
def pi():
"""
Estimating PI's value from N points, a rectangle and a circle
:param N: number of random points
:return: a float approximates to PI
"""
N = 100000
Nt = 0 #number of random points inside the circle
for _ in range(N):
x = random.unifor... | true |
b21cf4a05a09976fdeb5204424d9f58aa83785e5 | loganthomas/python-practice | /prep/fizzbuzz.py | 1,973 | 4.25 | 4 | """
FizzBuzz
--------
Write a program that outputs the string representation of numbers from
1 to n. For multiples of 3, it should output "Fizz" instead of the
number and for the multiples of 5 it should output "Buzz". For numbers
which are a multiple of both 3 and 5 it should output "FizzBuzz".
Notes
-----
%timeit ... | true |
190b6272017f62a133b0918c7176bc6dcdd0e82e | loganthomas/python-practice | /misc/rock_paper_scissors.py | 1,267 | 4.21875 | 4 | ##########################################################
# Make a two-player Rock-Paper-Scissors game.
# (Hint: Ask for player plays (using input), compare them,
# print out a message of congratulations to the winner, and ask if the
# players want to start a new game)
# Remember the rules:
# Rock beats scissors
# S... | true |
7a085e6f961de406845059715790f2f81df674fe | loganthomas/python-practice | /advent_of_code/year_2017/day1.py | 2,066 | 4.125 | 4 | """
Day 1:
Part 1:
The captcha requires you to review a sequence of digits (your puzzle input) and find the sum of all
digits that match the next digit in the list. The list is circular, so the digit after the last
digit is the first digit in the list.
For example:
1122 produces a sum of 3 (1 + 2) because the first ... | true |
0b8e2cd366095e60d257ca11c0bc06c89bc3df14 | loganthomas/python-practice | /misc/letter_counter.py | 1,122 | 4.21875 | 4 | """
Practice Problem:
Given a word and a letter, count the number of occurrences the given
letter has in the given word.
"""
def letter_counter(word, letter):
"""
Count number of times a give letter occurs in a given word.
Args:
word (str): Word provided in which to count letter
letter (... | true |
dcf88b8a5666c2add93a30314053ff1eb4530f63 | cifpfbmoll/practica-6-python-David-Sastre | /Práctica_6/P6_E10.py | 1,420 | 4.125 | 4 | #Escribe un programa que te pida los nombres y notas de alumnos. /
#Si escribes una nota fuera del intervalo de 0 a 10, el programa entenderá que no quieres introducir más notas de este alumno./
#Si no escribes el nombre, el programa entenderá que no quieres introducir más alumnos./
#Nota: La lista en la que se gu... | false |
e69da611aefc097fb3a1df50ddd6bd61ffd4bce4 | zwdnet/elephant | /currency/currency_converter_v5.py | 1,415 | 4.34375 | 4 | # -*- coding:utf-8 -*-
"""小象学院python教程
汇率兑换4.0版,识别币种,让程序不停运行,将兑换功能封装到函数里,使程序结构化"""
def convert_currency(im, er):
"""
:param im: 待兑换货币金额
:param er: 汇率
:return: 兑换的货币金额
"""
return im / er
def main():
# 带单位的货币输入
currency_str_value = input("请输入带单位的货币金额(退出程序输入Q):")
# rmb_value = eval... | false |
12017f29a1e87170dd443c8ce8d642613d957740 | chetan-mali/Python-Traning | /Regular Expression/Regex_3_Creditcard_number_validation.py | 957 | 4.15625 | 4 | #Regular Expression Credit card number verification
"""
A valid credit card from ABCD Bank has the following characteristics:
It must start with a '4', '5' or ' 6'.
It must contain exactly 16 digits
It must only consist of digits (0-9)
It may have digits in groups of 4, separated by one hyphen "-"
It must NOT use any ... | true |
82fb65a4c890b03e132aa7a9c76eea74d8bf6cd0 | rahulgupta271/DSC510-Spring2019 | /KAMMA_LENIN_DSC510/lkamma_wk3_asmnt.py | 2,943 | 4.375 | 4 | # File: lkamma_wk3_asmnt.py
# Course: DSC501-303 Introduction to Programming
# Assignment#: 3.1
# Author: Lenin Kamma
# Date: 03/29/2019
# Description: This program calculates the total installation cost of fiber optic cable with taxes
# discount is given if user purchases more than 100 feet of cable
# Usage: Th... | true |
e213a3b6971e411b2d94343963be0f934fd59c9d | rahulgupta271/DSC510-Spring2019 | /ERICKSON_HOLLY_DSC510/Assignment_2.1.py | 2,265 | 4.34375 | 4 | """
File: Assignment_2.1.py
Author: Holly Erickson
Date: 2019-03-23
Course: DSC 510-T303 Intro to Programming
Assignment: 2.1
Desc: This program display a welcome message. Then retrieves a company name &
the number of feet of fiber optic cable to be installed from the user.
It calculate the installation cost an... | true |
ae43a770aa72d98e07d9f3db8aa526709dbaadfa | alokkjnu/StringAndText | /6 SearchingReplacingCaseInsensitive.py | 627 | 4.53125 | 5 | # Searching and replacing Case-Insensitive Text
import re
text = 'UPPER PYTHON, lower python, Mixed Python'
t1 = re.findall('python',text, flags=re.IGNORECASE)
print(t1)
t2 = re.sub('python','snake',text, flags=re.IGNORECASE)
print(t2)
def matchcase(word):
def replace(m):
text = m.group()
if text... | true |
73833c450e8c011dc43947dcb0520002d4e7314f | jaap17/004_JaapAnjaria | /LAB1/numpy/scalingmatrices.py | 749 | 4.21875 | 4 | import numpy as np
okmatrix = np.array([[1,2],[3,4]])
result = okmatrix*2 + 1
print(result)
# Add two sum compatible matrices
result1 = okmatrix + okmatrix
print(result1)
# Subtract two sum compatible matrices. This is called the difference vector
result2 = okmatrix - okmatrix
print(result2)
result = okmatrix * okma... | true |
ee20b32bd13a7bcfd1c281bba74460a0b9dbb302 | om1chael/week3-python-Deloitte | /Python-Lessons/if statments homework .py | 1,118 | 4.4375 | 4 | #######list of movies with d
movies = {"Spiderman": {'release Date': 2002, "rating":"PG"},
"shrek": {'release Date': 2001, "rating":"PG-13"},
"mission impossible": {'release Date': 1996,"rating":"PG-13"},
}
####### print the list of movies ###
print("movie list",movies.keys())
#### ask ... | true |
b3437016d253cf0b7b14744eb87a61ca87832369 | but764/new-python | /задание2.py | 680 | 4.21875 | 4 |
#Для списка реализовать обмен значений соседних элементов,
# т.е. Значениями обмениваются элементы с индексами 0 и 1, 2 и 3 и т.д.
# При нечетном количестве элементов последний сохранить на своем месте.
# Для заполнения списка элементов необходимо использовать функцию input().
my_list = list(input('ввидете числа без ... | false |
e1c478fd41212d7d8807dc51c623f1407d59b718 | ramsandhya/Python | /ex11-rawinput.py | 838 | 4.21875 | 4 | # print "How old are you?",
# age = 9
# print "How tall are you?",
# height = 10
# print "How muxh do you weigh?",
# weight = 11
#
# print "So you are %d old, %d tall and %d heavy" % (age, height, weight)
# prints input in line 11, put the name, says line 12 with name, prints line 13
# name = raw_input("What is your n... | true |
2dcb30fe40d2cb3278d6360833ca2c8b3cd89ef9 | Semihcansertbas/CS_PF_Python_Unit4 | /tryme4.py | 461 | 4.28125 | 4 | def is_power(x,y):
if (x == y):
return True
if (y == 0) or (y == 1): #Exception Handling
return False
# Recursive
return ((x%y)==0) and (is_power(x/y,y)) #Includes is_divisible function
print("is_power(10, 2) returns: ", is_power(10, 2))
print("is_power(27, 3) returns: ", is_power(27, 3))
print("is_pow... | false |
060d8a18b506cf54ceeb8cd90bc9d30dcf57823e | SPOORTIA/Python-Tutorial | /program 3 - contd variables and strings.py | 1,284 | 4.4375 | 4 | # concatination of strings
message_1 = 'hello'
message_2 = 'hi'
message = message_1 + ' ' + message_2 + 'monkey'
print(message)
# f - formating
message = f'{message_1} {message_2}'
print(message)
message = f'{message_1} {message_2.upper()}'
print(message)
# dir - displays all the fuctions / attributes that are a... | true |
789ff1c81d403bb60f9895131fc8ce8cc18ffd49 | saurabh02/Bajaj_cc | /src/median_unique.py | 2,321 | 4.125 | 4 | #!/usr/bin/env python
import sys
import numpy as np
def running_median(file_object, file):
'''
Counts the number of unique words per line in a file, and calculates their running median
Arguments:
file_object: name of file object created for the input file containing the tweets
Re... | true |
e19b7b76d79b4fc66ffc2f089dda41ba433f561e | itsanjan/generic-python | /programs/P07_PrimeNumber.py | 558 | 4.3125 | 4 | # This program checks whether the entered number is prime or not
def checkPrime(number):
isPrime = False
i = 0
if (number == 1 or number == 2):
print("Number is a prime")
for i in range(2, int(number / 2) + 1):
if number % i == 0:
print("Number is not a prime")
... | true |
d9f243bc7e8c5623924700012385492527c16056 | jeancre11/PYTHON-2020 | /clase python con IDLE/listas_metodo pop.py | 471 | 4.3125 | 4 | """uso de datos y metodos"""
#lista1
#append y pop son METODOS.
lista1=[10, 20, 30]
print(lista1)
#lista2
lista2=[5,2,3,100]
print(lista2)
#concatenar listas
print('SE TIENE COMO CONCATENACIÓN')
print(lista1+lista2)
#sacar un elemento de la ultima posicion de la lista1, defoult ()
val=lista1.pop()
print('despues del me... | false |
de03dc8a5351810f75de7d9e657a50c9aca23e6d | BenjaminJ12/Group-dance-thing | /main.py | 1,332 | 4.125 | 4 | #19/8/20
#Hello Github
#Initialise arrays
nameArray = []
ticketArray = []
#collect data
groupName = input('What is the name of your group? ')
groupNumber = float(input('How many peple are in your group? Enter a number between 4 and 10 '))
#input validation
while groupNumber <4 or groupNumber >10 or not groupNumber... | true |
27bfe898dceeb51223d113597243b67b7d38882e | pyzhaoxd/jsj | /python_base/数据结构.py | 635 | 4.4375 | 4 | #Python 的列表数据类型包含更多的方法。这里是所有的列表对象方法:
#list.append(x)
#把一个元素添加到列表的结尾,相当于 a[len(a):] = [x]
x = [1,2,3,4]
print(len(x))
x.append(5)
print(x)
#list.extend(L)
#将一个给定列表中的所有元素都添加到另一个列表中,相当于 a[len(a):] = L
l = [9,10]
x.extend(l)
print(x)
# list.insert(i, x)
# 在指定位置插入一个元素。第一个参数是准备插入到其前面的那个元素的索引,例如 a.insert(0, x)
# 会插入到整个列表之... | false |
9946e2ee2bc5c1d3f3c68ea901e4987b391042e6 | cholzkorn/coding-challenges | /is-trimorphic/is_trimorphic.py | 426 | 4.375 | 4 | # Function to check if a number is trimorphic
# A trimorphic number is a number whose cube ends in itself
# Input 4: TRUE - (4^3 is 64, which ends in 4)
# Input 13: FALSE - (13^3 is 2197, which ends in 97)
import re
def is_trimorphic(x):
xc = x ** 3
xs = str(x)
xcs = str(xc)
pattern = re.escape(xs) + ... | true |
25d10b1e1e2e6bf1917ff4c5db8767e8a6159bc7 | stephen-weber/Project_Euler | /Python/Problem0019_Counting_Sundays.py | 2,456 | 4.15625 | 4 | """
Counting Sundays
Problem 19
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, twen... | true |
501bcb3355aa3b73020e0d3ad3fa4f0adcf0a011 | imagine-maven/Programs | /arrayInPython.py | 1,436 | 4.40625 | 4 | # no built in support for arrays , lists can be used
# import numpy to work with arrays
cars = ['bmw', 'ford', 'ferrari', 'mini']
# access items
print(cars[0])
print(cars[2])
# modify items just like lists
cars[0] = 'toyota'
print(cars[0])
# length of an array
x = len(cars)
print(x)
# looping through array elemen... | true |
9302d5a73d65cb6b75db6de6a690e6011f50e15c | vaishnavi-gupta-au16/Simple-Python-Programs | /calculator.py | 540 | 4.21875 | 4 | while True:
num1=int(input("Enter 1st number "))
num2=int(input("Enter 2nd number "))
choice = input("Enter your choices +, -, *, / or type ''q'' to quit: ")
if choice == "+":
calc = num1 + num2
print(calc)
elif choice == "-":
calc = num1 - num2
print(calc)
el... | false |
0c11cfccb306a801e3e46103231129f174795b4e | vaishnavi-gupta-au16/Simple-Python-Programs | /Lists/store_variable.py | 472 | 4.3125 | 4 | # Take 10 integer inputs from user and store them in a list and print them on screen using function.
num = []
def store_variable():
n = int(input("enter the 10 integer inputs"))
for i in range(0,n):
a = int(input())
num.append(a)
print(num)
store_variable()
## other solution ##
# i =... | true |
706eac28ddb856c2b9bcf2a18323aa1ec752d828 | htrahddis-hub/DSA-Together-HacktoberFest | /trees/BinaryTrees/Easy/tree_implementation.py | 1,266 | 4.15625 | 4 |
# Implementing Tree Data Structure
class TreeNode :
def __init__(self, data):
self.data = data
self.children = []
self.parent = None
def get_level(self):
level = 0
p = self.parent
while p:
level += 1
p = p.parent
return ... | false |
f20b29a9cdeb9aa91e23565f1f0dcb9b7914d021 | AlexeyZavar/informatics_solutions | /13 раздел(V2)/Задача G.py | 667 | 4.125 | 4 | #
# Напишите функцию CaseChange (c), меняющую регистр символа, то есть переводящую заглавные буквы в строчные, а строчные - в заглавные, остальные символы не меняющие. В решении нельзя использовать циклы. В решении нельзя использовать константы с неочевидным значением.
#
a = input()
def CaseChange(c):
c ... | false |
827040c9fa87434546df9f8365c41ece8cdd527d | Kuldeep28/Satrt_py | /zipinffuntion.py | 922 | 4.21875 | 4 | string="kuldeepop"
tup=[1,2,5,7,8,8,9,89,90]
print(list(zip(string,tup)))# in zip function the length of the zip list is depending on the value of the shortest listt
zipped=list(zip(string,tup))
for entity,num in zipped:# that cool we are using tupple assingnment to iterate over it as we are confirmed that there
... | true |
7ae81ec8b202b1423b004d8fd492eb1fd8486972 | Kuldeep28/Satrt_py | /lists_dic_funtion.py | 869 | 4.34375 | 4 | #in this we are using the lists function used for geeting the key value from a dict
# thed item finctin will return the tupple of key value pairs
d={1:23,3.23:24,34:23}
print(list(d))
print(d.items())#give iterator dictitems
#Combining dict with zip yields a concise way to create a dictionary:
#>>> d = dict(zip('a... | true |
4f4316a8d2c72f21c28ff259d557c43b6bb75ec7 | hiaQ/learnPython | /test31.py | 616 | 4.15625 | 4 | #!/user/bin/env python
#coding:utf-8
str = input('please input:')
if str == '':
print('Please input!')
elif str == 'M':
print('It is Monday')
elif str == 'W':
print('It is Wednesday')
elif str == 'F':
print('It is Friday')
elif str == 'T':
print('Please input the second letter:')
letter = input('Please input:')
... | false |
c402b2784049210bd33472b0f01c7acb0336012b | Qwatha/Test | /2nd_exercise.py | 570 | 4.375 | 4 | """ Написать метод/функцию, который/которая на вход принимает число (float),
а на выходе получает число, округленное до пятерок."""
def func(float_number):
"""Функция принимает вещественное число и округляет его"""
if type(float_number) != float:
return "Введите число с плавающей точкой"
retu... | false |
5936e36e171622063c5506f36aba4adc3ac4c8fc | gonzaloamadio/pacman | /app/board.py | 1,056 | 4.125 | 4 | """
The Board just has a width, a height and some walls.
The Board can only tell if a move is valid or invalid
"""
import logging
LOG = logging.getLogger(__name__)
class Board:
def __init__(self, x, y, walls):
self.x = x
self.y = y
self.walls = walls
LOG.debug("The board is %s by... | true |
571c1afec2aeeb3db64381176c485929236af584 | hazemshokry/CrackingTheCodingInterview | /CheckPermutation.py | 619 | 4.46875 | 4 | # Given two strings, write a method to decide if one is a permutation of the other.
# Example, Dog is considered a permutation of God.
def checkPermutation (string1, string2):
"""
:param string1: string #1 to check if it is considered as a permutation for string #2.
:param string2: string #2 to check if it... | true |
9a2417bca1c1da163dab3766ce8db79e94666f04 | hazemshokry/CrackingTheCodingInterview | /String Compression.py | 827 | 4.3125 | 4 | # Implement a method to perform basic string compression using the counts of repeated characters.
# For example: the string aabcccccaaa would be a2b1c5a3.
# Note: if the new string is larger than the older one, return the original.
def stringCompression(string):
"""
:param string:
:return: return a new str... | true |
b2cfe6d7b3c8fd4cbfc67b82dab661cc2ad02762 | cdw2003/CodingDojoProjects | /Python/Algorithms/MultiplesSumAverage.py | 2,034 | 4.25 | 4 | #Multiples
def MultiplesOdd(): #first define a function that does not take any parameters.
for i in range (1,1001): #run a for loop that goes from 1 to 1,001 so that 1,000 is included.
if i % 2 == 1: #use an if statement to select only the odd values.
print i #print the i values that meet th... | true |
88d65ac648be2bce67af9de17929160d6ee6c8d0 | antoniosalinasolivares/numericalMethods | /src/newtonRaphson.py | 1,589 | 4.21875 | 4 |
import math
import numpy as np
import matplotlib.pyplot as plt
class NewtonRaphson:
function = None
derivative = None
initial_point = None
def __init__(self, function, derivative, initial_point):
self.function = function
self.derivative = derivative
self.initial_point = initial... | true |
f41b90f5484a6da32054b361f3448a5455182023 | rashmee/Python-Projects | /nonRepeatingCharacter.py | 278 | 4.1875 | 4 | # coding=utf-8
#Find the first non repeating character
def first_non_repeating_char(str):
for character in str:
if str.count(character) > 1:
continue
else:
return character
return -1
print first_non_repeating_char("oohay")
print first_non_repeating_char("abccba")
| true |
0263d7361cb9697d8b9a4e97033a4129ec504493 | rashmee/Python-Projects | /guessNumber.py | 1,475 | 4.28125 | 4 | # coding=utf-8
# The Goal: Similar to the first project, this project also uses the random module in
# Python. The program will first randomly generate a number unknown to the user.
# The user needs to guess what that number is. In other words, the user needs to be
# able to input information. If the user’s guess is wr... | true |
b2c48680f43eed2bf16540a3fdab28d0347911ad | hakankaraahmet/python-projects | /password reminder.py | 216 | 4.15625 | 4 | name = "Freddie"
user_name = input("Please enter you user name: ").title()
if user_name == name:
print("Hello Freddie! The password is: Mercury")
else:
print("Hello {}! See you later.".format(user_name))
| true |
3d8b1f1ebb7f166cb3327dc656dfab6ec3373110 | grapefruit623/leetcode | /easy/144_binaryTreePreorder.py | 1,710 | 4.1875 | 4 | # -*- coding:utf-8 -*-
#! /usr/bin/python3
import unittest
from typing import Optional, List
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
'''
AC
'''
class Solution:
def preo... | true |
a186fb1e703f2276161e2e2923ee19fc576abea2 | EricRovell/project-euler | /deprecated/062/python/062.brute.py | 1,321 | 4.34375 | 4 | """
This is not optimised solution!
Even though the problem includes work with permutations,
it is not necessary to permute each and every cube to solve
the problem. This approach would take too much time and resources.
To explain the approch, let's take two arrays with the same elements
but in diff... | true |
1b9b7d0fbc3a640a68ea39be98bdb0706dfd1076 | sebaslherrera/holbertonschool-machine_learning | /math/0x00-linear_algebra/2-size_me_please.py | 335 | 4.1875 | 4 | #!/usr/bin/env python3
"""Module shape of a matrix """
def matrix_shape(matrix):
""" Return the shape of a matrix
returns a tuple with each index having the
number of corresponding elements """
ans = []
while (isinstance(matrix, list)):
ans.append(len(matrix))
matrix = matrix[0]
... | true |
4848a19e3e05d125d617075f3db15d8553c0ed64 | wahome24/100-Days-of-Code---The-Complete-Python-Pro-Bootcamp | /Project_1.py | 580 | 4.5 | 4 | #1. Create a greeting for your program.
print('Welcome to band name generator!')
print()
#2. Ask the user for the city that they grew up in.
city = input('Please enter the name of the city you grew up in:\n').capitalize()
#3. Ask the user for the name of a pet
pet = input('What is the name of your pet?\n').capital... | true |
ac7772c77ec2880f32dda146ec3c4cbf2f1190e5 | LBolser/CIT228 | /Chapter5/hello_admin.py | 1,080 | 4.25 | 4 | print("<<<<< Exercise 5-8 >>>>>")
usernames = ["Admin","Beth","Charlie","Daisy","Ed"]
for name in usernames:
if name == "Admin":
print(f"Hello, how are you today, {name}?")
else:
print(f"Thank you for logging in, {name}.")
print("\n<<<<< Exercise 5-9 >>>>>")
usernames = []
if usernames:
for... | false |
ba7e353c7f5b7255ba84b02c93dd8f5542eba464 | jackG97/PythonUdemyCourse | /Tutorials/venv/Data_Types_Variables_Strings.py | 457 | 4.15625 | 4 | character_name = "Tom"
character_age = "50"
print("There once was a man named " +character_name + ", ")
print("he was " + character_age + " years old. ")
character_name = "Mike"
print("he really liked the name "+character_name + ", ")
print("but didn't like being " +character_age + ". ")
phrase = "Giraffe Academy"
p... | false |
245ea942db80ba1efb6c86c8ca08245ec3a1f182 | sethsdo/Python_Algorithms | /making_dictionaries.py | 497 | 4.125 | 4 | #Assignment: Making Dictionaries
#Create a function that takes in two lists and creates a single dictionary where the first list contains keys and the second values.
# Assume the lists will be of equal length.
name = ["Anna", "Eli", "Pariece", "Brendan", "Amy", "Shane", "Oscar", "wild"]
favorite_animal = ["horse", "c... | true |
0277b0bcba538af98eb469a542ddc1c432eb0bc5 | sethsdo/Python_Algorithms | /List_Type.py | 814 | 4.1875 | 4 | #takes a list and prints a message for each element in the list, based on that element's data type
l = ['magical unicorns',19,'hello',98.98,'world']
j = [2,3,1,7,4,12,]
d = ['magical unicorns','hello','world']
def typeList(arr):
newArr = []
numSum = 0
for i in arr:
if type(i) == str:
n... | true |
707c2624437f23743a6cec1b8a3164dd9a8db602 | Jainam2848/Usask-CMPT141-Assignments | /Assignment 1/a1q4.py | 539 | 4.125 | 4 | # NAME :- SHAH JAINAM DINESHKUMAR
# NSID :- AYQ754
# STUDENT NUMBER :- 11321534
# INSTRUCTOR'S NAME :- Nisha Puthiyedth
# COURSE :- CMPT 141
weight = float(input("Enter your weight in kg :"))
height = float(input("Eter your height in meters :"))
def bmi(weight, height):
""" This function will calculate the body... | false |
f762d44cd9757e1c63fa0ed1a399cc9f18fcfe9b | paulizio/pythonexercises | /collatz.py | 338 | 4.375 | 4 | #Type in a number,and this program will call the Collatz function until the number is 1
def collatz(number):
while number!=1:
if number%2==0:
number=number//2
print(number)
else:
number=3*number+1
print(number)
num=int(input('Insert number: '))
coll... | true |
353db06c182e9f8655c0c0d9ed0c4bc4f51ca8d2 | applebyn/obds_training | /python/PythonexerciseDNAstrand.py | 2,321 | 4.375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 25 14:12:15 2021
Find the complementary DNA strand
@author: andreas
"""
#find the complementary DNA strand
def complementarynucleotide(nucleotide):
#input is nucleotide A, T, C or G
#output is nucleotide A, T, C or G
output = None
#... | true |
780a0db7d4ceb064a5514af1ac49a11514db67f0 | MichelGutardo/algorithms | /data_structure/queue_collection_deque.py | 956 | 4.34375 | 4 | #!/bin/python3
#collection_deque implementation using collection.deque class
#Use append() to add and popleft() elements in FiFo order
# Deque if preferred over list because append is quicker [ O(1) ], but
# pop operations as compared to list [ O(n) ]
from collections import deque
collection_deque = deque()
# ap... | true |
5f0bf6b6bd534c8901eb1f2fb3ff245b12e7b78f | vaishalicooner/practice_stacks_queues | /balance_parens_stack.py | 441 | 4.15625 | 4 | # Balance Parens with a Stack
def are_parens_balanced(symbols):
"""Are parentheses balanced in expression?"""
# make a stack
parens = Stack()
for char in symbols:
if char == "(":
parens.push(char) # push onto stack
elif char == ")":
if parens.is_empty():
return False
el... | true |
1aa46e19da8ae4ef5185d75bf2b97ad0d66ab061 | miguelex/Universidad-Python | /Fundamentos/operadores-logicos.py | 405 | 4.15625 | 4 | #a = int(input("Introduce un valor: "))
a =3
valorMinimo = 0
valorMaximo = 5
dentroRango = a >= valorMinimo and a <= valorMaximo
#print(dentroRango)
if(dentroRango):
print("Dentro del rango")
else:
print("Fuera del Rango")
vacaciones = False
diaDescanso = True
if(vacaciones or diaDescanso):
print("Pued... | false |
6935144e5631ab795771cad595e9f74cd42289c1 | miguelex/Universidad-Python | /Fundamentos/tuplas.py | 545 | 4.3125 | 4 | #Una tupla mantiene el orden oeri no se puede modificar
frutas = ("Naranja", "Platano", "Guayaba")
print(frutas)
#largo de la tupl
print(len(frutas))
#accediendo a un elemento
print(frutas[0])
#navegacion inversa
print(frutas[-1])
#rango
print(frutas[0:2]) #Excluyebdo indice 2
#modificar tupla
frutasLista = list(fru... | false |
21687309adf8bb75f56e15267b33f3c63c29c165 | munkhbat57/nucamp_python | /1-Fundamentals/battlegame.py | 2,415 | 4.125 | 4 | game_on = True
while game_on:
wizard = "Wizard"
elf = "Elf"
human = "Human"
orc = "Orc"
wizard_hp = 70
elf_hp = 100
human_hp = 150
orc_hp = 200
wizard_damage = 150
elf_damage = 100
human_damage = 20
orc_damage = 120
dragon_hp = 300
dragon_damage = 50
whil... | false |
86138310509f15c39891d2886711d8d609734d5c | anmolrishi/ProgrammingHub | /bogosort.py | 602 | 4.1875 | 4 | # Bogosort: A very effective and efficient sorting algorithm :^)
import random
def isSorted(listOfNums):
for i in range(len(listOfNums) - 1):
if listOfNums[i] > listOfNums[i + 1]:
return False
return True
def main:
print("Input a list of numbers (seperated by [enter]s) and terminate input by entering... | true |
67b2bcd448c3f7a3935f2f3ffc9c05b306f9895e | kakashi-hatake/wumpus | /wumpus_prebow.py | 2,491 | 4.125 | 4 | from random import choice
def create_tunnel(cfrom, cto):
"""create a tunnel between from and to"""
caves[cfrom].append(cto)
caves[cto].append(cfrom)
def visit_cave(number):
"""mark a cave as used"""
visited_caves.append(number)
unvisited_caves.remove(number)
def choose_cave(cave_list):
"""pick a cave p... | true |
a08f42e3bf4d1bad0300bef19434df11be473c2f | Jyothi-narayana/DSA | /MI1.py | 638 | 4.1875 | 4 | from sets import Set
class WordList:
"""Stores a list of words"""
def __init__(self):
"""Initializes a set to store the list of words"""
self.words = Set()
def addWord(self, word):
"""Add a word to the word list"""
self.words.add(word)
def addWords(self, words):
for w in words:
self.addWord(w)
def has... | true |
ae935303ed1f963925c756fdb70b964600442f5e | ttafsir/100-days-of-code | /code/day1/day1_datetime.py | 1,341 | 4.25 | 4 | from datetime import date, time, timedelta, datetime
april_fools_2021 = date(year=2021, month=4, day=1)
noon = time(hour=12, minute=0, second=0)
midnite = time(hour=0, minute=0, second=0)
print(f"april fool's day is: {april_fools_2021}")
print(f"noon == {noon}")
print(f"midnight == {midnite}")
# working with dates
... | false |
ba37bec74aae29348f52ae94d4bafc4ccf6a912b | jusnlifa/shiyanlou-code | /while.py | 202 | 4.1875 | 4 | # coding=utf-8
myList = ['English','Chinese','Japane','German','France']
# while len(myList):
# print('pop element out:',myList.pop())
for language in myList:
print('current element is :',language) | false |
fa73596b37501bb2804ea41e75e46bed8461a723 | momentum-cohort-2019-02/w2d2-palindrome-yyapuncich | /palindrome.py | 1,628 | 4.4375 | 4 | # ask user for sentence or name and let them know if it's a palindrome
# ask user for input string
phrase_entered = input("Enter a phrase and let's check if it's a palindrome: ")
#remove all special characters and spaces from phrase
def remove_extra_spaces(phrase_entered):
"""This function removes spaces and speci... | true |
11fe4ab12798b0c761227d0b183d90e0f7bcec89 | miroswd/python-impacta | /manipulandoArquivos.py | 724 | 4.15625 | 4 | # Read
# modo leitura ja esta embutido, nao precisa carregar modulo
# o arquivo deve permanecer no mesmo diretorio do arquivo py
def readFile(file):
arquivo = open(file,'r') # funcao open('nome','modo de manipulacao (r > read, w > write, a > apend, incluir depois do conteudo do arquivo, r+ > read e write)')
for l... | false |
52f8962a2909bcb3d0117cbf2ee2d99a5fb713f5 | miroswd/python-impacta | /orientacaoAObjeto.py | 1,312 | 4.3125 | 4 | # Classe
# interpretar como uma receita
# atributos => ingredientes
# metodos => modo de fazer
# classe Pessoa
# atributos => nome, idade e sexo
# metodos => andar, comer e dormir
# Criando um Objeto
# p = Pessoa() # Declara variavel referenciando a classe Pessoa
# p.nome = 'Miro'
# p.idade = 20
# p.sexo = ... | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.