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 |
|---|---|---|---|---|---|---|
2b991ca94e956eaeb88cb36aa663c7878cebcfb5 | shobhit-nigam/onsemi_one | /day5/sql/7.py | 351 | 3.640625 | 4 | # sqlite
# connecting, creating cursor
# creating db, creating table
# inserting values as a list
import sqlite3
lista = [11, "michelle yeoh", "malaysia", 23400]
con = sqlite3.connect('movies.db')
cur = con.cursor()
query = """INSERT into actors(id, name, country, earning) values (?, ?, ?, ?)"""
cur.execute(query,... |
8ce1e141f342f19188016d3af6e3d2ea2be641f4 | shobhit-nigam/onsemi_one | /day2/flow_control/4.py | 525 | 4.03125 | 4 | # relational operators
# flow control
gender = input("enter 'm' for male, 'f' for female, 'o' for others:\n")
age = int(input("enter your age\n:"))
if age > 45 and age < 60:
if gender == 'f':
print("you get a 10% discount")
else:
print("you get a 5% discount")
elif age >= 60 and age < 75:
... |
2f0c42db55bb7eb15892a67de1364cc2a97156a2 | shobhit-nigam/onsemi_one | /day2/gen_functions_2/1.py | 196 | 4.03125 | 4 | # data struct & general functions
# conversion
fruits = {'apples', 'oranges', 'limes', 'straberries', 'kiwifruit','watermelons'}
print(fruits)
print("----")
print(tuple(fruits))
print("----")
|
625388be4dcfbdcf1950cf3dfa7b3a825142c494 | shobhit-nigam/onsemi_one | /day6/json/5.py | 352 | 3.5 | 4 | import json
#json reading
fa = open("example_2.json", "r")
stra = json.load(fa)
# converts it into a dictionary
fa.close()
def funca(d):
for k, v in d.items():
# print(k)
# print("-----")
# print(v)
# print("-----")
if type(v) is dict:
funca(v)
else:
... |
8c3ac126e2393818dea12d1a70226736f8177d69 | aorura/machine_learning | /day2/lec_code/fileEx2.py | 350 | 3.53125 | 4 | def displayWithForLoop(file):
infile = open(file, 'r')
for line in infile:
print(line, end='')
infile.close()
def diplayWithList(file):
infile = open(file, 'r')
listData = [line.rstrip() for line in infile]
print(listData)
infile.close()
file = 'FirstPresidents.txt'
displayWithForL... |
090f25741f6a3474f7f93329ff08894f3f8a8f19 | Vansh-Arora/PythonCrashCourse | /NumOfZeroes.py | 84 | 3.703125 | 4 | n = input()
count=0
for digit in n:
if digit=='0':
count+=1
print(count) |
0824a8a6139a67983e0a3a42190a675d81f97752 | ProHiryu/leetcode | /code/730.count-different-palindromic-subsequences.py | 1,232 | 3.53125 | 4 | #
# @lc app=leetcode id=730 lang=python3
#
# [730] Count Different Palindromic Subsequences
#
# @lc code=start
class Solution:
def countPalindromicSubsequences(self, S: str) -> int:
def cache(start, end): # This function serves to save the result
if end <= start + 2: # simpl... |
bfffa7d5b363b7ff7e5bc3ab3ef44acd1230ad40 | ProHiryu/leetcode | /code/816.ambiguous-coordinates.py | 822 | 3.53125 | 4 | #
# @lc app=leetcode id=816 lang=python3
#
# [816] Ambiguous Coordinates
#
# @lc code=start
class Solution:
'''
思路:
if S == "": return []
if S == "0": return [S]
if S == "0XXX0": return []
if S == "0XXX": return ["0.XXX"]
if S == "XXX0": return [S]
return [S, "X.... |
23ce16904bf1733e331077d4683610762f81041b | ProHiryu/leetcode | /code/105.construct-binary-tree-from-preorder-and-inorder-traversal.py | 782 | 3.75 | 4 | #
# @lc app=leetcode id=105 lang=python3
#
# [105] Construct Binary Tree from Preorder and Inorder Traversal
#
# @lc code=start
# 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... |
a4854956fae5970363313e97dffa4230149697c5 | ZhZhShi/CSE-150 | /2048/ai.py | 5,929 | 3.515625 | 4 | from __future__ import absolute_import, division, print_function
import copy
import random
import math
MOVES = {0: 'up', 1: 'left', 2: 'down', 3: 'right'}
NUM = [[0.5,4,4.5,8],[1,3.5,5,7.5],[1.5,3,5.5,7],[2,2.5,6,6.5]]
NUMS = [[1,8,9,45],[2,7,10,34],[3,6,11,27],[4,5,15,20]]
class Gametree:
"""main class for the AI""... |
fd7a963ec1bbba262d7f0cb3348995198a805674 | isobelyoung/Week4_PythonExercises | /Saturday_Submission/exercise_loops.py | 2,201 | 4.15625 | 4 | # Q1
print("***QUESTION 1***")
# Sorry Hayley - I had already written this bit before our class on Tuesday so didn't use the same method you did!
all_nums = []
while True:
try:
if len(all_nums) == 0:
num = int(input("Enter a number! "))
all_nums.append(num)
else:
... |
a172ba8ec0fcd520ef686b757da9ef1e2a4fa620 | BrunaMS/python_course | /models.py | 4,247 | 3.609375 | 4 | # -*- coding: UTF-8 -*-
class Profile(object):
# Old style: Profile()
# New style: Profile(object)
# The new style add a lot of new utilities and tools.
# Description (optional)
'Default class for user profiles.'
# Define the characteristics of our class (builder/constructor)
# Called every time that we create... |
aece347354d616bc21d62772bce3c89c890eaa25 | KivenCkl/LeetCode | /Problemset/binary-tree-level-order-traversal-ii/binary-tree-level-order-traversal-ii.py | 900 | 3.640625 | 4 |
# @Title: 二叉树的层次遍历 II (Binary Tree Level Order Traversal II)
# @Author: KivenC
# @Date: 2020-09-06 23:38:59
# @Runtime: 40 ms
# @Memory: 13.9 MB
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solu... |
97efcf6b9f0d05267306df200a3ea020b6017aa1 | KivenCkl/LeetCode | /Problemset/number-of-equivalent-domino-pairs/number-of-equivalent-domino-pairs.py | 1,397 | 3.703125 | 4 |
# @Title: 等价多米诺骨牌对的数量 (Number of Equivalent Domino Pairs)
# @Author: KivenC
# @Date: 2019-07-31 21:20:36
# @Runtime: 336 ms
# @Memory: 23.5 MB
class Solution:
def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int:
# # way 1
# # 以元组为键
# ans = 0
# counter = {}
# for... |
45501e96ada0e4a65506b2c18d2932504dcf4b62 | KivenCkl/LeetCode | /Problemset/lru-cache/lru-cache.py | 3,078 | 3.578125 | 4 |
# @Title: LRU缓存机制 (LRU Cache)
# @Author: KivenC
# @Date: 2019-07-10 19:25:02
# @Runtime: 124 ms
# @Memory: 21.5 MB
# way 1
# from typing import Optional
# class ListNode:
# """定义双链表"""
# def __init__(self, key: Optional[int] = None, value: Optional[int] = None):
# self.key = key
# self.value =... |
80cfddca4076e431787975d20b3e214a08d42a59 | KivenCkl/LeetCode | /Problemset/bitwise-and-of-numbers-range/bitwise-and-of-numbers-range.py | 561 | 3.578125 | 4 |
# @Title: 数字范围按位与 (Bitwise AND of Numbers Range)
# @Author: KivenC
# @Date: 2020-08-23 14:37:46
# @Runtime: 64 ms
# @Memory: 13.7 MB
class Solution:
def rangeBitwiseAnd(self, m: int, n: int) -> int:
# 给定两个整数,找到它们对应的二进制字符串的公共前缀
# shift = 0
# while m < n:
# m >>= 1
# ... |
7740f0034a2633fc5ec2ffec59f3706e0e6dfec8 | KivenCkl/LeetCode | /Problemset/convert-sorted-list-to-binary-search-tree/convert-sorted-list-to-binary-search-tree.py | 1,238 | 3.546875 | 4 |
# @Title: 有序链表转换二叉搜索树 (Convert Sorted List to Binary Search Tree)
# @Author: KivenC
# @Date: 2020-08-18 22:37:05
# @Runtime: 172 ms
# @Memory: 19.9 MB
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
# Definition for... |
21dac9e3835b611b9bbb5b272f9ff786668d0974 | KivenCkl/LeetCode | /Problemset/letter-combinations-of-a-phone-number/letter-combinations-of-a-phone-number.py | 550 | 3.625 | 4 |
# @Title: 电话号码的字母组合 (Letter Combinations of a Phone Number)
# @Author: KivenC
# @Date: 2020-08-26 19:01:39
# @Runtime: 52 ms
# @Memory: 13.8 MB
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
if not digits:
return []
mapper = {'2': 'abc', '3': 'def', '4': 'ghi',... |
cf30c96a068a012f120cf2c46cc7e928fcf18dfc | HuongTran312/student-practices | /4_Tran_Thi_Nhu_Huong/bai 1.4.py | 251 | 4.09375 | 4 | """Write a program that asks the user for a number n and prints the sum of the numbers 1 to n."""
print("please input the number")
number = input("input your number")
k=0
for i in(1,int(number)):
k+=i
string = "sum is {}"
print(string.format(k)) |
e6e3fe4c8e42ba41bfdabdc0df75ef1d40584fb8 | rigzinangdu/python | /practice/and_or_condition.py | 984 | 4.3125 | 4 | # We have to see [and] [or] conditions in pythons :
#[and] remember if both the conditions true than output will be true !!! if it's one of condition wrong than it's cames false ----> !!
#[or] remember one of the condition if it's true than its will be came true conditions -----> !!
#<-----[and]------>
name = "python... |
f06e51aec3ad7cbd3d15caa9a846ab411f1069d5 | kaltinril/pythonTeaching | /assignments/4thgrade/class_participation_1/fortune.py | 1,252 | 4.0625 | 4 | # Fortune teller
print("I will predict who I am speaking to by asking these questions.")
print("")
# Ask 6 questions and store the answers (converted to upper-case)
color = input("What is your favorite color? ").upper() # purple
pets = input("How many pets do you have? ").upper() # 3
candy = input... |
cd1a75f2e08bc44d2673adda0ab955f49253f7b8 | kaltinril/pythonTeaching | /assignments/classes/part3/answer/machine_gun.py | 929 | 3.625 | 4 | from bullet import Bullet
class MachineGun(Bullet):
def __init__(self, damage, velocity, position, overheat_time, visible=True, fire_sound_filename=None, hit_sound_filename=None):
super().__init__(damage, velocity, position, True, visible, fire_sound_filename, hit_sound_filename)
self.overheat_tim... |
ee8f4dfc81534a9dcfb4952e2ebd1f10e2c52be5 | kaltinril/pythonTeaching | /assignments/rock_paper_scissors/sabreeen rock paper sisscors.py | 864 | 4.25 | 4 | import random
turns_left = 3
while turns_left > 0:
turns_left = turns_left - 1
player = input("Pick (R)ock, (P)aper, or (S)cissors:")
computer = random.randint(1, 3)
if computer == 1:
computer = "r"
elif computer == 2:
computer = "p"
elif computer == 3:
computer = "s"
... |
8b43e3010e09622678806c426ca6ef5414ce9853 | Jkwok2018/Math189Project | /Midterm/main.py | 7,520 | 3.609375 | 4 | # main.py
# Perform k-means clustering and Markov Model
from sklearn.decomposition import PCA
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import math as math
import random
from statistics import mean
import cluster2 as cluster
from matplotlib.patches import Ellipse
###### FUNCTIONS ########... |
f010397ab53465016b190732a599cf0c9645b1b7 | somesh3168/python-gui | /gui.py | 1,439 | 3.71875 | 4 | from tkinter import *
from tkinter import filedialog
from tkinter import messagebox
import os
def OpenFile():
open_file = filedialog.askopenfilename(initialdir = "c:/", filetypes = (("text files","*.txt"),("all files","*.*")))
global Txt
Txt = Text(root)
Txt.pack()
Txt.insert(END,open(open_file).read())
def Sav... |
509685abaad1157876d4aeed646d69b05dfea644 | TakeSwordWalkSkyline/SomeNote | /lexicon_tool/find_latter.py | 623 | 3.515625 | 4 | #!/usr/bin/python
#coding=utf-8
#找出词典中所有带英文的行
from sys import argv
import sys
import os
import re
if __name__ == "__main__":
if len(sys.argv) != 2:
print ("Usage: lexicon")
sys.exit()
lex = open(argv[1], 'r')
output = open("./eng_key.txt", 'w')
lines = lex.readlines()
for line in... |
a74b7c6845382f26fc8df0e599f47088b2cd6564 | gabrielestes/python-numpy-pandas-evaluation | /src/assessment.py | 1,529 | 3.53125 | 4 | import numpy as np
import pandas as pd
class Assessment:
# PYTHON SECTION
def count_characters(_self, string):
return {c: string.count(c) for c in string}
def invert_dictionary(_self, d):
result = {}
for k,v in d.items():
if v not in result:
r... |
94df7ef623912ec940a4a8fb8b851d9a3b678d0c | hideki/clustsrch | /clustering/text.py | 924 | 3.765625 | 4 | #!/usr/bin/env python
import re
import stopwords
def wordcount(words):
wc = {}
for word in words:
wc.setdefault(word, 0.0)
wc[word] += 1.0
return wc
def tokenize(text):
return cleanwords(re.split('\W+', text))
def cleanwords(words):
return _filterStopwords(_normalize(_filterEmpty... |
5cf6495287d61d7d201aa06f58f2db8347241743 | pritikadasgupta/HackerRank | /Python3/fizzbuzz.py | 848 | 3.65625 | 4 | #Score is (200 - # of characters in source code)/10
# #Initial solution in Hacker Rank
# # 2 points
# i=1
# while i <= 100:
# if i%3==0:
# print("Fizz", end="")
# if i%5==0:
# print("Buzz", end="")
# elif i%5==0:
# print("Buzz", end="")
# else:
# print(i, end="")... |
6952f9d447dc2c32a3c384ad47ddff07203c66c0 | AlexTelon/Javascript-interpreter-in-python-course | /Lab4/src/LogTimingDecorator.py | 1,470 | 3.828125 | 4 | import time
class Logger:
'''
Logger class. It should contains an array of objects containing the information about function calls
'''
function_calls = [] # includes tons of fib calls
class Func_call_obj:
def __init__(self, name, args, result, start, end):
self.func_name = name
self.func_arg... |
efe8924a8a5aed62bb583f213c6e8f2c0b79f91e | fodwazle/drfodwazle | /platform/library.py | 425 | 3.75 | 4 | def write_file(file, message = "You need to add something as a message!"):
writeFile = open(file, "w")
writeFile.write(message)
writeFile.close()
def read_file(file):
readFile = open(file, "r")
print(readFile.rstrip())
readFile.close()
def append_file(file, message = "You need to add som... |
60f184d76699d05f08bb158de177ce4c2d7230f3 | ukzncompphys/lecture2_2016 | /func_example.py | 560 | 3.546875 | 4 | import numpy
from matplotlib import pyplot as plt
#functions defined with def
#arguments can be given default values
def mygauss(x,cent=0,sig=0.1):
y=numpy.exp(-0.5*(x-cent)**2/sig**2)
#pick this normalization so area under
#gaussian is one.
y=1+y/numpy.sqrt(2*numpy.pi*sig**2)
return y
print __n... |
a3b1be7483b59c52a507970d312b59b1fd83fb94 | grishkin/aoc | /day9/day9.py | 1,090 | 3.640625 | 4 | import sys
import re
def get_len(line,start,end):
#for all children in this subset, call function recursively, and increment to next marker
#print(line,start,end)
print("this is my line",line[start:end])
if re.search(r'\(',line[start:end]) is None:
print("base is",end-start)
return end - start
i = start
leng... |
ca6f741a9a9300c892550aa72f17e1bcbb8197cf | Marwan-Mashaly/ICS3U-Weekly-Assignment-02-python | /hexagon_perimeter_calculator.py | 461 | 4.3125 | 4 | #!/usr/bin/env python3
# Created by Marwan Mashaly
# Created on September 2019
# This program calculates the perimeter of a hexagon
# with user input
def main():
# this function calculates perimeter of a hexagon
# input
sidelength = int(input("Enter sidelength of the rectangle (cm): "))
# proces... |
5cc1042a1cbead8ae1b2edb49c7d28fc475c73cf | Ganeshahere/basic_tasks | /palindrome.py | 371 | 4.03125 | 4 | import prompt
def is_palindrome(string):
pointer1 = 0
pointer2 = len(string) - 1
while pointer2 - pointer1 > 0:
if string[pointer1] != string[pointer2]:
print('False')
return False
pointer1 += 1
pointer2 -= 1
print('True')
return True
string = prompt.s... |
ca7ae2460673401b1e4db4424e3b15c540dd8837 | Abderzorai/PythonTraining | /POO Exercice/Pets_class.py | 1,214 | 3.9375 | 4 | # Parent class
class Dog:
# Class attribute
species = 'mammal'
# Initializer / Instance attributes
def __init__(self, name, age):
self.name = name
self.age = age
# instance method
def description(self):
return "{} is {} years old".format(self.name, self.age)
# inst... |
7d04f2014bef3983d0c0bcb4ded266474fb2bee6 | tiffanyxho/OOP_programs | /python-OOP/social_networking.py | 4,246 | 3.953125 | 4 | # create user, search friends, add/delete friends
class User:
# user attributes
def __init__(self, user_name, user_id, user_password):
self.name = user_name
self.id = user_id
self.user_password = user_password
self.connections = []
def change_user_name(self, user_... |
b46075da8b4fe108e5698da78e6dde2c0a034370 | Manjushanair/Encryption-and-Key-Generation-Techniques | /RSA/rsaserver.py | 1,492 | 3.6875 | 4 | #RSA SERVER
import math
import socket
#Choose two numbers a,b
#a,b prime and not equal
a = int(input("Enter a prime number: "))
b = int(input("Enter another prime number: "))
def checkprime(num):
numroo = int(math.sqrt(num))
for i in range(2,numroo):
if num%i == 0:
return False
return True
if a!=b:
print ... |
f720f78a8bb84eb84872a6c85b13f52add7b3e0b | maxcaseylin/ttt_minmax | /minimax.py | 1,885 | 3.734375 | 4 | import game
import copy
import sys
#created an evaluation function using minimax.
#usage: create a GameNode() with the initial board and "X" to play,
# then call minimax() with the node and player to use.
# 0 means the position evals to a tie with best play, 1 if X wins, 2 if Y wins
class GameNode():
def __init__... |
7b57a82f36a23842980281a4c6cf5c60ffc8d977 | vvalcristina/exercicios-python | /curso_em_video/05_guanabara.py | 171 | 4.03125 | 4 | num=int(input("Digite um número:"))
antecessor=int(num -1)
print("Seu antecessor é: %s " %(antecessor))
sucessor= int(num + 1)
print("Seu sucessor é: %s " %(sucessor))
|
e0191c2085c93bcd1140d4aaf3944ff947990870 | vvalcristina/exercicios-python | /curso_em_video/24_guanabara.py | 104 | 3.921875 | 4 | #Procurando uma string
cid = str(input("Em qual cidade você nasceu? "))
print('cid' == upper('SANTO'))
|
d144f3a33ac913e760b564c79ed0c3917553c577 | mauricirododendro/pythondatascience | /per30_1.py | 192 | 3.5 | 4 | lista=[5,10,15,18,21]
i=0
while (lista[i]<18) and (i<len(lista)): #5\n10\n15 dove \n vuol dire "a capo"
print(lista[i])
i+=1
s="1234"
print("{}:{}".format(s[0],s[-2])) # 1:3
|
75a3d8a466b9e3ba5e531a327c8e1d65f311e509 | SureshKumar1230/mypython | /Lists.py | 1,476 | 4.21875 | 4 | data1=[1,2,3,4]
data2=['x','y','z']
print(data1[0])
print(data1[0:2])
print(data2[-3:-1])
print(data1[0:])
print(data2[:2])
#list operator
list1=[10,20]
list2=[30,40]
list3=list1+list2
print(list3)
list1=[10,20,30]
print(list1+[40])
print(list1*2)
list1=[1,2,3,4,5,6,7]
print(list1[0:3])
#appending the ... |
01528b195d8b6fef5485f1ce6536c7f99c3d485c | jj-style/Backgammon | /Coursework/merge_sort.py | 658 | 4.03125 | 4 | def merge(a,b,ob):
merged = []
while len(a) != 0 and len(b) != 0:
if a[0][ob] < b[0][ob] or a[0][ob] == b[0][ob]:
merged.append(a.pop(0))
elif a[0][ob] > b[0][ob]:
merged.append(b.pop(0))
if len(a) !=0 and len(b) == 0:
merged += a
elif len(a) == 0... |
d820e76ad67bd4cd0d505a908b36495fa4e57e91 | Allwayz/MyFirstPythonProject | /week4Exercises/Exercise03.py | 387 | 3.859375 | 4 | def print_mash(element1, element2):
dash = '|'
dash_length = len(dash) + 5
mid_dash = dash.rjust(dash_length)
for i in range(11):
if 1 == i + 1 or 5 == i + 1 or 11 == i + 1:
print(element1, element2 * 4, element1, element2 * 4, element1)
else:
print(dash, mid_das... |
99ffe5800e8268e8c12b33282a7e30ecfa014b43 | adan1145/AI-and-ML-Workshop-2019 | /Module 1 Core Python/Unit 2/mylib/dataframe-2.py | 9,864 | 3.9375 | 4 | # -*- coding: utf-8 -*-
"""
@author: MASTER
"""
import statistics
import my_utils
class DataFrame():
def __init__(self,data):
'''
First we need to store rows and columns of the dataframe
Store column names in a property (first row of data)
'''
self.first_row_of_data = data[... |
fd4242fb44ac355d3326c464b6503354fefe0683 | adan1145/AI-and-ML-Workshop-2019 | /Module 1 Core Python/Unit 2/mylib/dataframe.py | 2,027 | 3.90625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Apr 20 08:02:31 2019
@author: MASTER
"""
import statistics
import my_utils
class DataFrame():
def __init__(self,data):
pass
def display(self,row_range=(0,5),col_range=(0,5)):
'''
displays the slice of the dataframe in the range of... |
b2fae54861e85187d322b58c59b15cfa19109126 | adan1145/AI-and-ML-Workshop-2019 | /Module 1 Core Python/Unit 2/nb5-extii/person.py | 2,106 | 4.09375 | 4 | # -*- coding: utf-8 -*-
"""
@author: MASTER
"""
import datetime
class Person(object):
def __init__(self, name):
"""Create a person"""
name =name.lower()
self.name = name.split(' ')# Set name property
self.Lastname = self.name[-1]
self.name = ' '.join(self.name[0:-1])
... |
d6efbb1a3ea57f6ecbafd98ae4a4896324563235 | jyp95/python_study | /hongong4.1.py | 825 | 3.921875 | 4 | # 4.1 리스트와 반복문
print()
# 리스트 특정 요소 변경
list_a = [1, 2, 3, "안녕", True, False]
print(list_a)
print()
list_a[0] = "변경"
print(list_a)
print()
# 리스트 안에 리스트 사용
list_b = [[1,2,3], [4,5,6], [7,8,9]]
print(list_b[1])
print(list_b[1][0])
print()
# append()함수 이용하여 리스트에 요소 추가
list_c = [1, 2, 3]
print("# 리스트 뒤에 요소 추가... |
0e9c9dcec6beb6abbeef18912be0fab8c5d54579 | navbharti/pythonwork | /smaple/linked_list/Employee.py | 400 | 3.59375 | 4 | '''
Created on 14-Apr-2020
@author: navbharti
'''
class Employee(object):
'''
classdocs
'''
id = 0;
name = None
def display (self):
print("ID: %d \nName: %s"%(self.id,self.name))
def __init__(self, id, name):
'''
Constructor
'''
self.id = id
... |
34fdb3452b61f9ff524124e09bd157738cfbacdf | omoreira/GM-Python-Workbook | /statistical_test/Lasso_Boston_cv_predict.py | 1,461 | 3.546875 | 4 | #10 Fold Boston Data and Lasso Regression
# Based on http://facweb.cs.depaul.edu/mobasher/classes/CSC478/Notes/IPython%20Notebook%20-%20Regression.html
from sklearn.cross_validation import KFold
from sklearn.linear_model import Lasso
import numpy as np
import pylab as pl
from sklearn.datasets import load_boston
#Loadin... |
d1b6b122538ce7914842eb38371e388ecfc56514 | Aaron9477/tiny_code | /LSTM/car_sales_preduction/new/test.py | 66 | 3.671875 | 4 | a = [1,2,3,4]
tmp = []
for i in a:
tmp.append([i,])
print(tmp) |
1f8075f88b15a263ce8b7e812e14e3c1b1fe05d6 | Aaron9477/tiny_code | /leetcode/5/5_answer1.py | 801 | 3.53125 | 4 | # 开始是打算把数组取反,挨个比较,发现不合适,因为反向之后回文的子字符串所在位置并不相同
# 这个程序能做到复杂度为O(n2)
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
res = ''
for i in xrange(len(s)):
temp = self.helper(s, i, i) # 回文的第一种形式
if len(temp) > le... |
cd1c93773da9537c603c9b62a4f4d5e6c63c2944 | eroneko/yihleego | /Python/mapReduce.py | 1,805 | 3.875 | 4 | #——————————map——————————————
def f(x):
return x*x
array1=[1,2,3,4,5,6,7,8,9]
map1=map(f,array1)
list1=list(map1)
print(list1)
map2=map(str,array1)
list2=list(map2)
print(list2)
#——————————reduce——————————————
from functools import reduce
def add(x,y):
return x+y
array2=[1,2,3,4,5,6,7,8,9]
sum1=reduce(add,... |
69e7d619e2d48a721dea71d11fea73faba636d33 | Claes1981/Optuna-Game-Parameter-Tuner | /tools/shuffler.py | 1,051 | 3.71875 | 4 | #!/usr/bin/env python
"""Shuffler
Shuffle contents of a file.
"""
__version__ = 'v0.1.0'
__script_name__ = 'Shuffler'
import argparse
import random
def shuffler(infn, outfn):
tmp_lines = []
with open(infn) as f:
for lines in f:
line = lines.strip()
tmp_lines.append(line... |
f88d47bc24188e786d7fc63d73768d3158ea1612 | rjones18/Rock-Paper-Scissors | /rock_paper_scissors.py | 1,134 | 4.09375 | 4 | import random
print ("rock...")
print ("paper...")
print ("scissors...")
print ("Welcome to rock, paper, scissors, smackdown!!!")
print ("What is your name?")
name = input()
player = input( name + ", select rock, paper, or scissors to make your move:")
rand_num = random.randint(0,2)
if rand_num == 0:
computer = "... |
e24512e387e8f0a912ea9a0a1f12c5b73a833c71 | sslampa/data-struct-algorithms | /stack/3-5.py | 244 | 3.53125 | 4 | from pythonds.basic.stack import Stack
def rev_string(mystr):
s = Stack()
for char in mystr:
s.push(char)
reversed = ""
while s.size() > 0:
reversed += s.pop()
return reversed
print rev_string("Hello")
|
a843820ffd1c102af6f6c831a2f5407e93aa79be | zenathark/VideoBWT | /python/WavePy/wave.py | 1,389 | 3.59375 | 4 | """ Wavelet definition.
File: wave.py
Author: jcgalanh@gmail.com
Description: Definition of the wavelet data type
"""
import numpy as np
import WavePy.tools as tools
class Wavelet(np.ndarray):
"""
This object represents a wavelet.
The fundamental element for signal processing using wavelets is an N m... |
4e233e640c8a0502a34ae17dc5a3a388c4b4a560 | AlekseiSpasiuk/python | /l2ex5.py | 1,443 | 3.578125 | 4 | #!python3
# 5. Реализовать структуру «Рейтинг», представляющую собой не возрастающий набор натуральных чисел.
# У пользователя необходимо запрашивать новый элемент рейтинга.
# Если в рейтинге существуют элементы с одинаковыми значениями,
# то новый элемент с тем же значением должен разместиться после них.
#
# Подсказк... |
1fca15a02681ee918c1ca292e0ced7ece90f53a5 | AlekseiSpasiuk/python | /l2ex1.py | 768 | 4.34375 | 4 | #!python3
# 1. Создать список и заполнить его элементами различных типов данных.
# Реализовать скрипт проверки типа данных каждого элемента. Использовать функцию type() для проверки типа.
# Элементы списка можно не запрашивать у пользователя, а указать явно, в программе.
array = []
array.append(None)
array.append(123... |
5c255bc08059065caeb555cdefe1209fe981476e | Dimitar-F/Comprehension-Python | /filter_numbers.py | 182 | 3.671875 | 4 |
start = int(input())
end = int(input())
def is_valid(i):
return any(i % x == 0 for x in range(2, 11))
print(
[i for i in range(start, end+1) if is_valid(i)]
) |
d1a9870722b71fe103071bc147847d24e8793e5f | amogh2004/Simple-Python-Programs | /larusse_product2.py | 195 | 3.578125 | 4 | import sys
#name = sys.argv[0]
a = int(sys.argv[1])
b = int(sys.argv[2])
product = 0
while a > 0:
if a % 2 == 1:
product = product + b
a = a // 2
b = b * 2
print(product)
|
7b3f91cc62ee9c636817e8201aff8fbfc4f40de8 | amogh2004/Simple-Python-Programs | /p3.py | 200 | 3.6875 | 4 | from turtle import *
x=100; n=4
def polygon(n,x):
angle=360//n
for i in range(n):
forward(x); left(angle)
penup(); forward(x); pendown()
polygon(4,50)
polygon(5,60)
polygon(4,50) |
bbcee24da4cfd59b15282bf3ac1e771ac964f9f3 | kyumiouchi/python-basic-to-advanced | /6.28. Loop while.py | 626 | 3.90625 | 4 | """
Loop while
General form;
while bool_expression:
//execute loop
Repeat until bool expression is True
bool expression is all expression where the result is True or False
Sample:
num = 5
num < 5 # False
num > 5 # False
# sample 1
number = 1
while number < 10: # 1, 2, 3, 4, 5, 6, 7, 8, 9
print(number... |
98b5abeb8423a147b69b90af2a79646d6bb3e80c | kyumiouchi/python-basic-to-advanced | /5.22. If, else, elif.py | 620 | 3.671875 | 4 | """
Conditions structures
If, else, elif
- Wrong:
if age < 18:
print('Minor', age)
if age == 18:
print('18 yeas', age)
if age > 18:
print('Adult', age)
# Conditions Structures if, else em C and Java
if(age < 18){
printf("Minor") # Java -> System.out.println("Minor")
} else if (age == 18){
printf... |
0070c8de50bbe1da1eb1f4e89f15dad5f2be73a7 | kyumiouchi/python-basic-to-advanced | /10.69. Len, Abs, Sum e Round.py | 1,321 | 4.0625 | 4 | """
Len, Abs, Sum e Round
# Len
len() -> count the number of items
# Just to review
print(len('Geek University')) # 15
print(len([1, 2, 3, 4, 5])) # 5
print(len({1, 2, 3, 4, 5})) # 5
print(len((1, 2, 3, 4, 5))) # 5
print(len({'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5})) # 5
# It is the same as:
# Dunder len
print... |
269fa0433fc048b50a8f24cc449a278c8b0b959c | kyumiouchi/python-basic-to-advanced | /11.73. Commun Errors.py | 2,023 | 4.25 | 4 | """
Common Errors
It is important to understand the error code
SyntaxError - Syntax error- not part of Python language
"""
# printf('Geek University') # NameError: name 'printf' is not defined
# print('Geek University')
# 1) Syntax Error
# 1
# def function: # SyntaxError: invalid syntax
# print('Geek Univers... |
1f57c2247c66beb01842fdca73db7eea09f78bac | kyumiouchi/python-basic-to-advanced | /4.19. Escopo de vaiáveis.py | 824 | 3.859375 | 4 | """
Scope of Variables
Two cases of scope
1- Global variables:
- Global Variables are recognized, in other words, understand your scope in all program
2- Local variables:
- Local variables are knowledge as a bloc where was declared, where you scope is limited in your bloc
where was declared
Declared Varia... |
3b596d94a7c67500b638f39b52239c412f746ed4 | kyumiouchi/python-basic-to-advanced | /10.64. Any e All.py | 1,289 | 4.09375 | 4 | """
Any and All
all() -> return True if all the elements of iterative are true or if is empty
# Sample all()
print(all([0, 1, 2, 3, 4])) # all the element are True? False
# 0 - False, 1- True, 2- True, 3- True, 4 True
print(all([1, 2, 3, 4])) # all the element are True? True
print(all((1, 2, 3, 4))) # all the ele... |
36307b89baded4d97e876167b680bc952c1dc4cf | kyumiouchi/python-basic-to-advanced | /9.54. List Comprehension - parte 2.py | 771 | 4.09375 | 4 | """
List Comprehension - Part 2
We can add conditional structure to out list Comprehension
"""
# Sample
# 1
numbers = [1, 2, 3, 4, 5]
even = [number for number in numbers if number % 2 == 0]
odd = [number for number in numbers if number % 2 != 0]
print(even) # [2, 4]
print(odd) # [1, 3, 5]
# Refactor
# Any nu... |
5c288cf56bcccd91d9188d0123433678cb5f9876 | kyumiouchi/python-basic-to-advanced | /10.67. Min e Max.py | 2,874 | 4.15625 | 4 | """
Min and Max
max() -> the biggest number
list_sample = [1, 8, 4, 99, 34, 129]
print(max(list_sample)) # 129
tuple_sample = (1, 8, 4, 99, 34, 129)
print(max(tuple_sample)) # 129
set_sample = {1, 8, 4, 99, 34, 129}
print(max(set_sample)) # 129
dict_sample = {'a': 1, 'b': 8, 'c': 4, 'd': 99, 'e': 34, 'f'... |
05ac29f89c81ab2bfa460be9b2f3fbe2f93fe12c | WilsonMa17/WikipediaSearch | /content-generator.py | 6,144 | 3.875 | 4 | import tkinter as tk
import wikipedia
import sys
import csv
import zmq
def write_file(data):
"""Writes output to a csv file"""
with open('output.csv', mode='w', newline='') as output_file:
output_writer = csv.writer(output_file)
output_writer.writerow(['input_keywords ', 'output_tex... |
4c39febaad78ee6ff43467c414bb21a21eca1a12 | purnesh42H/algorithms-in-python | /python_sequences/python_sequences_basic.py | 1,892 | 3.984375 | 4 | '''
5 basic sequences are available in python
1) list - mutatble
2) tuple - immutable
3) bytearray - mutable
4) string - immutable
5) bytes - immutable
'''
some_list = []
assert str(type(some_list)) == "<class 'list'>"
some_string = ''
assert str(type(some_string)) == "<class 'str'>"
some_tuple = ()
assert str(type(so... |
46e52e3551b90d01b56ebf21b2ce00db9c1af913 | purnesh42H/algorithms-in-python | /python_collections_and_data_structures/python_two_dice_sum_ways_using_dict.py | 462 | 3.65625 | 4 | from collections import defaultdict
def get_number_of_ways():
num_ways = defaultdict(int)
for i in range(1, 6+1):
for j in range(1, 6+1):
num_ways[i+j] += 1
return num_ways
def get_sum_probability(s):
if s > 12 or s < 2:
return None
return (get_number_of_ways()[s] / 36... |
1c4223792c7c293a0c2e8d922f26ad2ae970c323 | purnesh42H/algorithms-in-python | /python_collections_and_data_structures/remove_dups.py | 422 | 3.875 | 4 | import string
from collections import OrderedDict
# removes dups from string composed of ascii chracters
def remove_dups(word):
word_dict = OrderedDict() # Why use OrderedDict??? Why not a set??
for char in word:
word_dict.setdefault(char, 1)
return ''.join(list(word_dict.keys()))
def test_remove... |
03754a3a88e8f7fbc200b7b98d350c2917b11171 | purnesh42H/algorithms-in-python | /python_numbers/generate_n_bit_prime_python.py | 325 | 4.09375 | 4 | import math
import random
from is_prime_python import is_prime
def generate_prime(n=3):
while True:
p = random.randint(math.pow(2, n-2), math.pow(2, n-1) - 1)
p = 2 * p + 1
if is_prime(p):
return p
print(generate_prime(8))
print(generate_prime(8))
print(generate_prime(8))
... |
9cfad28ab50b4a35185510c8485ee303682df35e | undersfx/dewp | /code_examples/chapter3/read_write_from_postgres.py | 779 | 3.59375 | 4 | import psycopg2 as db
connection_params="dbname='dataengineering' host='localhost' user='airflow' password='airflow'"
connection = db.connect(connection_params)
cursor = connection.cursor()
query = "select * from users"
cursor.execute(query)
# Some attributes are set by psycopg
print('Number of rows in cursor:', cur... |
905bed4a4ceeb04799ce9a2513b937152c16d1c4 | mattpurcell/project_euler | /euler_problem3.py | 132 | 3.578125 | 4 | #!/usr/bin/python
n = 100
i = 2
while i * i < n:
while n % i == 0:
n = n / i
i = i + 1
print (n)
|
f1f5073eb56227142c7724e38c2454ef86e19ec6 | paratropper/starting | /DAY1/restart.py | 168 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jun 3 18:27:23 2019
@author: HP
"""
name = "RESTART"
print(name)
name1 = str.replace("ESTART","R","$",)
print("R" + name1) |
a3c5b00cff0a3386952f1f02675e98fe2a00f8d2 | paratropper/starting | /DAY2/reverse.py | 214 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 4 17:41:03 2019
@author: HP
"""
lst = []
while True :
a = input()
if not a:
break
lst.append(int(a))
lst.reverse()
print(lst)
|
125131f30952bb18a88072fc5adb7062935401f6 | paratropper/starting | /DAY3/generator.py | 278 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jun 5 15:46:32 2019
@author: HP
"""
list1 = []
while True:
user_input = input("Enter values >")
if not user_input:
break
list1.append(user_input)
tuple1 = tuple(list1)
print(list1)
print(tuple1)
|
1af3d4f2dfb924b5e5f0f40786ce7475c6b4df0f | paratropper/starting | /DAY3/frequency.py | 244 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jun 5 17:08:24 2019
@author: HP
"""
str1 = input("enter string")
dict1 = {}
str2 = set(str1)
counter = 0
for i in str1:
if i in dict1:
dict1[i] = dict1[i]+1
else:
dict1[i]=1 |
fcc159682706cfe317280ee29e22d36ccc2ad361 | paratropper/starting | /DAY3/Intersection.py | 197 | 3.921875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jun 5 17:55:44 2019
@author: HP
"""
list1 = set([1,3,6,78,35,55])
list2 = set([12,24,35,24,88,120,155])
list3 = list1.intersection(list2)
print(list3) |
f4539578d7e29ce956f342d78824c9807f972414 | jonmay/pylib | /algs.py | 744 | 3.796875 | 4 | #!/usr/bin/python
# useful generic algorithms
# 7/28/10: sort entries of a dictionary by key (from http://code.activestate.com/recipes/52306-to-sort-a-dictionary/)
def sortDict(dict):
"""
Given a dictionary with sortable keys, return
list of (key, value) tuples.
dict (dictionary) - the input dict... |
99fa8cd700cabc01631fa5f2e27192e1f616eabf | ryanlwrnc/AdventOfCode2020 | /Day04/passport_processing.py | 2,355 | 3.875 | 4 | def main():
passports = get_passports('input.txt')
required_fields = ['byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid']
num_valid_passports = get_num_valid_passports(passports, required_fields)
print("Number of valid passports: %d" % num_valid_passports)
def get_num_valid_passports(passports, required_f... |
533839fa8c67e484df652ca6da296c19b9edb577 | Lijia-Li/Schelling-Segregation-Model | /Schelling Segregation Model.py | 5,858 | 4.1875 | 4 | from random import randrange
EMPTY = " "
BLUE = "."
ORANGE = "^"
NUM_TRIBES = 2
HOMOGENEITY_LOWER_BOUND = .333
HOMOGENEITY_UPPER_BOUND = 1
def print_world(world):
world_size = len(world)
print(" +" + (world_size * "-") + "+")
for r, row in enumerate(world):
line = str(r % 10) + " |"
for c... |
631632c5fd1c857d8ec88288d114f5ca499a6a46 | elgun87/Dictionary | /main.py | 1,211 | 4.25 | 4 | # Created empty dictionary to add word and then to check if the word in the dictionary
# If yes print the meaning of the word
'''
dictionary = {}
while True:
word = input("Enter the word : ")
if word in dictionary: #checking if the word in the list
print(f'I have this word in my dictionary : {dictiona... |
1d08a2142134ab25d2c111be0f499da174efc326 | candido00/Python | /Python Exercicios/somaImpares.py | 276 | 4.03125 | 4 | num1 = int(input("digite um numero: "))
num2 = int(input("digite um numero: "))
soma = 0
if ( num1 % 2 == 0 ):
num1 += 1
while (num1 <= num2 ):
#print(" +" if num1 > 1 else "=" ,num1,end="")
print(num1,end="+")
soma += num1
num1 += 2
print(" =",soma)
|
640231e3ce9d857b654d1c28948c2081bb33feb1 | candido00/Python | /EXERCICIOS DE PYTHON/list01Ex06.py | 145 | 4.21875 | 4 | num = int(input("digite um número"))
total = 1
for x in range(num,1,-1):
total = x*total
print("x = ",x,"total = ",total)
print (total)
|
8c6988c39b1dfe143e94415eb8c8f1a7231260b3 | candido00/Python | /EXERCICIOS DE PYTHON/teste.py | 425 | 3.984375 | 4 | nome=input("digite o seu nome:\n")
nota1=float(input("digite a primeira nota:\n"))
nota2=float(input("digite a primeira nota:\n"))
media=float(nota1+nota2)/2
if(media==10):
print("Aprovado com sucesso")
elif(media>=7 and media<10):
print("Aprovado")
else:
print("Reprovado")
print("o nome é:"... |
8e942e497fa0cf219fe9553babb805f3d96bdabc | candido00/Python | /Python Exercicios/seqFibonacci.py | 243 | 4 | 4 | term1 = 0
term2 = 1
count = 3
num = int(input("INFORME UM NUMERO PARA A SEQUENCIA: "))
print(term1,term2,end="")
while(count <= num):
term3 = term1 + term2
print(" -", term3, end="")
term1 = term2
term2 = term3
count += 1
|
6cbcc6c20ab20563bb1b24a778eba682f9a2ca4a | candido00/Python | /Python Exercicios/somaFracao.py | 288 | 3.65625 | 4 | num = 1
den = 1
soma = 1
count = 1
print(num,den,end="--1")
print("")
while(num < 99 and den < 50):
count += 1
num += 2
den += 1
divi = (num + num )/(den + den)
soma = soma + divi
print(num,den,end="--")
#print(divi)
#print(count,end="--")
print(soma)
|
45524affbfc686f2e2caa1e1fc6a45a71d5d867d | hadeelayoub/Just_Flex_Copy | /fps.py | 1,390 | 3.953125 | 4 | #!/usr/bin/python
"""
__author__ = "Leon Fedden"
__copyright__ = "Copyright (C) 2016 Leon Fedden
"""
import time
class Fps(object):
"""Simple fps timing and management for inside the context of a loop.
Really simple class to pause thread of execution to meet desired fps.
Call within a loop and call... |
4f3871d2b276700ff0cdaa8b68e9e5e503f1f2fd | SahilMak/Road_Trip | /road_trip.py | 4,014 | 4 | 4 | #!/usr/bin/env python3.5
import sys
import math
import googlemaps
def main():
# Initialize shortest path variables
shortest = math.inf
path = []
# Get file and starting city from command line
file = open(sys.argv[1])
start = sys.argv[2]
# Store city names in list
city = file.readline().split(" ")
len... |
a64f92b8f924597c1a3f5701167c5ec5f70356a5 | CivilizedWork/Tommy-J | /Day_04/4thday1.py | 974 | 3.84375 | 4 | import time
import random
def time2_readabletime(time):
second = int(time % 60)
time /= 60
minute = int(time % 60)
time /= 60
hour = int(time % 24)
time /= 24
print(int(time), hour, minute, second)
def fermat_check():
[a, b, c, n] = map(int, input('input 4 numbers separated by commas... |
1bcf0da8525fad44e22f4b4c52211073d057a5e0 | CivilizedWork/Tommy-J | /Day_02/2ndday1.py | 388 | 3.59375 | 4 | def draw_a_line(column):
print('+', end='')
for j in range(column):
print('----+', end='')
print()
def test1(raw, column):
draw_a_line(column)
for i in range(raw):
for k in range(4):
print('|', end='')
for j in range(column):
print(' |', e... |
fe9e5f83e5bf68cb69370eeaeffa9aaea2714ed7 | suryakants/Python-Program | /OperatorOverload.py | 340 | 3.9375 | 4 |
class Vector:
def __init__(self, x, y):
self.x = x;
self.y = y;
def __add__(self, otherVector):
print('__add__')
return Vector(self.x + otherVector.x, self.y + otherVector.y)
def __str__(self):
print("__str__")
return "Vector (%d, %d) :" % (self.x, self.y);
v1 = Vector(10,20);
v2 = Vector(20,30)... |
a875587cac49a5ad5abcd9a7347082a9bb5219a3 | suryakants/Python-Program | /keyword.py | 275 | 3.53125 | 4 | import math as myAlias
# print(myAlias.cos(myAlias.pi))
a = 4 assert(a < 5), "that's true" assert(a > 5), "that's not true"
# Traceback (most recent call first):
# File "<string>", line 301, in runcode
# File "<interactive input>", line 1, in <module>
# AssertionError
|
cf4cd9cc2bceb55e82678625aa8d91c47d488c0e | suryakants/Python-Program | /Operators.py | 284 | 3.65625 | 4 | #!------------ Operators ----------
a = 10
b = 13
print a&b;
print a|b;
print a^b;
print ~a;
print a<<2; #left shift
print a>>2 # right shift
#in And not in operator
dict = [2,3,4];
print 3 not in dict;
aTuple = [(2, 3), (5, 6), (9, 1)]
print (9,6) in aTuple;
print 11//2; |
3f254ab9f5e53ee9036a972dfbe8d32ea6b962bb | hwjhwj55/machine_learning | /programming_ex2/ex2/costFunction.py | 959 | 3.609375 | 4 | import numpy as np
import sigmoid
# compute the cost and the partial derivations of theta, x,y can be a vector, matrix, scalar
def cost_function(theta, x_data, y_data):
m = y_data.shape[0]
theta = theta.reshape((-1, 1))
# compute cost
h_x = sigmoid.sigmoid(np.dot(x_data, theta))
ln_h = np.log(h_x)... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.