blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
7132b01f8aefc39d775455c3cb1e6343de6e738e | evensteven01/pythonTricks_sf | /oop.py | 2,314 | 4.5 | 4 | # Classes vs instance variables
class Car:
color = 'Red' # this is an class variable
def __init__(self, name):
self.name = name # This is an instance variable
my_car = Car('My car')
other_car = Car('Other car')
other_car.color = 'Blue'
print(f'My car color: {my_car.color} Other car color: {other_car.... | true |
df28bae3acee935a691689482bb39d4d14a31334 | giahienhoang99/C4T-BO4 | /session7/Part II/bt4.py | 223 | 4.375 | 4 | from turtle import *
numofsides = int(input("Enter number of sides: "))
length = int(input("Enter length of sides: "))
Angle = 360 / numofsides
for i in range(numofsides):
forward(length)
right(Angle)
mainloop()
| true |
00e6a5d4bfa0db65475fdcefafecdde02470a345 | sandeepgit32/Data_Structure_Tutorial_Python_Latex | /src/sort/bubblesort2.py | 639 | 4.25 | 4 | def bubble_sort(input_list):
L = len(input_list)
Round_num = L-1
Iterations_per_round = [L-x for x in range(1, L)]
for rnd in range(Round_num):
for iteration in range(Iterations_per_round[rnd]):
for i in range(0, L-1-iteration):
if input_list[i] > input_lis... | false |
21421a62659e44c410d2c46083120d2473cbff6e | sandeepgit32/Data_Structure_Tutorial_Python_Latex | /src/sort/selectionsort2.py | 662 | 4.125 | 4 | def selection_sort(input_list):
L = len(input_list)
Round_num = L-1
Iterations_per_round = [L-x for x in range(1, L)]
for rnd in range(Round_num):
for iteration in range(Iterations_per_round[rnd]):
for i in range(iteration, L-1):
if input_list[iteration] > ... | false |
b86d9a07ff57f36252fc262af668330b41438f08 | swapnil2188/python-myrepo | /parsing/find_dupes-words.py | 360 | 4.25 | 4 | #!/usr/bin/python
ex ='This is sample file. This is not a sample file. Not a sample file'
def freq(str):
# break the string into list of words
str_list = str.split()
# gives set of unique words
unique_words = set(str_list)
print unique_words
for words in unique_words:
print(words, str_list.count(words)... | true |
e87162070ec2b7e8b8332005452023b913ab115f | swapnil2188/python-myrepo | /lists/lists_methods.py | 1,805 | 4.59375 | 5 | #!/usr/bin/python
print "\n append - The append() method appends an element to the end of the list"
fruits = ['apple', 'banana', 'cherry']
fruits.append("Orange")
print fruits
print "\n The clear() method removes all the elements from a list"
#fruits.clear()
#print (fruits)
print "\n The copy() method returns a copy... | true |
e292a2649a8257eafd078d2a1054aa2c32a03f88 | Manoo-hao/project | /Exercises/function_exercise2.py | 2,003 | 4.125 | 4 | from __future__ import division
def get_percentage(sequence, amino_acids):
'''This is a more flexible version of function_exercise1 which can return the percentage of a list of amino acids
as specified in the argument 'amino_acids' above.
It will also work when entering an empty string, a single amino acid, and an amin... | true |
cdc4cb894dff239cc436d3b1e88d6edfa466e6ad | ilailabs/python | /tutorials/trash/SimpleCalculator.py | 1,581 | 4.3125 | 4 | while True:
print('Options:')
print ("Enter 'add' to add two numbers")
print("Enter 'sub' to subtract two numbers")
#print 'Enter 'mul' to multiply two numbers' #this will through a print error
print "Enter 'mul' to multiply two numbers"
print "Enter 'div' to divide two numbers"
print "Enter... | false |
1cf57e5d4f09523be84f5e773a40dbbe0c5ff92d | ilailabs/python | /tutorials/class.py | 852 | 4.5 | 4 | ##example01
class MyClass:
prop1 = 5
# "MyClass" is a class with property "prop1"
object1 = MyClass()
print(object1.property)
##example02
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
#all classes have function called __init__() which is executed when c... | true |
aa55d8043cf23aa0032d1ec5faf2122ea901f250 | ilailabs/python | /tutorials/trash/GetInputDict.py | 467 | 4.21875 | 4 | pairs={
1:"apple",
"Orange":[2, 3, 4],
True:False,
None:"True",
}
print(pairs)
#Number *1:'apple'* isn't added to dic
print(pairs.get("Orange"))
print(pairs["Orange"]) #same as above line
print(pairs.get(7)) # >>None
print(pairs.get(1,'ae its there'))# >>False
print(pairs.get(123,'its not in dic')) # >>its not i... | true |
b041376f95bcc64f7f9ec23524a2fe6bd7194238 | mbrown34/PowdaMix | /enemylist.py | 1,054 | 4.15625 | 4 | #!/usr/bin/env python
'''
Originally created on Oct 28, 2012
Updated/revised on November 27, 2012
@author: matthew
'''
#changed enemylist from the need to create a list variable and then add that list variable to the enemylist []
#now the person adding a new enemy can simply add another list into the main list by usin... | true |
3e44d163733cda5584a266a6bf898b3d6f59cd8b | carlsose/Coursera-PY4E | /8.4.py | 583 | 4.40625 | 4 | #Open the file romeo.txt and read it line by line. For each line, split the line into a list of words using the split() method.
#The program should build a list of words. For each word on each line check to see if the word is already in the list and if not append
#it to the list. When the program completes, sort and ... | true |
6cba2036bcf586e38298d3a079715c0b7d1277a9 | zhyordanova/Python-Basics | /Exam/06_passengers_per_flight.py | 729 | 4.15625 | 4 | import sys
import math
airline = int(input())
max_passengers = -sys.maxsize
max_name = ''
for name in range(1, airline + 1):
name_airline = input()
current_name = ''
passengers = input()
average = 0
counter = 0
total_passengers = 0
while passengers != "Finish":
total_passengers... | true |
a7559245d2e38ef9b06700fa09831cd71ef71b97 | jorzel/hackerrank | /30_days_of_code/day17_more_exceptions.py | 2,122 | 4.46875 | 4 | """
Objective
Yesterday's challenge taught you to manage exceptional situations by using try and catch blocks. In today's challenge, you're going to practice throwing and propagating an exception. Check out the Tutorial tab for learning materials and an instructional video!
Task
Write a Calculator class with a... | true |
e911e0833e1f5a387fb95d180ae241339cac2b74 | jooguilhermesc/cursoPython | /Scripts/Example.py | 755 | 4.34375 | 4 | #Pedir o nome do usuário utilizando o input e forçando que seja um texto com str()
nomeCompleto = str(input("Oi tudo, bem? Como é seu nome? "))
#Exibir no terminal uma mensagem de saudção personalizada com o nome inserido ateriormente
print("Olá "+nomeCompleto+" seu nome é muito legal!")
"""nomeCompleto = "João Gu... | false |
e065d4ba52fd31959bc4b08bad45b9fa82a9cc79 | Luciano-T-L/Books | /PTHW/ex39.1.py | 884 | 4.28125 | 4 | # Creating states map
states = {
'São Paulo': 'SP',
'Rio de Janeiro': 'RJ',
'Santa Catarina': 'SC',
'Paraná': 'PR',
'Rio Grande do Sul': 'RS'
}
# Creating cities map
cities = {
'SC': 'Florianópolis',
'PR': 'Curitiba',
'SP': 'São Paulo',
'RJ': 'Rio de Janeiro'
}
# A... | false |
6d1dd4459823ab8bca1993b137d7b1208d2a1030 | sonya-sa/guessing-game | /game.py | 2,553 | 4.15625 | 4 | import random
import requests
from api import get_word
#create a function that randomly selects a word
#create function that checks word and guess
#function has 3 paramaters: word selected, guess letter, list of guesses taken
def check(word, guesses, guess):
show = ''
matches = 0
for letter in word:
... | true |
4d7323eddc94f6cb5870a74f0ff2308b91ec808c | sanjaykumardbdev/pythonProject_1 | /32_Functions.py | 595 | 4.125 | 4 | # define a function
# call a function
def greet():
print("first function in python")
print("Hello ! Good Morning")
greet()
print("-----------")
# pass 2 arguments
def add(x,y):
z = x + y
print("sum of two num", z)
add(3,3)
add(12, 12)
# function that return value
def add_return(x, y):
z = x + y
... | true |
890a83f6f42250c8ce00ec9df3eaa9328552017a | adamjford/CMPUT296 | /Lecture-2013-01-30/example-orig.py | 1,767 | 4.25 | 4 | """
Graph example
G = (V, E)
V is a set
E is a set of edges, each edge is an unordered pair
(x, y), x != y
"""
import random
# from random import sample
# from random import *
def neighbours_of(G, v):
"""
>>> G = ( {1, 2, 3}, { (1, 2), (1, 3) })
>>> neighbours_of(G, 1) == { 2, 3 }
True
>>> neighbo... | true |
8603b7a58ef620a11bd69db086e9add33f21dab5 | smart9545/Python-assignments | /Q2.py | 2,914 | 4.3125 | 4 | #############################################
# COMPSCI 105 SS C, 2018 #
# Assignment 2 #
# #
# @author FanYu and fyu914 #
# @version 10/2/2018 #
#############################################
"""
Description:
Implement... | true |
d152916196ff4743c4a07146039cbfb920f19b6a | Tishacy/Algorithms | /code/0 pick_based_on_prob.py | 2,648 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""Given an array with each element has a probability, choose one element according to its probability.
0.1 Giant array pool method
step 1: Generate a new array by repeating the each element for multiple times according to its probability.
step 2: Randomly pick one from the array.
0.2 ... | true |
1dbea5c313b920cc6e4520af126a4516802910c7 | Tishacy/Algorithms | /leetcode/python_vers/4 Median of Two Sorted Arrays.py | 1,189 | 4.1875 | 4 | """
There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
You may assume nums1 and nums2 cannot be both empty.
Example 1:
nums1 = [1, 3]
nums2 = [2]
The median is 2.0
Example 2:
nums1 = [1,... | true |
2270fa9645a16015bc8440859b039802c1e4e7d6 | summerqiu7/python-practice | /test.py | 1,894 | 4.125 | 4 | # This line prints "hello world!"
# print('hello world!')
# print('hello world 2!')
# myverylongstring
# MyVeryLongString #Upper camel case
# myVeryLongString #camel case
# my_very_long_string #snake case
# myString = 'summer'
# print(myString)
# print(myString+"hello world")
# x = 2
# print(x)
# two = str('2')
# p... | false |
228c88cf0ebb2bc8a2d6777efdd99e61cab79149 | gungeet/python-programming | /unit-2/classwork.py | 955 | 4.4375 | 4 | classmates = ['Ros', 'Marcus', 'Flavio',
'Joseph', 'Maham', 'Vinay', 'Gungeet', 'Faris']
'''
#prints number of items in list
print(len(classmates))
#prints the first item in the list
print(classmates[0])
#prints last element in list
print(classmates[-1])
#adds element to list
classmates.append('John')
print(classma... | true |
7bf7df412be0dee227b8929b2e0c5fb5506cc361 | rebel47/Python-Revison | /chapter3.py | 1,631 | 4.4375 | 4 | # # WAP to display a user entered name followed by Good Afternoon using input() function
# a = input("Enter your good name: ")
# print(f"Good Afternoon, {a}") # f string is used in the print function
# WAP to fill in a letter template given below with name and date
# letter = ''' Dear <|NAME|>,
# ... | true |
f504a392c39c12bd9f6fffb187959142c9d74649 | MicahJank/cs-module-project-hash-tables | /applications/markov/markov.py | 2,254 | 4.125 | 4 | import random
words_list = None
data_set = {}
punctuation = [".", "!", "?"]
# Read in all the words in one go
with open("./markov/input.txt") as f:
words = f.read()
words_list = words.split(" ")
f.close()
# TODO: analyze which words can follow other words
'''
iterate over the words list
for each word i w... | true |
7d77e601bdc517610a6301ca5f3a68e6bf32b838 | adellario/pythonthw | /Exercises/ex11.2.py | 558 | 4.46875 | 4 | # This program calculates your longest maximum training run distance.
# First, ask some basic questions.
first_name = input("What's your first name? ")
last_name = input("What's your last name? ")
race_length = int(input("How long is your race? "))
# Calculate the max training run length
max_train_run = race_length / ... | true |
0383b22e52ef1cbf524782e1e9cac487842d04ea | adellario/pythonthw | /Exercises/ex7.py | 846 | 4.25 | 4 | # Print the first phrase
print("Mary had a little lamb.")
# Print the a string with an empty variable, using .format() to fill that variable with the word "snow."
print("Its fleece was white as {}.".format('snow'))
# Print another string in the poem
print("And everywhere that Mary went.")
# Use math to multiply the "."... | true |
d365b1ce01214a62267e9a88a52fd4ee190e5525 | robgan/Ciphers | /caesar.py | 992 | 4.375 | 4 | alphabet = {"a":0,"b":1,"c":2,"d":3,"e":4,"f":5,"g":6,"h":7,"i":8,"j":9,"k":10,"l":11,"m":12,"n":13,"o":14,"p":15,"q":16,"r":17,"s":18,"t":19,"u":20,"v":21,"w":22,"x":23,"y":24,"z":25}
def caesar():
#message that is going to be encrypted
plaintext = input("Provide the message you would like to encrypt")
#h... | true |
15a33dd8388cdb23a0e0768b394a12d6f9206bae | AdirthaBorgohain/python_practice | /Drawing/draw.py | 755 | 4.125 | 4 |
import turtle
def draw_square():
baby = turtle.Turtle() #grabs the turtle and names it chutiya
baby.color("green")
baby.shape("turtle")
baby.speed(2)
for i in range(0,4):
baby.forward(100)
baby.right(90)
def draw_circle():
jhon = turtle.Turtle()
jhon.shape("arrow")
... | false |
ffd75ca34c884132ddea7f8536ad2f3c280d705e | JohnADeady/PROGRAMMING-SCRIPTING | /Dice.py | 1,017 | 4.5 | 4 | #John Deady, 2018-23-02
#Dice Rolling Simulator
# Adapted from https://knightlab.northwestern.edu/2014/06/05/five-mini-programming-projects-for-the-python-beginner/
# The Goal: this program involves writing a program that simulates a rolling dice.
# When the program runs, it will randomly choose a number between... | true |
1a7116b2effe44c4edfbded20adefa9a1b640a01 | topefremov/mit6001x | /oddTuples.py | 376 | 4.15625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 8 08:55:56 2018
@author: efrem
"""
def oddTuples(aTup):
'''
aTup: a tuple
returns: tuple, every other element of aTup.
'''
result = ()
tupleLength = len(aTup)
i = 0
while (i < tupleLength):
result = re... | true |
9821fcd9ed69fc7b195f0586e83b557a840fe353 | topefremov/mit6001x | /psets/ps1/p3.py | 985 | 4.375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 3 14:09:14 2021
Write a program that prints the longest substring of s in which the letters
occur in alphabetical order.
For example, if s = 'azcbobobegghakl', then your program should print:
Longest substring in alphabetical order is: beggh
In... | true |
0bda046862f59efa69e0436da5461bae8712100f | ry-blank/Module-8 | /assign_average.py | 523 | 4.46875 | 4 | """
Program: selection_using_dictionary_assignment
Author: Ryan Blankenship
Last date modified: 10/14/2019
The purpose of this program is to use a
dictionary to mimic a switch statement
to return the value of a key.
"""
def switch_average(key):
"""
function to use dict to mimic switch
:para... | true |
3d538be12ed11eca5b813157f68b9726caa21d91 | JenVest2020/CSPT17repls | /mod1Obj2.py | 464 | 4.3125 | 4 | """
Use the print function, the variables below, and your own literal argument values to print the following output to the screen (your printed output should have the same format as below):
1 ~
two ~
3 ~
Lambda ~
School ~
4 ~
5 ~
6 --->
*Note*: you will need to change the default values for the `sep` and `end` keyword... | true |
c84dff9f1eb441fa427605385e28ccd176b193f1 | Lhotse867745418/Python3_Hardway | /ex3.py | 958 | 4.28125 | 4 | #-------------------------------------------------------------------------------
# Name: numbers and math
# Purpose: learn math
#
# Author: lhotse
#
# Created: 17/03/2018
# Copyright: (c) lhotse 2018
# Licence:
#-----------------------------------------------------------------------------... | true |
00318b5bce676767d620c64f9ef08f799177e692 | gathonicatherine/mkulima- | /test.py | 1,885 | 4.375 | 4 | # Given this list of students containing age and name,
# students = [{"age": 19, "name": "Eunice"}, {"age": 21, "name": "Agnes"},
# {"age": 18, "name": "Teresa"}, {"age": 22, "name": "Asha"}],
# write a function that greets each student and tells them the year they were born.
# e.g Hello Eunice, you were bor... | true |
c06c242f1f429f55fb0078b4c21498dbff9f2c15 | erick2014/hackerRankChallenges | /validateArraySubsequence.py | 2,445 | 4.125 | 4 | """
Given two non-empty arrays of integers, write a function that determines
whether the second array is a subsequence of the first one.
A subsequence of an array is a set of numbers that aren't necessarily adjacent
in the array but that are in the same order as they appear in the array. For
instance, the nu... | true |
ac5ce534e2ac23361f387a80d3a962df2657df56 | RussellSB/mathematical-algorithms | /task3.py | 2,714 | 4.1875 | 4 | #Name: Russell Sammut-Bonnici
#ID: 0426299(M)
#Task: 3
import time #used for execution time comparison
#checks if number is prime
def isPrime(n):
'''
The range for the loop is set from 2 to n, as we are concerned with finding factors
that aren't 1 and n itself. If no factors that aren't 1 and n are found... | true |
4f61092e6850fae2fbc1ebd8a360c5ba8a9b4eeb | jchinedu/alx-higher_level_programming | /0x07-python-test_driven_development/0-add_integer.py | 595 | 4.21875 | 4 | #!/usr/bin/python3
# 0-add_integer.py
# Brennan D Baraban <375@holbertonschool.com>
"""Defines an integer addition function."""
def add_integer(a, b=98):
"""Return the integer addition of a and b.
Float arguments are typecasted to ints before addition is performed.
Raises:
TypeError: If either o... | true |
be68c214ca60501c534739ce26b12c704c6659aa | jchinedu/alx-higher_level_programming | /0x01-python-if_else_loops_functions/6-print_comb3.py | 452 | 4.28125 | 4 | #!/usr/bin/python3
# 6-print_comb3.py
# Brennan D Baraban <375@holbertonschool.com>
"""Print all possible different combinations of two digits in ascending order.
The two digits must be different - 01 and 10 are considered identical.
"""
for digit1 in range(0, 10):
for digit2 in range(digit1 + 1, 10):
... | true |
229fd965d0e8b0185d3396ea2c6b6ab744b80f22 | JGRobinson17/hello_world | /test_input.py | 1,629 | 4.375 | 4 | # Starting to write python
#name=input('Enter Name')
#print('hello', name)
#password program
def main_menu():
print('Enter "New" for New Account')
print('Enter "Login" to access program')
print('Enter "Exit" to exit program')
user_login = {'Josh': 'jigger', 'Jenny':'asstastic'}
user_n... | false |
b6f811070299d8131da41bf0c4794b66b6ad7161 | murphy-codes/challenges | /Python_edabit_Easy_ATM-PIN-Code-Validation.py | 1,688 | 4.4375 | 4 | '''
Author: Tom Murphy
Last Modified: 2019-10-18 22:00
'''
# https://edabit.com/challenge/K4Pqh67Y9gpixPfjo
# ATM PIN Code Validation
# ATM machines allow 4 or 6 digit PIN codes and PIN codes cannot contain anything but exactly 4 digits or exactly 6 digits. Your task is to create a function that takes a str... | true |
e27d0e78e57057a06e4b5f998399a1375751feee | JZDBB/Python-ZeroToAll | /python_basis/list_learn.py | 1,778 | 4.125 | 4 | list_1 = [1, 2, 3, 4]
print(list_1)
list_2 = ['a', 'b', 'c']
print(list_2)
list_3 = [1, 2.33, 'python', 'a']
print(list_3)
list_4 = [1, 3.3, 'haha', list_3]
print(list_4)
list_5 = []
type(list_5)
#索引
print(list_1[0])
print(list_3[2])
#连接
print(list_1 + list_2)
#复制阵列
print(list_1 * 3)
#列表长度
len(list_2)
for i in... | false |
0a84867032b885b44c0da874bf70935473bff9d7 | arunrajput17/PSTUD | /4_Strings.py | 1,279 | 4.5625 | 5 | ## Strings can be stored in variables
first_name = 'Christopher'
last_name = 'Harrison'
print(first_name+last_name)
print('Hello '+ first_name +' '+ last_name)
## Use of functions to modify strings
sentence = 'the dog is named Sammy'
print(sentence.upper())
print(sentence.lower())
print(sentence.capitalize())
print... | true |
4b8745c9de1353a4d8eb535565ec650408de3bc1 | arunrajput17/PSTUD | /10-1_Functions_Parametrization.py | 1,421 | 4.28125 | 4 | ## Functions can accept multiple parameters
def get_initial(name, force_uppercase):
if force_uppercase:
initial = name[0:1].upper()
else:
initial = name[0:1]
return initial
first_name = input('Enter your first name: ')
first_name_initial = get_initial(first_name, False)
print('Your initia... | true |
43f64ac2af0fc45f3ca5f59e2784646d48cbaaa5 | arunrajput17/PSTUD | /23_ListSetDict_Comprehension.py | 931 | 4.5625 | 5 | ## List / set / dict Comprehension : It provides a way to transform one list into another
# General way to find the even numbers from list is
numbers=[1,2,3,4,5,6,7,8,9]
even=[]
for i in numbers:
if i%2 ==0:
even.append(i)
print(even)
## Comprehension
even = [i for i in numbers if i%2==0]
print(even)
... | true |
680a2b53d3c7539db114823758567c6e7a22ff48 | SoumyaSwaraj/DSA | /FileRecursion/program_2.py | 982 | 4.4375 | 4 | import os
def find_files(suffix, path):
"""
Find all files beneath path with file name suffix.
Note that a path may contain further subdirectories
and those subdirectories may also contain further subdirectories.
There are no limit to the depth of the subdirectories can be.
Args:
suffix... | true |
3de2b9372bff4b2eb7da0564f846333dafa3c5a2 | prasadmodi-pm/Python_Assign | /JulyTraining/ListInsert.py | 273 | 4.15625 | 4 | __author__ = 'prasadmodi'
list = []
num = int(input("Number of elements in list: ")) # Total Number of elements list accepts
for i in range(num):
nums = input("enter elements to be added to list: ") # Elements taken from user
list.append(nums)
print(list)
| true |
49ad4a8627275d3f27f619c0f44bdf3e8b12830d | aurelo/lphw | /source/ex11.py | 689 | 4.375 | 4 | # comma will force the user input inline with question, and will prevent print to end with new line chr
'''
print "How old are you?",
age = raw_input()
print "How tall are you?",
height = raw_input()
print "How much do you weight?",
weight = raw_input()
'''
# raw_input([prompt]) => If the prompt argument is present, i... | true |
631e2ba5480490d9e8d04f13adf05b08506ba966 | q-riku/Python3-basic2 | /01 函数式编程-匿名函数和高阶函数/test4.py | 459 | 4.25 | 4 | """
map接受一个函数和一个迭代器作为参数,并返回一个新的迭代器,该函数应用于每个参数;
语法:列表名 = map(一个函数,一个可迭代序列)
"""
def add_five(x):
return x + 5
nums = [11, 22, 33, 44, 55]
#对列表中的每个值都加5
result = list(map(add_five, nums))
print(result)
#用lambda表达式也可以达到效果;
nums = [11, 22, 33, 44, 55]
result = list(map(lambda x: x+5, nums))
print(result) | false |
3688c587241abfa8abb14457d41cc4bfd1cee5d9 | dunton-zz/coderbyte | /DistinctList.py | 584 | 4.21875 | 4 | # Have the function DistinctList(arr) take the array of numbers
# stored in arr and determine the total number of duplicate entries.
# For example if the input is [1, 2, 2, 2, 3] then your program
# should output 2 because there are two duplicates of one of the elements.
def DistinctList(arr):
# code goes here ... | true |
01a6bd4eaab38f5715d5a84906741fe3ce233dfc | adreg0/automate-the-boring-stuff-with-python | /Chapter-07/passdetection.py | 698 | 4.125 | 4 | import re
def strongPassword(password):
passlen = re.compile(r'(.{8,})')
passnum = re.compile(r'[0-9]+')
passlower = re.compile(r'[a-z]')
passupper = re.compile(r'[A-Z]')
if passlen.search(password)==None:
print('Password must be atleast 8 characters long')
elif passnum.search(password)... | false |
ccacaad967091b63213d29438c24fcdfc6f8d8fa | sharonLuo/LeetCode_py | /valid-palindrome.py | 2,465 | 4.125 | 4 | """
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
For example,
"A man, a plan, a canal: Panama" is a palindrome.
"race a car" is not a palindrome.
Note:
Have you consider that the string might be empty? This is a good question to ask during an interview.... | true |
cf90fab781c1c6a79bac24d75e854439f010edd6 | sharonLuo/LeetCode_py | /reverse-integer.py | 1,416 | 4.375 | 4 | """
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
click to show spoilers.
Have you thought about this?
Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!
If the integer's last digit is 0, what should the out... | true |
1b9f2258b688de5c8293a4d3eddb3cd4f8eebc45 | sharonLuo/LeetCode_py | /palindrome-number.py | 1,611 | 4.15625 | 4 |
"""
Determine whether an integer is a palindrome. Do this without extra space.
Could negative integers be palindromes? (ie, -1)
If you are thinking of converting the integer to string, note the restriction of using extra space.
You could also try reversing an integer. However, if you have solved the problem "Reverse... | true |
2cf6eb9a2d88f00823b912d762b3694e25013767 | Rushaniia/Python.Basic-course | /Lesson_7/Les_7_task_1.py | 909 | 4.3125 | 4 | ''' 1. Отсортируйте по убыванию методом "пузырька" одномерный целочисленный массив, заданный случайными числами на
промежутке [-100; 100). Выведите на экран исходный и отсортированный массивы. Сортировка должна быть реализована в виде
функции. По возможности доработайте алгоритм (сделайте его умнее).'''
import random
... | false |
2db201616dcb7a2eb53fb3e67ee3040763bd3de4 | rossoskull/python-beginner | /sumofn.py | 257 | 4.1875 | 4 | def summation_by_formula(n):
return (n * (n+1)) // 2
if __name__ == "__main__":
num = int(input("Enter the number until which you want to find the sum : "))
print("The sum of first %d numbers is %d." % (num, summation_by_formula(num)))
| true |
831e6f60382305fc67edd13f091e8be295e57a50 | DQTRUC/DeepLearningCV | /Ex01_PyCharm.py | 271 | 4.125 | 4 | # Write a Python program to add the digits of a positive integer repeatedly until the result has a single digit
A = input("Enter any number:")
while len(A) > 1:
S = 0
for i in range(len(A)):
S = S + int(A[i])
A = str(S)
print("Result:",S)
| true |
46ca4d5ac950f85f1621915d3e1aba2a979e4770 | pavankumarag/ds_algo_problem_solving_python | /ADT/linked_list_all.py | 1,874 | 4.1875 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def reverse(self):
prev = None
cur = self.head
while cur is not None:
next = cur.next
cur.next = prev
prev = cur
cur = next
self.head = prev
def reverse_util(s... | true |
75d13c3ce016a33223138479c0f487bd0d973a96 | pavankumarag/ds_algo_problem_solving_python | /practice/medium/_32_powerset.py | 2,698 | 4.15625 | 4 | """
Power set P(S) of a set S is the set of all subsets of S. For example S = {a, b, c} then
P(s) = {{}, {a}, {b}, {c}, {a,b}, {a, c}, {b, c}, {a, b, c}}.
If S has n elements in it then P(s) will have 2^n elements
https://rosettacode.org/wiki/Power_set#Python
https://www.geeksforgeeks.org/power-set/
"""
import math
... | true |
a0fd0a169bf028c408878baba7bb56eefe2c5b45 | pavankumarag/ds_algo_problem_solving_python | /practice/hard/_42_minimum_points.py | 2,227 | 4.15625 | 4 | """
Minimum Initial Points to Reach Destination
Given a grid with each cell consisting of positive, negative or no points i.e, zero points. We can move across a cell only if we have positive points ( > 0 ). Whenever we pass through a cell, points in that cell are added to our overall points. We need to find minimum in... | true |
d9851b96c4e8d23807887b3adddc09a44349cff9 | pavankumarag/ds_algo_problem_solving_python | /practice/medium/_37_group_anagrams.py | 974 | 4.40625 | 4 | """
Group Anagrams from given list
Anagrams are the words that are formed by similar elements but the orders in which these characters occur differ
Example:
The original list : ['lump', 'eat', 'me', 'tea', 'em', 'plum']
The grouped Anagrams : [['me', 'em'], ['lump', 'plum'], ['eat', 'tea']]
"""
def group_anagrams(... | true |
4c8c08e10ad29fa24864e3cba12f07d5bb3a13a5 | kindlyhickory/python_algorithms | /les_1/les_1_task_5.py | 1,194 | 4.3125 | 4 | # По длинам трех отрезков, введенных пользователем, определить возможность существования треугольника,
# составленного из этих отрезков. Если такой треугольник существует, то определить,
# является ли он разносторонним, равнобедренным или равносторонним.
print('Введите длины отрезков')
a = float(input('Первая длина от... | false |
d6ad86b51e3ef3aad2f37d8e75130c7e090d383c | skilldisk/Python_Basics_Covid19 | /list/append_func.py | 210 | 4.375 | 4 | even = [0, 2, 4, 6]
print("###### Before Appending #########")
print(even)
# append will add data to the end of the list
even.append(8)
print("###### After Appending 8 to the list even #########")
print(even) | true |
097e4b3e913afb3725b3a9c653ac05ad9377a85c | felipeadner/python-brasil-exercicios | /estrutura-sequencial/05centimetros.py | 234 | 4.21875 | 4 | """
Faça um Programa que converta metros para centímetros.
"""
def main():
meters = float(input("Digite a metragem: "))
centimeter = float(meters*100)
print(meters,"m corresponde a" ,centimeter,"cm")
main()
| false |
ca34b80e8aeb9ef1cffa096020cbc5471f5054d9 | felipeadner/python-brasil-exercicios | /estrutura-de-decisao/05aluno.py | 918 | 4.21875 | 4 | """
Faça um programa para a leitura de duas notas parciais de um aluno.
O programa deve calcular a média alcançada por aluno e apresentar:
A mensagem "Aprovado", se a média alcançada for maior ou igual a sete;
A mensagem "Reprovado", se a média for menor do que sete;
A mensagem "Aprovado com Distinção", se a méd... | false |
807be92c31db9b6f6ad427831c60402ffae667c1 | felipeadner/python-brasil-exercicios | /estrutura-de-decisao/09decrescente.py | 1,012 | 4.21875 | 4 | """
Faça um Programa que leia três números e mostre-os em ordem decrescente.
"""
def decrescente():
a = float(input("Informe o 1º número: "))
b = float(input("Informe o 2º número: "))
c = float(input("Informe o 3º número: "))
if a > b and b > c:
print("Seus números em ordem dec... | false |
f4b85f8857a986d7296d14b644ae3b9bebd9e4d9 | ameru/cs-fundamentals-101 | /labs/lab5.py | 1,985 | 4.4375 | 4 | def is_lower(char) -> bool:
""" Determines if given character is lowercase.
Arguments:
char (bool): character that is either lowercase or uppercase
Returns:
boolean: True if lowercase, False if other
"""
if char >= 'a' and char <= 'z':
return True
else:
return Fa... | true |
c4b6568ee5aa7f320e47295b7ce8e4a6b2d5544e | UChicagoInterviewPrep/algos | /matrix/rotate_matrix.py | 1,153 | 4.28125 | 4 | def rotate_matrix(matrix):
# assuming square matrix
n = len(matrix)
'''
1 2 3 7 4 1
4 5 6 => 8 5 2
7 8 9 9 6 3
'''
# transposing matrix across diagonal line
for i in range(n):
for j in range(i+1, n):
tmp = matrix[i][j]
matrix[i][j] = matrix[j][i]... | false |
b0c7264f12b3d6afc931232a0cbbf0fe834fcb05 | nachande/PythonPrograms | /Max_NumberUsingFunction.py | 295 | 4.21875 | 4 | def largest_number(list):
max=list[0]
for number in list:
if number>max:
max=number
return max
numbers=[13,5,7,8,2,10,14,5,7,4]
print("Actual List:" ,numbers)
max_number=largest_number(numbers)
print ("Largest Number in list is:", max_number)
| true |
c2b20d07828890dacab6cd2e332c61074c1be23c | joeyviolacode/advent-of-code-2020 | /dec_3/dec3.py | 718 | 4.15625 | 4 | from dec3_input import hill, width, height
slope_0 = {"x": 1, "y": 1}
slope_1 = {"x": 3, "y": 1}
slope_2 = {"x": 5, "y": 1}
slope_3 = {"x": 7, "y": 1}
slope_4 = {"x": 1, "y": 2}
slope_list = [slope_0, slope_1, slope_2, slope_3, slope_4]
def find_slope(hill_map, slope):
x = 0
y = 0
tree_count = 0
while... | false |
01a336f2c934ecba449af75a5fbba1890b3f3fca | kildarev7507/CTI110 | /P4HW3_SumNumbers_VeronicaKildare.py | 697 | 4.34375 | 4 | # Program will add the sum of positive numbers entered by user.
# 7/9/19
# CTI-110 P4HW3 - Sum of Numbers
# Veronica Kildare
#
# Program will ask the user to enter positive numbers.
# Program will calculate positive numbers until user enter a negative number.
# Program will display the total of all numbers ent... | true |
55aaad972d7586a688d70f104acf64719caa9dfd | okoth-lydia/modcom | /lesson6/lesson7.py | 1,005 | 4.34375 | 4 | #inheritance
#one object can borrow properties/functions from another object
class Fish():
def __init__(self, name, weight, age):
self.name = name
self.weight = weight
self.age = age
def swim(self):
print("a fish can swim")
def swim_backwards(self):
print("it's m... | true |
d6f55c7a795a4839fddbb2d9d8ad9e5914ba10e9 | afausti/query_builder | /model/tree.py | 1,117 | 4.28125 | 4 | """
It has the data_structure Node and methods to facilitate the creation of trees.
"""
class Node(object):
"""
It represents the basic data structure of a tree.
"""
def __init__(self, data=None, level=0):
self.data = data
self.level = level
self.sub_nodes = []
def __repr_... | true |
f75d0dd9324cfdfe80d9cb09862655debd799fed | go-bears/python-study-group-puzzles | /brick_wall_sample.py | 2,854 | 4.875 | 5 | """
Brick Wall exercise:
Functions are used to isolate different small specific tasks.
Functions abstract action, grouping several actions as a single object, and then you group those actions to create more bigger and more advanced objects.
to
Goal: I've given you "starter functions" of that create different size... | true |
d28c2e044c4c0d4d6f7dec57f8f74c97c6c22ee5 | ZachMillsap/VS | /input_while_exit/input_while_exit/input_while_exit.py | 604 | 4.125 | 4 | '''Takes user inputs, check the sentinel, and addes them to a list. Then prints list'''
'''Also give a breakout in the inner while loop'''
n = int(input('Enter a number between 1 and 100 or -99 to stop.'))
list= []
exit = -99
min = 1
max = 100
while n != exit:
list.append(n)
while n < min or n > max:
n = int(input... | true |
43c389b1429650de486a64eef615ab931ad011de | PowerLichen/pyTest | /HW5_final/3.py | 1,371 | 4.25 | 4 | """
Project: draw polygon
Author: Minsu Choe
StudentID: 21511796
Date of last update: Apr. 5, 2021
"""
import turtle
import math
# draw polygon function
def drawPolygon(x,y,n,width):
# check polygon vertex number
if n<3:
return
# define turtle
t= turtle.Turtle()
# initialize turtle... | false |
f9be69b3acbd500a061ea22c846f2a22e52dba00 | PowerLichen/pyTest | /HW2/draw_circle.py | 495 | 4.5 | 4 | # Draw Circle
"""
Project: Draw Circle
Author: Minsu Choe
Date of last update: Mar. 12, 2021
"""
import turtle
# init
t=turtle.Turtle()
t.shape("turtle")
# define variable
print("===Draw Circle Program===")
start_x = float(input("input x = "))
start_y = float(input("input y = "))
radius = int(input("input rad... | false |
399193cb6c2595dfaa10fe444aa9ced1b243f0ae | PowerLichen/pyTest | /HW2/circle.py | 387 | 4.1875 | 4 | # Area and Circumference of Circle
"""
Project: Area and Circumference of Circle
Author: Minsu Choe
Date of last update: Mar. 12, 2021
"""
#define const value
PI = 3.141592
#define radius value
radius = int(input("input radius = "))
# calculate answer
area = radius * radius * PI
circumference = 2*radius*PI
# ... | true |
5c3b4f2b6f4e35a879d7b43256ab27561b528f20 | Raffipam12/Data-Analysis-with-Python3 | /Numpy_Statistics.py | 1,885 | 4.375 | 4 | ##################################### STATISTICS WITH NUMPY #######################################
# Statistics with Numpy
# Those are the different methos t calculate statistical properties of a dataset:
# -Mean
# -Median
# -Percentiles
# -Interquartile Range
# -Outliers
# -Standard Deviation
# The first statistica... | true |
43173c18d53c47c28154b7a4385f61c7a2b771b0 | mendesivan/Python-the-Basics | /Iterators.py | 1,028 | 4.34375 | 4 | # -*- coding: utf-8 -*-
# Technically, in Python, an iterator is an
# object which implements the iterator
# protocol, which consist of the methods
# __iter__() and __next__().
# Example 1 from a tuple
mytuple = ("apple", "banana", "cherry")
myit = iter(mytuple)
print(next(myit))
print(next(myit))
pri... | false |
f95944ee706588fd85079edf8db226d397542b02 | laubonesire/Portfolio | /Basics/controlflow.py | 454 | 4.25 | 4 | # Examples of control flow using Python
# Prints numbers 1 to 10 using a for loop
for i in range(1, 11):
print(i)
# Prints numbers 1 to 10 using a while loop
i = 1
while i <= 10:
print(i)
i += 1
# Compares the value of a and b using an if/elif/else statement
a = 10
b = 20
if a < b:
print("{} is less ... | true |
fbcf7fa3cb0ec22eaf652d3feaeb1445f999c4f8 | Amarix/cti110 | /M4T1_BugCollector_AllieBeckman.py | 893 | 4.25 | 4 | # A program that adds the amount of bugs collected per day for five days and displays
# a total at the end of the five days
# 6/15/2017
# CTI-110 M4T1 - Bug Collector
# Allie Beckman
while True:
totalBugs = 0
dayLeft = 5
dayOn = 1
while dayLeft > 0:
try:
totalBugs = totalB... | true |
437f0a21139996ef4ca62073c2e3e303cc4b58c3 | ericwhyne/MIDS0901 | /number_tree_optional_exercise.py | 1,370 | 4.15625 | 4 | #!/usr/bin/python
# Prints a christmas tree on the terminal made up of ascending and descending integers
# 2014 datamungeblog.com
import sys
import random
size = int(sys.argv[1]) # first argument is an integer which is the height of the tree
probability_green = .7 # how much of the tree will be green vs a random ornam... | true |
667b1f62ff3ac5909b77784018f4a4653e06a185 | shahbaazsheikh7/Learn-Python | /ex_9_2.py | 920 | 4.3125 | 4 | """Write a program that categorizes each mail message by which day of
the week the commit was done. To do this look for lines that start with “From”,
then look for the third word and keep a running count of each of the days of the
week. At the end of the program print out the contents of your dictionary (order
does... | true |
377e3aaa3b75b32f2a52b2f38075f6ba044d35ee | shahbaazsheikh7/Learn-Python | /revisionex7_2.py | 1,059 | 4.40625 | 4 | """Exercise 2: Write a program to prompt for a file name, and then read through the
file and look for lines of the form:
X-DSPAM-Confidence:0.8475
When you encounter a line that starts with “X-DSPAM-Confidence:” pull apart
the line to extract the floating-point number on the line. Count these lines and
then comput... | true |
38598e1f4f5ce19800be9b20c7d0a584078bc6f4 | shahbaazsheikh7/Learn-Python | /revisionex9_2.py | 647 | 4.21875 | 4 | """Write a program that categorizes each mail message by which day of
the week the commit was done. To do this look for lines that start with “From”,
then look for the third word and keep a running count of each of the days of the
week. At the end of the program print out the contents of your dictionary (order
does... | true |
6a04f434a0d90beba779c8845ac14f1ddca49d4a | shahbaazsheikh7/Learn-Python | /revisionex5_2.py | 532 | 4.25 | 4 | """Write another program that prompts for a list of numbers
as above and at the end prints out both the maximum and minimum of
the numbers instead of the average."""
max = None
min = None
while True:
num = input("Enter the number: ")
if(num == "done"):
break
try:
numi = int(num... | true |
2d1e0f35150c9aa4af7f2458386d69172f5b4422 | shahbaazsheikh7/Learn-Python | /ex_9_5.py | 859 | 4.3125 | 4 | """This program records the domain name (instead of the address) where
the message was sent from instead of who the mail came from (i.e., the whole email
address). At the end of the program, print out the contents of your dictionary.
python schoolcount.py
Enter a file name: mbox-short.txt
{'media.berkeley.edu': 4,... | true |
e43bce7ecd15bec2705a64c055d87197add8f8f5 | sbobbala76/Python.HackerRank | /2 - Data Structures/2 - Linked Lists/6 - Print in Reverse.py | 434 | 4.15625 | 4 | """
Print elements of a linked list in reverse order as standard output.
Head could be None as well for empty list.
"""
from . import Node
def print_reverse_iterative(head):
if head:
stack = [head]
while stack[-1].next:
node = stack[-1]
stack.append(node.next)
while stack:
node = stack.pop()
print(... | true |
49216354dc668bca433a1ee313daa1f3a1ec2fc4 | miguelvelezmj25/coding-interviews | /python/euler-project/problem4.py | 1,254 | 4.28125 | 4 | """
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers
is 9009 = 91 * 99.
Find the largest palindrome made from the product of two 3-digit numbers.
"""
def main():
# List of all palindromes
palindromes = []
x = 1
y = 1
# While x is... | true |
5d7df64e4c3ca726b6605923d6c734657cedc345 | alu-rwa-dsa/implementations-Zubrah | /Week 8/Question_3.py | 944 | 4.1875 | 4 | """
The time Complexity to run the algorithm is O(n) as it moves through all the nodes and count the
levels associated with them
The Space complexity will be O(1) as it doesn't add anything the overall memory.
"""
# define a binary tree node
class Node:
# Constructor for data
def __init__(self, data... | true |
5fb9d92f1b15088e05576b3b988ce480c40d152e | nshefeek/udacity | /P0/Task4.py | 1,225 | 4.15625 | 4 | """
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
texts_sender = set()
texts_receiver = set()
for i in range(len(texts)):
texts_sender.add(texts[i][0])
texts_receiver.add(... | true |
1e5b97d55031b8c0378549ec0668c8a05adeaf20 | SerhiiTkachuk/Softserve-Internship | /Elementary Tasks/task2.py | 1,560 | 4.40625 | 4 | ''' Analysis of envelopes
There are two envelopes with sides (a, b) and (c, d) to determine if one envelope can be nested inside the other.
The program must handle floating point input. The program asks the user for the envelope sizes one parameter at a time.
After each calculation, the program asks the user if he want... | true |
ff9156316bf2bdde0a12ad340210151fe053640c | billwurles/apps-in-general | /python/Employees/main.py | 2,938 | 4.125 | 4 | __author__ = 'Will'
from staff import *
database = Staff()
def menuInput():
valid=['A','R','I','D','S','L','Q','a','r','i','d','s','l','q']
ok = False
while not ok:
choice=input('Enter the command you would like to run: ')
if choice in valid:
if len(choice) == 1:
... | true |
9cd501fea212ea2fdf905d4ef63007db5486b444 | dbrak/rpi_scripts | /Graphics/Dot_Game/Turtle_Chase_method.py | 1,347 | 4.21875 | 4 | #!/usr/bin/env python
import random
import time
import turtle
d = 80
t = turtle.Turtle()
t.pensize(10)
t.speed(0)
t.color('blue')
t.shape("turtle")
wn = turtle.Screen()
wn.bgcolor("black")
#wn.title(" ")
t2 = turtle.Turtle()
t2.pensize(10)
t2.speed(10)
t2.color('red')
t2.shape("circle")
t2.goto(-100,-100)
t3... | false |
a09569c79f0485d2f8f5ad6db42e595ab183b469 | NiramayThaker/N-Queen | /n_queen_(n x n)/NQueen_backtracking_advance.py | 2,468 | 4.15625 | 4 | import copy
import random
def board_size_input():
# Taking user input for the size of the board
while True:
# Using try except to give multiple chance to user for input if entered wrong
try:
chess_board_size = int(input('Enter the size of chessboard (chess_board_size) -> '))
... | true |
402e4368764e8f9f0e27bd3188bd106dcc18bcd8 | AamodPaud3l/python_assignment_dec15 | /cubeandappendlist.py | 341 | 4.53125 | 5 | #Program to cube each elements in a list and append it to another list
list = [1,2,4,4,3,5,6]
def cube_list(arbitary_list):
new_list = []
for each in arbitary_list:
each = each ** 3
print(each)
new_list.append(each)
new_list1 = [7,8,9]
new_list.append(new_list1)
print(new_li... | true |
959d371a52cb965cecd013cc6915c60dc7578adf | seema1711/My100DaysOfCode | /Day 3/linkedListAtTheEnd.py | 1,172 | 4.3125 | 4 | ''' This involves pointing the next pointer of the current last node of the linked list to the
new data node. So, the current last node of the linked list becomes the second last data node &
the new node becomes the last node of the LL.
'''
### LINKED LIST INSERTION AT THE END ###
class Node:
def __init__(self,da... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.