blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
c91cea964cc5f6b8931497a93c6ac1b37cf8ca62 | serereg/homework-repository | /homeworks/homework2/hw5.py | 1,611 | 4.15625 | 4 | """
Some of the functions have a bit cumbersome behavior when we deal with
positional and keyword arguments.
Write a function that accept any iterable of unique values and then
it behaves as range function:
import string
assert = custom_range(string.ascii_lowercase, 'g') ==
['a', 'b', 'c', 'd', 'e', 'f']
assert = c... | true |
c312bb50572e8260c13796c143961aa68d2cb8f8 | serereg/homework-repository | /homeworks/homework2/hw3.py | 752 | 4.125 | 4 | """
Write a function that takes K lists as arguments and
returns all possible
lists of K items where the first element is from the first list,
the second is from the second and so one.
You may assume that that every list contain at least
one element
Example:
assert combinations([1, 2], [3, 4]) == [
[1, 3],
[... | true |
d9085475d79d664153e73818e7a07fe628910a06 | DonCastillo/learning-python | /0060_sets_intro.py | 2,661 | 4.25 | 4 | farm_animals = {"sheep", "cow", "hen"} # sets are unordered, can set the order randomly every time the code is ran
print(farm_animals) # sets only contains one copy of each element
for animal in farm_animals:
print(animal)
print("=" * 40)
wild_animals = set(["lion", "tiger", "panther", "elepha... | true |
c67e8738b515c6f514123d1b27e57bdbee27a628 | mnovak17/wojf | /lab01/secondconverter.py | 497 | 4.125 | 4 | #secondconverter.py
#Translates seconds into hours, minutes, and seconds
#Mitch Novak
def main():
print("Welcome to my Second Converter! \n")
print("This program will properly calculate the number of \n minutes and seconds under 60 from a given number of seconds")
n = eval(input("How many seconds have you... | true |
4a0738f39e7d517d81903dd7a63f76b7f6b8d7a5 | RinkuAkash/Python-libraries-for-ML | /Numpy/23_scalar_multiplication.py | 426 | 4.1875 | 4 | '''
Created on 21/01/2020
@author: B Akash
'''
'''
problem statement:
Write a Python program to create an array of (3, 4) shape, multiply every element value by 3 and display the new array.
Expected Output:
Original array elements:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
New array elements:
[[ 0 3 6 9]
[12 15 18 21]... | true |
0ac549f8f324ddc0246cc9a6227ed0ddb715ffde | sabgul/python-mini-projects | /guess_the_number/main.py | 1,110 | 4.28125 | 4 | import random
def guess(x):
random_number = random.randint(1, x)
guess = 0
while guess != random_number:
guess = input(f'Guess a number between 1 and {x}: ')
guess = int(guess)
if guess < random_number:
print('Guess was too low. Try again.')
elif guess > ran... | true |
5f215b292c15000d73a2007e8ed8e81d32e536a5 | OmarKimo/100DaysOfPython | /Day 001/BandNameGenerator.py | 465 | 4.5 | 4 | # 1. Create a greeting for your program.
print("Welcome to My Band Name Generator. ^_^")
# 2. Ask the user for the city that they grow up in.
city = input("What's the name of the city you grow up in?\n")
# 3. Ask the user for the name of a pet.
pet = input("Enter a name of a pet.\n")
# 4. Combine the name of their c... | true |
ebca9d6de69c7539774b2a57852d492ab0d7295d | Nicodona/Your-First-Contribution | /Python/miniATM.py | 2,703 | 4.25 | 4 | # import date library
import datetime
currentDate = datetime.date.today()
# get name from user
name = input("enter name : ")
# create a list of existing name and password and account balance
nameDatabase = ['paul', 'peter', 'emile', 'nico']
passwordDatabase = ['paulpass', 'peterpass','emilepass', 'nicopass']
accountB... | true |
6614083932d6659190d7eb0dc5ba9693d2faa44e | jeremyosborne/python | /iters_lab/solution/itools.py | 816 | 4.28125 | 4 | """
Lab
---
Using the iterutils, figure out the number of permutations possible when
rolling two 6-sided dice. (Hint: Think cartesian product, not the
permutations function.)
Print the total number of permutations.
Make a simple ascii chart that displays the count of permutat... | true |
edc84c8a30911e7bd2d8c82fbdcac975cd3a1f40 | Deathcalling/Data-Analysis | /pythonData/pythonPandas/pandasBasics1.py | 1,529 | 4.125 | 4 | import pandas as pd #Here we import all necessary modules for us to use.
import datetime
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import style #This simply tells python that we want to make matplotlib look a bit nicer.
style.use('ggplot') #Here we tell python what kind of style we would l... | true |
ef5ad01f85285601321ec6fa246a16e6f07b775b | siddharth456/python_scripts | /python/add_elements_to_a_list.py | 251 | 4.34375 | 4 | # add elements to an empty list
testlist=[]
x=int(input("enter number of elements to be added to the list:"))
for i in range(x):
e=input("enter element:")
testlist.insert(i,e)
print() # adds an empty line
print("Your list is",testlist)
| true |
911040a477c107f353b3faace1d688dafde3064d | siddharth456/python_scripts | /python/create_user_input_list.py | 209 | 4.375 | 4 | # We will create a list using user input
userlist = [] # this is how you initialize a list
for i in range(5):
a=input("Enter element:")
userlist.append(a)
print ("your created list is:",userlist)
| true |
b32a498930d2701520f45965a56d65fa09e533ad | SergioG84/Python | /weight_converter.py | 1,113 | 4.15625 | 4 | from tkinter import *
window = Tk()
# define function for conversion
def convert_from_kg():
grams = float(entry_value.get()) * 1000
pounds = float(entry_value.get()) * 2.20462
ounces = float(entry_value.get()) * 35.274
text1.insert(END, grams)
text2.insert(END, pounds)
text3.inser... | true |
8aece43ba3fef62e3bd9b1f2cead27608995c2c4 | SHASHANKPAL301/Rock-Paper-and-Scissor-game | /game.py | 1,311 | 4.25 | 4 | import random
print(''' Welcome to the Rock,Paper and Scissor game. THe rule of the game is shown below:-
1. rock vs scissor---> rock win
2. scissor vs paper---> scissor win
3. paper vs rock---> paper win''')
def game(computer, player):
if computer == player:
return None #tie
elif comput... | true |
a43a0d590b70294442e9d92916cad822be961d3e | ohlemacher/pychallenge | /3_equality/equality.py | 2,339 | 4.34375 | 4 | #!/usr/bin/env python
'''
Find lower case characters surrounded by exactly three upper case
characters on each side.
'''
import pprint
import re
import unittest
def file_to_string():
'''Read the file into a string.'''
strg = ''
with open('equality.txt', 'r') as infile:
for line in infile:
... | true |
3fbe28eaf7e972df0dc5c38e6adcc6857769fccd | fhossain75/CS103-UAB | /lab/lab07/reverse_stubbed.py | 441 | 4.375 | 4 | # 19fa103; john k johnstone; jkj at uab dot edu; mit license
# reverse1 iterates over the element;
# this is the one to remember, since it is the most natural and clear;
# so this is the one to practice
def reverse1 (s):
"""Reverse a string, iteratively using a for loop (by element).
>>> reverse1 ('garden')
... | true |
8385b7cca4d9d2e2a7d25209233d5462ab8af24c | ErenBtrk/Python-Exercises | /Exercise21.py | 723 | 4.15625 | 4 | '''
Take the code from the How To Decode A Website exercise
(if you didn’t do it or just want to play with some different code, use the code from the solution),
and instead of printing the results to a screen, write the results to a txt file. In your code,
just make up a name for the file you are saving to.
Extras:
... | true |
f99df6b2eabb591210ef8a18b648deaf198a9ef8 | ErenBtrk/Python-Exercises | /Exercise5.py | 1,280 | 4.25 | 4 | '''
Take two lists, say for example these two:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
and write a program that returns a list that contains only the elements that are common between the lists
(without duplicates). Make sure your program works on two lists o... | true |
8b53226541e87eaee9b5ad490c425a35d84e3ab6 | Dinesh-Sivanandam/LeetCode | /53-maximum-subarray.py | 1,083 | 4.25 | 4 | #Program to find the maximum sum of the array
def maxSubArray(A):
"""
:type nums: List[int]
:rtype: int
"""
#length of the variable is stored in len_A
len_A = len(A)
#if the length of the variable is 1 then returning the same value
if 1 == len_A:
return A[0]
"""
... | true |
71929d852440e9767bed7adf6cb2d1deb9ed93b3 | ul-masters2020/CS6502-BigData | /lab_week2/intersection_v1.py | 349 | 4.1875 | 4 | def intersection_v1(L1, L2):
'''This function finds the intersection between
L1 and L2 list using in-built methods '''
s1 = set(L1)
s2 = set(L2)
result = list(s1 & s2)
return result
if __name__ == "__main__":
L1 = [1,3,6,78,35,55]
L2 = [12,24,35,24,88,120,155]
result = intersection_v1(L1, L2)
print(f"Inter... | true |
8b2ec04aef80d96e472eaf2592d180f41c0b06a2 | ABDULMOHSEEN-AlAli/Guess-The-Number | /Guess-The-Number.py | 2,895 | 4.25 | 4 | from random import randint # imports the random integer function from the random module
computer_guess = randint(1, 50) # stores the unknown number in a variable
chances = 5 # sets the chances available to the user to 5
def mainMenu(): # defines the main menu function, which will be prompted to the user every now an... | true |
7906bb35b5f7c0c0acb8730ff7ccc6423fdd1623 | LesroyW/General-Work | /Python-Work/Loops.py | 470 | 4.4375 | 4 | #Looping over a set of numbers
# For number in numbers:
# print(number) examples of for loop
# For loops can also loop of a range
#e.g for x in range(5):
# print(x)
#While loops can also be used within it
#Break and continue statements can be used to skip the current block or return to the for/whil statement
# el... | true |
9b3267d9488f10a980a2935d77bf906c4468f281 | adityagith/pythonprograms | /prime number.py | 278 | 4.15625 | 4 | a = int(input("Enter a number to check its prime or not\n"))
if(a<=0):
print("No")
elif(a==2):
print("Yes")
elif(a>2):
for i in range(2,a):
if(a%i==0):
print("Not a prime")
break
else:
print("Prime")
| true |
2584097aff364d6aeb60030eda2117628cbceda9 | siva4646/DataStructure_and_algorithms | /python/string/longest_word_indictioary_through_deleting.py | 986 | 4.15625 | 4 | """
Given a string and a string dictionary, find the longest string in the dictionary that can be formed by deleting some characters of the given string. If there are more than one possible results, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string.... | true |
2e274a24f93f81017686ad4c5ceabfaece95d419 | sebasbeleno/ST0245-001 | /laboratorios/lab02/codigo/laboratorio2.py | 1,610 | 4.15625 | 4 | import random
import sys
import time
sys.setrecursionlimit(1000000)
# Function to do insertion sort
def insertionSort(arr):
# Traverse through 1 to len(arr)
for i in range(1, len(arr)):
key = arr[i]
# Move elements of arr[0..i-1], that are
# greater than key, to one posi... | true |
afd31e371feaed5fdf84e4372460b931416b3284 | karankrw/LeetCode-Challenge-June-20 | /Week 3/Dungeon_Game.py | 1,918 | 4.3125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 22 01:25:32 2020
@author: karanwaghela
"""
"""
The demons had captured the princess (P) and imprisoned her in the bottom-right corner of a dungeon.
The dungeon consists of M x N rooms laid out in a 2D grid.
Our valiant knight (K) was initially po... | true |
65c2f70ca2dae1538060ac49c894702961d52e91 | Python-lab-cycle/Swathisha6 | /2.fibopnnaci.py | 214 | 4.15625 | 4 | n =int(input("enter the number of terms:"))
f1,f2=0,1
f3=f2+f1
print("fibonacci series of first" , n, "terms")
print(f1)
print(f2)
for i in range (3, n+1):
print(f3)
f1=f2
f2=f3
f3=f1+f2
| true |
ee934da6f5e0eee00050b8ed0845a2a9f70dd3e7 | katherfrain/Py101 | /tipcalculator2.py | 810 | 4.125 | 4 | bill_amount = float(input("What was the bill amount? Please don't include the dollar sign! "))
service_sort = input("What was the level of service, from poor to fair to excellent? ")
people_amount = int(input("And how many ways would you like to split that? "))
service_sort = service_sort.upper()
if service_sort == "P... | true |
2efd2878071e1534f85d45a7c3f36badb42c7a96 | katherfrain/Py101 | /grocerylist.py | 447 | 4.125 | 4 | def want_another():
do_you_want_another = input("Would you like to add to your list, yes/no? ")
if do_you_want_another == "yes":
grocery = input("What would you like to add to your list? ")
grocery_list.append(grocery)
print("You have added ", grocery, "to the list")
prin... | true |
15cba18ee92d82bf0f612e96ece1dc4a2911d9fc | ghimire007/jsonparser1 | /jsonparser.py | 1,111 | 4.1875 | 4 | # json parsor
import csv
import json
file_path = input("path to your csv file(add the name of your csv file as well):") # takes file path
base_new = "\\".join(file_path.split("\\")[:-1])
file_name = input(
"name of th file that you want to save as after conversion(no extension required):") # takes nam... | true |
84e0a3ba3678e6e5bc8618871e8d7a2eb6cebfe1 | himala76/Codding_Lesson_1 | /Lectures_Note_Day_1/Cancat.py | 352 | 4.4375 | 4 | # This is the result we want to have in the console
#print "Hello, world! My name is Josh."
# Create a variable to represent the name and introduction statement to print
name = "Josh"
# Comment out this line for the moment
# intro_statement = "Hello, world! My name is "
# print the concatenated string
print "Hello, ... | true |
4b02cf096cd437659968330d1e2fed228fd2036f | asenath247/COM404 | /1-basics/4-repetition/3-ascii/bot.py | 212 | 4.15625 | 4 | print("How many bars should be charged.")
bars = int(input())
chargedBars = 0
while chargedBars < bars:
print("Charging "+"█" * chargedBars)
chargedBars += 1
print("The battery is fully charged.")
| true |
4b3fd151726e2692179e72be9fb71e4b3fb632a3 | vishal-B-52/Documentation_of_Python | /GuessTheNumberModified.py | 1,693 | 4.25 | 4 | # Guess the number :-
print("This is a 'Guess the Number Game'. You have 10 Life(s) to guess the hidden number. You have to win in 10 Life(s) "
"else You lose!!! ")
Life = 10
while True:
N = int(input("Enter the number:- "))
Life -= 1
if 0 <= N < 18:
if Life == 0:
pr... | true |
9790f37381a1455af2fbb10777525caa9b8d0ab0 | innovatorved/BasicPython | /x80 - Tuples.py | 541 | 4.3125 | 4 | #turple
#turple is immutable
#once u defined turple u cannot change its elements
bmi_cat = ('Underweight' , 'Normal', 'Overweight' ,'very Overweight')
#type
print('Type: ',type(bmi_cat))
#access element of turple
print(bmi_cat[1]) #we use positive value
print(bmi_cat[-2]) #and we also use negative value
print(b... | true |
43fd97252b25c653bfdbe8a1349cd89475d40e60 | HananeKheirandish/Assignment-8 | /Rock-Paper-Scissor.py | 876 | 4.125 | 4 | import random
options = ['rock' , 'paper' , 'scissor']
scores = {'user' : 0 , 'computer' : 0}
def check_winner():
if scores['user'] > scores['computer']:
print('Play End. User Win!! ')
elif scores['user'] < scores['computer']:
print('Play End. Computer Win!! ')
else:
pri... | true |
e2a0c342c90cd07b387b7739b9869aee46df4090 | luroto/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/5-text_indentation.py | 761 | 4.15625 | 4 | #!/usr/bin/python3
"""
Function handbook:
text_identation("Testing this. Do you see the newlines? It's rare if you don't: all are in the code."
Testing this.
Do you see the newlines?
It's rare if you dont:
all are in the code.
"""
def text_indentation(text):
""" This function splits texts adding newlines when... | true |
3b0fe27b3dc3448de0bdcdd034ff6220af9bad2d | mtocco/ca_solve | /Python/CA041.py | 2,774 | 4.28125 | 4 | ## Code Abbey
## Website: http://www.codeabbey.com/index/task_view/median-of-three
## Problem #41
## Student: Michael Tocco
##
##
##
## Median of Three
##
##
## You probably already solved the problem Minimum of Three - and it was
## not great puzzle for you? Since programmers should improve their logic
## (and not o... | true |
fbec208c8dae08742e23d199f4a4debc8d125430 | unknownpgr/algorithm-study | /code-snippets/02. permutation.py | 724 | 4.15625 | 4 | '''
Recursive function may not be recommanded because of stack overflow.
However, permutation can be implemented with recursive function without warring about overflow.
That is because n! grows so fast that it will reach at time limit before it overflows.
'''
def permutation(array):
'''
This function returns ... | true |
af800a84a2887a6cc0561a74b3a44215ac9e8457 | jhglick/comp120-sp21-lab09 | /longest_increasing_subsequence.py | 467 | 4.125 | 4 | """
File: longest_increasing_subsequence.py
Author: COMP 120 class
Date: March 23, 2021
Description: Has function for longest_increasing_subsequence.
"""
def longest_increasing_subsequence(s):
"""
Returns the longest substring in s. In case of
ties, returns the first longest substring.
"""
pass
i... | true |
5b17d6216a339ee9642c7d826ff468a2bdd99139 | rachit-mishra/Hackerrank | /Sets 1 intro.py | 681 | 4.25 | 4 | # Set is an unordered collection of elements without duplicate entries
# when printed, iterated or converted into a sequence, its elements appear in an arbitrary order
# print set()
# print set('HackerRank')
# sets basically used for membership testing and eliminating duplicate entries
array = int(input())
sumlist = ... | true |
a5daff0eccc74862ba2f2cd962971a27f2ec7099 | tinybeauts/LPTHW | /ex15_mac.py | 1,197 | 4.375 | 4 | from sys import argv
script, filename = argv
txt = open(filename)
print "Here's your file %r:" % filename
print txt.read()
print "Type the filename again:"
file_again = raw_input("> ")
txt_again = open(file_again)
print txt_again.read()
# Extra Credit 4
# from sys import argv
#
# script, filename = argv
#
# t... | true |
de7f58a8084ee33e834c6487c65ef0cf13a19913 | Md-Hiccup/Problem-Solving | /HackerRank/Rank/easy/symmetric_difference.py | 2,623 | 4.125 | 4 | """
a new data type: sets.
Concept:
If the inputs are given on one line separated by a space character, use split() to get the separate values in the form of a list:
>> a = raw_input()
5 4 3 2
>> lis = a.split()
>> print (lis)
['5', '4', '3', '2']
If the list values are all integer types, use the map() method to conve... | true |
acfbd6ce55de265ead5aa37b15d13d6ad78c6060 | Md-Hiccup/Problem-Solving | /HackerRank/Rank/easy/any_or_all.py | 719 | 4.125 | 4 | """
any():
This expression returns True if any element of the iterable is true.
If the iterable is empty, it will return False.
all():
This expression returns True if all of the elements of the iterable are true. If the iterable is empty, it will return True.
Prob: Print True if all the conditions of the problem s... | true |
1ef078d6c92399bc43e5737112cf6d41105963de | Md-Hiccup/Problem-Solving | /HackerRank/Rank/easy/collection_namedtuple.py | 924 | 4.4375 | 4 | """
collections.namedtuple()
Basically, namedtuples are easy to create, lightweight object types.
They turn tuples into convenient containers for simple tasks.
With namedtuples, you don’t have to use integer indices for accessing members of a tuple.
Example:
>>> from collections import namedtuple
>>> Point = namedtu... | true |
c2c0745b71a66464daf21d104a2831c38de9d9bb | ErenBtrk/Python-Fundamentals | /Numpy/NumpyStrings/Exercise16.py | 313 | 4.125 | 4 | '''
16. Write a NumPy program to count the lowest index of "P" in a given array, element-wise.
'''
import numpy as np
np_array = np.array(['Python' ,'PHP' ,'JS' ,'examples' ,'html'])
print("\nOriginal Array:")
print(np_array)
print("count the lowest index of ‘P’:")
r = np.char.find(np_array, "P")
print(r) | true |
339a24e71cbd4b32a815332c1ad9426a1d99c335 | ErenBtrk/Python-Fundamentals | /Python Operators/4-ComparisonOperatorsExercises.py | 1,368 | 4.34375 | 4 | #1 - Prompt user to enter two numbers and print larger one
number1 = int(input("Please enter a number : "))
number2 = int(input("Please enter a number : "))
result = number1 > number2
print(f"number1 : {number1} is greater than number2 : {number2} => {result}")
#2 - Prompt user to enter 2 exam notes and calculate avera... | true |
b9d440a9aafd661b1d1ed641cc8921e5e24ebd02 | ErenBtrk/Python-Fundamentals | /Numpy/NumpyLinearAlgebra/Exercise14.py | 256 | 4.1875 | 4 | '''
14. Write a NumPy program to compute the condition number of a given matrix.
'''
import numpy as np
m = np.array([[1,2],[3,4]])
print("Original matrix:")
print(m)
result = np.linalg.cond(m)
print("Condition number of the said matrix:")
print(result) | true |
b99c2578051bef4298f3c7110ac76b9b3c0c9063 | ErenBtrk/Python-Fundamentals | /Numpy/NumpyLinearAlgebra/Exercise10.py | 270 | 4.125 | 4 | '''
10. Write a NumPy program to find a matrix or vector norm.
'''
import numpy as np
v = np.arange(7)
result = np.linalg.norm(v)
print("Vector norm:")
print(result)
m = np.matrix('1, 2; 3, 4')
print(m)
result1 = np.linalg.norm(m)
print("Matrix norm:")
print(result1) | true |
d888cf76ca3c466760c7c6397a7c056aa44f9368 | ErenBtrk/Python-Fundamentals | /Python Conditional Statements/4-IfElseExercises2.py | 2,940 | 4.46875 | 4 | #1- Prompt the user to enter a number and check if its between 0-100
number1 = int(input("Please enter a number : "))
if(number1>0) and (number1<100):
print(f"{number1} is between 0-100")
else:
print(f"{number1} is NOT between 0-100")
#2- Prompt the user to enter a number and check if its positive even number
... | true |
31e0a2c1b41f587b63bb213ebda6c68d96d83d36 | ErenBtrk/Python-Fundamentals | /Pandas/PandasDataSeries/Exercise13.py | 289 | 4.15625 | 4 | '''
13. Write a Pandas program to create a subset of a given series based on value and condition.
'''
import pandas as pd
pd_series = pd.Series([1,2,3,4,5])
print(pd_series)
relationalVar = pd_series > 3
new_series = pd_series[relationalVar]
new_series.index = [0,1]
print(new_series) | true |
66c7b75d33b882e78fc35a61720bd25ded68c7cf | ErenBtrk/Python-Fundamentals | /Numpy/NumpyStatistics/Exercise13.py | 515 | 4.4375 | 4 | '''
13. Write a Python program to count number of occurrences of each value
in a given array of non-negative integers.
Note: bincount() function count number of occurrences of each value
in an array of non-negative integers in the range of the array between
the minimum and maximum values including the values that did ... | true |
2461f2c598528a6a45b35da2708517717532fd3a | ErenBtrk/Python-Fundamentals | /Pandas/PandasDataframe/Exercise53.py | 425 | 4.5 | 4 | '''
53. Write a Pandas program to insert a given column at a specific column index in a DataFrame.
'''
import pandas as pd
d = {'col2': [4, 5, 6, 9, 5], 'col3': [7, 8, 12, 1, 11]}
df = pd.DataFrame(data=d)
print("Original DataFrame")
print(df)
new_col = [1, 2, 3, 4, 7]
# insert the said column at the beginning in ... | true |
789d52f7c4e9b6fd3a91586d188bd06fec4da709 | ErenBtrk/Python-Fundamentals | /Numpy/NumpyRandom/Exercise13.py | 288 | 4.4375 | 4 | '''
13. Write a NumPy program to find the most frequent value in an array.
'''
import numpy as np
x = np.random.randint(0, 10, 40)
print("Original array:")
print(x)
print("Most frequent value in the above array:")
print(np.unique(x))
print(np.bincount(x))
print(np.bincount(x).argmax()) | true |
dcecd4f5f65e24e8bcf2bb130d180b590c3aae74 | ErenBtrk/Python-Fundamentals | /Pandas/PandasDataSeries/Exercise24.py | 311 | 4.25 | 4 | '''
24. Write a Pandas program convert the first and last character
of each word to upper case in each word of a given series.
'''
import pandas as pd
import numpy as np
pd_series = pd.Series(["kevin","lebron","kobe","michael"])
print(pd_series.map(lambda x: x[0].upper() + x[1:-1] + x[-1].upper() ))
| true |
68131c94887ff1da6069d0a22c3a07352769ea24 | ErenBtrk/Python-Fundamentals | /Numpy/NumpyLinearAlgebra/Exercise1.py | 304 | 4.40625 | 4 | '''
1. Write a NumPy program to compute the multiplication of two given matrixes.
'''
import numpy as np
np_matrix1 = np.arange(0,15).reshape(5,3)
print(np_matrix1)
np_matrix2 = (np.ones(9,int)*2).reshape(3,3)
print(np_matrix2)
print(f"Multiplication of matrixes :\n{np.dot(np_matrix1,np_matrix2)}")
| true |
a82bd7fba196142b95745e0fef2c83054557c2cb | ErenBtrk/Python-Fundamentals | /Numpy/NumpySortingAndSearching/Exercise1.py | 407 | 4.5 | 4 | '''
1. Write a NumPy program to sort a given array of shape 2
along the first axis, last axis and on flattened array.
'''
import numpy as np
a = np.array([[10,40],[30,20]])
print("Original array:")
print(a)
print("Sort the array along the first axis:")
print(np.sort(a, axis=0))
print("Sort the array along the last ax... | true |
924527cad45d7f7c910fc4658a0b60b50517dbc3 | anshu9/LeetCodeSolutions | /easy/add_digits.py | 796 | 4.21875 | 4 | """
Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
For example:
Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.
Follow up:
Could you do it without any loop/recursion in O(1) runtime?
"""
def add_digits_... | true |
67334c8d4146f1c8ba8580a5c95039a163e4bec2 | juliancomcast/100DaysPython | /Module1/Day09/day09_indexing.py | 1,121 | 4.5 | 4 | #specific items can be retrieved from a list by using its indicies
quotes = ["Pitter patter, let's get ar 'er", "Hard no!", "H'are ya now?", "Good-n-you", "Not so bad.", "Is that what you appreciates about me?"]
print(quotes[0])
print(f"{quotes[2]}\n\t {quotes[3]}\n {quotes[4]}")
#slicing uses the format [start:stop:s... | true |
4fe297d8354295929f95c9f78e80dd4c90e131d1 | juliancomcast/100DaysPython | /Module1/Day11/day11_augAssign.py | 811 | 4.59375 | 5 | #An augmented assignment improves efficiency because python can iterate a single variable instead of using a temporary one.
#There are several types of augmented assignment operators:
# += : Addition
# -= : Subtraction
# *= : Multiplication
# /= : Division
# //= : Floor Division
# %= : Remainder/Modulus
# **= : Exponen... | true |
dc853f47647cfa8185eeded8b7b4abd458463413 | jpike/PythonProgrammingForKids | /BasicConcepts/Functions/FirstFunction.py | 828 | 4.4375 | 4 | # This is the "definition" of our first function.
# Notice the "def" keyword, the function's name ("PrintGreeting"),
# the parentheses "()", and the colon ":".
def PrintGreeting():
# Here is the body of our function, which contains the block
# or lines of code that will be executed when our function is
# ca... | true |
5a63befb4bb2b1b00552c54b2416ad8c1da0b99e | jpike/PythonProgrammingForKids | /BasicConcepts/SyntaxErrors/Volume1_Chapter3_SyntaxErrors.py | 689 | 4.125 | 4 | # String variable statements with syntax errors.
string variable = 'This line should have a string variable.'
1string_variable_2 = "This line should have another string variable."
another_string_variable = 'This line has another string variable."
yet_another_string_variable = "This line has yet another string variable.... | true |
4cf02d87043e701ed04156a935e710a10f54e7a0 | techacker/Hackerank | /commandlistchallenge.py | 1,279 | 4.21875 | 4 | print('The program performs the given function on a list in a recursive manner.')
print('First enter an "Integer" to tell how many functions you would like to do.')
print('Then enter the command with appropriate values.')
print()
print('Enter an integer.')
N = int(input())
z = []
def operation(inst, item, ind):
if... | true |
68571bcf57eaa90a749cfbeaa39e613e6aeaa7f6 | techacker/Hackerank | /calendarModule.py | 392 | 4.125 | 4 | # Task
# You are given a date. Your task is to find what the day is on that date.
# Input Format
# A single line of input containing the space separated month, day and year, respectively, in MM DD YYYY format.
import calendar
s = input().split()
m = int(s[0])
d = int(s[1])
y = int(s[2])
day = calendar.weekday(y,m,d... | true |
3215b0ada68e50621452d257cac18e767d0239e6 | techacker/Hackerank | /alphabetRangoli.py | 811 | 4.25 | 4 | # You are given an integer, N.
# Your task is to print an alphabet rangoli of size N.
# (Rangoli is a form of Indian folk art based on creation of patterns.)
#
# Example : size 5
#
# --------e--------
# ------e-d-e------
# ----e-d-c-d-e----
# --e-d-c-b-c-d-e--
# e-d-c-b-a-b-c-d-e
# --e-d-c-b-c-d-e--
# ---... | true |
0b0dcbc0b619f5ce51dd55a65a7ede07dfbb5695 | Joeshiett/beginner-python-projects | /classes_example.py | 633 | 4.125 | 4 | class Person: # Instantiate class person as blueprint to create john and esther object
def __init__(self, name, age):
self.name = name
self.age = age
def walking(self): #defining of behaviour inside of class indentation
print(self.name +' ' + 'is walking...')
def speaking(self)... | true |
3f8cd4a99aeffc1420bf4dd4c9af2f1b487914f7 | Jonie23/python-calculator | /calculator.py | 2,095 | 4.375 | 4 | #welcome user
def welcome():
print('''
Welcome to Jones's calculator built with python
''')
welcome()
# calculator()
#define a function to run program many times
def calculator():
#ask what operation user will want to run
operation = input('''
Please type in the calculator operation you will want... | true |
4d7a1ccf22595544dfedd57e7cc2181d18013d5c | milan-crypto/PRACTICE_PYTHON | /Divisors.py | 503 | 4.3125 | 4 | # Create a program that asks the user for a number and then prints out a list of all the divisors of that number.
# (If you don’t know what a divisor is, it is a number that divides evenly into another number.
# For example, 13 is a divisor of 26 because 26 / 13 has no remainder.)
number = int(input("Please choose a n... | true |
68247317c0145405a949c82d10f08dd4d535bd52 | dhirajMaheswari/findPhoneAndEmails | /findPhonesAndEmails.py | 1,853 | 4.4375 | 4 | '''this code makes use of the command line to find emails and/or phones from supplied text file
or text using regular expressions.
'''
import argparse, re
def extractEmailAddressesOrPhones(text, kKhojne = "email"):
''' this function uses the regular expressions to extract emails from the
supplie... | true |
04f9b9e623652aff89ff6261069df137c4e48c25 | ManishVerma16/Data_Structures_Learning | /python/recursion/nested_recursion.py | 226 | 4.125 | 4 | # Recursive program to implement the nested recursion
def nestedFun(n):
if (n>100):
return n-10
else:
return nestedFun(nestedFun(n+11))
number=int(input("Enter any number: "))
print(nestedFun(number)) | true |
88db8f87b369d7626c0f2e0466e60cc73b1d11cc | BrettMcGregor/coderbyte | /time_convert.py | 499 | 4.21875 | 4 | # Challenge
# Using the Python language, have the function TimeConvert(num)
# take the num parameter being passed and return the number of
# hours and minutes the parameter converts to (ie. if num = 63
# then the output should be 1:3). Separate the number of hours
# and minutes with a colon.
# Sample Test Cases
#
# Inp... | true |
6eb3619bec8465aab552c5ad9043447217d81334 | BrettMcGregor/coderbyte | /check_nums.py | 578 | 4.1875 | 4 | # Challenge
# Using the Python language, have the function CheckNums(num1,num2)
# take both parameters being passed and return the string true if num2
# is greater than num1, otherwise return the string false. If the
# parameter values are equal to each other then return the string -1.
# Sample Test Cases
#
# Input:3 &... | true |
1645c0e1b348decce12680b6e3980b659f87c82a | RahulBantode/Pandas_python | /Dataframe/application-14.py | 702 | 4.40625 | 4 | '''
Write a program to delete the dataframe columns by name and index
'''
import pandas as pd
import numpy as np
def main():
data1 = [10,20,30,40]
data2 = ["a","b","c","d"]
data3 = ["jalgaon","pune","mumbai","banglore"]
df = pd.DataFrame({"Int":data1,"Alpha":data2,"city":data3})
print(df)
... | true |
141abe7dfe844acd5ce5f999880197ce266a2865 | ziyadedher/birdynet | /src/game/strategy.py | 2,091 | 4.1875 | 4 | """This module contains strategies used to play the game."""
import random
import pygame
from game import config
class Strategy:
"""Defines an abstract strategy that can be built on."""
def __init__(self) -> None:
"""Initialize this abstract strategy.
Do not initialize an abstract strateg... | true |
dadaab812f4ce7ee2e0a5a95436088f109a0a63d | saadhasanuit/Lab-04 | /question 11.py | 487 | 4.125 | 4 | print("Muhammad Saad Hasan 18B-117-CS Section:-A")
print("LAB-04 -9-NOV-2018")
print("QUESTION-11")
# Program which calculates the vowels from the given string.
print("This program will count total number of vowels from user defined sentence")
string=input("Enter your string:")
vowels=0
for i in string:
if(... | true |
877a89267774f79b7b4516e112c8f73a1ebad162 | MariyaAnsi/Python-Assignments | /Assignment_5.py | 363 | 4.34375 | 4 | #Write a program that prompts for a file name, then opens that file and reads through the file,
#and print the contents of the file in upper case.
fname = input("Enter file name: ")
fh = open(fname)
print("fh___", fh)
book = fh.read()
print("book___", book)
bookCAPITAL = book.upper()
bookCAPITALrstrip = boo... | true |
e23db0c2b2df63611d1066b76cf1606fd40852ba | TewariUtkarsh/Python-Programming | /Tuple.py | 553 | 4.1875 | 4 | myCars = ("Toyota","Mercedes","BMW","Audi","BMW") #Tuple declared
print("\nTuple: ",myCars)
# Tuple has only 2 built in functions:
# 1.count()- To count the number of Element ,that is passed as the Parameter, in the Tuple
print("\nNumber of times BMW is present in the Tuple: ",myCars.count("BMW"))
print("Number... | true |
6717306792716cbc062e400eeb7c6d434f28544a | gorkememir/PythonProjects | /Basics/pigTranslator.py | 1,160 | 4.21875 | 4 | # Take a sentence from user
original = input("Please enter a sentence: ").strip().lower()
# Split it into words
splitted = original.split()
# Define a new list for storing the final sentence
new_words = []
# Start a for loop to scan all the splitted words one by one
for currentWord in splitted:
# If the first l... | true |
a23034a6ada538ad5c35ec45b514900a68183d1f | GospodinJovan/raipython | /Triangle.py | 1,234 | 4.5625 | 5 | """""
You are given the lengths for each side on a triangle. You need to find all three angles for this triangle. If the given side lengths cannot form a triangle
(or form a degenerated triangle), then you must return all angles as 0 (zero). The angles should be represented as a list of integers in ascending order.
Eac... | true |
6681c74eed15a86ce699efb6e28cbf1e98630cfb | bipuldev/US_Bike_Share_Data_Analysis | /Bike_Share_Analysis_Q4a.py | 2,117 | 4.4375 | 4 | ## import all necessary packages and functions.
import csv # read and write csv files
from datetime import datetime # operations to parse dates
from pprint import pprint # use to print data structures like dictionaries in
# a nicer way than the base print function.
def number_of_trips(fil... | true |
006d4318ecc5f77efd912464de98ef2cf852dd42 | NataliaBeckstead/cs-module-project-recursive-sorting | /src/searching/searching.py | 1,278 | 4.40625 | 4 | # TO-DO: Implement a recursive implementation of binary search
def binary_search(arr, target, start, end):
if start > end:
return -1
mid = (start + end) // 2
if arr[mid] == target:
return mid
elif target < arr[mid]:
return binary_search(arr, target, start, mid-1)
else:
... | true |
70dcd1ee1a606f67646d7e8f7f3862908e3a0c76 | JannickStaes/LearningPython | /TablePrinter.py | 1,061 | 4.21875 | 4 | #! python3
# prints a table of a list of string lists
tableDataExample = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]
def determineMaxColumnWidths(tableData):
columnWidths = [] #a list to store the max length of ea... | true |
af175e0913b72d5c984cd90490f8405d8843d258 | Hubert51/pyLemma | /Database_sqlite/SecondPart_create class/Test_simplify_function/class2.py | 1,440 | 4.125 | 4 | import sqlite3
class DatabaseIO:
l12 = [1, 2, 3]
d_table = {}
def __init__(self, name):
"""
In my opinion, this is an initial part. If I have to use variable from
other class, I can call in this part and then call to the following
part.
Some variable must be renamed... | true |
5a2dd5cb914cdbd397847ab8d77521e0612580e0 | shubhranshushivam/DSPLab_22-10-2020 | /ques8.py | 605 | 4.1875 | 4 | # 8. Find the Union and Intersection of the two sorted arrays
def union(arr1,arr2):
res=arr1+arr2
res=set(res)
return list(res)
def intersection(arr1, arr2):
res=[]
for i in arr1:
if i in arr2:
res.append(i)
return res
n1=int(input("Enter size of 1st array="... | true |
fd8b7a3eb61438223ca6563de920c9e7f8eab7a4 | jadenpadua/Data-Structures-and-Algorithms | /efficient/validParenthesis/validParenthesis.py | 1,772 | 4.125 | 4 | #Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
#imports functions from our stack data structure file
from stack import Stack
#helper method checks if our open one and closed are the same
def is_match(p1, p2):
if p1 == "(" and p2 == ")":
... | true |
3b98b69d8a5182fca01f3ceea90444eff427a5a6 | jadenpadua/Data-Structures-and-Algorithms | /bruteforce/largest_swap.py | 370 | 4.21875 | 4 | Write a function that takes a two-digit number and determines if it's the largest of two possible digit swaps.
To illustrate:
largest_swap(27) ➞ False
largest_swap(43) ➞ True
def largest_swap(num):
original = num
d = 0
rev = 0
while num > 0:
d = num % 10
num = int(num/10)
rev = rev*10 + d
if rev > origin... | true |
d6404fac5d7e72741972ade1038e83de849ac709 | jadenpadua/Data-Structures-and-Algorithms | /bruteforce/needleInHaystack.py | 564 | 4.25 | 4 | # Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
def strStr(haystack,needle):
for i in range(len(haystack) - len(needle) + 1):
if haystack[i:i+len(needle)] == needle:
return i
return - 1
haystack = "Will you be able to find the ne... | true |
3702a2e59ec372033ed9f0f3cb2aa2af7bc4653b | jadenpadua/Data-Structures-and-Algorithms | /bruteforce/alternating_one_zero.py | 626 | 4.46875 | 4 | Write a function that returns True if the binary string can be rearranged to form a string of alternating 0s and 1s.
Examples
can_alternate("0001111") ➞ True
# Can make: "1010101"
can_alternate("01001") ➞ True
# Can make: "01010"
can_alternate("010001") ➞ False
can_alternate("1111") ➞ False
def can_alternate(s):
... | true |
0ccbe214b5bc91d4c53e4f16218b0835b1b9d513 | jadenpadua/Data-Structures-and-Algorithms | /bruteforce/digits_in_list.py | 689 | 4.3125 | 4 | #Create a function that filters out a list to include numbers who only have a certain number of digits.
#Examples
#filter_digit_length([88, 232, 4, 9721, 555], 3) ➞ [232, 555]
# Include only numbers with 3 digits.
#filter_digit_length([2, 7, 8, 9, 1012], 1) ➞ [2, 7, 8, 9]
# Include only numbers with 1 digit.
#filter... | true |
67c62395c49f7327da7f66d2ab1d04b96886b53a | UnicodeSnowman/programming-practice | /simulate_5_sided_die/main.py | 565 | 4.1875 | 4 | # https://www.interviewcake.com/question/simulate-5-sided-die?utm_source=weekly_email
# You have a function rand7() that generates a random integer from 1 to 7.
# Use it to write a function rand5() that generates a random integer from 1 to 5.
# rand7() returns each integer with equal probability. rand5() must also ret... | true |
7443a894f9ca0f6e6276d36e49a12f27dbd76b80 | JITHINPAUL01/Python-Assignments | /Day_5_Assignment.py | 1,654 | 4.25 | 4 | """
Make a generator to perform the same functionality of the iterator
"""
def infinite_sequence(): # to use for printing numbers infinitely
num = 0
while True:
yield num
num += 1
for i in infinite_sequence():
print(i, end=" ")
"""
Try overwriting some default dunder methods and manipu... | true |
36a3aa0df6425f0876442c374eca48c0c709d592 | shahasifbashir/LearnPython | /ListOver/ListOverlap.py | 591 | 4.28125 | 4 | import random
#This Examples gives the union of two Lists
A = [1,2,3,4,5,6,7,8,5,4,3,3,6,7,8]
B=[6,7,8,9,4,3,5,6,78,97,2,3,4,5,5,6,7,7,8]
# we will use the set becouse a set contains unique elemets only ann then use an and operator
print(list(set(A)&set(B)))
# The same example using Random Lists
A= range(1,random.r... | true |
57992d8e576a9c5df264083e74d67b6d29ae00c9 | susanbruce707/Virtual-Rabbit-Farm | /csv_mod.py | 1,205 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Feb 13 00:27:26 2020
@author: susan
Module to read CSV file into nested dictionary and
write nested dictionar to CSV file
rd_csv requires 1 argument file, as file name for reading
wrt_csv requires 2 arguments file name and dictionary name to write CSV file.
"""
imp... | true |
29e7fdf995e4f6245899f4a61aac03ac1cac6426 | fadhilmulyono/cp1404practicals | /prac_09/sort_files_1.py | 910 | 4.25 | 4 | """
CP1404/CP5632 Practical
Sort Files 1.0
"""
import os
def main():
"""Sort files to folders based on extension"""
# Specify directory
os.chdir('FilesToSort')
for filenames in os.listdir('.'):
# Check if there are any files in directory
if os.path.isdir(filenames):
conti... | true |
6e6569c90097c6ae65b39aa6736e234fbf6f4bdf | BruderOrun/PY111-april | /Tasks/a0_my_stack.py | 798 | 4.1875 | 4 | """
My little Stack
"""
stak = []
def push(elem) -> None:
"""
Operation that add element to stack
:param elem: element to be pushed
:return: Nothing
"""
stak.append(elem)
def pop():
"""
Pop element from the top of the stack
:return: popped element
"""
if stak == []:
... | true |
7f72b1120e1a02c17ccc9113866e32cab1164830 | tjgiannhs/Milisteros | /GreekBot/greek_preprocessors.py | 1,609 | 4.15625 | 4 | """
Statement pre-processors.
"""
def seperate_sentences(statement):
'''
Adds a space after commas and dots to seperate sentences
If this results in more than one spaces after them another pre-processor will clean them up later
:param statement: the input statement, has values such as text
... | true |
24409c8cc7b6c497409449e8327e5f16a2162020 | qufeichen/Python | /asciiUni.py | 352 | 4.15625 | 4 | # program that prints out a table with integers from decimal 0 to 255, it's hex number, and the character corresponding to the unicode with UTF-8 encoding
# using a loop
for x in range(0, 256):
print('{0:d} {0:#04x} {0:c}'.format(x))
# using list comprehension
ll = [('{0:d} {0:#04x} {0:c}'.format(x)) for x in range(... | true |
f2a34668c27bc15c17545666e077ad857937c554 | PravinSelva5/LeetCode_Grind | /Dynamic Programming/BestTimetoBuyandSellaStock.py | 1,006 | 4.125 | 4 | '''
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.
Note that you cannot sell a stock before you buy one.
-------
RES... | true |
e238362a9fe70015b725ea93b7d4ea60663dfcab | PravinSelva5/LeetCode_Grind | /RemoveVowelsFromAString.py | 1,081 | 4.21875 | 4 | '''
Given a string S, remove the vowels 'a', 'e', 'i', 'o', and 'u' from it, and return the new string.
Example 1:
Input: "leetcodeisacommunityforcoders"
Output: "ltcdscmmntyfrcdrs"
Example 2:
Input: "aeiou"
Output: ""
Runtime: 28 ms, faster than 75.93% of Python3 online submissions for Remove Vowels from a Stri... | true |
1f5c2a31e43d65a1bb470666f432c53b1e0bd8c9 | PravinSelva5/LeetCode_Grind | /SlidingWindowTechnique.py | 1,204 | 4.125 | 4 | # It is an optimization technique.
# Given an array of integers of size N, find maximum sum of K consecutive elements
'''
USEFUL FOR:
- Things we iterate over sequentially
- Look for words such as contiguous, fixed sized
- Strings, arrays, linked-lists
- Minimum, maximum, longest, shortest, co... | true |
41fa5b705be4a2f44f143a811186796fa94f9e01 | PravinSelva5/LeetCode_Grind | /Trees and Graphs/symmetricTree.py | 1,008 | 4.28125 | 4 | '''
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
-------------------
Results
-------------------
Time Complexity: O(N)
Space Complexity: O(N)
Runtime: 28 ms, faster than 93.85% of Python3 online submissions for Symmetric Tree.
Memory Usage: 14.4 MB, less than 52.06% ... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.