blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
bdf2b0fe68c75b4e9c5fe1c1173ebd19fa8cf5ff | CHS-computer-science-2/python2ChatBot | /chatBot1.py | 808 | 4.40625 | 4 | #This is the starter code for the Chatbot
# <Your Name Here>
#This is a chatbot and this is a comment, not executed by the program
#Extend it to make the computer ask for your favorite movie and respond accordingly!
def main():
print('Hello this is your computer...what is your favorite number?')
#Declaring our... |
431e4c9c9b2480b0fd17a39e1ca4e5f8a9e45fab | Adsime/TDT4173-A4 | /task 2.1/task_2_1.py | 1,506 | 3.546875 | 4 | import functions as f
from collections import defaultdict
import random
def knn(sample, k, data_set):
# Places the Euclidean distance of each set to the sample in an array
distances = [f.distance(feature.get_coords(), sample.get_coords()) for feature in data_set]
res = distances.copy()
# Sorting to ha... |
da747071d01d138647d7ad2f3a51043d1e23b97a | dkswnstns/dkswnstn2 | /문제300/41~50.py | 645 | 3.5 | 4 | #41 : upper() 함수 : 대문자로 변환 해주는 함수
ticker="btc_krw"
print(ticker.upper() )
#42 : lower()함수 : 소문자로 변환 해주는 함수
ticker="btc_krw"
print(ticker.lower())
#43
ticker="btn_krw"
print(ticker.capitalize())
#44
file_name="보고서.xlsx" # 엑셀 파일
print(file_name.endswith("xlsx"))
#45
file_name="보고서.xlsx"
print(file_name.endswith(("xls... |
656a8aa6365b48aeb6a9fa3bfd06c02c044074c0 | Rybak-a87/practice-first_steps | /Samouchka/test_time.py | 759 | 3.8125 | 4 | import time
# проверка любой функции
def test_time(func):
start_time = time.time()
a = func()
finish_time = time.time()
res_time = finish_time - start_time
print(f"\nВремя работы данной программы составляет: {res_time}сек.")
return a
# проверка функции с аргументом и выводом(ret... |
8ffad90164b9dd63ad882253bed746672653cd33 | yuchunhaiGit/pyProject | /TestBookGuide/A Byte of Python3(中文版).pdf/Code/第11章--解决问题/backup_ver1.py | 1,354 | 3.53125 | 4 | #!/usr/bin/python
# Filename: backup_ver1.py
import os
import time
# 1. The files and directories to be backed up are specified in a list.
source = ['C:\\tmp', 'C:\\temp']
running = True
while running:
your_source=input("Your own path or your own file path:")
source.append(your_source)
if input("Do you wa... |
d6b79e6024a44792ac9779dba4bdbfac0cf27df7 | yuchunhaiGit/pyProject | /TestBookGuide/A Byte of Python3(中文版).pdf/Code/第14章--异常/raising.py | 638 | 3.859375 | 4 | # -*-- coding: UTF-8 --*-
#!/usr/bin/python
#filename: raising.py
class ShortInputException(Exception):
'''A user-defined exception class'''
def __init__(self, length,atleast):
Exception.__init__(self)
self.length = length
self.atleast = atleast
try:
text = input('Enter something-->')
if len(text) < 3:
... |
e98ee8f754f4bc91759422057bceb9de4d19a848 | yuchunhaiGit/pyProject | /TestBookGuide/A Byte of Python3(中文版).pdf/Code/第12章--面向对象编程/my_test_class.py | 518 | 3.796875 | 4 | class coordinate:
def __init__(self,x=0,y=0):
self.x=int(x)
self.y=int(y)
def getx(self):
return self.x
def gety(self):
return self.y
def main():
xx=coordinate()
print('坐标x的初始化值是:',xx.getx())
print('坐标y的初始化值是:',xx.gety())
xy=coordinate(3,6)
print('更改后的x坐标是... |
48289fce75dd681fa14abaffbcce0d53c1ef0ce0 | Chiuchi700/Project_UAM | /Validate_Expression_Automaton/LFA.py | 4,192 | 3.6875 | 4 | import re
import sys
def check_expression(exp):
beforeEqual = ''
afterEqual = ''
result = ''
equal = ''
igual = ''
# transforma a expressão algébrica em uma lista de caracteres
for ex, pos in enumerate(exp):
aux = list(pos)
# verifica o primeiro caractere do identificador... |
9572ea20e6fdef0d1f4854eddcce8fb9ce1b45fb | helenlavr/Hangman | /Hangman/task/hangman/hangman_test.py | 604 | 4.03125 | 4 | import random
title = 'H A N G M A N'
secret_word_list = ['python', 'java', 'kotlin', 'javascript']
select_random_from_list = random.choice(secret_word_list)
tires = 0
def guess_the_word(guess, word):
if guess == word:
print('You survived!')
else:
print('You lost!')
def replace_characters(s... |
3d8a5519369b5932f9f8228dd053e09991e28fdf | huangsam/leetcode | /python/constructMaximumBinaryTree.py | 907 | 3.8125 | 4 | # https://leetcode.com/problems/maximum-binary-tree/
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def constructMaximumBinaryTree(self, nums):
"""
:type nums: ... |
05499443c767374a94124bf1e6d315005500d4ea | huangsam/leetcode | /python/totalHammingDistance.py | 545 | 3.625 | 4 | # https://leetcode.com/problems/total-hamming-distance/
class Solution(object):
def totalHammingDistance(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
count = 0
for i in range(32):
mask = 1 << i
countOnes = 0
countZeros = ... |
06e20201cba33e0fe946a9f9d9a0c83d922c6522 | kwkelley/csv-file-to-mySQL-database- | /PythonScript-SQL.py | 1,219 | 3.734375 | 4 | #author @ Keane Kelley
import csv
import os
import pymysql
#1ST METHOD
#opens and reads csv file via iteration
with open(raw_input("Input a file path please: ")) as input_file:
#tells you what directory your file is in
print("You chose this directory that your file is in: " + os.path.realpath(raw_input()))
#adds... |
77b6384a7f7ce2741242128cd0bab09a894864ed | muthusrathinam/30dayscoding | /array/left_rotation.py | 510 | 3.5625 | 4 | def rotateLeft(d, arr):
# Write your code here
arr = arr[d:] + arr[:d]
return arr
'''
if d==len(arr):
return arr
for i in range(0,d):
tmp = arr[0]
for j in range(1,len(arr)):
arr[j-1] = arr[j]
arr[len(arr)-1] = tmp
return arr
'''
'''
... |
fee5552fbf254b736107f76314cc2da6f9bdcea1 | muthusrathinam/30dayscoding | /linked list/Cycle detection in linked list.py | 998 | 3.859375 | 4 | approach 1 : optimized using only 2 ptr's
***************Floyd’s Cycle-Finding Algorithm*******************
def has_cycle(head):
#initialize two pointers
fast = slow = head
while fast != None and fast.next != None:
slow = slow.next
fast = fast.next.next
#checks for a... |
09cf6f7180cf4a125f28ec1629fc501026177646 | muthusrathinam/30dayscoding | /binary_tree/huffman_decoding.py | 489 | 3.65625 | 4 | def decodeHuff(root, s):
#Enter Your Code Here
#create temp. pointer
temp = root
result=[]
#traverse binary coded string
for char in s:
#traverse left of the tree
if char is '0':
temp = temp.left
#traverse right of the tree
else:
temp = t... |
1455d86990e8a670fa985282f2df05c91032525d | sosgang/asn-mobiliti-2016 | /script/cercauniversitaUnibo/01.createDB.py | 2,154 | 3.515625 | 4 | import sqlite3
from sqlite3 import Error
from glob import glob
import json
import csv
import sys
import os
import conf
def create_connection(db_file):
""" create a database connection to the SQLite database
specified by db_file
:param db_file: database file
:return: Connection object or None
"""
conn = None
... |
11169909a526e7340f3bf697a8b40a49f3efd4b5 | adamkalman/CDIPS_2015 | /age.py | 4,040 | 3.953125 | 4 |
# The following line is from converting this from an iPython Notebook
# coding: utf-8
from dateutil.parser import parse
from datetime import datetime, date
def calculate_age(birthdateStr):
""" Calculates the age from a string containing the birthdate.
birthdateStr must have the format "YYYY-MM-DD" or "Y... |
523edeea44c084012c865f40d348eedd01fa1a5d | KershawK5646/CSC-221 | /textAdventure/testdata.py | 636 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Ideas for text Adventure data structures.
"""
# We could use lists.
kitchen = ["Kitchen","This is the kitchen."]
livingRoom = ["Living Room","There's a dusty sofa here."]
bedroom = ["Bedroom","There is a creepy doll here."]
rooms = [kitchen, livingRoom, bedroom]
for room in rooms:
pri... |
6b1867c749d722fd9a0ba344ccc4528ca1bb06df | fruit8067/My_PS_NOTE | /Solved_PS/no.4.py | 702 | 4.03125 | 4 | #문제 https://programmers.co.kr/learn/courses/30/lessons/42888?language=python3
#문제 알고리즘 : 시뮬래이션
def solution(record):
answer = []
real_answer = []
user_dic = dict()
for i in record:
temp = i.split()
if temp[0]=='Enter':
user_dic[temp[1]] = temp[2]
answer.append(f... |
0e67a8056ae6d7fff83ba6f5e17352fb70615846 | thatdruth/Drew-Lewis-FinalCode | /ForLoops.py | 375 | 3.9375 | 4 |
for letter in "Big Pappy":
print(letter)
friends = ["Jack", "John", "Jerry"]
for friend in friends:
print(friend)
for index in range(2,11):
print(index)
for index in range(len(friends)):
print(friends[index])
for index in range(5):
if index == 0:
print("first iteration... |
a66ee557c0557d6dfe61852771995e3143b74022 | thatdruth/Drew-Lewis-FinalCode | /ExponentFunction.py | 247 | 4.40625 | 4 |
print(3**3) #Easy exponent
def raise_to_power(base_num, pow_num):
result = 1
for index in range(pow_num):
result = result * base_num
return result
print(raise_to_power(4,3)) #A coded loop exponent function
|
a2a6cbcd629fa78a317f14cd29eb95a199022793 | lerozhao/pythontest | /320.py | 1,985 | 3.9375 | 4 | # list3=['A','a','B','b','C','c']
# #取出所有大写字母
# print('取出所有大写字母')
# # i=0
# # list33=[]
# # while i<6:
# # print(list3[i],end='\t')
# # list33.insert(list3[i])
# # i=i+2
# # print(list33)
# print(list3[0::2])
# #将所有小写字母顺序倒过来
# print('将所有小写字母顺序倒过来')
# list4=list3[1::2]
# list4.reverse()
# print(list4)
# #想办法... |
be01c2401123204a76e8e54a1ca13cf9b9912580 | andikacsui/testing | /sort_and_combine/sort_and_combine.py | 1,190 | 3.640625 | 4 |
class SortAndCombine:
def __init__(self):
self.result = []
def sort_and_combine(self, input_1, input_2):
if not(all(isinstance(i, int) for i in input_1) and isinstance(input_1, list)):
raise ValueError('input_1 must be a list with integer in all values')
elif not (all(isi... |
5d84cb4ec703a488bf7cbc81eb81de31cc479b86 | getachew67/163hw3 | /hw3.py | 7,465 | 4.0625 | 4 | """
Name: Anastasia Stevens
Section: CSE 163 AC
hw3.py uses data on degree attainment in the United States from
the National Center for Education Statistics. It calculates statistics,
outputs several graphs, and fits a model to the data.
"""
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
fro... |
1dc166e09c6b5970c735775d5e9cd9421125557c | chandana4/Python_Beginners | /game.py | 10,755 | 3.828125 | 4 | import random #To generate Random numbers
import time #To pause the program
import numpy as np #To do matrix operations(Here,to print)
import sys #for exit
class Player:
def __init__(self,playername,superpower): #constructor to set player name
self.name=playername #Setting typed playername
self.health=100 #setti... |
cd45463220e5c5131dc52ad5ff1c9c6baeefba1d | dakbill/Lab_Python_03 | /Lab03_2.py | 560 | 3.875 | 4 | #Lab03_2a
out=""
for i in range(1,7):
for j in range(1,i+1):
out+=str(j)
out+="\n"
print out
#Lab03_2b
out=""
for i in range(6,-1,-1):
for j in range(1,i+1):
out+=str(j)
out+="\n"
print out
#Lab03_2c
out=""
for i in range(1,8):
for j in range(6,0,-1):
if(j>i-1):
... |
57db2f2cfdb89f0989e3185ad10ca42b534d55fb | Prizrak4416/book-of-recipes | /3_numbers_date_time/3_2.py | 368 | 3.84375 | 4 | # Вычисление точных вычислений с десятичными дробями
from decimal import Decimal, localcontext
a = Decimal('4.2')
b = Decimal('2.1')
print(a + b)
a = Decimal('1.3')
b = Decimal('1.7')
print(a / b)
with localcontext() as ctx:
ctx.prec = 3
print(a / b)
with localcontext() as ctx:
ctx.prec = 50
print(a /... |
5ab5469782250e358caf3af341d1828f9e675cb3 | Prizrak4416/book-of-recipes | /2_string_text/2_11.py | 420 | 3.59375 | 4 | # Срезание нежелательных символов из строк
import re
text = " Hellow world \n "
print(text.strip())
print(text.lstrip())
print(text.rstrip(), "\n")
text2 = "-- new text and __"
print(text2.strip('-'))
print(text2.strip('_'))
print(text2.strip('_-'), "\n")
text3 = " Tis is new text and __"
print(text3)... |
3f920a6ebd442dfa31a4e23955e8f9c3fefe8d55 | uwsailbot/boat_2018 | /boat_utilities/src/boat_utilities/points.py | 513 | 4.09375 | 4 | #!/usr/bin/env python
def dist(a, b):
"""Determine the distance between between two points."""
from math import sqrt
return sqrt((a.y - b.y)**2 + (a.x - b.x)**2)
def is_within_dist(a, b, tol):
"""Determine if the dist between two points is within the specified tolerance.
Args:
p1: The f... |
251bced6b2de4e49413060e2ca920d57c7a3f737 | GabrielDaKing/Amateur_ML | /amateur_ml/ann/layer.py | 683 | 3.921875 | 4 | from activation_functions import *
from neuron import Neuron
class Layer():
"""
A class to handle the working of a layer in the neural network.
"""
def __init__(self, no_of_inputs, no_of_neurons, actifunc = relu):
self.neurons = [Neuron(no_of_inputs, actifunc = actifunc) for _ in range(no_of_... |
f97a33df94c0b8bf5424a74bef1d7cc584b7bfb7 | GabrielDaKing/Amateur_ML | /amateur_ml/regression/linear.py | 1,448 | 4.34375 | 4 | class Linear:
"""
A class to handle the basic training and pridiction capability
of a Linear Regression model while storing the slope and intercept.
"""
def __init__(self):
self.slope = 0
self.intercept = 0
def fit(self, x, y):
"""
A function to set the slope a... |
e262ea15bd11b7fd4eeca59fbf7ff3eaeaacbbcd | dannyhammer/CompetitiveGraphColoring | /Research_Game/game_v1.0.1.py.8e795eea1bee30071218399c9a1f4a58.py | 32,418 | 3.78125 | 4 | ##
# A small pygame program that displays a circle on a screen.
# Detects when the user has clicked within a circle
#
# Authors: Nicholas O'Kelley, Daniel Hammer, Brandon Moore
# Date: March 7th, 2020
##
"""
TODO:
Refactor
"""
import pygame
import random
import math
import os
# Global constants
RADIUS = 35
THI... |
d3f8aa52029fd3ad478def527972d5e26b28c2bd | My-Data-Science-Projects/Crypto-Data-Analysis | /crypto_dashboard.py | 2,683 | 3.828125 | 4 | # Description: Build a Cryptocurrency Dashboard
# Import Libraries
import streamlit as st
import pandas as pd
import datetime
import yfinance as yf
import plotly.graph_objects as go
from PIL import Image
st.write("""
# Cryptocurrency Dashboard Application
** Visually Show Data on Crypto (BTC, DOGE & ETH) ... |
6cbb8bcbc7196063a08f9c9caf5b13433aa1ba05 | kiranrraj/100Days_Of_Coding | /Day_62/zip_in_python.py | 698 | 4.15625 | 4 | # Title : Zip function in python
# Author : Kiran Raj R.
# Date : 11:11:2020
languages = ["Malayalam", "tamil", "hindi", "english", "spanish"]
popularity = [10, 20, 50, 100, 40]
area = ['kerala', 'tamil nadu', 'north india', 'world', 'spain']
name =['kiran', 'vishnu', 'manu', 'sivan']
age = [32, 25,24]
first_zip ... |
60ee55b8a309e062e27e041f3ca26d8672d1a396 | kiranrraj/100Days_Of_Coding | /Day_60/palindrome_generators.py | 984 | 3.75 | 4 | # Title : Palindrome and generators
# Author : Kiran raj R.
# Date : 31:10:2020
def isPalindrome(num):
if num // 10 == 0:
return False
temp = num
rev_num = 0
while temp != 0:
rev_num = (rev_num*10) + (temp % 10)
temp = temp//10
if rev_num == num:
return num
... |
f00708554377d2843bf0af1e5188ff13a0affadd | kiranrraj/100Days_Of_Coding | /Day_60/map_in_python.py | 267 | 3.984375 | 4 | # Title : Map function in python
# Author : Kiran raj R.
# Date : 31:10:2020
def getSquare(n):
return n * n
numbers = [1, 2, 3, 4, 5]
result = map(getSquare, numbers)
square = set(result)
print(square)
result = list(map(lambda x: x+3, numbers))
print(result)
|
9d0ae16cf21fee2236ccf76e27b3a0566757a07b | kiranrraj/100Days_Of_Coding | /Day_8/least_frequent.py | 405 | 3.890625 | 4 | # Title : Find the least frequent
# Author : Kiran raj R.
# Date : 22:10:2020
userInput = input("Enter a string to find the least frequent element: ")
freq_dist = {}
for char in userInput:
if char in freq_dist:
freq_dist[char] += 1
else:
freq_dist[char] = 1
result = min(freq_dist, key= lam... |
e2be2cff40f33e116984eb4870909251bcad5d18 | kiranrraj/100Days_Of_Coding | /Day_18/find_missing_num.py | 521 | 4 | 4 | # Title : Find the missing number
# Author : Kiran raj R.
# Date : 01:11:2020
# limit = int(input("Enter the number of elements to be entered: "))
# nums = []
# for num in range(limit):
# nums.append(num)
def find_smallest(list_in):
num_sum = sum(list_in)
length = len(list_in)+1
full_sum = lengt... |
ef7fc6de72d7f28fe6dacb3ad4c2edfcebce3d3d | kiranrraj/100Days_Of_Coding | /Day_59/delete_elemt_linked_list_frnt_back.py | 1,971 | 4.375 | 4 | # Title : Linked list :- delete element at front and back of a list
# Author : Kiran raj R.
# Date : 30:10:2020
class Node:
"""Create a node with value provided, the pointer to next is set to None"""
def __init__(self, value):
self.value = value
self.next = None
class Simply_linked_list:
... |
854616d109a06681b8765657cb5ba0e47689484f | kiranrraj/100Days_Of_Coding | /Day_12/dict_into_list.py | 537 | 4.15625 | 4 | # Title : Convert dictionary key and values into a new list
# Author : Kiran raj R.
# Date : 26:10:2020
# method 1 using dict.keys() and dict.values()
main_dict = {'a': 'apple', 'b': 'ball',
'c': 'cat', 'd': 'dog', 'e': 'elephant'}
list_keys = list(main_dict.keys())
list_values = list(main_dict.values... |
f3b2e9aff5896d56252f8815f92cd0b49d72710f | kiranrraj/100Days_Of_Coding | /Day_37/print_nth_prime_num.py | 1,098 | 4.0625 | 4 | # Title : Print nth prime number
# Author : Kiran Raj R.
# Date : 20/11/2020
def isPrime(userNum):
# if userNum in [0, 1]:
# return False
for num in range(2, userNum):
if userNum % num == 0:
# print(num)
return False
return True
def print_nth_prime(num):
n... |
291df0a49480c44ae76f12e1c6fc3ca52bb04508 | kiranrraj/100Days_Of_Coding | /Day_50/sort_byMax_tuple.py | 237 | 3.6875 | 4 | # Title : Sort tuple by max value in tuple
# Author : Kiran raj R.
# Date : 16:10:2020
list1 = [(10, 90, 23, 7), (90, 101, 10, 1), (20, 34, 15), (77, 66, 55)]
def getMax(elem):
return max(elem)
list1.sort(key=getMax)
print(list1)
|
19ea68c556c52b616ab33e76b24e779a21a8bc08 | kiranrraj/100Days_Of_Coding | /Day_7/count_items_string.py | 998 | 4.1875 | 4 | # Title : Find the number of upper, lower, numbers in a string
# Author : Kiran raj R.
# Date : 21:10:2020
import string
def count_items(words):
word_list = words.split()
upper_count = lower_count = num_count = special_count = 0
length_wo_space = 0
for word in words:
word = word.rstrip()... |
f83464ab9a16f4477dd92a46ee14c3d3de031a4c | kiranrraj/100Days_Of_Coding | /Day_31/generator_function.py | 408 | 3.84375 | 4 | # Title : Generator function
# Author : Kiran Raj R.
# Date : 14/11/2020
def my_generator():
n = 1
print(f"This is a generator's first message: {n}");
yield n
n += 1
print(f"This is a generator message: {n}");
yield n
n+=1
print(f"This is a generator message: {n}");
yield n
... |
ec074f7136a4a786840144495d61960430c61c1c | kiranrraj/100Days_Of_Coding | /Day_26/linked_list_insert.py | 1,340 | 4.125 | 4 | # Title : Linked list insert element
# Author : Kiran Raj R.
# Date : 09:11:2020
class Node:
def __init__(self,data):
self.next = None
self.data = data
class LinkedList:
def __init__(self):
self.head = None
def print_list(self):
start = self.head
while start:
... |
5840c71a6f1faf367d3a5de1e4e49dd43d3e3116 | kiranrraj/100Days_Of_Coding | /Day_69/py_countDown.py | 258 | 3.921875 | 4 | # Title : Count down
# Author : Kiran raj R.
# Date :
user_input = input("Enter a number to count down :")
def countDown(x):
if x==0:
print("Lift off")
else:
print(x)
countDown(x-1)
intVal = int(user_input)
countDown(intVal) |
25ee94661cc1cce075df1356cbd9e9c76c9eb2be | kiranrraj/100Days_Of_Coding | /Day_47/check_tri_angle.py | 402 | 4.21875 | 4 | # Title : Triangle or not
# Author : Kiran Raj R.
# Date : 30/11/2020
angles = []
total = 0
for i in range(3):
val = float(input(f"Enter the angle of side {i}: "))
angles.append(val)
total = sum(angles);
# print(total)
if total == 180 and angles[0] != 0 and angles[1] != 0 and angles[2] != 0:
print("Va... |
63c17332e8e33707d4d4a0d24314e024b3870f58 | kiranrraj/100Days_Of_Coding | /Day_58/print_secondSat.py | 481 | 3.75 | 4 | # Title : Print second saturdays
# Author : Kiran raj R.
# Date : 29:10:2020
import calendar
for month in range(1, 13):
weeks = calendar.monthcalendar(2020, month)
first_week = weeks[0]
second_week = weeks[1]
third_weeks = weeks[2]
if first_week[calendar.SATURDAY]:
second_sat = second... |
037d537dcac93a71179b8e44f66441384778bc4e | kiranrraj/100Days_Of_Coding | /Day_52/palindrome.py | 442 | 4.125 | 4 | # Title : Palindrome
# Author : Kiran raj R.
# Date : 19:10:2020
userInput = input("Enter a number or word to check whether it is palinfrome or note :").strip()
reverse_ui = userInput[-1::-1]
# if userInput == reverse_ui:
# print(f"'{userInput}' is a palindrome")
# else:
# print(f"'{userInput}' is not a pa... |
7f68e2bdc77e7affaf4bb82b8cd73e5bdf2b431b | kiranrraj/100Days_Of_Coding | /Day_9/dict_python.py | 1,167 | 3.96875 | 4 | # Title : Dictionary examples
# Author : Kiran raj R.
# Date : 23:10:2020
dict1 = {1: 10, 2: 20}
dict2 = {'a': 'apple', 'b': 'ball'}
dict3 = {}
for d in (dict1, dict2):
dict3.update(d)
print(dict3)
def find_key(dict_in, key_in):
if key_in in list(dict_in):
print(f"Key {key_in} available in {dict... |
56cb1102a390ef19fc6d6a31b59103be19201ae8 | kiranrraj/100Days_Of_Coding | /Day_22/selection_sort_algo_findIndex.py | 510 | 3.921875 | 4 | # Title : Selection sort Method#2
# Author : Kiran Raj R.
# Date : 05:11:2020
def findIndex(arr):
smallest = arr[0]
smallest_index = 0
for i in range(1, len(arr)):
if arr[i] < smallest:
smallest = arr[i]
smallest_index = i
return smallest_index
def selection_sort(ar... |
4dd9a7d411744cafe8e486f64d94d954cb68b57a | kiranrraj/100Days_Of_Coding | /Day_59/singly_linked_list.py | 675 | 4.09375 | 4 | # Title : Linked list implementation in python
# Author : Kiran raj R.
# Date : 30:10:2020
class Node:
"""Create a node with value provided, the pointer to next is set to None"""
def __init__(self, value):
self.value = value
self.next = None
class Simply_linked_list:
"""create a empty... |
70767281fae5b89610484250cb4805c68366d566 | kiranrraj/100Days_Of_Coding | /Day_57/list_comprehension.py | 933 | 4.0625 | 4 | # Title : List comprehension examples
# Author : Kiran raj R.
# Date : 27:10:2020
# Transpose of a matrix
list1 = [[1, 2], [3, 4], [5, 6], [7, 8]]
out = [[row[i] for row in list1] for i in range(2)]
print(out)
# Square of elements
square = [i*i for i in range(1, 11)]
print(square)
# Print vowels
name = "kiran ... |
78ec831f6a1433cb5c2ce17fc4085300694d09d7 | kiranrraj/100Days_Of_Coding | /Day_31/arr_frequency.py | 497 | 3.875 | 4 | # Title : Element frequency in an array
# Author : Kiran Raj R.
# Date : 14/11/2020
arr1 = [23,1,2,2,3,4,3,1,4,2,3,5,3,4,0]
arr1_freq = [None] * len(arr1)
flag = -1
for i in range(0, len(arr1)):
count = 1
for j in range(i+1, len(arr1)):
if arr1[i] == arr1[j]:
count+=1
arr1_f... |
27c6c5f04cef63421c1208c9407e53126f1bc758 | kiranrraj/100Days_Of_Coding | /Day_24/smallest_divisible.py | 434 | 3.859375 | 4 | # Title : Find the smallest number divisible by 1 to 10
# Author : Kiran Raj R.
# Date : 07:11:2020
def smallest_num(num_range):
i = 0
while 1:
i += num_range * (num_range - 1)
flag = 0
for j in range(2, num_range):
if i % j != 0:
flag = 1
... |
b986daaeb24958d068252a329993bacdc1b7b1dd | kiranrraj/100Days_Of_Coding | /Day_5/count_capLetters.py | 728 | 3.96875 | 4 | # Title : Count capital letters in a sentence
# Author : Kiran raj R.
# Date : 19:10:2020
capital = 0
text = """Web sites are written using HTML, which means that each web page is a structured document.
Sometimes it would be great to obtain some data from them and preserve the structure while we’re at it.
Web si... |
13917f87c5fd24ee4f0f90bc0d5152aa2dccce83 | priyankaVi/Python | /challenge 3 #strings.py | 1,983 | 4.4375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
###challenge3 STRINGSabs
# In[ ]:
020
## Ask the user to enter their first name
##and then display the length of their name
# In[2]:
user=input("nter the first name")
len(user)
# In[ ]:
021
#Ask the user to enter their first name
#and then ask t... |
deda4822691fc9870bc643b557ade79227d938d1 | xnaveira/aoc2020 | /5/5.py | 2,043 | 3.5625 | 4 | def upper_half(s, e):
return s+(round((e-s)/2)), e
def lower_half(s, e):
return s, s+(round((e-s)/2))-1
def find_column(col_code, s=0, e=7):
if len(col_code) == 1:
if col_code[0] == 'L':
return s
else:
return e
if col_code[0] == 'L':
return find_column... |
c1ca4e1a9026cdc4a14584513292aee384473844 | thi-fernandes/exercicio-py | /funcoes.py | 186 | 3.9375 | 4 | def soma (x,y):
return x+y
num1=float(input("digite um numero: "))
num2=float(input("digite um numero: "))
resultado = soma (x=num1, y=num2)
print(f'{num1} + {num2} = {resultado}') |
48df34171e1567253c974d7b274618417d773913 | dimaswahabp/Kumpulan-Catatan-Fundamental | /KumpulanCatatan/Daynote9.py | 1,361 | 3.546875 | 4 | #lambda function
x = lambda a:a
x(2)
y =lambda a,b,c : a+b+c
y(2,5,1)
def my_function(x):
return lambda a:a**x
pangkat2 = my_function(2)
pangkat3 = my_function(3)
pangkat5 = my_function(5)
print(pangkat2(4))
print(pangkat3(4))
print(pangkat5(4))
y = lambda a : True if a%2 == 0 else False
print(y(2))
print(y(3)... |
4e78133f183038327019c656f1671b0c0c04d38c | dimaswahabp/Kumpulan-Catatan-Fundamental | /KumpulanCatatan/Daynote10.py | 2,614 | 4.25 | 4 | #10.1.1 How to make class
class Mobil:
warna = 'merah'
tahun = 2010
mobil1 = Mobil()
print(mobil1.warna)
print(vars(mobil1))
#10.1.2 How to make class properties
class MobilCustom():
def __init__(self, warna, tahun):
self.color = warna
self.year = tahun
mobil1 = MobilCust... |
d5857ce07d2fd01c78a09e56850bbb8c18a8ad83 | queeniehe/queenie.github.io | /PycharmProjects/hw2/hw4/test.py | 1,832 | 3.984375 | 4 | class computer():
"""
This is the class to be specialized by students.
"""
def move(self, match):
def getBoardCopy(b):
# Make a duplicate of the board. When testing moves we don't want to
# change the actual board
dupeBoard = []
for j in b:
dupeBoard.append(j)
return dupeBoard
... |
cef56fd721d2b692c2455c166e64c0a54ec370b4 | carlosmaccarrone/Python | /garfios/tateti.py | 5,519 | 3.5 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# TA-TE-TI versión beta, próximamente se pensará una interfaz
# gráfica y conectividad P2P y cliente/servidor.
import random
def dibujarTablero(tablero):
print ' | |'
print ' ' + tablero[1] + ' | ' + tablero[2] + ' | ' + tablero[3]
print ' | |'
print '-----------... |
a2e4e60f95afc41f0b5968ecd3d7894335af95b3 | carlosmaccarrone/Python | /1-mayor.py | 855 | 4.09375 | 4 | #!/usr/bin/python
#importa libreria sys
import sys
#chequea que la cantidad de argumentos en el comando sea correcta y si no sale con error
#chequea que que la cantidad de argumentos no sea menor que 3, esto es "./mayor.py numero1 numero2" tiene que tener 3 palabras. Para contar el numero de palabras se usa la funci... |
5741e8c17e02435f6747a53d076ab6816e76d9e7 | smackov/migrator_for_python_book | /models.py | 2,359 | 3.625 | 4 | """
Helpfull Chapter, Section, Article classes.
"""
class Chapter:
"""
Chapter contains all necessary information for creating itself in db.
"""
def __init__(self, raw_name):
self.raw_name = raw_name
self.number, self.name = raw_name.split('-', 1)
def __repr__(self):
retu... |
f764f30ea63adbbf7e7bb05a4d66b58aaf0288b7 | Neelik/krell-wiki-bot | /roll_dice.py | 910 | 3.53125 | 4 | import random
def roll_dice(dice):
"""
:param dice: String of what dice to roll and how many, plus modifier of the form: "1d4+2"
:return: String representing each individual dice and their sum
"""
modifier = 0
# Parse the dice
no_spaces = "".join(dice.split())
# check for modifier
... |
51f346a94b5b7df4ae2b093dabfd75fe076b2624 | andrefabricio-f/mateapp-clase-03 | /operaciones incrementadas.py | 234 | 4.125 | 4 | #Operaciones con Incremento
a = 23
print("a=23 -->", a)
a=a+1
print("a=a+1 -->", a)
a+=1
print("a+=1 -->", a)
#a++ -> ERROR
a*=2
print("a*=2 -->", a)
a/=2
print("a/=2 -->", a)
a-=2
print("a-=1 -->", a)
a**=2
print("a**=1 -->", a)
|
aaa462ee952eba075ac3a94971750ee05c9691d0 | crolfsson/The-Tech-Academy-Basic-Python-Projects | /guiProject2/guiProject2.py | 3,095 | 4.125 | 4 | #
#Python: 3.7.2
#
#Author: Cheyanne Rolfsson
#
#Purpose: The Tech Academy - Python course, write a script that creates a GUI with a
# button widget and a text widget. Your script will also include a function
# that when it is called will invoke a dialog modal which will allow users
# ... |
04ae203c5141337886d98e9902d3f91a09213988 | arturblch/game_patterns | /result/command.py | 1,848 | 4.34375 | 4 | # TODO: Улучшить обработчик ввода (InputHandler) описанный ниже.
# 1. Необходимо добавить возможность измение настройки кнопок. (Например поставить выстрел на ПКМ.)
# 2* Добавить возможность передавать в метод параметр(ы). (Например можно передавать юнит, который будет выполнять, команду)
# 3* Для возможности реализова... |
8ebf60db3e82ed6276dadbf80487e09d5006f397 | zhongziqi/python_study | /python_cases/case_9.py | 246 | 4.15625 | 4 | # -*- coding: UTF-8 -*-
# 等三秒打印我爱你
import time
obj = {'a':'i like you','b':'i love you'}
# print dict.values(obj)
# print dict.keys(obj)
# print dict.values(obj)
for key,value in dict.items(obj):
print value
time.sleep(3)
|
d9e47654bd6155e43440be8505a6e146f1b1c671 | zhongziqi/python_study | /python_cases/case_8.py | 320 | 3.671875 | 4 | # -*- coding: UTF-8 -*-
for i in range(1,10):
print
for y in range(1,i+1):
print "%d*%d=%d" % (i, y, i*y),
# 打印九九乘法口诀表
# 其中第一个print为将第一次的循环放在一处,如果没有第二个print 的话该打印就会竖直排列,
# 第二个print的作用是水平排列
|
960e202393b902662012cc0a24ddced7628e7ffd | Deniz-shelby/project_euler | /project_euler/5_smallest_mutliple.py | 560 | 3.796875 | 4 | '''
Smallest multiple
Problem 5
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
'''
smallest_number = 2520
n = 10
def divide_by_all(num):
for i in range(2,... |
d2d61939102d0076e2528c5d2e4600af1af25943 | Deniz-shelby/project_euler | /code_wars/vowel_count.py | 184 | 3.984375 | 4 | # count vowels in a string
def get_count(input_str):
num_vowels = 0
for char in input_str:
if char in "aeiouAEIOU":
num_vowels += 1
return num_vowels
|
3f6b5a2aee53e85b0bf7bd2aaa96ccb41d28ace6 | nicholasdomene/project-euler | /prime_pair_sets.py | 1,998 | 3.90625 | 4 | import datetime
t1 = datetime.datetime.now()
def is_prime(n):
if n in primes:
return True
for prime in primes:
if n%prime==0:
return False
#assuming a prior set of primes all smaller than n,
#if n is not divisible by any other prime smaller than itself, it is a prime
return True
#create set wit... |
100dee6fac715aec02f6a1a32184687204186b87 | juingzhou/ai-vision-for-endoscopy | /ai_vision_for_endoscopy/timer.py | 580 | 3.5 | 4 | #!/usr/bin/env python3
# filename: timer.py
import os
import datetime
def record_duration(interval, description, filepath):
days = interval.days
secs = interval.seconds
total_seconds = days*86400 + secs
hrs = secs//3600
mins = (secs-hrs*3600)//60
secs = secs - hrs*3600 - mins*60
file = o... |
373fa201d4da64f86c256df09842f6c33e56f99e | 15minmod/wagonsort | /wagonSort_v1.py | 2,206 | 4 | 4 | ''' This is my first proper python program'''
''' Import Libraries'''
import os
import random #random function for randomly selecting the wagons and industries and spots
'''First set up individual wagon data'''
wagonList = ['PAM2399', 'GUI45001', 'NEC1334', 'GUI45887', 'CSX89989', 'CPR5823', 'PWR12339', 'PAM87612', '... |
0c5e86701d177bb55077832efb42c7caef1c070a | Pablo909/PSI_projekt | /Zadania python/C01/zadania1.py | 1,857 | 3.796875 | 4 |
# 1,2
a = "Lorem Ipsum jest tekstem stosowanym jako przykładowy wypełniacz w przemyśle poligraficznym. Został po raz pierwszy użyty w XV w. przez nieznanego drukarza do wypełnienia tekstem próbnej książki. Pięć wieków później zaczął być używany przemyśle elektronicznym, pozostając praktycznie niezmienionym. Spopularyz... |
3e13e0a9cacb5aa64767c65d9fe80ccc564a7c8c | ShayanPervez/myprojects | /ascii_art.py | 490 | 3.765625 | 4 | from pyfiglet import figlet_format
from termcolor import colored
def ascii_art(name, color):
ascii_text= figlet_format(name, font='standard')
if color not in ('red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white'):color = "magenta"
color_text = colored(ascii_text, color)
... |
bacf23040a895a9ebe7a38afb50744f94c6c3fe6 | fanzhikang/date_visual | /random_walk.py | 631 | 3.84375 | 4 | from random import choice
class RandomWalk(object):
"""docstring for Random"""
def __init__(self, num_points=5000):
self.num_points = num_points
self.x_values = [0]
self.y_values = [0]
def get_step(self):
direction = choice([-1,1])
distance = choice ([0,1,2,3,4])
step = distance*direction
return step
... |
7ad81d0d86075ceae6909f3e210c729017a3f107 | MaxLikesMath/DeepLearningImplementations | /QLearn_Func.py | 1,828 | 3.5625 | 4 | '''
This is a quick and dirty Q-Learning function for exploring the concept. It runs the Frozen Lake environment, and can run most other environments
if the observation and action spaces are tweaked. That being said, there are much better algorithms for reinforcement learning, and a lot can be deployed
easily usin... |
92a7c5afaa591445e9bb0fa6912da2c6ddaa0110 | ramlaxman/Interview_Practice | /General/int_array_pairs_sum_10.py | 3,192 | 3.796875 | 4 | ###################### worst way: Big O(n^2) #############################
def worst_find_pair_sum(int_arry, target):
pairs = []
for i in range(len(int_arry)): # move up array
x = int_arry[i]
for j in reversed(range(len(int_arry))): # move down array
y = int_arry[j]
if ... |
dfa353728f27230e57cde4ea7d3ed84d0746527a | ramlaxman/Interview_Practice | /Strings/reverse_string.py | 548 | 4.21875 | 4 | # Reverse a String iteratively and recursively
def reverse_iteratively(string):
new_string = str()
for char in reversed(string):
new_string += char
return new_string
def test_reverse_iteratively():
assert reverse_iteratively('whats up') == 'pu stahw'
def reverse_recursively(string):
prin... |
4d8bd39f69cd563e569ab3998b93691f540a4417 | ramlaxman/Interview_Practice | /Graphs/Graph.py | 531 | 3.5 | 4 | class node:
key = None
def __init__(self, key):
self.key = key
self._edges = set()
@property
def edges(self):
return self._edges
@edges.setter
def edges(self, n):
if n not in self._edges:
edges = self._edges
edges.add(n)
self... |
7ecf7e341b07fd417f7271c429ed2ab0c17689c8 | VeriSandy/LEETCODE | /210_NArrTreePreorder.py | 1,175 | 3.75 | 4 | '''
1. Recursive approach.
2. Iterative approach.
Push root value first, then its children from left to right.
Use combination of stack and queue.
'''
#Recursive approach.
class Solution:
def preorder(self, root: 'Node') -> List[int]:
l = []
if root == None:
re... |
3504e9f91941c4a8365c8d4040c3c468912b6f3d | VeriSandy/LEETCODE | /90_InsertDelGetrandom.py | 1,766 | 3.859375 | 4 | '''
Insert Delete GetRandom O(1)
Design a data structure that supports all following operations in average O(1) time.
insert(val): Inserts an item val to the set if not already present.
remove(val): Removes an item val from the set if present.
getRandom: Returns a random element from current set of elements... |
2fc5362720f843549099bceab35c6ad83465fb13 | Toirdealbhach/FYP | /perceptron.py | 2,484 | 3.875 | 4 | import numpy as np
import random
import matplotlib.pyplot as plt
class Perceptron():
def __init__(self,inputlen):
self.inputlen = inputlen
self.weights = np.random.rand(inputlen)
self.learningRate = 0.10
@staticmethod
def activate(n):
if n>0:
return 1... |
3da277c213ea3907dcd50f93ffa8a854119a820c | Yifan-FENG/cci_data_maths_methods | /week03_operators-logic/w3_circle_tkinter_starter.py | 880 | 3.984375 | 4 | import tkinter as tk
import math
root = tk.Tk()
root.title("Drawing")
canvas_width = 1000
canvas_height = 1000
w = tk.Canvas(root,
width=canvas_width,
height=canvas_height)
w.pack(expand=tk.YES, fill=tk.BOTH)
def draw_point(x,y):
w.create_oval((x - 1), (y - 1), (x + 1), (y + 1), fill="#476... |
71076acbab9cda6b046f78d509c235ea2072b744 | bryantbyr/LeetCode-solutions | /450. Delete Node in a BST.py | 1,496 | 3.90625 | 4 | #450. Delete Node in a BST
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Tree(object):
def front_recursion(self, root):
"""利用递归实现树的先序遍历"""
if root is None:
... |
5135a9f048c50d7923fd710b914c2d1238a59d6b | bryantbyr/LeetCode-solutions | /133. Clone Graph.py | 3,938 | 3.5625 | 4 | # -*- coding: utf-8 -*-
# @Time : 2019/1/14
# @Author : qirui
# @FileName: 133. Clone Graph.py
# Definition for a undirected graph node
class UndirectedGraphNode:
def __init__(self, x):
self.label = x
self.neighbors = []
# Time: O(N)
# Space: O(N)
# BFS
class Solution:
#... |
9effc1c65946cfd4eb21fae64466c0cd06978f8f | bryantbyr/LeetCode-solutions | /559. Maximum Depth of N-ary Tree.py | 976 | 3.703125 | 4 | #559. Maximum Depth of N-ary Tree
# Definition for a Node.
class Node(object):
def __init__(self, val, children):
self.val = val
self.children = children
#Created by bryanybyr on 20181105
#Time:O(N)
#Space:O(N)
#Tree + Recursion
class Solution(object):
def maxDepth(self, root):
... |
3f15527965429528100b312d3d797a3f90bbde3c | bryantbyr/LeetCode-solutions | /834. Sum of Distances in Tree.py | 1,966 | 3.59375 | 4 | # 834. Sum of Distances in Tree
import collections
# Time Limit Exceeded O(N^2)
# class Solution:
# def sumOfDistancesInTree(self, N, edges):
# """
# :type N: int
# :type edges: List[List[int]]
# :rtype: List[int]
# """
#
# conn = collections.defaultd... |
9513ac68e81511346f2adb01f8dfe7c4cb2a3475 | bryantbyr/LeetCode-solutions | /337. House Robber III.py | 2,118 | 3.640625 | 4 | #337. House Robber III
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
#Learn from discuss on 20181030
#Time:O(N^2)
#Space:O(1)
#Tree + Recursion
Time Limit Exceeded
class Solution(object):
... |
4ff561d4a7d86aac70490db57aab0b9a772d3556 | bryantbyr/LeetCode-solutions | /494. Target Sum.py | 1,450 | 3.546875 | 4 | # -*- coding: utf-8 -*-
# @Time : 2018/12/23
# @Author : qirui
# @FileName: 494. Target Sum.py
# Time Limit Exceeded
# Time:O(2^N)
# Space:O(N)
# DFS
# class Solution(object):
# def findTargetSumWays(self, nums, S):
# """
# :type nums: List[int]
# :type S: int
# :r... |
8fcfeca5043399cd9df1a3d5190e3b015df7235e | bryantbyr/LeetCode-solutions | /222. Count Complete Tree Nodes.py | 2,709 | 4.03125 | 4 | #222. Count Complete Tree Nodes
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
#Created by bryantbyr on 20181027
#Time:O(N)
#Space:O(1)
#Tree + Recursion
class Solution(object):
def count... |
5cd762ddd9d9eb2bec64a6246a49c58f516ab123 | bryantbyr/LeetCode-solutions | /99. Recover Binary Search Tree.py | 2,924 | 3.78125 | 4 | # 99. Recover Binary Search Tree
from tools import Tree, TreeNode
#Learn from discuss on 20181204
#Time:O(N)
#Space:O(N)
#in_order_traversal recursively
class Solution:
def recoverTree(self, root):
"""
:type root: TreeNode
:rtype: void Do not return anything, modify root in-pla... |
0225833071cab836feb97ba9e5d0d6841f7c6b4b | bryantbyr/LeetCode-solutions | /637. Average of Levels in Binary Tree.py | 1,862 | 3.671875 | 4 | #637. Average of Levels in Binary Tree
#
#Created by bryantbyr on 20180713
#Space:O(n)
#Time:O(n)
#二叉树的层次遍历
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def averageOfLevels(s... |
3a1477595cc17b2adf326b1b5b788b0e3800db8f | bryantbyr/LeetCode-solutions | /96. Unique Binary Search Trees.py | 478 | 3.609375 | 4 | #96. Unique Binary Search Trees
#Learn from solution on 20181017
#Time:O(n^2)
#Space:O(n)
#Tree + DP
class Solution:
def numTrees(self, n):
"""
:type n: int
:rtype: int
"""
dp = [0 for i in range(n + 1)]
dp[0], dp[1] = 1, 1
for i in range(2, n +... |
825360b8ceb0342e19890f7c00193717cf6403da | bryantbyr/LeetCode-solutions | /538. Convert BST to Greater Tree.py | 1,125 | 3.890625 | 4 | #538. Convert BST to Greater Tree
#
#Learn from the solution on 20180714
#Space:O(1)
#Time:O(n)
#recursion*
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Tree(object):
def front_recursi... |
2478e6fb6ab122c209b06c7c10d2c64d00c2dfb7 | bryantbyr/LeetCode-solutions | /17. Letter Combinations of a Phone Number.py | 2,469 | 3.671875 | 4 | # -*- coding: utf-8 -*-
# @Time : 2019/1/28
# @Author : qirui
# @FileName: 17. Letter Combinations of a Phone Number.py
# Time: O(N^3)
# Space: O(N)
# DFS / Backtracking
class Solution(object):
def letterCombinations(self, digits):
"""
:type digits: str
:rtype: List[str]
... |
1bb3cfc746cd568ed5862b7c06835d8d0f7e1159 | bryantbyr/LeetCode-solutions | /589. N-ary Tree Preorder Traversal.py | 1,371 | 3.75 | 4 | #589. N-ary Tree Preorder Traversal
# Definition for a Node.
class Node(object):
def __init__(self, val, children):
self.val = val
self.children = children
#Created by bryantbyr on 20181106
#Time:O(N)
#Space:O(N)
#Tree + Iteration
class Solution(object):
def preorder(self, root):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.