blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
b0f0a1f8f453e7976759afcd539eabd754a28c45 | anapaulalg/100-days-of-code | /Month-1/Week-01/Day-05/py/main.py | 419 | 3.734375 | 4 | # Pair of Socks
def numberOfPairs(sockPairs):
uniqueSocks = []
for elem in sockPairs:
if uniqueSocks.count(elem) == 0:
uniqueSocks.append(elem)
pairsSocks = 0
for elem in uniqueSocks:
socks = sockPairs.count(elem)
pairsSocks = pairsSocks + int(socks / 2)
return ... |
68c507951a632afdb5ff7e3f1c32a229bb82308a | anapaulalg/100-days-of-code | /Month-1/Week-01/Day-06/py/main.py | 568 | 4.09375 | 4 | # Next Prime
def isPrime(number):
allNumbers = []
y = 1
while y < number - 1:
y = y + 1
allNumbers.append(y)
floatCount = 0
for elem in allNumbers:
if number % elem > 0:
floatCount = floatCount + 1
isPrime = floatCount == len(allNumbers)
return isPrime... |
e5ce150d599dbb67031279dfd8b1ccb1e0aceb01 | scooterh4/pdsnd_github | /bikeshare.py | 8,226 | 4.15625 | 4 | import time
import pandas as pd
import numpy as np
CITY_DATA = { 'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv' }
months = ['january', 'february', 'march', 'april', 'may', 'june']
days = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday... |
e2ffc272b100428b9138ec5592537ac61b9976bd | DylanBedetti/UR5 | /Dylan/RoboDK/test.py | 4,565 | 3.515625 | 4 | # This macro shows an example to run a program on the robot from the Python API (online programming)
#
# Important: By default, right clicking a program on the RoboDK API and selecting "Run On Robot" has the same effect as running this example.
# Use the Example_OnlineProgramming.py instead if the program is run from t... |
e439bbbb222a53f4b88f9ba8694e1ac74aca76c6 | truong225/learning-python | /basic/dictionary.py | 547 | 3.546875 | 4 | point = {'name': 'Kobayashi', 'age': 681, 'salary': 1000}
print point['name']
point['country'] = 'vietnam'
print point
"""Xoa toan bo du lieu trong doi tuong"""
dict.clear(point)
point.clear()
print point
"""Copy"""
dict.copy(point)
"""Tao doi tuong voi danh sach key tu seq va lay value lam gia tri neu co"""
sequen... |
f659585909b456f38140e7cd0976862c624ba0eb | wondershow/CodingTraining | /Python/LC863_AllNodesDistanceKinBinaryTree.py | 1,362 | 3.609375 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
"""
the if depth > k:
break
statement should be put before the for loop.
"""
class Solution:
def distanceK(self, root: Tre... |
a070b0c18d859580352107ce91d08e43526a76e3 | wondershow/CodingTraining | /Python/LC249_GroupShiftedStrings.py | 612 | 3.734375 | 4 | class Solution:
"""
The key is how to carefully compute the 'signature' of each string
"""
def groupStrings(self, strings: List[str]) -> List[List[str]]:
def get_signature(string):
delta = ord(string[0]) - ord('a')
res = ""
for c in string:
... |
a7061a35bdff42067bffa73112eec3c9c1cc81a0 | wondershow/CodingTraining | /Python/LC138_CopyListWithRandomPointer.py | 982 | 3.65625 | 4 | """
# Definition for a Node.
class Node:
def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
self.val = int(x)
self.next = next
self.random = random
"""
class Solution:
def copyRandomList(self, head: 'Node') -> 'Node':
if not head:
return None
... |
32f868baf04f2ecd7e0f5aca236a651da43c64b0 | wondershow/CodingTraining | /Python/LC127_WordLadder.py | 843 | 3.78125 | 4 | class Solution:
"""
Time: O(N*26*W^2)
Space complexity is O(N*W)
"""
def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
que, seen = [(beginWord, 1)], {beginWord}
word_set = set(wordList)
alphabet = set(list("abcdefghijklmnopqrstuvwxyz"))
... |
5b8cca558ea253291943c9d0d59613dbc6089d47 | wondershow/CodingTraining | /Python/LC1382_BlanceABinarySearchTree.py | 830 | 3.734375 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def balanceBST(self, root: TreeNode) -> TreeNode:
def build(nodes, lo, hi):
if lo > hi:
... |
b92d147a2d817df326bf4453f65becb7ca3c7d86 | wondershow/CodingTraining | /Python/LC247_StrobogrammaticNumberII.py | 1,101 | 4.1875 | 4 | class Solution:
"""
The example of this case is confusing, which may trick you think the n = 2 case to be a basic case of recursion.
instead of using n = 1 and n =2 , we need to use n = 0 and n =1 as basic use cases.
We need to pass in two variables into recursion (start, cur)
start means the o... |
e6b98e2a42e80d57e4090a6de16e64c473b01f5b | wondershow/CodingTraining | /Python/LC1776_CarFleetII.py | 1,170 | 3.515625 | 4 | class Solution:
"""
Scan from right to left, we use a stack to keep all the vehciels that from slow to fast (stack top is the fastest). At each iteration, if the current vehicle speed is slower than the stack top vehicle, that means the current vehicle will never catch up with the stack top vehicle, pop stack.
... |
9a3a67f6dcd79cd6379f342d5ecebf2888af116c | CFN-softbio/SciStreams | /SciStreams/processing/image.py | 1,580 | 3.796875 | 4 | from scipy.ndimage.filters import gaussian_filter
def blur(image, sigma=None):
''' blur the image
Uses a Gaussian blurring method.
Parameters
----------
image : 2d np.ndarray
the image to blur
sigma : float, optional
the std dev of the Gaussian ke... |
1514b3d7daa48faf7d3c88306e683574ec82bca7 | pasqualegabriel/OperativeSystem | /poc/calculadora/calculadora1.py | 817 | 4.09375 | 4 | import sys
#Esta calculadora solo acepta numeros enteros
class Calculator:
def __init__(self,num1,operator,num2):
self.oneNumber=num1
self.twoNumber=num2
self.operator=operator
self.validOperator=["+","-","/","*"]
#Primero verifico que el operador sea un operador valido de la calculadora
#Luego verifico que... |
cdea05821bb581b364f23aba62552b98570e68e5 | pasqualegabriel/OperativeSystem | /poc/calculadora/calculadora2.py | 1,849 | 3.984375 | 4 |
import sys
class calculator:
# La calculadora solo acepta numeros enteros
def __init__(self, primerNumero, operador, segundoNumero):
self.firstNumber=int(primerNumero)
self.secondNumber=int(segundoNumero)
self.operator=operador
self.validOperators=["+","-","*","/"]
# Retor... |
f1621a0f6f3db23bceb8e0cb5a20b654f578abf6 | utkarsh-ls/Brick-Breaker | /powerup.py | 11,336 | 3.515625 | 4 | import random
from objects import *
from paddle import *
from ball import *
powerups = []
# powerups_del = []
MAX_POWERUPS = 7
bullets = []
rem_time = [0,0,0,0,0,0,0,0]
class Powerup(Obj):
def __init__(self, x, y):
self.x = x
self.y = y
board_pos = brickcol[0]
active_time = 10
... |
64aa1377709f513f330e852f8ec34b5f0309ac33 | asimahmood/Programming-Practice | /cardDesks.py | 623 | 3.765625 | 4 | class Card:
def __init__(self, suit, val):
self.suit = suit
self.val = val
def __str__(self):
return str(self.val) + " of " + self.suit
class Deck:
def __init__(self):
self.cards = []
self.build()
def build(self):
for s in ["Spades", "Hear... |
f27c31ac95cda99c10b1fb798bbf50ff9e71a90c | asimahmood/Programming-Practice | /Sort.py | 511 | 3.921875 | 4 | def bubble_sort(l):
n = len(l)
for i in range(n):
for j in range(0, (n - i)-1):
if l[j] > l[j + 1]
l[j], l[j + 1] = l[j + 1], l[j]
def insertion_sort(l):
for i in range(1, len(l)):
key = l[i]
j = i - 1
while j >= 0 and key < l[j]:
l[j + 1] = l[j]
j -= 1
l[j + 1] = key
... |
f1601b5e57eacca7a419988d5fb587b7479cfea7 | LuisTavaresJr/cursoemvideo | /ex87.py | 994 | 4.1875 | 4 | matriz = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] # como ja sabe o numero de elementos ja declarou para nao ter que usar o append
par = soma = maior = 0
for l in range(0, 3): # vai pegar a primeira linha
for c in range(0, 3): # vai percorrer a primeira linha adicionando os valores
matriz[l][c] = int(input(f'Digite... |
87d52258eacd7dbdb9947522d499afc260117119 | LuisTavaresJr/cursoemvideo | /ex99.py | 524 | 3.75 | 4 | def maior(*num):
from time import sleep
cont = maior = 0
print('~'* 30)
print('\nAnalizando os valores passados.')
for valor in num:
print(f'{valor} ', end='')
sleep(0.3)
if cont == 0:
maior = valor
else:
if valor > maior:
maior... |
cd0413f3ec6ddd30000f474d1ddbda8c5a0bfbf9 | LuisTavaresJr/cursoemvideo | /ex96 aula 20.py | 220 | 3.5625 | 4 | def area(a, b):
total = a * b
print(f'A área de um terreno de {a}x{b} é de {total}m²')
print('Controle de Terrenos')
lar = float(input('Largura (m) '))
comp = float(input('Comprimento (m) '))
area(lar, comp) |
a5745b5ca9360a6dbef625f4b5dc3acc987a02f1 | LuisTavaresJr/cursoemvideo | /ex28 aula 10.py | 416 | 3.8125 | 4 | from random import randint
from time import sleep
print('VOU PENSAR EM UM NÚMERO ENTRE 0 E 5 ! TENTE ADIVINHAR')
jogador = int(input('Digite um número entre 0 e 5: '))
computador = randint(0, 5)
print('PROCESSANDO...')
sleep(2)
if jogador == computador:
print(f'Parabéns você Venceu! Eu e você pensamos em {computado... |
06fb80bd0298646106554094e788d54309fee699 | LuisTavaresJr/cursoemvideo | /ex74.py | 293 | 3.78125 | 4 | from random import randint
n = randint(1, 10), randint(1, 10), randint(1, 10), randint(1, 10), randint(1, 10)
print('Os números sorteados foram: ', end='')
for c in n:
print(f'{c} ',end='')
print(f'\nO maior número sorteado foi {max(n)}')
print(f'O menor número sorteado foi {min(n)}')
|
09d0210248a308137f3653bf3059a0fc96fb7b45 | LuisTavaresJr/cursoemvideo | /ex52.py | 445 | 3.921875 | 4 | print('Dizer se o número é primo!')
n = int(input('Digite um número: '))
cont = 0
for c in range(1, n+1):
if n % c == 0:
print(f'\033[33m', end='')
cont += 1
else:
print('\033[31m', end= '')
print(f'{c} ', end='')
if cont == 2:
print(f'\n\033[mO número {n} foi divisivel {cont} ve... |
2cb44d4339a9a5d7560938ea5f319b9e28906747 | LuisTavaresJr/cursoemvideo | /ex10.py | 215 | 3.828125 | 4 | print('Com o valor do dolar de U$ 3.91, na data de hoje')
valor = float(input('Digite quanto de Reais você tem: R%'))
d = valor / 3.91
print(f'Hoje com o valor de R${valor:.2f}, você compraria U${d:.2f} Dolares!') |
3fd482d5b9c77a05fe4d619a12e8965490b24cfc | LuisTavaresJr/cursoemvideo | /ex02 aula04.py | 210 | 3.90625 | 4 | dia = int(input('Qual dia você nasceu: '))
mes = str(input('Qual o mês que você nasceu: '))
ano = int(input('Qual o ano que você nasceu: '))
print(f'Você nasceu no dia {dia} de {mes} de {ano} . correto?')
|
e7677f9685c1b7321e5dde9f756ba31b16572b2c | LuisTavaresJr/cursoemvideo | /ex78 aula 17.py | 472 | 3.71875 | 4 | valores = []
for c in range(0, 5):
valores.append(int(input(f'Digite um valor para a Posição {c}: ')))
print(f'Você digitou {valores}')
print('-='* 15)
print(f'O maior valor foi {max(valores)} na posição', end=' ')
for i, v in enumerate(valores):
if v == max(valores):
print(f'{i}...', end='')
print(f'\n... |
378fe1ebfd5ae2ac4a9bc29bb36085b4dab1e24e | polaroidz/hacker_rank | /alg/fraudelent_activity_notification_merge_sort.py | 1,248 | 3.78125 | 4 |
def calc_median_merge(arr, left, mid, right):
if arr[mid - 1] <= arr[mid]:
return
i = left
j = mid
k = 0
sorted_array = [0] * (right - left)
while i < mid and j < right:
if arr[i] <= arr[j]:
sorted_array[k] = arr[i]
i += 1
else:
sorted_array[k] = arr[j]
j += 1
... |
dc0f54f91aa140817581fda5d67db9a33425b21b | MorKalo/L5_HomeWork03-10-21 | /P36 EX3.py | 279 | 3.90625 | 4 | #לבקשת איתי שימוש בקליטת 10 כרטיסים בלבד
i=1
tmax=40
tmin=-5
while i<=9:
ticket = int(input('insert the temp'))
if tmin>ticket or ticket>=tmax:
print('WRONG value')
break
i=i+1
if i==10:
print ('GOOD value') |
7c8eed62e35d4e49828ad5771c675c80931ba9e5 | TaimurGhani/School | /CS1134/Homework/hw05/tg1632_hw5_q5.py | 2,870 | 3.890625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 27 18:35:31 2017
@author: taimur
"""
class Empty(Exception):
pass
class ArrayStack:
def __init__(self):
self.data = []
def __len__(self):
return len(self.data)
def is_empty(self):
return len(self) == 0
... |
07eb82a7dae3e341f8b95289c183354e41414920 | TaimurGhani/School | /CS1134/Labs/Lab04/is_palindrome.py | 454 | 4.0625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 29 12:51:43 2017
@author: taimur
"""
def is_palindrome(input_str, low = 0, high = None):
if (high is None):
high = len(input_str)-1
if (low > high):
return True
elif (input_str[low] == input_str[high]):
low += 1
... |
b97c7d3445cf7e3b47c66a7dc763fa331f422d71 | TaimurGhani/School | /CS1134/Homework/hw05/tg1632_hw5_q3.py | 2,681 | 3.890625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 27 00:13:15 2017
@author: taimur
"""
class Empty(Exception):
pass
class ArrayStack:
def __init__(self):
self.data = []
def __len__(self):
return len(self.data)
def is_empty(self):
return len(self) == 0
... |
041ab8902f49bc64d80379c5a278c753f85eaa53 | TaimurGhani/School | /CS1134/Labs/Lab01/add_binary.py | 411 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""
Taimur Ghani
QuestionOne.py
8 September 2017
This program will create a fucntion that is passed through
two binary numbers and will return the sum of these two
binary numbers as another binary number.
"""
import math
def add_binary(num1_str, num2_str):
finalSum =... |
e67932febfca13098db5a84b8fcee7482e4dd6bd | peggiefang/LeetCode | /242_Valid_Anagram.py | 352 | 3.875 | 4 | '''
Given two strings s and t, return true if t is an anagram of s, and false otherwise.
Example 1:
Input: s = "anagram", t = "nagaram"
Output: true
'''
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
c = Counter(s)
d = Counter(t)
if c == d:
return True
... |
d440706c3ec031482b38a99151c1a3aa47eb5b0d | peggiefang/LeetCode | /122_Best_Time_to_Buy_and_Sell_Stock_II.py | 589 | 3.84375 | 4 | '''
You are given an array prices where prices[i] is the price of a given stock on the ith day.
Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times).
Note: You may not engage in multiple transactions simultaneously (i... |
771e595027f41828f607d64d81bdbbf6c7fa8786 | muad-dweeb/keypad-phrase | /util.py | 235 | 3.78125 | 4 | def length_filtered_word_generator(input_file, length):
with open(input_file, 'r') as dictionary:
words = dictionary.readlines()
for word in words:
if len(word) == length + 1:
yield word
|
b66ddc0cd08af48251d5a48af408f7be2d229aa2 | Colris/NumpyDL | /npdl/objectives.py | 6,101 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Provides some minimal help with building loss expressions for training or
validating a neural network.
These functions build element- or item-wise loss expressions from network
predictions and targets.
Examples
--------
Assuming you have a simple neural network for 3-way classification:
... |
f6e071e09fff2d0da3dff6f5e041aa944eb49e05 | Ksorz/Poly | /Programming/Py/(Coursera) Py4e/Ex`s of Course 2/10_2 (sorting).py | 680 | 4.15625 | 4 | # 10.2 Write a program to read through the mbox-short.txt and figure out the distribution by hour of the day for each of the messages. You can pull the hour out from the 'From ' line by finding the time and then splitting the string a second time using a colon.
# From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008... |
ac02c4bc8917fa358b68fdc911326f4fd5a7d729 | zjahid19/snakegame | /snake.py | 2,270 | 4.09375 | 4 | from turtle import Turtle
from turtle import Screen
import random
import time
UP = 90
DOWN = 270
LEFT = 180
RIGHT = 0
class Snake:
""" This Class Create and Initiate Snake"""
def __init__(self):
self.screen = Screen()
self.initial_coordinates = [(0, 0), (-20, 0), (-40, 0)]
self.segment_... |
d3095f0ae30c1bbe61c25a7efae30f61c847ff22 | SamwiseLA/0Testit | /0Testit_numpy.py | 1,712 | 3.59375 | 4 | from samwise import pb
import numpy as np
x = np.array([14, 21, 24, 7, 99])
y = np.array([12, 6, 23, 29, 77]) # a list of 5 items
z = np.array([x, y]) # each item is a row with a value of list, so 2 dimensional arrays.
pb(z.shape,"Show the shape for the numpy array (rows, cols): z.shape")
pb("","Array z")
print(z)
... |
27db6214ace77e4e625437a2f54d081ac6364f3f | SamwiseLA/0Testit | /0Testit_if_single_line.py | 813 | 3.65625 | 4 | # if single line
from samwise import pb
s_input = input("please give 2 numbers sepearted by a space: ")
n_space = s_input.index(" ")
n_1 = float(s_input[0:n_space])
n_2 = float(s_input[n_space:])
# print(f"{n_1}:{n_2}")
s_oper = "*"
if n_1 * n_2 > 1000: s_oper = "+"
# value set conditionally
n_val = n_1 * n_2 if n_1 ... |
6ced45552aee1c4344ba1b763ef84ed4c3da6d5a | ukzncompphys/lecture7_2016 | /overload2.py | 760 | 3.5 | 4 | #class_example4.py
import numpy
class Complex:
def __init__(self,r=0,i=0):
self.r=r
self.i=i
def copy(self):
return Complex(self.r,self.i)
def __add__(self,val):
ans=self.copy()
if isinstance(val,Complex):
ans.r=ans.r+val.r
ans.i=ans.i+val.i
... |
98871764cba7afe415cd382a313e67a22645db19 | msds-thakur/Artificial-Intelligence-and-Deep-Learning-Python | /Assignment4.py | 8,491 | 3.515625 | 4 |
# coding: utf-8
# In[2]:
#Prabhat Thakur Date 06/07/2019
#2019SP_MSDS_458-DL_SEC56 Week10- Assignment4
#Create deep neural networks CNN for Gender classcification.
#Data : Downloaded from Google
#Code Addopted from F. Challot (2018), Deep Learning with Python (Manning)
# and https://github.com/arunpo... |
cd116e9c8960517615061fb400da760b9b7b5f1e | VishwanathPrabhuRajamani/python-csv-util | /csv_util.py | 551 | 3.875 | 4 | import pandas as pd
def print_csv_data(csv_data):
print(csv_data)
def read_csv():
csv_data = pd.read_csv('student_data.csv')
print_csv_data(csv_data)
def wite_to_csv():
# data includes student name,subject and marks
data = [['Rohit','Maths', 80], ['Virat','Science', 90], ['Rahul','... |
be8cd6df26286aa404eb35cb988bbe4dd45a3b6f | carlosdlr/python_course | /Dictionaries.py | 2,405 | 4.5625 | 5 | fruits = {"orange": "a sweet, citrus fruit",
"apple": "good for making cyder",
"lemon": "a sour, yellow citrus fruit",
"grape": "a small, sweet fruit growing in bunches"}
# print(fruits)
# print(fruits["apple"]) # accessing the date in the dictionary by key
#
# bike = {"make": "honda", ... |
362c81202913f8965e1e28d14f09cfd32683a2d6 | carlosdlr/python_course | /ProgramFlowChallenge.py | 897 | 3.921875 | 4 | # another way to allow split a text expression using parenthesis
ip_address_input_text = ("Please enter an "
"IP address ")
ip_address = input(ip_address_input_text)
address_array = ip_address.split(".")
# if address_array[0] in '. ' or address_array[-1] in '.':
# print("The address cannot... |
f47c2e1b6b469709a446717cf01a28750ad2b44c | criscross01/Python-Assignments | /Archived/Case Study-Nondirective Psychotherapy.py | 1,130 | 3.703125 | 4 | from random import randint
def getReply(statement):
#Makes the statement lower case
statement = statement.lower()
#Changes first person to second person
statement = statement.split()
firstToSecond = {"i":"you","me":"you" ,"my":"your","mine":"yours"}
for word in statement:
if word in fir... |
d6f21086cb34ec48e11fdffe00344b1d0d85f4ac | giri-sai/AdvancedPython | /SuperMarketProject.py | 2,256 | 3.828125 | 4 | import math
from datetime import datetime
Customer_name = input('Enter Customer Name:')
def bill_cal():
a = True
Total_Price = 0
List_of_Items = []
while a:
print('''
1. list of items
2. Choose items
3.exit
''')
choice = int(input('Ent... |
147dddbc3ecb8a9b7f059434babac6f098f21650 | nb98/alarm_clock | /localtime.py | 1,078 | 3.859375 | 4 | import time
import datetime
print "Time in seconds since the epoch: %s" %time.time()
print "Current date and time: " , datetime.datetime.now()
print "Or like this: " ,datetime.datetime.now().strftime("%y-%m-%d-%H-%M")
print "Current year: ", datetime.date.today().strftime("%Y")
print "Month of year: ", datetime.date... |
70c932d3e6ee21cf5962300a96e123562939eb30 | mubinui/Pycharm | /venv/PythonFiles.py | 336 | 3.828125 | 4 |
f =open("yourfile.txt","w")
f.write("Hello baby")
f.close();
g = open("yourfile.txt","r")
print(g.read())
g.close()
k = open("Text.txt","a")
k.write("I love you baby ")
k.close()
import os
os.remove("yourfile.txt")
h = open("yourfile.txt","r")
print(h.read())
h.close()
# import os
#os.rmdir("myfolder") for deleti... |
a3f186b9d535d807edff432842aaa15f358825d7 | ramkumar24597/Mobile_Robotics | /checking_loop.py | 206 | 3.671875 | 4 | count = 0
def pick(x):
while True:
y = 1
if ( x == 0 ):
print(x)
if( y == 1 ):
print(y)
while True:
pick(count)
count+=1
|
6c98546e442adbbf3d5f52f51b0292c2f55ee9d7 | grigoriishveps/PosovSubject | /binary_search.py | 530 | 3.84375 | 4 | def binary_search(array, val):
left = -1
right = len(array)-1
while right > left + 1:
middle = (left + right) // 2
if array[middle] >= val:
right = middle
else:
left = middle
if array[right] == val:
return right
return -1
def start_binary():
... |
e113081a7c394b9f84d4ce213cd43d246349e558 | serenascalzi/python-specialization | /exercises/chapter06-exercises.py | 678 | 4.15625 | 4 | # chapter 6
# strings
# traversal program
word = input('Enter Word:\n')
index = len(word) - 1
while index >= 0:
letter = word[index]
print(letter)
index = index - 1
# fruit[:] - means a slice starting at the beginning and going to the end of the string
# count program
word = input('Enter Word:\n')
letter... |
107617c5153325f7e6ad19a527f345b336e175a8 | siddharthgaud/python_basic_code | /python basics/HelloWorld/conditions.py | 1,379 | 4.1875 | 4 | is_hot = False
is_cold =False
if is_hot:
print("its a hot day")
print("drink plenty of water")
if is_cold:
print("its a cold day")
print("wear warm clothes")
else:
print("its awesome day")
#if statement
i = 10
if i>25:
print("i is greater than 15")
print("good")
#if-else statement
a = 20
if a... |
4d6f7ea6880d99beb08028c8f8d743ce07d3024a | siddharthgaud/python_basic_code | /python basics/w3school/list.py | 1,156 | 4.28125 | 4 | #List
thislist = ["apple", "banana", "cherry"]
print(thislist)
#Access Items
thislist = ["apple", "banana", "cherry"]
print(thislist[1])
#Negative Indexing
thislist = ["apple", "banana", "cherry"]
print(thislist[-1])
#Range of Index
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(t... |
1597944c94de80352007fc50fd330704667dd56e | siddharthgaud/python_basic_code | /python basics/pythonconcepts/ifelse.py | 330 | 4.03125 | 4 | a = 33
b = 200
if a>b:
print("a is greater than b")
elif a<b:
print("a is less than b")
else:
print("a is equal to b")
if a>b :print("a is greater than b")
else:
print("a is less than b")
x =10
y = 20
print("x") if x>b else print("y")
a= 200
b = 33
c = 500
if a > b or c > a:
print("Both conditions ... |
275d3478e1424e6442d4c4f85ce7050c7d7a02c9 | siddharthgaud/python_basic_code | /python basics/w3school1/list.py | 1,190 | 4.15625 | 4 | thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist)
print(thislist[1]) #Access Item
print(thislist[-1]) #Negative indexing
print(thislist[2:5]) #range of index
print(thislist[:4])
print(thislist[2:])
print(thislist[-4:-1]) #negative indexing
thislist[1] = "bla... |
3cf9063b5077c5a8d92f17f2e965e4a925dcb05b | siddharthgaud/python_basic_code | /python basics/HelloWorld/patterns.py | 579 | 3.921875 | 4 | '''for i in range(4):
for j in range(4):
print("# ",end=" ")
print()'''
print("***************************************************")
'''for i in range(4):
for j in range(4-i):
print("#",end=" ")
print()'''
print("****************************************************")
"""for i in range(3... |
065606cb581454e73182471c711cbbf33cc6bc55 | siddharthgaud/python_basic_code | /python basics/pythonconcepts/Datatypes.py | 791 | 4.21875 | 4 | 'integer'
print(10+12)
print(10*5)
print(6-3)
print(10/5)
print(10%5)
print("=" *100)
'float'
print(2.5+2.4)
print(2.5*1.2)
print(6.6-3.3)
print(6.3/2.3)
print(6.3%2.3)
'string'
print("Hello world")
print("Hello" + "World")
print(len("Hello world"))
print("""hi everyone
this is siddharth
i am new to python
""")
print(... |
431de876fb7aec74fb267abbe4a7a1ca03446977 | siddharthgaud/python_basic_code | /python basics/HelloWorld/Getting_Input.py | 2,332 | 4.21875 | 4 | """name = input("what is your name? ")
color = input("what is your favourite color? ")
print("Hi "+name)
print(name+" likes "+color)"""
print("***************************************************")
"""birth_year = input("Birth Year: ")
print(type(birth_year))
age = 2020-int(birth_year)
print(type(age))
print(age)"""
pri... |
38f842a6232484ffbe623589da469573864fcdef | kamil-matula/AiSD | /Moduł 2. Algorytmy obsługi masowej/Mod2_Stos.py | 1,556 | 3.796875 | 4 | # 01.06.2020, Kamil Matula gr. D
# Zestaw II, algorytm 3: Stos - POPRAWA
class Stack(object):
def __init__(self, maxlength):
self.maxlength = maxlength # statyczna wielkość stosu
self.tail = 0 # indeks pierwszego wolnego miejsca w tablicy/stosie
self.stack = ["nic" for i in... |
7f42b4d02e4134cf63f45747842b940011b5af1c | kamil-matula/AiSD | /Moduł 4. Algorytmy wyszukiwania wzorca/Mod4_BoyerMoore.py | 1,236 | 3.515625 | 4 | # Kamil Matula gr. D, 07.04.2020
# Moduł IV, algorytm 2: algorytm Boyera-Moore'a
def BM(text, pattern):
def GenerateCharsTable(pattern):
lettersandvalues = {}
for i in range (patternlength):
lettersandvalues[pattern[i]] = max(1, patternlength - i - 1)
return lettersandvalues
... |
8cc4586653bdee80689241372458bd64a4b9d123 | crishonsou/hackerrank_30_days_of_code | /strings_to_integer.py | 198 | 3.765625 | 4 | def str_to_int(S):
try:
S = int(S)
return S
except:
return 'Bad String'
S = input().strip()
result = str_to_int(S)
print(result)
|
54e1b645005e0c8a7e118ae0ef25fda7a47e96fa | RamonMR95/sge-python | /sge-python/practica05/ej13.py | 756 | 4.125 | 4 | # !/usr/bin/env python3
# 12.- Diseña una función que reciba una matriz (generada a partir de la función del ejercicio anterior) y, si
# es cuadrada (es decir, tiene igual número de filas que de columnas), devuelva la suma de todos los
# componentes dispuestos en la diagonal principal (es decir, todos los elementos de ... |
f613752b54fc0ab911cd6eb95cfb906d5affeac2 | RamonMR95/sge-python | /sge-python/practica01/ej3.py | 402 | 4.15625 | 4 | # Escribe un programa que pregunte por tu nombre, por tu primer apellido y por tu segundo apellido.
nombre = input("¿Cuál es tu nombre?")
primer_apellido = input("¿Y tu primer apellido?")
segundo_apellido = input("¿Y tu segundo apellido?")
print(f"Te llamas: {nombre} {primer_apellido} {segundo_apellido}")
print(f"En l... |
92576f8f378aa2797467ca5e43e1d30bc8f99f07 | RamonMR95/sge-python | /sge-python/practica01/ej6.py | 409 | 3.890625 | 4 | # Mejora el programa para que no acepte ni números menores de 10 ni mayores de 99.
numero = int(input("Dame un número: "))
if 10 <= numero:
if numero <= 99:
print(f"El número al revés es: {str(numero)[::-1]}")
else:
print(f"El número {numero} no me sirve, tiene que menor o igual que 99.")
else:... |
6741172c01e4b26fb84ea85b72e842381101f14a | RamonMR95/sge-python | /sge-python/practica01/ej8.py | 288 | 3.890625 | 4 | # Escribe un programa que calcule la superficie de un cuadrado, para ello tiene que pedir la longitud del lado:
print("Vamos a calcular la superficie de un cuadrado...")
lado = int(input("¿Cuánto mide el lado (en cm): "))
print(f"La superficie del cuadrado es de {pow(lado, 2)} cm^2")
|
76b4aa6421312c1531182a76fb94e940c90730e6 | RamonMR95/sge-python | /sge-python/practica02/ej4.py | 972 | 3.9375 | 4 | # Escribir un programa que calcule ecuaciones de segundo grado del tipo ax2+bx+c=0. El programa solicitará los
# coeficientes a, b y c. A continuación mostrará las soluciones.
import math
a = int(input("Introduce a: "))
b = int(input("Introduce b: "))
c = int(input("Introduce c: "))
if a == 0 and b == 0:
print("... |
19212e4dbdd30fdbc38bf3a9680b558f70ac2494 | RamonMR95/sge-python | /sge-python/practica03/ej16.py | 1,705 | 3.921875 | 4 | #!/usr/bin/env python3
# Escribir un programa para que dada una cantidad de euros la devuelva en el menor número
# de billetes y monedas de curso legal posible (billetes: 500 €, 200 €, 100 €, 50 €, 20 €, 10 € y 5€.
# Monedas: 2 €, 1 €. Ejemplo:
__author__ = "Ramón Moñino Rubio"
__email__ = "ramonmr16@gmail.com"
__versi... |
e96ad405503c031991edc5f239803c43b0003130 | RamonMR95/sge-python | /sge-python/examen/ejercicios/programa1.py | 662 | 3.9375 | 4 | # Programa que usa la funcion recortes
from examen.ejercicios.ej1 import recortes
test = [[1, 2, 3], [4, 5], [6, 7], [8, 9, 10]]
def mostrar_matriz(mat):
for i in range(len(mat)):
for j in range(len(mat[i])):
print(mat[i][j], end="")
print()
def mostrar_label(num):
if num == 0:... |
17012eb117e32a419ead577b937d24e6ed4382b3 | Not-Aryan/Attentive | /train.py | 2,120 | 3.5 | 4 | from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, Activation, Flatten
from tensorflow.keras.layers import Conv2D, MaxPooling2D
import pickle
import time
from sklearn.model_selection import train_test_split
import numpy as np
def trainn(X, y, name):
# pickle_in = op... |
9e64b9d759fd9e55ea050ee2bee8d65a9567fe14 | kurt-stolle/tue-design-automation | /src/operations/split.py | 1,411 | 3.5625 | 4 | from typing import List
from operations import Operation, tabs
from operations.variable import *
class Split(Operation):
"""The split operation parallelize a number of operations, the execution time is the time of the longest path"""
ops: [Operation] = []
def __init__(self, *args):
self.ops = li... |
f92209633a6bbbc74e1f6dbbf64a5f06997a92fb | apache1027/connectFour | /board.py | 7,644 | 4.21875 | 4 | class Board(object):
"""Holds the current game state in a board.
The current game state is represented by a 2d array that is initialized
full of '*'; representing a blank space. As the board is updated, the
char for the player who made the move is inserted into the column at the
row that is determ... |
514b2a361fb47fae83f171d8ab59691a64080fc3 | csheare/RunningFormatter | /scrape_scripts/marathon_scraper.py | 1,106 | 3.578125 | 4 | from selenium import webdriver
from bs4 import BeautifulSoup
import re
import pandas as pd
import json
url = "https://en.wikipedia.org/wiki/List_of_marathoners"
driver = webdriver.Chrome()
driver.get(url)
soup=BeautifulSoup(driver.page_source, "lxml")
div = soup.find('div', attrs={'class':'mw-parser-output'})
table ... |
f550eb312db84381e1d526a91d53ea3ba9a72ad7 | bbradleyX/Python-Labs | /Pyton Modules/HW10.py | 588 | 4.03125 | 4 | '''
n=1
while(n<6):
m=1
while(m<6):
p=m*n
print(p, end='')
m=m+1
print()
n=n+1
'''
#This code is backwards...had trouble figuring out how to reverse the plus output
num=int(input("Enter an integer:"))
count=1
plus="+"
while(count<=num):
print(count)
count... |
d37b39d60c8a7d8413d256f942d730f422893aef | bbradleyX/Python-Labs | /Pyton Modules/HW8.py | 663 | 3.984375 | 4 | ##num=0
##while(num<5):
## print(num)
## num=num+1
##num=5
##while(num<5):
## print(num)
## num=num+1
##num=0
##total=0
##while(total<10):
## print(total)
## print(num)
## num=num+1
## total=total+num
##print(total)
##print(num)
##num1=0
##num2=1
##while(num1<5 and num2<5):
#... |
e709f85585c44d11bd1d41180f81a95fd81cd7ed | bbradleyX/Python-Labs | /Pyton Modules/Lab2.py | 936 | 4.125 | 4 | #Name:Bria Bradley
#Date: 9/26/17
#Purpose: To calculate the total area of a house with dimensions from user input
width=float(input("Enter width of house: "))
#Check: print(width)
length=float(input("Enter length of house: "))
#Check: print(length)
height=float(input("Enter height of house: "))
#Check: print(h... |
2ed78d57fb4b9925165061361cf7b0ff2d0ba13e | christine415/Python_Crash_Course | /List/motorcycles.py | 531 | 4.03125 | 4 | motorcycles = ["Honda", "Yamaha", "Suzuki"]
# Insert Ducati to the beginning of list motorcycles
motorcycles.insert(0, "Ducati")
print(motorcycles)
# Delete the first item in list motorcycles
del motorcycles[0]
print(motorcycles)
# Remove an item by using pop() method
popped_motorcycles = motorcycles.pop()
print(mot... |
f1b0709a4fa45310f70017a7ac8520526113c2a4 | PrzemekPardel/pythonLectures | /partW2/2_list.py | 741 | 3.734375 | 4 | #random
import random
#standard solution
for a in range(1,7):
print(random.randint(1,49))
#optimal
list = []
ret = []
for a in range(1, 50):
list.append(a)
print(list)
for a in range(1,7):
rnd = random.choice(list)
print("Wylosowano:", rnd)
ret.append(rnd)
list.remove(rnd)
print("LISTA R... |
2638c22bc8a7a9f51c5e07a110c8f77072b1730d | kishikuni/challenges | /6_challenge_06.py | 182 | 3.875 | 4 | # http://tinyurl.com/hapm4dx
words = "A screaming comes across the sky."
x = words.replace("s","$")
print(x)
#-- Upper word cannot be replaced.
x = words.replace("a","@")
print(x)
|
2b9874fcd35fc317fc1040d08de806eaf869e2c6 | kishikuni/challenges | /12_challenge_04.py | 219 | 3.609375 | 4 | # http://tinyurl.com/gpqe62e
class Hexagon:
def __init__(self,h):
self.height = h
def calculate_perimeter(self):
return 1/2 * self.height * 6
hex = Hexagon(2)
print(hex.calculate_perimeter())
|
9350f0994cf8053a437eec793fdbe3847fc1e264 | kishikuni/challenges | /14_challenge_03+.py | 381 | 3.765625 | 4 | # http://tinyurl.com/j9qjnep
class Square:
square_list = []
def __init__(self, s1):
self.s1 = s1
self.square_list.append(self)
def calculate_perimeter(self):
return self.s1*4
def is_same(obj1, obj2):
return obj1 is obj2
sq = Square(10)
same_sq = sq
print(is_same(sq,same... |
2d830af71c605b002056a2697af7864ba132912f | leminem/myproject | /order.py | 839 | 3.515625 | 4 | from recode import Recode
import time
import random
class Order:
def __init__(self,order_number=random.randint(1,10000),recode=Recode()):
self.order_number=order_number
self.recode=recode
def list(self):
self.recode.car.info()
random=self.recode.list()+str(self.order_number)
... |
72ce4d0bab0491de34fc2886a8be1830b2316a79 | brotherhutch/python101 | /chapter2/ex25.py | 158 | 3.75 | 4 | # ex 2.5 Python :: Mark Hutchison
temp = raw_input('Enter temperature in C: ')
tempF = float(temp) * (9.0/5.0) + 32.0
print 'Your temperature in F: ' + str(tempF)
|
a72175a3d3b8e53c27207ae47e06ad01af25cf9b | brotherhutch/python101 | /chapter2/ex23.py | 165 | 3.875 | 4 | # ex 2.3 Python :: Mark Hutchison
hrs = raw_input('Enter hours: ')
rate = raw_input('Enter rate: ')
pay = float(hrs) * float(rate)
print 'Your pay: ' + str(round(pay,2))
|
d7ac738e49631bae62a11f9e4dbede91b8c416e9 | brotherhutch/python101 | /chapter5/ex51.py | 339 | 4.03125 | 4 | # ex 5.1 Python :: Mark Hutchison
total = 0
count = 0
average = 0
while True:
try:
num = raw_input('Enter a number: ')
if num == "done" or num == "Done" :
break
num = float(num)
except:
print 'Invalid input'
num = 0
count = count - 1
total = total + num
count = count + 1
average = total / count
pri... |
0f2a7e8b61a60fdb134cc7fc1f632af112a9d510 | subhashis/codehub | /socketProgramming/simpleFileTransfer/client.py | 854 | 3.59375 | 4 | import socket
IP = socket.gethostbyname(socket.gethostname())
PORT = 4455
ADDR = (IP, PORT)
FORMAT = "utf-8"
SIZE = 1024
def main():
#Staring a TCP socket
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#Connecting to the server
client.connect(ADDR)
#Opening and reading the file data
... |
b9aa2bb2bf1e2929598a2f401abd4b673963c472 | shannonturner/text-to-bitmap | /text_to_smiley.py | 4,547 | 3.515625 | 4 | import struct
def distribute_to_rgb(char_value, base_rgb, midpoint=0, deviation=32, random_zeropadding=True):
" Distributes ord values of char evenly among R, G, and B values, calculated as distance from the midpoint. "
# RGB value boundaries of 0 and 255 MUST NOT wrap around
color_distribution = ['r', ... |
4fbbccb461fb3b9554cb21641e10f591cb9b225d | Elemento24/OpenCV-Computer-Vision-Basics | /chapter4.py | 796 | 3.515625 | 4 | import cv2
import numpy as np
img = np.zeros((512, 512, 3), np.uint8)
# print(img.shape)
# img[:] = 255,0,0
# =================
# SHAPES ON IMAGES
# =================
# The 1st arg is the image, 2nd is the Starting Point, 3rd is the Ending Point, 4th is the Color, & 5th is the
# Thickness
cv2.line(img, (0,0), (img.s... |
6962e807c07455e169e84f6b0e9ccb1b75f0bd80 | nkatebi/ICD_Mapping | /map.py | 1,924 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 2 10:17:48 2018
@author: nkatebi
This code is for finding the number of one to one, one to many mappings and no map.
For this purpose flags of the mapping are used. Approximate flag is the first one
which shows there is an approximate match or iden... |
21b951da087e74baafaa58b0287aece8031debfb | siddheshsule/100_days_of_code_python_new | /day_8/caeser_cipher.py | 2,270 | 4.0625 | 4 | # Importing the logo from art file
from art_ceaser_cipher import logo
# Defining list of alphabets
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p'... |
96d439c85d36b3a9b46b0c071f2fe34cecd0c458 | siddheshsule/100_days_of_code_python_new | /day_18/turtle_random_walk.py | 688 | 3.75 | 4 | # Importing required modules
from turtle import Turtle, Screen, colormode
import turtle
import random
timmy = Turtle()
turtle.colormode(255)
# Creating function for random colors acc. to RGB colors
def random_color():
r = random.randint(0,255)
g = random.randint(0,255)
b = random.randint(0,255)
return ... |
19e31e0adeb87acb9b46a9acb3778380b084d43d | siddheshsule/100_days_of_code_python_new | /day_36/stock-news-hard-start/stock_price_alert.py | 3,965 | 3.65625 | 4 | import requests
import smtplib
from newsapi import NewsApiClient
import datetime as dt
STOCK_NAME = "TSLA"
COMPANY_NAME = "Tesla Inc"
STOCK_ENDPOINT = "https://www.alphavantage.co/query"
NEWS_ENDPOINT = "https://newsapi.org/v2/everything"
NEWS_API_KEY = "63928176adaf4b57a93930106a06c165"
STCK_PRC_API_KEY = "N55390ZP... |
2affb3eb4c027b14011750ee72c325634f9c4552 | siddheshsule/100_days_of_code_python_new | /day_27/main.py | 737 | 3.953125 | 4 | import tkinter
def button_click():
# print("I got clicked!")
# my_label["text"] = "I got clicked!"
new_text = input.get()
my_label.config(text= new_text)
window = tkinter.Tk()
window.title("My first GUI Program")
window.minsize(width=500, height=300)
my_label = tkinter.Label(text= " I am a text."... |
844b63c1b75e33bf1527fc35c151d8ff21abecd1 | siddheshsule/100_days_of_code_python_new | /day_26/main_5.py | 262 | 4.21875 | 4 | sentence = "What is the Airspeed Velocity of an Unladen Swallow?"
# Don't change code above 👆
# Write your code below:
words_in_sentence = sentence.split(" ")
print(words_in_sentence)
result = {word: len(word) for word in words_in_sentence}
print(result) |
a292bac412b5e0dd89360fa542abbaab0b23239f | Itsukara/Python-Tutorial-Scripts | /tutorial-ch5.py | 11,025 | 3.78125 | 4 | # coding: UTF-8
# http://docs.python.jp/2.7/tutorial/datastructures.html
# 5. データ構造
from print_and_exec import *
print_and_exec(ur'''
"■5.1. リスト型についてもう少し - 1"
"""
リストデータ型には、他にもいくつかメソッドがあります。リストオブジェクトのすべてのメソッドを以下に示します:
list.append(x)
リストの末尾に要素を一つ追加します。 a[len(a):] = [x] と等価です。
list.extend(L)
指定したリスト中のすべての要素を対象の... |
03a4ce1e55bb0edca3dbc1f96f4c2c6d58552ea5 | mhddiallo/daily_code | /Day2.py | 336 | 4.1875 | 4 | #Mohamed Diallo - Day 2: 05/05/2021
#Description: Show how much times an element appear in a given string.
elements = ['a', 'b', 'c', 'd', 'e']
count = 0
my_string = input('Type anything: ')
for i in elements:
for j in my_string:
if(i == j):
count += 1
print(i +" appears " +str(count)+ " ti... |
2956d2384a1b600e44c8d99c2d44cdd7c4f01ff0 | mikaelbeat/Python_Programming_Masterclass | /Python_Programming_Masterclass/Exceptions/Challenge.py | 417 | 4.15625 | 4 |
def calculator():
number1 = int(input("\nEnter first number: "))
number2 = int(input("\nEnter second number: "))
sum = number1 // number2
return f"\nValue {number1} divided by {number2} is {sum}."
try:
print(calculator())
except ValueError:
print("\nPlease enter only integer values... |
3507fe1480d0fed35312ad1aef187221679dc1a6 | mikaelbeat/Python_Programming_Masterclass | /Python_Programming_Masterclass/Basics/Start_args.py | 233 | 3.84375 | 4 |
def sum_all_numbers(*args):
sum = 0
numbers = []
for value in args:
sum += value
numbers.append(value)
print(f"Sum of all values {numbers} is {sum}.")
sum_all_numbers(5, 6, 3, 1) |
ea6d4bb974b0ebc0c8f0d6751834de5e1b589502 | hanacoon/SI206-adventure-game | /adventure-game.py | 4,334 | 3.5625 | 4 | #test comment
class Player:
def __init__(self, currentRoom):
self.currentRoom = currentRoom
self.lives = 3
self.treasure = list()
### getter and setter for currentRoom
def getRoom(self):
return self.currentRoom
def setRooms(self, newRoom):
self.currentRoom = newRoom
### getter and setter for lives
d... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.