blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
983b106ab6e4e093ee330866707bd6e35b7df3da | barvaliyavishal/DataStructure | /Cracking the Coding Interview Exercises/Linked Lists/SinglyLinkedList/removeDuplicates.py | 766 | 4.25 | 4 | from LinkedList import LinkedList
class RemoveDuplicates:
# Remove duplicates Using O(n^2)
def removeDuplicates(self, head):
if head.data is None:
return
temp = head
while temp.next:
start = temp
while start.next:
if start.next.data ... | true |
923aafcb9147d70e62d8512fabb477b5a8365a5e | garciaha/DE_daily_challenges | /2020-08-13/eadibitan.py | 1,788 | 4.15625 | 4 | """Eadibitan
You're creating a conlang called Eadibitan. But you're too lazy to come up with your own phonology,
grammar and orthography. So you've decided to automatize the proccess.
Write a function that translates an English word into Eadibitan.
English syllables should be analysed according to the following rule... | true |
85051a8cef826a0fb73dfc66172c8f588dc3433f | garciaha/DE_daily_challenges | /2020-07-09/maximize.py | 1,015 | 4.1875 | 4 | """ Maximize
Write a function that makes the first number as large as possible by swapping out its digits for digits in the second number.
To illustrate:
max_possible(9328, 456) -> 9658
# 9658 is the largest possible number built from swaps from 456.
# 3 replaced with 6 and 2 replaced with 5.
Each digit in the secon... | true |
081fa71ed4ff5ac6c1e5402c48cbb46429f5e46f | garciaha/DE_daily_challenges | /2020-08-20/summer_olympics.py | 1,058 | 4.21875 | 4 | """Summer Olympics
Analyse statistics of Olympic Games in the summer CSV file.
Create a function that returns
1. Find out the (male and female) athlete who won most medals in all the
Summer Olympic Games (1896-2014).
2. Return the first 10 countries that won most medals:
Bonus:
Use pandas to create a datafr... | false |
736a16c6c9f13efd689a4449c5bdaef22d1d96fc | garciaha/DE_daily_challenges | /2020-08-03/unravel.py | 641 | 4.4375 | 4 | """Unravel all the Possibilities
Write a function that takes in a string and returns all possible combinations. Return the final result in alphabetical order.
Examples
unravel("a[b|c]") -> ["ab", "ac"]
Notes
Think of each element in every block (e.g. [a|b|c]) as a fork in the road.
"""
def unravel(string):
pas... | true |
8cd9783dc602893f32c52a2c4c2e21952662def3 | garciaha/DE_daily_challenges | /2020-07-22/connect.py | 1,742 | 4.28125 | 4 | """Connecting Words
Write a function that connects each previous word to the next word by the shared
letters. Return the resulting string (removing duplicate characters in the overlap)
and the minimum number of shared letters across all pairs of strings.
Examples
connect(["oven", "envier", "erase", "serious"]) -> ["... | true |
79b243b7c8dc4a887e111dac8b620adb5db55420 | garciaha/DE_daily_challenges | /2020-09-09/all_explode.py | 1,679 | 4.21875 | 4 | """Chain Reaction (Part 1)
In this challenge you will be given a rectangular list representing a "map" with
three types of spaces:
- "+" bombs: When activated, their explosion activates any bombs directly above,
below, left, or right of the "+" bomb.
- "x" bombs: When activated, their explosion activates any bombs p... | true |
56ae86a640e1ffef13d7f04792943bfd696a6b9d | Yossarian0916/AlogrithmsSpecialization | /insertion_sort.py | 380 | 4.15625 | 4 | # insertion sort
def insertion_sort(array):
for i in range(1, len(array)):
# insert key into sorted subarray
card = array[i]
j = i-1
while j >= 0 and array[j] > card:
array[j+1] = array[j]
j = j-1
array[j+1] = card
if __name__ == '__main__':
lst ... | false |
a0042c5e43f8b7608b580d7e0fa70876a50a9da4 | tahe-ba/Programmation-Python | /serie/serie 3 liste/code/exemple.py | 225 | 4.21875 | 4 | # creating an empty list
lst = []
# number of elemetns as input
n = int(input("Enter number of elements : "))
for i in range(n):
ele = int(input("element n° "+str(i+1)+": "))
lst.append(ele)
print (lst)
| false |
891b21382cc0cd84bb66d14ef296e4f70a230ccc | tahe-ba/Programmation-Python | /serie/serie 3 liste/code/ex9.py | 369 | 4.21875 | 4 | '''
program to find the list of words that are longer than n
from a givenlist of words.
'''
li = []
li = [item for item in input("Enter the words seperated by space: ").split()]
msg=input("text= ")
txt=msg.split(" ")
print (txt)
print (li)
n=int(input("longueur de mot "))
lw = []
for i in range(len(li)):
if len... | false |
31de87045288069ce8dc80acd46cda2ff4d86dd8 | tahe-ba/Programmation-Python | /serie/serie 1 I-O/code/second.py | 629 | 4.15625 | 4 | # Find how many numbers are even and how many are odd in a sequenece of inputs without arrays
while True :
try :
n=int(input("combien d'entier vous aller entrer: "))
break
except ValueError:
print("Wrong input")
j=z=0
for i in range(n):
while True :
try :
... | false |
381007913bcd073e5a1aa745b00ea030fe371b84 | sandeepvura/Mathematical-Operators | /main.py | 538 | 4.25 | 4 | print(int(3 * 3 + 3 / 3 - 3))
# b = print(int(a))
**Mathematical Operators**
```
###Adding two numbers
2 + 2
### Multiplication
3 * 2
### Subtraction
4 - 2
### Division
6 / 3
### Exponential
When you want to raise a number
2 ** 2 = 4
2 ** 3 = 8
```
***Note:*** Order of Mathematical operators to execute... | true |
44c3662bac6085bd63fcb52a666c2e81e5a683ff | farhadkpx/Python_Codes_Short | /list.py | 1,689 | 4.15625 | 4 |
#list
# mutable, multiple data type, un-ordered
lis = [1,2,3,4,5,6,7,8,9] #nos
lis2 = ['atul','manju','rochan'] #strings
lis3 = [1,'This',2,'me','there'] #both
#create empty list
lis4 = [] #empty
lis5 = list() #empty
#traversl
for item in lis:
print (item),
#slicing
print (lis[:],lis[2:3],lis[3:])
#Mutable
l... | true |
28ec5060a74ff5c0e0f62742317d22266a5f41a2 | sadieBoBadie/feb-python-2021 | /Week1/Day2/OOP/intro_OOP.py | 2,111 | 4.46875 | 4 | #1.
# OOP:
# Object Oriented Programming
# Style of programming uses a blueprint for modeling data
# Blueprint defined by the programmer -- DIY datatypes
# -- customize it for your situation
# Modularizing
# 2:
# What is CLASS:
# User/Programmer defined data-type
# Like a function is a reci... | true |
36c9bac791ef0ee4aba78e32851a4fcb6756fafb | Lawlietgit/Python_reviews | /review.py | 2,202 | 4.15625 | 4 | # 4 basic python data types:
# string, boolean, int, float
# str(), bool(), int(), float()
# bool("False") --> True
# bool("") --> False
# bool(10.2351236) --> True
# bool(0.0) --> False
# bool(object/[1,2,3]) --> True
# bool([]) --> False
# bool(None) --> False
# FIFO --> queue dat... | true |
4fd15d3e74cb6ea719d26bf9f30704f5f7c7de7b | mfcust/sorting | /sorting.py | 2,274 | 4.53125 | 5 | # 1) Run the code in the markdown and write a comment about what happens.
# 2) Try to print(sorted(my_list2)) and print(my_list2.sort()). Is there a difference? What do you observe?
my_list2 = [1,4,10,9,8,300,20,21,21,46,52]
# 3) Let's say you wanted to sort your list but in reverse order. To do this, you ... | true |
5b9dff75a516f758e8e8aef83cf89794176b488b | Mukilavan/LinkedList | /prblm.py | 880 | 4.21875 | 4 | #Write a Python program to find the size of a singly linked list.
class Node:
def __init__(self, data, next=None):
self.data = data
self.next = next
class linkedList:
def __init__(self):
self.head = None
def insert_beg(self, data):
node = Node(data, self.head)
... | true |
6da93542a02ae983ed180784310ea3eeaa2985dc | Paradox-1337/less3 | /les3_4.py | 1,344 | 4.21875 | 4 | # Решение1
# x = int(input("Введите чило для возведения в степень: "))
# y = int(input("Введите отрицательное чило, для возведения числа X в эту степень: "))
# if y <= 0:
# x_y = x**y
# print(x_y)
# else:
# print("Введите отрицательное число! ")
# Решение 2
# def my_func():
# x = float((... | false |
f10be4d04fea97886db620447999632fc3c706da | Nishinomiya0foa/Old-Boys | /1_base_OO_net/day24_3features/4_multi_Inheritance.py | 1,402 | 4.53125 | 5 | """多继承
平时尽量不用! 应使用单继承
"""
# class A:
# def func(self):
# print('A')
#
# class B:
# def func(self):
# print('B')
#
# class C:
# def func(self):
# print('C')
#
# class D(A, B, C):
# pass
# # def func(self):
# # print('D')
#
# d = D()
# d.func() # 如果D()中有 func方法,则调用其... | false |
50042e3c7051ee2be4a19e9d4f858a22a7be88f7 | clarkjoypesco/pythoncapitalname | /capitalname.py | 332 | 4.25 | 4 | # Write Python code that prints out Clark Joy (with a capital C and J),
# given the definition of z below.
z = 'xclarkjoy'
name1 = z[1:6]
name1 = name1.upper()
name1 = name1.title()
name2 = z[-3:]
name2 = name2.upper()
name2 = name2.title()
print name1 + ' ' + name2
s = "any string"
print s[:3] + s[3:]
print s... | true |
ee8a14b46db017786571c81da934f06a614b3553 | Jamsheeda-K/J3L | /notebooks/lutz/supermarket_start.py | 1,724 | 4.3125 | 4 | """
Start with this to implement the supermarket simulator.
"""
import numpy as np
import pandas as pd
class Customer:
'''a single customer that can move from one state to another'''
def __init__(self, id, initial_state):
self.id = id
self.state = initial_state
def __repr__(self):
... | true |
7c61f608b0278498c5bac3c8c2833d827754f124 | lynnxlmiao/Coursera | /Python for Everybody/Using Database with Python/Assignments/Counting Organizations/emaildb.py | 2,686 | 4.5 | 4 | """PROBLEM DESCRIPTION:
COUNTING ORGANIZATIONS
This application will read the mailbox data (mbox.txt) count up the number email
messages per organization (i.e. domain name of the email address) using a database
with the following schema to maintain the counts:
CREATE TABLE Counts (org TEXT, count INTEGER)
When you have... | true |
9415684dc35e4d73694ef14abe732a7ba32bf301 | lenatester100/AlvinAileyDancers | /Helloworld.py | 806 | 4.1875 | 4 | print ("Hello_World")
print ("I am sleepy")
'''
Go to sleep
print ("sleep")
Test1=float(input("Please Input the score for Test 1..."))
Test2=float(input("Please Input the score for Test 2..."))
Test3=float(input("Please Input the score for Test 3..."))
average=(Test1+Test2+Test3)/3
print ("The Average of... | true |
b719b552170b8128a75a5121ac7578aa51a3e691 | Krishan27/assignment | /Task1.py | 1,466 | 4.375 | 4 | # 1. Create three variables in a single a line and assign different
# values to them and make sure their data types are different. Like one is
# int, another one is float and the last one is a string.
a=10
b=10.14
c="Krishan"
print(type(a))
print(type(b))
print(type(c))
# 2. Create a variable of value type comple... | true |
953ed2c94e19a170fbe076f10339ff79ccda32f7 | chaithanyabanu/python_prog | /holiday.py | 460 | 4.21875 | 4 | from datetime import date
from datetime import datetime
def holiday(day):
if day%6==0 or day%5==0:
print("hii this is weekend you can enjoy holiday")
else:
print("come to the office immediately")
date_to_check_holiday=input("enter the date required to check")
day=int(input("enter the day"))
month=int(input("en... | true |
91572a07bf2cbe5716b5328c0d4afc34c5f375f8 | prince5609/Coding_Bat_problems | /make_bricks.py | 1,151 | 4.5 | 4 | """ QUESTION =
We want to make a row of bricks that is goal inches long. We have a number of small bricks (1 inch each)
and big bricks (5 inches each). Return True if it is possible to make the goal by choosing from the given bricks.
make_bricks(3, 1, 8) → True
make_bricks(3, 1, 9) → False
make_bricks(3, 2, 10) → True... | true |
022d1d89d419686f2ecf256f9e9a67aff141f13b | he44/Practice | /leetcode/35.py | 822 | 4.125 | 4 | """
35. Search Insert Position
Given a sorted array and a target value, return the index if the target is found.
If not, return the index where it would be if it were inserted in order.
"""
class Solution:
def searchInsert(self, nums, target) -> int:
size = len(nums)
# no element / smaller than f... | true |
158ebdaca82112ce33600ba4f14c92b2c628a2b8 | Anjalics0024/GitLearnfile | /ListQuestion/OopsConcept/OopsQ10.py | 880 | 4.3125 | 4 | #Method Overloading :1. Compile time polymorphisam 2.Same method name but different argument 3.No need of more than one class
#method(a,b)
#method(a,b,c)
class student:
def __init__(self,m1,m2):
self.m1 = m1
self.m2 = m2
def add(self,a= None, b=None, c=None):
s = a+b+c
return... | true |
0cc3fb7a602f1723486a9e3f4f4394e7b4b89f90 | zhuxiuwei/LearnPythonTheHardWay | /ex33.py | 572 | 4.3125 | 4 | def addNum(max, step):
i = 0
numbers = []
while(i < max):
print "At the top i is %d" % i
numbers.append(i)
i += step
print "Numbers now: ", numbers
print "At the bottom i is %d" % i
return numbers
numbers = addNum(10, 2)
print "The numbers: ", numbers
for num in numbers:
print num
# below is add point... | true |
230f959d35d8e8f8e3d7fa98045d73896691f7dc | Pankaj-GoSu/Python-Data-Structure-Exercises | /450 Questions Of Data Structure/Qu3 Array.py | 713 | 4.125 | 4 | #====== Find the kth max and min elelment of an array =========
'''
Input -->
N = 6
arr[] = 7 10 4 3 20 15
k = 3
output : 7
Explanation:
3rd smallest element in the given array is 7
'''
# kth smallest element
list = [7,10,4,3,20,15]
k = 3
asceding_list =[]
def kth_min_element(list):
i = list[0]
if len(list... | false |
0249f8cb4fce6702f631c51de53449e0e80b5fde | sidhanshu2003/LetsUpgrade-Python-Batch7 | /Python Batch 7 Day 3 Assignment 1.py | 700 | 4.3125 | 4 | # You all are pilots, you have to land a plane, the altitude required for landing a plane is 1000ft,
#if less than that tell pilot to land the plane, or it is more than that but less than 5000 ft ask pilot to
# come down to 1000ft else if it is more than 5000ft ask pilot to go around and try later!
Altitude = inpu... | true |
1c5d80a5243fb8636f82ca76f0cb1945d25627ec | ash8454/python-review | /exception-handling-class20.py | 1,414 | 4.375 | 4 | ###Exception handling
"""
The try block lets you test a block of code for errors.
The except block lets you handle the error.
The finally block lets you execute code, regardless of the result of the
try- and except blocks.
"""
try:
print(x)
except NameError:
print("Variable x is not defined")
except:
p... | true |
7e8cf8455bbc07fbe9e46c10a6f26dd188d599bc | ash8454/python-review | /if-else-class8.py | 1,168 | 4.1875 | 4 | #if else
a = 3
b = 200
if b > a:
print('b is greater than a')
#if-elif-else
a = 36
b = 33
if b > a:
print('b is greater than a')
elif b == a:
print('b and a are equal')
else:
print('a is greater than b')
#short hand if else
c = 30
d = 21
if c > d: print('a is greater than b')
#short hand if elif
e ... | false |
0f26b50662decd207ceaf2ce4367b138a9644ee7 | saad-ahmed/Udacity-CS-101--Building-a-Search-Engine | /hw_2_6-find_last.py | 617 | 4.3125 | 4 | # Define a procedure, find_last, that takes as input
# two strings, a search string and a target string,
# and outputs the last position in the search string
# where the target string appears, or -1 if there
# are no occurences.
#
# Example: find_last('aaaa', 'a') returns 3
# Make sure your procedure has a return stat... | true |
cdb7b7ba096285c5c6e732820544bd43c2e36a2b | varunkamboj11/python_project | /wheel.py | 1,255 | 4.125 | 4 | #create the account
#print("1>:signup")
#print("2>:create the acoount")
a=int(input("1>: Create the account \n 2>: Signup "))
if(a==1):
b=input("Firstname: ")
print("Avoid using coomon words and include a mix of letters and numbers ")
c=input("Lastname: ")
print("PASSWORD MUST CONTAIN 1 NUMERIC 1 CHARAC... | false |
d7a51f2eabba8da6c74a184e518dacf683a0651a | Gioia31/tuttainfo | /es25p293.py | 1,684 | 4.1875 | 4 | '''
Crea la classe Triangolo, la classe derivata TriangoloIsoscele e, da quest'ultima, la classe derivata TriangoloEquilatero.
'''
class Triangolo():
def __init__(self, lato1, lato2, lato3):
self.lato1 = lato1
self.lato2 = lato2
self.lato3 = lato3
def info_scaleno(self):
... | false |
98cfbcf9b135a4851035453a1182acfbb389545f | samicd/coding-challenges | /duplicate_encode.py | 738 | 4.1875 | 4 | """
The goal of this exercise is to convert a string to a new string
where each character in the new string is "(" if that character appears only once in the original string,
or ")" if that character appears more than once in the original string.
Ignore capitalization when determining if a character is a duplicate.
... | true |
f52079869f41ba7c7ac004521b99586c6b235dad | Ritella/ProjectEuler | /Euler030.py | 955 | 4.125 | 4 | # Surprisingly there are only three numbers that can be
# written as the sum of fourth powers of their digits:
# 1634 = 1^4 + 6^4 + 3^4 + 4^4
# 8208 = 8^4 + 2^4 + 0^4 + 8^4
# 9474 = 9^4 + 4^4 + 7^4 + 4^4
# As 1 = 1^4 is not a sum it is not included.
# The sum of these numbers is 1634 + 8208 + 9474 = 19316.
# Find th... | true |
83571a887f9f89107aa9d621c0c2ebcac139fd2e | Ritella/ProjectEuler | /Euler019.py | 1,836 | 4.15625 | 4 | # 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, twenty-nine.
# A l... | true |
146af7c28e0698203d3a45ff3e9494f44d17f13f | Unclerojelio/python_playground | /drawcircle.py | 479 | 4.1875 | 4 | """
drawcircle.py
A python program that draws a circle
From the book, "Python Playground"
Author: Mahesh Venkitachalam
Website: electronut.in
Modified by: Roger Banks (roger_banks@mac.com)
"""
import math
import turtle
# draw the circle using turtle
def drawCircleTurtle(x, y, r):
turtle.up()
turtle.setpos(x + r, y)... | false |
b284b148982d4c0607e0e0c15ac07641aea81011 | ho-kyle/python_portfolio | /081.py | 229 | 4.21875 | 4 | def hypotenuse():
a, b = eval(input('Please enter the lengths of the two shorter sides \
of a right triangle: '))
square_c = a**2 + b**2
c = square_c**0.5
print(f'The length of hypotenuse: {c}')
hypotenuse() | true |
9aa293a22aa5a13515746f2b669bf095b21cb84e | sreekanthramisetty/Python | /Scope.py | 1,198 | 4.25 | 4 | # s = 10
# def f():
# print(s)
#
# print(s)
# f()
# print(s)
# # # # # # # # # # # # # # # # # # # # #
# s = 20
# def f():
# s = 30
# print(s)
# print(s)
# f()
# print(s)
# # # # # # # # # # # # # # # # # # # # #
# We cannot print global variable directly inside the functions if we are assigning a va... | false |
817a57ad576fcc602e6de0a8daa1a0811f5a6657 | chilperic/Python-session-coding | /mutiple.py | 868 | 4.28125 | 4 | #!/usr/bin/env python
#This function is using for find the common multiple of two numbers within a certain range
def multiple(x,y,m,t): #x is the lower bound the range and y higher bound
from sys import argv
x, y, m, t= input("Enter the the lower bound of your range: "), input("Enter the the higher bound of your r... | true |
228e5e3c7ca9ae56d0b6e0874f592c58cbaadc24 | TeknikhogskolanGothenburg/PGBPYH21_Programmering | /sep9/textadventure/game.py | 2,467 | 4.3125 | 4 | from map import the_map
from terminal_color import color_print
def go(row, col, direction):
if direction in the_map[row][col]['exits']:
if direction == "north":
row -= 1
elif direction == "south":
row += 1
elif direction == "east":
col += 1
elif ... | true |
db64c4552a3eef0658031283a760edc8cf20b3c0 | mprzybylak/python2-minefield | /python/getting-started/functions.py | 1,568 | 4.65625 | 5 | # simple no arg function
def simple_function():
print 'Hello, function!'
simple_function()
# simple function with argument
def fib(n):
a, b = 0, 1
while a < n:
print a,
a, b = b, a+b
fib(10)
print ''
# example of using documentation string (so-called docstring)
def other_function():
"""Simple gibbrish print... | true |
336522ccc3314a8dc4e7e3d0b361a2538152ed46 | mprzybylak/python2-minefield | /python/getting-started/for.py | 1,128 | 4.40625 | 4 |
# Regular for notation acts as an interator
words = ['first', 'second', 'third']
print 'Regular loop over list: ' + str(words)
for w in words:
print w
# If we want to modify list inside for - it is best to create copy of list
list_to_modify = ['1', '22', '333']
print 'example of modifiaction list in loop: ' + str(li... | false |
457c259a8515b806833cf54ccd0c79f8069f874c | surenderpal/Durga | /Regular Expression/quantifiers.py | 481 | 4.125 | 4 | import re
matcher=re.finditer('a$','abaabaaab')
for m in matcher:
print(m.start(),'...',m.group())
# Quantifiers
# The number of occurrences
# a--> exactly one 'a'
# a+-> atleast one 'a'
# a*-> any number of a's including zero number also
# a?-> atmost one a
# either one a or zero number of a's
# a{num}-> Ex... | true |
2c53a0967ba066ca381cc67d277a4ddcd9b3c4e7 | adreena/DataStructures | /Arrays/MaximumSubarray.py | 358 | 4.125 | 4 | '''
Given an integer array nums, find the contiguous subarray (containing at least one number)
which has the largest sum and return its sum.
'''
def maxSubarray(nums):
max_sum = float('-inf')
current_sum = nums[0]
for num in nums[1:]:
current_sum = max(current_sum+num, num)
max_sum = max(max... | true |
cf2b6794d3d6dbe17d5ee7d88cabecae3b9894d2 | xuyuntao/python-code | /2/def.py | 1,049 | 4.125 | 4 | print("来学习函数吧")
def MySun(*args):
sum = 0
for i in args:
sum += i
return sum
print(MySun(1,2,3,4,5,6))
def func(**args):
print(args)
print(type(args))
func(x=1, y=2, z=3)
"""
lambada的主体是有一个表达式,而不是代码块,仅仅只能在lambda中
封装简单逻辑
lambada的函数有自己的命名空间
"""
sum = lambda num1, num2: num1 + num2
print(s... | false |
f5b7673a8c092aa49bec8f2d464f01acb67c6d80 | xuyuntao/python-code | /2/turtle_test.py | 496 | 4.125 | 4 | """
一个简单绘图工具
提供一个小海龟,可以把它理解为一个机器人,只能听懂有限的命令
其他命令
done()保持程序不结束
"""
import turtle
turtle.speed(10)
turtle.forward(100)
turtle.right(45)
turtle.forward(100)
turtle.left(45)
turtle.forward(100)
turtle.goto(0,0)
turtle.up()
turtle.goto(-100,100)
turtle.down()
turtle.pensize(5)
turtle.pencolor("red")
turtle.goto(100,-100... | false |
855817e03fa062cb755c166042bdb16037aefe5c | IEEE-WIE-VIT/Awesome-DSA | /python/Algorithms/quicksort.py | 898 | 4.28125 | 4 |
# Function that swaps places for to indexes (x, y) of the given array (arr)
def swap(arr, x, y):
tmp = arr[x]
arr[x] = arr[y]
arr[y] = tmp
return arr
def partition(arr, first, last):
pivot = arr[last]
index = first
i = first
while i < last:
if arr[i] <= pivot: # Swap if curr... | true |
5d81d3e6f16f4fc1d5c9fcc5ed452becefa95935 | IEEE-WIE-VIT/Awesome-DSA | /python/Algorithms/Queue/reverse_k_queue.py | 1,231 | 4.46875 | 4 | # Python3 program to reverse first k
# elements of a queue.
from queue import Queue
# Function to reverse the first K
# elements of the Queue
def reverseQueueFirstKElements(k, Queue):
if (Queue.empty() == True or
k > Queue.qsize()):
return
if (k <= 0):
return
Stack = []
... | true |
43012784b596503267cd6db2beb45bd19a7d1b0a | cuongnguyen139/Course-Python | /Exercise 3.3: Complete if-structure | 262 | 4.1875 | 4 | num=input("Select a number (1-3):")
if num=="1":
num="one."
print("You selected",num)
elif num=="2":
num="two."
print("You selected",num)
elif num=="3":
num="three."
print("You selected",num)
else:
print("You selected wrong number.")
| true |
297071abe7a2bbfdb797a7cc84cc1aeac99f4850 | RickyCode/CursoProgramacionBasico | /Codigos Clase 4/04_cuadrado.py | 309 | 4.15625 | 4 | # Se le pide un número al usuario:
numero = int(input('>>> Ingresa un número: ')) # La función int() transformará el texto a número.
# Se calcula el cuadrado del número:
cuadrado_num = numero ** 2
# Se muestra en la pantalla el resultado:
print('El cuadrado del número es: ', cuadrado_num)
| false |
d99103049b500922d6d7bab8268503ad8190067c | osudduth/Assignments | /assignment1/assignment1.py | 1,987 | 4.1875 | 4 | #!/usr/bin/env python3
#startswith,uppercase,endswith, reverse, ccat
#
# this will tell you the length of the given string
#
def length(word):
z = 0
for l in word:
z = z + 1
return z
#
# returns true if word begins with beginning otherwise false
#
def startsWith(word, beginning):
for x in r... | true |
d0524ae575c3cf1697039a0f783618e247a96d18 | TeresaChou/LearningCpp | /A Hsin/donuts.py | 222 | 4.25 | 4 | # this program shows how while loop can be used
number = 0
total = 5
while number < total:
number += 1
donut = 'donuts' if number > 1 else 'donut'
print('I ate', number, donut)
print('There are no more donuts') | true |
0d7273d3c8f1599fa823e3552d5dfe677f2eb37b | AdarshMarakwar/Programs-in-Python | /Birthday Database.py | 1,456 | 4.15625 | 4 | import sys
import re
birthday = {'John':'Apr 6','Robert':'Jan 2','Wayne':'Oct 10'}
print('Enter the name:')
name=input()
if name in birthday.keys():
print('Birthday of '+name+' is on '+birthday[name])
else:
print('The name is not in database.')
print('Do you want to see the entire databse?'... | true |
f6f745b08e14bb8d912565e1efecf3bbf9a437a1 | mnk343/Automate-the-Boring-Stuff-with-Python | /partI/ch3/collatz.py | 321 | 4.1875 | 4 | import sys
def collatz(number):
if number%2 :
print(3*number+1)
return 3*number+1
else:
print(number//2)
return number//2
number = input()
try :
number = int(number)
except ValueError:
print("Please enter integer numbers!!")
sys.exit()
while True:
number = collatz(number)
if number == 1:
break
... | true |
34ce2cbc18f6a937592da46d748ce032e709cfa4 | Rusvi/pippytest | /testReact/BasicsModule/dictionaries.py | 867 | 4.125 | 4 | #Dictionaries (keys and values)
# simple dictionary
student = {
"name": "Mark",
"student_id": 15163,
"feedback": None
}
#Get values
print(student["name"])# = Mark
#print(student["last_name"]) KeyError if there is no key
#avoid by get("key","default value")
print(student.get("last_name","Unknown_key"))# = ... | true |
0eb8624cbe3c84cfbeeb7c3494e271fb00bfb726 | SchoBlockchain/ud_isdc_nd113 | /6. Navigating Data Structures/Temp/geeksforgeeks/geeksforgeeks_BFS_udacity.py | 1,679 | 4.3125 | 4 | # Program to print BFS traversal from a given source
# vertex. BFS(int s) traverses vertices reachable
# from s.
from collections import defaultdict
# This class represents a directed graph using adjacency
# list representation
class Graph:
# Constructor
def __init__(self):
# default dictionary to... | true |
4599cd49493f9376018cee225a14f139fd9c316f | m-tambo/code-wars-kata | /python-kata/counting_duplicate_characters.py | 1,112 | 4.21875 | 4 | # https://www.codewars.com/kata/54bf1c2cd5b56cc47f0007a1/train/python
# Write a function that will return the count of distinct
# case-insensitive alphabetic characters and numeric digits
# that occur more than once in the input string.
# The input string can be assumed to contain only
# alphabets (both uppercase and ... | true |
39dd901b68ac263934d07e52ace777357d37edbc | ProgrammingForDiscreteMath/20170828-karthikkgithub | /code.py | 2,881 | 4.28125 | 4 | from math import sqrt, atan, log
class ComplexNumber:
"""
The class of complex numbers.
"""
def __init__(self, real_part, imaginary_part):
"""
Initialize ``self`` with real and imaginary part.
"""
self.real = real_part
self.imaginary = imaginary_part
def __rep... | true |
aef037a891c81af4f75ce89a534c7953f5da6f57 | christian-million/practice-python | /13_fibonacci.py | 653 | 4.1875 | 4 | # 13 Fibonacci
# Author: Christian Million
# Started: 2020-08-18
# Completed: 2020-08-18
# Last Modified: 2020-08-18
#
# Prompt: https://www.practicepython.org/exercise/2014/04/30/13-fibonacci.html
#
# Write a program that asks the user how many Fibonnaci numbers to generate and then generates them.
# Take this opportu... | true |
88157f9c38fd2952634c6a17f987d0d1a5149965 | git-uzzal/python-learning | /genPrimeNumbers.py | 579 | 4.21875 | 4 | def isPrime(n):
for num in range(2,n):
if n % num == 0:
return False
return True
def get_valid_input():
''' Get valid integer more than equal to 3'''
while(True):
try:
num = int(input('Enter a number: '))
except:
print("I dont undersand that")
continue
else:
if num < 3:
print("Number m... | true |
e5d7cde3aa799b147de8bb6a5ff62b308cac45d5 | ruchit1131/Python_Programs | /learn python/truncate_file.py | 896 | 4.1875 | 4 | from sys import argv
script,filename=argv
print(f"We are going to erase {filename}")
print("If you dont want that hit Ctrl-C")
print("If you want that hit ENTER")
input("?")
print("Opening file")
target=open(filename,'w')
print("Truncating the file.")
target.truncate()#empties the file
print("Writ... | true |
d636b023af3f4e570bef64a37a4dbb5a162bd6db | chavarera/codewars | /katas/Stop gninnipS My sdroW.py | 1,031 | 4.34375 | 4 | '''
Stop gninnipS My sdroW!
Write a function that takes in a string of one or more words, and returns the same string,
but with all five or more letter words reversed (Just like the name of this Kata).
Strings passed in will consist of only letters and spaces.
Spaces will be included only when more than one word is pre... | true |
1b081dfc115a840dde956934dbab0ee5f3b41891 | harshaghub/PYTHON | /exercise.py | 457 | 4.15625 | 4 | """Create a list to hold the to-do tasks"""
to_do_list=[]
finished=False
while not finished:
task = input('enter a task for your to-do list. Press <enter> when done: ')
if len(task) == 0:
finished=True
else:
to_do_list.append(task)
print('Task added')
"""Display to-... | true |
4fa45f63c6bbadc3ab8c3490058f3ac239648957 | NikhilDusane222/Python | /DataStructurePrograms/palindromeChecker.py | 965 | 4.1875 | 4 | #Palindrome checker
#class Dequeue
class Deque:
def __init__(self):
self.items = []
def add_front(self, item):
self.items.append(item)
def add_rear(self, item):
self.items.insert(0, item)
def remove_front(self):
return self.items.pop()
def remove_rear(self):
... | false |
f4bd846af010b1782d0e00da64f0fdf4314e93ba | mikikop/DI_Bootcamp | /Week_4/day_3/daily/codedaily.py | 700 | 4.1875 | 4 | choice = input('Do you want to encrypt (e) or decrypt (d)? ')
cypher_text = ''
decypher_text = ''
if choice == 'e' or choice == 'E':
e_message = input('Enter a message you want to encrypt: ')
#encrypt with a shift right of 3
for letter in e_message:
if ord(letter) == 32:
cypher_text += chr(ord(letter))
else:... | true |
25e86fc49773801757274ede8969c27c68168747 | mikikop/DI_Bootcamp | /Week_4/day_5/exercises/Class/codeclass.py | 1,542 | 4.25 | 4 | # 1 Create a function that has 2 parameters:
# Your age, and your friends age.
# Return the older age
def oldest_age(my_age,friend_age):
if my_age > friend_age:
return my_age
return friend_age
print(oldest_age(34,23))
# 2. Create a function that takes 2 words
# It must return the lenght of the longer... | true |
aff2134f2e4a76a59dc2d99184a548e17f290de0 | LStokes96/Python | /Code/teams.py | 945 | 4.28125 | 4 | #Create a Python file which does the following:
#Opens a new text file called "teams.txt" and adds the names of 5 sports teams.
#Reads and displays the names of the 1st and 4th team in the file.
#Create a new Python file which does the following:
#Edits your "teams.txt" file so that the top line is replaced with "This ... | true |
58d75067e577cf4abaafc6e369db8da6cf8e7df1 | FL9661/Chap1-FL9661 | /Chap3-FL9661/FL9661-Chap3-3.py | 2,254 | 4.5 | 4 | # F Lyness
# Date 23 Sept 2021
# Lab 3.4.1.6: the basics of lists #
# Task: use a list to print a series of numbers
hat_numbers = [1,2,3,4,5]
#list containing each number value known as an element
print ('There once was a hat. The hat contained no rabbit, but a list of five numbers: ', hat_numbers [0], hat_numbers [... | true |
6c68a4b129524de39ef050160decd697dfec5a86 | sigrunjm/Maximum-number | /maxnumb.py | 471 | 4.4375 | 4 |
num_int = int(input("Input a number: ")) # Do not change this line
# Fill in the missing code
#1. Get input from the user
#2. if number form user is not negative print out the largest positive number
#3. Stop if user inputs negative number
max_int = 0
while num_int > 0:
if num_int > max_int:
max_int = ... | true |
28962e9e8aaa5fb3ce7f67f8b4109c426fed0f65 | yaseenshaik/python-101 | /ints_floats.py | 539 | 4.15625 | 4 | int_ex = 2
float_ex = 3.14
print(type(float_ex))
# Float/normal division
print(3 / 2) # 1.5
# Floor division
print(3 // 2) # gives 1
# Exponent
print(3 ** 2) # 9
# Modulus
print(3 % 2) # 1
# priorities - order of operations
print(3 + 2 * 4) # 11
# increment
int_ex += 1
print(int_ex)
# round (takes a... | true |
dae861a719ced79a05da501c28302a2452395924 | abercrombiedj2/week_01_revision | /lists_task.py | 493 | 4.4375 | 4 | # 1. Create an empty list called `task_list`
task_list = []
# 2. Add a few `str` elements, representing some everyday tasks e.g. 'Make Dinner'
task_list.append("Make my bed")
task_list.append("Go for a run")
task_list.append("Cook some breakfast")
task_list.append("Study for class")
# 3. Print out `task_list`
print(t... | true |
a430e9bb28ae56dfe1309b2debbfff29b73a41b8 | milincjoshi/Python_100 | /95.py | 217 | 4.40625 | 4 | '''
Question:
Please write a program which prints all permutations of [1,2,3]
Hints:
Use itertools.permutations() to get permutations of list.
'''
import itertools
l = [1,2,3]
print tuple(itertools.permutations(l)) | true |
fac3f0586e4c82f66a35d23b3ec09640da8dab44 | milincjoshi/Python_100 | /53.py | 682 | 4.6875 | 5 | '''
Define a class named Shape and its subclass Square.
The Square class has an init function which takes a length as argument.
Both classes have a area function which can print the area of the shape
where Shape's area is 0 by default.
Hints:
To override a method in super class, we can define a method with the
sa... | true |
2822a1bdf75dc41600d2551378b7c533316e6a86 | milincjoshi/Python_100 | /45.py | 318 | 4.25 | 4 | '''
Question:
Write a program which can map() to make a list whose elements are square of elements in [1,2,3,4,5,6,7,8,9,10].
Hints:
Use map() to generate a list.
Use lambda to define anonymous functions.
'''
#print map([x for x in range(1,11)], lambda x : x**2)
print map( lambda x : x**2,[x for x in range(1,11)]) | true |
bc2efffa5e46d51c508b6afa2f5deda322a77765 | milincjoshi/Python_100 | /28.py | 247 | 4.15625 | 4 | '''
Question:
Define a function that can receive two integral numbers in string form and compute their sum and then print it in console.
Hints:
Use int() to convert a string to integer.
'''
def sum(a,b):
return int(a)+int(b)
print sum("2","4") | true |
e95d429da8c1244e407913413e549ed08316bf59 | LMIGUE/Github-mas-ejercicios-py | /classCircle.py | 717 | 4.25 | 4 | class Circle:
def __init__ (self, radius):
self.radius = radius
def circumference(self):
pi = 3.14
circumferenceValue = pi * self.radius * 2
return circumferenceValue
def printCircumference (self):
myCircumference = self.circumference()
print ("Circumference of a circ... | false |
9de6d50bce515e0003aaff576c3c92d04b162b9d | chandanakgd/pythonTutes | /lessons/lesson6_Task1.py | 1,513 | 4.125 | 4 | '''
* Copyright 2016 Hackers' Club, University Of Peradeniya
* Author : Irunika Weeraratne E/11/431
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-... | true |
6a0c9526c14dd7fb71a9ba8002d3673e7da8b29b | yangzhao1983/leetcode_python | /src/queue/solution225/MyStack.py | 1,512 | 4.125 | 4 | from collections import deque
class MyStack(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.q1 = deque()
self.q2 = deque()
def push(self, x):
"""
Push element x onto stack.
:type x: int
:rtype: None
... | true |
a657612ac1dbce789b2f2815e631ffad2a8de060 | AlexMazonowicz/PythonFundamentals | /Lesson2.1/solution/urlvalidator_solution.py | 1,040 | 4.28125 | 4 | import requests
def validate_url(url):
"""Validates the given url passed as string.
Arguments:
url -- String, A valid url should be of form <Protocol>://<hostmain>/<fileinfo>
Protocol = [http, https, ftp]
Hostname = string
Fileinfo = [.html, .csv, .docx]
"""
protocol_valid = True
valid_pro... | true |
79a2b5f3b7e3594ed0137ed3f0d12912f15e6d6f | mulus1466/raspberrypi-counter | /seconds-to-hms.py | 302 | 4.15625 | 4 | def convertTime(seconds):
'''
This function converts an amount of
seconds and converts it into a struct
containing [hours, minutes, seconds]
'''
second = seconds % 60
minutes = seconds / 60
hours = minutes / 60
Time = [hours, minutes, second]
return Time
| true |
5be76054d3e797c6f7a997569a99f01aedfbd6a8 | Nilsonsantos-s/Python-Studies | /Mundo 1 by Curso em Video/Exercicios Python 3/ex022.py | 458 | 4.125 | 4 | # leia um nome completo e mostre : letra maiusculas, letras miusculas, quantas letras sem espaços, letras tem o primero nome.
nome = input('Digite seu nome completo:')
print(f' O seu nome completo em maiusculo é : {nome.upper()}')
print(f' O seu nome completo em minusculo é : {nome.lower()}')
print(f' O seu nome tem {l... | false |
ba25f64610567598313f2b33919334f925db8b86 | Nilsonsantos-s/Python-Studies | /Mundo 3 by Curso em Video/Exercicios/ex115/__init__.py | 2,125 | 4.34375 | 4 | # crie um pequeno sistema modularizado que
# permita cadastrar pessoas pelo seu nome e idade em um arquivo de txt simples
# o sistema so vai ter 2 opções: cadastrar uma nova pessoa e listar todas as pessoas cadastradas
def titulo(texto):
texto = str(texto)
print('*-' * 25)
print(f'{texto.title(): ^50}')
... | false |
2fbde86ebba0d575833e4aeb65e77dfd1f2e0ab2 | Nilsonsantos-s/Python-Studies | /basic_python/aulas_by_geek_university/reversed.py | 986 | 4.65625 | 5 | '''
-> Reversed
OBS: não confundir com reverse pois é uma função das listas:
lista.reverse() # Retorna a lista invertida
O Reversed funciona para quaisquer iterável, invertendo o mesmo.
-> Retorna um iterável propio, de nome: List Reversed Iterator
# Exemplos:
## Iteraveis
dados = list(range(10))
print(dados)... | false |
8d1947a37f5305936fe58775d47c8267a767db97 | Nilsonsantos-s/Python-Studies | /Mundo 3 by Curso em Video/Exercicios/075.py | 1,207 | 4.125 | 4 | # leia quatro valores pelo teclado e guardalos em uma tupla, no final mostrar, quantas vezes apareceu o valor 9.
# em que posição foi digitado o primeiro valor 3, quais foram os numeros pares.
valores = pares = tuple()
# Forma Realizada
for x in range(0,4):
inpu = input('Digite um valor:')
valores += tuple... | false |
3ae76c70671c80b157240feeef76e21f52312354 | Nilsonsantos-s/Python-Studies | /basic_python/aulas_by_geek_university/ordered_dict.py | 491 | 4.21875 | 4 | """
Modulo Collections (Modulo conhecido por alta performance) - Ordered Dict
> Um dicionario que tem a ordem de inserção garantida
# Demonstrando Diferença entre Dict e Ordered Dict
from collections import OrderedDict
dict1 = {'a':1,'b':2}
dict2 = {'b':2,'a':1}
print(dict1 == dict2)
# True
odict1 = OrderedDict({... | false |
45d1a3a08d68b4f7f24f36b9dc01f505ee715004 | JamesSG2/Handwriting-Conversion-Application | /src/GUI.py | 1,998 | 4.40625 | 4 | #tkinter is pre-installed with python to make very basic GUI's
from tkinter import *
from tkinter import filedialog
root = Tk()
#Function gets the file path and prints it in the command
#prompt as well as on the screen.
def UploadAction(event=None):
filename = filedialog.askopenfilename()
print('Selected:', fil... | true |
fcfe2cc13a4f75d0ea9d47f918a7d53e3f8495df | cs-fullstack-2019-fall/python-basics2f-cw-marcus110379 | /classwork.py | 1,610 | 4.5 | 4 | ### Problem 1:
#Write some Python code that has three variables called ```greeting```, ```my_name```, and ```my_age```. Intialize each of the 3 variables with an appropriate value, then rint out the example below using the 3 variables and two different approaches for formatting Strings.
#1) Using concatenation and the... | true |
3763ee2e94ab64e04a0725240cdc3a7a6990a3ad | yz398/LearnFast_testing | /list_module/max_difference.py | 1,314 | 4.125 | 4 | def max_difference(x):
"""
Returns the maximum difference of a list
:param x: list to be input
:type x: list
:raises TypeError: if input is not a list
:raises ValueError: if the list contains a non-float or integer
:raises ValueError: if list contains +/-infinity
... | true |
70276b8e585bd6299b8e9a711f5271089f25ab04 | BenjaminLBowen/Simple-word-frequency-counter | /word_counter.py | 938 | 4.25 | 4 | # Simple program to list each word in a text that is entered by the user
# and to count the number of time each word is used in the entered text.
# variable to hold users inputed text
sentence= input("Type your text here to count the words: ")
# function to perform described task
def counting_wordfunc(sentence):
#... | true |
e557e78a72b9ad5863b730d7d207b726612b5989 | TH-Williamson/Class-Projects | /dateformat.py | 688 | 4.3125 | 4 | #need to tqke an integer input, and convert it to mm/dd/yyyy AND DD-MM-YYY format
#TH Williamson, intro to programming, Prof. Kurdia
user_day = str(input('Please enter day: '))
user_month = str(input('Please enter month: '))
user_year = str(input('Please enter year: '))
if user_day[0] == 0:
user_day = '0' + use... | false |
c7b32d7c040304d87a25b09008f6045d0d5d304b | rj-fromm/assignment3b-python | /assignment3b.py | 530 | 4.375 | 4 | # !user/bin/env python3
# Created by: RJ Fromm
# Created on: October 2019
# This program determines if a letter is uppercase or lowercase
def main():
ch = input("Please Enter a letter (uppercase or lowercase) : ")
if(ord(ch) >= 65 and ord(ch) <= 90):
print("The letter", ch, "is an uppercase letter")... | true |
27b16e6ee0cbd9477fc99475382e5e8e95d1efb7 | gautamdayal/natural-selection | /existence/equilibrium.py | 2,379 | 4.28125 | 4 | from matplotlib import pyplot as plt
import random
# A class of species that cannot reproduce
# Population is entirely driven by birth and death rates
class Existor(object):
def __init__(self, population, birth_rate, death_rate):
self.population = population
self.birth_rate = birth_rate
sel... | true |
1a5f5335e97941b5797ba92bc13877e4a73acd00 | markagy/git-one | /Mcq_program.py | 1,487 | 4.25 | 4 | # Creating a class for multiple choice exam questions.Each class object has attribute "question" and "answer"
class Mcq:
def __init__(self, question, answer):
self.question = question
self.answer = answer
# Creating a list of every question
test = [
"1.How many sides has a triangle?\n (a) 1\... | true |
a3e8cfb8a4f8f7765e9088883440d151e6d972d5 | nagios84/AutomatingBoringStuff | /Dictionaries/fantasy_game_inventory.py | 767 | 4.1875 | 4 | #! python3
# fantasy_game_inventory.py - contains functions to add a list of items to a dictionary and print it.
__author__ = 'm'
def display_inventory(inventory):
total_number_of_items = 0
for item, quantity in inventory.items():
print(quantity, item)
total_number_of_items += quantity
... | true |
017b0543fd031602af8129b05cd6567ce67fc5db | AnuraghSarkar/DataStructures-Algorithms_Practice | /queue.py | 1,671 | 4.53125 | 5 | class queue:
def __init__(self):
self.items = []
def enqueue(self, item):
"""
Function to add item in first index or simply enqueue.
Time complexity is O(n) or linear. If item is added in first index all next items should be shifted by one.
Time depends upon list length.... | true |
75d580033b9ae7be6a86340e7b214ac101d25fdb | xpansong/learn-python | /对象(2)/3. 方法重写.py | 1,079 | 4.21875 | 4 | print('----------方法重写---------------')
'''如果子类对继承自父类的某个属性或方法不满意,可以在子类中对其(方法体)进行重新编写'''
'''子类重写后的方法中可以通过super().XXX()调用父类中被重写的方法'''
class Person: #也可以写Person(object)
def __init__(self,name,age):
self.name=name
self.age=age
def info(self):
print(self.name,self.age)
class Student(Person)... | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.