blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
66510521396ed5c733e85cc1cd114b213585fa67 | Ankita-Dake/PythonRegularExpression | /RegularExpression.py | 1,282 | 4.25 | 4 | # using search method
import re
s = "Hello from python"
i = re.search("from", s)
if (i):
print("string match")
else:
print("No match found")
# ^ start with string
a = "This is regular expression"
j = re.search("^This", a)
if (j):
print("string match")
else:
print("No match found")
# $ end with string... | false |
1d4b7b925e4c71c3bde9b6e62b7ef864f041eb33 | 2amitprakash/Python_Codes | /Grokking_Algo/quicksort.py | 494 | 4.125 | 4 | import random
def quicksort(list):
if len(list) < 2:
return list
else:
pi = random.randint(0,len(list)-1)
#pi = 0
print ("The list is {l} and random index is {i}".format(l=list,i=pi))
pivot = list.pop(pi)
less = [i for i in list if i <= pivot]
more = [i f... | true |
1b076c0cac0d11470b6ee48b998ba73b20182317 | TechyAditya/COLLEGE_ASSIGNMENTS | /Python/chapter4/list_methods.py | 395 | 4.1875 | 4 | l1=[1,8,9,5,6,6] #can have same elemnets repeatedly
l1.sort() #arranges in ascending order
print(l1)
l1.reverse() #reverse the list elements
print(l1)
l1.append(10) #adds element at the end of the list
print(l1)
l1.insert(3,69) #adds element at the index mentioned, but doesn't removes the elements
print(l1)
l1.pop(2)... | true |
57e8eda341a70e86b185c04304d6d73d814737b6 | AkashKumarSingh11032001/100-Days-Python-Bootcamp-By-AngelaYu | /Day 3 - Beginner - Control Flow and Logical Operators/Lec_code.py | 2,300 | 4.21875 | 4 | # 1
# if-else
# height = eval(input("Enter your height: "))
# if(height > 120):
# print("Sell Ticket")
# else:
# print("Not Eligible")
# 2
# ex-3.1
# num = eval(input("Enter Number. : "))
# if(num % 2 == 0):
# print("Even Num.")
# else:
# print("Odd Num.")
# 3
# nested If-else
# height = eval(input("... | false |
f7789ce8986996cdbaf4b06dcb527077538b0170 | RUSTHONG/Algorithm | /pythondev/bubble_sort.py | 372 | 4.15625 | 4 | def bubble_sort(List):
for t in range(len(List)-1, 0, -1):
for i in range(t):
if List[i] > List[i+1]:
List[i], List[i+1] = List[i+1], List[i]
print(List)
if __name__ == "__main__":
List = input("Please type in your list: ").split(",")
List = [int(a) for a in List]
... | false |
5e9f0ec62bdb1ee1c60a53b921d14741fded440d | I-bluebeard-I/GB_py_algorithms | /less07_task01.py | 1,000 | 4.1875 | 4 | """
1. Отсортируйте по убыванию методом "пузырька" одномерный целочисленный массив, заданный случайными числами на
промежутке [-100; 100). Выведите на экран исходный и отсортированный массивы. Сортировка должна быть реализована
в виде функции. По возможности доработайте алгоритм (сделайте его умнее).
"""
from random ... | false |
c902d56fd3a438b0e7bab5d0df826422979ea800 | HarryBaker/Fuka | /cleanTxtFiles.py | 1,960 | 4.1875 | 4 | # A program that cleans text files when given raw input in the following manner:
# Remove all characters except letters, spaces, and periods
# Convert all letters to lowercase
__author__ = 'loaner'
from sys import argv
class Cleaner:
def __init__(self, input):
raw_file_name = raw_input(input);
fil... | true |
0ffbe7a1cc9c186c1043d0b683f19ba6499a1602 | onestarshang/leetcode | /validate-binary-search-tree.py | 1,814 | 4.1875 | 4 | #coding: utf-8
'''
http://oj.leetcode.com/problems/validate-binary-search-tree/
Given a binary tree, determine if it is a valid binary search tree (BST).\n\nAssume a BST is defined as follows:
The left subtree of a node contains only nodes with keys less than the node's key.
The right subtree of a node contains only ... | true |
f3634048b65198301168cf657d3e7ffa463ba159 | onestarshang/leetcode | /decode-string.py | 1,719 | 4.125 | 4 | '''
https://leetcode.com/problems/decode-string/
Given an encoded string, return it's decoded string.
The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer.
You may assume that the input strin... | true |
0b7d06e83d9a32417b0ef408ffcc340960bf268b | onestarshang/leetcode | /convert-a-number-to-hexadecimal.py | 1,277 | 4.625 | 5 | # coding: utf-8
'''
https://leetcode.com/problems/convert-a-number-to-hexadecimal/
Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two’s complement method is used.
Note:
All letters in hexadecimal (a-f) must be in lowercase.
The hexadecimal string must not contain extra lead... | true |
351202ef5ebd3c6de3fc46c446fc1c9ff4d8efc6 | onestarshang/leetcode | /fraction-to-recurring-decimal.py | 2,300 | 4.125 | 4 | '''
https://leetcode.com/problems/fraction-to-recurring-decimal/
Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.
If the fractional part is repeating, enclose the repeating part in parentheses.
For example,
Given numerator = 1, denominator = 2, retur... | true |
12383bafbb9af46d9e220928ccb9746ba4725084 | onestarshang/leetcode | /find-all-anagrams-in-a-string.py | 1,569 | 4.125 | 4 | '''
https://leetcode.com/problems/find-all-anagrams-in-a-string/
Given a string s and a non-empty string p, find all the start indices of p's anagrams in s.
Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100.
The order of output does not matter.
... | true |
2924fb03143cf10abacfe8f59a64be61300e8f1a | onestarshang/leetcode | /number-of-1-bits.py | 660 | 4.15625 | 4 | # coding: utf-8
'''
https://leetcode.com/problems/number-of-1-bits/
Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).
For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should ret... | true |
366baaa2535d13166583420c45c6a80229d810ef | onestarshang/leetcode | /zigzag-conversion.py | 1,235 | 4.25 | 4 | '''
https://leetcode.com/problems/zigzag-conversion/
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P A H N
A P L S I I G
Y I R
And then read line by line: "PAHNAPLSIIGYIR"
Write the... | true |
83c3d2036ad237a76c79a6a69ef638acd4a01b1e | onestarshang/leetcode | /balanced-binary-tree.py | 1,062 | 4.15625 | 4 | #coding: utf-8
'''
http://oj.leetcode.com/problems/balanced-binary-tree/
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
'''
# Definition for... | true |
e4e68fbe07641281facb7986ebd93b855e85c967 | onestarshang/leetcode | /insertion-sort-list.py | 1,308 | 4.25 | 4 | #coding: utf-8
'''
http://oj.leetcode.com/problems/insertion-sort-list/
Sort a linked list using insertion sort.
'''
class Solution:
# @param head, a ListNode
# @return a ListNode
def insertionSortList(self, head):
if not head or not head.next:
return head
p = he... | true |
9dce19d97804637a281134363814828aba1d17a5 | maxkajiwara/Sorting | /project/iterative_sorting.py | 1,237 | 4.28125 | 4 | # Complete the selection_sort() function below in class with your instructor
def selection_sort(arr):
# loop through n-1 elements
for i in range(0, len(arr) - 1):
cur_index = i
smallest_index = cur_index
# find next smallest element
for j in range(cur_index, len(arr)):
... | true |
3d46063fcec3096eaa699de7d89894b398974fa4 | PetosPy/rock_paper_scissor | /Rock_Paper_Scissors.py | 1,342 | 4.25 | 4 | rock = '''
_______
---' ____)
(_____)
(_____)
(____)
---.__(___)
'''
paper = '''
_______
---' ____)____
______)
_______)
_______)
---.__________)
'''
scissors = '''
_______
---' ____)____
______)
__________)
(____)
---.__(___)
'''... | false |
91f57de49217b1186f6990ee5b15826c493ef99b | janagodbole/ProblemSet12 | /ProblemSet8.py | 1,375 | 4.125 | 4 | number_list = [5,3,7]
print("negative")
number_list[0] = number_list[0] * -1
[print(number_list)]
print("10 added")
number_list.append(10)
print(number_list)
print("16 @ 2")
number_list = number_list[0:2] + [16] + number_list[2:]
print(number_list)
print("letter @ 1 removed")
number_list.remove(number_list[1])
print... | false |
cf9e93785bfc81f9d26c666366a78c979a0ec166 | raymondng1893/Python-CodingBatExercises | /CodingBatString-1/extra_end.py | 292 | 4.28125 | 4 | # Given a string, return a new string made of 3 copies of the last 2 chars of the original string. The string length will be at least 2.
def extra_end(str):
start = len(str) - 2
return 3*str[start:]
print(extra_end('Hello'))
print(extra_end('ab'))
print(extra_end('Hi'))
| true |
f8f2d3e0d9fb69a648c079cf5682afb0242eff54 | raymondng1893/Python-CodingBatExercises | /CodingBatString-2/count_hi.py | 266 | 4.25 | 4 | # Return the number of times that the string "hi" appears anywhere in the given string.
import re
def count_hi(str):
count = re.findall('hi', str)
return len(count)
print(count_hi('abc hi ho'))
print(count_hi('ABChi hi'))
print(count_hi('hihi'))
| true |
608aea8f1c2d4fd673d29ee20cadfeff30cdc245 | TarikEskiyurt/Python-Projects | /Determine Prime Number.py | 324 | 4.21875 | 4 | number=int(input("Please enter the number")) #I take a number from user
counter=0
for i in range(2,number):
if number%i==0:
counter=counter+1
if counter > 0:
print("It is not a prime number.") #I print output to screen
else:
print("Is the prime number.") #I print output to screen... | true |
4cf8466775023cd269a1959762ae2d87a9eda0e0 | imodin07/Python-Basics | /FileWritin.py | 797 | 4.125 | 4 | # Creating a new text file.
f = open("writee.txt", "w") # 'f' is file handle. 'w' is write mode.
f.write("It's a beautiful day out there. ") # With the help of 'f.write' we can write the file.
f.close() # Command to close file.
# Append Function in... | true |
a642e37cd7f786b709a2186939ad0615fb4d0f16 | shuihan0555/100-days-of-python | /day014/main.py | 1,068 | 4.1875 | 4 | # coding=utf-8
"""Day 014 - setdefault: When dict.get it's a bad idea.
This example covers the difference between dict.get and dict.setdefault functions.
Setdefault is a function that is more efficient that dict.get,
because it already set a default value if the key doesn't exists
and return the value... | true |
6a2b485596a36d8ac8e35762ef3c79f3d3bcfab8 | shuihan0555/100-days-of-python | /day006/main.py | 1,084 | 4.1875 | 4 | # coding=utf-8
def run():
# Attributing tuple values in variables
name, age, height, weight = ('Marcos', 21, 173, 62)
print("Name: {} - Age: {} - Height: {} - Weight: {}".format(
name, age, height, weight)
)
# >>> Name: Marcos - Age: 21 - Height: 173 - Weight: 62
animes = (
('A... | false |
26a496a3ee887173f2ded8cfd166c9987f4ce210 | JonOlav95/algorithm_x | /backtracking/backtrack_helpers.py | 1,371 | 4.125 | 4 | from backtracking.backtrack_node import Node
def arr_to_node(arr):
node_arr = [[Node() for i in range(len(arr))] for j in range(len(arr[0]))]
for i in range(9):
for j in range(9):
node = Node()
node.x = j
node.y = i
if arr[i][j] != 0:
... | true |
f37c99c9a7412bc00b5be50ef7e76e174c859575 | Swinvoy/Cyber_IntroProg_Group1 | /Quizes/Exceptions and Input Validation/getIpAddress.py | 882 | 4.25 | 4 | # Write a function called 'GetIpAddress' that will keep asking the user to enter an IP Address until it is valid. The function will then return the IP address as a string.
# 255.255.255.255
def getIpAddress():
noError = False
while noError == False:
try:
ipAddress = input("What IP Address... | true |
572bbb8d6a87bb282ad30707fce34dc7e9bfb12c | AShipkov/AShipkov-Python-Algorithms-and-Data-Structures | /lesson3_3.py | 891 | 4.15625 | 4 | """
3. В массиве случайных целых чисел поменять местами минимальный и максимальный элементы.
"""
import random
random_list = random.sample(range(0,1000), 5)
print(f'{"Массив случаных чисел":25} {random_list}')
index_max = index_min = 0
number_max = random_list[0]
number_min = random_list[0]
for index, number in enume... | false |
ce6785e84216dff35bff5cfdf9236074a534d712 | AShipkov/AShipkov-Python-Algorithms-and-Data-Structures | /lesson3_7.py | 927 | 4.1875 | 4 | """
7. В одномерном массиве целых чисел определить два наименьших элемента.
Они могут быть как равны между собой (оба являться минимальными), так и различаться.
"""
import random
random_list = random.sample([i for i in range(0, 10)] * 2,10)
print(random_list)
numbers = {}
for index, number in enumerate(random_list)... | false |
6b970c0e14015da18e596f5c07aaa0c8e5cac8fc | xiao-miao97/xiao_learn | /练习191225.py | 1,256 | 4.125 | 4 | '''
华氏温度转换为摄氏温度
'''
f = float(input('请输入华氏温度:'))
c = (f - 32) /1.8
print('%.1f华氏温度 = %.1f摄氏温度' % (f, c))
'''
输入圆的半径计算周长和面积
'''
import math # math是常用数学函数库,math.pi是圆周率
r = float(input('请输入圆的半径: '))
z = r ** 2 * math.pi
y = 2 * math.pi * r
print('圆的周长为%.2f,面积为%.2f' % (y, z))
'''
math中常用数学函数
ceil(x) 取顶
flo... | false |
e7a3547585379afed4381762a14e51ffc7400400 | tamsynsteed/palindrometask | /recursiontask.py | 616 | 4.3125 | 4 | #if the string is made of no letters or just one letter, then it is a palindrome.
def palindrome(s):
if len(s) < 1:
return True
#check if first and last letters are the same
else:
if s[0] == s[-1]:
# if the first and last letters are the same. Strip them from the string, and determine whether t... | true |
f4b5aa25d217a23e345e7c0b5ad1479941c5d78d | chennakesava1/python | /con.py | 1,316 | 4.1875 | 4 | #!/user/bin/python
inputs = float(input("enter ur number"))
if inputs == 3:
print ("con is truu")
else:
print "input is not 3"
##elif
inputs = float(input("enter the second number"))
if inputs == 2:
print "given number is 2"
elif inputs > 2:
print "given number below 2"
else:
print "given number... | false |
1daca47cdf2cd8d0feb87b65d4d17f19410a01e8 | acikgozmehmet/Python | /TicTacToe/TicTacToeStudent.py | 2,395 | 4.34375 | 4 | ## @author Mehmet ACIKGOZ
# This program simulates a simple game of Tic-Tac-Toe
def main():
MAX_TURNS = 9
turnsTaken = 0
isWinner = False
board = createBoard()
player = "O"
while (not isWinner and turnsTaken < MAX_TURNS) :
# Switch players
# (If player contained an O assign... | true |
fb23d64f4c9943f1f81aae0f41d9e253d183e843 | Ryuuken-dev/Python-Zadania | /Moduł VII-lekcja 41/41_1.py | 1,483 | 4.34375 | 4 | """
Przygotuj mini program do zarządzania Twoimi oszczędnościami. Starasz się wpłacać pieniądze
z różnych źródeł, chcesz na bieżąco wiedzieć, ile udało Ci się już zaoszczędzić.
"""
from datetime import datetime
class Saving:
def __init__(self, date: datetime, saving_value: float):
self._saving_value = sav... | false |
6a4f626b7137370d353e7f335d38688a616b5610 | Ryuuken-dev/Python-Zadania | /Moduł II-praca domowa/HowManyChars.py | 315 | 4.1875 | 4 | # Napisz program zliczający ilość wystąpień każdego znaku w zadanym napisie
users_word = input('Podaj zdanie: ')
how_many_chars = {}
for word in users_word:
if word not in how_many_chars:
how_many_chars[word] = users_word.count(word)
print(f'Znak: {word} Ilość: {how_many_chars[word]}')
| false |
cc5dcbdcdaa89a3e66d23e9e0ba40369e47c62e5 | Ryuuken-dev/Python-Zadania | /Moduł VI-lekcja 36/36_2.py | 1,100 | 4.125 | 4 | """
Przygotuj klasę Car, która powinna przechowywać nazwę samochodu oraz jego cenę
i maksymalną prędkość. Zapytaj użytkownika o 5 samochodów, a następnie wypisz je na ekranie w
kolejności od najdroższego do najtańszego oraz poniżej od najwolniejszej do najszybszej
prędkości.
"""
class Car:
def __init__(self, car_... | false |
e59e17fabd7f5c6677ce7b90f2735be699f1132b | Ryuuken-dev/Python-Zadania | /Practice Python/List Less Than Ten.py | 740 | 4.34375 | 4 | """
Take a list, say for example this one:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
and write a program that prints out all the elements of the list that are less than 5.
Extras:
1. Instead of printing the elements one by one, make a new list that has all the elements
less than 5 from this list in it and print o... | true |
7b0e0ad002ed665d5ec79acafa59ae783b6dae56 | Ryuuken-dev/Python-Zadania | /Moduł II-lekcja 12/12.1.py | 1,186 | 4.25 | 4 | """
Przygotuj mały słownik języka angielskiego, pytaj użytkownika co chce zrobić i wyświetlaj mu słowo
przetłumaczone na język polski lub na język angielski.
"""
users_choice = input('Podaj parę językową-Polski>Angielski (P>A), Angielski>Polski (A>P): ').lower()
users_choice = users_choice.replace(' ', '')
words = {
... | false |
822f149e5cc3c35b5fd057c38b45de473d2c950a | BhujayKumarBhatta/OOPLearning | /pOOP/pOOp/static_method.py | 1,516 | 4.21875 | 4 | '''
Created on 02-Oct-2018
@author: Bhujay K Bhatta
'''
'''
Static methods are a special case of methods.
Sometimes, you'll write code that belongs to
a class, but that doesn't use the object itself at all.
For example:
'''
class Pizza(object):
@staticmethod
def mix_ingradients(x, y):
... | true |
78c733bb240940129d830fefe817a8bd1d7ac956 | KrishnaSindhur/python-scripts | /cp/stack.py | 1,491 | 4.40625 | 4 | # dynamic stack operation
class Stack(object):
def __init__(self, limit=10):
self.stk = limit*[]
self.limit = limit
def is_empty(self):
return self.stk <= 0
def push(self, item):
if len(self.stk) >= self.limit:
print("stack is full")
print("stack is ... | true |
6f8efad9b8fb1792c14a4af94707d6a9f1cb3d3a | Noorul834/PIAIC | /assignment03.py | 669 | 4.125 | 4 | # 3. Divisibility Check of two numbers
# Write a Python program to check whether a number is completely divisible by another number. Accept two integer values form the user
# Program Console Sample Output 1:
# Enter numerator: 4
# Enter Denominator: 2
# Number 4 is Completely divisible by 2
# Program Console Samp... | true |
79e9aabb9a44898766e4c9fd5af2edefd0f86304 | Jordan-1234/Wave-1 | /Volume of a Cylinder.py | 265 | 4.28125 | 4 | import math
radius = float(input("Enter in the radius of the cylinder "))
height = float(input("Enter in the height of the cylinder "))
cylinder_Area = (2 * math.pi * pow(radius,2) * height)
print('The volume of the cylinder will be ' + str(round(cylinder_Area,1))) | true |
373a821293faaec8b08aa36dd08a9f3753b5e3d6 | lilymaechling/codingAssignment4 | /helper.py | 1,971 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Helper File Created on Mon Mar 23 22:25:37 2020
@author: deepc
"""
# In this "alive" code below, we will provide many subroutines (functions) in Python 3 which may be useful.
# We will often provide tips as well
import matplotlib.pyplot as plt
def read_pi(n):
#opens the file name "pi" ... | true |
d183aa5bbc14b2ec779224ae2ce86ca0be3547b4 | ghostvic/leetcode | /RotateArray.py | 1,151 | 4.25 | 4 | '''
Rotate an array of n elements to the right by k steps.
For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].
'''
'''
The idea of this solution is: the array we can cut it into 3, A:[1,2,3,4] B:[5,6,7].
To get the result[B,A], first revers A, then reverse B, then reverse the e... | true |
28c4806baade080629c649028bd8b36e12dd7de4 | SoenMC/Programacion | /EjercicioFun8_men_may.py | 1,068 | 4.46875 | 4 | '''
Confeccionar una función que reciba tres enteros y los muestre ordenados de menor a mayor.
En otra función solicitar la carga de 3 enteros por teclado
y proceder a llamar a la primer función definida.
'''
def ordenar_enteros(num1,num2,num3):
if num1<num2 and num1<num3:
print(num1)
if n... | false |
bb98c4b3f474ea603a9576dd81713e0af8d3bf70 | Ezdkdr/Algorithms | /RainTrap.py | 967 | 4.25 | 4 | # a function that takes a list of positive integers as argument. The elements represent the lengths of the towers
# it returns the number of units of water trapped between the towers
#from typing import List, Any
def measure_trapped_water(arr):
i = 0
trapped_water_units = 0
j = len(arr) - 1
added = Tr... | true |
6b9fda45cb8bbc08d20afba5d0919d2dd2f9e15c | dcgibbons/learning | /advent_of_code/2019/day10.py | 1,988 | 4.25 | 4 | #!/usr/bin/env python3
#
# day10.py
# Advent of code 2019 - Day 10
# https://adventofcode.com/2019/day/10
#
# Chad Gibbons
# December 20, 2019
#
import math
import sys
def read_map(filename):
# reads a map from an input file - assuming one row per line of text
map = []
with open(filename) as fp:
... | true |
34d5fc23e16c4eb8acca98dd368726b427f09b0f | ahhampto/py4e | /ex_7.2.py | 1,108 | 4.125 | 4 | #Write a program that prompts for a file name, then opens that file and reads through the file, looking for lines of the form:
#X-DSPAM-Confidence: 0.8475
#Count these lines and extract the floating point values from each of the lines and compute the average of those values and produce an output as shown below.
... | true |
3a833c388abc1fd1e27c14a603e3780b8b6fd657 | Asmin75/Beeflux_soln | /2.py | 235 | 4.125 | 4 | """Q2.
Consider a dictionary
d = {1:1, 2:2, 3:3}
a. whats the value of d[4] ??
b. How can you set 9 value in 2 key.
Write a program to print value with 2 key."""
d = {1:1, 2:2, 3:3}
#print(d[4]) #give KeyError: 4
d[2]=9
print(d[2])
| true |
836b1abfb6f7ba743da277f73799926daf67aad6 | Asmin75/Beeflux_soln | /1.py | 386 | 4.21875 | 4 | """Q1.
Create a function to sum Input Numbers (parameters) which returns sum of inputed numbers. Also write Unittest for the function.
my_sum(1,2) should return 3 e.g.
my_sum(1,2,3) should return 6
my_sum(1,3,5,7,8) = ?"""
def my_sum(*args):
total = 0
for num in args:
total += num
return tota... | true |
5a811e8625601ba78a4723e4a92539f15573376d | wangjiaqiys/tensorflow2.0 | / Data_Structures_Algorithms/_deque.py | 934 | 4.125 | 4 | # _*_ coding:utf-8 _*_
"""
双端队列(deque, double-ended queue): 是一种具有队列和栈的性质的数据结构
单独看双端队列的一端, 相当于一个栈, 相当于两个栈底合在一起
"""
class Deque():
def __init__(self):
self.__list = []
def add_front(self, item):
"""从对头加入一个item元素"""
self.__list.insert(0, item)
def add_rear(self, item):
"""从队尾加入... | false |
a8448f10e865e57443ffddea639346d62ed63b15 | brealxbrealx/beetroot | /Homework5/h5task2.py | 712 | 4.375 | 4 | # Author: Andrey Maiboroda
# brealxbrealx@gmail.com
# Homework5
# task2
# this program Generate 2 lists with the length of 10 with random integers from 1 to 10, \
# and make a third list containing the common integers between the 2 initial lists without any duplicates.
import random
# generate 2 lists in range 10 wit... | true |
2137e9ea6a4349220acb56ee37f258e245d479a8 | brealxbrealx/beetroot | /Homework8/h8task1.py | 481 | 4.28125 | 4 | # Author: Andrey Maiboroda
# brealxbrealx@gmail.com
# Homework8
# task1
# Write a function called oops that explicitly raises an IndexError \
# exception when called. Then write another function that calls oops inside a try/except statement to catch the error. What happens if\
# you change oops to raise KeyError ins... | true |
98f9f3ab231065992f45e0b2a41ecb2904bfd1ef | Diegofergamboa/day-3-1-exercise | /main.py | 468 | 4.4375 | 4 | # 🚨 Don't change the code below 👇
number = int(input("Which number do you want to check? "))
# 🚨 Don't change the code above 👆
#Write your code below this line 👇
if number % 2 == 1:
print('The number is odd')
else:
print('The number is even')
#It´s important to know that the modulo gives 0 when the number is e... | true |
e3c90bb28c3d9df47a7eba8eb2ce678600bf4379 | OperationFman/LeetCode | /RevisionKit/Bubble-Sort.py | 677 | 4.21875 | 4 | # Given an array of integers, sort the array in ascending order using the Bubble
# Print the following three lines:
# Array is sorted in X swaps.
# First Element: Y
# Last Element: Z
# Where X, Y, Z are numbers
def countSwaps(a):
""" [2, 1, 3] """
# Clue: Follow the traditional method of bubble sort and run ... | true |
da348de88096524bb92353cf5cd1a8c76947842a | Kuroposha/Data-itmo | /lesson05/lesson5.py | 2,796 | 4.3125 | 4 | """
Лекция 5. Модули, пакеты, дистрибуция пакетов(распространение)
Модуль - это обычный файл-Python
Названия для модуля имеют теже ограничения, что и остальные в пай
Регистр!
- Исполняемый (запускаемый / главный) модуль также называется MAIN
"""
#-- КАк импортировать модуль? --
#1. Испортировать целиком ( весь сраз... | false |
986bb3f771eaf065f792427508a7a33bc4d3a3ee | themanoftalent/Python-3-Training | /guessWrongNUmber.py | 449 | 4.25 | 4 | num = 0
secretnumber = 3
while True:
try:
num = int(input("Enter an integer 1-5: "))
except ValueError:
print("Please enter a valid integer 1-5")
continue
if num >= 1 and num <= 5:
break
else:
print('The integer must be in the range 1-5')
if num == secretnumber:
... | true |
b250352075bd8f0c8ce67731bd9acea04b8756d2 | DanielOjo/variables | /Task 6.2.py | 402 | 4.28125 | 4 | #Daniel Ogunlana
#9/9/2014
#Task 6
#1.Write a program that will ask the user for three integers and display the total.
#2.Write a program that will ask the user for two integers and display the result of multiplying them together.
#3.Ask the user for the length, width and depth of a rectangular swimming pool. Calc... | true |
1c9c3138bcb59f06b7db6158e04fa706e5df5a52 | VitaliiStorozh/Python_Core | /HW3/3.4.py | 310 | 4.15625 | 4 | area = float(input("Hall's area(S) is: "))
radius = float(input("Stage's radius(R) is: "))
aisle = float(input("Aisle width(K) is: "))
from math import sqrt
if aisle*2 <= (sqrt(area) - (2*radius) ) :
print("The stage can be located in this hall")
else :
print("You should find another stage or hall")
| true |
f04698861002ec8c9db241672b00cee8f9834942 | VitaliiStorozh/Python_Core | /HW4/4.3(from_book).py | 1,099 | 4.15625 | 4 | my_bd = int(input('Year of your burn: '))
years_list = [my_bd, my_bd+1, my_bd+2, my_bd+3, my_bd+4, my_bd+5]
my_3th_bd = years_list[3]
print('Year when I was 3 year old:', my_3th_bd)
things = ["mozzarella", "cinderella", "salmonella"]
print('List of sth: ', things)
things[1] = "Cinderella"
print ('List with element conn... | false |
23fc1a4b24c6bffe7676ae4fde1d37bee3274404 | sakiii999/Python-and-Deep-Learning-Lab | /Python Lab Assignment 2/Source/LA2_4.py | 417 | 4.15625 | 4 | import numpy as np
#Creates a list of array wit size 15 and range in between 0 to 20
random = np.random.randint(low=0,high=20,size=15)
print("The random vector is",random)
#Total count of each integer are calculated using bincount method
totalcount = np.bincount(random)
#Most occurences of an integer i.e. highest count... | true |
8aca065e622cba0a79ce5d6b7332f57783ee15d1 | anujpanchal57/Udemy-Challenges | /Lect-43-challenge.py | 716 | 4.4375 | 4 | # Create a list of items (you may use either strings or numbers in the list),
# 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 loop, use next() on your list to print the next item.
#
# hint: use the len() ... | true |
62f5189ad9440541eb7aeeb16b4ddcfa3ae944b2 | Psp29/basic-python | /chapter 4/03_list_methods.py | 572 | 4.25 | 4 | # Always use the python docs to find all the info!!
list1 = [1, 5, 3, 7, 86, 420, 69]
print(list1)
# list1.sort() # sorts the list
# list1.reverse() # reverses the list
# list1.append(669) # adds the elements at the end of the list.
# list1.insert(3, 5) # Inserts the element at the specific position here, first ... | true |
28b8d144e32d73af5edd0c5247354c3b65e3d691 | Psp29/basic-python | /speedlearn.py | 521 | 4.125 | 4 | # (tuples are immutable means that we cannot replace the values in an tuples) and are denoted by brackets i.e. ()
# e.g. x = (3, 'string', 4.0)
# list (it is mutable means they store reference of the items not the copy, basically you can change, append, add, remove items in a list) are denoted by square brackets []
# ... | true |
789afdfbbf8c0dec19bb5fb2e2ccfc121b058886 | Psp29/basic-python | /chapter 6/01_conditionals.py | 467 | 4.15625 | 4 | a = input("Enter value of a: ")
b = input("Enter value of b: ")
# if-elif-else ladder
# if(a > b):
# print("The value of a is greater than b.")
# elif(a == b):
# print("value a is equal to b.")
# else:
# print("The value of b is greater than a.")
# Multiple if statements
if(a > b):
print("The value o... | true |
0bf4818daf53695a7a026b679abcafc2980ee80d | Jorgeteixeira00/CURSO-EM-V-DEO---EXERCICIOS | /Ex04.py | 545 | 4.21875 | 4 | #Exercício Python 004: Faça um programa que leia algo pelo teclado e mostre na tela o seu tipo primitivo e todas as informações possíveis sobre ele.
frase = input('Digite algo:')
print('O tipo primitivo desse valo é:',type(frase))
print('Só tem espaços?', frase.isspace())
print('É um número?', frase.isalnumeric())
pr... | false |
e2933d6c61d51c209647c89f7b1a53828383e644 | Jorgeteixeira00/CURSO-EM-V-DEO---EXERCICIOS | /Ex42.py | 717 | 4.125 | 4 | # Exercício Python 042: Refaça o DESAFIO 035 dos triângulos, acrescentando o recurso de mostrar que tipo de triângulo será formado:
# - EQUILÁTERO: todos os lados iguais
# - ISÓSCELES: dois lados iguais, um diferente
# - ESCALENO: todos os lados diferentes
r1 = float(input('Primeiro segmento:'))
r2 = float(input('Seg... | false |
3c62d8f25c65cebdcb2f90b600bc44c11fd2c4e0 | Jorgeteixeira00/CURSO-EM-V-DEO---EXERCICIOS | /Ex28.py | 807 | 4.46875 | 4 | # Exercício Python 028: Escreva um programa que faça o computador "pensar" em um número inteiro entre 0 e 5 e peça para o usuário tentar descobrir qual foi o número escolhido pelo computador.O programa deverá escrever na tela se o usuário venceu ou perdeu.
#Importei a biblioteca Random e a função randint que randomiza... | false |
670ee009fae5d0614817e49e7396e17b21ed2a3f | Jorgeteixeira00/CURSO-EM-V-DEO---EXERCICIOS | /Ex26.py | 471 | 4.125 | 4 | # Exercício Python 026: Faça um programa que leia uma frase pelo teclado e
# mostre quantas vezes aparece a letra "A",
# em que posição ela aparece a primeira vez e em que posição ela aparece a última vez.
f = str(input('Digite uma frase: ')).strip().upper()
print('A letra "A" aparece {} vezes nessa frase'.format(f.c... | false |
8a5c4b17873dfdf37705f91b8c27ea4e774ed86c | Jorgeteixeira00/CURSO-EM-V-DEO---EXERCICIOS | /Ex37.py | 627 | 4.1875 | 4 | # Exercício Python 037: Escreva um programa em Python que leia
#um número inteiro qualquer e peça para o usuário escolher
#qual será a base de conversão: 1 para binário, 2 para octal e 3 para hexadecimal.
num = int(input('Digite um número:'))
print('''
SISTEMA DE CONVERSÃO
[1] BÍNARIO
[2] OCTAL
[3] HEXADECIMAL
''')
o... | false |
1c744073c9e13b0b8b00aeda923185ea169b549a | vScourge/Advent_of_Code | /2021/09/2021_day_09_1.py | 2,804 | 4.15625 | 4 | """
--- Day 9: Smoke Basin ---
These caves seem to be lava tubes. Parts are even still volcanically active; small hydrothermal vents release smoke into the caves that slowly settles like rain.
If you can model how the smoke flows through the caves, you might be able to avoid it and be that much safer.
The submarine g... | true |
b247e24618e9c2263362c18b5b47ef5faad97e54 | abhijitsahu/python | /project_01/parse.py | 1,236 | 4.34375 | 4 | #!/usr/bin/python
# Import sys for exit()
import sys
# Import os for checking the file if present
import os.path
# Check if input has provided
if len(sys.argv) <= 1:
print('Enter file name to parse the content: ./sample.py <filename>')
sys.exit()
# Get input file from commandline arg
input_file = sys.argv[1]
... | true |
de028eba3f662d85d09305eb24ee3989523344ac | Amirkhan73/Algorithms | /Python/fundamentals/easy/pythonIfElse.py | 648 | 4.46875 | 4 | # Task
# Given an integer, , perform the following conditional actions:
# If is odd, print Weird
# If is even and in the inclusive range of to , print Not Weird
# If is even and in the inclusive range of to , print Weird
# If is even and greater than , print Not Weird
# Input Format
# A single line containing a ... | true |
6546d19b2e52da46f3b38810b1d51cb8b6f69fd1 | ianpaulfo/cs-module-project-algorithms | /sliding_window_max/sliding_window_max.py | 1,773 | 4.3125 | 4 | '''
Input: a List of integers as well as an integer `k` representing the size of the sliding window
Returns: a List of integers
'''
# First-Pass Solution
# Find the maximum for each and every contiguous subarray of size k
# Approach: run a nested loop, the outer loop which will mark the starting point of the subarray ... | true |
a1410bca8d6afc93e4f85f096f37e10982a9a050 | mauricejulesm/python_personal_projects | /creating_files/CreateFiles.py | 895 | 4.125 | 4 | # declare an object name ( just any name)
objectForCreating = open("maurice.txt", "w") # this "w" should be ther to prepare the file for writing on to it
objectForCreating.write("Name: Jules Maurice\n")
objectForCreating.write("Age: 23\n")
objectForCreating.write("School: African Leadership University\n")
objec... | true |
4d92a09dd5ecb17cbd97e6645da78ee8ee4d7316 | arijitsdrush/python | /concept/if-else.py | 270 | 4.15625 | 4 | #!/usr/bin/python3
a, b = 10, 12
# Normal if else
if a > b :
print("a ({}) is greater than b ({})".format(a, b))
else:
print("a ({}) is less than b ({})".format(a, b))
# Ternary Operator
c = ("Greater" if a > b else "Lesser")
print("Value of a is {}".format(c)) | false |
661edcb48e2c8949fb7a4c5315ff3aba10c67369 | eltonlee/Practice | /practice/Notes.py | 1,695 | 4.1875 | 4 | # -------------Arrays----------
# Initalize a array of size k with n stuff inside it
a = ['n']*len(k)
# Loop backwards
for i in range(len(something)-1, -1, -1) # range (start, stop before, step)
# sort the array from lowest to highest
a.sort()
# sort the array from highest to lowest
a.sort(reverse=True)
# Set remo... | true |
e2ac7e249de6f3381063dc20282b793f4d8d7df1 | jarabt/Python-Academy | /Lekce05/stringToList.py | 379 | 4.15625 | 4 | """
Write a Python program which prompts and accepts a string of comma-separated
numbers from a user and generates a list of those individual numeric strings
converted into numbers.
"""
stringFromUser = input("Please enter comma separated numbers: ")
l = stringFromUser.split(",")
result = []
for word in l:
word ... | true |
db9d4c1b74746699433293e9f5f690031c9a202a | sharankonety/algorithms-and-data-structures | /Stack/implement_ll.py | 839 | 4.125 | 4 | # Implementing a stack using linked list
class Node:
def __init__(self,data=None):
self.data = data
self.next = None
class Linked_list:
def __init__(self):
self.head = None
def push(self,new_data):
new_node = Node(new_data)
if self.head is None:
self.head ... | true |
9bcb72d92a0a5e64765e78c2d112e9b62c96f961 | sharankonety/algorithms-and-data-structures | /Geeks_for_Geeks_Prob's/linked_lists/count_nodes.py | 960 | 4.15625 | 4 | # program to count the number of nodes in the linked list
class Node:
def __init__(self,data=None):
self.data = data
self.next = None
class Linked_list:
def __init__(self):
self.head = None
def count_list(self):
count = 0
temp = self.head
while temp:
... | true |
dc28c0282c0be6dbc735f7e79e65ce26862a86e6 | sharankonety/algorithms-and-data-structures | /Trees/Binary_Tree/search.py | 1,189 | 4.1875 | 4 | # program to search if a node exists in a tree or not.
class Node:
def __init__(self,data):
self.data = data
self.left = None
self.right = None
def insert(self,data):
if self.data:
if data<self.data:
if self.left is None:
self.left ... | true |
2a04fec5a4d637fb538a33da170c0bc7c249dda6 | sharankonety/algorithms-and-data-structures | /linked_lists/doubly_linked_lists/create.py | 813 | 4.1875 | 4 | # Inserting in a doubly linked list.
class Node:
def __init__(self,data=None):
self.pre = None
self.data = data
self.next = None
class Doubly_linked_list:
def __init__(self):
self.head = None
self.tail = None
def insert(self,new_data):
new_node = Node(new_data... | true |
b85a8c65a50055d40ed0bd2352b7335055691848 | sharankonety/algorithms-and-data-structures | /linked_lists/linear_linked_lists/deletion/deleting.py | 1,561 | 4.1875 | 4 | class Node:
def __init__(self,data=None):
self.data = data
self.next = None
class Linked_list:
def __init__(self):
self.head = None
def Print_list(self):
print_val = self.head
while print_val:
print(print_val.data,end="-->")
print_val = print_v... | true |
149cf5b025db9757d37aaedac1f6c097adf89c36 | carlosmanri/Logic-Thinking | /Carlos/Ejercicios-2/IngresoDatos.py | 1,753 | 4.1875 | 4 | def validarnombre(nombre):
while len(nombre)>12 or len(nombre)<6 or nombre.isalnum()==False:
if len(nombre)>12 or len(nombre)<6:
print("El usuario debe tener un mínimo de 6 caracteres y un máximo de 12.")
if nombre.isalnum()==False:
print("El nombre de usuario solo puede cont... | false |
f252cf151ced6f28de04b9e72fedc98d103360ba | ayush-206/python | /assignment13.py | 1,976 | 4.375 | 4 | #Q.1- Name and handle the exception occured in the following program:
a=3
if a<4:
try:
a=a/(a-3)
except Exception:
print("an Exception occured")
#Q.2- Name and handle the exception occurred in the following program:
l=[1,2,3]
try:
print(l[3])
except Exception:
print("an exception occured")
#Q.3... | true |
2fe4a1d7dabf7e49da3bd244c1957287a7c7604c | Oybek-uzb/py_full_course | /py_full_course/21_stirng_format.py | 1,867 | 4.1875 | 4 | animal = "dog"
item = "moon"
print("The " + animal + " jumped over the " + item)
print("The {} jumped over the {}".format(animal, item)) # yuqoridagiga alternativ
print("The {1} jumped over the {0}".format(animal, item)) # positional arguments, bu usul bilan format ni ichiga berilgan argumentlarning qaysi tartibda tur... | false |
f90231f573c38e66952d5a0f6c1b6f3d9209d819 | Jdamianbello2/cs190 | /CS190/venv/crashcourse.py | 987 | 4.34375 | 4 | name = "salad head"
print(name.upper())
print(name.lower())
simple_message = "I like you too"
print(simple_message)
print("The language 'Python' is named after Monty Python, not the snake.")
first_name = "ada"
last_name = "lovelace"
full_name = first_name + " " + last_name
print(full_name)
print("Hello, " + full_name.t... | true |
47c7676763843267376b3c17461f418bd285f394 | samipsairam/PythonDS_ALGO | /basics/Dictionary_Tut.py | 1,577 | 4.1875 | 4 | # Dictionary is another data structure which in other language is called as 'HashTable' or 'Map' or 'Object' in another language
# Dictionary or dict is a data type or data structure itself
# Have KV pairs
# Dictionary is unordered Key-Value pairs, Unlike List they are not ordered hence cannot be get by index
dictionar... | true |
df4626c4f30fa2562000de499a79170be1969bd1 | diegoortizmatajira/python-learning | /classes/20210721/Chapter-9-Practice.py | 2,944 | 4.28125 | 4 | import datetime
def task01():
print("=========================\nTask 1\n-------------------------")
birth_date = datetime.date(1982, 5, 1)
print(f"Your birthday is: {birth_date}")
today = datetime.date.today()
print(f"Today is {today}")
age = today - birth_date
print(f"Your age today is {a... | false |
8643f4628e3b260434ff2475e0c5fb1a85f5832d | ManuelLoraRoman/Apuntes-1-ASIR | /LM/PYTHON/Ejercicios alternativas/Ejercicio 12.py | 424 | 4.21875 | 4 |
#Escribir un programa que lea un año indicar si es bisiesto.
#Nota: un año es bisiesto si es un número divisible por 4, pero no si es divisible por 100,
#excepto que también sea divisible por 400.
anyo = int(input("Dime un año:"))
if (anyo % 4 == 0 and anyo % 100 != 0) or (anyo % 4 == 0 and anyo % 100 == 0 and ... | false |
33ee2c047ab99d11285c9a7f71776e4d2451f163 | ManuelLoraRoman/Apuntes-1-ASIR | /LM/PYTHON/Ejercicios diccionarios/Ejercicio 4.py | 1,398 | 4.125 | 4 |
#Codifica un programa en python que nos permita guardar los nombres de los alumnos de una clase
#y las notas que han obtenido. Cada alumno puede tener distinta cantidad de notas.
#Guarda la información en un diccionario cuya claves serán los nombres de los alumnos
#y los valores serán listas con las notas de cada ... | false |
caf15d215cc73a389f11351d123ff65bd3de4a4e | ManuelLoraRoman/Apuntes-1-ASIR | /LM/PYTHON/Entrega 1/Ejercicio 3.py | 1,106 | 4.28125 | 4 |
#Escriba un programa que pida tres números y que escriba si son los tres iguales, si hay dos iguales o si son los tres distintos.
#COMPARADOR DE TRES NÚMEROS
#Escriba un número: 6
#Escriba otro número: 6
#Escriba otro número más: 6
#Ha escrito tres veces el mismo número.
#COMPARADOR DE TRES NÚMEROS
#Escrib... | false |
5008d3855f3271694ca799cebb4a2939f9b14245 | ManuelLoraRoman/Apuntes-1-ASIR | /LM/PYTHON/Ejercicios diccionarios/Ejercicio 3.py | 989 | 4.125 | 4 |
#Vamos a crear un programa en python donde vamos a declarar un diccionario para guardar los precios de las distintas frutas.
#El programa pedirá el nombre de la fruta y la cantidad que se ha vendido
#y nos mostrará el precio final de la fruta a partir de los datos guardados en el diccionario.
# Si la fruta no exis... | false |
aad213697313f4f67d999af41119d0e172cae57a | LiuHB2096/Backup | /notes1.py | 421 | 4.28125 | 4 | # This is a comment, use them very often
print (4 + 6) # addition
print (-4 - 5) # subtraction
print (6 * 3) # multiplication
print (8 / 3) # Division
print (3 ** 3) # exponents- 3 to the 3rd power
print (10 % 3) # modulo - gives you the remainder
print (15 % 5)
print (9 % 4)
print (16 % 3)
print (16 % 7)
... | true |
c299f3c87a9935300a0880b7ad7bfa599bd39f6b | divya-nk/hackerrank_solutions | /Python-practice/Strings/captilize.py | 425 | 4.21875 | 4 | import string
def solve(s):
return string.capwords(s, ' ')
# Split the argument into words using str.split(), capitalize each word using str.capitalize(), and join the capitalized words using str.join(). If the optional second argument sep is absent or None, runs of whitespace characters are replaced by a single s... | true |
59bd1f32dd0cb7ed6f999c0079670b852527787c | Nathhill92/PY4E_Exercise | /Code Challenges/ReducePractice.py | 840 | 4.1875 | 4 | #return max
import functools
lis = [ 1 , 3, 5, 6, 2, ]
print ("The maximum element of the list is : ",end="")
print (functools.reduce(lambda a,b : a if a > b else b,lis))
# ruber ducky walkthrough:
# reduce takes two arguments,
# the function logic and the list to to perform the function logic on
# The value of ... | true |
b872bc0979aab82371c80794eebd6dc61b1dab91 | Nathhill92/PY4E_Exercise | /Code Challenges/ColorInverter.py | 649 | 4.46875 | 4 | # Create a function that inverts the rgb values of a given tuple.
# Examples
# color_invert((255, 255, 255)) ➞ (0, 0, 0)
# # (255, 255, 255) is the color white.
# # The opposite is (0, 0, 0), which is black.
# color_invert((0, 0, 0)) ➞ (255, 255, 255)
# color_invert((165, 170, 221)) ➞ (90, 85, 34)
# Notes
# Must ret... | true |
33c48b23e18d00aa230254ee18f1e48a62b29138 | Nathhill92/PY4E_Exercise | /Code Challenges/OOPCalculator.py | 1,061 | 4.53125 | 5 | # Simple OOP Calculator
# Create methods for the Calculator class that can do the following:
# Add two numbers.
# Subtract two numbers.
# Multiply two numbers.
# Divide two numbers.
# Examples
# calculator = Calculator()
# calculator.add(10, 5) ➞ 15
# calculator.subtract(10, 5) ➞ 5
# calculator.multiply(10, 5) ➞ 50
#... | true |
b38c4fc99ad9bfafa16e07237e3dcb2f89c0496e | Nathhill92/PY4E_Exercise | /chap2.py | 1,177 | 4.625 | 5 | #Chapter 2 exercises
#https://www.py4e.com/html3/02-variables
#Write a program that uses input to prompt the user for their name and then welcomes them
# name = input("Hello! What is your name? ")
# print("Hello " +name)
# print()
#Write a program to prompt users for hours and hourly rate to compute gross wage
hours... | true |
71ac0a3e35fa69cdaf0574332f49a51213594dc7 | Hassan-Farid/DAA-Assignments | /Minimum Numbers/QuadraticMin.py | 670 | 4.21875 | 4 | def findQuadMin(arr):
'''
Sorts the values in the given array in O(n^2) time in ascending order
and returns the first index value i.e. minimum value
'''
for j in range(1, len(arr)):
key = arr[j]
i = j - 1
while i >= 0 and arr[i] > key:
arr[i+1] = arr[... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.