blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
72b47792b2fd0f9fb5ebec1af6c671d042658223 | Minu94/PythonWorkBook1 | /luminar_for_python/language_fundamentals/functional_progrmng/mapp_filter.py | 542 | 4.0625 | 4 | ## map,filter
# # map() apply to each element(if we want to find square of each element in a list)
# map accept two argument :: function and iterable
# #filter not apply to each element (in a list if want to extract element of length 2)
lst=[10,20,21]
def squares(no):
return no*no
data=list(map(squares,lst)) #squ... |
d42b495490c5c1c85c71165a80ce012162290d3e | dappletonj/cse210-tc04 | /hilo/game/director.py | 4,701 | 4.09375 | 4 | from game.dealer import Dealer
class Director:
"""A code template for a person who directs the game. The responsibility of
this class of objects is to keep track of the score, control the
sequence of play, and determine if the player can keep playing.
Attributes:
score (number): The tota... |
fc44b177bddec47635601a1ea1d65e42e636f6c2 | mtholder/eebprogramming | /lec2pythonbasics/fast_factor.py | 1,261 | 4.0625 | 4 | #!/usr/bin/env python
import sys
import math
if len(sys.argv) != 2:
sys.exit(sys.argv[0] + ": Expecting one command line argument -- the integer to factor into primes")
n = long(sys.argv[1])
if n < 1:
sys.exit(sys.argv[0] + "Expecting a positive integer")
if n == 1:
print 1
sys.exit(0)
def factor_int... |
467d31899bee92861eadbb98039b25bf26165a27 | tzvetandacov/Programming0 | /week8/basic_sort.py | 434 | 3.625 | 4 | A = [2, 0, 10, -2, 5, 1, -5]
B = []
def min_element(numbers):
min_index = 0
index = 0
for number in A:
if number < A[min_index]:
min_index = index
index += 1
return min_index
print(min_element(A))
def basic_sort(numbers):
n = len(A)
while A > []:
#while len(B) !... |
c73ccce6940073417d11e81476a2961fdbd73ce7 | samkarki/CrackingCodingInterview | /chapter2/partition.py | 1,311 | 3.984375 | 4 |
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
def __str__(self):
return str(self.data)
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
def print_Linkedlist(self):
node = []
current = self.h... |
4bfea643488cb77e5b52d483b63b4102dd11d11b | thammaneni/Python | /Practice/DateTimeExcercise.py | 284 | 4.0625 | 4 | from datetime import date
from datetime import time
from datetime import datetime
today = date.today()
print (today)
print (today.day, today.month, today.year)
today = datetime.now()
print ("Current date is :", today)
time = datetime.time(today)
print ("Current time is : ", time) |
8d46a0c495e5dd1e65325e7e0d065a522270204e | SuminPark-developer/Twitter_Realtime_Plot_With_Sentiment_Analysis | /Tutorial_Plotting Live Data in Real-Time/Plotting Live Data.py | 997 | 3.625 | 4 | import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
plt.style.use('fivethirtyeight')
frame_len = 10000
fig = plt.figure(figsize=(9, 6))
def animate(i):
data = pd.read_csv('tweet data.csv')
# data['Create_Time'] = pd.to_datetime(data['Create_Time']) # https://e... |
9ad6372f1990c0bf87835f2cc9cc0edb20415089 | RubelAhmed57/Python-Bangla | /listEx.py | 389 | 3.90625 | 4 | item = [1, 2,4,3,5,6,7,8]
print(type(item))
item2 = ["A", "C", "B"]
print(item2)
print(" sort function")
resize = list(sorted(item))
print(resize)
print("Reverse function")
re = list(reversed(resize))
print(re)
print(" adding system ")
resize.append(9)
print(resize)
print("Remove system ")
resize.remove(1)
prin... |
599b94feb0d6cc049aaf900691bbf9c903c6e950 | Vahid-Esmaeelzadeh/CTCI-Python | /LeetCode Contests/Contest 189/1451. Rearrange Words in a Sentence.py | 1,650 | 3.953125 | 4 | # 1451. Rearrange Words in a Sentence
import math
def arrangeWords(text: str) -> str:
count_word_map = {}
words = text.split()
for word in words:
if len(word) in count_word_map:
count_word_map[len(word)].append(word.lower())
else:
count_word_map[len(word)] = [word.l... |
092c1887b959f133984840f901e33cf434c55032 | jeremychodges/NumberOfTheDay | /NumberOfTheDay.py | 2,927 | 3.71875 | 4 | #!/usr/bin/python
# encoding: utf-8
import random
import os
import sys
import subprocess
global maxNum
global minNum
subprocess.Popen(["say", "-v", "Fred", "Pick", "a", "number..."])
dailyNum = int(raw_input("What is the number of the day: "))
iterations = int(raw_input("How many examples would you like: "))
def g... |
2e858dee1218898496603005871e99b4cf871757 | sumittal/coding-practice | /python/find_array_size.py | 2,438 | 3.90625 | 4 | #!/bin/python
import sys
import os
# CalculateArraySizeTest
# The idea behind the test is to find the size of an array.
# The Array is virtual and is not implemented as a traditional memory array.
# Actual implementation is hidden, but the array elements may be accessed by
# the methods provided by this class.
#
#... |
013f5eba6796a24ca258ef9502e710770df94733 | rhenderson2/python1-class | /chapter08/hw_8-6.py | 311 | 3.984375 | 4 | # homework assignment section 8-6
def city_country(city, country= 'US'):
full_city_country = f'"{city}, {country}."'
return full_city_country.title()
city01 = city_country("nashvill")
print(city01)
city02 = city_country('columbus')
print(city02)
city03 = city_country('london', 'england')
print(city03) |
3fde5b1997416e15e6ef16009f60d8a6aec9e1d7 | JOLLA99/Algorithm-Study | /07_이인재/Week1/2753.py | 111 | 3.65625 | 4 | year = int(input())
if (((year%4 == 0) and (year%100 != 0)) or (year%400==0)):
print(1)
else:
print(0) |
465499875fe3b0246732e4dab83c4db79feaef1c | pk1397117/python_study01 | /study01/day04/08-元组的的使用.py | 1,060 | 4.3125 | 4 | # 元组和列表很像,都是用来保存多个数据的
# 使用一对小括号 () 来表示一个元组
# 元组和列表的区别在于,列表是可变数据类型,而元组是不可变数据类型
words = ["hello", "yes", "good", "hi"] # 列表,使用 [] 表示
nums = (9, 4, 3, 1, 7, 6) # 元组,使用 () 表示
# 元组和列表一样,也是一个有序的存储数据的容器
# 可以通过下标来获取元素
print(nums[3])
print(nums.count(9))
print(nums.index(9))
# 特殊情况:如何表示只有一个元素的元组?
age = (18,) # 如果元组里只有一个元素... |
3606e1f117e4231a216dc7922b8cdbbd328189ee | Carlosx71/estudos | /EstudosPython/exe043.py | 447 | 3.921875 | 4 | altura = float(input('Altura: '))
peso = float(input('Peso: '))
imc = peso / (altura * altura)
if imc <= 18.5:
print('Você esta abaixo do peso!!!')
elif imc >= 18.6 and imc <= 25.99:
print('Você esta com o peso ideal!!!')
elif imc >= 26 and imc <= 30.99:
print('Você esta com sobrepeso!!!')
elif imc >= 30 ... |
2b98bc078d6f180a185d114027cf501cac96892d | Havrushchyk/pass | /Prepare_the_filtered_test_data.py | 1,584 | 3.5 | 4 | import itertools
import pandas as pd
alphabet="123456789FGJLNRSWYZ"
all_combinations = itertools.product(alphabet, repeat=8)
df = pd.DataFrame(columns=list('ABCDEFGH')) # ABCDEFGHI
j=0
number_iter=0
for row in all_combinations:
k=1
print("\r {0} - {1}".format(row,number_iter), end='') ... |
c2bfcfa7ff661f7979bfabb1e90f0db47cfd2def | mhee4321/python_algorithm | /programmers/Level1/intReverseToArray.py | 248 | 3.78125 | 4 | def solution(n):
n = list(str(n))
# n.sort(reverse=True)하면 내림차순 정렬이 되어버림
n.reverse()
return list(map(int, n))
def digit_reverse(n):
return list(map(int, reversed(str(n))))
n = 12345
print(solution(n)) |
9e7de6ab142c420fed417c0530199caafc621bae | houhailun/leetcode | /剑指offer/57_II_和为s的连续整数序列.py | 1,036 | 3.53125 | 4 | #!/usr/bin/env python
# -*- encoding:utf-8 -*-
class Solution(object):
def findContinuousSequence(self, target):
"""
:type target: int
:rtype: List[List[int]]
"""
# 双指针法,start=1,end=2
# 1. start,...end之间元素和小于target,则end+=1
# 2. start,...end之间元素和大于target,则star... |
b8abca919dfd800209b510405c044b79ad8b7c0e | gpleee/Goldworld | /Programmers/programmers_Prodo.py | 488 | 3.5625 | 4 | def solution(record):
for i in record:
answer = []
#입장
if record[i][0:5] == "Enter":
print(record[i].rfind(' '))
a = record[record[i].rfind(' ')+1 : ]
answer.insert(0, a + "님이 들어왔습니다.")
#퇴장
elif record[i][0:5] == "Leave":
... |
e20d9c18f2e6583d6394538fb51333d40b2ac913 | Applejuice186/Applejuice186 | /Asteroids/flying_objects.py | 1,199 | 3.5 | 4 | """
Program:
CS241 Assignment 11, Asteroids Project
Instructor:
Borther Macbeth
Author:
Aaron Jones
Summary:
This program will be the top of the hierarchy that other
programs will derive from. Its base values will be passed
through to other classes through polymorphism.
... |
b7ebc7cd5086369fd705e15665c9de5a8844b0dc | rupali23-singh/task_question | /attende.py | 161 | 3.796875 | 4 | x=int(input("enter the number"))
y=int(input("enter the number"))
present = x/y*100
if present >= 75:
print("allowed hai")
else:
print("allowed nhi hai") |
b3aa035d7726760b657691c9cc19b412fa03850d | mstelwach/CodeWars---Solutions | /tests/kyu_6/your_order_please.py | 137 | 3.59375 | 4 | def order(sentence):
words = sentence.split()
return ' '.join([word for i in range(1,10) for word in words if str(i) in word])
|
ebdd42f1330e12b6694f4b7ae18ded3c6ac936aa | joshuajz/grade12 | /1.functions/Assignment 3d.py | 1,972 | 3.9375 | 4 | # Author: Josh Cowan
# Date: October 8, 2020
# Filename: Assignment #3c.py
# Descirption: Assignment 3: Password Checker
import string, random, time
# List of the entire alphabet (string.ascii_letters) + numbers
digits_letters = string.ascii_letters + "123456789"
# Creates a random password
def random_pwd... |
0b690f0a82d5740ad54263f34989c76e34b7d07d | razaali11110/PythonPrograms | /tuple to string.py | 387 | 3.796875 | 4 | a=("2","3","4","5","6","7")
sep=" "
print(sep.join(a))
print(a)
# create tuple object and assign it to variable t
t = ('Jan','Feb','Mar','Jan')
# create single space string and assign it to variable separator
separator = ' '
# call join() method on separator by passing tuple t as an argument
output = separ... |
f88188640daca822de003171e533741e6aa1cadc | Kalyan-Amarthi/100-days-python | /29.py | 782 | 3.828125 | 4 | '''n = int(input('Enter value of n: '))
for i in range(1,(2*n)+1):
for j in range(1,(2*n)+1):
if i==n or j==n:
print('*', end='')
elif i< n and j==1:
print('*', end='')
elif i==1 and j >n:
print('*', end='')
elif i>n and j==2*n:
... |
9e31681742b5258d5fa6acb762b5b70a5aed2bbb | Orenjonas/school_projects | /python/flask_web_application/temperature_CO2_plotter.py | 4,618 | 3.671875 | 4 | import matplotlib
matplotlib.use('Agg') # pyplot backend for web server usage
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import io
import base64
"""
Module used for plotting various csv data of temperature and CO2 emissions.
"""
def get_temperature_months_and_years():
"""Returns a list... |
143c9be2c3f102be8841c6c1188afa0fc6a32e2c | Andromeda2333/ImageProcessing | /Demo_6_17_2014/test/test_list.py | 216 | 3.5625 | 4 | #coding=utf-8
'''
Created on 2014年6月19日
@author: lenovo
'''
L=[1,23,23,2,3,2,4,34,3]
print L
L.extend([12,43,43,5,34])
print L
L.append([2,4,4])
print L
L.remove(2)
print L
del L[-1]
print L
L=[231]+L
print L |
a318110123b525fcd28cbbcd4e3060734cadb2fb | AsjadA/Kaprekars | /Kaprekars.py | 711 | 3.609375 | 4 | def Kaprekar(num):
num=str(num)
count=0
value=num
while value!="6174":
if len(value)==3:
value=value+"0"
elif len(value)==2:
value=value+"00"
elif len(value)==1:
value=value+"000"
array=[]
ascendfinal=""
d... |
55dcf7d1afd192a6b47fa4074667a79dc19eb6c8 | washingtoncandeia/PyCrashCourse | /15_Dados/rw_visual3.py | 532 | 3.515625 | 4 | import matplotlib.pyplot as plt
from random_walk import RandomWalk
"""rw_visual.py, p.432"""
while True:
# Cria um passeio aleatório e plota os pontos
rw = RandomWalk()
rw.fill_walk()
# Plots
point_numbers = list(range(rw.num_points))
plt.scatter(rw.x_values, rw.y_values, c=point_numbers, cma... |
7a41bb309e9efda9fc88b3b47075d43944d09142 | urskaburgar/python-dn | /naloga-8/secret_number/secret_number.py | 280 | 3.953125 | 4 | secret = 15
guess = int(input("Guess the secret number (between 1-20): "))
if guess == secret:
print("Congratulation, you guessed the correct number! ")
else:
print("Sorry, you didn't guess the correct number! It's not " + str(guess) + "!")
print("Konec programa! ")
|
9b840d406133e73c49ebe6153aa6f6c6959d7310 | ekimekim/pylibs | /tests/test_partialorder.py | 1,115 | 3.859375 | 4 | import functools as ft
from partialorder import partial_ordering
@partial_ordering
class N(object):
"""A numeric object that is only comparable with other values that share an integer factor"""
def __init__(self, value):
self.value = value
def __repr__(self): return "<{} {}>".format(self.__class__.__name__, self.... |
b2503b1f37138dc3a91b0c9c02b7a471828ff6b3 | Oleh-Kenny/python | /dz-4mass/next2.py | 732 | 3.921875 | 4 | #Дано список(А) із К елементів (К- парне число). Утворити 2 списки(В і С),
# переписуючи у списку В першу половину масиву А,
# у список С – другу половину масиву А
a = int(input("Введіть початок інтервалу: "))
b = int(input("Введіть кінець інтервалу: "))
spisok = [1,2,3,4,5,6,7,8,9,10,22,33,44,55,11,34]
interval = ra... |
4b27539a98bde3e7df4507ad2e346220cbc04a28 | LasMetricas/Python-Mini-Projects | /PhoneNoValidation.py | 1,474 | 4 | 4 | #! python 3
import re
def isPhoneNumber(no):
# if len(no)!=12:
# return False
# for i in range(0,3):
# if not no[i].isdecimal():
# return False
# if no[3]!='-':
# return False
# for i in range(4,7):
# if not no[i].isdecimal():
# return False
# if no[7]!='-':
# return False
# for i in range(8,12):... |
22cce4eab438a877ff4f88bf39365c91a831adcf | AlexJOlson/CS111_Connect4 | /Connect4.py | 15,585 | 3.828125 | 4 | # Connect4.py
# Anna Meyer, Alex Olson, CS111, Fall 2014
from button import *
from graphics import *
from random import *
def drawButtons(window):
""" Makes and returns a list of all the buttons, each of which correspond
to a column, and will be used to place tiles on the board. """
button1 = Button(... |
323d5de7fec0a5bf30b67cda675c84f89abd46c7 | tanzimzaki/Python_EH | /Password_Cracker.py | 1,601 | 3.84375 | 4 | #!/usr/bin/python
#Tanzim_Zaki_Saklayen
#ID:10520140
import crypt #Cyrpt module is retrieved to generate a hash for specific salt to crack UNIX passwords with dictionary
shadowlist = input("Enter the shadow file you want: ") #user is prompt to insert the retrieved shadow file
passwordlist= input("Enter the password ... |
890068f1d15d581614f61e869084b8a8b7f81fd8 | amourlee123/leetcode | /LC203_RemoveLinkedListElements.py | 756 | 3.859375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Definition for singly-linked list
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def removeElements(self, head, val):
"""
type head: ListNode
type val: int
rtype: ListNode
... |
d96eb4d384e04f1ebdbda641d4790036685881c1 | Nateque123/python_tutorials | /chapter5_list/split_join.py | 209 | 3.859375 | 4 | """Join and Split Methods"""
# Split Method to convert string into list
# name1 = 'nateq 23'.split()
# print(name1)
# Join Method to convert list into string
# name2 = ['nateq','23']
# print(','.join(name2)) |
9252b1a660d32315253f8e0c6878f5c6091a3490 | WilbertHo/leetcode | /easy/pascals_triangle/py/pascalstriangle.py | 760 | 4.0625 | 4 | """
Given numRows, generate the first numRows of Pascal's triangle.
For example, given numRows = 5,
Return
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
"""
from collections import deque
class Solution(object):
# @return a list of lists of integers
def generate(self, numRows):
if num... |
f98f4ce4f594fb6d407de5040de8d90dcc909b08 | bmandiya308/python_trunk | /numpy_ops/numpy_ops.py | 5,137 | 4.25 | 4 | '''
NumPy is a Python package. It stands for 'Numerical Python'. It is a library consisting of multidimensional array objects
and a collection of routines for processing of array.
'''
import numpy as np
#N-dimensional array
a = np.array([1,2,3])
print(a)
# more than one dimensions
a = np.array([[1, 2], [3, 4]])
prin... |
367a0a038cd17723cd2a8b422758e86d5b73e09e | manishshiwal/guvi | /factorial.py | 78 | 3.734375 | 4 | a=int(raw_input("enter the number"))
s=1
for n in range(1,a+1):
s*=n
print s
|
35e7eca625c21461ea40448c6160f477139119af | menard-noe/LeetCode | /Minimum Depth of Binary Tree.py | 862 | 3.765625 | 4 | # Definition for a binary tree node.
import math
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def __init__(self):
self.ans = []
def minDepth(self, root: TreeNode) -> int:
if r... |
975e4914314528aba42ed09149e403fb1cd47a8b | saulorodriguesm/ifsp-exercises | /Python/Lista 2/exer14.py | 627 | 3.578125 | 4 | val1 = input("Melhor matéria do 2º Semestre: \n a) LP2 \n b) ADM \n c) SO \n d) ESW \n")
val2 = input("\nMelhor time do Brasil: \n a) Flamengo \n b) Palmeiras \n c) São Paulo \n d) Corinthians\n")
val3 = input("\nMelhor herói: \n a) Superman \n b) Batman\n c) Homem-Aranha\n d) Hulk\n")
resultado = 0
if val1 == "a":
... |
02bce76a2c700c99918e41cafd56cf02b28f53ac | jinsuwang/GoogleGlass | /src/main/python/DP/Maximum_Subarray.py | 452 | 3.59375 | 4 | from sys import maxint
class Solution(object):
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums: return 0
max_val = 0
sol = -maxint
for i in range(0,len(nums)):
max_val = max(nums[i], max_val+nums[i])
... |
858edbbb18d40817d7fb56ee56164cda278eb7ae | saikrishna6415/python-problem-solving | /numstar.py | 160 | 3.609375 | 4 | n = int(input("enter number : "))
for i in range(n,0,-1):
print((i)*" "+( str(i)+ " ")*(n-i+1))
# enter number : 4
# 4
# 3 3
# 2 2 2
# 1 1 1 1
|
68f35f796d7ef127749742ddd0611901e6b3921a | GhazanfarShahbaz/interviewPrep | /recursion_and_dynamic_programming/parens.py | 628 | 3.828125 | 4 | def generateParens(num: int) -> list:
if num == 0:
return []
parentheses = set()
generate("()", parentheses, num)
return parentheses
def generate(string: str, arr, n):
if(len(string) == n*2):
arr.add(string)
else:
for x in range(len(string)-1):
if (string[x]... |
bd61409e71446d7121362e7e08f92a5804f58507 | bremiy/shiyanlou-code | /jump.py | 146 | 3.609375 | 4 | a = 1
while a<101:
if a%7 ==0:
pass
elif a//10 == 7:
pass
elif a%10 == 7:
pass
a = a+1
continue
else:
print(a,end = ' ')
a = a+1
|
88815f36edc30bbe39ef3c886691138efa21ed5e | culeo/LeetCode | /Python/DynamicProgramming/test_delete_operation_for_two_strings.py | 1,092 | 3.890625 | 4 | # coding: utf-8
def min_distance(word1, word2):
"""
583. Delete Operation for Two Strings(两个字符串的删除操作)
Given two words word1 and word2, find the minimum number of steps required to make word1 and word2 the same,
where in each step you can delete one character in either string.
Example 1:
... |
d878b0572007e7c4fd2f8950fb8eb7703f55d29c | javiervar/EstructuraDeDatos | /Practicas/practica3_fibonacciIterativo.py | 206 | 4.15625 | 4 | #funcion que devuelve la suma de un numero con el anterior de forma recursiva
def fibonacciIterativo(num=1):
a, b = 0,1
while a < num:
print(a)
a, b = b, a+b
fibonacciIterativo(50) |
6485866499ddf5777f7d4558ecd9bd42e2559f8c | ryandw11/Chat | /code.py | 908 | 3.890625 | 4 | print ('Welcome to Ryandw11 chat')
print ('what is your user name?')
user = input()
print ('Welcome ' + user + ', to ryan chat!')
usern = '[' + user + ']'
e = 1
r = 0
while e > r:
e = e + 1
a = input()
String = a
if a == 'Stupid':
print ('Error: "stupid" is not a vaild word')
elif a == 'idio... |
2f2f68f1b39583219e924d1f590de7f7a9f320eb | vyshakrameshk/EDUYEAR-PYTHON---20 | /Day16-practice.py | 1,342 | 3.9375 | 4 | # print("om namah shivaya !")
# print("Hello World !")
import numpy as np
# import numpy
# from numpy import *
# from numpy import arange
# print(type(np)) #class module
# import sys
# a = [1,2,3,4,5]
# print(sys.getsizeof(1) * 5) #140 -> 140/5=28 Bytes
# b = np.array([1,2,3,4,5])
# print(b.itemsize... |
f522c11c725275bba7c1655a33846f3f4a16d17d | di37/Unit1 | /Palindromechecker.py | 135 | 3.953125 | 4 | #Palindrome checker
word = 'madam'
if (word[::-1] == word):
is_palindrome = 0
else:
is_palindrome = -1
print (is_palindrome)
|
3e76b55b9e53fd2504d45f2d2eab763066ea7d6d | ryousuke-seki/Sudoku | /Project/DFS.py | 5,385 | 3.515625 | 4 | import os
import sys
class Sudoku_DFS():
# データを初期化
def __init__(self):
# 小枠の大きさ
self.n = 2
# 大枠と数値の終端を定義
self.N = self.n * self.n
# 問題の全ての配列を0で初期化する
self.question = [[0 for i in range((self.N))] for j in range((self.N))]
# 横行に答えがあっているか調べる
def checkQu... |
d51d15db367d85cdc5fcdff6dbea60ff21f88f6d | adityaaggarwal19/data-structures-MCA-201 | /Stack_LinkedList.py | 1,336 | 3.84375 | 4 | class Node:
def __init__(self,value):
'''
OBJECTIVE:
Input Parameter
'''
self.data=value
self.next=None
class Stack:
def __init__(self):
'''
'''
self.top=None
def push(self,value):
if self.top == None:
... |
1b0b9efbbe61f2896749eef1fb7c2b5936c0ad9c | milson389/metode-numerik | /535180021_AudieMilson_UTS/nomor3.py | 412 | 3.859375 | 4 | # Audie Milson(535180021)
userInput = int(input('Masukkan jumlah barang yang ingin dimasukkan : '))
listBarang = []
listDuplicate = []
jumlah = {}
for i in range(userInput):
barang = input('Masukkan nama barang : ')
listBarang.append(barang)
print(set(listBarang))
dictionary = {i: listBarang.count(i) for i ... |
c0be7c8eb91672edd56342a37214641082632f0c | taroserigano/coderbyte | /Recursion/StringReduction.py | 1,529 | 4.1875 | 4 | '''
String Reduction
HIDE QUESTION
Have the function StringReduction(str) take the str parameter being passed and return the smallest number you can get through the following reduction method. The method is: Only the letters a, b, and c will be given in str and you must take two different adjacent characters and r... |
0a9d6b03a294bc0db5c0dcada4ca6855b8a6cae7 | chkp-yevgeniy/Python_examples_collection | /advanced/csv_dictReader.py | 535 | 3.96875 | 4 | #!/usr/bin/python3
import csv
#input_file = csv.DictReader(open("people.csv"))
# for item in input_file:
# print("dict item: "+str(item))
# print(item["name"])
with open('people.csv', newline='') as csvfile:
reader = csv.DictReader(csvfile, delimiter=";")
print("Reader type: "+str(type(reader)))
for row ... |
62e91c11276a4b0aad7e0e39951878f956d03862 | saulmont/programacion_python | /Bases/ley_signos.py | 524 | 3.96875 | 4 | # LEY DE SIGNOS
# 1. Menos por menos es igual a mas
a = -1
b = -1
res = a * b
print("1) {a} * {b} = {res}".format(a = a, b = b, res = res))
# 2. Menos por mas es igual a menos
a = -1
b = +1
res = a * b
print("2) {a} * {b} = {res}".format(a = a, b = b, res = res))
# 3. Mas por menos es igual a menos
a = +1
b =... |
65dda3af1961f5d626e027fbd00772c30e09073b | sqrvrtx/AoC2017 | /day6unfinshed/day6.py | 709 | 3.515625 | 4 | data_str = "11 11 13 7 0 15 5 5 4 4 1 1 7 1 15 11"
data = [int(x) for x in data_str.split()]
print data
length = len(data)
cycles = [data]
def get_highest(data_input):
z = [(x, i) for i,x in enumerate(data_input)]
return sorted(z, key=lambda x: x[0], reverse=True)[0]
def distribute(da... |
9906795d86eaa7d028f2c7635fe701af96f16d8c | tigransargsyan1994/Tigran_Sargsyan_My_projects | /Homework_1/sum_of_1_to_10.py | 133 | 3.9375 | 4 | summa = 0
list1 = [1,2,3,4,5,6,7,8,9,10]
for x in list1:
summa = summa + x
print('Sum of numbers between 1 and 10 is : ', summa)
|
d0d990ef5b699e38d1182c714e32c1d7d4232ae0 | ThEfReAkYgEeK/Python-Learning | /Numpy/06AssigmentOperations.py | 619 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat May 9 01:24:22 2020
@author: rsu1
"""
import numpy as np
#To create a array of integers
a=np.ones((2,3),dtype=int)
#To create a array of float
b=np.random.random((2,3))
print("a = ",a)
print("b = ",b)
#Elements of a will be added with 3 and teh result wi... |
9db360ac5e1df032c34321713ef5f287510d6309 | Taomengyuan/Demo | /Pythonbasic/day1-5/demo17.py | 568 | 3.71875 | 4 | #while...else和列表实现1~9的平方
'''
list1=[1,2,3,4,5,6,7,8,9]
total=len(list1)
i=0
print("计算1~9的平方:")
while i<total:
square=list1[i]*list1[i]
print(i+1,"的平方是:",square)
i=i+1
else:
print("循环正常结束:")
'''
list1=[1,2,3,4,5,6,7,8,9]
total=len(list1)
i=0
print("计算1~9的平方:")
while i<total:
square=list1[i]*list1[i]
... |
70d1d1ea37fddef79bacc30510988ecc3de1dd71 | much-to-learn2/Singleton | /Singleton.py | 1,604 | 4.28125 | 4 | """
Python Singleton class
The first time the Singleton class is created, instance is None and so
the instance is created by
# cls.instance = super().__new__(cls)
Once an instance exists, the Singleton.instance attribute will point to
that singular instance. Therefore, creating "new" Singleton instances becomes... |
fecdc68843ef2fac7bb29c9b4c5ab546e3ab98b4 | Lettuce222/NLP-100knocks | /0-9/5.py | 756 | 3.5 | 4 | import re
def word_split(str):
_words = re.split('[ ]', str)
words = []
for word in _words:
words.append(word.strip(',.'))
return words
def word_ngram(str,n):
words = word_split(str)
result = []
for i in range(len(words)-(n-1)):
gram = []
for j in range(n... |
ccc568ed1b9585e8cd8e4da2d661aa6ed9b74945 | Ford-z/LeetCode | /409 最长回文串.py | 788 | 3.75 | 4 | #给定一个包含大写字母和小写字母的字符串,找到通过这些字母构造成的最长的回文串。
#在构造过程中,请注意区分大小写。比如 "Aa" 不能当做一个回文字符串。
class Solution:
def longestPalindrome(self, s: str) -> int:
Dict={}
for i in range(len(s)):
if(s[i] in Dict):
Dict[s[i]]+=1
else:
Dict[s[i]]=1
ans=0
... |
508daa49577aa38997ef453d0daa1c813b9e7fb3 | SousaPedro11/solid | /python/5 - Dependency Inversion/base.py | 985 | 3.578125 | 4 | from enum import Enum
class Time(Enum):
AZUL = 1
VERMELHO = 2
PRETO = 3
class Jogador:
def __init__(self, nome) -> None:
self.nome = nome
class IntegranteTime:
def __init__(self) -> None:
self.integrantes = []
def adicionar_integrante(self, jogador, time):
self.int... |
7ea9ad8270e87f35404a99662e1b9ea197938cf0 | uoflCoder/Learning-Python-The-Hard-Way | /Exercise36.py | 846 | 4.15625 | 4 | #Exercise 36
def main():
print("You enter the pharaoh's tomb...")
print("There is a relic in the middle of the room what do you do?")
print("Grab it")
print("Explore")
print("Pick up a rock")
decision = input(">")
if(decision.upper() == "GRAB IT"):
booby_trap(1)
elif(decision... |
de5e7a045e6425046f9d7b00883c077c653158e8 | Arsen0312/if_else_elif | /problem5.py | 230 | 4.0625 | 4 | a = int(input('Введите число\n'))
if a % 2 == 0:
print('число чётное')
if a % 3 == 0:
print('Число делится на 3 без остатка')
a = (a**2)
if a > 1000:
print('A больше 1000') |
8df663524cfd6b526da7b2c463fa6a163fa505f3 | takaooo0/Python.py | /4-7.py | 203 | 3.71875 | 4 | print('文字を2つ入力してください。')
n=int(input('1つ目の文字:'))
m=int(input('2つ目の文字:'))
if n==m:
print('同じ文字です')
else:
print('異なる文字です') |
998ee17d7bcef5b72ab36a2905462bbb9a3b2955 | vansun11/tensorflow-Deep-learning | /autoencoder.py | 3,295 | 3.6875 | 4 |
""" Auto Encoder Example.
Using an auto encoder on MNIST handwritten digits.
[MNIST Dataset] http://yann.lecun.com/exdb/mnist/
"""
from __future__ import division, print_function, absolute_import
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
#import mnist data
from tensorflow.exam... |
0f6095279662f267232b0329440d311b81ddd3b2 | KnorrFG/pyparadigm | /doc/examples/stroop.py | 9,879 | 3.984375 | 4 | """ This script contains an example implementation of the stroop task.
The easiest way to understand this code is to start reading in the main
function, and then read every function when it's called first
"""
import random
import time
import csv
from collections import namedtuple
from enum import Enum
from functools... |
5822f30701d9c1bd3b83f4d1ccf9e0c726e21fde | FatimaYousif/Python | /lab2/task5.py | 89 | 4.125 | 4 | #task 5:
arr=[2,3,4,6];
arr.sort()
print("the largest element is= " +str(arr[-1]))
|
699bce0d94545231e615e4958d8246fc027010bb | euanstirling/udemy_2021_complete_bootcamp | /my_work_python_2021/section_3_objects_and_data_structures/string_methods_and_properties.py | 1,581 | 4.46875 | 4 |
#! STRING METHODS AND PROPERTIES
# * Immutability
# * We would like to change the name Sam to Pam
#! name = "Sam"
#! name[0] = "P"
#! This does not work are 'str' object does not support item assignment
# * To do this, we need to concatinate using the slice function
name = "Sam"
# * First we would slice the lett... |
9bf51c8f78d34bdd601e8e27e139f315f94a93af | balloontmz/python_test | /a_important/creatcount.py | 365 | 3.8125 | 4 | # -*- coding: utf-8 -*-
def createCounter():
a=(x for x in range(1,10))
return lambda :next(a)
# 测试:
counterA = createCounter()
print(counterA(), counterA(), counterA(), counterA(), counterA()) # 1 2 3 4 5
counterB = createCounter()
if [counterB(), counterB(), counterB(), counterB()] == [1, 2, 3, 4]:
pri... |
e0b9d4ce9236487317f503183b0a78050fb84956 | magcurly/Data_Structure | /Homework-Part5/Bin-Tree.py | 5,555 | 3.640625 | 4 | class BinTreeNode:
def __init__(self,dat):
self.data=dat
self.left=None
self.right=None
def GetData(self):
return self.data
def SetData(self,item):
self.data=item
def SetLeft(self, L):
self.left=L
def SetRight(self,R):
self.right=R
class BinT... |
4f01ef22068882e178867bdf590a1f95733ed448 | Jinyu97/python | /생성소멸자.py | 442 | 3.59375 | 4 | class Car:
man=4
def __init__(self, _man=4): #생성자는 객체 만들 때 자동 수행(c1, c2 만들때마다 수행하므로 init 2번 출력)
print('init')
self.man=_man
def run(self):
print('run')
def __del__(self): #소멸자는 객체가 사라질 때 자동 수행
print('del')
#자동차 생성과 동시에 4/6인용 결정
c1=Car(6)
c2=Car()
print(c1.... |
32bc4ea0a3466e771871145a5b82303ac2d933a3 | paweldata/Kurs-Pythona | /lista2/zad5.py | 3,902 | 3.640625 | 4 | from random import SystemRandom
from random import getrandbits
from math import gcd
import sys
# Miller–Rabin primality test
def isPrime(number):
systemRandom = SystemRandom()
if number == 2:
return True
if number < 1 or number % 2 == 0:
return False
s = 0
d = number - 1
whil... |
2cdc93873ecc6b94e8d7aa0041c760dc6f5a4534 | JupiterWalker/algorithm016 | /Week_04/102_二叉树的层序遍历.py | 695 | 3.6875 | 4 | # coding:utf-8
__author__ = 'cwang14'
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
if not root:
return ... |
86720323437e58fc04b07299d8da4893f65bf66c | LucasKiewek/PythonPrimeChecker | /isPrime.py | 1,818 | 4.375 | 4 | # Lucas Kiewek
# Oct 18, 2017
# Primality Test
# Input a number and it will tell you wether it is prime or not.
import math
from time import *
def is_prime(n, isPrime):#primality test function
s=n%6 # setting s to the remainder of your number divided by six
print "remainder: ", s
if (s==1) or (s==5... |
473cb1c030f79fad0315afbce7b295907d7c5ee5 | OleksiiDovhaniuk/GCG_v1.0 | /algorithm.py | 13,393 | 3.671875 | 4 | import random
class Genetic():
""" Contains all ginetic algorithm stages.
Each function of the modul represent stage of genetic algorithm.
Args:
sgn_no (int): number of inputs/outputs in truth table.
control_range=(1,1): tuple of two integer digits (n, m), where
0 < n <= m ... |
bc3228712f94429cee102bde8c57c05c62482ff0 | cloudsecuritylabs/learningpython3 | /ch1/pass_args_to_python.py | 393 | 3.546875 | 4 | # To pass multiple values via commandline, we can use 'argv' module
# in this code, we are passing three variable to the "script"
# run this program from the commandline
from sys import argv
script, first, second, third = argv
print('the script is ', script)
print('the first is', first)
print('the second is', second)
p... |
a67d3bc4aa14ba70c55ae459801a58560f1623dc | pluxurysport/wwwww | /steganografia/RW.py | 1,196 | 3.53125 | 4 | class readwrite():
def read(self):
try:
namefile = input("File name: ")
with open(namefile, "rb") as r:
byte = r.read(1)
k = 0
while byte:
try:
byte = r.read(1).decode("utf-8")
... |
716c79ac7bf02281219482ba35f8b4296655e52b | SmallSir/Design-Patterns | /design_patterns/builder/python/builder.py | 1,776 | 3.84375 | 4 | # code: utf-8
from abc import ABC, abstractmethod, abstractproperty
class Builder(ABC):
@abstractmethod
def Part1(self):
pass
@abstractmethod
def Part2(self):
pass
@abstractmethod
def Part3(self):
pass
class Director(object):
def __init__(self):
self._... |
a7fbaad0680360551307a45b7f2436909616c8a7 | smm10/code-forces-solutions | /anton_and_polyhedrons.py | 719 | 3.859375 | 4 | '''
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons:
Tetrahedron. Tetrahedron has 4 triangular faces.
Cube. Cube has 6 square faces.
Octahedron. Octahedron has 8 triangular faces.
Dodecahedron. Dodecahedron has 12 pentagonal faces.
Icosahedron. Icosah... |
bed66880d73b49a0fd7dc75c321900bfeee76c53 | Chibizov96/project | /Lesson 2-1.py | 781 | 4.03125 | 4 | # Создать список и заполнить его элементами различных типов данных.
# # Реализовать скрипт проверки типа данных каждого элемента.
# # Использовать функцию type() для проверки типа.
# # Элементы списка можно не запрашивать у пользователя, а указать явно, в программе.
some_int = 5
some_float = 1.3
some_str = "Hello"
some... |
9c8691e77967a32648a3013fba4730b64c76f74a | nasrinyasari/BTH-Pythonista | /service.py | 27,036 | 3.546875 | 4 | """
The module called service includes heavily simplified UNIX-based commands and represent the
services of the server.This file contains Three classes named: 1-User which handle the request
from server sent by user privilege from Client, 2-Admin handle the request from server sent by
admin privilege from Client, 3-Use... |
44ef60bff56152cba36c83e0283bf5b98c3f349b | abeelashraf98/pgm-lab-abeel | /CO1Pg8.py | 255 | 3.703125 | 4 | a=input("Enter a word")
count=0
for j in range(0,len(a)):
if(j==0):
print(a[j],end="")
else:
if(a[0]==a[j]):
print("$",end="")
else:
print(a[j],end="")
|
c2ab1530b17953370c2c754306814a937830e4f9 | GZHOUW/Algorithm | /LeetCode Problems/Binary Search/Find Minimum in Rotated Sorted Array.py | 856 | 3.75 | 4 | '''
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
Find the minimum element.
You may assume no duplicate exists in the array.
Example 1:
Input: [3,4,5,1,2]
Output: 1
Example 2:
Input: [4,5,6,7,0,1,2]
Output: 0
''... |
2ca128e33d58917ca46ba1b18af91f631996c6c6 | AugustLONG/Code | /CC150Python/crackingTheCodingInterview-masterPython全/crackingTheCodingInterview/cha04/4.3.py | 443 | 3.8125 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim: tabstop=4 softtabstop=4 shiftwidth=4
"""
Given a sorted (increasing order) array, write an algorithm to create a binary tree with
minimal height.
Analyse:
* I don't know why it mentions that the array is an increasing array.
* I think the minimal height binary tre... |
a371a4316a9d0b330d7d5d63523dca7cd4f73dc5 | jancion/studious-journey | /1Julian's Stuff/Lab 12/cash-register.py | 4,985 | 3.53125 | 4 | '''
Julian Ancion
Robert Ordóñez & CPTR-215
CPTR-215
Cash Register
'''
from random import randint
class CashRegister:
def __init__(self):
'''
initializes the cash register
'''
self.scanner = Scanner()
self.inventory = Inventory()
def process_transaction(self):
... |
6158fb6585a367c1ba799146e9507c834ee696f9 | chalmerlowe/darkartofcoding | /weekly_class_materials/wk_04/chapter.04.py | 1,334 | 4.125 | 4 |
# coding: utf-8
# <h1>Welcome to the Dark Art of Coding:</h1>
# <h2>Introduction to Python</h2>
# Chapter 04: Lists
# <h1>Today's class</h1>
# <ul>
# <li><strong>Review and Questions?</strong></li>
# <li><strong>Objectives:</strong></li>
# <ul>
# <li><strong>What is a list?</strong></li>
# <li><... |
f3531a5406c081c386f73f60a16b5e99d7f6f803 | 08hughes/oop-basics-data3 | /oop_animal_class.py | 425 | 3.546875 | 4 |
class Animal:
def __init__(self, name, age, species):
self.name = name
self.age = age
self.species = species
self.alive = True
self.number_animal_eaten = 0
def sleep(self):
return "Zzzzzzzz"
def eat(self, food):
self.number_animal_eaten += 1
... |
eb8bf7a0c2325053bad0096bbafb7f55cea81656 | zachary-andrews/Codefoo | /Hard/Traping_Rain_Water/solution.py | 622 | 3.75 | 4 | class Solution:
def trap(self, height: List[int]) -> int:
water_levels = []
highpoint = 0
if len(height) < 3:
return 0
for i,h in enumerate(height):
if h >= highpoint:
highpoint = h
print("highpoint set")
else:
... |
6380129b5767b88bc00c42225894d794dd125fc2 | alexrogeriodj/Caixa-Eletronico-em-Python | /capitulo 06/06.35 - Programa 6.11 Verificacao do maior valor.py | 783 | 4.125 | 4 | ##############################################################################
# Parte do livro Introdução à Programação com Python
# Autor: Nilo Ney Coutinho Menezes
# Editora Novatec (c) 2010-2019
# Primeira edição - Novembro/2010 - ISBN 978-85-7522-250-8
# Segunda edição - Junho/2014 - ISBN 978-85-7522-408-3
# Terce... |
4b54199b2b8aaa1b195814c6b35486207bb2c104 | sushantkumar-1996/Python_tutorials | /Python_ListElementsMultiply.py | 1,207 | 4.1875 | 4 | """Python Program for multiplying all the elements in a list-- 3 different ways
Method 1: Traversal--- Initialize the value of product to 1(not 0 as 0 multiplication by zero) traverse till the end of
the list, multiply every number with the product"""
def mulList(lst):
result = 1
for i in lst:
result ... |
293c588e0fff9fc81df9afe60db72c55a248c302 | Ninjamaster20000/Week-9-Assignment | /Money Over Time.py | 328 | 4.0625 | 4 | print("Starting at 1 penny on day 1, each day the salary is doubled")
days = int(input("Enter the number of days to calculate: "))
print()
count = 1
total = 0
for i in range(days):
money = count / 100
print("Day ", i+1, ": $", money, sep='')
count = count * 2
total = total + money
print("Total: $"... |
5035cb2fc2f7e9c501ed776f72f5f47d8ff3e141 | n0skill/AVOSINT | /libs/icao_converter.py | 2,913 | 3.78125 | 4 | base9 = '123456789' # The first digit (after the "N") is always one of these.
base10 = '0123456789' # The possible second and third digits are one of these.
# Note that "I" and "O" are never used as letters, to prevent confusion with "1" and "0"
base34 = 'ABCDEFGHJKLMNPQRSTUVWXYZ0123456789'
icaooffset = 0xA00001 # The... |
7e53e9f6cc3224142f52a3a674d2c640050da820 | rsamit26/InterviewBit | /Python/GraphDataStructureAlgorithms/BFS/ValidPath.py | 2,065 | 4.0625 | 4 | """
There is a rectangle with left bottom as (0, 0) and right up as (x, y). There
are N circles such that their centers are inside the rectangle.
Radius of each circle is R. Now we need to find out if it is possible that we
can move from (0, 0) to (x, y) without touching any circle.
Note : We can move from any cell t... |
8a26a264bd5cdfc2d3e591341e6bf6fb54971e18 | futurewujun/python_14_0402 | /week_3/demo.py | 1,497 | 3.796875 | 4 | # -*- coding: utf-8 -*-
# a = {'name':'w','age':10}
# print(type(a))
# for i in a:
# print(i)
# 4、一个足球队在寻找年龄在x岁到y岁的小女孩(包括x岁和y岁)加入。编写一个程序,询问用户的性别(m表示男性,f表示女性)和年龄,
# 然后显示一条消息指出这个人是否可以加入球队,询问k次后,输出满足条件的总人数。
def join_team(sex,age,k=int(4),x=int(10),y=int(12)):
sum=0 #人数
count=0 #次数
while 1:
... |
e92808b90fd0217595f9ad4e93ae6351497763bd | RBachmanIt/Tarea-Redes-3 | /servidor.py | 7,315 | 3.640625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Programa Servidor
import socket
import sys
if len(sys.argv) != 2:
print ("Agregar el puerto donde se va a ofrecer el servicio.")
sys.exit(0)
IP = ""
PUERTO = int(sys.argv[1])
print ("\nServicio se va a configurar en el puerto: ", PUERTO, " ...")
socket_servid... |
a08b618ea8c30a27ef87cbda9ea1fabd69104550 | KranthiKumarGangineni/Python | /Labs/Lab1/Source/sentence.py | 1,589 | 4.375 | 4 | print("program to find:\n1.Middle words\n2.Highest Length word\n3.Sentence in reverse order")
# Asking for User Input
sentence = input("Enter sentence:")
# Method Definition to find the Middle Word
def middle(sen):
words=sen.split(" ")
cenWord=[]
# Finding the Center length
center = int(len(words) / 2... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.