blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
c528ece8650c68ce80f1141af1f1903ef7e1ed70 | ccrain78990s/Python-Exercise | /0317 資料定義及字典/0317-2-list資料定義.py | 2,076 | 4.34375 | 4 | #0317 CH7 資料定義
print("===append===")
list1=[3,1,2]
print(list1)
list1.append(100) #<----添加資料到陣列最後面
print(list1)
list1.append(2197)
print(list1)
print("===extend===")
list2=[2,1,3]
print(list2)
list2.extend([10]) #<----添加 " 矩陣 " 資料到陣列最後面
print(list2)
list2.extend([21,97])
print(list2)
print("===i... | false |
716d36f828edf84625bcaceec67f7a5d0d024815 | jwhitenews/computers-mn | /tk/Snowmobiles.py | 1,761 | 4.15625 | 4 | import sqlite3
from tkinter import *
def create_table():
#connect to db
conn = sqlite3.connect("lite.db")
#create cursor object
cur = conn.cursor()
#write an SQL query
cur.execute("CREATE TABLE IF NOT EXISTS store (item TEXT, quantity INTEGER , price REAL )")
#commit changes
conn.com... | true |
884ee0304f568e8137f23722bba533df504703d3 | DsDoctor/Basic-python-program | /Offer/q3_duplicate_nums.py | 2,027 | 4.125 | 4 | """
在一个长度为n的数组里的所有数字都在0~n-1范围内。数组中某些数字是重复的,
但不知道有个数字重复了,也不知道每个数字冲了了几次。
请找出数组中任意一个重复的数字。
例如输入长度为7的数组[2,3,1,0,2,5,3],那么对应的输出是重复的数字2或者3。
"""
import doctest
def q3_1(lis):
"""
>>> q3_1([2,3,1,0,2,5,3])
2
>>> q3_1([])
Empty List!
>>> q3_1([2, 2, 2, 2, 2])
2
>>> q3_1([3, 2, 3])
Length Er... | false |
5ff39f24214038947d4da34accd9dcc9b6db1ba8 | Worros/2p2-Euler-Project | /problem-1/Sorrow/solution.py | 473 | 4.15625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Problem 1
#
# If we list all the natural numbers below 10 that are multiples of 3 or 5, we
# get 3, 5, 6 and 9. The sum of these multiples is 23.
# Find the sum of all the multiples of 3 or 5 below 1000.
i = 3
MAX = 1000
max_count = MAX - 1
trees = set()
fives = se... | true |
91071429cfce206297f39f3a2d7f485d6f5bcf65 | brenddesigns/learning-python | /_ 11. Dictionaries/dictionaries.py | 858 | 4.28125 | 4 | # Project Name: Dictionaries
# Version: 1.0
# Author: Brendan Langenhoff (brend-designs)
# Description: Using the Dictionary data type which is similar to arrays, but works with keys and values instead of indexes.
# Define an empty Dictionary
phonebook = {}
# Storing values using specific keys, so we may retrieve the... | true |
6f4ecce8aeddcb4bbfe6c115eeb52022d85741f2 | sarohan/project_euler | /3-largest-prime-factor.py | 371 | 4.125 | 4 | def prime_factors(n):
i = 2
factors = []
while i*i <= n:
if n % i :
i = i+1
else:
n = n // i
factors.append(i)
if n > 1:
factors.append(n)
return factors
def accept():
num = int(input("Enter number to find prime factor : "))
print(... | false |
cfb0ed3a10794d7c2fa82e2669523b595e49d3ab | ugwls/PRACTICAL_FILE | /5.py | 1,010 | 4.21875 | 4 | # Count and display the number of vowels,
# consonants, uppercase, lowercase characters in string
def countCharacterType(s):
vowels = 0
consonant = 0
lowercase = 0
uppercase = 0
for i in range(0, len(s)):
ch = s[i]
if ((ch >= 'a' and ch <= 'z') or
(ch >= 'A' and ch... | true |
25baca22cd8baab76c4511dc09e631f0ecd4b662 | ugwls/PRACTICAL_FILE | /21.py | 415 | 4.3125 | 4 | # WAP to input employee number and name for ‘N’
# employees and display all information in ascending
# order of their employee number
n = int(input("Enter number of Employee: "))
emp = {}
for i in range(n):
print("Enter Details of Employee No.", i+1)
Empno = int(input("Employee No: "))
name = input("Name: ... | true |
21a79559ef6a4ec719b68c5d690eddc9e5e83160 | ugwls/PRACTICAL_FILE | /35.py | 2,083 | 4.1875 | 4 | # Write a menu driven program to add and manipulate data
# from customer.csv file. Give function to do the following:
# 1.Add Customer Details, 2.Search Customer Details
# 3.Remove Customer Details
# 4.Display all the Customer Details, 5.Exit
import csv
def add():
with open('customer.csv', 'w', newline='') as f... | true |
8196c34bf0cf65826cbd5af81f712f2980577a92 | ugwls/PRACTICAL_FILE | /4.py | 523 | 4.125 | 4 | # Compute the greatest common divisor and least
# common multiple of two integers.
def gcd(x, y):
while y > 0:
x, y = y, x % y
return x
def lcm(x, y):
lcm = (x*y)//gcd(x, y)
return lcm
k = True
while k == True:
x = int(input('Enter a number: '))
y = int(input('Enter a number: '))
... | true |
6fb0b3831d5b56eb05d39b30df7b4634a091eb8a | maxxymuch/gbpy20 | /les01/hw03.py | 1,076 | 4.3125 | 4 | # Урок 1. Введение в алгоритмизацию и реализация простых алгоритмов на Python
# 3. По введенным пользователем координатам двух точек вывести уравнение прямой вида y=kx+b, проходящей через эти точки.
while (1):
first_point = input('Введите через запятую координаты x,y первой точки : ')
second_point = input('Вве... | false |
faa07e9618a4d07bc4ad932f63d0f6ea9989d167 | maxxymuch/gbpy20 | /les01/hw01.py | 2,503 | 4.3125 | 4 | # Урок 1. Введение в алгоритмизацию и реализация простых алгоритмов на Python
# 1. Найти сумму и произведение цифр трехзначного числа, которое вводит пользователь.
################################## Вариант 1 #########################################
while (1):
try:
user_input = int(input('Введите трехзнач... | false |
0da6d8a6bb0c7b06615a622583759ca646112f7f | motoko2045/python_masterclass | /f_strings.py | 447 | 4.1875 | 4 | # you cannot concatenate a string and a number
# in comes f strings (you don't have to use the format function)
greeting = "oy!"
age = 23
name = "charlie"
print(age)
print(type(greeting))
print(type(age))
age_in_words = "2 years"
print(name + f" is {age} years old")
print(type(age))
print(f"Pi is approximately {22 ... | true |
c93e5d825a3e7a5d94dca656b4c9e22dacf7bba0 | motoko2045/python_masterclass | /s3_lecture2.py | 1,328 | 4.40625 | 4 | # escape character portion of lecture
splitString = "this string has been\nsplit over\nseveral\nlines"
print(splitString)
# note the \n for new line between words
tabbedStr = "1\t2\t3\t4\t5"
print(tabbedStr)
# using the escape to use only one type of quote
print('the pet shop owner said "no, no, he\'s uh, ... he\'s ... | true |
4d17f656c66cda50889096e334b0887a4f1cd21c | glingden/Machine-Learning | /Regression_line_fit.py | 2,844 | 4.21875 | 4 | """"
Authur: Ganga Lingden
This is a simple demonstration for finding the best regression line
on the given data points. This code provides 2d interative regression
line plot.
Given equation: y = ax + b. After solving the derivatives of the loss
function- MES w.r.t 'a' and 'b', the value of 'a' and 'b' are found as
fo... | true |
df62030a1249a201a21335ab9f94006bfac6463f | Sarefx/Dates-and-Times-in-Python | /Let's Build a Timed Quiz App/time_machine.py | 1,424 | 4.25 | 4 | # my solution to the Simple Time Machine challenge/exercise in Let's Build a Timed Quiz App
# the challenge: Write a function named delorean that takes an integer. Return a datetime that is that many hours ahead from starter.
import datetime
starter = datetime.datetime(2015, 10, 21, 16, 29)
def delorean(integer):
... | true |
97d0d2120b76fc91f4dc0124e7608ba070b85076 | AdamC66/01---Reinforcing-Exercises-Programming-Fundamentals | /fundamentals.py | 1,377 | 4.40625 | 4 | import random
# from random import randrange
# Exercise 1
# Create an emotions dict, where the keys are the names of different human emotions and the values are the degree to which the emotion is being felt on a scale from 1 to 3.
# Exercise 2
# Write a Person class with the following characteristics:
# name (string)... | true |
fd5a819c0ff4c27e929adcae1dac025d87c45d5c | sunjinshuai/Python | /Code/nested_loop.py | 568 | 4.15625 | 4 | # Python 语言允许在一个循环体里面嵌入另一个循环。
# Python for 循环嵌套语法:
# for iterating_var in sequence:
# for iterating_var in sequence:
# statements(s)
# statements(s)
# Python while 循环嵌套语法:
# while expression:
# while expression:
# statement(s)
# statement(s)
# 以下实例使用了嵌套循环输出2~100之间的素数:
i = 2
while(i < 100):
... | false |
d0bbea6d2de955a86244d220f6d2a1ff7c659004 | ashish-bisht/must_do_geeks_for_geeks | /stack/python/parentheseis.py | 485 | 4.1875 | 4 | def valid_parentheses(string):
stack = []
brackets = {"(": ")", "{": "}", "[": "]"}
for ch in string:
if ch not in brackets:
if not stack:
return False
cur_bracket = stack.pop()
if not brackets[cur_bracket] == ch:
return False
... | true |
6a9b1f3952572d73b05af1e42cb948906234a816 | karam-s/assignment_1 | /Q2.py | 460 | 4.125 | 4 | while 1:
decimal_num = int(input("enter a decimal numbe: "))
pout=decimal_num
if decimal_num==-1:
break
binary_num = []
while decimal_num!=0:
y= decimal_num %2
binary_num.append(y)
decimal_num=decimal_num//2
binary_num.reverse()
prin... | false |
490c73c4444ccdcbbe02b825d0bbe159264fc9e2 | karam-s/assignment_1 | /Q1-E.py | 345 | 4.1875 | 4 | L=["Network" , "Math" , "Programming", "Physics" , "Music"]
length = []
for i in L:
x =len(i)
length.append(x)
the_longest_item=max(length)
the_index_for_the_longest_item=length.index(the_longest_item)
print ("the longest item in list is "+str(L[the_index_for_the_longest_item])+"\
And its length "+s... | true |
6ee7ed7a04cfcb5325f58bf60d4ad2fd367f6860 | Naganandhinisri/python-beginner | /hacker_rank/palindrome.py | 233 | 4.28125 | 4 | word = "12345"
new_word = "54321"
sorted_word = sorted(word)
new_sorted_word = sorted(new_word)
if sorted_word == new_sorted_word:
print('the given string is palindrome')
else:
print('The given string is not palindrome')
| true |
4920a9b8776f24f142025fcd3d50170a2fd21f65 | Naganandhinisri/python-beginner | /test3/sorted_number.py | 337 | 4.125 | 4 | def sort_numbers():
number = "687"
sorted_number = ''.join(sorted(number))
rev_sorted_number = ''.join(reversed(number))
if number == sorted_number:
return 'Ascending Order'
elif sorted_number == rev_sorted_number:
return 'descending order'
else:
return 'neither'
print... | true |
7bd1794f73990e131743cf4ea47cd86d51f9b893 | Chanchal1603/python-gs-eop | /day-2/create-container.py | 752 | 4.40625 | 4 | """
A professor asked Lisha to list up all the marks in front of her name but she doesn't know how to do it.
Help her to use a container that solves this problem.
Input Format
First line of input contains name Next three lines contains marks of a student in three subjects.
Constraints
type(marks) = int
Output For... | true |
e4c2cbd32810a0d7d8720d6d53c27e55e738632c | theburningmonk/IntroductionToAOP | /AopDemo/AopDemo.DynamicLanguage/Demo.py | 749 | 4.28125 | 4 | class Person:
"""A simple class representing a person"""
def __init__(self, name, age):
self.name = name
self.age = age
def say_hello(self):
print "Hello, my name is {}, I'm {} years old".format(self.name, self.age)
def say_goodbye(self, recipient):
print "Good bye, {}"... | false |
b7f96b7a47d1b99f5a0e62e7d2979e127a7759d4 | rikudo765/algorithms | /lab7/aud/7.1-4.py | 1,805 | 4.28125 | 4 | """
Реалізуйте підпрограми сортування масиву.
"""
def bubble_sort(array):
""" Сортування "Бульбашкою"
:param array: Масив (список однотипових елементів)
"""
n = len(array)
for i in range(n - 1, 0, -1):
for j in range(i):
if array[j] > array[j + 1]:
array[j], arr... | false |
493f7024a4af67c7cd527dc824aa596beb60f9d4 | RinatStar420/programming_training | /lesson/call_twice.py | 697 | 4.34375 | 4 | """
Вам предстоит реализовать функцию call_twice(), которая должна
принять функцию и произвольный набор аргументов для неё,
вызвать функцию с заданными аргументами дважды,
вернуть пару из результатов вызовов (первый, затем второй).
call_twice(input, 'Enter value: ')
Enter value: foo
Enter value: barc
('foo', 'bar')
""... | false |
398b6bb3187a835deda3719fddc5520eedf6f82b | dinohadzic/python-washu-2014 | /hw3/merge_sort.py | 801 | 4.1875 | 4 | def merge_sort(list):
if len(list) <= 1: #If the length of the input is 1, simply return that value
return list
else:
mid = len(list)/2
left = list[:mid]
right = list[mid:]
left = merge_sort(left)
right = merge_sort(right)
sorted_list = []
i = 0
j = 0
while i < len(left) and j < len(r... | true |
7e3d9d503c9e92294fdb49f18f03399f12f60412 | scottherold/python_refresher_2 | /iterators.py | 403 | 4.3125 | 4 | # Create a list of items (you may use either strings or numbers)
# then create an iterator using the iter() function.
# Use a for loop to loop "n" times, where n is the number of items in
# your list. Each time round the loops, use next() on your list to
# to print the next item
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, ... | true |
9e0925d29868d5406da243e131f388c8331794d4 | yanil3500/data-structures | /src/stack.py | 1,022 | 4.25 | 4 | """
implementation of a stack
"""
from linked_list import LinkedList
class Stack(object):
def __init__(self, iterable=None):
if type(iterable) in [list, tuple, str]:
self._container = LinkedList(iterable=iterable)
elif iterable is None:
self._container = LinkedList()
... | true |
185d672f79d2297615e67163751c153da825f113 | Gloamglozer/PythonScripts | /Sixthproblem.py | 1,905 | 4.125 | 4 | """
LEGENDARY SIXTH PROBLEM
https://www.youtube.com/watch?v=Y30VF3cSIYQ
This is a quickly made script which visualizes a small grid containing solutions to the equation
given in the legendary sixth problem
something something vieta jumping
"""
from math import sqrt
import numpy
print("Legendary sixth probl... | true |
a76b154bd030a73cf6c509e47f2b3dcdadfbbadf | ryhanlon/legendary-invention | /labs_Fundaments/pig-latin/pig-latin-func.py | 845 | 4.125 | 4 | """
This file was writting by Rebecca Hanlon
Changing an English word into Pig Latin.
"""
def ask_word():
# asking for word
word = input("Let's speak some Pig Latin! Input one word. >> ")
vowels = "aeiou"
# Get first letter.
first_letter = word[0]
if first_letter in vowels:
# Cuts off... | false |
97f8053fb78f12d76ea006aeb506c97112867ce9 | ryhanlon/legendary-invention | /labs_Functional_Iteration/functions_2/functions_2.py | 1,291 | 4.125 | 4 | """
>>> combine(7, 4)
11
>>> combine(42)
42
>>> combine_many(980, 667, 4432, 788, 122, 9, 545, 222)
7765
>>> choose_longest("Greg", "Rooney")
'Rooney'
>>> choose_longest("Greg", "Rooney", "Philip", "Maximus", "Gabrielle")
'Gabrielle'
>>> choose_longest("Greg", [0, 0, 0, 0, 4])
[0, 0, 0, 0, 4]
"""
def combine(n... | true |
a263ae4127db5b6cccfb196958a8be667938bf86 | ryhanlon/legendary-invention | /labs_Functional_Iteration/distance_converter/distance-converter.py | 1,666 | 4.375 | 4 | """
This file is written by Rebecca Y. Hanlon.
"""
# catch input errors, refactor, add additional units
def converter():
input_distance = int(input("Enter distance: "))
input_unit = input("Enter units (m, km, ft, mi): ")
target_unit = input("Enter target units (m, km, ft, mi): ")
m_to_meters = in... | false |
46279bcd5591db4fedaa49e964e950459732ad6e | ryhanlon/legendary-invention | /labs_Fundaments/simple_converter.py | 319 | 4.15625 | 4 | """
This is a file written by Rebecca Hanlon
Ask for miles and then convert to feet.
"""
def question(miles):
'''
Ask for # of miles, then converts to feet.
'''
result = miles * 5280
print(f"You walk {result} feet everyday.")
answer = int(input("How many miles do you walk everyday? "))
question(... | true |
33cadac1f1ea635e2b0a1595391887ae892421dc | AndersonTorres1993/jogo-da-forca | /Aula31/aula31.py | 747 | 4.15625 | 4 | '''
Formatando valores modificados - Aula 5
:s - Texto (strings)
:d - Inteiros (int)
:f - Números de ponto flutuante ( float)
:.(NÚMERO)f - Quantidade de casas decimais ( float)
:(CARACTERE)(>ou < ou ^) ( QUANTIDADE)( TIPO - s,d ou f)
> - Esquerda
< - Direita
^ - Centralizar
'''
'''num_1 = 10
num_2 = 3
divisao= num... | false |
fa927006a4537ae68cb0c52a9f158bfd05a4f00d | HanChen1988/BookExercise_02 | /Chapter_07/Page_100/even_or_odd.py | 553 | 4.28125 | 4 | # -*- coding: utf-8 -*-
# @Time : 2020/4/12 3:20 下午
# @Author : hanchen
# @File : even_or_odd.py
# @Software: PyCharm
# ------------------ example01 ------------------
# 判断一个数是奇数还是偶数
number = input("Enter a number, and I'll tell you if it's even or odd: ")
number = int(number)
if number % 2 == 0: # 求模运算符(%),它将两个数相除... | false |
7234c896215dfc924ba7bbea68817de5b7df8fe9 | ragavanrajan/Python3-Basics | /breakContinue.py | 823 | 4.21875 | 4 | student_names = ["Mike", "Bisset", "Clark","Ragavan"]
# imagine if you have 1000 list in array it will not execute once the match is found
for name in student_names:
if name == "Bisset":
print("Found him! " + name)
print("End of Break program")
break
print("currently testing " + name)
... | true |
ff511ef0763e5e4616a3339185553599a642fa09 | begora/apuntespython | /Ej_.varios.py | 635 | 4.1875 | 4 | #numero1=int(input("Introduce un número"))
#numero2=int(input("Introduce otro número"))
#numero3=int(input("Introduce otro"))
#
#def devuelveMax():
# if numero1>numero2 & numero2>numero3:
# print (numero1)
# elif numero2>numero1 & numero1>numero3:
# print(numero2)
# else:
# print(numero3)
... | false |
870ecf814b003df11af879f0c0456862215060c4 | pooja-pichad/dictionary | /saral4.py | 800 | 4.375 | 4 | # Ek program likhiye jo ki nested dictionary me se first key or value ko remove kare.
# Example :- Input :- Output :-
# output
# Dic= {
# 1: 'NAVGURUKUL',
# 2: 'IN',
# 3:
# { 'B' : 'To',
# 'C' : 'DHARAMSALA'
# }
# }
# people= {
# 1: 'NAVGURUKUL',
# 2: 'IN',
#... | false |
29fc112780357814e8accdd1364d97e140f44245 | delio1314/sort | /bubble-sort/python/bubble-sort.py | 422 | 4.28125 | 4 | #!/usr/bin/python
#coding:utf8
def bubbleSort(list):
i = 0
ordered = False
while i<len(list)-2 and not ordered:
ordered = True
j = len(list)-1
while j > i:
if list[j] < list[j-1]:
ordered = False
temp = list[j]
list[j] = list[j-1]
list[j-1] = temp
j-=1
i+=1
list = [4, 1, 2, 9, 6, 5, ... | true |
36e6d43c0be830348c682e2f051b867e4cf9ace1 | raioliva21/Taller-N-1 | /ex07.py | 1,446 | 4.1875 | 4 | """
Ejercicio 7
El buen gordito” ofrece hamburguesas sencillas, dobles y triples, las cuales tienen un costo de $2000,
$2500 y $3000 respectivamente. La empresa acepta tarjetas de cr ́edito con un cargo de 5 % sobre la
compra. Suponiendo que los clientes adquieren solo un tipo de hamburguesa, realice un algoritmo para... | false |
6a2c642ee5c77a77dca94e5360300880ce93ec9a | 27fariha/Python1903F1 | /ListComprehension.py | 1,082 | 4.21875 | 4 | #syntax : [expression(variable) for item in list]
#example 1
fruits=["Apple","Banana","Watermelon","Kiwi","Cherry"]
for x in fruits:
print(x)
# with compre
new_List=[x for x in fruits]
print(new_List)
#Example -2
#simple
letter=['A','B','C','D','E','F']
letter.append("abc")
for x in 'Human':
letter.append(... | false |
0a1c54a2598a6a04a890993e959122f053439313 | nandhinik13/Sqlite | /select.py | 390 | 4.1875 | 4 | import sqlite3
conn = sqlite3.connect("data_movies")
cur = conn.cursor()
#selects the record if the actor name is ajith
query = "select * from movies where actor='Ajith'"
cur.execute(query)
#fetchall fetches all the records which satisfies the condition
data = cur.fetchall()
print("type of data is :... | true |
1b449bced7c40519774de41684941e1acbdcc02d | m-junaidaslam/Coding-Notes | /Python/decorators.py | 2,160 | 4.25 | 4 | # decorators.py
# Just important attributes of object(function "add" in this case)
# add : physical memory address of function
# add.__module__: defined in which module
# add.__defaults__: what default values it had
# add.__code__.co_code: byte code for this add function
# add.__code__.co_... | true |
e371094c000056f90580b37925467171a4a70cb6 | raj9226/rk | /sesion3a.py | 210 | 4.28125 | 4 | #assignment operator
num1=10 #write operation /update operation
num1=5
num2=num1 #copy operation/referrence copy
#num1=num1+10
num1 += 5
print(num1)
# *=,/=,//=,**=
num1 **=2
num1 //=2
print(num1) | false |
4a88628231baaef87a2cc2c333bde75cc370067b | programiranje3/2020 | /python/sets.py | 1,176 | 4.4375 | 4 | """Demonstrates sets
"""
def demonstrate_sets():
"""Creating and using sets.
- create a set with an attempt to duplicate items
- demonstrate some of the typical set operators:
& (intersection)
| (union)
- (difference)
^ (disjoint)
"""
the_beatles = {'John', 'Paul',... | true |
c02d56bd3bffe56f87326121d368f8a5978f7d1a | accus84/python_bootcamp_28032020 | /moje_skrypty/nauka/02_funkcje/007_funkcje.py | 1,796 | 4.15625 | 4 | #lambda x: x....
#lambda umożliwia operacje na samym sobie
kolekcja = [(10, "z"), (5, "c"), (15, "a")]
#sortowanie po drugim elemencie czyli 5,10,15
def first(x):
return x[0]
def second(x):
return x[1]
#sortowanie po pierwszym elemencie czyli 5,10,15
print(first(kolekcja)) #(10,... | false |
b9f683c78b4ab99a53b561f8268a0cc95d39776d | alshayefaziz/comp110-21f-workspace | /exercises/ex02/fortune_cookie.py | 1,507 | 4.15625 | 4 | """Program that outputs one of at least four random, good fortunes."""
__author__ = "730397680"
# The randint function is imported from the random library so that
# you are able to generate integers at random.
#
# Documentation: https://docs.python.org/3/library/random.html#random.randint
#
# For example, consider t... | true |
2b32a6ef5be1b97a3a5a8fb14df6929c0e1de254 | alshayefaziz/comp110-21f-workspace | /lessons/data_utils.py | 1,254 | 4.25 | 4 | """Some helpful utility functions for working with CSV files."""
from csv import DictReader
def read_csv_rows(filename: str) -> list[dict[str, str]]:
"""Read the rows of a csv into a 'table'."""
result: list[dict[str, str]] = []
# Open ahandle to the data file
file_handle = open(filename, "r", e... | true |
a0b1b9a6082b26cdb54174c9c24fa63687c5ab66 | alshayefaziz/comp110-21f-workspace | /exercises/ex05/utils.py | 1,614 | 4.21875 | 4 | """List utility functions part 2."""
__author__ = "730397680"
def only_evens(even: list[int]) -> list[int]:
"""A function that returns only the even values of a list."""
evens: list[int] = list()
if len(even) == 0:
return evens
i: int = 0
while i < len(even):
item: int = even[i]
... | true |
d25b2e03c3dbbde0adaf951479bb747130c54a5b | grahamRuttiman/practicals | /exceptions.py | 614 | 4.46875 | 4 | try:
numerator = int(input("Enter the numerator: "))
denominator = int(input("Enter the denominator: "))
fraction = numerator / denominator
except ValueError:
print("Numerator and denominator must be valid numbers!")
except ZeroDivisionError:
print("Cannot divide by zero!")
print("Finished.")
# QUESTIONS:
# 1. A V... | true |
8b0196b9cd8643a516730276f084afc249ce8b8e | dfm066/Programming | /ProjectEuler/Python/latticepath.py | 369 | 4.15625 | 4 | def lattice_path(n):
list = []
list.append(1)
for i in range(1,n+1):
for j in range(1,i):
list[j] += list[j-1]
list.append(list[-1]*2)
return list[-1]
def main():
size = int(input("Enter Grid Size : "))
path_count = lattice_path(size)
print("Total Poss... | false |
9d7f4a745fb024199bcc0be0bd89542931aea90a | ohiosuperstar/Meow | /meow.py | 755 | 4.15625 | 4 | import string
def isCaps(word):
for letter in word:
if letter in string.ascii_lowercase:
return False
return True
str = input('Give me a string, mortal: ')
out = ''
str = str.split()
for word in str:
meowDone = False
for symbol in word:
if symbol not in string.ascii_letter... | true |
37c535b3f96153785af441fe876b7d0524d69511 | PyStyle/LPTHW | /EX20/ex20.py | 1,249 | 4.3125 | 4 | from sys import argv
# adding a module to my code
script, input_file = argv
# create a function to display an entire text file,
# "f" is just a variable name for the file
def print_all(f):
print f.read()
# dot operator to use the read function
# create a function to go to beginning of a file (i.e. byte 0)
def re... | true |
7a598699e2e43fa3ee4f7fb2d0ba971e6c68fdbe | mhdaimi/Python-Selenium | /python_basics/data_type_dictionary.py | 457 | 4.28125 | 4 | # Dictionary stores a key:value pair
city_pincode = {"Pune": 411014, "Mumbai": 400001, 100011:"Delhi"}
print("Pincode of Pune is {}".format(city_pincode["Pune"]))
print("Size of dictionary -> {}".format(len(city_pincode)))
#Add new key:value pair
city_pincode["Aurangabad"] = 431001
print(city_pincode)
#Update value... | false |
6943815ec00b9a7fc6885b1aff1cd3568b86a488 | mhdaimi/Python-Selenium | /python_basics/concatenation.py | 832 | 4.34375 | 4 | print("Welcome to " + "Python learning")
name = "Python 3.8"
print("We are learning " + name)
print("We are learning Python", 3.8)
name = "Python"
version = "3.8" #Version as string
print("We are using version " + version + " of " + name )
# Plus(+) operator works only with 2 strings
name = "Python"
version = 3.8 ... | true |
93e0dca5501fe5aabf2d2b3c216bc152c02438e1 | DeanHe/Practice | /LeetCodePython/MinimumAdditionToMakeIntegerBeautiful.py | 1,690 | 4.3125 | 4 | """
You are given two positive integers n and target.
An integer is considered beautiful if the sum of its digits is less than or equal to target.
Return the minimum non-negative integer x such that n + x is beautiful. The input will be generated such that it is always possible to make n beautiful.
Example 1:
Inpu... | true |
be719ca69d88a89af3bb9f354e1c77021338ccf2 | DeanHe/Practice | /LeetCodePython/MaximumXORAfterOperations.py | 1,588 | 4.46875 | 4 | """
You are given a 0-indexed integer array nums. In one operation, select any non-negative integer x and an index i, then update nums[i] to be equal to nums[i] AND (nums[i] XOR x).
Note that AND is the bitwise AND operation and XOR is the bitwise XOR operation.
Return the maximum possible bitwise XOR of all elements o... | true |
d41b7798d86f4d8806d6fd96ceb97baace6604d0 | DeanHe/Practice | /LeetCodePython/ValidParenthesisString.py | 1,253 | 4.25 | 4 | """
Given a string s containing only three types of characters: '(', ')' and '*', return true if s is valid.
The following rules define a valid string:
Any left parenthesis '(' must have a corresponding right parenthesis ')'.
Any right parenthesis ')' must have a corresponding left parenthesis '('.
Left parenthesis '... | true |
0b296ace36871717597aeb6153f07e7f0449ace6 | DeanHe/Practice | /LeetCodePython/PalindromePartitioning.py | 939 | 4.15625 | 4 | """
Given a string s, partition s such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s.
A palindrome string is a string that reads the same backward as forward.
Example 1:
Input: s = "aab"
Output: [["a","a","b"],["aa","b"]]
Example 2:
Input: s = "a"
Output: [["... | true |
fbaa5c030a51d6dff0dea8f50f15d6c8fb152b13 | DeanHe/Practice | /LeetCodePython/OddEvenLinkedList.py | 1,259 | 4.15625 | 4 | """
Given the head of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return the reordered list.
The first node is considered odd, and the second node is even, and so on.
Note that the relative order inside both the even and odd groups should remain as it... | true |
a69d0974b8aaa8cbcb4feec4161756a793b5de90 | DeanHe/Practice | /LeetCodePython/LargestRectangleInHistogram.py | 1,209 | 4.1875 | 4 | """
Given an array of integers heights representing the histogram's bar height where the width of each bar is 1, return the area of the largest rectangle in the histogram.
Example 1:
Input: heights = [2,1,5,6,2,3]
Output: 10
Explanation: The above is a histogram where width of each bar is 1.
The largest rectangle is s... | true |
e7e281750a240d1fd64d121b218d4d4aa036d833 | DeanHe/Practice | /LeetCodePython/ReconstructItinerary.py | 1,653 | 4.40625 | 4 | """
You are given a list of airline tickets where tickets[i] = [fromi, toi] represent the departure and the arrival airports of one flight. Reconstruct the itinerary in order and return it.
All of the tickets belong to a man who departs from "JFK", thus, the itinerary must begin with "JFK". If there are multiple valid... | true |
cf15cecb8c0a3143bb30877307a6cf62f7f91a29 | DeanHe/Practice | /LeetCodePython/RaceCar.py | 1,867 | 4.25 | 4 | """
Your car starts at position 0 and speed +1 on an infinite number line. Your car can go into negative positions. Your car drives automatically according to a sequence of instructions 'A' (accelerate) and 'R' (reverse):
When you get an instruction 'A', your car does the following:
position += speed
speed *= 2
When y... | true |
9f72042b90ed8510e7bb546b43646b17cf4d5cc3 | DeanHe/Practice | /LeetCodePython/Largest3SameDigitNumberInString.py | 1,110 | 4.125 | 4 | """
You are given a string num representing a large integer. An integer is good if it meets the following conditions:
It is a substring of num with length 3.
It consists of only one unique digit.
Return the maximum good integer as a string or an empty string "" if no such integer exists.
Note:
A substring is a conti... | true |
c015380c6afec6e616a443dc036ac4fd9c8f3fe2 | DeanHe/Practice | /LeetCodePython/TheNumberOfBeautifulSubsets.py | 1,979 | 4.25 | 4 | """
You are given an array nums of positive integers and a positive integer k.
A subset of nums is beautiful if it does not contain two integers with an absolute difference equal to k.
Return the number of non-empty beautiful subsets of the array nums.
A subset of nums is an array that can be obtained by deleting so... | true |
77fd864cec47777a25e1ee2d1701c56056cd61d4 | DeanHe/Practice | /LeetCodePython/NumberOfWaysToBuyPensAndPencils.py | 1,489 | 4.15625 | 4 | """
You are given an integer total indicating the amount of money you have. You are also given two integers cost1 and cost2 indicating the price of a pen and pencil respectively. You can spend part or all of your money to buy multiple quantities (or none) of each kind of writing utensil.
Return the number of distinct ... | true |
e695e23413a87d0581dcdb9b903d222b7450ddac | DeanHe/Practice | /LeetCodePython/PseudoPalindromicPathsInaBinaryTree.py | 2,298 | 4.25 | 4 | """
Given a binary tree where node values are digits from 1 to 9. A path in the binary tree is said to be pseudo-palindromic if at least one permutation of the node values in the path is a palindrome.
Return the number of pseudo-palindromic paths going from the root node to leaf nodes.
Example 1:
Input: root = [2,3,1... | true |
600fd6d1eeb0d0c8469a8b5cb43241fcfc9e6643 | DeanHe/Practice | /LeetCodePython/MinimumSpeedToArriveOnTime.py | 2,928 | 4.40625 | 4 | """
You are given a floating-point number hour, representing the amount of time you have to reach the office. To commute to the office, you must take n trains in sequential order. You are also given an integer array dist of length n, where dist[i] describes the distance (in kilometers) of the ith train ride.
Each trai... | true |
899f69376cfae31d701cded34e814c3c59230582 | DeanHe/Practice | /LeetCodePython/RotateImage.py | 1,222 | 4.375 | 4 | """
You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).
You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
Example 1:
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output... | true |
7a7124640f42f2d1c4acb10b0e66cda54000fc37 | DeanHe/Practice | /LeetCodePython/JumpGameII.py | 930 | 4.21875 | 4 | """
Given an array of non-negative integers nums, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Your goal is to reach the last index in the minimum number of jumps.
You can assume that you can always reach the last index.
E... | true |
9a167a3e2e3c0363a88e9f9634961e96dd9b917d | DeanHe/Practice | /LeetCodePython/EvaluateReversePolishNotation.py | 1,653 | 4.28125 | 4 | """
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +, -, *, and /. Each operand may be an integer or another expression.
Note that division between two integers should truncate toward zero.
It is guaranteed that the given RPN expression is always valid. That means the exp... | true |
b12cb8e6a34c038f0101677a30e6b6d0516c152d | DeanHe/Practice | /LeetCodePython/MinimumRoundsToCompleteAllTasks.py | 1,479 | 4.125 | 4 | """
You are given a 0-indexed integer array tasks, where tasks[i] represents the difficulty level of a task. In each round, you can complete either 2 or 3 tasks of the same difficulty level.
Return the minimum rounds required to complete all the tasks, or -1 if it is not possible to complete all the tasks.
Example 1:
... | true |
be312d6f0f96fd863f820a60a6e90ece3402949d | DeanHe/Practice | /LeetCodePython/DiagonalTraverse.py | 1,151 | 4.15625 | 4 | """
Given a matrix of M x N elements (M rows, N columns), return all elements of the matrix in diagonal order as shown in the below image.
Example:
Input:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
Output: [1,2,4,7,5,3,6,8,9]
Explanation:
Note:
The total number of elements of the given matrix will not exceed 10,0... | true |
8d11d7a8dd15d7f14065f5add86461c7df0f2f50 | DeanHe/Practice | /LeetCodePython/FindAllDuplicatesInAnArray.py | 837 | 4.125 | 4 | """
Given an integer array nums of length n where all the integers of nums are in the range [1, n] and each integer appears once or twice, return an array of all the integers that appears twice.
You must write an algorithm that runs in O(n) time and uses only constant extra space.
Example 1:
Input: nums = [4,3,2,7,8,... | true |
ccb2064dbc964d22eb4bee06e3d645b1a471d10c | DeanHe/Practice | /LeetCodePython/SpiralMatrixIV.py | 1,586 | 4.375 | 4 | """
You are given two integers m and n, which represent the dimensions of a matrix.
You are also given the head of a linked list of integers.
Generate an m x n matrix that contains the integers in the linked list presented in spiral order (clockwise), starting from the top-left of the matrix. If there are remaining e... | true |
0bcf3dc0b60184a6dcea836244be4078142597ec | DeanHe/Practice | /LeetCodePython/MinimumScoreOfaPathBetweenTwoCities.py | 2,451 | 4.21875 | 4 | """
You are given a positive integer n representing n cities numbered from 1 to n. You are also given a 2D array roads where roads[i] = [ai, bi, distancei] indicates that there is a bidirectional road between cities ai and bi with a distance equal to distancei. The cities graph is not necessarily connected.
The score o... | true |
6d458c64d633e36514f328028523552662fb7cde | DeanHe/Practice | /LeetCodePython/SmallestStringWithSwaps.py | 2,210 | 4.3125 | 4 | """
You are given a string s, and an array of pairs of indices in the string pairs where pairs[i] = [a, b] indicates 2 indices(0-indexed) of the string.
You can swap the characters at any pair of indices in the given pairs any number of times.
Return the lexicographically smallest string that s can be changed to afte... | true |
11b1c94525690e9d36624e25cb529c7b86cc04dc | DeanHe/Practice | /LeetCodePython/MaximumWidthOfBinaryTree.py | 1,760 | 4.28125 | 4 | """
Given the root of a binary tree, return the maximum width of the given tree.
The maximum width of a tree is the maximum width among all levels.
The width of one level is defined as the length between the end-nodes (the leftmost and rightmost non-null nodes), where the null nodes between the end-nodes are also cou... | true |
38182bdebe7cf53b1813723b2bea1a5c1352734b | DeanHe/Practice | /LeetCodePython/SlidingSubarrayBeauty.py | 2,409 | 4.25 | 4 | """
Given an integer array nums containing n integers, find the beauty of each subarray of size k.
The beauty of a subarray is the xth smallest integer in the subarray if it is negative, or 0 if there are fewer than x negative integers.
Return an integer array containing n - k + 1 integers, which denote the beauty of... | true |
6c81710c6bd12f2be15e2a65ac086a0f3fc3f62d | DeanHe/Practice | /LeetCodePython/NestedIterator.py | 2,710 | 4.40625 | 4 | """
You are given a nested list of integers nestedList. Each element is either an integer or a list whose elements may also be integers or other lists. Implement an iterator to flatten it.
Implement the NestedIterator class:
NestedIterator(List<NestedInteger> nestedList) Initializes the iterator with the nested list ... | true |
4c78d4e5275c5876f65381339bb2fa4446c85bd8 | DeanHe/Practice | /LeetCodePython/BasicCalculatorII.py | 1,750 | 4.15625 | 4 | """
Given a string s which represents an expression, evaluate this expression and return its value.
The integer division should truncate toward zero.
You may assume that the given expression is always valid. All intermediate results will be in the range of [-2^31, 2^31 - 1].
Note: You are not allowed to use any buil... | true |
810bd042c218118cbc37224bc70a6a7ff41908a7 | DeanHe/Practice | /LeetCodePython/StringCompressionII.py | 2,700 | 4.5 | 4 | """
Run-length encoding is a string compression method that works by replacing consecutive identical characters (repeated 2 or more times) with the concatenation of the character and the number marking the count of the characters (length of the run). For example, to compress the string "aabccc" we replace "aa" by "a2" ... | true |
509c8bd395006d72234f8e1ebaa163a657272a44 | DeanHe/Practice | /LeetCodePython/LexicographicallySmallestEquivalentString.py | 2,883 | 4.25 | 4 | """
You are given two strings of the same length s1 and s2 and a string baseStr.
We say s1[i] and s2[i] are equivalent characters.
For example, if s1 = "abc" and s2 = "cde", then we have 'a' == 'c', 'b' == 'd', and 'c' == 'e'.
Equivalent characters follow the usual rules of any equivalence relation:
Reflexivity: 'a'... | true |
074543c4bf98194eee8df87f0eb1cc44d7986784 | DeanHe/Practice | /LeetCodePython/PartitionLabels.py | 1,195 | 4.125 | 4 | """
A string S of lowercase letters is given. We want to partition this string into as many parts as possible so that each letter appears in at most one part,
and return a list of integers representing the size of these parts.
Example 1:
Input: S = "ababcbacadefegdehijhklij"
Output: [9,7,8]
Explanation:
The par... | true |
9099ed0b6953d30c9a5621e96823f14b466a914f | DeanHe/Practice | /LeetCodePython/MinimumJumpsToReachHome.py | 2,470 | 4.3125 | 4 | """
A certain bug's home is on the x-axis at position x. Help them get there from position 0.
The bug jumps according to the following rules:
It can jump exactly a positions forward (to the right).
It can jump exactly b positions backward (to the left).
It cannot jump backward twice in a row.
It cannot jump to any fo... | true |
03728766edfcd9ff0d48545c420d5c1b1f5fcd47 | DeanHe/Practice | /LeetCodePython/MakeNumberOfDistinctCharactersEqual.py | 2,206 | 4.1875 | 4 | """
You are given two 0-indexed strings word1 and word2.
A move consists of choosing two indices i and j such that 0 <= i < word1.length and 0 <= j < word2.length and swapping word1[i] with word2[j].
Return true if it is possible to get the number of distinct characters in word1 and word2 to be equal with exactly one m... | true |
7f249e49eba5ae7295208d8f15cb7d297277da3a | MrThoe/CV_Turt_Proj | /1_Square.py | 504 | 4.125 | 4 | """
1. Create a function that will draw a Square - call it DrawSquare()
2. Allow this function to have 1 Parameter (s) for the side length.
3. Use a FOR Loop for this function.
"""
"""
4. Inside a for loop, call the Square function 100 times,
for the sidelength of 10*i.
5. Using the pen up and pendown ... | true |
76339afe4f8ed4e8bd260b872016b116b8ddc8d0 | Sahha2001000/Paradigm | /lab_1/t7.py | 268 | 4.1875 | 4 | print("\ntask7")
chosen_number = int(input("Сhoose number: "))
print("Can be divided by 2" if chosen_number % 2 == 0 else "Cannot divided by 2. Choose another one")
print("Last number is 5" if chosen_number % 10 == 5 else "Last number is not 5. Choose another one")
| true |
c00fa047e97983fc4276343207ac8185c1a52548 | Sahha2001000/Paradigm | /lab_1/t4.py | 306 | 4.125 | 4 | print("\ntask4")
number = input("Choose three-digit number: ")
tmp = number
number_list = list(number)
number_list.reverse()
number = "".join(number_list)
print("The reversed number of {} is ".format(tmp) + number)
"""
tmp = tmp[::-1]
print("Второй вариант через срез:" + tmp)
""" | true |
fd0777adf5b1fe5e6d8195ccc82e407ef9befc36 | chrissyblissy/CS50x | /pset6/caesar/caesar.py | 854 | 4.5625 | 5 | # means command line arguments can be used
import sys
# checks that only 2 arguments have been given
if len(sys.argv) != 2:
exit(1)
# exits the program if the key is not an integer
while True:
try:
key = int(sys.argv[1])
break
except:
exit()
if key < 0:
exit()
while key > 26:
... | true |
f8e27eeb55fa7cd5fb20ddb667309bfc3897ac65 | jofabs/210-COURSE-WORK | /Task 2.py | 655 | 4.1875 | 4 | """TASK 2
Count the number of trailing 0s (number of 0s at the end of the number)
in a factorial number. Input: 5 Output: 1, Input: 10 Output: 2
Hint: Count the prime factors of 5"""
#get input factorial number from user
f = int(input("Enter a factorial number you want to trail zeros for: "))
def tailingZeros... | true |
106635ff03b655232dc33dba990e26341105f220 | jofabs/210-COURSE-WORK | /Task 13.py | 2,702 | 4.125 | 4 | """TASK 13
Write the pseudocode for an unweighted graph data structure.
You either use an adjacency matrix or an adjacency list approach.
Also, write a function to add a new node and a function to add an edge.
Following that,implement the graph you have designed in python.
You may use your own linked list from pre... | true |
22df9eade79c6d2944530289d6fd1750fdb8f154 | Robert1GA/Python_Practice | /read_file.py | 432 | 4.15625 | 4 | # Read an entire file
read_a_file = open('filename.txt', 'r')
print(read_a_file.read())
read_a_file.close()
# Read a line
read_a_file = open('filename.txt', 'r')
print('first line: ' + read_a_file.readline())
print('second line: ' + read_a_file.readline())
print('third line: ' + read_a_file.readline())
read_a_file.clo... | false |
2c5ebc4a893593397a899518c1a65f492b213930 | tbehailu/wat-camp-2014 | /Day3/ex3sol.py | 1,673 | 4.1875 | 4 | # Q1
class VendingMachine(object):
"""A vending machine that vends some product for some price.
>>> v = VendingMachine('crab', 10)
>>> v.vend()
'Machine is out of stock.'
>>> v.restock(2)
'Current crab stock: 2'
>>> v.vend()
'You must deposit $10 more.'
>>> v.deposit(7)
'Current... | true |
69803e6698abb9083d8fb9037330158c6785c5c2 | Tossani/Phyton | /calculadora.py | 748 | 4.125 | 4 | print ("Calculadora em PYTHON")
print (" Escolha uma das alternativas abaixo /n")
print (" Digite 1 - para Soma: ")
print (" Digite 2 - para Subtração: ")
print (" Digite 3 - para Multiplicação: ")
print (" Digite 4 - para Divisão: ")
op = input(" Selecione a operação: ")
num1 = int(input("Digite o primeiro núme... | false |
b9c469c886e07b506d630c3519de52d301fd7332 | adityalprabhu/coding_practice | /CodingPad/Algorithms/QuickSort.py | 1,141 | 4.375 | 4 | # Quicksort implementation
# function that swaps the elements
def swap(arr, left, right):
tmp = arr[left]
arr[left] = arr[right]
arr[right] = tmp
# function that partitions the elements
# and arranges the left array where elements < pivot and right > pivot
def partition(arr, left, right):
# pivot sel... | true |
f562bc5a3aac08a4080fef03a43a353408e643af | CT-Kyle/mobiTest | /mobiTest/numPretty.py | 2,055 | 4.34375 | 4 | import sys
#This program will take numbers and make them look all pretty
#This block accepts any input as raw input and stores as a string. It is stored as a string so that
#it can be sliced later for output.
print "********** Welcome to the Number Prettifier **********"
rawNum = raw_input('Enter a numerical value in... | true |
20836ecc29adb82fe99b29c798d8648b4b6997d8 | tomvapon/snake | /logic/input.py | 1,022 | 4.125 | 4 | """
This file implements the load input for the files
"""
import sys
import configparser
def load_input_file(file):
"""
This function load an input file which contains the board dimensions, the snake and the depth.
This simplifies the problem of manual console input and let check the three acceptance tes... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.